diff --git a/lib/features/earthquake/data/eew_replay_source.dart b/lib/features/earthquake/data/eew_replay_source.dart index 2659a8558..67e504f2f 100644 --- a/lib/features/earthquake/data/eew_replay_source.dart +++ b/lib/features/earthquake/data/eew_replay_source.dart @@ -1,3 +1,4 @@ +import 'package:dpip/core/error/failure.dart'; import 'package:dpip/core/error/result.dart'; import 'package:dpip/core/network/api_exception.dart'; import 'package:dpip/core/realtime/realtime_source.dart'; @@ -35,7 +36,19 @@ class EewReplaySource extends RealtimeSource> { for (final e in all) if (!e.isJma && (!onlyCwa || e.isCwa)) e, ]; - }); + }, shouldLog: (failure) => !isIgnorableFailure(failure)); + + /// A 404 is the archive saying "no record at that instant", which per the + /// endpoint's own contract covers both ends: a replay that has walked past + /// the retained range, and an event older than the first row the database + /// holds. Neither is a fault — the replay is running, there is just nothing + /// recorded there — and counting it as one would turn the whole tail of an + /// old event into a wall of retries. Inside the range the endpoint answers + /// 200 with `[]` for a second that simply carried no bulletin, so the two + /// cases stay distinguishable in the payload; for the card they mean the same + /// thing (nothing to show), and [_stickyAlerts] keeps the last real set. + @override + bool isIgnorableFailure(Failure failure) => failure is NotFoundFailure; /// Null: same fetch-freshness rationale as the live [EewRealtimeSource] — /// here doubly so, since the payload's own time is deliberately historical. diff --git a/lib/features/earthquake/presentation/pages/report_detail_page.dart b/lib/features/earthquake/presentation/pages/report_detail_page.dart index 7ed6c57f6..5390e3c21 100644 --- a/lib/features/earthquake/presentation/pages/report_detail_page.dart +++ b/lib/features/earthquake/presentation/pages/report_detail_page.dart @@ -24,6 +24,7 @@ import 'package:dpip/core/settings/region_store.dart'; import 'package:dpip/core/settings/setting_keys.dart'; import 'package:dpip/core/settings/settings_store.dart'; import 'package:dpip/features/earthquake/domain/earthquake_report.dart'; +import 'package:dpip/features/earthquake/replay_eew_probe.dart'; import 'package:dpip/shared/seismic/intensity.dart'; import 'package:dpip/features/earthquake/domain/report_repository.dart'; import 'package:dpip/shared/seismic/intensity_icon_renderer.dart'; @@ -356,7 +357,9 @@ class _ReportMapDetailState extends State<_ReportMapDetail> { /// the event was never replayable. Future _probeReplay() async { final repository = context.read(); - final timestamp = widget.report.originTimeUtc.millisecondsSinceEpoch - 2000; + final timestamp = + widget.report.originTimeUtc.millisecondsSinceEpoch - + replayLeadIn.inMilliseconds; final result = await repository.hasReplayAt(timestamp); if (!mounted) return; setState(() { @@ -1096,8 +1099,11 @@ class _ReportHeader extends StatelessWidget { } void _openReplay(BuildContext context) { - // 2s lead-in before the report's origin time, matching the legacy replay. - final replayTimestamp = report.originTimeUtc.millisecondsSinceEpoch - 2000; + // [replayLeadIn] before the report's origin time — the replay page needs + // the same constant to recover the origin for its availability probe. + final replayTimestamp = + report.originTimeUtc.millisecondsSinceEpoch - + replayLeadIn.inMilliseconds; context.pushNamed( AppRoutes.earthquakeReplay, pathParameters: {'id': report.id}, diff --git a/lib/features/earthquake/presentation/pages/report_replay_page.dart b/lib/features/earthquake/presentation/pages/report_replay_page.dart index 29aec1495..949975d47 100644 --- a/lib/features/earthquake/presentation/pages/report_replay_page.dart +++ b/lib/features/earthquake/presentation/pages/report_replay_page.dart @@ -28,6 +28,7 @@ import 'package:dpip/core/realtime/realtime_service.dart'; import 'package:dpip/core/realtime/realtime_state.dart'; import 'package:dpip/core/realtime/replay_clock.dart'; import 'package:dpip/features/earthquake/domain/eew.dart'; +import 'package:dpip/features/earthquake/replay_eew_probe.dart'; import 'package:dpip/features/earthquake/domain/eew_town_levels.dart'; import 'package:dpip/shared/seismic/spoken_intensity.dart'; import 'package:dpip/features/earthquake/domain/monitor_eew_announcement_controller.dart'; @@ -49,6 +50,7 @@ import 'package:dpip/features/earthquake/presentation/rts_realtime_controller.da import 'package:dpip/features/earthquake/presentation/pages/report_list_page.dart' show ReportListPage; import 'package:dpip/features/earthquake/presentation/widgets/eew_card.dart'; +import 'package:dpip/features/earthquake/presentation/widgets/replay_eew_notice.dart'; import 'package:dpip/shared/navigation/refresh_on_appear.dart'; import 'package:dpip/features/earthquake/replay_session.dart'; import 'package:dpip/l10n/gen/app_localizations.dart'; @@ -120,6 +122,21 @@ class _ReportReplayPageState extends State { /// advances it through the alert set (modulo the count in the builder). int _eewIndex = 0; + /// The last non-empty alert set the feed published. + /// + /// `/api/v2/eq/eew/{sec}` answers with the bulletins *still in force* at that + /// second, not the ones issued that second: for the 2026-11-01 M5.6 event one + /// serial stayed in the set for about 90 seconds and the endpoint then went + /// back to `[]`. Driving the card straight off the poll therefore made it + /// vanish while the alert was still current, so the card holds the newest set + /// it has seen — a later empty answer means "nothing new", not "nothing". + List _stickyAlerts = const []; + + /// What the three samples said about EEW for this event, once they answer. + /// `null` until then, and `undecided` when a sample failed — a dead request + /// must never be read as "no data". + final ValueNotifier _eewVerdict = ValueNotifier(null); + /// The app-wide immersive toggle, borrowed from the map tab for the length /// of this route. The shell draws the bottom nav bar for every branch, /// including this nested one, so a page-local flag could hide the replay's @@ -167,6 +184,23 @@ class _ReportReplayPageState extends State { cwaOnly: () => cwaOnly.enabled, )..start(); _session.eew.addListener(_syncAnnouncement); + _session.eew.addListener(_captureAlerts); + // Started once, in parallel with the replay, and cached for the session: + // three instants of the event are enough to say "not detected", and asking + // again on every revisit would cost three requests for the same answer. + final origin = DateTime.fromMillisecondsSinceEpoch( + widget.replayTimestamp, + isUtc: true, + ).add(replayLeadIn); + unawaited( + ReplayEewProbe( + context.read(), + origin: origin, + cwaOnly: () => cwaOnly.enabled, + ).run().then((verdict) { + if (mounted) _eewVerdict.value = verdict; + }), + ); _immersive = context.read() ..addListener(_onImmersiveChanged); // A replay opens with its controls, whatever the map tab was left in. @@ -274,6 +308,12 @@ class _ReportReplayPageState extends State { /// The listener's last cached fix, for choosing which alert to speak. geo.LatLng? _rankObserver; + /// Keeps the newest non-empty alert set — see [_stickyAlerts]. + void _captureAlerts() { + final alerts = _session.eew.alerts; + if (alerts.isNotEmpty) _stickyAlerts = alerts; + } + void _syncAnnouncement() { final controller = _announcement; final l10n = _l10n; @@ -296,6 +336,8 @@ class _ReportReplayPageState extends State { _ticker?.cancel(); _tick.dispose(); _session.eew.removeListener(_syncAnnouncement); + _session.eew.removeListener(_captureAlerts); + _eewVerdict.dispose(); _speechSettings?.removeListener(_syncAnnouncement); _announcement?.dispose(); _clockSecond.dispose(); @@ -444,11 +486,19 @@ class _ReportReplayPageState extends State { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ ListenableBuilder( - listenable: _session.eew, + listenable: Listenable.merge([ + _session.eew, + _eewVerdict, + ]), builder: (context, _) { - final alerts = _session.eew.alerts; - if (alerts.isEmpty) { - return const SizedBox.shrink(); + final alerts = _stickyAlerts; + final slot = replayEewSlot( + hasAlerts: alerts.isNotEmpty, + feed: _session.eew.state, + verdict: _eewVerdict.value, + ); + if (slot != ReplayEewSlot.card) { + return ReplayEewNotice(slot: slot); } // One card at a time — tapping cycles through the // active alerts (parallel earthquakes, overlapping diff --git a/lib/features/earthquake/presentation/widgets/replay_eew_notice.dart b/lib/features/earthquake/presentation/widgets/replay_eew_notice.dart new file mode 100644 index 000000000..4e699ec17 --- /dev/null +++ b/lib/features/earthquake/presentation/widgets/replay_eew_notice.dart @@ -0,0 +1,95 @@ +import 'package:dpip/app/theme/app_radius.dart'; +import 'package:dpip/app/theme/app_spacing.dart'; +import 'package:dpip/features/earthquake/replay_eew_probe.dart'; +import 'package:dpip/l10n/gen/app_localizations.dart'; +import 'package:flutter/material.dart'; + +/// The line the replay shows on the EEW slot while there is no card to show. +/// +/// Four different things can be true at that moment and they must not look +/// alike: nothing has answered yet, the feed is failing, the feed is down, or +/// the event was sampled and nothing turned up. Only the last one is a verdict; +/// the other three are states of the connection, so the wording never borrows +/// "there is no EEW" for them. +class ReplayEewNotice extends StatelessWidget { + const ReplayEewNotice({super.key, required this.slot}); + + /// The slot to draw. [ReplayEewSlot.card] and [ReplayEewSlot.pending] draw + /// nothing, so the caller can pass whatever it decided without branching. + final ReplayEewSlot slot; + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context); + final (IconData icon, String message, String? detail) = switch (slot) { + ReplayEewSlot.waiting => ( + Icons.hourglass_empty, + l10n.replayEewWaiting, + null, + ), + ReplayEewSlot.retrying => ( + Icons.sync_problem, + l10n.replayEewRetrying, + null, + ), + ReplayEewSlot.unavailable => ( + Icons.cloud_off, + l10n.replayEewUnavailable, + null, + ), + ReplayEewSlot.none => ( + Icons.search_off, + l10n.replayEewNone, + l10n.replayEewNoneDetail, + ), + ReplayEewSlot.card || + ReplayEewSlot.pending => (Icons.hourglass_empty, '', null), + }; + if (message.isEmpty) return const SizedBox.shrink(); + + final theme = Theme.of(context); + final colors = theme.colorScheme; + final muted = colors.onSurfaceVariant; + return Container( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.md, + vertical: AppSpacing.sm, + ), + decoration: BoxDecoration( + color: colors.surface.withValues(alpha: 0.94), + borderRadius: AppRadius.medium, + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.12), + blurRadius: 12, + ), + ], + ), + child: Row( + children: [ + Icon(icon, size: 16, color: muted), + const SizedBox(width: AppSpacing.sm), + Expanded( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + message, + style: theme.textTheme.labelLarge?.copyWith(color: muted), + ), + if (detail != null) + Text( + detail, + style: theme.textTheme.labelSmall?.copyWith( + color: muted.withValues(alpha: 0.8), + ), + ), + ], + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/earthquake/replay_eew_probe.dart b/lib/features/earthquake/replay_eew_probe.dart new file mode 100644 index 000000000..edfa1f31b --- /dev/null +++ b/lib/features/earthquake/replay_eew_probe.dart @@ -0,0 +1,150 @@ +/// Decides whether a replay's event had any EEW at all, without walking the +/// whole timeline. +/// +/// Lives at the feature root for the same reason [ReplaySession] does: the +/// replay page is presentation and may not import `data/`. +library; + +import 'package:dpip/core/network/api_client.dart'; +import 'package:dpip/core/network/api_exception.dart'; +import 'package:dpip/core/realtime/realtime_state.dart'; +import 'package:dpip/features/earthquake/data/earthquake_api.dart'; +import 'package:dpip/features/earthquake/domain/eew.dart'; + +/// How far before a report's origin time a replay starts. +/// +/// The legacy player opened two seconds early; keeping the constant shared +/// means the replay page can recover the event's origin time from the start +/// instant it was handed, without the route carrying both. +const Duration replayLeadIn = Duration(seconds: 2); + +/// The three instants sampled relative to the origin time. +/// +/// `/api/v2/eq/eew/{sec}` answers with the bulletins that are **still active** +/// at that second, not the ones issued in it: for the 2026-11-01 M5.6 event +/// the endpoint stayed empty until origin + 20 s, returned the same serial +/// from +30 s to +120 s, and was empty again by +300 s. So "start, middle, +/// end" is one sample before any bulletin could exist, one inside the window +/// where a first bulletin is still up, and one past it — where only a re-issued +/// serial could appear. +const List replayProbeOffsets = [ + Duration(seconds: -60), + Duration(seconds: 120), + Duration(seconds: 300), +]; + +/// What three samples can honestly say about an event's EEW. +enum ReplayEewVerdict { + /// At least one sample carried a bulletin. The card itself comes from the + /// live poll as the replayed clock reaches it — this only rules absence out. + found, + + /// All three samples answered successfully with an empty list. + none, + + /// A sample failed (timeout, dropped connection, 5xx). Three samples cannot + /// say anything then: a dead network must never read as "no data". + undecided, +} + +/// Samples [replayProbeOffsets] once, concurrently, and folds the answers into +/// a [ReplayEewVerdict]. +/// +/// This is deliberately not a crawl of the window: at one request per second a +/// ten-minute event is 600 requests before the page can say anything, which is +/// both slow and impolite. Three concurrent GETs answer the only question the +/// UI needs — may it say "nothing was found". +class ReplayEewProbe { + ReplayEewProbe( + ApiClient client, { + required this.origin, + required bool Function() cwaOnly, + }) : _api = EarthquakeApi(client), + _cwaOnlyFilter = cwaOnly; + + final EarthquakeApi _api; + + /// The report's origin time — the reference [replayProbeOffsets] are + /// measured from. + final DateTime origin; + + /// Read per sample, like [EewReplaySource] does, so the probe applies the + /// same JMA/CWA filter the replayed feed will. + final bool Function() _cwaOnlyFilter; + + /// Runs the three samples. Never throws: a failed sample folds into + /// [ReplayEewVerdict.undecided]. + Future run() async { + final samples = await Future.wait([ + for (final offset in replayProbeOffsets) _sample(origin.add(offset)), + ]); + // A bulletin anywhere settles it, whatever the other two said. + if (samples.any((eews) => eews?.isNotEmpty ?? false)) { + return ReplayEewVerdict.found; + } + if (samples.any((eews) => eews == null)) return ReplayEewVerdict.undecided; + return ReplayEewVerdict.none; + } + + /// The bulletins at [instant], filtered exactly as [EewReplaySource] filters + /// them. `null` is a failed sample — a timeout, a bad gateway, or the 404 the + /// archive answers for an instant it no longer holds; none of them may read + /// as "there was nothing". + Future?> _sample(DateTime instant) async { + final seconds = instant.millisecondsSinceEpoch ~/ 1000; + final result = await guardResult(() async { + final json = await _api.getEewAt(seconds); + final all = [ + for (final item in json) Eew.fromJson(item as Map), + ]; + final onlyCwa = _cwaOnlyFilter(); + return [ + for (final eew in all) + if (!eew.isJma && (!onlyCwa || eew.isCwa)) eew, + ]; + }); + return result.valueOrNull; + } +} + +/// Which of the EEW slot's shapes the replay page should draw. +enum ReplayEewSlot { + /// An alert set is on screen: the card is drawn. + card, + + /// Nothing yet and nothing to say: the first answer has not arrived. + pending, + + /// The feed answered and this second carries no bulletin, but the event has + /// not been ruled out. + waiting, + + /// Polls are failing and being retried. Never says "no data". + retrying, + + /// Polls have failed long enough for the feed to be offline. + unavailable, + + /// The three samples found nothing across the event. + none, +} + +/// Decides what the slot shows, as a pure function so the precedence is +/// testable without a page: a card always wins (late data must replace any +/// message), then failures (a dead feed must never borrow the wording of an +/// empty one), then the sampled verdict, then "not yet". +ReplayEewSlot replayEewSlot({ + required bool hasAlerts, + required RealtimeState> feed, + required ReplayEewVerdict? verdict, +}) { + if (hasAlerts) return ReplayEewSlot.card; + if (feed.consecutiveFailures >= 2) { + return feed.status == RealtimeStatus.offline + ? ReplayEewSlot.unavailable + : ReplayEewSlot.retrying; + } + if (!feed.hasData) return ReplayEewSlot.pending; + if (verdict == ReplayEewVerdict.none) return ReplayEewSlot.none; + return ReplayEewSlot.waiting; +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 32a97bb94..114d05fc4 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -885,6 +885,11 @@ } }, "feedReplaying": "Replaying", + "replayEewWaiting": "No EEW yet for this instant", + "replayEewRetrying": "Couldn't load the EEW replay — retrying", + "replayEewUnavailable": "The EEW replay is temporarily unavailable", + "replayEewNone": "No EEW was detected for this replay", + "replayEewNoneDetail": "Sampled the start, middle, and end of the event", "mapLayerStyleBd": "Dvorak BD", "@mapLayerSatelliteB09": { "description": "Himawari mid-level water-vapour channel (B09, 6.9 µm) layer name" @@ -1200,6 +1205,26 @@ "@feedReplaying": { "description": "Status word on the replay page when the replayed instant is older than the RTS retention window: the replay is running, the server just has no shaking snapshot that far back. Never 'offline' — the feed is not broken" }, + "replayEewWaiting": "No EEW yet for this instant", + "@replayEewWaiting": { + "description": "Low-key line on the replay page when the replayed instant has no EEW yet: the replay is running and the feed is healthy, this second simply carries no bulletin" + }, + "replayEewRetrying": "Couldn't load the EEW replay — retrying", + "@replayEewRetrying": { + "description": "Replay EEW line after repeated request failures. The feed is being retried; this must never read as 'no data'" + }, + "replayEewUnavailable": "The EEW replay is temporarily unavailable", + "@replayEewUnavailable": { + "description": "Replay EEW line once the feed has been unreachable long enough to be considered offline" + }, + "replayEewNone": "No EEW was detected for this replay", + "@replayEewNone": { + "description": "Replay EEW line when three samples taken across the event found no bulletin. Deliberately 'was not detected', never 'none exists' — three samples cannot prove absence" + }, + "replayEewNoneDetail": "Sampled the start, middle, and end of the event", + "@replayEewNoneDetail": { + "description": "Second line under replayEewNone, naming which instants were sampled so the headline is not read as a stronger claim" + }, "reportFilterIntensityInfoModernTitle": "Current (from 2020)", "@mapAppGoogleMaps": { "description": "External map app choice: Google Maps" diff --git a/lib/l10n/app_fil.arb b/lib/l10n/app_fil.arb index c2d5c0d45..096290123 100644 --- a/lib/l10n/app_fil.arb +++ b/lib/l10n/app_fil.arb @@ -294,6 +294,11 @@ "durationHours": "{count, plural, =1{1 oras} other{{count} oras}}", "durationDays": "{count, plural, =1{1 araw} other{{count} araw}}", "feedReplaying": "Nire-replay", + "replayEewWaiting": "Wala pang alerto para sa oras na ito", + "replayEewRetrying": "Hindi na-load ang datos ng alerto — sinusubukang muli", + "replayEewUnavailable": "Pansamantalang hindi available ang datos ng alerto", + "replayEewNone": "Walang nakitang alerto sa replay na ito", + "replayEewNoneDetail": "Na-sample ang simula, gitna, at huli ng pangyayari", "mapLayerStyleBd": "Dvorak BD", "moreSectionDisplay": "Display", "rainInterval3d": "3 araw", diff --git a/lib/l10n/app_id.arb b/lib/l10n/app_id.arb index ac95fb5d9..481e650e3 100644 --- a/lib/l10n/app_id.arb +++ b/lib/l10n/app_id.arb @@ -294,6 +294,11 @@ "durationHours": "{count, plural, other{{count} jam}}", "durationDays": "{count, plural, other{{count} hari}}", "feedReplaying": "Memutar ulang", + "replayEewWaiting": "Belum ada peringatan untuk waktu ini", + "replayEewRetrying": "Gagal memuat data peringatan — mencoba lagi", + "replayEewUnavailable": "Data peringatan sementara tidak tersedia", + "replayEewNone": "Tidak ada peringatan yang terdeteksi pada putar ulang ini", + "replayEewNoneDetail": "Sudah mengambil sampel awal, tengah, dan akhir peristiwa", "mapLayerStyleBd": "Dvorak BD", "moreSectionDisplay": "Tampilan", "rainInterval3d": "3 hr", diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 68d6e3688..edff89847 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -294,6 +294,11 @@ "durationHours": "{count, plural, other{{count}時間}}", "durationDays": "{count, plural, other{{count}日}}", "feedReplaying": "再生中", + "replayEewWaiting": "この時点の速報はまだありません", + "replayEewRetrying": "速報データを読み込めませんでした。再試行中", + "replayEewUnavailable": "速報データを一時的に取得できません", + "replayEewNone": "このリプレイでは速報を検出できませんでした", + "replayEewNoneDetail": "イベントの開始・中間・終了をサンプリング済み", "mapLayerStyleBd": "Dvorak BD", "moreSectionDisplay": "表示", "rainInterval3d": "3日", diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index 78ff85bb3..2576f693a 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -294,6 +294,11 @@ "durationHours": "{count, plural, other{{count}시간}}", "durationDays": "{count, plural, other{{count}일}}", "feedReplaying": "재생 중", + "replayEewWaiting": "이 시점의 속보가 아직 없습니다", + "replayEewRetrying": "속보 데이터를 불러오지 못했습니다. 다시 시도 중", + "replayEewUnavailable": "속보 데이터를 일시적으로 가져올 수 없습니다", + "replayEewNone": "이 재생에서 속보를 찾지 못했습니다", + "replayEewNoneDetail": "이벤트의 시작·중간·끝을 샘플링했습니다", "mapLayerStyleBd": "Dvorak BD", "moreSectionDisplay": "표시", "rainInterval3d": "3일", diff --git a/lib/l10n/app_th.arb b/lib/l10n/app_th.arb index 65eb0abf8..0bd17a71a 100644 --- a/lib/l10n/app_th.arb +++ b/lib/l10n/app_th.arb @@ -294,6 +294,11 @@ "durationHours": "{count, plural, other{{count} ชั่วโมง}}", "durationDays": "{count, plural, other{{count} วัน}}", "feedReplaying": "กำลังเล่นซ้ำ", + "replayEewWaiting": "ยังไม่มีประกาศเตือนภัย ณ เวลานี้", + "replayEewRetrying": "โหลดข้อมูลประกาศเตือนภัยไม่สำเร็จ กำลังลองใหม่", + "replayEewUnavailable": "ไม่สามารถดึงข้อมูลประกาศเตือนภัยได้ชั่วคราว", + "replayEewNone": "ไม่พบประกาศเตือนภัยในการเล่นซ้ำนี้", + "replayEewNoneDetail": "สุ่มตรวจช่วงเริ่ม กลาง และสิ้นสุดของเหตุการณ์แล้ว", "mapLayerStyleBd": "Dvorak BD", "moreSectionDisplay": "การแสดงผล", "rainInterval3d": "3 วัน", diff --git a/lib/l10n/app_vi.arb b/lib/l10n/app_vi.arb index 8b66d3657..8aa572779 100644 --- a/lib/l10n/app_vi.arb +++ b/lib/l10n/app_vi.arb @@ -294,6 +294,11 @@ "durationHours": "{count, plural, other{{count} giờ}}", "durationDays": "{count, plural, other{{count} ngày}}", "feedReplaying": "Đang phát lại", + "replayEewWaiting": "Chưa có cảnh báo cho thời điểm này", + "replayEewRetrying": "Không tải được dữ liệu cảnh báo — đang thử lại", + "replayEewUnavailable": "Tạm thời không lấy được dữ liệu cảnh báo", + "replayEewNone": "Không phát hiện cảnh báo nào trong lần phát lại này", + "replayEewNoneDetail": "Đã lấy mẫu đầu, giữa và cuối sự kiện", "mapLayerStyleBd": "Dvorak BD", "moreSectionDisplay": "Hiển thị", "rainInterval3d": "3 ngày", diff --git a/lib/l10n/app_yue.arb b/lib/l10n/app_yue.arb index 0ea250dae..ff2f4155e 100644 --- a/lib/l10n/app_yue.arb +++ b/lib/l10n/app_yue.arb @@ -296,6 +296,11 @@ "durationHours": "{count, plural, other{{count} 個鐘}}", "durationDays": "{count, plural, other{{count} 日}}", "feedReplaying": "重播緊", + "replayEewWaiting": "目前重播時間未有速報資料", + "replayEewRetrying": "速報資料載入失敗,正在重試", + "replayEewUnavailable": "速報資料暫時未能取得", + "replayEewNone": "今次重播未偵測到速報資料", + "replayEewNoneDetail": "已取樣事件開始、中段與結束", "mapLayerStyleBd": "Dvorak BD", "moreSectionDisplay": "顯示", "rainInterval3d": "3 日", diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 6e511473c..76c904f18 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -294,6 +294,11 @@ "durationHours": "{count, plural, other{{count} 小時}}", "durationDays": "{count, plural, other{{count} 天}}", "feedReplaying": "重播中", + "replayEewWaiting": "目前重播時間尚無速報資料", + "replayEewRetrying": "速報資料載入失敗,正在重試", + "replayEewUnavailable": "速報資料暫時無法取得", + "replayEewNone": "此次重播未偵測到速報資料", + "replayEewNoneDetail": "已取樣事件開始、中段與結束", "mapLayerStyleBd": "Dvorak BD", "moreSectionDisplay": "顯示", "rainInterval3d": "3 日", diff --git a/lib/l10n/app_zh_Hans.arb b/lib/l10n/app_zh_Hans.arb index a3b453ef7..afff1d5bb 100644 --- a/lib/l10n/app_zh_Hans.arb +++ b/lib/l10n/app_zh_Hans.arb @@ -294,6 +294,11 @@ "durationHours": "{count, plural, other{{count} 小时}}", "durationDays": "{count, plural, other{{count} 天}}", "feedReplaying": "重播中", + "replayEewWaiting": "当前重播时间暂无速报资料", + "replayEewRetrying": "速报资料载入失败,正在重试", + "replayEewUnavailable": "速报资料暂时无法取得", + "replayEewNone": "此次重播未检测到速报资料", + "replayEewNoneDetail": "已取样事件开始、中段与结束", "mapLayerStyleBd": "Dvorak BD", "moreSectionDisplay": "显示", "rainInterval3d": "3 日", diff --git a/lib/l10n/app_zh_Hant_HK.arb b/lib/l10n/app_zh_Hant_HK.arb index 0decca079..452795497 100644 --- a/lib/l10n/app_zh_Hant_HK.arb +++ b/lib/l10n/app_zh_Hant_HK.arb @@ -294,6 +294,11 @@ "durationHours": "{count, plural, other{{count} 個鐘}}", "durationDays": "{count, plural, other{{count} 日}}", "feedReplaying": "重播中", + "replayEewWaiting": "目前重播時間尚無速報資料", + "replayEewRetrying": "速報資料載入失敗,正在重試", + "replayEewUnavailable": "速報資料暫時無法取得", + "replayEewNone": "此次重播未偵測到速報資料", + "replayEewNoneDetail": "已取樣事件開始、中段與結束", "mapLayerStyleBd": "Dvorak BD", "moreSectionDisplay": "顯示", "rainInterval3d": "3 日", diff --git a/lib/l10n/app_zh_TW.arb b/lib/l10n/app_zh_TW.arb index b2452a8fc..ec12fe0eb 100644 --- a/lib/l10n/app_zh_TW.arb +++ b/lib/l10n/app_zh_TW.arb @@ -294,6 +294,11 @@ "durationHours": "{count, plural, other{{count} 小時}}", "durationDays": "{count, plural, other{{count} 天}}", "feedReplaying": "重播中", + "replayEewWaiting": "目前重播時間尚無速報資料", + "replayEewRetrying": "速報資料載入失敗,正在重試", + "replayEewUnavailable": "速報資料暫時無法取得", + "replayEewNone": "此次重播未偵測到速報資料", + "replayEewNoneDetail": "已取樣事件開始、中段與結束", "mapLayerStyleBd": "Dvorak BD", "moreSectionDisplay": "顯示", "rainInterval3d": "3 日", diff --git a/lib/l10n/gen/app_localizations.dart b/lib/l10n/gen/app_localizations.dart index 2554f1abb..34963283e 100644 --- a/lib/l10n/gen/app_localizations.dart +++ b/lib/l10n/gen/app_localizations.dart @@ -1326,6 +1326,36 @@ abstract class AppLocalizations { /// **'Replaying'** String get feedReplaying; + /// Low-key line on the replay page when the replayed instant has no EEW yet: the replay is running and the feed is healthy, this second simply carries no bulletin + /// + /// In en, this message translates to: + /// **'No EEW yet for this instant'** + String get replayEewWaiting; + + /// Replay EEW line after repeated request failures. The feed is being retried; this must never read as 'no data' + /// + /// In en, this message translates to: + /// **'Couldn\'t load the EEW replay — retrying'** + String get replayEewRetrying; + + /// Replay EEW line once the feed has been unreachable long enough to be considered offline + /// + /// In en, this message translates to: + /// **'The EEW replay is temporarily unavailable'** + String get replayEewUnavailable; + + /// Replay EEW line when three samples taken across the event found no bulletin. Deliberately 'was not detected', never 'none exists' — three samples cannot prove absence + /// + /// In en, this message translates to: + /// **'No EEW was detected for this replay'** + String get replayEewNone; + + /// Second line under replayEewNone, naming which instants were sampled so the headline is not read as a stronger claim + /// + /// In en, this message translates to: + /// **'Sampled the start, middle, and end of the event'** + String get replayEewNoneDetail; + /// Colour-style option: Dvorak BD curve stepped grayscale /// /// In en, this message translates to: diff --git a/lib/l10n/gen/app_localizations_en.dart b/lib/l10n/gen/app_localizations_en.dart index 3e8da7f9f..d1381d224 100644 --- a/lib/l10n/gen/app_localizations_en.dart +++ b/lib/l10n/gen/app_localizations_en.dart @@ -690,6 +690,23 @@ class AppLocalizationsEn extends AppLocalizations { @override String get feedReplaying => 'Replaying'; + @override + String get replayEewWaiting => 'No EEW yet for this instant'; + + @override + String get replayEewRetrying => 'Couldn\'t load the EEW replay — retrying'; + + @override + String get replayEewUnavailable => + 'The EEW replay is temporarily unavailable'; + + @override + String get replayEewNone => 'No EEW was detected for this replay'; + + @override + String get replayEewNoneDetail => + 'Sampled the start, middle, and end of the event'; + @override String get mapLayerStyleBd => 'Dvorak BD'; diff --git a/lib/l10n/gen/app_localizations_fil.dart b/lib/l10n/gen/app_localizations_fil.dart index 4cafad404..9f59b1e44 100644 --- a/lib/l10n/gen/app_localizations_fil.dart +++ b/lib/l10n/gen/app_localizations_fil.dart @@ -693,6 +693,24 @@ class AppLocalizationsFil extends AppLocalizations { @override String get feedReplaying => 'Nire-replay'; + @override + String get replayEewWaiting => 'Wala pang alerto para sa oras na ito'; + + @override + String get replayEewRetrying => + 'Hindi na-load ang datos ng alerto — sinusubukang muli'; + + @override + String get replayEewUnavailable => + 'Pansamantalang hindi available ang datos ng alerto'; + + @override + String get replayEewNone => 'Walang nakitang alerto sa replay na ito'; + + @override + String get replayEewNoneDetail => + 'Na-sample ang simula, gitna, at huli ng pangyayari'; + @override String get mapLayerStyleBd => 'Dvorak BD'; diff --git a/lib/l10n/gen/app_localizations_id.dart b/lib/l10n/gen/app_localizations_id.dart index fef76ac2e..e8292831b 100644 --- a/lib/l10n/gen/app_localizations_id.dart +++ b/lib/l10n/gen/app_localizations_id.dart @@ -688,6 +688,23 @@ class AppLocalizationsId extends AppLocalizations { @override String get feedReplaying => 'Memutar ulang'; + @override + String get replayEewWaiting => 'Belum ada peringatan untuk waktu ini'; + + @override + String get replayEewRetrying => 'Gagal memuat data peringatan — mencoba lagi'; + + @override + String get replayEewUnavailable => 'Data peringatan sementara tidak tersedia'; + + @override + String get replayEewNone => + 'Tidak ada peringatan yang terdeteksi pada putar ulang ini'; + + @override + String get replayEewNoneDetail => + 'Sudah mengambil sampel awal, tengah, dan akhir peristiwa'; + @override String get mapLayerStyleBd => 'Dvorak BD'; diff --git a/lib/l10n/gen/app_localizations_ja.dart b/lib/l10n/gen/app_localizations_ja.dart index 09cb50396..da7bec534 100644 --- a/lib/l10n/gen/app_localizations_ja.dart +++ b/lib/l10n/gen/app_localizations_ja.dart @@ -678,6 +678,21 @@ class AppLocalizationsJa extends AppLocalizations { @override String get feedReplaying => '再生中'; + @override + String get replayEewWaiting => 'この時点の速報はまだありません'; + + @override + String get replayEewRetrying => '速報データを読み込めませんでした。再試行中'; + + @override + String get replayEewUnavailable => '速報データを一時的に取得できません'; + + @override + String get replayEewNone => 'このリプレイでは速報を検出できませんでした'; + + @override + String get replayEewNoneDetail => 'イベントの開始・中間・終了をサンプリング済み'; + @override String get mapLayerStyleBd => 'Dvorak BD'; diff --git a/lib/l10n/gen/app_localizations_ko.dart b/lib/l10n/gen/app_localizations_ko.dart index c5fb075bb..bf93d2575 100644 --- a/lib/l10n/gen/app_localizations_ko.dart +++ b/lib/l10n/gen/app_localizations_ko.dart @@ -677,6 +677,21 @@ class AppLocalizationsKo extends AppLocalizations { @override String get feedReplaying => '재생 중'; + @override + String get replayEewWaiting => '이 시점의 속보가 아직 없습니다'; + + @override + String get replayEewRetrying => '속보 데이터를 불러오지 못했습니다. 다시 시도 중'; + + @override + String get replayEewUnavailable => '속보 데이터를 일시적으로 가져올 수 없습니다'; + + @override + String get replayEewNone => '이 재생에서 속보를 찾지 못했습니다'; + + @override + String get replayEewNoneDetail => '이벤트의 시작·중간·끝을 샘플링했습니다'; + @override String get mapLayerStyleBd => 'Dvorak BD'; diff --git a/lib/l10n/gen/app_localizations_th.dart b/lib/l10n/gen/app_localizations_th.dart index 46a4b9bc0..1d44ad5ef 100644 --- a/lib/l10n/gen/app_localizations_th.dart +++ b/lib/l10n/gen/app_localizations_th.dart @@ -685,6 +685,24 @@ class AppLocalizationsTh extends AppLocalizations { @override String get feedReplaying => 'กำลังเล่นซ้ำ'; + @override + String get replayEewWaiting => 'ยังไม่มีประกาศเตือนภัย ณ เวลานี้'; + + @override + String get replayEewRetrying => + 'โหลดข้อมูลประกาศเตือนภัยไม่สำเร็จ กำลังลองใหม่'; + + @override + String get replayEewUnavailable => + 'ไม่สามารถดึงข้อมูลประกาศเตือนภัยได้ชั่วคราว'; + + @override + String get replayEewNone => 'ไม่พบประกาศเตือนภัยในการเล่นซ้ำนี้'; + + @override + String get replayEewNoneDetail => + 'สุ่มตรวจช่วงเริ่ม กลาง และสิ้นสุดของเหตุการณ์แล้ว'; + @override String get mapLayerStyleBd => 'Dvorak BD'; diff --git a/lib/l10n/gen/app_localizations_vi.dart b/lib/l10n/gen/app_localizations_vi.dart index ab2a86dd5..d032681e8 100644 --- a/lib/l10n/gen/app_localizations_vi.dart +++ b/lib/l10n/gen/app_localizations_vi.dart @@ -685,6 +685,23 @@ class AppLocalizationsVi extends AppLocalizations { @override String get feedReplaying => 'Đang phát lại'; + @override + String get replayEewWaiting => 'Chưa có cảnh báo cho thời điểm này'; + + @override + String get replayEewRetrying => + 'Không tải được dữ liệu cảnh báo — đang thử lại'; + + @override + String get replayEewUnavailable => 'Tạm thời không lấy được dữ liệu cảnh báo'; + + @override + String get replayEewNone => + 'Không phát hiện cảnh báo nào trong lần phát lại này'; + + @override + String get replayEewNoneDetail => 'Đã lấy mẫu đầu, giữa và cuối sự kiện'; + @override String get mapLayerStyleBd => 'Dvorak BD'; diff --git a/lib/l10n/gen/app_localizations_yue.dart b/lib/l10n/gen/app_localizations_yue.dart index 9129a7ba9..b14ced322 100644 --- a/lib/l10n/gen/app_localizations_yue.dart +++ b/lib/l10n/gen/app_localizations_yue.dart @@ -674,6 +674,21 @@ class AppLocalizationsYue extends AppLocalizations { @override String get feedReplaying => '重播緊'; + @override + String get replayEewWaiting => '目前重播時間未有速報資料'; + + @override + String get replayEewRetrying => '速報資料載入失敗,正在重試'; + + @override + String get replayEewUnavailable => '速報資料暫時未能取得'; + + @override + String get replayEewNone => '今次重播未偵測到速報資料'; + + @override + String get replayEewNoneDetail => '已取樣事件開始、中段與結束'; + @override String get mapLayerStyleBd => 'Dvorak BD'; diff --git a/lib/l10n/gen/app_localizations_zh.dart b/lib/l10n/gen/app_localizations_zh.dart index 4aad366ca..9f7cfe1db 100644 --- a/lib/l10n/gen/app_localizations_zh.dart +++ b/lib/l10n/gen/app_localizations_zh.dart @@ -674,6 +674,21 @@ class AppLocalizationsZh extends AppLocalizations { @override String get feedReplaying => '重播中'; + @override + String get replayEewWaiting => '目前重播時間尚無速報資料'; + + @override + String get replayEewRetrying => '速報資料載入失敗,正在重試'; + + @override + String get replayEewUnavailable => '速報資料暫時無法取得'; + + @override + String get replayEewNone => '此次重播未偵測到速報資料'; + + @override + String get replayEewNoneDetail => '已取樣事件開始、中段與結束'; + @override String get mapLayerStyleBd => 'Dvorak BD'; @@ -4287,6 +4302,21 @@ class AppLocalizationsZhHans extends AppLocalizationsZh { @override String get feedReplaying => '重播中'; + @override + String get replayEewWaiting => '当前重播时间暂无速报资料'; + + @override + String get replayEewRetrying => '速报资料载入失败,正在重试'; + + @override + String get replayEewUnavailable => '速报资料暂时无法取得'; + + @override + String get replayEewNone => '此次重播未检测到速报资料'; + + @override + String get replayEewNoneDetail => '已取样事件开始、中段与结束'; + @override String get mapLayerStyleBd => 'Dvorak BD'; @@ -7899,6 +7929,21 @@ class AppLocalizationsZhHantHk extends AppLocalizationsZh { @override String get feedReplaying => '重播中'; + @override + String get replayEewWaiting => '目前重播時間尚無速報資料'; + + @override + String get replayEewRetrying => '速報資料載入失敗,正在重試'; + + @override + String get replayEewUnavailable => '速報資料暫時無法取得'; + + @override + String get replayEewNone => '此次重播未偵測到速報資料'; + + @override + String get replayEewNoneDetail => '已取樣事件開始、中段與結束'; + @override String get mapLayerStyleBd => 'Dvorak BD'; @@ -11512,6 +11557,21 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { @override String get feedReplaying => '重播中'; + @override + String get replayEewWaiting => '目前重播時間尚無速報資料'; + + @override + String get replayEewRetrying => '速報資料載入失敗,正在重試'; + + @override + String get replayEewUnavailable => '速報資料暫時無法取得'; + + @override + String get replayEewNone => '此次重播未偵測到速報資料'; + + @override + String get replayEewNoneDetail => '已取樣事件開始、中段與結束'; + @override String get mapLayerStyleBd => 'Dvorak BD'; diff --git a/test/features/earthquake/data/eew_replay_source_test.dart b/test/features/earthquake/data/eew_replay_source_test.dart index 50cd64bdc..e19967671 100644 --- a/test/features/earthquake/data/eew_replay_source_test.dart +++ b/test/features/earthquake/data/eew_replay_source_test.dart @@ -189,13 +189,18 @@ void main() { expect(source.sameData(a, c), isFalse); }); - test('isIgnorableFailure defaults to false, unlike the RTS replay', () { + test('isIgnorableFailure is true only for the archive 404', () { final source = EewReplaySource(api, clock, cwaOnly: () => false); - expect(source.isIgnorableFailure(const NotFoundFailure('x')), isFalse); + // 404 is the endpoint saying "no record at that instant" — before the + // first row it holds, or past the end. Counting it as a fault would read + // as an outage for the whole tail of an old replay. + expect(source.isIgnorableFailure(const NotFoundFailure('x')), isTrue); + expect(source.isIgnorableFailure(const NetworkFailure('x')), isFalse); + expect(source.isIgnorableFailure(const TimeoutFailure('x')), isFalse); }); test( - 'a 404 still folds into NotFoundFailure (recorded, just not ignored)', + 'a 404 is still recorded as NotFoundFailure, it is only not counted', () async { api.error = _dio(DioExceptionType.badResponse, status: 404); final source = EewReplaySource(api, clock, cwaOnly: () => false); diff --git a/test/features/earthquake/presentation/pages/report_replay_page_test.dart b/test/features/earthquake/presentation/pages/report_replay_page_test.dart index c64d718bd..e9180f47c 100644 --- a/test/features/earthquake/presentation/pages/report_replay_page_test.dart +++ b/test/features/earthquake/presentation/pages/report_replay_page_test.dart @@ -605,7 +605,10 @@ void main() { platform.failNextBlink = true; await tester.pump(const Duration(milliseconds: 1100)); await tester.pump(const Duration(seconds: 1)); - expect(find.text('花蓮縣'), findsNothing); + // Sticky: `[]` means this second carries no *new* bulletin, not that + // the alert ended — the archive keeps one answer up for about two + // minutes, so a card driven straight off the poll would vanish mid-event. + expect(find.text('花蓮縣'), findsOneWidget); // Settle, never a bare pump: the menu opens on an animation, so one // frame leaves every row mid-flight and a tap lands wherever it was @@ -629,10 +632,21 @@ void main() { expect(find.byTooltip('Reset north'), findsNothing); expect(platform.moves, greaterThan(0)); - tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); - await tester.pump(); - tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); - await tester.pump(); + // Walk the chain the platform actually sends. Jumping straight from + // paused to resumed trips AppLifecycleListener's transition assert, which + // any listener built while the app was backgrounded would hit — and the + // card now keeps one such listener alive across the whole replay. + for (final state in const [ + AppLifecycleState.inactive, + AppLifecycleState.hidden, + AppLifecycleState.paused, + AppLifecycleState.hidden, + AppLifecycleState.inactive, + AppLifecycleState.resumed, + ]) { + tester.binding.handleAppLifecycleStateChanged(state); + await tester.pump(); + } // The replay carries the same immersive chip as the map tab, and hides // its own back/legend/ranking and base-map chrome while it is on. diff --git a/test/features/earthquake/presentation/widgets/replay_eew_notice_test.dart b/test/features/earthquake/presentation/widgets/replay_eew_notice_test.dart new file mode 100644 index 000000000..8e91cd43f --- /dev/null +++ b/test/features/earthquake/presentation/widgets/replay_eew_notice_test.dart @@ -0,0 +1,61 @@ +import 'package:dpip/features/earthquake/presentation/widgets/replay_eew_notice.dart'; +import 'package:dpip/features/earthquake/replay_eew_probe.dart'; +import 'package:dpip/l10n/gen/app_localizations.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Widget _app(ReplayEewSlot slot) => MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: Center(child: ReplayEewNotice(slot: slot)), + ), +); + +void main() { + late AppLocalizations l10n; + + Future pump(WidgetTester tester, ReplayEewSlot slot) async { + await tester.pumpWidget(_app(slot)); + l10n = AppLocalizations.of(tester.element(find.byType(Scaffold))); + } + + testWidgets('draws nothing before there is anything to say', (tester) async { + await pump(tester, ReplayEewSlot.pending); + expect(find.byType(Text), findsNothing); + + // The caller passes the card slot through the same path; the notice must + // stay out of its way. + await pump(tester, ReplayEewSlot.card); + expect(find.byType(Text), findsNothing); + }); + + testWidgets('says the instant has no bulletin yet', (tester) async { + await pump(tester, ReplayEewSlot.waiting); + expect(find.text(l10n.replayEewWaiting), findsOneWidget); + expect(find.byIcon(Icons.hourglass_empty), findsOneWidget); + }); + + testWidgets('says it is retrying, not that there is no data', (tester) async { + await pump(tester, ReplayEewSlot.retrying); + expect(find.text(l10n.replayEewRetrying), findsOneWidget); + expect(find.byIcon(Icons.sync_problem), findsOneWidget); + expect(find.text(l10n.replayEewNone), findsNothing); + }); + + testWidgets('separates a dead feed from an empty one', (tester) async { + await pump(tester, ReplayEewSlot.unavailable); + expect(find.text(l10n.replayEewUnavailable), findsOneWidget); + expect(find.byIcon(Icons.cloud_off), findsOneWidget); + expect(find.text(l10n.replayEewNone), findsNothing); + }); + + testWidgets('qualifies the verdict with what it was based on', ( + tester, + ) async { + await pump(tester, ReplayEewSlot.none); + expect(find.text(l10n.replayEewNone), findsOneWidget); + expect(find.text(l10n.replayEewNoneDetail), findsOneWidget); + expect(find.byIcon(Icons.search_off), findsOneWidget); + }); +} diff --git a/test/features/earthquake/replay_eew_probe_test.dart b/test/features/earthquake/replay_eew_probe_test.dart new file mode 100644 index 000000000..371ef091a --- /dev/null +++ b/test/features/earthquake/replay_eew_probe_test.dart @@ -0,0 +1,243 @@ +import 'package:dio/dio.dart'; +import 'package:dpip/core/network/api_client.dart'; +import 'package:dpip/core/network/api_region.dart'; +import 'package:dpip/core/network/region_selection.dart'; +import 'package:dpip/core/realtime/realtime_state.dart'; +import 'package:dpip/core/settings/settings_store.dart'; +import 'package:dpip/features/earthquake/domain/eew.dart'; +import 'package:dpip/features/earthquake/replay_eew_probe.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// An [ApiClient] whose replay archive answers per second, so the probe's +/// three samples can be told apart. +class _Api extends ApiClient { + _Api(this.replies) + : super(Dio(), RegionSelection(SettingsStore.inMemory(const {}))); + + /// Seconds that answer a bulletin; every other second answers `[]`. + final Map>> replies; + + /// Seconds that should fail instead of answering. + final Set down = {}; + + /// Seconds the archive answers 404 for — no record at that instant. + final Set missing = {}; + + final asked = []; + + @override + Future get( + ApiTier tier, + String path, { + Map? query, + CancelToken? cancelToken, + }) async { + final second = int.parse(path.split('/').last); + asked.add(second); + if (down.contains(second)) { + throw DioException( + requestOptions: RequestOptions(path: path), + type: DioExceptionType.connectionError, + ); + } + if (missing.contains(second)) { + throw DioException( + requestOptions: RequestOptions(path: path), + type: DioExceptionType.badResponse, + response: Response( + requestOptions: RequestOptions(path: path), + statusCode: 404, + ), + ); + } + return replies[second] ?? const >[]; + } +} + +Map _eew({ + String author = 'cwa', + String id = 'cwa-1', + String location = '花蓮縣', +}) => { + 'author': author, + 'id': id, + 'serial': 1, + 'status': 1, + 'final': 0, + 'eq': { + 'time': DateTime.utc(2026, 11, 1).millisecondsSinceEpoch, + 'lon': 121.6, + 'lat': 23.98, + 'depth': 10, + 'mag': 6.2, + 'loc': location, + 'max': 5, + }, +}; + +void main() { + final origin = DateTime.utc(2026, 11, 1, 16, 20, 7); + + int secondAt(Duration offset) => + origin.add(offset).millisecondsSinceEpoch ~/ 1000; + + ReplayEewProbe probe(_Api api, {bool cwaOnly = false}) => + ReplayEewProbe(api, origin: origin, cwaOnly: () => cwaOnly); + + group('ReplayEewProbe', () { + test('samples the three instants of the window, once each', () async { + final api = _Api({}); + expect(await probe(api).run(), ReplayEewVerdict.none); + expect(api.asked, [ + secondAt(replayProbeOffsets[0]), + secondAt(replayProbeOffsets[1]), + secondAt(replayProbeOffsets[2]), + ]); + }); + + test('finds a bulletin in any one sample', () async { + final mid = secondAt(replayProbeOffsets[1]); + final api = _Api({ + mid: [_eew()], + }); + expect(await probe(api).run(), ReplayEewVerdict.found); + }); + + test('stays undecided when a sample fails', () async { + final api = _Api({})..down.add(secondAt(replayProbeOffsets[2])); + // A dead request must never read as "no data". + expect(await probe(api).run(), ReplayEewVerdict.undecided); + }); + + test( + 'leaves the answer undecided when the archive 404s a sample', + () async { + // Whether the archive holds the event at all is the report page's job + // (it hides the replay chip when nothing is retained); a 404 here can + // also mean the window moved mid-session, and neither may read as + // "nothing was detected". + final api = _Api({}) + ..missing.addAll([ + for (final offset in replayProbeOffsets) secondAt(offset), + ]); + expect(await probe(api).run(), ReplayEewVerdict.undecided); + }, + ); + + test('a 404 never argues with a bulletin found elsewhere', () async { + final api = _Api({ + secondAt(replayProbeOffsets[2]): [_eew()], + })..missing.add(secondAt(replayProbeOffsets[0])); + expect(await probe(api).run(), ReplayEewVerdict.found); + }); + + test('a network failure still outranks the 404s around it', () async { + final api = _Api({}) + ..missing.add(secondAt(replayProbeOffsets[0])) + ..down.add(secondAt(replayProbeOffsets[1])); + expect(await probe(api).run(), ReplayEewVerdict.undecided); + }); + + test('ignores a bulletin the replayed feed would filter out', () async { + final mid = secondAt(replayProbeOffsets[1]); + final jma = _Api({ + mid: [_eew(author: 'jma', id: 'jma-1')], + }); + expect(await probe(jma).run(), ReplayEewVerdict.none); + + final nied = _Api({ + mid: [_eew(author: 'nied', id: 'nied-1')], + }); + expect(await probe(nied, cwaOnly: true).run(), ReplayEewVerdict.none); + }); + }); + + group('replayEewSlot', () { + RealtimeState> feed({ + List? data, + RealtimeStatus status = RealtimeStatus.live, + int failures = 0, + }) => RealtimeState( + status: status, + data: data, + consecutiveFailures: failures, + ); + + test('a card always wins', () { + expect( + replayEewSlot( + hasAlerts: true, + feed: feed( + data: const [], + failures: 5, + status: RealtimeStatus.offline, + ), + verdict: ReplayEewVerdict.none, + ), + ReplayEewSlot.card, + ); + }); + + test('a failing feed says it is retrying, never that there is no EEW', () { + expect( + replayEewSlot( + hasAlerts: false, + feed: feed(data: const [], failures: 2), + verdict: ReplayEewVerdict.none, + ), + ReplayEewSlot.retrying, + ); + expect( + replayEewSlot( + hasAlerts: false, + feed: feed( + data: const [], + failures: 9, + status: RealtimeStatus.offline, + ), + verdict: null, + ), + ReplayEewSlot.unavailable, + ); + }); + + test('waits for the first answer instead of drawing an empty one', () { + expect( + replayEewSlot( + hasAlerts: false, + feed: const RealtimeState.connecting(), + verdict: null, + ), + ReplayEewSlot.pending, + ); + }); + + test('says "not yet" until the samples rule the event out', () { + expect( + replayEewSlot( + hasAlerts: false, + feed: feed(data: const []), + verdict: ReplayEewVerdict.found, + ), + ReplayEewSlot.waiting, + ); + expect( + replayEewSlot( + hasAlerts: false, + feed: feed(data: const []), + verdict: ReplayEewVerdict.none, + ), + ReplayEewSlot.none, + ); + // An undecided probe has nothing to say either way. + expect( + replayEewSlot( + hasAlerts: false, + feed: feed(data: const []), + verdict: ReplayEewVerdict.undecided, + ), + ReplayEewSlot.waiting, + ); + }); + }); +}