From c8a56ebb9b61c00a4d25afa9088b0b956e575369 Mon Sep 17 00:00:00 2001 From: YinCheng0106 Date: Fri, 20 Nov 2026 14:37:19 +0800 Subject: [PATCH 1/3] chore(earthquake): add native Story map projection and layout support --- ARCHITECTURE.md | 24 + .../exptech/dpip/MapSnapshotProjectionTest.kt | 197 +++++++ .../com/exptech/dpip/MapSnapshotChannel.kt | 122 ++++- ios/Runner/MapSnapshotPlugin.swift | 104 +++- .../presentation/story_camera_fit.dart | 74 +++ .../presentation/story_map_snapshot.dart | 145 ++++++ .../presentation/story_marker_layout.dart | 298 +++++++++++ .../story_observation_clustering.dart | 110 ++++ .../fixtures/story_reports/README.md | 15 + .../tnn1-115057-2026-0825-150011.json | 1 + .../tyo1-107022-2018-0206-235041.json | 1 + .../tyo1-115000-2026-0909-192104.json | 1 + .../tyo1-115057-2026-0825-150011.json | 1 + .../tyo1-115067-2026-0930-130027.json | 1 + .../tyo1-115074-2026-1030-043743.json | 1 + .../tyo1-115075-2026-1101-162007.json | 1 + .../presentation/story_map_snapshot_test.dart | 266 ++++++++++ .../story_observation_clustering_test.dart | 480 ++++++++++++++++++ 18 files changed, 1814 insertions(+), 28 deletions(-) create mode 100644 android/app/src/androidTest/kotlin/com/exptech/dpip/MapSnapshotProjectionTest.kt create mode 100644 lib/features/earthquake/presentation/story_camera_fit.dart create mode 100644 lib/features/earthquake/presentation/story_map_snapshot.dart create mode 100644 lib/features/earthquake/presentation/story_marker_layout.dart create mode 100644 lib/features/earthquake/presentation/story_observation_clustering.dart create mode 100644 test/features/earthquake/presentation/fixtures/story_reports/README.md create mode 100644 test/features/earthquake/presentation/fixtures/story_reports/tnn1-115057-2026-0825-150011.json create mode 100644 test/features/earthquake/presentation/fixtures/story_reports/tyo1-107022-2018-0206-235041.json create mode 100644 test/features/earthquake/presentation/fixtures/story_reports/tyo1-115000-2026-0909-192104.json create mode 100644 test/features/earthquake/presentation/fixtures/story_reports/tyo1-115057-2026-0825-150011.json create mode 100644 test/features/earthquake/presentation/fixtures/story_reports/tyo1-115067-2026-0930-130027.json create mode 100644 test/features/earthquake/presentation/fixtures/story_reports/tyo1-115074-2026-1030-043743.json create mode 100644 test/features/earthquake/presentation/fixtures/story_reports/tyo1-115075-2026-1101-162007.json create mode 100644 test/features/earthquake/presentation/story_map_snapshot_test.dart create mode 100644 test/features/earthquake/presentation/story_observation_clustering_test.dart diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 50fc291c7..3504b2012 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -100,6 +100,30 @@ Each of these is a rule the code is expected to follow, not a description of what it happens to do. They live here so there is one copy: `CLAUDE.md` and `AGENTS.md` point at this file rather than restating it. +## Story map snapshot + +On `com.exptech.dpip/map_snapshot`, `capture` returns PNG bytes. +`captureWithProjection` takes the same style, center, zoom, logical +`width`/`height`, `pixelRatio`, and optional `showLogo` arguments, plus +`points`, a nonempty list of maps with unique nonempty string `id` and numeric +`latitude`/`longitude` in degrees. Story uses a 360×640 logical viewport and +integer pixel ratios 1–3. The pixel ratio is required, and width and height +must be positive whole numbers. + +The response is a single map with `png` (typed bytes), `pngWidth` and +`pngHeight` (integer raster pixels), `logicalWidth` and `logicalHeight` +(requested logical dimensions), and `points` (ID to `[x, y]` in logical +pixels from the top left). Off-canvas points are valid. All coordinates +come from the completed native snapshot that produced the PNG. Android +converts bitmap pixels against the actual bitmap dimensions. iOS converts +image points against the corresponding UIImage dimensions in points. + +Story matches the reserved `epicenter` ID to the report epicenter and each +observation ID to its JSON-encoded `[area name, station name]` pair. The app +requires a finite point for every requested ID and matching PNG dimensions +before export. Invalid requests fail with `bad_args`, and unusable native +projections or mismatched dimensions fail with `invalid_projection`. + ## Logging Always log through `Log` (`lib/core/logging/log.dart`): diff --git a/android/app/src/androidTest/kotlin/com/exptech/dpip/MapSnapshotProjectionTest.kt b/android/app/src/androidTest/kotlin/com/exptech/dpip/MapSnapshotProjectionTest.kt new file mode 100644 index 000000000..282ced2d6 --- /dev/null +++ b/android/app/src/androidTest/kotlin/com/exptech/dpip/MapSnapshotProjectionTest.kt @@ -0,0 +1,197 @@ +package com.exptech.dpip + +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.maplibre.android.MapLibre +import org.maplibre.android.camera.CameraPosition +import org.maplibre.android.geometry.LatLng +import org.maplibre.android.maps.Style +import org.maplibre.android.snapshotter.MapSnapshot +import org.maplibre.android.snapshotter.MapSnapshotter +import java.io.ByteArrayOutputStream +import java.util.concurrent.CompletableFuture +import java.util.concurrent.TimeUnit +import kotlin.math.hypot + +@RunWith(AndroidJUnit4::class) +class MapSnapshotProjectionTest { + private val instrumentation = InstrumentationRegistry.getInstrumentation() + private val context = instrumentation.targetContext + private val channel = MapSnapshotChannel(context) + private var nativeControl: MapSnapshotter? = null + + private val style = """ + {"version":8,"sources":{},"layers":[ + {"id":"background","type":"background","paint":{"background-color":"#66bbcc"}} + ]} + """.trimIndent() + private val center = LatLng(22.458492717664083, 120.71) + private val zoom = 5.806293217527967 + private val points = linkedMapOf( + "epicenter" to LatLng(22.64, 121.59), + "west" to LatLng(23.57, 119.56), + "north" to LatLng(25.08, center.longitude), + "south" to LatLng(21.90, center.longitude), + "center" to center, + ) + + @Test + fun projectsNorthUpInLogicalPixelsAndKeepsLegacyPngAtAllThreeScales() { + for (scale in 1..3) { + val args = arguments(scale) + val response = projected(args) + val png = response["png"] as ByteArray + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(png, 0, png.size, bounds) + assertEquals(360 * scale, bounds.outWidth) + assertEquals(640 * scale, bounds.outHeight) + assertEquals(bounds.outWidth, response["pngWidth"]) + assertEquals(bounds.outHeight, response["pngHeight"]) + assertEquals(360.0, response["logicalWidth"]) + assertEquals(640.0, response["logicalHeight"]) + assertArrayEquals(png, capture("capture", args - "points").get(30, TimeUnit.SECONDS) as ByteArray) + + val positions = response["points"] as Map<*, *> + assertEquals(points.keys, positions.keys) + val control = CompletableFuture() + instrumentation.runOnMainSync { + MapLibre.getInstance(context) + val options = MapSnapshotter.Options(360, 640) + .withPixelRatio(scale.toFloat()) + .withLogo(false) + .withStyleBuilder(Style.Builder().fromJson(style)) + .withCameraPosition( + CameraPosition.Builder() + .target(center) + .zoom(zoom) + .bearing(0.0) + .tilt(0.0) + .build(), + ) + val snapshotter = MapSnapshotter(context, options) + nativeControl = snapshotter + snapshotter.start({ snapshot -> + try { + val bitmapPng = ByteArrayOutputStream() + assertTrue(snapshot.bitmap.compress(Bitmap.CompressFormat.PNG, 100, bitmapPng)) + assertArrayEquals(png, bitmapPng.toByteArray()) + comparePoints(snapshot, scale, positions) + control.complete(Unit) + } catch (error: AssertionError) { + control.completeExceptionally(error) + } finally { + nativeControl = null + } + }, { message -> + nativeControl = null + control.completeExceptionally(AssertionError(message)) + }) + } + control.get(30, TimeUnit.SECONDS) + } + } + + @Test + fun rejectsInvalidCoordinatesAndDuplicateIds() { + val original = arguments(2) + val invalid = mapOf("id" to "invalid", "latitude" to Double.NaN, "longitude" to 121.5) + val duplicate = mapOf("id" to "same", "latitude" to 22.64, "longitude" to 121.59) + for (points in listOf(emptyList(), listOf(invalid), listOf(duplicate, duplicate))) { + val response = capture("captureWithProjection", original + ("points" to points)) + assertEquals("bad_args", response.get(30, TimeUnit.SECONDS)) + } + } + + @Test + fun reportsNativeStyleFailureThroughProjectionCapture() { + val response = capture("captureWithProjection", arguments(2) + ("style" to "invalid JSON")) + assertEquals("snapshot_failed", response.get(30, TimeUnit.SECONDS)) + } + + @Test + fun keepsConcurrentSnapshotsPairedWithTheirCameraAndDimensions() { + val first = capture("captureWithProjection", arguments(1)) + val second = capture("captureWithProjection", arguments(3) + ("zoom" to 7.0)) + val lowZoom = first.get(30, TimeUnit.SECONDS) as Map<*, *> + val highZoom = second.get(30, TimeUnit.SECONDS) as Map<*, *> + assertEquals(360, lowZoom["pngWidth"]) + assertEquals(1080, highZoom["pngWidth"]) + fun eastOffset(response: Map<*, *>): Double { + val locations = response["points"] as Map<*, *> + return ((locations["epicenter"] as List<*>)[0] as Double) - 180 + } + assertEquals( + eastOffset(lowZoom) * Math.pow(2.0, 7.0 - zoom), + eastOffset(highZoom), + 0.01, + ) + } + + private fun comparePoints(snapshot: MapSnapshot, scale: Int, projected: Map<*, *>) { + for ((id, coordinate) in points) { + val reference = snapshot.pixelForLatLng(coordinate) + val point = projected[id] as List<*> + val x = point[0] as Double + val y = point[1] as Double + val error = hypot(x - reference.x.toDouble() / scale, y - reference.y.toDouble() / scale) + assertTrue("$id at ${scale}x: $error logical px", error < 0.001) + // Three points on the camera's meridian must stay on one column. + when (id) { + "north" -> { + assertEquals(180.0, x, 0.001) + assertTrue(y < 320.0) + } + "south" -> { + assertEquals(180.0, x, 0.001) + assertTrue(y > 320.0) + } + "center" -> { + assertEquals(180.0, x, 0.001) + assertEquals(320.0, y, 0.001) + } + } + } + } + + private fun arguments(scale: Int): Map = mapOf( + "style" to style, + "latitude" to center.latitude, + "longitude" to center.longitude, + "zoom" to zoom, + "width" to 360.0, + "height" to 640.0, + "pixelRatio" to scale.toDouble(), + "showLogo" to false, + "points" to points.map { (id, coordinate) -> + mapOf("id" to id, "latitude" to coordinate.latitude, "longitude" to coordinate.longitude) + }, + ) + + private fun projected(args: Map): Map<*, *> = + capture("captureWithProjection", args).get(30, TimeUnit.SECONDS) as Map<*, *> + + private fun capture(method: String, args: Map): CompletableFuture { + val response = CompletableFuture() + instrumentation.runOnMainSync { + channel.onMethodCall(MethodCall(method, args), object : MethodChannel.Result { + override fun success(result: Any?) { response.complete(result) } + override fun error(code: String, message: String?, details: Any?) { + response.complete(code) + } + override fun notImplemented() { + response.completeExceptionally(AssertionError("$method is not implemented")) + } + }) + } + return response + } +} diff --git a/android/app/src/main/kotlin/com/exptech/dpip/MapSnapshotChannel.kt b/android/app/src/main/kotlin/com/exptech/dpip/MapSnapshotChannel.kt index 56f69882e..d3111487f 100644 --- a/android/app/src/main/kotlin/com/exptech/dpip/MapSnapshotChannel.kt +++ b/android/app/src/main/kotlin/com/exptech/dpip/MapSnapshotChannel.kt @@ -8,6 +8,7 @@ import org.maplibre.android.MapLibre import org.maplibre.android.camera.CameraPosition import org.maplibre.android.geometry.LatLng import org.maplibre.android.maps.Style +import org.maplibre.android.snapshotter.MapSnapshot import org.maplibre.android.snapshotter.MapSnapshotter import java.io.ByteArrayOutputStream @@ -28,19 +29,20 @@ class MapSnapshotChannel(private val context: Context) : override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { when (call.method) { - "capture" -> capture(call, result) + "capture", "captureWithProjection" -> capture(call, result) else -> result.notImplemented() } } private fun capture(call: MethodCall, result: MethodChannel.Result) { - val style = call.argument("style") - val latitude = call.argument("latitude") - val longitude = call.argument("longitude") - val zoom = call.argument("zoom") - val width = call.argument("width") - val height = call.argument("height") - val pixelRatio = call.argument("pixelRatio") ?: 1.0 + val style = call.argument("style") as? String + val latitude = (call.argument("latitude") as? Number)?.toDouble() + val longitude = (call.argument("longitude") as? Number)?.toDouble() + val zoom = (call.argument("zoom") as? Number)?.toDouble() + val width = (call.argument("width") as? Number)?.toDouble() + val height = (call.argument("height") as? Number)?.toDouble() + val requestedRatio = (call.argument("pixelRatio") as? Number)?.toDouble() + val pixelRatio = requestedRatio ?: 1.0 if (style == null || latitude == null || longitude == null || zoom == null || width == null || height == null ) { @@ -48,31 +50,111 @@ class MapSnapshotChannel(private val context: Context) : return } + val points = if (call.method == "captureWithProjection") { + val coordinates = projectionPoints(call.argument("points")) + if (coordinates == null || !validCoordinate(latitude, longitude) || + !zoom.isFinite() || requestedRatio !in listOf(1.0, 2.0, 3.0) || + !validDimension(width, pixelRatio) || !validDimension(height, pixelRatio) + ) { + result.error("bad_args", "Invalid snapshot viewport, camera or points", null) + return + } + coordinates + } else { + null + } + MapLibre.getInstance(context) - val options = MapSnapshotter.Options( - (width * pixelRatio).toInt(), - (height * pixelRatio).toInt(), - ) + val camera = CameraPosition.Builder() + .target(LatLng(latitude, longitude)) + .zoom(zoom) + if (points != null) { + // MapLibre uses an unset bearing of -1° in the native Snapshot. + // Story's camera fit assumes a north-up, unpitched viewport. + camera.bearing(0.0).tilt(0.0) + } + + // Options takes the logical viewport; MapLibre scales the output bitmap. + val options = MapSnapshotter.Options(width.toInt(), height.toInt()) .withPixelRatio(pixelRatio.toFloat()) + .withLogo(call.argument("showLogo") ?: true) .withStyleBuilder(Style.Builder().fromJson(style)) - .withCameraPosition( - CameraPosition.Builder() - .target(LatLng(latitude, longitude)) - .zoom(zoom) - .build(), - ) + .withCameraPosition(camera.build()) val snapshotter = MapSnapshotter(context, options) pending.add(snapshotter) snapshotter.start({ snapshot -> pending.remove(snapshotter) val stream = ByteArrayOutputStream() - snapshot.bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream) - result.success(stream.toByteArray()) + val encoded = snapshot.bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream) + if (points == null) { + result.success(stream.toByteArray()) + } else if (!encoded) { + result.error("no_image", "Snapshot PNG encoding failed", null) + } else { + val response = projectionResponse( + snapshot, stream.toByteArray(), width, height, pixelRatio, points, + ) + if (response == null) { + result.error("invalid_projection", "Invalid snapshot dimensions or points", null) + } else { + result.success(response) + } + } }, { error -> pending.remove(snapshotter) result.error("snapshot_failed", error, null) }) } + + private fun projectionPoints(raw: Any?): Map? { + if (raw !is List<*> || raw.isEmpty()) return null + val points = mutableMapOf() + for (item in raw) { + val point = item as? Map<*, *> ?: return null + val id = point["id"] as? String ?: return null + val latitude = (point["latitude"] as? Number)?.toDouble() ?: return null + val longitude = (point["longitude"] as? Number)?.toDouble() ?: return null + if (id.isEmpty() || id in points || !validCoordinate(latitude, longitude)) return null + points[id] = LatLng(latitude, longitude) + } + return points + } + + private fun validCoordinate(latitude: Double, longitude: Double): Boolean = + latitude in -90.0..90.0 && longitude in -180.0..180.0 + + private fun validDimension(value: Double, pixelRatio: Double): Boolean = + value >= 1 && value <= Int.MAX_VALUE / pixelRatio && value % 1 == 0.0 + + private fun projectionResponse( + snapshot: MapSnapshot, + png: ByteArray, + width: Double, + height: Double, + pixelRatio: Double, + points: Map, + ): Map? { + val pngWidth = snapshot.bitmap.width + val pngHeight = snapshot.bitmap.height + if (pngWidth != (width * pixelRatio).toInt() || + pngHeight != (height * pixelRatio).toInt() + ) return null + + // MapLibre's Android JNI returns physical bitmap coordinates. + val projected = points.mapValues { (_, coordinate) -> + val pixel = snapshot.pixelForLatLng(coordinate) + if (!pixel.x.isFinite() || !pixel.y.isFinite()) return null + listOf(pixel.x * width / pngWidth, pixel.y * height / pngHeight) + } + return mapOf( + "png" to png, + "pngWidth" to pngWidth, + "pngHeight" to pngHeight, + "logicalWidth" to width, + "logicalHeight" to height, + "points" to projected, + ) + } } diff --git a/ios/Runner/MapSnapshotPlugin.swift b/ios/Runner/MapSnapshotPlugin.swift index e6696f52e..0665bf7a2 100644 --- a/ios/Runner/MapSnapshotPlugin.swift +++ b/ios/Runner/MapSnapshotPlugin.swift @@ -22,14 +22,19 @@ public class MapSnapshotPlugin: NSObject, FlutterPlugin { public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch call.method { - case "capture": - capture(call.arguments as? [String: Any] ?? [:], result: result) + case "capture", "captureWithProjection": + capture( + call.arguments as? [String: Any] ?? [:], + withProjection: call.method == "captureWithProjection", + result: result) default: result(FlutterMethodNotImplemented) } } - private func capture(_ args: [String: Any], result: @escaping FlutterResult) { + private func capture( + _ args: [String: Any], withProjection: Bool, result: @escaping FlutterResult + ) { guard let style = args["style"] as? String, let latitude = args["latitude"] as? Double, @@ -42,6 +47,26 @@ public class MapSnapshotPlugin: NSObject, FlutterPlugin { return } + let center = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) + let scale = args["pixelRatio"] as? Double + let points: [String: CLLocationCoordinate2D]? + if withProjection { + guard + let coordinates = Self.projectionPoints(args["points"]), + CLLocationCoordinate2DIsValid(center), + zoom.isFinite, + let scale, [1.0, 2.0, 3.0].contains(scale), + Self.validDimension(width, scale: scale), Self.validDimension(height, scale: scale) + else { + result(FlutterError( + code: "bad_args", message: "Invalid snapshot viewport, camera or points", details: nil)) + return + } + points = coordinates + } else { + points = nil + } + // MLNMapSnapshotOptions needs a style URL — write the JSON to a temp file. let styleURL: URL do { @@ -54,14 +79,16 @@ public class MapSnapshotPlugin: NSObject, FlutterPlugin { } let camera = MLNMapCamera() - camera.centerCoordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) + camera.centerCoordinate = center let options = MLNMapSnapshotOptions( styleURL: styleURL, camera: camera, size: CGSize(width: width, height: height)) options.zoomLevel = zoom - if let pixelRatio = args["pixelRatio"] as? Double, pixelRatio > 0 { - options.scale = CGFloat(pixelRatio) + // Keep the existing default unless explicitly overridden. + options.showsLogo = (args["showLogo"] as? Bool) ?? true + if let scale, scale > 0 { + options.scale = CGFloat(scale) } let snapshotter = MLNMapSnapshotter(options: options) @@ -73,11 +100,72 @@ public class MapSnapshotPlugin: NSObject, FlutterPlugin { result(FlutterError(code: "snapshot_failed", message: error.localizedDescription, details: nil)) return } - guard let png = snapshot?.image.pngData() else { + guard let snapshot, let png = snapshot.image.pngData() else { result(FlutterError(code: "no_image", message: "Snapshot produced no image", details: nil)) return } - result(FlutterStandardTypedData(bytes: png)) + let bytes = FlutterStandardTypedData(bytes: png) + guard let points, let scale else { + result(bytes) + return + } + guard let response = Self.projectionResponse( + snapshot, png: bytes, width: width, height: height, scale: scale, points: points) + else { + result(FlutterError( + code: "invalid_projection", message: "Invalid snapshot dimensions or points", details: nil)) + return + } + result(response) + } + } + + private static func projectionPoints(_ raw: Any?) -> [String: CLLocationCoordinate2D]? { + guard let entries = raw as? [[String: Any]], !entries.isEmpty else { return nil } + var points: [String: CLLocationCoordinate2D] = [:] + for entry in entries { + guard + let id = entry["id"] as? String, !id.isEmpty, points[id] == nil, + let latitude = entry["latitude"] as? Double, + let longitude = entry["longitude"] as? Double + else { return nil } + let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) + guard CLLocationCoordinate2DIsValid(coordinate) else { return nil } + points[id] = coordinate + } + return points + } + + private static func validDimension(_ value: Double, scale: Double) -> Bool { + value >= 1 && value <= Double(Int32.max) / scale && value.rounded(.towardZero) == value + } + + private static func projectionResponse( + _ snapshot: MLNMapSnapshot, png: FlutterStandardTypedData, + width: Double, height: Double, scale: Double, + points: [String: CLLocationCoordinate2D] + ) -> [String: Any]? { + let image = snapshot.image + guard + let raster = image.cgImage, raster.width == Int(width * scale), + raster.height == Int(height * scale), image.scale == CGFloat(scale) + else { return nil } + + // MapLibre's iOS API takes and returns UIImage points, independent of scale. + var projected: [String: [Double]] = [:] + for (id, coordinate) in points { + let point = snapshot.point(for: coordinate) + guard point.x.isFinite, point.y.isFinite else { return nil } + projected[id] = [ + Double(point.x / image.size.width) * width, + Double(point.y / image.size.height) * height, + ] } + return [ + "png": png, + "pngWidth": raster.width, "pngHeight": raster.height, + "logicalWidth": width, "logicalHeight": height, + "points": projected, + ] } } diff --git a/lib/features/earthquake/presentation/story_camera_fit.dart b/lib/features/earthquake/presentation/story_camera_fit.dart new file mode 100644 index 000000000..5ea280245 --- /dev/null +++ b/lib/features/earthquake/presentation/story_camera_fit.dart @@ -0,0 +1,74 @@ +import 'dart:math' as math; +import 'dart:ui'; + +import 'package:dpip/features/earthquake/domain/earthquake_report.dart'; +import 'package:dpip/features/earthquake/presentation/story_map_snapshot.dart'; +import 'package:dpip/shared/map/camera_fit.dart'; +import 'package:maplibre_gl/maplibre_gl.dart' show LatLng; + +typedef StoryCameraLayout = ({Rect mapRegion, Rect anchorRegion}); +typedef StoryCamera = ({LatLng target, double zoom}); + +/// The map fills the canvas, while its symbols belong between the upper +/// Instagram guide and the HUD. The footprint bounds are relative to an +/// anchor and are known before projection, grouping or collision avoidance. +StoryCameraLayout storyCameraLayout({ + required Size canvas, + required double safeTop, + required double safeBottom, + required Rect hud, + required Rect footprint, + required double gap, +}) { + final region = Rect.fromLTRB( + 0, + safeTop, + canvas.width, + math.min(hud.top, canvas.height - safeBottom), + ); + final side = math.max(-footprint.left, footprint.right) + gap; + return ( + mapRegion: region, + anchorRegion: Rect.fromLTRB( + region.left + side, + region.top - footprint.top + gap, + region.right - side, + region.bottom - footprint.bottom - gap, + ), + ); +} + +/// FULL always fits the epicenter and every drawable report observation. +/// If the minimum zoom is reached, the caller checks actual native anchors +/// against the requested region to distinguish a fit from a constrained map. +StoryCamera fitStoryCamera(EarthquakeReport report, StoryCameraLayout layout) { + final anchors = layout.anchorRegion; + if (anchors.isEmpty) { + throw StateError('Story HUD leaves insufficient room for map symbols'); + } + if (!isStoryMapCoordinate(report.latitude, report.longitude)) { + throw const FormatException('Invalid Story epicenter coordinates'); + } + final bounds = safeFitBounds( + boundsFromPoints([ + LatLng(report.latitude, report.longitude), + for (final area in report.list.values) + for (final observation in area.town.values) + if (isStoryMapCoordinate(observation.latitude, observation.longitude)) + LatLng(observation.latitude, observation.longitude), + ])!, + )!; + // The shared fitter accepts symmetric horizontal padding and separate + // top/bottom insets. Together they describe the center rectangle exactly. + final camera = boundsFitCamera( + bounds, + viewport: StoryMapSnapshot.canvas, + padding: anchors.left, + topInset: anchors.top - anchors.left, + bottomInset: StoryMapSnapshot.canvas.height - anchors.bottom - anchors.left, + minZoom: 2, + maxZoom: 7, + ); + if (camera == null) throw StateError('Story camera fit unavailable'); + return camera; +} diff --git a/lib/features/earthquake/presentation/story_map_snapshot.dart b/lib/features/earthquake/presentation/story_map_snapshot.dart new file mode 100644 index 000000000..eee1d2833 --- /dev/null +++ b/lib/features/earthquake/presentation/story_map_snapshot.dart @@ -0,0 +1,145 @@ +import 'dart:convert'; + +import 'package:dpip/core/logging/log.dart'; +import 'package:dpip/features/earthquake/domain/earthquake_report.dart'; +import 'package:dpip/features/earthquake/presentation/story_observation_clustering.dart'; +import 'package:flutter/services.dart'; + +bool isStoryMapCoordinate(double latitude, double longitude) => + latitude >= -90 && latitude <= 90 && longitude >= -180 && longitude <= 180; + +/// The map and overlay anchors from one completed native Story capture. +final class StoryMapSnapshot { + StoryMapSnapshot._(this.png, this.epicenter, this.markers); + + static const canvas = Size(360, 640); + static const _channel = MethodChannel('com.exptech.dpip/map_snapshot'); + static const _epicenterId = 'epicenter'; + + final Uint8List png; + final Offset epicenter; + final List markers; + + static Future capture({ + required EarthquakeReport report, + required String style, + required double centerLatitude, + required double centerLongitude, + required double zoom, + double pixelRatio = 2, + }) async { + if (!isStoryMapCoordinate(report.latitude, report.longitude)) { + throw const FormatException('Invalid Story epicenter coordinates'); + } + final observations = { + for (final area in report.list.entries) + for (final station in area.value.town.entries) + jsonEncode([area.key, station.key]): station.value, + }; + final total = observations.length; + observations.removeWhere( + (_, station) => + !isStoryMapCoordinate(station.latitude, station.longitude), + ); + if (observations.length != total) { + Log.warning( + '[StoryMap] invalidObservationCoordinates=${total - observations.length} ' + 'validObservations=${observations.length}', + ); + } + final points = { + _epicenterId: (report.latitude, report.longitude), + for (final observation in observations.entries) + observation.key: ( + observation.value.latitude, + observation.value.longitude, + ), + }; + final response = await _channel.invokeMapMethod( + 'captureWithProjection', + { + 'style': style, + 'latitude': centerLatitude, + 'longitude': centerLongitude, + 'zoom': zoom, + 'width': canvas.width, + 'height': canvas.height, + 'pixelRatio': pixelRatio, + 'showLogo': false, + 'points': [ + for (final point in points.entries) + { + 'id': point.key, + 'latitude': point.value.$1, + 'longitude': point.value.$2, + }, + ], + }, + ); + final png = response?['png']; + final pngWidth = response?['pngWidth']; + final pngHeight = response?['pngHeight']; + if (response?['logicalWidth'] != canvas.width || + response?['logicalHeight'] != canvas.height || + pngWidth is! int || + pngHeight is! int || + pngWidth != canvas.width * pixelRatio || + pngHeight != canvas.height * pixelRatio || + png is! Uint8List || + !_matchesPngHeader(png, pngWidth, pngHeight)) { + throw const FormatException('Invalid Story snapshot PNG dimensions'); + } + + final rawPoints = response?['points']; + if (rawPoints is! Map || rawPoints.length != points.length) { + throw const FormatException('Missing or inconsistent Story projections'); + } + final projected = {}; + for (final id in points.keys) { + final pair = rawPoints[id]; + if (pair is! List || + pair.length != 2 || + pair[0] is! num || + pair[1] is! num) { + throw const FormatException( + 'Missing or invalid Story projection point', + ); + } + final position = Offset( + (pair[0] as num).toDouble(), + (pair[1] as num).toDouble(), + ); + if (!position.isFinite) { + throw const FormatException('Non-finite Story projection point'); + } + projected[id] = position; + } + + final markers = [ + for (final observation in observations.entries) + StoryStationMarker( + sourceId: observation.key, + latitude: observation.value.latitude, + longitude: observation.value.longitude, + position: projected[observation.key]!, + intensity: observation.value.intensity, + ), + ]; + return StoryMapSnapshot._( + png, + projected[_epicenterId]!, + List.unmodifiable(markers), + ); + } + + static bool _matchesPngHeader(Uint8List png, int width, int height) { + if (png.length < 24) return false; + final header = ByteData.sublistView(png); + return header.getUint32(0) == 0x89504E47 && + header.getUint32(4) == 0x0D0A1A0A && + header.getUint32(8) == 13 && + header.getUint32(12) == 0x49484452 && // IHDR + header.getUint32(16) == width && + header.getUint32(20) == height; + } +} diff --git a/lib/features/earthquake/presentation/story_marker_layout.dart b/lib/features/earthquake/presentation/story_marker_layout.dart new file mode 100644 index 000000000..9b53e32d0 --- /dev/null +++ b/lib/features/earthquake/presentation/story_marker_layout.dart @@ -0,0 +1,298 @@ +import 'dart:math' as math; +import 'dart:ui'; + +/// The rendered boxes relative to the marker's placement point. +/// +/// Use the envelope for canvas containment and the individual components for +/// collisions, so the empty corners of the envelope don't displace markers. +final class StoryMarkerFootprint { + StoryMarkerFootprint({required Size icon, Size? badge}) + : components = List.unmodifiable(_components(icon, badge)); + + static List _components(Size icon, Size? badge) { + const gap = 1.0; + final iconBox = Rect.fromCenter( + // Center grouped markers as a whole. The geographic placement point + // stays inside the intensity icon for the Story's small count badge. + center: badge == null + ? Offset.zero + : Offset(0, -(badge.height + gap) / 2), + width: icon.width, + height: icon.height, + ); + return [ + iconBox, + if (badge != null) + Offset(iconBox.right + 8 - badge.width, iconBox.bottom + gap) & badge, + ]; + } + + final List components; + + Rect get envelope => components.reduce((a, b) => a.expandToInclude(b)); + + List at(Offset center) => [ + for (final component in components) component.shift(center), + ]; +} + +typedef StoryMarkerAnchor = ({Offset anchor, StoryMarkerFootprint footprint}); + +final class StoryConnector { + const StoryConnector(this.from, this.to); + + final Offset from; + final Offset to; + static const strokeWidth = 1.5; + + /// Clip the segment's parameter range against both axes of the box. + bool intersects(Rect bounds) { + final rect = bounds.inflate(strokeWidth / 2); + var entry = 0.0; + var exit = 1.0; + for (final (start, end, min, max) in [ + (from.dx, to.dx, rect.left, rect.right), + (from.dy, to.dy, rect.top, rect.bottom), + ]) { + final delta = end - start; + if (delta == 0) { + if (start < min || start > max) return false; + continue; + } + final a = (min - start) / delta; + final b = (max - start) / delta; + entry = math.max(entry, math.min(a, b)); + exit = math.min(exit, math.max(a, b)); + if (entry > exit) return false; + } + return true; + } + + /// Count interior crossings or a shared stretch of collinear line. + /// Segments that merely touch at an endpoint don't count as crossings. + bool crosses(StoryConnector other) { + double cross(Offset a, Offset b) => a.dx * b.dy - a.dy * b.dx; + final direction = to - from; + final otherDirection = other.to - other.from; + final between = other.from - from; + final determinant = cross(direction, otherDirection); + if (determinant != 0) { + final t = cross(between, otherDirection) / determinant; + final u = cross(between, direction) / determinant; + return t > 0 && t < 1 && u > 0 && u < 1; + } + if (cross(between, direction) != 0) return false; + final useX = direction.dx.abs() >= direction.dy.abs(); + double axis(Offset p) => useX ? p.dx : p.dy; + final a = axis(from); + final b = axis(to); + final c = axis(other.from); + final d = axis(other.to); + return math.max(math.min(a, b), math.min(c, d)) < + math.min(math.max(a, b), math.max(c, d)); + } +} + +// The Task 4A fixtures used 48 px offsets and one ~65 px diagonal. Search up +// to the smaller limit in any direction, with 2 px rings to resolve the small +// badge overlaps without a full marker-width jump. +const storyMarkerDisplacementLimit = 48.0; +const _ringStep = 2.0; +const _directionCount = 16; +final _directions = [ + for (var i = 0; i < _directionCount; i++) + Offset.fromDirection(i * 2 * math.pi / _directionCount), +]; + +/// Places existing clusters in priority order, highest intensity first. +/// Returns a position for every anchor, even if some collisions are insoluble. +List layoutStoryMarkers({ + required List markers, + required Rect canvas, + required Rect? epicenter, + required Rect hud, +}) { + final centers = []; + final components = [ + for (final marker in markers) marker.footprint.at(marker.anchor), + ]; + final exclusions = [?epicenter, hud]; + final connectors = []; + for (final (index, marker) in markers.indexed) { + final envelope = marker.footprint.envelope; + final legalCenters = Rect.fromLTRB( + canvas.left - envelope.left, + canvas.top - envelope.top, + canvas.right - envelope.right, + canvas.bottom - envelope.bottom, + ); + final anchor = marker.anchor; + final origin = Offset( + _fitAxis(anchor.dx, legalCenters.left, legalCenters.right), + _fitAxis(anchor.dy, legalCenters.top, legalCenters.bottom), + ); + var best = origin; + final original = marker.footprint.at(origin); + final needsSearch = + origin != anchor || + (epicenter != null && original.any(epicenter.overlaps)) || + original.any(hud.overlaps) || + components + .take(index) + .any((other) => _overlapArea(original, other) > 0); + if (needsSearch) { + List score(Offset center) { + final boxes = marker.footprint.at(center); + final connector = center == anchor + ? null + : StoryConnector(anchor, center); + var higherCollisions = 0; + var higherArea = 0.0; + var lowerCollisions = 0; + var markerIntersections = 0; + for (final (otherIndex, other) in components.indexed) { + if (otherIndex == index) continue; + final area = _overlapArea(boxes, other); + if (area > 0) { + if (otherIndex < index) { + higherCollisions++; + higherArea += area; + } else { + lowerCollisions++; + } + } + if (connector != null && other.any(connector.intersects)) { + markerIntersections++; + } + } + return [ + if (epicenter != null) _overlapArea(boxes, [epicenter]), + _overlapArea(boxes, [hud]), + higherCollisions, + higherArea, + lowerCollisions, + markerIntersections + + connectors.where((line) => boxes.any(line.intersects)).length, + if (connector != null) ...[ + exclusions + .where( + (box) => !box.contains(anchor) && connector.intersects(box), + ) + .length, + connectors.where(connector.crosses).length, + ] else ...[ + 0, + 0, + ], + (center - anchor).distanceSquared, + ]; + } + + var bestScore = score(origin); + // Canvas containment can force a larger correction for an off-canvas + // anchor. Don't add to that distance if it already exceeds the budget. + final limit = math.max( + storyMarkerDisplacementLimit, + (origin - anchor).distance, + ); + for ( + var radius = _ringStep; + radius <= storyMarkerDisplacementLimit; + radius += _ringStep + ) { + for (final direction in _directions) { + final candidate = origin + direction * radius; + if (candidate.dx < legalCenters.left || + candidate.dx > legalCenters.right || + candidate.dy < legalCenters.top || + candidate.dy > legalCenters.bottom || + (candidate - anchor).distanceSquared > limit * limit) { + continue; + } + final candidateScore = score(candidate); + if (_isBetter(candidateScore, bestScore)) { + best = candidate; + bestScore = candidateScore; + } + } + } + } + centers.add(best); + components[index] = marker.footprint.at(best); + if (best != anchor) connectors.add(StoryConnector(anchor, best)); + } + return centers; +} + +/// Finds the topmost, then leftmost, unobstructed position for the measured +/// legend. Observations and their connectors keep their existing placement. +/// Returns null when the legend cannot fit among the reserved rectangles. +Rect? layoutStoryLegend({ + required Size legend, + required Rect safeRegion, + required List occupied, + required Iterable observations, + required List connectors, +}) { + if (legend.width > safeRegion.width || legend.height > safeRegion.height) { + return null; + } + + const observationClearance = 4.0; + const connectorClearance = StoryConnector.strokeWidth / 2 + 0.5; + final blockers = [ + ...occupied, + for (final position in observations) + Rect.fromCircle(center: position, radius: observationClearance), + for (final line in connectors) + Rect.fromPoints(line.from, line.to).inflate(connectorClearance), + ]..removeWhere((box) => !box.overlaps(safeRegion)); + blockers.sort((a, b) => a.left.compareTo(b.left)); + + // A new horizontal gap can only open at a blocker's bottom edge. Check + // those rows and the safe top, instead of searching pixel by pixel. + final rows = { + safeRegion.top, + for (final box in blockers) + if (box.bottom + legend.height <= safeRegion.bottom) box.bottom, + }.toList()..sort(); + for (final top in rows) { + final bottom = top + legend.height; + var left = safeRegion.left; + for (final box in blockers) { + if (box.bottom <= top || box.top >= bottom || box.right <= left) continue; + if (left + legend.width <= box.left) break; + left = box.right; + if (left + legend.width > safeRegion.right) break; + } + if (left + legend.width <= safeRegion.right) { + return Offset(left, top) & legend; + } + } + return null; +} + +double _fitAxis(double value, double low, double high) => + low <= high ? value.clamp(low, high) : (low + high) / 2; + +double _overlapArea(List first, List second) { + var area = 0.0; + for (final a in first) { + for (final b in second) { + final intersection = a.intersect(b); + if (!intersection.isEmpty) { + area += intersection.width * intersection.height; + } + } + } + return area; +} + +bool _isBetter(List candidate, List best) { + for (var i = 0; i < candidate.length; i++) { + final difference = candidate[i] - best[i]; + // Equivalent distances at different angles can differ by roundoff. + if (difference.abs() > 1e-9) return difference < 0; + } + return false; +} diff --git a/lib/features/earthquake/presentation/story_observation_clustering.dart b/lib/features/earthquake/presentation/story_observation_clustering.dart new file mode 100644 index 000000000..3eda17de0 --- /dev/null +++ b/lib/features/earthquake/presentation/story_observation_clustering.dart @@ -0,0 +1,110 @@ +import 'dart:ui' show Offset; + +import 'package:dpip/core/models/lat_lng.dart'; + +/// Local D75-compact validation value, pending earthquake-data approval. +const storyD75MaxDiameterMetres = 75000.0; + +final class StoryStationMarker { + const StoryStationMarker({ + required this.sourceId, + required this.latitude, + required this.longitude, + required this.position, + required this.intensity, + }); + + /// The original report's area and station keys, encoded as a pair. + final String sourceId; + final double latitude; + final double longitude; + + /// Native projection of the geographic coordinates onto the logical canvas. + final Offset position; + + /// Raw report intensity. The report date determines its display label. + final int intensity; +} + +final class StoryMarkerCluster { + StoryMarkerCluster._(List members) + : members = List.unmodifiable(members); + + final List members; + + /// An original highest-intensity observation with its geographic coordinates + /// and projected position. The widget may displace the display position + /// independently and draw a connector back to this projected anchor. + StoryStationMarker get anchor => members.first; + int get maxIntensity => anchor.intensity; + int get count => members.length; +} + +/// Greedily assigns observations to the closest existing anchor within 40 +/// logical pixels. Within an intensity, priority goes east to west, then north +/// to south, then by source ID. Each source ID is unique within a report. +/// +/// When [maxDiameterMetres] is supplied, the great-circle distance to every +/// existing member must be at most that many metres. Both limits include the +/// boundary. Omit the geographic limit to reproduce the screen-only baseline. +List clusterStoryObservations( + Iterable markers, { + double? maxDiameterMetres, +}) { + if (maxDiameterMetres != null && + (!maxDiameterMetres.isFinite || maxDiameterMetres < 0)) { + throw ArgumentError.value(maxDiameterMetres, 'maxDiameterMetres'); + } + const radiusSquared = 40.0 * 40.0; + final ordered = markers.where((marker) => marker.position.isFinite).toList() + ..sort((a, b) { + final intensity = b.intensity.compareTo(a.intensity); + return intensity != 0 ? intensity : _compareGeography(a, b); + }); + + final groups = >[]; + for (final marker in ordered) { + final coordinate = LatLng(marker.latitude, marker.longitude); + List? nearest; + var nearestDistanceSquared = double.infinity; + for (final group in groups) { + final distanceSquared = + (marker.position - group.first.position).distanceSquared; + // Equal distances favor the anchor with the earlier canonical priority. + // Groups are visited in that order because the sorted input seeds them. + if (distanceSquared <= radiusSquared && + distanceSquared < nearestDistanceSquared && + (maxDiameterMetres == null || + group.every( + (member) => + coordinate.distanceTo( + LatLng(member.latitude, member.longitude), + ) <= + maxDiameterMetres, + ))) { + nearest = group; + nearestDistanceSquared = distanceSquared; + } + } + if (nearest == null) { + groups.add([marker]); + } else { + nearest.add(marker); + } + } + + // Weaker groups draw first. Equal-strength groups use the same geographic + // priority for both displacement and painting. + return groups.map(StoryMarkerCluster._).toList()..sort((a, b) { + final intensity = a.maxIntensity.compareTo(b.maxIntensity); + return intensity != 0 ? intensity : _compareGeography(a.anchor, b.anchor); + }); +} + +int _compareGeography(StoryStationMarker a, StoryStationMarker b) { + final longitude = b.longitude.compareTo(a.longitude); + if (longitude != 0) return longitude; + final latitude = b.latitude.compareTo(a.latitude); + if (latitude != 0) return latitude; + return a.sourceId.compareTo(b.sourceId); +} diff --git a/test/features/earthquake/presentation/fixtures/story_reports/README.md b/test/features/earthquake/presentation/fixtures/story_reports/README.md new file mode 100644 index 000000000..3ca276703 --- /dev/null +++ b/test/features/earthquake/presentation/fixtures/story_reports/README.md @@ -0,0 +1,15 @@ +# Story earthquake reports + +These byte-for-byte responses were archived during the 2026-11-18 DPIP Story +audit. Each filename contains the ExpTech core API node and the report ID +used in `GET /api/v2/eq/report/{id}`. The tests run offline. + +| File | SHA-256 | +| --- | --- | +| `tnn1-115057-2026-0825-150011.json` | `0342f897dd9e79b729cb47f0188e8852dee9e900ad9bc25b0165aa7b31ae66fe` | +| `tyo1-115057-2026-0825-150011.json` | `b3bc54f9e6695ad6bd19c08059a5c4a51ae695701f6266b882ca7d34bb85a7c9` | +| `tyo1-115074-2026-1030-043743.json` | `47dfed266da323d727bb4005497947e5fc7ad2172b70b44058a61196b3b43c6c` | +| `tyo1-115067-2026-0930-130027.json` | `d55346e691583c64fdc9496a810e5b79c9cf4e02fa2490dfc86a0002b5ba89e3` | +| `tyo1-115075-2026-1101-162007.json` | `2a61e43b3153690ef20b4408098ff3b1930394a7179e0f29ecd6f4338217bd21` | +| `tyo1-115000-2026-0909-192104.json` | `fe18cbe9a073f88efc4970945b25d26dcff68a71680eaf38165d6a97effc238e` | +| `tyo1-107022-2018-0206-235041.json` | `7bef97714a8d7a65744a7669995e0d1ae0492396ff51c23b49e60f27ab3dfc8c` | diff --git a/test/features/earthquake/presentation/fixtures/story_reports/tnn1-115057-2026-0825-150011.json b/test/features/earthquake/presentation/fixtures/story_reports/tnn1-115057-2026-0825-150011.json new file mode 100644 index 000000000..9f565b015 --- /dev/null +++ b/test/features/earthquake/presentation/fixtures/story_reports/tnn1-115057-2026-0825-150011.json @@ -0,0 +1 @@ +{"depth":15.4,"id":"115057-2026-0825-150011","lat":22.64,"list":{"南投縣":{"int":2,"town":{"信義鄉":{"lat":23.7,"lon":120.85,"int":2},"南投市":{"lat":23.91,"lon":120.68,"int":2},"合歡山":{"lat":24.14,"lon":121.27,"int":2},"國姓":{"lat":24.06,"lon":120.91,"int":1},"埔里":{"lat":24.01,"lon":120.96,"int":1},"奧萬大":{"lat":23.95,"lon":121.18,"int":2},"日月潭":{"lat":23.88,"lon":120.91,"int":2},"玉山":{"lat":23.49,"lon":120.96,"int":2},"竹山":{"lat":23.82,"lon":120.73,"int":2},"魚池":{"lat":23.91,"lon":120.87,"int":1}}},"嘉義市":{"int":3,"town":{"嘉義市":{"lat":23.5,"lon":120.43,"int":3}}},"嘉義縣":{"int":3,"town":{"大埔":{"lat":23.24,"lon":120.62,"int":2},"太保市":{"lat":23.46,"lon":120.29,"int":2},"民雄":{"lat":23.53,"lon":120.47,"int":2},"番路":{"lat":23.44,"lon":120.6,"int":3},"義竹":{"lat":23.35,"lon":120.22,"int":2},"阿里山":{"lat":23.51,"lon":120.81,"int":2}}},"宜蘭縣":{"int":2,"town":{"冬山":{"lat":24.63,"lon":121.72,"int":1},"南山":{"lat":24.44,"lon":121.38,"int":2},"南澳":{"lat":24.43,"lon":121.75,"int":1},"大同":{"lat":24.6,"lon":121.51,"int":1},"宜蘭市":{"lat":24.76,"lon":121.76,"int":1},"牛鬥":{"lat":24.64,"lon":121.57,"int":1},"蘇澳":{"lat":24.61,"lon":121.86,"int":1},"頭城":{"lat":24.85,"lon":121.83,"int":1}}},"屏東縣":{"int":2,"town":{"三地門":{"lat":22.74,"lon":120.64,"int":2},"九如":{"lat":22.72,"lon":120.5,"int":2},"南灣":{"lat":21.96,"lon":120.75,"int":2},"墾丁":{"lat":21.94,"lon":120.81,"int":1},"小琉球":{"lat":22.35,"lon":120.38,"int":1},"屏東市":{"lat":22.68,"lon":120.5,"int":2},"恆春":{"lat":22,"lon":120.75,"int":2},"新埤":{"lat":22.48,"lon":120.57,"int":2},"春日":{"lat":22.37,"lon":120.63,"int":2},"東港":{"lat":22.46,"lon":120.46,"int":2},"滿州":{"lat":22.02,"lon":120.84,"int":2},"獅子":{"lat":22.22,"lon":120.8,"int":2},"鵝鑾鼻":{"lat":21.9,"lon":120.86,"int":1}}},"彰化縣":{"int":2,"town":{"二林":{"lat":23.9,"lon":120.38,"int":1},"員林":{"lat":23.96,"lon":120.58,"int":2},"大城":{"lat":23.86,"lon":120.29,"int":1},"彰化市":{"lat":24.08,"lon":120.56,"int":2},"鹿港":{"lat":24.06,"lon":120.43,"int":2}}},"新北市":{"int":1,"town":{"新北市":{"lat":25.02,"lon":121.47,"int":1},"新店":{"lat":24.96,"lon":121.53,"int":1},"汐止":{"lat":25.08,"lon":121.64,"int":1}}},"新竹市":{"int":1,"town":{"新竹市":{"lat":24.78,"lon":121.02,"int":1}}},"新竹縣":{"int":1,"town":{"五峰":{"lat":24.63,"lon":121.12,"int":1},"竹北市":{"lat":24.83,"lon":121.01,"int":1},"竹東":{"lat":24.74,"lon":121.09,"int":1},"關西":{"lat":24.78,"lon":121.18,"int":1}}},"桃園市":{"int":1,"town":{"大溪":{"lat":24.88,"lon":121.29,"int":1},"桃園市":{"lat":25,"lon":121.3,"int":1}}},"澎湖縣":{"int":1,"town":{"馬公市":{"lat":23.57,"lon":119.56,"int":1}}},"臺中市":{"int":2,"town":{"大甲":{"lat":24.35,"lon":120.64,"int":2},"德基":{"lat":24.25,"lon":121.16,"int":2},"梧棲":{"lat":24.26,"lon":120.52,"int":2},"梨山":{"lat":24.25,"lon":121.24,"int":2},"烏石坑":{"lat":24.28,"lon":120.95,"int":2},"臺中市":{"lat":24.15,"lon":120.68,"int":1},"霧峰":{"lat":24.04,"lon":120.7,"int":2}}},"臺北市":{"int":1,"town":{"信義區":{"lat":25.04,"lon":121.57,"int":1}}},"臺南市":{"int":3,"town":{"佳里":{"lat":23.17,"lon":120.2,"int":2},"善化":{"lat":23.14,"lon":120.29,"int":2},"新化":{"lat":23.02,"lon":120.35,"int":2},"曾文":{"lat":23.22,"lon":120.5,"int":2},"楠西":{"lat":23.18,"lon":120.53,"int":2},"永康":{"lat":23.04,"lon":120.24,"int":2},"白河":{"lat":23.35,"lon":120.41,"int":3},"臺南市":{"lat":22.99,"lon":120.2,"int":2}}},"臺東縣":{"int":4,"town":{"利稻":{"lat":23.19,"lon":121.03,"int":2},"卑南":{"lat":22.82,"lon":121.08,"int":3},"大武":{"lat":22.34,"lon":120.89,"int":2},"太麻里":{"lat":22.6,"lon":120.96,"int":3},"成功":{"lat":23.1,"lon":121.37,"int":4},"東河":{"lat":22.97,"lon":121.3,"int":4},"池上":{"lat":23.1,"lon":121.22,"int":4},"海端":{"lat":23.15,"lon":121.21,"int":3},"綠島":{"lat":22.67,"lon":121.47,"int":4},"臺東市":{"lat":22.75,"lon":121.16,"int":3},"蘭嶼":{"lat":22.04,"lon":121.56,"int":4},"長濱":{"lat":23.32,"lon":121.45,"int":3},"鹿野":{"lat":22.91,"lon":121.13,"int":3}}},"花蓮縣":{"int":3,"town":{"光復":{"lat":23.67,"lon":121.43,"int":2},"和平":{"lat":24.31,"lon":121.75,"int":1},"太魯閣":{"lat":24.16,"lon":121.62,"int":1},"富里":{"lat":23.2,"lon":121.29,"int":3},"東富":{"lat":23.68,"lon":121.48,"int":3},"水璉":{"lat":23.79,"lon":121.56,"int":2},"石梯坪":{"lat":23.48,"lon":121.51,"int":2},"秀林":{"lat":24.08,"lon":121.6,"int":1},"花蓮市":{"lat":23.98,"lon":121.61,"int":2},"萬榮":{"lat":23.49,"lon":121.35,"int":2},"西寶":{"lat":24.21,"lon":121.48,"int":2},"西林":{"lat":23.81,"lon":121.44,"int":2},"銅門":{"lat":23.97,"lon":121.49,"int":2},"鹽寮":{"lat":23.9,"lon":121.6,"int":2}}},"苗栗縣":{"int":2,"town":{"三義":{"lat":24.41,"lon":120.77,"int":2},"南庄":{"lat":24.63,"lon":121.01,"int":1},"後龍":{"lat":24.65,"lon":120.83,"int":1},"泰安":{"lat":24.47,"lon":120.94,"int":1},"竹南":{"lat":24.68,"lon":120.87,"int":1},"苗栗市":{"lat":24.56,"lon":120.83,"int":1},"鯉魚潭":{"lat":24.35,"lon":120.78,"int":2}}},"雲林縣":{"int":3,"town":{"古坑":{"lat":23.68,"lon":120.57,"int":2},"四湖":{"lat":23.64,"lon":120.23,"int":2},"斗六市":{"lat":23.71,"lon":120.54,"int":2},"水林":{"lat":23.52,"lon":120.23,"int":2},"草嶺":{"lat":23.6,"lon":120.68,"int":3},"西螺":{"lat":23.79,"lon":120.49,"int":2},"麥寮":{"lat":23.8,"lon":120.22,"int":1}}},"高雄市":{"int":2,"town":{"六龜":{"lat":22.99,"lon":120.65,"int":2},"壽山":{"lat":22.64,"lon":120.26,"int":1},"大寮":{"lat":22.59,"lon":120.42,"int":2},"旗山":{"lat":22.89,"lon":120.49,"int":2},"桃源":{"lat":23.18,"lon":120.78,"int":2},"甲仙":{"lat":23.08,"lon":120.59,"int":2},"路竹":{"lat":22.87,"lon":120.26,"int":2},"高雄市":{"lat":22.62,"lon":120.31,"int":2}}}},"loc":"臺東縣政府東南東方 46.7 公里 (位於臺灣東南部海域)","lon":121.59,"mag":5.9,"time":1787641211000,"trem":0} \ No newline at end of file diff --git a/test/features/earthquake/presentation/fixtures/story_reports/tyo1-107022-2018-0206-235041.json b/test/features/earthquake/presentation/fixtures/story_reports/tyo1-107022-2018-0206-235041.json new file mode 100644 index 000000000..a17854f2a --- /dev/null +++ b/test/features/earthquake/presentation/fixtures/story_reports/tyo1-107022-2018-0206-235041.json @@ -0,0 +1 @@ +{"depth":6.3,"id":"107022-2018-0206-235041","lat":24.1,"list":{"南投縣":{"int":5,"town":{"南投市":{"lat":23.91,"lon":120.68,"int":3},"合歡山":{"lat":24.14,"lon":121.27,"int":5},"名間":{"lat":23.88,"lon":120.69,"int":2},"埔里":{"lat":24.01,"lon":120.96,"int":3},"日月潭":{"lat":23.88,"lon":120.91,"int":3},"魚池":{"lat":23.91,"lon":120.87,"int":2}}},"嘉義市":{"int":3,"town":{"嘉義市":{"lat":23.5,"lon":120.43,"int":3}}},"嘉義縣":{"int":3,"town":{"大埔":{"lat":23.24,"lon":120.62,"int":2},"草山":{"lat":23.35,"lon":120.59,"int":3},"阿里山":{"lat":23.51,"lon":120.81,"int":3}}},"基隆市":{"int":2,"town":{"基隆市":{"lat":25.15,"lon":121.77,"int":2}}},"宜蘭縣":{"int":9,"town":{"內城":{"lat":24.72,"lon":121.68,"int":3},"南山":{"lat":24.44,"lon":121.38,"int":4},"南澳":{"lat":24.43,"lon":121.75,"int":9},"宜蘭市":{"lat":24.76,"lon":121.76,"int":3},"牛鬥":{"lat":24.64,"lon":121.57,"int":4},"蘇澳":{"lat":24.61,"lon":121.86,"int":3}}},"屏東縣":{"int":2,"town":{"三地門":{"lat":22.74,"lon":120.64,"int":1},"九如":{"lat":22.72,"lon":120.5,"int":2},"南灣":{"lat":21.96,"lon":120.75,"int":1},"屏東市":{"lat":22.68,"lon":120.5,"int":2},"恆春":{"lat":22,"lon":120.75,"int":1},"枋寮":{"lat":22.37,"lon":120.63,"int":1},"鵝鑾鼻":{"lat":21.9,"lon":120.86,"int":1}}},"彰化縣":{"int":3,"town":{"員林":{"lat":23.96,"lon":120.58,"int":3},"大城":{"lat":23.86,"lon":120.29,"int":3}}},"新北市":{"int":3,"town":{"三貂角":{"lat":25.01,"lon":122,"int":2},"五分山":{"lat":25.07,"lon":121.78,"int":3},"五股":{"lat":25.1,"lon":121.42,"int":2},"石門":{"lat":25.29,"lon":121.59,"int":2},"萬里":{"lat":25.2,"lon":121.66,"int":2}}},"新竹市":{"int":2,"town":{"新竹市":{"lat":24.78,"lon":121.02,"int":2}}},"新竹縣":{"int":3,"town":{"竹北市":{"lat":24.83,"lon":121.01,"int":3},"竹東":{"lat":24.74,"lon":121.09,"int":3}}},"桃園市":{"int":3,"town":{"三光":{"lat":24.67,"lon":121.37,"int":3},"中壢":{"lat":24.97,"lon":121.19,"int":3},"桃園市":{"lat":25,"lon":121.3,"int":2}}},"澎湖縣":{"int":2,"town":{"東吉島":{"lat":23.26,"lon":119.67,"int":1},"馬公市":{"lat":23.57,"lon":119.56,"int":2}}},"臺中市":{"int":4,"town":{"德基":{"lat":24.25,"lon":121.16,"int":4},"臺中市":{"lat":24.15,"lon":120.68,"int":2}}},"臺北市":{"int":3,"town":{"信義區":{"lat":25.04,"lon":121.57,"int":3},"指南宮":{"lat":24.98,"lon":121.59,"int":2},"臺北市":{"lat":25.04,"lon":121.51,"int":3},"陽明山":{"lat":25.18,"lon":121.53,"int":2}}},"臺南市":{"int":3,"town":{"七股":{"lat":23.15,"lon":120.09,"int":2},"佳里":{"lat":23.17,"lon":120.2,"int":3},"善化":{"lat":23.14,"lon":120.29,"int":2},"新化":{"lat":23.08,"lon":120.36,"int":2},"東山":{"lat":23.27,"lon":120.5,"int":2},"楠西":{"lat":23.18,"lon":120.53,"int":2},"永康":{"lat":23.04,"lon":120.24,"int":2},"臺南市":{"lat":22.99,"lon":120.2,"int":2}}},"臺東縣":{"int":3,"town":{"利稻":{"lat":23.19,"lon":121.03,"int":2},"卑南":{"lat":22.82,"lon":121.08,"int":1},"太麻里":{"lat":22.6,"lon":120.96,"int":1},"安朔":{"lat":22.38,"lon":120.86,"int":1},"成功":{"lat":23.1,"lon":121.37,"int":3},"東河":{"lat":22.97,"lon":121.3,"int":2},"池上":{"lat":23.1,"lon":121.22,"int":3},"綠島":{"lat":22.67,"lon":121.47,"int":1},"臺東市":{"lat":22.75,"lon":121.16,"int":2},"蘭嶼":{"lat":22.04,"lon":121.56,"int":1},"長濱":{"lat":23.32,"lon":121.45,"int":3}}},"花蓮縣":{"int":9,"town":{"和平":{"lat":24.31,"lon":121.75,"int":5},"太魯閣":{"lat":24.16,"lon":121.62,"int":9},"磯崎":{"lat":23.71,"lon":121.55,"int":3},"秀林":{"lat":24.08,"lon":121.6,"int":5},"花蓮市":{"lat":23.98,"lon":121.61,"int":9},"西林":{"lat":23.81,"lon":121.44,"int":4},"銅門":{"lat":23.97,"lon":121.49,"int":6},"鹽寮":{"lat":23.9,"lon":121.6,"int":9}}},"苗栗縣":{"int":3,"town":{"三義":{"lat":24.41,"lon":120.77,"int":2},"獅頭山":{"lat":24.63,"lon":121.01,"int":2},"竹南":{"lat":24.68,"lon":120.87,"int":3},"苗栗市":{"lat":24.56,"lon":120.83,"int":2},"鯉魚潭":{"lat":24.35,"lon":120.78,"int":2}}},"雲林縣":{"int":4,"town":{"古坑":{"lat":23.68,"lon":120.57,"int":3},"四湖":{"lat":23.64,"lon":120.23,"int":3},"斗六市":{"lat":23.71,"lon":120.54,"int":3},"草嶺":{"lat":23.6,"lon":120.68,"int":4}}},"高雄市":{"int":2,"town":{"旗山":{"lat":22.82,"lon":120.43,"int":2},"桃源":{"lat":23.16,"lon":120.77,"int":2},"甲仙":{"lat":23.08,"lon":120.59,"int":2}}}},"loc":"花蓮縣政府東北方 16.5 公里 (位於臺灣東部海域)","lon":121.73,"mag":6.2,"time":1517932241000,"trem":0} \ No newline at end of file diff --git a/test/features/earthquake/presentation/fixtures/story_reports/tyo1-115000-2026-0909-192104.json b/test/features/earthquake/presentation/fixtures/story_reports/tyo1-115000-2026-0909-192104.json new file mode 100644 index 000000000..243905748 --- /dev/null +++ b/test/features/earthquake/presentation/fixtures/story_reports/tyo1-115000-2026-0909-192104.json @@ -0,0 +1 @@ +{"depth":9.6,"id":"115000-2026-0909-192104","lat":24.53,"list":{"苗栗縣":{"int":1,"town":{"後龍":{"lat":24.65,"lon":120.83,"int":1}}}},"loc":"苗栗縣政府西南方 6.8 公里 (位於苗栗縣西湖鄉)","lon":120.77,"mag":2.7,"time":1788952864000,"trem":0} \ No newline at end of file diff --git a/test/features/earthquake/presentation/fixtures/story_reports/tyo1-115057-2026-0825-150011.json b/test/features/earthquake/presentation/fixtures/story_reports/tyo1-115057-2026-0825-150011.json new file mode 100644 index 000000000..e87d44ab6 --- /dev/null +++ b/test/features/earthquake/presentation/fixtures/story_reports/tyo1-115057-2026-0825-150011.json @@ -0,0 +1 @@ +{"depth":15.4,"id":"115057-2026-0825-150011","lat":22.64,"list":{"南投縣":{"int":2,"town":{"信義鄉":{"lat":23.7,"lon":120.85,"int":2},"南投市":{"lat":23.91,"lon":120.68,"int":2},"合歡山":{"lat":24.14,"lon":121.27,"int":2},"國姓":{"lat":24.06,"lon":120.91,"int":1},"埔里":{"lat":24.01,"lon":120.96,"int":1},"奧萬大":{"lat":23.95,"lon":121.18,"int":2},"日月潭":{"lat":23.88,"lon":120.91,"int":2},"玉山":{"lat":23.49,"lon":120.96,"int":2},"竹山":{"lat":23.82,"lon":120.73,"int":2},"魚池":{"lat":23.91,"lon":120.87,"int":1}}},"嘉義市":{"int":3,"town":{"嘉義市":{"lat":23.5,"lon":120.43,"int":3}}},"嘉義縣":{"int":3,"town":{"大埔":{"lat":23.24,"lon":120.62,"int":2},"太保市":{"lat":23.46,"lon":120.29,"int":2},"民雄":{"lat":23.53,"lon":120.47,"int":2},"番路":{"lat":23.44,"lon":120.6,"int":3},"義竹":{"lat":23.35,"lon":120.22,"int":2},"阿里山":{"lat":23.51,"lon":120.81,"int":2}}},"宜蘭縣":{"int":2,"town":{"冬山":{"lat":24.63,"lon":121.72,"int":1},"南山":{"lat":24.44,"lon":121.38,"int":2},"南澳":{"lat":24.43,"lon":121.75,"int":1},"大同":{"lat":24.6,"lon":121.51,"int":1},"宜蘭市":{"lat":24.76,"lon":121.76,"int":1},"牛鬥":{"lat":24.64,"lon":121.57,"int":1},"蘇澳":{"lat":24.61,"lon":121.86,"int":1},"頭城":{"lat":24.85,"lon":121.83,"int":1}}},"屏東縣":{"int":2,"town":{"三地門":{"lat":22.74,"lon":120.64,"int":2},"九如":{"lat":22.72,"lon":120.5,"int":2},"南灣":{"lat":21.96,"lon":120.75,"int":2},"墾丁":{"lat":21.94,"lon":120.81,"int":1},"小琉球":{"lat":22.35,"lon":120.38,"int":1},"屏東市":{"lat":22.68,"lon":120.5,"int":2},"恆春":{"lat":22,"lon":120.75,"int":2},"新埤":{"lat":22.48,"lon":120.57,"int":2},"春日":{"lat":22.37,"lon":120.63,"int":2},"東港":{"lat":22.46,"lon":120.46,"int":2},"滿州":{"lat":22.02,"lon":120.84,"int":2},"獅子":{"lat":22.22,"lon":120.8,"int":2},"鵝鑾鼻":{"lat":21.9,"lon":120.86,"int":1}}},"彰化縣":{"int":2,"town":{"二林":{"lat":23.9,"lon":120.38,"int":1},"員林":{"lat":23.96,"lon":120.58,"int":2},"大城":{"lat":23.86,"lon":120.29,"int":1},"彰化市":{"lat":24.08,"lon":120.56,"int":2},"鹿港":{"lat":24.06,"lon":120.43,"int":2}}},"新北市":{"int":1,"town":{"新北市":{"lat":25.02,"lon":121.47,"int":1},"新店":{"lat":24.96,"lon":121.53,"int":1},"汐止":{"lat":25.08,"lon":121.64,"int":1}}},"新竹市":{"int":1,"town":{"新竹市":{"lat":24.78,"lon":121.02,"int":1}}},"新竹縣":{"int":1,"town":{"五峰":{"lat":24.63,"lon":121.12,"int":1},"竹北市":{"lat":24.83,"lon":121.01,"int":1},"竹東":{"lat":24.74,"lon":121.09,"int":1},"關西":{"lat":24.78,"lon":121.18,"int":1}}},"桃園市":{"int":1,"town":{"大溪":{"lat":24.88,"lon":121.29,"int":1},"桃園市":{"lat":25,"lon":121.3,"int":1}}},"澎湖縣":{"int":1,"town":{"馬公市":{"lat":23.57,"lon":119.56,"int":1}}},"臺中市":{"int":2,"town":{"大甲":{"lat":24.35,"lon":120.64,"int":2},"德基":{"lat":24.25,"lon":121.16,"int":2},"梧棲":{"lat":24.26,"lon":120.52,"int":2},"梨山":{"lat":24.25,"lon":121.24,"int":2},"烏石坑":{"lat":24.28,"lon":120.95,"int":2},"臺中市":{"lat":24.15,"lon":120.68,"int":1},"霧峰":{"lat":24.04,"lon":120.7,"int":2}}},"臺北市":{"int":1,"town":{"信義區":{"lat":25.04,"lon":121.57,"int":1},"臺北市":{"lat":25.04,"lon":121.51,"int":1}}},"臺南市":{"int":3,"town":{"佳里":{"lat":23.17,"lon":120.2,"int":2},"善化":{"lat":23.14,"lon":120.29,"int":2},"新化":{"lat":23.02,"lon":120.35,"int":2},"曾文":{"lat":23.22,"lon":120.5,"int":2},"楠西":{"lat":23.18,"lon":120.53,"int":2},"永康":{"lat":23.04,"lon":120.24,"int":2},"白河":{"lat":23.35,"lon":120.41,"int":3},"臺南市":{"lat":22.99,"lon":120.2,"int":2}}},"臺東縣":{"int":4,"town":{"利稻":{"lat":23.19,"lon":121.03,"int":2},"卑南":{"lat":22.82,"lon":121.08,"int":3},"大武":{"lat":22.34,"lon":120.89,"int":2},"太麻里":{"lat":22.6,"lon":120.96,"int":3},"成功":{"lat":23.1,"lon":121.37,"int":4},"東河":{"lat":22.97,"lon":121.3,"int":4},"池上":{"lat":23.1,"lon":121.22,"int":4},"海端":{"lat":23.15,"lon":121.21,"int":3},"綠島":{"lat":22.67,"lon":121.47,"int":4},"臺東市":{"lat":22.75,"lon":121.16,"int":3},"蘭嶼":{"lat":22.04,"lon":121.56,"int":4},"長濱":{"lat":23.32,"lon":121.45,"int":3},"鹿野":{"lat":22.91,"lon":121.13,"int":3}}},"花蓮縣":{"int":3,"town":{"光復":{"lat":23.67,"lon":121.43,"int":2},"和平":{"lat":24.31,"lon":121.75,"int":1},"太魯閣":{"lat":24.16,"lon":121.62,"int":1},"富里":{"lat":23.2,"lon":121.29,"int":3},"東富":{"lat":23.68,"lon":121.48,"int":3},"水璉":{"lat":23.79,"lon":121.56,"int":2},"石梯坪":{"lat":23.48,"lon":121.51,"int":2},"秀林":{"lat":24.08,"lon":121.6,"int":1},"花蓮市":{"lat":23.98,"lon":121.61,"int":2},"萬榮":{"lat":23.49,"lon":121.35,"int":2},"西寶":{"lat":24.21,"lon":121.48,"int":2},"西林":{"lat":23.81,"lon":121.44,"int":2},"銅門":{"lat":23.97,"lon":121.49,"int":2},"鹽寮":{"lat":23.9,"lon":121.6,"int":2}}},"苗栗縣":{"int":2,"town":{"三義":{"lat":24.41,"lon":120.77,"int":2},"南庄":{"lat":24.63,"lon":121.01,"int":1},"後龍":{"lat":24.65,"lon":120.83,"int":1},"泰安":{"lat":24.47,"lon":120.94,"int":1},"竹南":{"lat":24.68,"lon":120.87,"int":1},"苗栗市":{"lat":24.56,"lon":120.83,"int":1},"鯉魚潭":{"lat":24.35,"lon":120.78,"int":2}}},"雲林縣":{"int":3,"town":{"古坑":{"lat":23.68,"lon":120.57,"int":2},"四湖":{"lat":23.64,"lon":120.23,"int":2},"斗六市":{"lat":23.71,"lon":120.54,"int":2},"水林":{"lat":23.52,"lon":120.23,"int":2},"草嶺":{"lat":23.6,"lon":120.68,"int":3},"西螺":{"lat":23.79,"lon":120.49,"int":2},"麥寮":{"lat":23.8,"lon":120.22,"int":1}}},"高雄市":{"int":2,"town":{"六龜":{"lat":22.99,"lon":120.65,"int":2},"壽山":{"lat":22.64,"lon":120.26,"int":1},"大寮":{"lat":22.59,"lon":120.42,"int":2},"旗山":{"lat":22.89,"lon":120.49,"int":2},"桃源":{"lat":23.18,"lon":120.78,"int":2},"甲仙":{"lat":23.08,"lon":120.59,"int":2},"路竹":{"lat":22.87,"lon":120.26,"int":2},"高雄市":{"lat":22.62,"lon":120.31,"int":2}}}},"loc":"臺東縣政府東南東方 46.7 公里 (位於臺灣東南部海域)","lon":121.59,"mag":5.9,"time":1787641211000,"trem":0} \ No newline at end of file diff --git a/test/features/earthquake/presentation/fixtures/story_reports/tyo1-115067-2026-0930-130027.json b/test/features/earthquake/presentation/fixtures/story_reports/tyo1-115067-2026-0930-130027.json new file mode 100644 index 000000000..3e4ad8132 --- /dev/null +++ b/test/features/earthquake/presentation/fixtures/story_reports/tyo1-115067-2026-0930-130027.json @@ -0,0 +1 @@ +{"depth":42.9,"id":"115067-2026-0930-130027","lat":23.84,"list":{"南投縣":{"int":1,"town":{"信義鄉":{"lat":23.7,"lon":120.85,"int":1},"南投市":{"lat":23.91,"lon":120.68,"int":1},"合歡山":{"lat":24.14,"lon":121.27,"int":1},"國姓":{"lat":24.06,"lon":120.91,"int":1},"日月潭":{"lat":23.88,"lon":120.91,"int":1},"玉山":{"lat":23.49,"lon":120.96,"int":1},"竹山":{"lat":23.82,"lon":120.73,"int":1}}},"嘉義市":{"int":1,"town":{"嘉義市":{"lat":23.5,"lon":120.43,"int":1}}},"嘉義縣":{"int":2,"town":{"太保市":{"lat":23.46,"lon":120.29,"int":1},"民雄":{"lat":23.53,"lon":120.47,"int":1},"番路":{"lat":23.44,"lon":120.6,"int":2},"義竹":{"lat":23.35,"lon":120.22,"int":2},"阿里山":{"lat":23.51,"lon":120.81,"int":1}}},"宜蘭縣":{"int":2,"town":{"內城":{"lat":24.72,"lon":121.68,"int":2},"冬山":{"lat":24.63,"lon":121.72,"int":2},"南山":{"lat":24.44,"lon":121.38,"int":1},"南澳":{"lat":24.43,"lon":121.75,"int":2},"大同":{"lat":24.6,"lon":121.51,"int":1},"宜蘭市":{"lat":24.76,"lon":121.76,"int":2},"牛鬥":{"lat":24.64,"lon":121.57,"int":1},"蘇澳":{"lat":24.61,"lon":121.86,"int":1},"頭城":{"lat":24.85,"lon":121.83,"int":2},"龜山島":{"lat":24.84,"lon":121.94,"int":1}}},"屏東縣":{"int":1,"town":{"九如":{"lat":22.72,"lon":120.5,"int":1},"屏東市":{"lat":22.68,"lon":120.5,"int":1}}},"彰化縣":{"int":2,"town":{"二林":{"lat":23.9,"lon":120.38,"int":2},"員林":{"lat":23.96,"lon":120.58,"int":1},"大城":{"lat":23.86,"lon":120.29,"int":2},"彰化市":{"lat":24.08,"lon":120.56,"int":2},"鹿港":{"lat":24.06,"lon":120.43,"int":1}}},"新北市":{"int":2,"town":{"三峽":{"lat":24.94,"lon":121.37,"int":1},"五分山":{"lat":25.07,"lon":121.78,"int":1},"新北市":{"lat":25.02,"lon":121.47,"int":2},"新店":{"lat":24.96,"lon":121.53,"int":1},"汐止":{"lat":25.08,"lon":121.64,"int":1},"淡水":{"lat":25.16,"lon":121.45,"int":1},"烏來":{"lat":24.86,"lon":121.55,"int":1},"萬里":{"lat":25.2,"lon":121.66,"int":1},"雙溪":{"lat":24.97,"lon":121.83,"int":1}}},"新竹市":{"int":1,"town":{"新竹市":{"lat":24.78,"lon":121.02,"int":1}}},"新竹縣":{"int":1,"town":{"五峰":{"lat":24.63,"lon":121.12,"int":1},"竹北市":{"lat":24.83,"lon":121.01,"int":1},"竹東":{"lat":24.74,"lon":121.09,"int":1},"關西":{"lat":24.78,"lon":121.18,"int":1}}},"桃園市":{"int":1,"town":{"三光":{"lat":24.67,"lon":121.37,"int":1},"中壢":{"lat":24.97,"lon":121.19,"int":1},"大溪":{"lat":24.88,"lon":121.29,"int":1},"桃園市":{"lat":25,"lon":121.3,"int":1}}},"臺中市":{"int":1,"town":{"大甲":{"lat":24.35,"lon":120.64,"int":1},"德基":{"lat":24.25,"lon":121.16,"int":1},"梧棲":{"lat":24.26,"lon":120.52,"int":1},"梨山":{"lat":24.25,"lon":121.24,"int":1},"烏石坑":{"lat":24.28,"lon":120.95,"int":1},"臺中市":{"lat":24.15,"lon":120.68,"int":1},"霧峰":{"lat":24.04,"lon":120.7,"int":1}}},"臺北市":{"int":1,"town":{"信義區":{"lat":25.04,"lon":121.57,"int":1},"木柵":{"lat":24.98,"lon":121.59,"int":1},"臺北市":{"lat":25.04,"lon":121.51,"int":1}}},"臺南市":{"int":1,"town":{"佳里":{"lat":23.17,"lon":120.2,"int":1},"善化":{"lat":23.14,"lon":120.29,"int":1},"新化":{"lat":23.02,"lon":120.35,"int":1},"白河":{"lat":23.35,"lon":120.41,"int":1}}},"臺東縣":{"int":1,"town":{"成功":{"lat":23.1,"lon":121.37,"int":1},"東河":{"lat":22.97,"lon":121.3,"int":1},"池上":{"lat":23.1,"lon":121.22,"int":1},"海端":{"lat":23.15,"lon":121.21,"int":1},"綠島":{"lat":22.67,"lon":121.47,"int":1},"蘭嶼":{"lat":22.04,"lon":121.56,"int":1},"長濱":{"lat":23.32,"lon":121.45,"int":1}}},"花蓮縣":{"int":2,"town":{"光復":{"lat":23.67,"lon":121.43,"int":1},"和平":{"lat":24.31,"lon":121.75,"int":2},"太魯閣":{"lat":24.16,"lon":121.62,"int":1},"富里":{"lat":23.2,"lon":121.29,"int":1},"東富":{"lat":23.68,"lon":121.48,"int":1},"水璉":{"lat":23.79,"lon":121.56,"int":1},"石梯坪":{"lat":23.48,"lon":121.51,"int":1},"花蓮市":{"lat":23.98,"lon":121.61,"int":1},"萬榮":{"lat":23.49,"lon":121.35,"int":1},"西寶":{"lat":24.21,"lon":121.48,"int":2},"銅門":{"lat":23.97,"lon":121.49,"int":1},"鹽寮":{"lat":23.9,"lon":121.6,"int":1}}},"苗栗縣":{"int":1,"town":{"南庄":{"lat":24.63,"lon":121.01,"int":1},"後龍":{"lat":24.65,"lon":120.83,"int":1},"泰安":{"lat":24.47,"lon":120.94,"int":1},"竹南":{"lat":24.68,"lon":120.87,"int":1},"苗栗市":{"lat":24.56,"lon":120.83,"int":1},"鯉魚潭":{"lat":24.35,"lon":120.78,"int":1}}},"雲林縣":{"int":2,"town":{"古坑":{"lat":23.68,"lon":120.57,"int":1},"四湖":{"lat":23.64,"lon":120.23,"int":1},"斗六市":{"lat":23.71,"lon":120.54,"int":1},"水林":{"lat":23.52,"lon":120.23,"int":1},"草嶺":{"lat":23.6,"lon":120.68,"int":1},"西螺":{"lat":23.79,"lon":120.49,"int":2},"麥寮":{"lat":23.8,"lon":120.22,"int":2}}},"高雄市":{"int":1,"town":{"大寮":{"lat":22.59,"lon":120.42,"int":1},"旗山":{"lat":22.89,"lon":120.49,"int":1}}}},"loc":"花蓮縣政府東方 129.7 公里 (位於臺灣東部海域)","lon":122.88,"mag":6,"time":1790744427000,"trem":0} \ No newline at end of file diff --git a/test/features/earthquake/presentation/fixtures/story_reports/tyo1-115074-2026-1030-043743.json b/test/features/earthquake/presentation/fixtures/story_reports/tyo1-115074-2026-1030-043743.json new file mode 100644 index 000000000..6c51d8e04 --- /dev/null +++ b/test/features/earthquake/presentation/fixtures/story_reports/tyo1-115074-2026-1030-043743.json @@ -0,0 +1 @@ +{"depth":24.7,"id":"115074-2026-1030-043743","lat":24.18,"list":{"南投縣":{"int":1,"town":{"合歡山":{"lat":24.14,"lon":121.27,"int":1}}},"宜蘭縣":{"int":3,"town":{"內城":{"lat":24.72,"lon":121.68,"int":1},"冬山":{"lat":24.63,"lon":121.72,"int":2},"南山":{"lat":24.44,"lon":121.38,"int":2},"南澳":{"lat":24.43,"lon":121.75,"int":3},"宜蘭市":{"lat":24.76,"lon":121.76,"int":1},"牛鬥":{"lat":24.64,"lon":121.57,"int":2},"蘇澳":{"lat":24.61,"lon":121.86,"int":1}}},"臺中市":{"int":1,"town":{"德基":{"lat":24.25,"lon":121.16,"int":1},"梨山":{"lat":24.25,"lon":121.24,"int":1}}},"花蓮縣":{"int":3,"town":{"和平":{"lat":24.31,"lon":121.75,"int":3},"太魯閣":{"lat":24.16,"lon":121.62,"int":3},"水璉":{"lat":23.79,"lon":121.56,"int":1},"秀林":{"lat":24.08,"lon":121.6,"int":1},"花蓮市":{"lat":23.98,"lon":121.61,"int":1},"西寶":{"lat":24.21,"lon":121.48,"int":2},"銅門":{"lat":23.97,"lon":121.49,"int":1},"鹽寮":{"lat":23.9,"lon":121.6,"int":1}}}},"loc":"花蓮縣政府東北方 29.1 公里 (位於臺灣東部海域)","lon":121.82,"mag":4.5,"time":1793306263000,"trem":0} \ No newline at end of file diff --git a/test/features/earthquake/presentation/fixtures/story_reports/tyo1-115075-2026-1101-162007.json b/test/features/earthquake/presentation/fixtures/story_reports/tyo1-115075-2026-1101-162007.json new file mode 100644 index 000000000..4b2b4019b --- /dev/null +++ b/test/features/earthquake/presentation/fixtures/story_reports/tyo1-115075-2026-1101-162007.json @@ -0,0 +1 @@ +{"depth":119.5,"id":"115075-2026-1101-162007","lat":24.89,"list":{"南投縣":{"int":2,"town":{"信義鄉":{"lat":23.7,"lon":120.85,"int":2},"南投市":{"lat":23.91,"lon":120.68,"int":1},"合歡山":{"lat":24.14,"lon":121.27,"int":2},"國姓":{"lat":24.06,"lon":120.91,"int":1},"埔里":{"lat":24.01,"lon":120.96,"int":1},"奧萬大":{"lat":23.95,"lon":121.18,"int":2},"日月潭":{"lat":23.88,"lon":120.91,"int":2},"玉山":{"lat":23.49,"lon":120.96,"int":2},"竹山":{"lat":23.82,"lon":120.73,"int":1}}},"嘉義市":{"int":1,"town":{"嘉義市":{"lat":23.5,"lon":120.43,"int":1}}},"嘉義縣":{"int":2,"town":{"太保市":{"lat":23.46,"lon":120.29,"int":1},"番路":{"lat":23.44,"lon":120.6,"int":2},"義竹":{"lat":23.35,"lon":120.22,"int":1},"阿里山":{"lat":23.51,"lon":120.81,"int":1}}},"基隆市":{"int":1,"town":{"基隆市":{"lat":25.15,"lon":121.77,"int":1},"彭佳嶼":{"lat":25.63,"lon":122.08,"int":1}}},"宜蘭縣":{"int":3,"town":{"內城":{"lat":24.72,"lon":121.68,"int":2},"冬山":{"lat":24.63,"lon":121.72,"int":2},"南山":{"lat":24.44,"lon":121.38,"int":2},"南澳":{"lat":24.43,"lon":121.75,"int":3},"大同":{"lat":24.6,"lon":121.51,"int":2},"宜蘭市":{"lat":24.76,"lon":121.76,"int":2},"牛鬥":{"lat":24.64,"lon":121.57,"int":3},"蘇澳":{"lat":24.61,"lon":121.86,"int":2},"頭城":{"lat":24.85,"lon":121.83,"int":2}}},"彰化縣":{"int":2,"town":{"二林":{"lat":23.9,"lon":120.38,"int":2},"員林":{"lat":23.96,"lon":120.58,"int":1},"大城":{"lat":23.86,"lon":120.29,"int":2},"彰化市":{"lat":24.08,"lon":120.56,"int":2},"鹿港":{"lat":24.06,"lon":120.43,"int":1}}},"新北市":{"int":2,"town":{"三峽":{"lat":24.94,"lon":121.37,"int":2},"三貂角":{"lat":25.01,"lon":122,"int":1},"五分山":{"lat":25.07,"lon":121.78,"int":2},"五股":{"lat":25.1,"lon":121.42,"int":1},"新北市":{"lat":25.02,"lon":121.47,"int":2},"新店":{"lat":24.96,"lon":121.53,"int":2},"汐止":{"lat":25.08,"lon":121.64,"int":2},"淡水":{"lat":25.16,"lon":121.45,"int":2},"烏來":{"lat":24.86,"lon":121.55,"int":2},"石門":{"lat":25.29,"lon":121.59,"int":2},"萬里":{"lat":25.2,"lon":121.66,"int":1},"雙溪":{"lat":24.97,"lon":121.83,"int":1}}},"新竹市":{"int":2,"town":{"新竹市":{"lat":24.78,"lon":121.02,"int":2}}},"新竹縣":{"int":2,"town":{"五峰":{"lat":24.63,"lon":121.12,"int":1},"竹北市":{"lat":24.83,"lon":121.01,"int":1},"竹東":{"lat":24.74,"lon":121.09,"int":2},"關西":{"lat":24.78,"lon":121.18,"int":2}}},"桃園市":{"int":2,"town":{"三光":{"lat":24.67,"lon":121.37,"int":2},"中壢":{"lat":24.97,"lon":121.19,"int":2},"大溪":{"lat":24.88,"lon":121.29,"int":1},"新屋":{"lat":25.01,"lon":121.05,"int":2},"桃園市":{"lat":25,"lon":121.3,"int":2}}},"臺中市":{"int":2,"town":{"大甲":{"lat":24.35,"lon":120.64,"int":1},"德基":{"lat":24.25,"lon":121.16,"int":2},"梧棲":{"lat":24.26,"lon":120.52,"int":2},"梨山":{"lat":24.25,"lon":121.24,"int":2},"烏石坑":{"lat":24.28,"lon":120.95,"int":1},"霧峰":{"lat":24.04,"lon":120.7,"int":1}}},"臺北市":{"int":2,"town":{"信義區":{"lat":25.04,"lon":121.57,"int":2},"木柵":{"lat":24.98,"lon":121.59,"int":1},"臺北市":{"lat":25.04,"lon":121.51,"int":1}}},"臺南市":{"int":2,"town":{"佳里":{"lat":23.17,"lon":120.2,"int":2},"善化":{"lat":23.14,"lon":120.29,"int":1},"永康":{"lat":23.04,"lon":120.24,"int":1},"白河":{"lat":23.35,"lon":120.41,"int":1}}},"臺東縣":{"int":1,"town":{"利稻":{"lat":23.19,"lon":121.03,"int":1},"成功":{"lat":23.1,"lon":121.37,"int":1},"東河":{"lat":22.97,"lon":121.3,"int":1},"池上":{"lat":23.1,"lon":121.22,"int":1},"蘭嶼":{"lat":22.04,"lon":121.56,"int":1},"長濱":{"lat":23.32,"lon":121.45,"int":1}}},"花蓮縣":{"int":3,"town":{"光復":{"lat":23.67,"lon":121.43,"int":1},"和平":{"lat":24.31,"lon":121.75,"int":2},"太魯閣":{"lat":24.16,"lon":121.62,"int":2},"富里":{"lat":23.2,"lon":121.29,"int":1},"東富":{"lat":23.68,"lon":121.48,"int":2},"水璉":{"lat":23.79,"lon":121.56,"int":2},"石梯坪":{"lat":23.48,"lon":121.51,"int":1},"秀林":{"lat":24.08,"lon":121.6,"int":1},"花蓮市":{"lat":23.98,"lon":121.61,"int":2},"萬榮":{"lat":23.49,"lon":121.35,"int":1},"西寶":{"lat":24.21,"lon":121.48,"int":3},"西林":{"lat":23.81,"lon":121.44,"int":1},"銅門":{"lat":23.97,"lon":121.49,"int":2},"鹽寮":{"lat":23.9,"lon":121.6,"int":2}}},"苗栗縣":{"int":2,"town":{"三義":{"lat":24.41,"lon":120.77,"int":1},"南庄":{"lat":24.63,"lon":121.01,"int":1},"後龍":{"lat":24.65,"lon":120.83,"int":2},"泰安":{"lat":24.47,"lon":120.94,"int":1},"竹南":{"lat":24.68,"lon":120.87,"int":1},"苗栗市":{"lat":24.56,"lon":120.83,"int":2}}},"雲林縣":{"int":2,"town":{"古坑":{"lat":23.68,"lon":120.57,"int":1},"四湖":{"lat":23.64,"lon":120.23,"int":2},"土庫":{"lat":23.69,"lon":120.39,"int":2},"斗六市":{"lat":23.71,"lon":120.54,"int":1},"水林":{"lat":23.52,"lon":120.23,"int":1},"草嶺":{"lat":23.6,"lon":120.68,"int":1},"西螺":{"lat":23.79,"lon":120.49,"int":2},"麥寮":{"lat":23.8,"lon":120.22,"int":1}}}},"loc":"宜蘭縣政府東北東方 39.4 公里 (位於臺灣東部海域)","lon":122.11,"mag":5.6,"time":1793521207000,"trem":0} \ No newline at end of file diff --git a/test/features/earthquake/presentation/story_map_snapshot_test.dart b/test/features/earthquake/presentation/story_map_snapshot_test.dart new file mode 100644 index 000000000..0b328b6f9 --- /dev/null +++ b/test/features/earthquake/presentation/story_map_snapshot_test.dart @@ -0,0 +1,266 @@ +import 'dart:async'; + +import 'package:dpip/features/earthquake/domain/earthquake_report.dart'; +import 'package:dpip/features/earthquake/presentation/story_map_snapshot.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +const _channel = MethodChannel('com.exptech.dpip/map_snapshot'); +const _report = EarthquakeReport( + id: '115074-2026-1030-043743', + longitude: 121.82, + latitude: 24.18, + location: '', + depth: 24.7, + magnitude: 4.5, + time: 1793306263000, + trem: 0, + list: { + '宜蘭縣': AreaIntensity( + intensity: 3, + town: { + '同名測站': StationIntensity( + longitude: 121.75, + latitude: 24.43, + intensity: 3, + ), + }, + ), + '花蓮縣': AreaIntensity( + intensity: 1, + town: { + '同名測站': StationIntensity( + longitude: 121.56, + latitude: 23.79, + intensity: 1, + ), + '另一測站': StationIntensity( + longitude: 121.56, + latitude: 23.79, + intensity: 1, + ), + }, + ), + }, +); +const _yilanId = '["宜蘭縣","同名測站"]'; +const _hualienId = '["花蓮縣","同名測站"]'; +const _otherId = '["花蓮縣","另一測站"]'; + +Future _capture({ + double scale = 2, + double zoom = 7, + EarthquakeReport report = _report, +}) => StoryMapSnapshot.capture( + report: report, + style: '{}', + centerLatitude: 23.84, + centerLongitude: 121.51, + zoom: zoom, + pixelRatio: scale, +); + +Map _response(int scale, {double x = 225.6}) { + final header = ByteData(24) + ..setUint32(0, 0x89504E47) + ..setUint32(4, 0x0D0A1A0A) + ..setUint32(8, 13) + ..setUint32(12, 0x49484452) + ..setUint32(16, 360 * scale) + ..setUint32(20, 640 * scale); + return { + 'png': header.buffer.asUint8List(), + 'pngWidth': 360 * scale, + 'pngHeight': 640 * scale, + 'logicalWidth': 360.0, + 'logicalHeight': 640.0, + 'points': { + _otherId: [-10.3, 334.5], + _hualienId: [-10.3, 334.5], + 'epicenter': [x, 243.2], + _yilanId: [201.1, 52.9], + }, + }; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + tearDown(() => messenger.setMockMethodCallHandler(_channel, null)); + + for (final scale in [1, 2, 3]) { + test('preserves logical anchors and validates the $scale× PNG', () async { + messenger.setMockMethodCallHandler(_channel, (call) async { + expect(call.method, 'captureWithProjection'); + expect(call.arguments, { + 'style': '{}', + 'latitude': 23.84, + 'longitude': 121.51, + 'zoom': 7.0, + 'width': 360.0, + 'height': 640.0, + 'pixelRatio': scale.toDouble(), + 'showLogo': false, + 'points': [ + {'id': 'epicenter', 'latitude': 24.18, 'longitude': 121.82}, + {'id': _yilanId, 'latitude': 24.43, 'longitude': 121.75}, + {'id': _hualienId, 'latitude': 23.79, 'longitude': 121.56}, + {'id': _otherId, 'latitude': 23.79, 'longitude': 121.56}, + ], + }); + return _response(scale); + }); + final result = await _capture(scale: scale.toDouble()); + expect(result.epicenter, const Offset(225.6, 243.2)); + expect(result.markers.map((m) => m.sourceId), [ + _yilanId, + _hualienId, + _otherId, + ]); + expect(result.markers.map((m) => (m.latitude, m.longitude)), [ + (24.43, 121.75), + (23.79, 121.56), + (23.79, 121.56), + ]); + expect(result.markers.map((m) => m.position), [ + const Offset(201.1, 52.9), + const Offset(-10.3, 334.5), + const Offset(-10.3, 334.5), + ]); + expect(result.markers.map((m) => m.intensity), [3, 1, 1]); + }); + } + + test( + 'rejects missing, mismatched and non-finite projection metadata', + () async { + final valid = _response(2); + final points = valid['points']! as Map; + for (final response in [ + null, + {...valid}..remove('points'), + { + ...valid, + 'points': {...points}..remove(_yilanId), + }, + { + ...valid, + 'points': {...points}..[_yilanId] = [double.nan, 5], + }, + { + ...valid, + 'points': {...points}..[_yilanId] = ['3', 5], + }, + { + ...valid, + 'points': { + ...points, + 'unknown': [1, 2], + }..remove(_yilanId), + }, + {...valid, 'logicalWidth': 640.0}, + {...valid, 'pngWidth': 360}, + {...valid, 'png': _response(1)['png']}, + {...valid, 'png': Uint8List(24)}, + ]) { + messenger.setMockMethodCallHandler(_channel, (_) async => response); + await expectLater(_capture(), throwsFormatException); + } + }, + ); + + test('propagates native failures and missing methods', () async { + for (final code in ['bad_args', 'snapshot_failed', 'no_image']) { + messenger.setMockMethodCallHandler(_channel, (_) async { + throw PlatformException(code: code); + }); + await expectLater( + _capture(), + throwsA(isA().having((e) => e.code, 'code', code)), + ); + } + messenger.setMockMethodCallHandler(_channel, null); + await expectLater(_capture(), throwsA(isA())); + }); + + test( + 'projects every valid source and excludes invalid coordinates', + () async { + final report = _report.copyWith( + list: { + ..._report.list, + 'invalid': const AreaIntensity( + intensity: 9, + town: { + 'latitude': StationIntensity( + longitude: 121, + latitude: 91, + intensity: 9, + ), + 'longitude': StationIntensity( + longitude: double.infinity, + latitude: 24, + intensity: 9, + ), + }, + ), + }, + ); + var calls = 0; + messenger.setMockMethodCallHandler(_channel, (call) async { + calls++; + expect(call.arguments['points'], hasLength(4)); + return _response(2); + }); + final result = await _capture(report: report); + expect(result.markers.map((marker) => marker.sourceId), [ + _yilanId, + _hualienId, + _otherId, + ]); + await expectLater( + _capture(report: report.copyWith(longitude: 181)), + throwsFormatException, + ); + expect(calls, 1); + }, + ); + + test('supports an epicenter with no valid observations', () async { + messenger.setMockMethodCallHandler(_channel, (call) async { + expect(call.arguments['points'], hasLength(1)); + return { + ..._response(2), + 'points': { + 'epicenter': [180.0, 227.0], + }, + }; + }); + final result = await _capture(report: _report.copyWith(list: {})); + expect(result.markers, isEmpty); + expect(result.epicenter, const Offset(180, 227)); + }); + + test( + 'keeps concurrent responses paired when they finish out of order', + () async { + final older = Completer>(); + final newer = Completer>(); + messenger.setMockMethodCallHandler( + _channel, + (call) => call.arguments['zoom'] == 7.0 ? older.future : newer.future, + ); + final first = _capture(zoom: 7, scale: 1); + final second = _capture(zoom: 8, scale: 3); + newer.complete(_response(3, x: 190)); + final latest = await second; + older.complete(_response(1, x: 221)); + final previous = await first; + expect(latest.epicenter.dx, 190); + expect(ByteData.sublistView(latest.png).getUint32(16), 1080); + expect(previous.epicenter.dx, 221); + expect(ByteData.sublistView(previous.png).getUint32(16), 360); + }, + ); +} diff --git a/test/features/earthquake/presentation/story_observation_clustering_test.dart b/test/features/earthquake/presentation/story_observation_clustering_test.dart new file mode 100644 index 000000000..2995cba32 --- /dev/null +++ b/test/features/earthquake/presentation/story_observation_clustering_test.dart @@ -0,0 +1,480 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:math' as math; + +import 'package:dpip/core/models/lat_lng.dart' as geo; +import 'package:dpip/features/earthquake/domain/earthquake_report.dart'; +import 'package:dpip/features/earthquake/presentation/story_map_snapshot.dart'; +import 'package:dpip/features/earthquake/presentation/story_observation_clustering.dart'; +import 'package:dpip/shared/map/camera_fit.dart'; +import 'package:dpip/shared/seismic/intensity.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:maplibre_gl/maplibre_gl.dart' show LatLng; + +const _fixtureDir = + 'test/features/earthquake/presentation/fixtures/story_reports'; +const _channel = MethodChannel('com.exptech.dpip/map_snapshot'); +const _seeds = [0, 1, 7, 17, 42, 241, 115057, 115075]; +const _cases = [ + ('tnn1', '115057-2026-0825-150011', {1: 38, 2: 64, 3: 12, 4: 5}), + ('tyo1', '115057-2026-0825-150011', {1: 39, 2: 64, 3: 12, 4: 5}), + ('tyo1', '115074-2026-1030-043743', {1: 11, 2: 4, 3: 3}), + ('tyo1', '115067-2026-0930-130027', {1: 81, 2: 15}), + ('tyo1', '115075-2026-1101-162007', {1: 48, 2: 48, 3: 3}), + ('tyo1', '115000-2026-0909-192104', {1: 1}), + ( + 'tyo1', + '107022-2018-0206-235041', + {1: 11, 2: 33, 3: 27, 4: 5, 5: 3, 6: 1, 9: 4}, + ), + ('long', '115075-2026-1101-162007', {1: 48, 2: 48, 3: 3}), +]; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + tearDown(() => messenger.setMockMethodCallHandler(_channel, null)); + + for (final (node, id, histogram) in _cases) { + test( + '$node/$id accounts for every source under input permutations', + () async { + final sourceReport = _loadReport(node == 'long' ? 'tyo1' : node, id); + final report = node == 'long' + ? sourceReport.copyWith(location: '臺灣東部外海與菲律賓海板塊交界附近海域') + : sourceReport; + expect(report.id, id); + final sourceIds = { + for (final area in report.list.entries) + for (final station in area.value.town.entries) + jsonEncode([area.key, station.key]): station.value, + }; + expect(sourceIds, hasLength(histogram.values.reduce((a, b) => a + b))); + expect({ + for (final level in sourceIds.values.map((v) => v.intensity).toSet()) + level: sourceIds.values.where((v) => v.intensity == level).length, + }, histogram); + if (report.serial == '115057') { + expect( + sourceIds['["臺北市","臺北市"]']?.intensity, + node == 'tyo1' ? 1 : null, + ); + } + if (report.serial == '115067') { + expect(report.longitude, 122.88); + expect( + sourceIds.values.map((v) => v.latitude).reduce(math.min), + lessThan(22.1), + ); + expect( + sourceIds.values.map((v) => v.latitude).reduce(math.max), + greaterThan(25.1), + ); + } + if (report.serial == '115075') { + expect(sourceIds, contains('["臺東縣","蘭嶼"]')); + expect( + sourceIds.values.map((v) => v.latitude).reduce(math.max), + greaterThan(25.6), + ); + } + final legacy = id.startsWith('107022'); + expect(Intensity.usesLegacyScale(report.originTimeUtc), legacy); + final camera = _camera(report); + final projections = { + 'epicenter': _project(report.latitude, report.longitude, camera), + for (final station in sourceIds.entries) + station.key: _project( + station.value.latitude, + station.value.longitude, + camera, + ), + }; + + Future> capture( + EarthquakeReport input, + Iterable responseIds, + ) async { + messenger.setMockMethodCallHandler(_channel, (call) async { + expect(call.method, 'captureWithProjection'); + final points = List>.from( + call.arguments['points'] as List, + ); + expect( + points.map((p) => p['id']), + unorderedEquals(projections.keys), + ); + for (final point in points.where((p) => p['id'] != 'epicenter')) { + final source = sourceIds[point['id']]!; + expect(point['latitude'], source.latitude); + expect(point['longitude'], source.longitude); + } + return { + 'logicalWidth': 360.0, + 'logicalHeight': 640.0, + 'pngWidth': 720, + 'pngHeight': 1280, + 'png': _pngHeader(), + 'points': { + for (final key in responseIds) + key: [projections[key]!.dx, projections[key]!.dy], + }, + }; + }); + final snapshot = await StoryMapSnapshot.capture( + report: input, + style: '{}', + centerLatitude: camera.target.latitude, + centerLongitude: camera.target.longitude, + zoom: camera.zoom, + ); + return snapshot.markers; + } + + List verify( + List clusters, { + double? maxDiameterMetres, + }) { + final seen = {}; + for (final group in clusters) { + expect(group.anchor, same(group.members.first)); + expect(group.count, group.members.length); + expect( + group.maxIntensity, + group.members.map((m) => m.intensity).reduce(math.max), + ); + for (final member in group.members) { + expect( + seen.add(member.sourceId), + isTrue, + reason: member.sourceId, + ); + expect(sourceIds, contains(member.sourceId)); + final source = sourceIds[member.sourceId]!; + expect( + (member.latitude, member.longitude, member.intensity), + (source.latitude, source.longitude, source.intensity), + ); + expect(member.position, projections[member.sourceId]); + expect( + (member.position - group.anchor.position).distance, + lessThanOrEqualTo(40), + ); + } + if (maxDiameterMetres != null) { + for (final (index, a) in group.members.indexed) { + for (final b in group.members.skip(index + 1)) { + expect(_distance(a, b), lessThanOrEqualTo(maxDiameterMetres)); + } + } + } + } + expect(seen, unorderedEquals(sourceIds.keys)); + final maximum = clusters.map((c) => c.maxIntensity).reduce(math.max); + expect(maximum, report.maxIntensity); + if (legacy) { + for (final group in clusters.where((c) => c.maxIntensity >= 5)) { + final label = Intensity.displayForReport( + group.maxIntensity, + report.originTimeUtc, + ).label; + expect(label, {5: '5', 6: '6', 9: '7'}[group.maxIntensity]); + } + } + return [ + for (final group in clusters) + [ + group.anchor.sourceId, + group.anchor.latitude, + group.anchor.longitude, + group.anchor.position, + group.maxIntensity, + group.count, + group.members.map((m) => m.sourceId).toList(), + ], + ]; + } + + List verifyBoth(List markers) => [ + for (final limit in [null, storyD75MaxDiameterMetres]) + verify( + clusterStoryObservations(markers, maxDiameterMetres: limit), + maxDiameterMetres: limit, + ), + ]; + + final baseline = verifyBoth(await capture(report, projections.keys)); + for (final seed in _seeds) { + final random = math.Random(seed); + final shuffledReport = _reorder( + report, + (List items) => items.shuffle(random), + ); + final responseIds = projections.keys.toList()..shuffle(random); + final markers = await capture(shuffledReport, responseIds); + expect(verifyBoth(markers), baseline, reason: 'API seed $seed'); + expect( + verifyBoth(markers.toList()..shuffle(random)), + baseline, + reason: 'marker seed $seed', + ); + } + final reversed = _reorder( + report, + (List items) => items.setAll(0, items.reversed.toList()), + ); + expect( + verifyBoth( + await capture(reversed, projections.keys.toList().reversed), + ), + baseline, + reason: 'all API and projection keys reversed', + ); + }, + ); + } + + test( + '75 km is inclusive and a point one millimetre beyond is ineligible', + () { + const origin = geo.LatLng(0, 0); + final atLimit = origin.destinationPoint(45, storyD75MaxDiameterMetres); + final beyond = origin.destinationPoint( + 45, + storyD75MaxDiameterMetres + .001, + ); + final anchor = _marker( + 'anchor', + Offset.zero, + latitude: 0, + longitude: 0, + intensity: 4, + ); + StoryStationMarker member(geo.LatLng point) => _marker( + 'member', + const Offset(40, 0), + latitude: point.latitude, + longitude: point.longitude, + ); + expect(_distance(anchor, member(atLimit)), storyD75MaxDiameterMetres); + expect(_distance(anchor, member(beyond)), closeTo(75000.001, 1e-8)); + expect(_d75([anchor, member(atLimit)]).single.count, 2); + expect(_d75([anchor, member(beyond)]), hasLength(2)); + expect(clusterStoryObservations([anchor, member(beyond)]), hasLength(1)); + }, + ); + + test('members within range of the anchor can exceed the pairwise limit', () { + final anchor = _marker('anchor', const Offset(120, 80), intensity: 4); + final east = _marker('east', const Offset(135, 80), longitude: 121.5); + final west = _marker('west', const Offset(105, 80), longitude: 120.5); + expect(_distance(anchor, east), lessThan(storyD75MaxDiameterMetres)); + expect(_distance(anchor, west), lessThan(storyD75MaxDiameterMetres)); + expect(_distance(east, west), greaterThan(storyD75MaxDiameterMetres)); + expect(_d75([west, east, anchor]).map((c) => c.members), [ + [west], + [anchor, east], + ]); + }); + + test( + 'an ineligible nearest cluster yields to an eligible farther cluster', + () { + final east = _marker( + 'east', + const Offset(80, 80), + longitude: 121.8, + intensity: 4, + ); + final west = _marker('west', const Offset(130, 80), intensity: 3); + final middle = _marker('middle', const Offset(95, 80)); + expect(_d75([middle, west, east]).map((c) => c.members), [ + [west, middle], + [east], + ]); + }, + ); + + test( + 'distance wraps longitude and coincident IDs remain separate records', + () { + final east = _marker( + 'east', + const Offset(30, 80), + longitude: 179.8, + intensity: 4, + ); + final west = _marker('west', const Offset(45, 80), longitude: -179.8); + final duplicate = _marker( + 'west-2', + const Offset(45, 80), + longitude: -179.8, + ); + expect(_d75([duplicate, west, east]).single.members, [ + east, + west, + duplicate, + ]); + expect(_d75([west]).single.anchor, same(west)); + }, + ); + + test('equal eligible screen distances favor canonical anchor order', () { + final east = _marker( + 'east', + const Offset(20, 80), + longitude: 121.2, + intensity: 4, + ); + final west = _marker( + 'west', + const Offset(100, 80), + longitude: 120.8, + intensity: 4, + ); + final middle = _marker('middle', const Offset(60, 80)); + expect(_d75([middle, west, east]).map((c) => c.members), [ + [east, middle], + [west], + ]); + }); + + test( + 'coordinate ties use source ID and keep distinct coincident sources', + () { + final first = _marker('first', const Offset(10, 10), intensity: 5); + final last = _marker('last', const Offset(10, 10), intensity: 5); + final stronger = _marker('stronger', const Offset(55, 10), intensity: 6); + final y = _marker('north', const Offset(55, 55), latitude: 24); + final z = _marker('south', const Offset(55, 100)); + for (final markers in [ + [last, first, stronger, z, y], + [y, z, stronger, first, last], + ]) { + final clusters = clusterStoryObservations(markers); + expect(clusters.map((c) => c.anchor), [y, z, first, stronger]); + expect(clusters[2].members, [first, last]); + } + }, + ); + + test('equidistant observation at the inclusive 40 px radius joins the priority anchor', () { + final west = _marker('west', const Offset(20, 80), intensity: 5); + final east = _marker( + 'east', + const Offset(100, 80), + longitude: 122, + intensity: 5, + ); + final mid = _marker('mid', const Offset(60, 80)); + final outside = _marker('outside', const Offset(60, 81)); + final nonfinite = _marker('invalid', const Offset(double.nan, 0)); + for (final markers in [ + [outside, west, mid, east, nonfinite], + [east, mid, west, nonfinite, outside], + ]) { + final clusters = clusterStoryObservations(markers); + expect(clusters.map((c) => c.anchor), [outside, east, west]); + expect(clusters[1].members, [east, mid]); + expect(clusters[2].members, [west]); + } + expect(clusterStoryObservations([]), isEmpty); + }); +} + +List _d75(List markers) => + clusterStoryObservations( + markers, + maxDiameterMetres: storyD75MaxDiameterMetres, + ); + +double _distance(StoryStationMarker a, StoryStationMarker b) => geo.LatLng( + a.latitude, + a.longitude, +).distanceTo(geo.LatLng(b.latitude, b.longitude)); + +EarthquakeReport _loadReport(String node, String id) => + EarthquakeReport.fromJson( + jsonDecode(File('$_fixtureDir/$node-$id.json').readAsStringSync()) + as Map, + ); + +EarthquakeReport _reorder( + EarthquakeReport report, + void Function(List) reorder, +) { + List reordered(Iterable entries) { + final items = entries.toList(); + reorder(items); + return items; + } + + return report.copyWith( + list: { + for (final area in reordered(report.list.entries)) + area.key: area.value.copyWith( + town: Map.fromEntries(reordered(area.value.town.entries)), + ), + }, + ); +} + +({LatLng target, double zoom}) _camera(EarthquakeReport report) { + final bounds = boundsFromPoints([ + LatLng(report.latitude, report.longitude), + for (final area in report.list.values) + for (final station in area.town.values) + LatLng(station.latitude, station.longitude), + ])!; + return boundsFitCamera( + safeFitBounds(bounds)!, + viewport: StoryMapSnapshot.canvas, + topInset: 80, + bottomInset: 260, + padding: 12, + minZoom: 2, + maxZoom: 7, + )!; +} + +// A fixed Mercator reference for mock native responses. Production uses the +// points returned by the snapshot channel. +Offset _project(double lat, double lon, ({LatLng target, double zoom}) camera) { + double mercatorY(double latitude) { + final sine = math.sin(latitude * math.pi / 180); + return 0.5 - math.log((1 + sine) / (1 - sine)) / (4 * math.pi); + } + + final world = 512 * math.pow(2, camera.zoom); + return Offset( + 180 + (lon - camera.target.longitude) * world / 360, + 320 + (mercatorY(lat) - mercatorY(camera.target.latitude)) * world, + ); +} + +Uint8List _pngHeader() => + (ByteData(24) + ..setUint32(0, 0x89504E47) + ..setUint32(4, 0x0D0A1A0A) + ..setUint32(8, 13) + ..setUint32(12, 0x49484452) + ..setUint32(16, 720) + ..setUint32(20, 1280)) + .buffer + .asUint8List(); + +StoryStationMarker _marker( + String id, + Offset position, { + double longitude = 121, + double latitude = 23, + int intensity = 1, +}) => StoryStationMarker( + sourceId: id, + latitude: latitude, + longitude: longitude, + position: position, + intensity: intensity, +); From 1741d049e4e6168ea2b4a4728514d83436a1d44a Mon Sep 17 00:00:00 2001 From: YinCheng0106 Date: Fri, 20 Nov 2026 14:37:31 +0800 Subject: [PATCH 2/3] chore(gallery): distinguish photo permissions and guard image saves --- .../com/exptech/dpip/ImageSaverChannel.kt | 53 +++-- ios/Runner/ImageSaverPlugin.swift | 58 +++--- lib/core/error/failure.dart | 12 +- lib/core/platform/image_saver.dart | 182 ++++++++++-------- test/core/platform/image_saver_test.dart | 117 ++++++++++- 5 files changed, 283 insertions(+), 139 deletions(-) diff --git a/android/app/src/main/kotlin/com/exptech/dpip/ImageSaverChannel.kt b/android/app/src/main/kotlin/com/exptech/dpip/ImageSaverChannel.kt index c76803973..2a7c369d9 100644 --- a/android/app/src/main/kotlin/com/exptech/dpip/ImageSaverChannel.kt +++ b/android/app/src/main/kotlin/com/exptech/dpip/ImageSaverChannel.kt @@ -85,14 +85,13 @@ class ImageSaverChannel(private val context: Context) : try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { saveToMediaStore(bytes, fileName, mimeType) + result.success(null) } else { - saveToPicturesDirectory(bytes, fileName, mimeType) + saveToPicturesDirectory(bytes, fileName, mimeType, result) } - result.success(null) } catch (error: SecurityException) { - // The legacy grant, and only that: API 29+ needs no permission, so - // reaching this there means something else refused the write. - result.error("permission_denied", error.message, null) + val code = if (status() == "denied") "permission_denied" else "save_failed" + result.error(code, error.message, null) } catch (error: Exception) { result.error("save_failed", error.message, null) } @@ -118,23 +117,28 @@ class ImageSaverChannel(private val context: Context) : val stream = resolver.openOutputStream(uri) ?: throw IOException("MediaStore could not open the image for writing") stream.use { it.write(bytes) } + val published = resolver.update( + uri, + ContentValues().apply { put(MediaStore.Images.Media.IS_PENDING, 0) }, + null, + null, + ) + if (published != 1) throw IOException("MediaStore could not publish the image") } catch (error: Exception) { // A failed write must not leave a pending row behind: it would be // invisible to the gallery and never cleaned up by it. - resolver.delete(uri, null, null) + runCatching { resolver.delete(uri, null, null) } throw error } - - resolver.update( - uri, - ContentValues().apply { put(MediaStore.Images.Media.IS_PENDING, 0) }, - null, - null, - ) } /** API 26–28: the public Pictures directory, then tell the gallery about it. */ - private fun saveToPicturesDirectory(bytes: ByteArray, fileName: String, mimeType: String) { + private fun saveToPicturesDirectory( + bytes: ByteArray, + fileName: String, + mimeType: String, + result: MethodChannel.Result, + ) { if (context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ) { @@ -153,11 +157,22 @@ class ImageSaverChannel(private val context: Context) : } val file = uniqueFile(album, fileName) - file.writeBytes(bytes) - // Writes outside MediaStore are invisible until something tells the - // gallery to index them; without this the picture exists but no Photos - // app lists it. - MediaScannerConnection.scanFile(context, arrayOf(file.absolutePath), arrayOf(mimeType), null) + try { + file.writeBytes(bytes) + MediaScannerConnection.scanFile( + context, arrayOf(file.absolutePath), arrayOf(mimeType), + ) { _, uri -> + if (uri != null) { + result.success(null) + } else { + runCatching { file.delete() } + result.error("save_failed", "The gallery could not index the image", null) + } + } + } catch (error: Exception) { + runCatching { file.delete() } + throw error + } } /** [fileName] in [directory], or the first `name (n).ext` that is free. */ diff --git a/ios/Runner/ImageSaverPlugin.swift b/ios/Runner/ImageSaverPlugin.swift index 83d80db9a..f89db34c3 100644 --- a/ios/Runner/ImageSaverPlugin.swift +++ b/ios/Runner/ImageSaverPlugin.swift @@ -42,10 +42,14 @@ public class ImageSaverPlugin: NSObject, FlutterPlugin { switch status { case .authorized, .limited: return "granted" - case .denied, .restricted: + case .denied: return "denied" - default: + case .restricted: + return "restricted" + case .notDetermined: return "notDetermined" + @unknown default: + return "unsupported" } } @@ -62,38 +66,32 @@ public class ImageSaverPlugin: NSObject, FlutterPlugin { } let data = payload.data - PHPhotoLibrary.requestAuthorization(for: .addOnly) { status in - guard status == .authorized || status == .limited else { - // A refusal is not a failure to report as "try again": the only way - // forward is Settings, and the Dart side says exactly that. - DispatchQueue.main.async { + let status = PHPhotoLibrary.authorizationStatus(for: .addOnly) + guard status == .authorized || status == .limited else { + // Authorization may have changed after the Dart preflight. + let code = status == .restricted ? "permission_restricted" : "permission_denied" + result(FlutterError(code: code, message: "Photo library access was refused", details: nil)) + return + } + + PHPhotoLibrary.shared().performChanges({ + let request = PHAssetCreationRequest.forAsset() + let options = PHAssetResourceCreationOptions() + options.originalFilename = fileName + request.addResource(with: .photo, data: data, options: options) + }) { success, error in + // The completion handler runs off the main thread; Flutter's reply + // belongs to the platform thread. + DispatchQueue.main.async { + if success { + result(nil) + } else { result( FlutterError( - code: "permission_denied", message: "Photo library access was refused", + code: "save_failed", + message: error?.localizedDescription ?? "The image could not be saved", details: nil)) } - return - } - - PHPhotoLibrary.shared().performChanges({ - let request = PHAssetCreationRequest.forAsset() - let options = PHAssetResourceCreationOptions() - options.originalFilename = fileName - request.addResource(with: .photo, data: data, options: options) - }) { success, error in - // The completion handler runs off the main thread; Flutter's reply - // belongs to the platform thread. - DispatchQueue.main.async { - if success { - result(nil) - } else { - result( - FlutterError( - code: "save_failed", - message: error?.localizedDescription ?? "The image could not be saved", - details: nil)) - } - } } } } diff --git a/lib/core/error/failure.dart b/lib/core/error/failure.dart index a36b5222f..5f9b65cfb 100644 --- a/lib/core/error/failure.dart +++ b/lib/core/error/failure.dart @@ -50,8 +50,7 @@ final class UnexpectedFailure extends Failure { /// An image could not be handed to the platform's photo library. /// -/// Its own type because the recovery differs by reason: a refused permission -/// needs the user in Settings, while a failed write is a plain "try again". +/// Its own type because recovery depends on what prevented the save. final class ImageSaveFailure extends Failure { const ImageSaveFailure(this.reason, super.message); @@ -63,10 +62,15 @@ enum ImageSaveFailureReason { /// This build has no photo library to save into. unavailable, - /// The OS refused: photo-library access on iOS, or the legacy storage grant - /// on Android 9 and below. + /// The OS declined the grant and can still ask on another attempt. permissionDenied, + /// The OS will only grant access through the app's settings. + permissionSettingsRequired, + + /// System policy prevents the app from obtaining photo access. + permissionRestricted, + /// The write itself failed. failed, } diff --git a/lib/core/platform/image_saver.dart b/lib/core/platform/image_saver.dart index de24901e7..bb1405bb8 100644 --- a/lib/core/platform/image_saver.dart +++ b/lib/core/platform/image_saver.dart @@ -30,11 +30,27 @@ abstract interface class ImageSaver { /// Obtains the grant [saveToGallery] needs, prompting when the OS still can. /// /// Returned separately so a caller can check before fetching anything, and - /// so the UI can tell "the library refused" (Settings is the only way - /// forward) apart from a failed write. + /// so the UI can choose the appropriate recovery when the library refuses. Future> ensurePermission(); } +extension GuardedImageSave on ImageSaver { + /// Saves only while the caller still owns the image. A null result means + /// eligibility was lost before the write was dispatched. + Future?> saveToGalleryIfCurrent({ + required Uint8List bytes, + required String fileName, + required bool Function() isCurrent, + String mimeType = 'image/png', + }) async { + if (!isCurrent()) return null; + if (this case final _MethodChannelImageSaver saver) { + return saver._saveToGallery(bytes, fileName, mimeType, isCurrent); + } + return saveToGallery(bytes: bytes, fileName: fileName, mimeType: mimeType); + } +} + /// The one MethodChannel protocol both platforms speak. /// /// iOS's `ImageSaverPlugin` and Android's `ImageSaverChannel` implement the same @@ -48,6 +64,7 @@ base class _MethodChannelImageSaver implements ImageSaver { final MethodChannel _channel; final bool _isSupportedPlatform; + bool _writing = false; /// The permission this save needs, asked **before** anything is written. /// @@ -60,22 +77,33 @@ base class _MethodChannelImageSaver implements ImageSaver { Future> ensurePermission() async { if (!_isSupportedPlatform) return _unavailable(); - final status = await _channelString('status'); - switch (status) { - case 'granted': - return const Ok(null); - case 'denied': - // iOS never asks twice, so a refusal here is already final. - return _permissionDenied(); - case 'notDetermined': - return await _channelString('request') == 'granted' - ? const Ok(null) - : _permissionDenied(); - default: - // No answer — an engine that never registered the channel, or a future - // platform without a status method. `save` still reports unavailable. - return const Ok(null); + try { + final status = await _channel.invokeMethod('status'); + if (status == 'granted') return const Ok(null); + return await _checkPermission(status); + } on MissingPluginException { + return _unavailable(); + } catch (error, stackTrace) { + Log.handle(error, stackTrace, 'Checking gallery access failed'); + return Err(_failure(ImageSaveFailureReason.failed)); + } + } + + Future> _checkPermission(String? status) async { + if (status == 'notDetermined') { + status = await _channel.invokeMethod('request'); } + return switch (status) { + 'granted' => const Ok(null), + 'denied' => Err( + _failure(ImageSaveFailureReason.permissionSettingsRequired), + ), + 'restricted' => Err( + _failure(ImageSaveFailureReason.permissionRestricted), + ), + 'notDetermined' => Err(_failure(ImageSaveFailureReason.permissionDenied)), + _ => _unavailable(), + }; } @override @@ -83,39 +111,40 @@ base class _MethodChannelImageSaver implements ImageSaver { required Uint8List bytes, required String fileName, String mimeType = 'image/png', - }) async { + }) async => (await _saveToGallery(bytes, fileName, mimeType))!; + + Future?> _saveToGallery( + Uint8List bytes, + String fileName, + String mimeType, [ + bool Function()? isCurrent, + ]) async { if (!_isSupportedPlatform) return _unavailable(); + if (_writing) return Err(_failure(ImageSaveFailureReason.failed)); final permission = await ensurePermission(); + // Permission prompts can outlive the dialog. Check immediately before + // the irreversible native call, without an async gap after this guard. + if (isCurrent?.call() == false) return null; if (permission case Err(:final failure)) return Err(failure); + if (_writing) return Err(_failure(ImageSaveFailureReason.failed)); - return _invoke(bytes, fileName, mimeType); - } - - Future _channelString(String method) async { + _writing = true; try { - return await _channel.invokeMethod(method); - } on MissingPluginException { - return null; - } on PlatformException catch (error, stackTrace) { - Log.handle(error, stackTrace, 'image saver $method'); - return null; + return await _invoke(bytes, fileName, mimeType); + } finally { + _writing = false; } } - static Result _unavailable() => const Err( - ImageSaveFailure( - ImageSaveFailureReason.unavailable, - 'Saving images is unavailable on this platform.', - ), - ); + static Result _unavailable() => + Err(_failure(ImageSaveFailureReason.unavailable)); - static Result _permissionDenied() => const Err( - ImageSaveFailure( - ImageSaveFailureReason.permissionDenied, - 'The photo library refused the image.', - ), - ); + static ImageSaveFailure _failure(ImageSaveFailureReason reason) => + ImageSaveFailure(reason, 'Gallery save failed: ${reason.name}'); + + ImageSaveFailureReason get _nativeDenial => + ImageSaveFailureReason.permissionSettingsRequired; Future> _invoke( Uint8List bytes, @@ -130,43 +159,21 @@ base class _MethodChannelImageSaver implements ImageSaver { }); return const Ok(null); } on MissingPluginException { - return const Err( - ImageSaveFailure( - ImageSaveFailureReason.unavailable, - 'Saving images is unavailable on this platform.', - ), - ); + return _unavailable(); } on PlatformException catch (error) { - final failure = _saveFailure(error); - Log.warning('Saving an image failed: ${failure.reason.name}'); - return Err(failure); - } on Object { - Log.warning('Saving an image failed unexpectedly'); - return const Err( - ImageSaveFailure( - ImageSaveFailureReason.failed, - 'The image could not be saved.', - ), - ); + final reason = switch (error.code) { + 'permission_denied' => _nativeDenial, + 'permission_restricted' => ImageSaveFailureReason.permissionRestricted, + 'unsupported' => ImageSaveFailureReason.unavailable, + _ => ImageSaveFailureReason.failed, + }; + Log.warning('Saving an image failed: ${reason.name} (${error.code})'); + return Err(_failure(reason)); + } catch (error, stackTrace) { + Log.handle(error, stackTrace, 'Saving an image failed unexpectedly'); + return Err(_failure(ImageSaveFailureReason.failed)); } } - - static ImageSaveFailure _saveFailure(PlatformException error) { - return switch (error.code) { - 'permission_denied' => const ImageSaveFailure( - ImageSaveFailureReason.permissionDenied, - 'The photo library refused the image.', - ), - 'unsupported' => const ImageSaveFailure( - ImageSaveFailureReason.unavailable, - 'Saving images is unavailable on this platform.', - ), - _ => const ImageSaveFailure( - ImageSaveFailureReason.failed, - 'The image could not be saved.', - ), - }; - } } /// Android implementation — MediaStore, with the legacy public-directory write @@ -195,21 +202,28 @@ final class AndroidImageSaver extends _MethodChannelImageSaver { /// `permission_handler` reports it permanently denied because the manifest /// caps the declaration at API 28. @override - Future> ensurePermission() async { - if (!_isSupportedPlatform) return super.ensurePermission(); - - if (await _channelString('status') == 'granted') return const Ok(null); + Future> _checkPermission(String? nativeStatus) async { + // Only the API 26–28 path returns denied. An absent or unknown reply + // cannot establish that the platform needs a storage permission. + if (nativeStatus != 'denied') { + return _MethodChannelImageSaver._unavailable(); + } var status = await _storageStatus(); + if (status.isDenied) status = await _requestStorage(); if (status.isGranted || status.isLimited) return const Ok(null); - if (status.isPermanentlyDenied) { - return _MethodChannelImageSaver._permissionDenied(); - } - status = await _requestStorage(); - if (status.isGranted || status.isLimited) return const Ok(null); - return _MethodChannelImageSaver._permissionDenied(); + final reason = status.isPermanentlyDenied + ? ImageSaveFailureReason.permissionSettingsRequired + : status.isRestricted + ? ImageSaveFailureReason.permissionRestricted + : ImageSaveFailureReason.permissionDenied; + return Err(_MethodChannelImageSaver._failure(reason)); } + + @override + ImageSaveFailureReason get _nativeDenial => + ImageSaveFailureReason.permissionDenied; } /// iOS implementation — `PHPhotoLibrary` add-only access. diff --git a/test/core/platform/image_saver_test.dart b/test/core/platform/image_saver_test.dart index 32897f818..b669f5255 100644 --- a/test/core/platform/image_saver_test.dart +++ b/test/core/platform/image_saver_test.dart @@ -6,6 +6,8 @@ /// gate, what crosses the channel, and how each error code is classified. library; +import 'dart:async'; + import 'package:dpip/core/error/failure.dart'; import 'package:dpip/core/error/result.dart'; import 'package:dpip/core/platform/image_saver.dart'; @@ -80,11 +82,64 @@ void main() { expect( failureOf(result)!.reason, - ImageSaveFailureReason.permissionDenied, + ImageSaveFailureReason.permissionSettingsRequired, ); expect(saved, isFalse, reason: 'a refused save must not write'); }); + test( + 'a declined first request requires Settings without writing', + () async { + final methods = []; + messenger.setMockMethodCallHandler(channel, (call) async { + methods.add(call.method); + return call.method == 'status' ? 'notDetermined' : 'denied'; + }); + final result = await IosImageSaver(isSupportedPlatform: true) + .saveToGallery(bytes: bytes, fileName: 'report.png'); + + expect( + failureOf(result)!.reason, + ImageSaveFailureReason.permissionSettingsRequired, + ); + expect(methods, ['status', 'request']); + }, + ); + + test( + 'system restrictions cannot be recovered from the app settings', + () async { + messenger.setMockMethodCallHandler(channel, (call) async { + expect(call.method, 'status'); + return 'restricted'; + }); + final result = await IosImageSaver(isSupportedPlatform: true) + .saveToGallery(bytes: bytes, fileName: 'report.png'); + + expect( + failureOf(result)!.reason, + ImageSaveFailureReason.permissionRestricted, + ); + }, + ); + + test( + 'revoking permission before the native write requires Settings', + () async { + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == 'status') return 'granted'; + throw PlatformException(code: 'permission_denied'); + }); + final result = await IosImageSaver(isSupportedPlatform: true) + .saveToGallery(bytes: bytes, fileName: 'report.png'); + + expect( + failureOf(result)!.reason, + ImageSaveFailureReason.permissionSettingsRequired, + ); + }, + ); + test('asks once when the library has never been asked', () async { final methods = []; messenger.setMockMethodCallHandler(channel, (call) async { @@ -175,7 +230,7 @@ void main() { expect(saved, isFalse); expect( failureOf(result)!.reason, - ImageSaveFailureReason.permissionDenied, + ImageSaveFailureReason.permissionSettingsRequired, ); }); @@ -201,6 +256,64 @@ void main() { }); }); + test( + 'another caller cannot start a concurrent native write on the same saver', + () async { + final started = Completer(); + final finished = Completer(); + var writes = 0; + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == 'status') return 'granted'; + expect(call.method, 'save'); + if (++writes == 1) { + started.complete(); + await finished.future; + } + return null; + }); + final saver = IosImageSaver(isSupportedPlatform: true); + final first = saver.saveToGallery(bytes: bytes, fileName: 'story.png'); + await started.future; + final second = await saver.saveToGallery( + bytes: bytes, + fileName: 'story.png', + ); + expect(second.isOk, isFalse); + expect(writes, 1); + + finished.complete(); + expect((await first).isOk, isTrue); + expect( + (await saver.saveToGallery(bytes: bytes, fileName: 'story.png')).isOk, + isTrue, + ); + expect(writes, 2); + }, + ); + + test('an absent Android channel never asks for storage permission', () async { + final saver = AndroidImageSaver( + isSupportedPlatform: true, + storageStatus: () async => fail('Unexpected storage status check'), + requestStorage: () async => fail('Unexpected storage request'), + ); + final result = await saver.saveToGallery( + bytes: bytes, + fileName: 'report.png', + ); + expect(failureOf(result)!.reason, ImageSaveFailureReason.unavailable); + }); + + test('a failed permission check cannot dispatch a native write', () async { + messenger.setMockMethodCallHandler(channel, (call) async { + expect(call.method, 'status'); + throw PlatformException(code: 'temporary_error'); + }); + final result = await IosImageSaver(isSupportedPlatform: true) + .saveToGallery(bytes: bytes, fileName: 'report.png'); + expect(failureOf(result)!.reason, ImageSaveFailureReason.failed); + }); + test( 'a write failure is reported as failed, not as a permission problem', () async { From d73521914090a5dd90880b0798e85962c3ea2e7b Mon Sep 17 00:00:00 2001 From: YinCheng0106 Date: Fri, 20 Nov 2026 14:37:40 +0800 Subject: [PATCH 3/3] feat(earthquake): add 4:5 and 9:16 report sharing cards MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Platform: all New(zh-Hant): 地震報告可預覽並儲存 4:5 資訊卡與 9:16 限時動態圖片 New(en-US): Preview and save 4:5 information cards and 9:16 Story images from earthquake reports --- .../pages/report_detail_page.dart | 214 ++- .../widgets/earthquake_share_card.dart | 352 +++++ .../widgets/earthquake_share_dialog.dart | 680 +++++++++ .../widgets/earthquake_share_icon.dart | 32 + .../widgets/earthquake_share_story_card.dart | 1013 +++++++++++++ .../widgets/report_image_save_feedback.dart | 20 + lib/l10n/app_en.arb | 105 ++ lib/l10n/app_fil.arb | 22 +- lib/l10n/app_id.arb | 22 +- lib/l10n/app_ja.arb | 22 +- lib/l10n/app_ko.arb | 22 +- lib/l10n/app_th.arb | 22 +- lib/l10n/app_vi.arb | 22 +- lib/l10n/app_yue.arb | 22 +- lib/l10n/app_zh.arb | 22 +- lib/l10n/app_zh_Hans.arb | 22 +- lib/l10n/app_zh_Hant_HK.arb | 22 +- lib/l10n/app_zh_TW.arb | 22 +- lib/l10n/gen/app_localizations.dart | 124 ++ lib/l10n/gen/app_localizations_en.dart | 88 ++ lib/l10n/gen/app_localizations_fil.dart | 82 ++ lib/l10n/gen/app_localizations_id.dart | 82 ++ lib/l10n/gen/app_localizations_ja.dart | 77 + lib/l10n/gen/app_localizations_ko.dart | 77 + lib/l10n/gen/app_localizations_th.dart | 81 + lib/l10n/gen/app_localizations_vi.dart | 82 ++ lib/l10n/gen/app_localizations_yue.dart | 75 + lib/l10n/gen/app_localizations_zh.dart | 300 ++++ lib/shared/widgets/intensity_badge.dart | 45 +- .../presentation/fixtures/story_map_blue.png | Bin 0 -> 4542 bytes .../presentation/fixtures/story_map_green.png | Bin 0 -> 4542 bytes .../pages/report_detail_page_test.dart | 1300 ++++++++++++++++- .../presentation/story_camera_fit_test.dart | 198 +++ .../story_marker_layout_test.dart | 528 +++++++ 34 files changed, 5699 insertions(+), 98 deletions(-) create mode 100644 lib/features/earthquake/presentation/widgets/earthquake_share_card.dart create mode 100644 lib/features/earthquake/presentation/widgets/earthquake_share_dialog.dart create mode 100644 lib/features/earthquake/presentation/widgets/earthquake_share_icon.dart create mode 100644 lib/features/earthquake/presentation/widgets/earthquake_share_story_card.dart create mode 100644 lib/features/earthquake/presentation/widgets/report_image_save_feedback.dart create mode 100644 test/features/earthquake/presentation/fixtures/story_map_blue.png create mode 100644 test/features/earthquake/presentation/fixtures/story_map_green.png create mode 100644 test/features/earthquake/presentation/story_camera_fit_test.dart create mode 100644 test/features/earthquake/presentation/story_marker_layout_test.dart diff --git a/lib/features/earthquake/presentation/pages/report_detail_page.dart b/lib/features/earthquake/presentation/pages/report_detail_page.dart index 731bee9d2..999304d36 100644 --- a/lib/features/earthquake/presentation/pages/report_detail_page.dart +++ b/lib/features/earthquake/presentation/pages/report_detail_page.dart @@ -10,6 +10,7 @@ import 'package:dpip/app/theme/app_motion.dart'; import 'package:dpip/app/theme/app_radius.dart'; import 'package:dpip/app/theme/app_spacing.dart'; import 'package:dpip/core/error/failure.dart'; +import 'package:dpip/core/error/result.dart'; import 'package:dpip/core/geo/town.dart'; import 'package:dpip/core/geo/town_directory.dart'; import 'package:dpip/core/logging/log.dart'; @@ -25,6 +26,8 @@ import 'package:dpip/core/settings/settings_store.dart'; import 'package:dpip/features/earthquake/domain/earthquake_report.dart'; import 'package:dpip/shared/seismic/intensity.dart'; import 'package:dpip/features/earthquake/domain/report_repository.dart'; +import 'package:dpip/features/earthquake/presentation/widgets/earthquake_share_dialog.dart'; +import 'package:dpip/features/earthquake/presentation/widgets/report_image_save_feedback.dart'; import 'package:dpip/shared/seismic/intensity_icon_renderer.dart'; import 'package:dpip/l10n/gen/app_localizations.dart'; import 'package:dpip/shared/map/base_map.dart'; @@ -652,6 +655,14 @@ class _ReportSheetState extends State<_ReportSheet> { ); } + void _expand() { + _dragController.animateTo( + _ReportSheet._expanded, + duration: AppMotion.medium, + curve: Curves.easeOutCubic, + ); + } + @override Widget build(BuildContext context) { final colors = Theme.of(context).colorScheme; @@ -738,17 +749,29 @@ class _ReportSheetState extends State<_ReportSheet> { children: [ Opacity( opacity: revealProgress, - child: IgnorePointer( - ignoring: !expanded, - child: expandedContent, + child: ExcludeSemantics( + excluding: !expanded, + child: IgnorePointer( + ignoring: !expanded, + child: expandedContent, + ), ), ), if (peekOpacity > 0) Opacity( opacity: peekOpacity, - child: IgnorePointer( - ignoring: expanded, - child: peekContent, + child: ExcludeSemantics( + excluding: expanded, + child: IgnorePointer( + ignoring: expanded, + child: Semantics( + container: true, + explicitChildNodes: true, + expanded: false, + onExpand: _expand, + child: peekContent, + ), + ), ), ), ], @@ -773,12 +796,29 @@ class _ReportSheetState extends State<_ReportSheet> { Widget _expandedContent(BuildContext context, EarthquakeReport report) { final l10n = AppLocalizations.of(context); + return Padding( padding: const EdgeInsets.symmetric(horizontal: AppSpacing.lg), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ _ReportHeader(report: report), + const SizedBox(height: AppSpacing.lg), + + OutlinedButton.icon( + onPressed: () => showDialog( + context: context, + builder: (_) => EarthquakeShareDialog( + report: report, + saver: widget.saver, + isReportCurrent: () => + mounted && identical(widget.report, report), + ), + ), + icon: const Icon(Icons.visibility_outlined), + label: Text(l10n.reportDetailSharePreview), + ), + const SizedBox(height: AppSpacing.lg), SectionHeader(l10n.reportDetailInfo), _ReportInfoCard(report: report), @@ -829,7 +869,11 @@ class _ExpandedHeader extends StatelessWidget { ), child: Row( children: [ - IconButton(icon: const Icon(Icons.arrow_back), onPressed: onBack), + IconButton( + icon: const Icon(Icons.arrow_back), + tooltip: MaterialLocalizations.of(context).backButtonTooltip, + onPressed: onBack, + ), Expanded( child: Text( l10n.reportDetailTitle, @@ -904,10 +948,15 @@ class _ReportPeekSummary extends StatelessWidget { ), ), const SizedBox(width: AppSpacing.md), - IntensityBadge( - label: presentation.label, - color: IntensityColors.discrete(presentation.colorLevel), - size: 56, + Semantics( + label: l10n.reportDetailMaximumIntensity(presentation.label), + excludeSemantics: true, + child: IntensityBadge( + label: presentation.label, + color: IntensityColors.discrete(presentation.colorLevel), + size: 56, + expandForText: true, + ), ), ], ), @@ -991,10 +1040,15 @@ class _ReportHeader extends StatelessWidget { Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ - IntensityBadge( - label: presentation.label, - color: IntensityColors.discrete(presentation.colorLevel), - size: 56, + Semantics( + label: l10n.reportDetailMaximumIntensity(presentation.label), + excludeSemantics: true, + child: IntensityBadge( + label: presentation.label, + color: IntensityColors.discrete(presentation.colorLevel), + size: 56, + expandForText: true, + ), ), const SizedBox(width: AppSpacing.lg), Expanded( @@ -1129,7 +1183,10 @@ class _InfoRow extends StatelessWidget { horizontal: AppSpacing.lg, vertical: AppSpacing.md, ), - child: Row( + child: OverflowBar( + alignment: MainAxisAlignment.spaceBetween, + spacing: AppSpacing.sm, + overflowSpacing: AppSpacing.xs, children: [ Text( label, @@ -1137,17 +1194,23 @@ class _InfoRow extends StatelessWidget { color: colors.onSurfaceVariant, ), ), - const Spacer(), - if (dotColor != null) ...[ - LegendDot(color: dotColor!), - const SizedBox(width: AppSpacing.sm), - ], - Text( - value, - style: theme.textTheme.bodyLarge?.copyWith( - fontWeight: FontWeight.w600, - fontFeatures: const [FontFeature.tabularFigures()], - ), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (dotColor != null) ...[ + LegendDot(color: dotColor!), + const SizedBox(width: AppSpacing.sm), + ], + Flexible( + child: Text( + value, + style: theme.textTheme.bodyLarge?.copyWith( + fontWeight: FontWeight.w600, + fontFeatures: const [FontFeature.tabularFigures()], + ), + ), + ), + ], ), ], ), @@ -1330,12 +1393,15 @@ class _LocalIntensityRow extends StatelessWidget { label: result.presentation.label, color: IntensityColors.discrete(result.presentation.colorLevel), size: 36, + expandForText: true, ) else - Text( - l10n.reportDetailLocalIntensityUnavailable, - style: theme.textTheme.bodyMedium?.copyWith( - color: colors.onSurfaceVariant, + Flexible( + child: Text( + l10n.reportDetailLocalIntensityUnavailable, + style: theme.textTheme.bodyMedium?.copyWith( + color: colors.onSurfaceVariant, + ), ), ), ], @@ -1457,7 +1523,12 @@ class _IntensityGroupRow extends StatelessWidget { children: [ Padding( padding: const EdgeInsets.all(AppSpacing.md), - child: IntensityBadge(label: label, color: color, size: 40), + child: IntensityBadge( + label: label, + color: color, + size: 40, + expandForText: true, + ), ), Expanded( child: Column( @@ -1652,15 +1723,16 @@ class _TownChip extends StatelessWidget { child: Row( mainAxisSize: MainAxisSize.min, children: [ - SizedBox( - width: 20, - height: 20, + ConstrainedBox( + constraints: const BoxConstraints(minWidth: 20, minHeight: 20), child: DecoratedBox( decoration: BoxDecoration( color: color, borderRadius: AppRadius.small, ), - child: Center( + child: Align( + widthFactor: 1, + heightFactor: 1, child: Text( label, style: theme.textTheme.labelSmall?.copyWith( @@ -1677,7 +1749,7 @@ class _TownChip extends StatelessWidget { ), ), const SizedBox(width: AppSpacing.xs), - Text(townName, style: theme.textTheme.labelLarge), + Flexible(child: Text(townName, style: theme.textTheme.labelLarge)), ], ), ); @@ -1727,41 +1799,57 @@ class _ReportImageCardState extends State<_ReportImageCard> { Future _save(Uint8List bytes) async { if (_saving) return; + ScaffoldMessenger.of(context).removeCurrentSnackBar(); setState(() => _saving = true); - final result = await widget.saver.saveToGallery( - bytes: bytes, - fileName: _fileName, - ); + ImageSaveFailureReason? reason; + try { + final result = await widget.saver.saveToGallery( + bytes: bytes, + fileName: _fileName, + ); + if (result case Err(:final failure)) { + reason = imageSaveFailureReason(failure); + } + } catch (error, stackTrace) { + Log.handle(error, stackTrace, 'Saving the official report image failed'); + reason = ImageSaveFailureReason.failed; + } if (!mounted) return; setState(() => _saving = false); final l10n = AppLocalizations.of(context); - final refused = - result.failureOrNull is ImageSaveFailure && - (result.failureOrNull! as ImageSaveFailure).reason == - ImageSaveFailureReason.permissionDenied; - final message = result.when( - ok: (_) => l10n.reportDetailImageSaved, - // A refusal is not "try again": the only way forward is Settings, so the - // two failures must not share a sentence — nor the same snackbar. - err: (_) => refused - ? l10n.reportDetailImageSavePermissionDenied - : l10n.reportDetailImageSaveFailed, + _showSaveMessage( + reason?.message(l10n) ?? l10n.reportDetailImageSaved, + action: switch (reason) { + ImageSaveFailureReason.permissionSettingsRequired => SnackBarAction( + label: l10n.permissionOpenSettings, + onPressed: _openSettings, + ), + ImageSaveFailureReason.permissionDenied || + ImageSaveFailureReason.failed => SnackBarAction( + label: l10n.commonRetry, + onPressed: () => _save(bytes), + ), + _ => null, + }, ); + } + + Future _openSettings() async { + if (!mounted) return; + final opened = await openAppSettingsPage(); + if (!opened && mounted) { + _showSaveMessage( + AppLocalizations.of(context).reportDetailImageSaveSettingsFailed, + ); + } + } + + void _showSaveMessage(String message, {SnackBarAction? action}) { ScaffoldMessenger.of(context) ..hideCurrentSnackBar() - ..showSnackBar( - SnackBar( - content: Text(message), - action: refused - ? SnackBarAction( - label: l10n.permissionOpenSettings, - onPressed: openAppSettingsPage, - ) - : null, - ), - ); + ..showSnackBar(SnackBar(content: Text(message), action: action)); } @override diff --git a/lib/features/earthquake/presentation/widgets/earthquake_share_card.dart b/lib/features/earthquake/presentation/widgets/earthquake_share_card.dart new file mode 100644 index 000000000..81d5e50f5 --- /dev/null +++ b/lib/features/earthquake/presentation/widgets/earthquake_share_card.dart @@ -0,0 +1,352 @@ +import 'dart:typed_data'; + +import 'package:dpip/core/network/api_client.dart'; +import 'package:provider/provider.dart'; +import 'package:dpip/features/earthquake/domain/earthquake_report.dart'; +import 'package:dpip/features/earthquake/presentation/widgets/earthquake_share_icon.dart'; +import 'package:dpip/l10n/gen/app_localizations.dart'; +import 'package:flutter/material.dart'; +import 'package:dpip/app/theme/app_spacing.dart'; +import 'package:dpip/core/realtime/app_time.dart'; +import 'package:intl/intl.dart'; +import 'package:dpip/app/theme/app_radius.dart'; +import 'package:dpip/shared/seismic/intensity.dart'; +import 'package:dpip/shared/seismic/intensity_colors.dart'; +import 'package:dpip/shared/widgets/intensity_badge.dart'; + +enum ShareCardFormat { post, story } + +/// The fixed 4:5 report artwork, with an optional official-image layout. +class EarthquakeShareCard extends StatelessWidget { + const EarthquakeShareCard({ + super.key, + required this.report, + this.format = ShareCardFormat.post, + }); + + static const canvas = Size(360, 450); + static const brandImage = EarthquakeShareIcon.image; + + final EarthquakeReport report; + final ShareCardFormat format; + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context); + final colors = Theme.of(context).colorScheme; + final creditStyle = Theme.of(context).textTheme.bodySmall; + final originTime = DateFormat('yyyy/MM/dd HH:mm:ss') + .format(AppTime.taipei(report.originTimeUtc)); + final intensity = Intensity.displayForReport( + report.maxIntensity, + report.originTimeUtc, + ); + + final content = [ + Row( + children: [ + EarthquakeShareIcon( + size: 44, + // The dialog checks the same provider before enabling export. + errorBuilder: (_, _, _) => const SizedBox.square(dimension: 44), + ), + const SizedBox(width: AppSpacing.md), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'DPIP', + style: Theme.of(context).textTheme.titleMedium + ?.copyWith(fontWeight: FontWeight.bold), + ), + Text( + l10n.moreTagline, + style: Theme.of(context).textTheme.bodySmall + ?.copyWith(color: colors.onSurfaceVariant), + ), + ], + ), + ), + const SizedBox(width: AppSpacing.sm), + Container( + constraints: const BoxConstraints(maxWidth: 120), + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.md, + vertical: AppSpacing.sm, + ), + decoration: BoxDecoration( + color: colors.primaryContainer, + borderRadius: BorderRadius.circular(8), + ), + child: Text( + l10n.reportDetailTitle, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.labelMedium?.copyWith( + color: colors.onPrimaryContainer, + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ), + const SizedBox(height: AppSpacing.lg), + const Divider(height: 1), + const SizedBox(height: AppSpacing.lg), + + Text( + l10n.reportDetailOriginTime, + style: Theme.of(context).textTheme.labelMedium + ?.copyWith(color: colors.onSurfaceVariant), + ), + const SizedBox(height: AppSpacing.xs), + Text( + originTime, + style: Theme.of(context).textTheme.bodyLarge + ?.copyWith(fontWeight: FontWeight.w500), + ), + const SizedBox(height: AppSpacing.lg), + Text( + report.shortLocation, + style: Theme.of(context).textTheme.headlineSmall + ?.copyWith(fontWeight: FontWeight.bold), + ), + if (report.location.trim() != report.shortLocation) ...[ + const SizedBox(height: AppSpacing.xs), + Text( + report.location, + style: Theme.of(context).textTheme.bodySmall + ?.copyWith(color: colors.onSurfaceVariant), + ), + ], + const SizedBox(height: AppSpacing.xl), + + IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + child: _ShareMetric( + label: l10n.reportDetailMagnitude, + value: report.magnitude.toStringAsFixed(1), + caption: l10n.reportDetailShareRichterScale, + ), + ), + const SizedBox(width: AppSpacing.sm), + Expanded( + child: _ShareMetric( + label: l10n.reportDetailMaximumIntensityLabel, + value: '', + caption: l10n.reportDetailShareObservedIntensity, + badge: IntensityBadge( + label: intensity.label, + color: IntensityColors.discrete(intensity.colorLevel), + size: 36, + ), + ), + ), + const SizedBox(width: AppSpacing.sm), + Expanded( + child: _ShareMetric( + label: l10n.reportDetailDepth, + value: report.depth.toStringAsFixed(1), + caption: l10n.reportDetailShareKilometers, + ), + ), + ], + ), + ), + const SizedBox(height: AppSpacing.lg), + ]; + + // The preview shows the typography of the fixed-size artwork. The share + // dialog offers the same report as responsive text at the system size. + return MediaQuery.withNoTextScaling( + child: AspectRatio( + aspectRatio: format == ShareCardFormat.post ? 4 / 5 : 9 / 16, + child: ColoredBox( + color: colors.surface, + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Allow the optional official image to take the space + // left below the artwork's text. + if (format == ShareCardFormat.story) ...[ + ...content, + Expanded( + child: Padding( + padding: const EdgeInsets.symmetric( + vertical: AppSpacing.md, + ), + child: ClipRRect( + borderRadius: AppRadius.medium, + child: ColoredBox( + color: colors.surfaceContainer, + child: _ReportImagePreview( + url: report.reportImageUrl.toString(), + ), + ), + ), + ), + ), + ] else + Expanded( + child: LayoutBuilder( + builder: (context, viewport) => FittedBox( + alignment: AlignmentDirectional.topStart, + // Some translations wrap the metric labels and the + // location. Fit the complete content when it uses up the + // space above the credits. + fit: BoxFit.scaleDown, + child: SizedBox( + width: viewport.maxWidth, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: content, + ), + ), + ), + ), + ), + + // Data source must always be visible. + Text(l10n.reportDetailShareSource, style: creditStyle), + Text(l10n.reportDetailSharePreparedBy, style: creditStyle), + ], + ), + ), + ), + ), + ); + } +} + +class _ShareMetric extends StatelessWidget { + const _ShareMetric({ + required this.label, + required this.value, + required this.caption, + this.badge, + }); + + final String label; + final String value; + final String caption; + final Widget? badge; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colors = theme.colorScheme; + + return Container( + padding: const EdgeInsets.all(AppSpacing.md), + decoration: BoxDecoration( + color: colors.surfaceContainer, + borderRadius: AppRadius.medium, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: theme.textTheme.labelSmall?.copyWith( + color: colors.onSurfaceVariant, + ), + ), + const SizedBox(height: AppSpacing.sm), + SizedBox( + height: 40, + child: Align( + alignment: Alignment.centerLeft, + child: + badge ?? + FittedBox( + fit: BoxFit.scaleDown, + alignment: Alignment.centerLeft, + child: Text( + value, + maxLines: 1, + style: theme.textTheme.headlineSmall?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ), + const SizedBox(height: AppSpacing.xs), + Text( + caption, + style: theme.textTheme.labelSmall?.copyWith( + color: colors.onSurfaceVariant, + ), + ), + ], + ), + ); + } +} + +class _ReportImagePreview extends StatefulWidget { + const _ReportImagePreview({required this.url}); + + final String url; + + @override + State<_ReportImagePreview> createState() => _ReportImagePreviewState(); +} + +class _ReportImagePreviewState extends State<_ReportImagePreview> { + late Future _imageFuture; + + @override + void initState() { + super.initState(); + _loadImage(); + } + + void _loadImage() { + _imageFuture = context + .read() + .getBytesAbsolute(widget.url) + .then((response) => response.bytes); + } + + @override + void didUpdateWidget(covariant _ReportImagePreview oldWidget) { + super.didUpdateWidget(oldWidget); + + if (oldWidget.url != widget.url) { + _loadImage(); + } + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context); + return FutureBuilder( + future: _imageFuture, + builder: (context, snapshot) { + if (snapshot.hasError) { + return Center(child: Text(l10n.reportDetailImageUnavailable)); + } + + if (!snapshot.hasData) { + return const Center(child: CircularProgressIndicator()); + } + + return Center( + child: Image.memory( + snapshot.data!, + fit: BoxFit.contain, + gaplessPlayback: true, + errorBuilder: (_, _, _) => Text(l10n.reportDetailShareImageInvalid), + ), + ); + }, + ); + } +} diff --git a/lib/features/earthquake/presentation/widgets/earthquake_share_dialog.dart b/lib/features/earthquake/presentation/widgets/earthquake_share_dialog.dart new file mode 100644 index 000000000..0c16e3850 --- /dev/null +++ b/lib/features/earthquake/presentation/widgets/earthquake_share_dialog.dart @@ -0,0 +1,680 @@ +import 'dart:async'; +import 'dart:math' as math; +import 'dart:ui' as ui; + +import 'package:dpip/app/theme/app_spacing.dart'; +import 'package:dpip/core/error/failure.dart'; +import 'package:dpip/core/error/result.dart'; +import 'package:dpip/core/logging/log.dart'; +import 'package:dpip/core/permissions/system_settings.dart'; +import 'package:dpip/core/platform/image_saver.dart'; +import 'package:dpip/core/realtime/app_time.dart'; +import 'package:dpip/features/earthquake/domain/earthquake_report.dart'; +import 'package:dpip/features/earthquake/presentation/story_camera_fit.dart'; +import 'package:dpip/features/earthquake/presentation/story_map_snapshot.dart'; +import 'package:dpip/features/earthquake/presentation/widgets/earthquake_share_card.dart'; +import 'package:dpip/features/earthquake/presentation/widgets/earthquake_share_story_card.dart'; +import 'package:dpip/features/earthquake/presentation/widgets/report_image_save_feedback.dart'; +import 'package:dpip/l10n/gen/app_localizations.dart'; +import 'package:dpip/shared/map/map_style.dart'; +import 'package:dpip/shared/seismic/intensity.dart'; +import 'package:dpip/shared/seismic/intensity_icon_renderer.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:intl/intl.dart'; + +enum _SharePhase { + preparing, + capturing, + composing, + ready, + exporting, + layoutUnavailable, + captureFailed, + exportFailed, + closed, +} + +typedef _StoryCapture = ({StoryMapSnapshot map, Map icons}); + +extension on ShareCardFormat { + Size get canvas => switch (this) { + ShareCardFormat.post => EarthquakeShareCard.canvas, + ShareCardFormat.story => StoryMapSnapshot.canvas, + }; + + String get filePrefix => switch (this) { + ShareCardFormat.post => 'dpip-card', + ShareCardFormat.story => 'dpip-story', + }; +} + +/// Owns one dialog's report, selected format and export state. +class EarthquakeShareDialog extends StatefulWidget { + const EarthquakeShareDialog({ + super.key, + required this.report, + required this.saver, + required this.isReportCurrent, + this.useD75Compact = const bool.fromEnvironment('DPIP_STORY_D75_COMPACT'), + }); + + final EarthquakeReport report; + final ImageSaver saver; + final bool Function() isReportCurrent; + final bool useD75Compact; + + @override + State createState() => _EarthquakeShareDialogState(); +} + +class _EarthquakeShareDialogState extends State { + // Task 5A's Android 1,200 ms latency run had a complete preview within + // about 14 s including UI automation. Budget 20 s end-to-end to give HUD + // layout, asset decoding and 3x rasterization headroom on either platform. + static const _captureBudget = Duration(seconds: 20); + static const _exportPixelRatio = 3.0; + + GlobalKey _boundaryKey = GlobalKey(); + ShareCardFormat _format = ShareCardFormat.post; + _SharePhase _phase = _SharePhase.preparing; + ModalRoute? _route; + Object? _compositionInputs; + int _generation = 0; + Timer? _deadline; + StoryCameraLayout? _layout; + _StoryCapture? _capture; + ({ShareCardFormat format, Uint8List png})? _artwork; + // A Post depends only on the report and inherited artwork inputs. Story + // still takes a fresh Snapshot each time it is selected. + Uint8List? _completedPost; + ImageSaveFailureReason? _saveFailure; + bool _openingSettings = false; + bool _settingsFailed = false; + bool _saving = false; + + bool get _isActive => + mounted && + _phase != _SharePhase.closed && + _route?.isActive == true && + widget.isReportCurrent(); + + bool _isCurrent(int generation) => _isActive && generation == _generation; + + bool get _canSave => + _isActive && + _route?.isCurrent == true && + !_saving && + !_openingSettings && + _saveFailure != ImageSaveFailureReason.unavailable && + _saveFailure != ImageSaveFailureReason.permissionRestricted && + _artwork?.format == _format && + (_phase == _SharePhase.ready || _phase == _SharePhase.exportFailed); + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _route = ModalRoute.of(context); + final textStyle = DefaultTextStyle.of(context); + final inputs = ( + MediaQuery.boldTextOf(context), + MediaQuery.devicePixelRatioOf(context), + Localizations.localeOf(context), + Directionality.of(context), + DefaultAssetBundle.of(context), + textStyle.style, + textStyle.textHeightBehavior, + textStyle.maxLines, + textStyle.overflow, + textStyle.softWrap, + textStyle.textWidthBasis, + Theme.of(context), + ); + if (_compositionInputs != inputs) { + _compositionInputs = inputs; + _completedPost = null; + if (_isActive) _beginAttempt(); + } + } + + @override + void didUpdateWidget(covariant EarthquakeShareDialog oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.report != oldWidget.report) { + _completedPost = null; + if (_isActive) _beginAttempt(); + } else if (_format == ShareCardFormat.story && + widget.useD75Compact != oldWidget.useD75Compact && + _isActive) { + _beginAttempt(); + } + } + + @override + void dispose() { + _invalidate(); + _phase = _SharePhase.closed; + super.dispose(); + } + + void _invalidate() { + _generation++; + _boundaryKey = GlobalKey(); + _deadline?.cancel(); + _deadline = null; + _capture = null; + _artwork = null; + _saveFailure = null; + _settingsFailed = false; + } + + void _selectFormat(Set selection) { + final format = selection.single; + if (_saving || format == _format) return; + setState(() { + _format = format; + _beginAttempt(); + }); + } + + void _beginAttempt() { + _invalidate(); + _layout = null; + final generation = _generation; + final format = _format; + if (format == ShareCardFormat.post && _completedPost != null) { + _artwork = (format: format, png: _completedPost!); + _phase = _SharePhase.ready; + return; + } + + _phase = _SharePhase.preparing; + _deadline = Timer(_captureBudget, () { + _failCapture( + generation, + TimeoutException('Share composition deadline exceeded', _captureBudget), + StackTrace.current, + ); + }); + if (format == ShareCardFormat.post) { + _phase = _SharePhase.composing; + unawaited(_composePost(generation)); + } + } + + Future _composePost(int generation) async { + try { + await _decode(EarthquakeShareCard.brandImage); + await _encodeArtwork(generation, ShareCardFormat.post); + } catch (error, stackTrace) { + _failCapture(generation, error, stackTrace); + } + } + + void _retryCapture(int generation) { + if (!_isCurrent(generation) || _phase != _SharePhase.captureFailed) return; + setState(_beginAttempt); + } + + void _updateLayout(int generation, StoryCameraLayout layout) { + if (!_isCurrent(generation) || layout == _layout) return; + // A failed attempt stays failed until Retry or a fresh format selection. + if (_phase == _SharePhase.captureFailed) return; + if (layout.anchorRegion.isEmpty) { + _markLayoutUnavailable(generation); + return; + } + setState(() { + if (_phase != _SharePhase.preparing) _beginAttempt(); + _layout = layout; + _phase = _SharePhase.capturing; + }); + unawaited(_captureAndCompose(_generation, layout)); + } + + void _markLayoutUnavailable(int generation) { + if (!_isCurrent(generation)) return; + setState(() { + _invalidate(); + _phase = _SharePhase.layoutUnavailable; + }); + } + + void _failCapture(int generation, Object error, StackTrace stackTrace) { + if (!_isCurrent(generation)) return; + Log.handle( + error, + stackTrace, + 'Earthquake share capture or composition failed', + ); + setState(() { + _invalidate(); + _phase = _SharePhase.captureFailed; + }); + } + + Future _captureAndCompose( + int generation, + StoryCameraLayout layout, + ) async { + try { + final report = widget.report; + final camera = fitStoryCamera(report, layout); + final map = await StoryMapSnapshot.capture( + report: report, + style: exptechVectorStyle( + MapColors.light, + basemapTileUrl: basemapOriginTileUrl, + glyphsUrl: glyphsOriginUrl, + ), + centerLatitude: camera.target.latitude, + centerLongitude: camera.target.longitude, + zoom: camera.zoom, + ); + if (!_isCurrent(generation)) return; + + // Allow two logical pixels of native camera rounding in the symbol gap. + final anchors = layout.anchorRegion.inflate(2); + final outside = map.markers + .where((marker) => !anchors.contains(marker.position)) + .length; + final epicenterOutside = !anchors.contains(map.epicenter); + if (outside > 0 || epicenterOutside) { + Log.warning( + '[StoryFit] FULL constrained zoom=${camera.zoom} ' + 'anchorRegion=${layout.anchorRegion} ' + 'observationsOutside=$outside epicenterOutside=$epicenterOutside', + ); + } + assert(() { + debugPrint( + '[StoryFit] FULL zoom=${camera.zoom} center=${camera.target} ' + 'mapRegion=${layout.mapRegion} anchorRegion=${layout.anchorRegion} ' + 'observations=${map.markers.length}', + ); + return true; + }()); + + setState(() => _phase = _SharePhase.composing); + final icons = await IntensityIconRenderer.renderAll(); + if (!_isCurrent(generation)) return; + + await Future.wait([ + _decode(EarthquakeShareStoryCard.brandImage), + _decode(MemoryImage(map.png)), + for (final bytes in icons.values) _decode(MemoryImage(bytes)), + ], eagerError: true); + if (!_isCurrent(generation)) return; + + setState(() => _capture = (map: map, icons: icons)); + await _encodeArtwork(generation, ShareCardFormat.story); + } catch (error, stackTrace) { + _failCapture(generation, error, stackTrace); + } + } + + Future _encodeArtwork(int generation, ShareCardFormat format) async { + if (!_isCurrent(generation)) return; + // Let the decoded images and text paint at the fixed artwork dimensions. + // The FittedBox and all dialog controls sit outside this boundary. + await WidgetsBinding.instance.endOfFrame; + if (!_isCurrent(generation)) return; + + final canvas = format.canvas; + final boundary = _boundaryKey.currentContext?.findRenderObject(); + if (boundary is! RenderRepaintBoundary || + !boundary.attached || + !boundary.hasSize || + boundary.size != canvas) { + throw StateError('Share composition boundary is unavailable'); + } + + final image = await boundary.toImage(pixelRatio: _exportPixelRatio); + try { + if (!_isCurrent(generation)) return; + if (image.width != canvas.width * _exportPixelRatio || + image.height != canvas.height * _exportPixelRatio) { + throw StateError( + 'Unexpected ${format.name} size: ${image.width}x${image.height}', + ); + } + final data = await image.toByteData(format: ui.ImageByteFormat.png); + if (!_isCurrent(generation)) return; + if (data == null || data.lengthInBytes == 0) { + throw StateError('Share PNG encoding failed'); + } + + final png = data.buffer.asUint8List( + data.offsetInBytes, + data.lengthInBytes, + ); + _deadline?.cancel(); + _deadline = null; + setState(() { + if (format == ShareCardFormat.post) _completedPost = png; + _artwork = (format: format, png: png); + _phase = _SharePhase.ready; + }); + debugPrint( + '[${format == ShareCardFormat.story ? 'Story' : 'ShareCard'}Export] ' + 'size=${image.width}x${image.height} bytes=${data.lengthInBytes}', + ); + } finally { + image.dispose(); + } + } + + Future _decode(ImageProvider image) async { + final configuration = createLocalImageConfiguration(context); + Object? failure; + StackTrace? trace; + await precacheImage( + image, + context, + onError: (error, stackTrace) { + failure = error; + trace = stackTrace; + }, + ); + if (failure case final error?) { + // A failed decode may leave a live completer in Flutter's image cache. + // Retry must resolve a new image stream instead of replaying that error. + await image.evict(configuration: configuration); + Error.throwWithStackTrace(error, trace ?? StackTrace.current); + } + } + + Future _save(int generation) async { + if (!_isCurrent(generation) || !_canSave) return; + final artwork = _artwork!; + final l10n = AppLocalizations.of(context); + ScaffoldMessenger.of(context).removeCurrentSnackBar(); + setState(() { + _saving = true; + _saveFailure = null; + _settingsFailed = false; + _phase = _SharePhase.exporting; + }); + + try { + final result = await widget.saver.saveToGalleryIfCurrent( + bytes: artwork.png, + fileName: '${artwork.format.filePrefix}-${widget.report.id}.png', + isCurrent: () => _isCurrent(generation) && _route?.isCurrent == true, + ); + if (!mounted || !_isCurrent(generation)) return; + + switch (result) { + case Ok(): + setState(() => _phase = _SharePhase.ready); + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text(l10n.reportDetailImageSaved))); + case Err(:final failure): + Log.warning('Earthquake share gallery save failed: $failure'); + _markExportFailed(failure); + case null: + // Eligibility was lost while waiting for permission. The write + // never started, even if the user has since returned to this route. + setState(() => _phase = _SharePhase.ready); + } + } catch (error, stackTrace) { + if (!_isCurrent(generation)) return; + Log.handle(error, stackTrace, 'Earthquake share gallery save failed'); + _markExportFailed(); + } finally { + // A layout update can start a new capture while a gallery request is + // still in flight. It may become ready but cannot start a second write. + if (mounted && _route?.isActive == true) { + setState(() => _saving = false); + } + } + } + + void _markExportFailed([Failure? failure]) { + setState(() { + _saveFailure = failure == null + ? ImageSaveFailureReason.failed + : imageSaveFailureReason(failure); + _phase = _SharePhase.exportFailed; + }); + } + + Future _openGallerySettings(int generation) async { + if (!_isCurrent(generation) || + _route?.isCurrent != true || + _openingSettings || + _saveFailure != ImageSaveFailureReason.permissionSettingsRequired) { + return; + } + setState(() { + _openingSettings = true; + _settingsFailed = false; + }); + final opened = await openAppSettingsPage(); + if (!mounted || _route?.isActive != true) return; + setState(() { + _openingSettings = false; + _settingsFailed = !opened && _isCurrent(generation); + }); + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context); + final screenSize = MediaQuery.sizeOf(context); + final generation = _generation; + final layoutUnavailable = _phase == _SharePhase.layoutUnavailable; + final captureFailed = _phase == _SharePhase.captureFailed; + final error = switch (_phase) { + _SharePhase.layoutUnavailable => l10n.reportDetailStoryLayoutUnavailable, + _SharePhase.captureFailed => l10n.commonFetchFailed, + _SharePhase.exportFailed => _saveFailure?.message(l10n), + _ => null, + }; + final save = FilledButton.icon( + onPressed: _canSave ? () => _save(generation) : null, + icon: _saving + ? const SizedBox.square( + dimension: 16, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.save_alt), + label: Text(l10n.reportDetailImageSave), + ); + + return Dialog( + child: SizedBox( + height: screenSize.height * 0.72, + child: LayoutBuilder( + builder: (context, constraints) { + // Keep Save in view. A very short viewport can scroll all controls. + final pinSave = constraints.maxHeight >= 240; + return Column( + children: [ + Expanded( + child: LayoutBuilder( + builder: (context, viewport) => SingleChildScrollView( + primary: false, + padding: const EdgeInsets.all(AppSpacing.md), + child: Column( + children: [ + Wrap( + alignment: WrapAlignment.center, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: AppSpacing.sm, + children: [ + SegmentedButton( + segments: const [ + ButtonSegment( + value: ShareCardFormat.post, + label: Text('4:5'), + ), + ButtonSegment( + value: ShareCardFormat.story, + label: Text('9:16'), + ), + ], + selected: {_format}, + onSelectionChanged: _saving + ? null + : _selectFormat, + ), + IconButton( + onPressed: () => Navigator.of(context).pop(), + tooltip: l10n.commonClose, + icon: const Icon(Icons.close), + ), + ], + ), + const SizedBox(height: AppSpacing.md), + if (error != null) + Semantics( + liveRegion: true, + child: Text( + _settingsFailed + ? l10n.reportDetailImageSaveSettingsFailed + : error, + textAlign: TextAlign.center, + ), + ), + if (_saveFailure == + ImageSaveFailureReason.permissionSettingsRequired) + TextButton( + onPressed: _openingSettings + ? null + : () => _openGallerySettings(generation), + child: Text(l10n.permissionOpenSettings), + ), + if (!layoutUnavailable && !captureFailed) + _buildPreview(viewport.maxHeight, l10n), + if (captureFailed) + TextButton( + onPressed: () => _retryCapture(generation), + child: Text(l10n.commonRetry), + ), + if (!pinSave) save, + _ShareReportDetails(report: widget.report), + ], + ), + ), + ), + ), + if (pinSave) + Padding( + padding: const EdgeInsets.fromLTRB( + AppSpacing.md, + AppSpacing.xs, + AppSpacing.md, + AppSpacing.md, + ), + child: save, + ), + ], + ); + }, + ), + ), + ); + } + + Widget _buildPreview(double viewportHeight, AppLocalizations l10n) { + final story = _format == ShareCardFormat.story; + final generation = _generation; + final canvas = _format.canvas; + final capture = _capture; + final loading = switch (_phase) { + _SharePhase.preparing || + _SharePhase.capturing || + _SharePhase.composing => true, + _ => false, + }; + return SizedBox( + // Leave room for controls on a short viewport. The + // document can scroll when labels need additional lines. + height: math.min(viewportHeight * 0.7, canvas.height), + width: double.infinity, + child: Stack( + alignment: Alignment.center, + children: [ + ExcludeSemantics( + excluding: loading, + child: FittedBox( + fit: BoxFit.contain, + child: SizedBox( + width: canvas.width, + height: canvas.height, + child: story + ? EarthquakeShareStoryCard( + key: ValueKey(generation), + report: widget.report, + mapPng: capture?.map.png, + markerIcons: capture?.icons ?? const {}, + stationMarkers: capture?.map.markers ?? const [], + epicenterPosition: capture?.map.epicenter, + useD75Compact: widget.useD75Compact, + compositionKey: capture == null ? null : _boundaryKey, + onMapLayout: (layout) => + _updateLayout(generation, layout), + onLayoutUnavailable: () => + _markLayoutUnavailable(generation), + ) + : RepaintBoundary( + key: _boundaryKey, + child: EarthquakeShareCard(report: widget.report), + ), + ), + ), + ), + if (loading) + Semantics( + liveRegion: true, + child: CircularProgressIndicator( + semanticsLabel: l10n.commonLoading, + ), + ), + ], + ), + ); + } +} + +/// Text equivalent for the report information printed on either artwork. +class _ShareReportDetails extends StatelessWidget { + const _ShareReportDetails({required this.report}); + + final EarthquakeReport report; + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context); + final time = DateFormat('yyyy/MM/dd HH:mm:ss') + .format(AppTime.taipei(report.originTimeUtc)); + final intensity = Intensity.displayForReport( + report.maxIntensity, + report.originTimeUtc, + ); + return ExpansionTile( + title: Text(l10n.reportDetailInfo), + tilePadding: EdgeInsets.zero, + expandedCrossAxisAlignment: CrossAxisAlignment.start, + expandedAlignment: AlignmentDirectional.centerStart, + children: [ + Text( + report.hasNumber + ? l10n.reportDetailNumbered(report.number!) + : l10n.reportDetailLocalFelt, + ), + Text(report.location), + Text('${l10n.reportDetailOriginTime} $time'), + Text(l10n.reportListMagnitude(report.magnitude.toStringAsFixed(1))), + Text(l10n.reportDetailMaximumIntensity(intensity.label)), + Text( + '${l10n.reportDetailDepth} ' + '${l10n.reportFilterDepthKm(report.depth.toStringAsFixed(1))}', + ), + ], + ); + } +} diff --git a/lib/features/earthquake/presentation/widgets/earthquake_share_icon.dart b/lib/features/earthquake/presentation/widgets/earthquake_share_icon.dart new file mode 100644 index 000000000..f06fd1a4c --- /dev/null +++ b/lib/features/earthquake/presentation/widgets/earthquake_share_icon.dart @@ -0,0 +1,32 @@ +import 'package:flutter/widgets.dart'; + +/// The DPIP app icon as it appears in earthquake share artwork. +class EarthquakeShareIcon extends StatelessWidget { + const EarthquakeShareIcon({ + super.key, + required this.size, + this.excludeFromSemantics = false, + this.errorBuilder, + }); + + static const image = AssetImage('assets/DPIP.png'); + + final double size; + final bool excludeFromSemantics; + final ImageErrorWidgetBuilder? errorBuilder; + + @override + Widget build(BuildContext context) { + return ClipRSuperellipse( + borderRadius: BorderRadius.circular(size * 0.22), + child: Image( + image: image, + width: size, + height: size, + fit: BoxFit.contain, + excludeFromSemantics: excludeFromSemantics, + errorBuilder: errorBuilder, + ), + ); + } +} diff --git a/lib/features/earthquake/presentation/widgets/earthquake_share_story_card.dart b/lib/features/earthquake/presentation/widgets/earthquake_share_story_card.dart new file mode 100644 index 000000000..4322acb6c --- /dev/null +++ b/lib/features/earthquake/presentation/widgets/earthquake_share_story_card.dart @@ -0,0 +1,1013 @@ +import 'dart:convert'; +import 'dart:math' as math; +import 'dart:typed_data'; + +import 'package:dpip/app/theme/app_radius.dart'; +import 'package:dpip/app/theme/app_spacing.dart'; +import 'package:dpip/core/realtime/app_time.dart'; +import 'package:dpip/features/earthquake/domain/earthquake_report.dart'; +import 'package:dpip/features/earthquake/presentation/story_camera_fit.dart'; +import 'package:dpip/features/earthquake/presentation/story_map_snapshot.dart'; +import 'package:dpip/features/earthquake/presentation/story_marker_layout.dart'; +import 'package:dpip/features/earthquake/presentation/story_observation_clustering.dart'; +import 'package:dpip/features/earthquake/presentation/widgets/earthquake_share_icon.dart'; +import 'package:dpip/l10n/gen/app_localizations.dart'; +import 'package:dpip/shared/seismic/intensity.dart'; +import 'package:dpip/shared/seismic/intensity_colors.dart'; +import 'package:dpip/shared/seismic/intensity_icon_renderer.dart'; +import 'package:dpip/shared/seismic/spoken_intensity.dart'; +import 'package:dpip/shared/widgets/intensity_badge.dart'; +import 'package:flutter/foundation.dart' show listEquals; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:intl/intl.dart'; + +/// 9:16 earthquake report card for social stories. +/// +/// Uses a fixed 360x640 logical canvas, intended for +/// rendering at 3x resolution (1080x1920). +class EarthquakeShareStoryCard extends StatefulWidget { + const EarthquakeShareStoryCard({ + super.key, + required this.report, + this.mapPng, + this.markerIcons = const {}, + this.stationMarkers = const [], + this.epicenterPosition, + this.showSafeAreaGuides = false, + this.useD75Compact = const bool.fromEnvironment('DPIP_STORY_D75_COMPACT'), + this.onMapLayout, + this.onLayoutUnavailable, + this.compositionKey, + }); + + final EarthquakeReport report; + final Uint8List? mapPng; + final Map markerIcons; + final List stationMarkers; + final Offset? epicenterPosition; + final bool showSafeAreaGuides; + + /// Opt-in while the 75 km validation threshold awaits product approval. + final bool useD75Compact; + final ValueChanged? onMapLayout; + final VoidCallback? onLayoutUnavailable; + + /// The rasterized content excludes the preview-only safe-area guides. + final GlobalKey? compositionKey; + + static const brandImage = EarthquakeShareIcon.image; + + @override + State createState() => + _EarthquakeShareStoryCardState(); + + // Instagram Story (9:16) safe-area test configuration. + // + // Logical canvas: 360x640 + // Planned export: 1080x1920 at 3x + // + // Instagram Story Template v2. + // Experimental safe-area values based on real-device testing. + static const double _safeTop = 56; + static const double _safeBottom = 40; + static const double _safeGap = 8; + static const double _horizontalInset = AppSpacing.lg; +} + +class _EarthquakeShareStoryCardState extends State { + final _debugCanvasKey = GlobalKey(); + final _debugLogoKey = GlobalKey(); + final _debugHudKey = GlobalKey(); + + @override + Widget build(BuildContext context) { + final EarthquakeShareStoryCard( + :report, + :mapPng, + :markerIcons, + :stationMarkers, + :epicenterPosition, + :onMapLayout, + :onLayoutUnavailable, + :useD75Compact, + :showSafeAreaGuides, + :compositionKey, + ) = widget; + final l10n = AppLocalizations.of(context); + // The exported card always uses the light DPIP palette. + final colors = ColorScheme.fromSeed( + seedColor: const Color(0xFF00696D), + brightness: Brightness.light, + ); + + final originTime = DateFormat('yyyy/MM/dd HH:mm:ss') + .format(AppTime.taipei(report.originTimeUtc)); + + final intensity = Intensity.displayForReport( + report.maxIntensity, + report.originTimeUtc, + ); + + assert(() { + if (mapPng == null) return true; + + WidgetsBinding.instance.addPostFrameCallback((_) { + final canvasObject = _debugCanvasKey.currentContext?.findRenderObject(); + + if (canvasObject is! RenderBox || !canvasObject.attached) { + return; + } + + Rect? measureRect(GlobalKey key) { + final object = key.currentContext?.findRenderObject(); + + if (object is! RenderBox || !object.attached) { + return null; + } + + final origin = object.localToGlobal( + Offset.zero, + ancestor: canvasObject, + ); + + return origin & object.size; + } + + final logoRect = measureRect(_debugLogoKey); + final hudRect = measureRect(_debugHudKey); + + if (logoRect == null || hudRect == null) { + debugPrint('[StoryChrome] measurement unavailable'); + return; + } + + const markerSize = 22.0; + const crossSize = 36.0; + + var logoCovered = 0; + var hudCovered = 0; + var eitherCovered = 0; + var maxIntensityCovered = 0; + var maxIntensityTotal = 0; + + for (final marker in stationMarkers) { + final position = marker.position; + + if (!position.dx.isFinite || !position.dy.isFinite) { + continue; + } + + final markerRect = Rect.fromCenter( + center: position, + width: markerSize, + height: markerSize, + ); + + final coversLogo = logoRect.overlaps(markerRect); + final coversHud = hudRect.overlaps(markerRect); + + if (coversLogo) logoCovered++; + if (coversHud) hudCovered++; + + if (coversLogo || coversHud) { + eitherCovered++; + } + + if (marker.intensity == report.maxIntensity) { + maxIntensityTotal++; + + if (coversLogo || coversHud) { + maxIntensityCovered++; + } + } + } + + final epicenter = epicenterPosition; + + final epicenterCovered = + epicenter != null && + (logoRect.overlaps( + Rect.fromCenter( + center: epicenter, + width: crossSize, + height: crossSize, + ), + ) || + hudRect.overlaps( + Rect.fromCenter( + center: epicenter, + width: crossSize, + height: crossSize, + ), + )); + + debugPrint( + '[StoryChrome] ' + 'canvas=${canvasObject.size} ' + 'logo=$logoRect ' + 'hud=$hudRect', + ); + + debugPrint( + '[StoryOcclusion] ' + 'total=${stationMarkers.length} ' + 'logoCovered=$logoCovered ' + 'hudCovered=$hudCovered ' + 'eitherCovered=$eitherCovered', + ); + + debugPrint( + '[StoryOcclusion] ' + 'maxIntensityCovered=' + '$maxIntensityCovered/$maxIntensityTotal ' + 'epicenterCovered=$epicenterCovered', + ); + }); + + return true; + }()); + + final hud = Positioned( + left: EarthquakeShareStoryCard._horizontalInset, + right: EarthquakeShareStoryCard._horizontalInset, + bottom: + EarthquakeShareStoryCard._safeBottom + + EarthquakeShareStoryCard._safeGap, + child: Semantics( + container: true, + explicitChildNodes: true, + sortKey: const OrdinalSortKey(0), + child: ClipRRect( + key: _debugHudKey, + borderRadius: AppRadius.large, + child: ColoredBox( + color: Colors.white.withValues(alpha: 0.91), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + // Earthquake report identifier. + Expanded( + child: Text( + report.hasNumber + ? l10n.reportDetailNumbered(report.number!) + : l10n.reportDetailLocalFelt, + style: TextStyle( + color: colors.onSurfaceVariant, + fontSize: 10, + ), + ), + ), + + const SizedBox(width: 8), + + // Compact DPIP branding. + Row( + key: _debugLogoKey, + mainAxisSize: MainAxisSize.min, + children: [ + const EarthquakeShareIcon( + size: 18, + excludeFromSemantics: true, + ), + const SizedBox(width: 4), + // Keep the icon anchored when system fonts give the + // wordmark different widths. + const SizedBox( + width: 28, + child: FittedBox( + alignment: AlignmentDirectional.centerStart, + fit: BoxFit.scaleDown, + child: Text( + 'DPIP', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: Color(0xFF172B2D), + ), + ), + ), + ), + ], + ), + ], + ), + const SizedBox(height: AppSpacing.xs), + + Text( + report.shortLocation, + style: TextStyle( + color: colors.onSurface, + fontSize: 22, + fontWeight: FontWeight.w800, + ), + ), + const SizedBox(height: AppSpacing.xs), + + Text( + originTime, + style: TextStyle( + color: colors.onSurfaceVariant, + fontSize: 13, + ), + ), + const SizedBox(height: AppSpacing.md), + + Row( + children: [ + Expanded( + child: _StoryMetric( + label: l10n.reportDetailMagnitude, + value: 'M${report.magnitude.toStringAsFixed(1)}', + ), + ), + Expanded( + child: _StoryMetric( + label: l10n.reportDetailMaximumIntensityLabel, + badge: IntensityBadge( + label: intensity.label, + color: IntensityColors.discrete( + intensity.colorLevel, + ), + size: 28, + ), + ), + ), + Expanded( + child: _StoryMetric( + label: l10n.reportDetailDepth, + value: report.depth.toStringAsFixed(1), + suffix: 'km', + ), + ), + ], + ), + + const SizedBox(height: AppSpacing.md), + Divider(color: colors.outlineVariant, height: 1), + const SizedBox(height: AppSpacing.sm), + + LayoutBuilder( + builder: (context, viewport) => ConstrainedBox( + // Reserve the same single-line space across system + // fonts. Longer credits still have a two-line budget. + constraints: const BoxConstraints( + minHeight: 17, + maxHeight: 32, + ), + child: FittedBox( + alignment: AlignmentDirectional.centerStart, + fit: BoxFit.scaleDown, + child: SizedBox( + width: viewport.maxWidth, + child: Text( + l10n.reportDetailStoryAttribution( + l10n.reportDetailShareSource, + ), + style: TextStyle( + fontSize: 11, + color: colors.onSurfaceVariant, + ), + ), + ), + ), + ), + ), + ], + ), + ), + ), + ), + ), + ); + + final content = Stack( + fit: StackFit.expand, + children: [ + Positioned.fill( + child: mapPng == null + ? ColoredBox(color: colors.surfaceContainerHigh) + : Image.memory( + mapPng, + width: StoryMapSnapshot.canvas.width, + height: StoryMapSnapshot.canvas.height, + fit: BoxFit.cover, + excludeFromSemantics: true, + ), + ), + Positioned.fill( + child: Semantics( + container: true, + explicitChildNodes: true, + child: _StoryMapMarkers( + markers: mapPng == null ? const [] : stationMarkers, + icons: mapPng == null ? const {} : markerIcons, + epicenterPosition: epicenterPosition, + originTimeUtc: report.originTimeUtc, + hud: hud, + useD75Compact: useD75Compact && mapPng != null, + locations: { + if (mapPng != null) + for (final area in report.list.entries) + for (final name in area.value.town.keys) + jsonEncode([area.key, name]): name == area.key + ? name + : '${area.key}$name', + }, + observationCount: report.list.values.fold( + 0, + (count, area) => count + area.town.length, + ), + onMapLayout: onMapLayout, + onLayoutUnavailable: onLayoutUnavailable, + ), + ), + ), + ], + ); + return SizedBox( + key: _debugCanvasKey, + width: StoryMapSnapshot.canvas.width, + height: StoryMapSnapshot.canvas.height, + // The preview and PNG share a single composition. Scale the dialog's + // controls and report text independently of the original artwork sizes. + child: MediaQuery.withNoTextScaling( + child: Stack( + fit: StackFit.expand, + children: [ + if (compositionKey != null) + RepaintBoundary(key: compositionKey, child: content) + else + content, + + // Temporary Instagram Story safe-area guides. + // Preview only — never include in exported images. + if (showSafeAreaGuides) ...[ + // Upper safe-area boundary. + Positioned( + top: EarthquakeShareStoryCard._safeTop, + left: 0, + right: 0, + child: IgnorePointer( + child: Container(height: 2, color: Colors.red), + ), + ), + + // Lower safe-area boundary. + Positioned( + bottom: EarthquakeShareStoryCard._safeBottom, + left: 0, + right: 0, + child: IgnorePointer( + child: Container(height: 2, color: Colors.red), + ), + ), + ], + ], + ), + ), + ); + } +} + +class _StoryMetric extends StatelessWidget { + const _StoryMetric({ + required this.label, + this.value, + this.suffix, + this.badge, + }); + + final String label; + final String? value; + final String? suffix; + final Widget? badge; + + @override + Widget build(BuildContext context) { + return MergeSemantics( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + label, + style: const TextStyle(fontSize: 11, color: Color(0xFF607477)), + ), + const SizedBox(height: AppSpacing.xs), + SizedBox( + height: 28, + child: Align( + alignment: Alignment.centerLeft, + child: + badge ?? + FittedBox( + fit: BoxFit.scaleDown, + alignment: Alignment.centerLeft, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + value ?? '—', + style: const TextStyle( + fontSize: 21, + fontWeight: FontWeight.w800, + color: Color(0xFF172B2D), + ), + ), + if (suffix != null) ...[ + const SizedBox(width: AppSpacing.xs), + Text( + suffix!, + style: const TextStyle( + fontSize: 11, + color: Color(0xFF607477), + ), + ), + ], + ], + ), + ), + ), + ), + ], + ), + ); + } +} + +class _StoryMapMarkers extends StatelessWidget { + const _StoryMapMarkers({ + required this.markers, + required this.icons, + required this.epicenterPosition, + required this.originTimeUtc, + required this.hud, + required this.useD75Compact, + required this.locations, + required this.observationCount, + required this.onMapLayout, + required this.onLayoutUnavailable, + }); + + static const _stationSize = 22.0; + static const _crossSize = 36.0; + static const _countStyle = TextStyle( + color: Colors.white, + fontSize: 9, + height: 1, + fontWeight: FontWeight.w700, + fontFeatures: [FontFeature.tabularFigures()], + ); + static const _countPadding = EdgeInsets.symmetric(horizontal: 3, vertical: 1); + static final _countDecoration = BoxDecoration( + color: const Color(0xFF213D47), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.white), + ); + + final List markers; + final Map icons; + final Offset? epicenterPosition; + final DateTime originTimeUtc; + final Widget hud; + final bool useD75Compact; + final Map locations; + final int observationCount; + final ValueChanged? onMapLayout; + final VoidCallback? onLayoutUnavailable; + + Rect _fitFootprint(BuildContext context) { + const cross = Rect.fromLTWH( + -_crossSize / 2, + -_crossSize / 2, + _crossSize, + _crossSize, + ); + if (observationCount < 2) return cross; + + // A badge cannot have more digits than the report's observation count. + // Use the largest digit footprint at that length before clusters exist. + final defaults = DefaultTextStyle.of(context); + var style = defaults.style.merge(_countStyle); + if (MediaQuery.boldTextOf(context)) { + style = style.merge(const TextStyle(fontWeight: FontWeight.bold)); + } + final painter = TextPainter( + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + textHeightBehavior: defaults.textHeightBehavior, + locale: Localizations.maybeLocaleOf(context), + ); + final digits = observationCount.toString().length; + var textBox = Rect.zero; + for (var digit = 0; digit <= 9; digit++) { + painter.text = TextSpan(text: '$digit' * digits, style: style); + painter.layout(); + textBox = textBox.expandToInclude(Offset.zero & painter.size); + } + painter.dispose(); + final badgeSize = _countPadding + .add(_countDecoration.padding) + .inflateSize(textBox.size); + return cross.expandToInclude( + StoryMarkerFootprint( + icon: const Size.square(_stationSize), + badge: badgeSize, + ).envelope, + ); + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context); + final clusters = + clusterStoryObservations( + markers, + maxDiameterMetres: useD75Compact ? storyD75MaxDiameterMetres : null, + ).indexed.toList()..sort((a, b) { + final intensity = a.$2.maxIntensity.compareTo(b.$2.maxIntensity); + // Paint the earlier canonical anchor above later equal-intensity + // anchors, and give it first choice when laying out in reverse order. + return intensity != 0 ? intensity : b.$1.compareTo(a.$1); + }); + final cross = epicenterPosition; + final crossBytes = icons['cross']; + final showCross = cross != null && cross.isFinite && crossBytes != null; + return _StoryMarkerStack( + markers: [ + for (final (_, cluster) in clusters) + (anchor: cluster.anchor.position, hasBadge: cluster.count > 1), + ], + hasEpicenter: showCross, + legendObservations: useD75Compact ? markers : null, + fitFootprint: onMapLayout == null ? null : _fitFootprint(context), + onMapLayout: onMapLayout, + onLayoutUnavailable: onLayoutUnavailable, + children: [ + for (final (_, cluster) in clusters) ...[ + Positioned( + left: 0, + top: 0, + width: _stationSize, + height: _stationSize, + child: Semantics( + container: true, + sortKey: const OrdinalSortKey(3), + excludeSemantics: true, + label: _observationLabel(l10n, cluster), + child: _icon(cluster), + ), + ), + if (cluster.count > 1) + Positioned( + left: 0, + top: 0, + child: Container( + padding: _countPadding, + decoration: _countDecoration, + child: ExcludeSemantics( + child: Text('${cluster.count}', style: _countStyle), + ), + ), + ), + ], + if (showCross) + Positioned( + left: cross.dx - _crossSize / 2, + top: cross.dy - _crossSize / 2, + child: Semantics( + container: true, + sortKey: const OrdinalSortKey(1), + child: Image.memory( + crossBytes, + width: _crossSize, + height: _crossSize, + fit: BoxFit.contain, + gaplessPlayback: true, + semanticLabel: l10n.reportDetailEpicenter, + ), + ), + ), + if (useD75Compact) + Positioned(left: 0, top: 0, child: _StoryLegend(l10n: l10n)), + hud, + ], + ); + } + + String _observationLabel(AppLocalizations l10n, StoryMarkerCluster cluster) { + final level = cluster.maxIntensity; + // A screen reader may skip the superscript sign on a split-scale icon. + final intensity = + level >= 5 && level <= 8 && !Intensity.usesLegacyScale(originTimeUtc) + ? spokenIntensityLabel(level, l10n.localeName) + : Intensity.displayForReport(level, originTimeUtc).label; + final location = locations[cluster.anchor.sourceId]; + if (location == null) { + return l10n.reportDetailStoryObservations(cluster.count, intensity); + } + return cluster.count == 1 + ? l10n.reportDetailStorySingleObservation(location, intensity) + : l10n.reportDetailStoryObservationGroup( + cluster.count, + intensity, + location, + ); + } + + Widget _icon(StoryMarkerCluster cluster) { + final presentation = Intensity.displayForReport( + cluster.maxIntensity, + originTimeUtc, + ); + final name = IntensityIconRenderer.nameFor( + presentation, + useDarkSuffix: true, + ); + final bytes = icons[name]; + if (bytes != null) { + return Image.memory( + bytes, + width: _stationSize, + height: _stationSize, + fit: BoxFit.contain, + gaplessPlayback: true, + ); + } + return IntensityBadge( + label: presentation.label, + color: IntensityColors.discrete(presentation.colorLevel), + size: _stationSize, + ); + } +} + +class _StoryLegend extends StatelessWidget { + const _StoryLegend({required this.l10n}); + + final AppLocalizations l10n; + + @override + Widget build(BuildContext context) { + const style = TextStyle(fontSize: 10, height: 1, color: Color(0xFF263B45)); + final count = l10n.reportDetailStoryLegendCount; + final intensity = l10n.reportDetailStoryLegendIntensity; + return Semantics( + container: true, + sortKey: const OrdinalSortKey(2), + excludeSemantics: true, + label: '$count\n$intensity', + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2), + decoration: BoxDecoration( + color: Colors.white.withValues(alpha: 0.92), + borderRadius: BorderRadius.circular(4), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(count, style: style, softWrap: false, maxLines: 1), + Text(intensity, style: style, softWrap: false, maxLines: 1), + ], + ), + ), + ); + } +} + +typedef _MarkerChildren = ({Offset anchor, bool hasBadge}); + +class _StoryMarkerStack extends Stack { + const _StoryMarkerStack({ + required this.markers, + required this.hasEpicenter, + required this.legendObservations, + required this.fitFootprint, + required this.onMapLayout, + required this.onLayoutUnavailable, + required super.children, + }) : super(alignment: Alignment.topLeft); + + final List<_MarkerChildren> markers; + final bool hasEpicenter; + final List? legendObservations; + final Rect? fitFootprint; + final ValueChanged? onMapLayout; + final VoidCallback? onLayoutUnavailable; + + @override + _RenderStoryMarkerStack createRenderObject(BuildContext context) => + _RenderStoryMarkerStack(markers, hasEpicenter) + ..updateMapLayout(fitFootprint, onMapLayout) + ..updateLegend(legendObservations, onLayoutUnavailable); + + @override + void updateRenderObject( + BuildContext context, + covariant _RenderStoryMarkerStack renderObject, + ) { + renderObject.updateMarkers(markers, hasEpicenter); + renderObject.updateMapLayout(fitFootprint, onMapLayout); + renderObject.updateLegend(legendObservations, onLayoutUnavailable); + } +} + +class _RenderStoryMarkerStack extends RenderStack { + _RenderStoryMarkerStack(this._markers, this._hasEpicenter) + : super(alignment: Alignment.topLeft); + + List<_MarkerChildren> _markers; + bool _hasEpicenter; + List _connectors = []; + Rect? _fitFootprint; + ValueChanged? _onMapLayout; + StoryCameraLayout? _lastLayout; + List? _legendObservations; + VoidCallback? _onLayoutUnavailable; + bool _legendUnavailable = false; + + void updateLegend( + List? observations, + VoidCallback? onLayoutUnavailable, + ) { + _onLayoutUnavailable = onLayoutUnavailable; + if (identical(_legendObservations, observations)) return; + _legendObservations = observations; + markNeedsLayout(); + } + + void updateMapLayout( + Rect? footprint, + ValueChanged? onMapLayout, + ) { + _onMapLayout = onMapLayout; + if (_fitFootprint == footprint) return; + _fitFootprint = footprint; + markNeedsLayout(); + } + + void updateMarkers(List<_MarkerChildren> markers, bool hasEpicenter) { + if (_hasEpicenter == hasEpicenter && listEquals(_markers, markers)) return; + _markers = markers; + _hasEpicenter = hasEpicenter; + markNeedsLayout(); + } + + @override + void performLayout() { + // Stack lays out the original HUD and the unconstrained count labels in + // this pass. Use those actual sizes before assigning marker offsets, so + // font changes are reflected in the same frame and in offscreen exports. + super.performLayout(); + var child = firstChild; + final boxes = <({RenderBox icon, RenderBox? badge})>[]; + final footprints = []; + for (final marker in _markers) { + final icon = child!; + final badge = marker.hasBadge ? childAfter(icon)! : null; + boxes.add((icon: icon, badge: badge)); + footprints.add(( + anchor: marker.anchor, + footprint: StoryMarkerFootprint(icon: icon.size, badge: badge?.size), + )); + child = childAfter(badge ?? icon); + } + Rect bounds(RenderBox box) => + (box.parentData! as StackParentData).offset & box.size; + + // Reserve the full cross image (including its white outline) and HUD box. + final epicenter = _hasEpicenter ? bounds(child!) : null; + final hud = bounds(lastChild!); + final canvas = Offset.zero & size; + if (_fitFootprint case final footprint?) { + final layout = storyCameraLayout( + canvas: size, + safeTop: EarthquakeShareStoryCard._safeTop, + safeBottom: EarthquakeShareStoryCard._safeBottom, + hud: hud, + footprint: footprint, + gap: EarthquakeShareStoryCard._safeGap, + ); + if (layout != _lastLayout) { + _lastLayout = layout; + // Start the capture outside layout, using the most recent measured + // geometry. A later layout can supersede this callback. + SchedulerBinding.instance.addPostFrameCallback((_) { + if (attached && _lastLayout == layout) _onMapLayout?.call(layout); + }); + } + } else { + _lastLayout = null; + } + final centers = layoutStoryMarkers( + markers: footprints.reversed.toList(), + canvas: canvas, + epicenter: epicenter, + hud: hud, + ).reversed.toList(); + + final connectors = []; + for (final (index, position) in centers.indexed) { + final anchor = footprints[index]; + final components = anchor.footprint.at(position); + final box = boxes[index]; + (box.icon.parentData! as StackParentData).offset = + components.first.topLeft; + final badge = box.badge; + if (badge != null) { + (badge.parentData! as StackParentData).offset = components.last.topLeft; + } + if (position != anchor.anchor) { + connectors.add(StoryConnector(anchor.anchor, position)); + } + } + _connectors = connectors; + + _legendUnavailable = false; + if (_legendObservations case final observations?) { + final legend = childBefore(lastChild!)!; + final placement = layoutStoryLegend( + legend: legend.size, + safeRegion: Rect.fromLTRB( + EarthquakeShareStoryCard._horizontalInset, + EarthquakeShareStoryCard._safeTop + 1, + size.width - EarthquakeShareStoryCard._horizontalInset, + math.min( + size.height - EarthquakeShareStoryCard._safeBottom, + hud.top - EarthquakeShareStoryCard._safeGap, + ), + ), + occupied: [ + hud, + ?epicenter, + for (final box in boxes) ...[ + bounds(box.icon), + if (box.badge case final badge?) bounds(badge), + ], + ], + observations: observations.map((marker) => marker.position), + connectors: connectors, + ); + if (placement == null) { + _legendUnavailable = true; + SchedulerBinding.instance.addPostFrameCallback((_) { + if (attached && _legendUnavailable) _onLayoutUnavailable?.call(); + }); + } else { + (legend.parentData! as StackParentData).offset = placement.topLeft; + } + } + + assert(() { + final components = [ + for (final box in boxes) + [bounds(box.icon), if (box.badge != null) bounds(box.badge!)], + ]; + var overlapPairs = 0; + for (final (index, group) in components.indexed) { + overlapPairs += components + .skip(index + 1) + .where((other) => group.any((box) => other.any(box.overlaps))) + .length; + } + final all = components.expand((group) => group); + final epicenterOverlaps = epicenter == null + ? 0 + : all.where(epicenter.overlaps).length; + final hudOverlaps = all.where(hud.overlaps).length; + final outside = all.where((box) => canvas.intersect(box) != box).length; + if (overlapPairs + epicenterOverlaps + hudOverlaps + outside > 0) { + debugPrint( + '[StoryClusterLayout] unresolved ' + 'overlapPairs=$overlapPairs epicenterOverlaps=$epicenterOverlaps ' + 'hudOverlaps=$hudOverlaps outsideCanvas=$outside', + ); + } + return true; + }()); + } + + @override + void paintStack(PaintingContext context, Offset offset) { + if (_legendUnavailable) return; + if (_connectors.isNotEmpty) { + final paint = Paint() + ..color = const Color(0xB3263B45) + ..strokeWidth = StoryConnector.strokeWidth + ..style = PaintingStyle.stroke; + for (final line in _connectors) { + context.canvas.drawLine(line.from + offset, line.to + offset, paint); + } + } + super.paintStack(context, offset); + } +} diff --git a/lib/features/earthquake/presentation/widgets/report_image_save_feedback.dart b/lib/features/earthquake/presentation/widgets/report_image_save_feedback.dart new file mode 100644 index 000000000..322a82535 --- /dev/null +++ b/lib/features/earthquake/presentation/widgets/report_image_save_feedback.dart @@ -0,0 +1,20 @@ +import 'package:dpip/core/error/failure.dart'; +import 'package:dpip/l10n/gen/app_localizations.dart'; + +ImageSaveFailureReason imageSaveFailureReason(Failure failure) => + failure is ImageSaveFailure + ? failure.reason + : ImageSaveFailureReason.failed; + +extension ReportImageSaveFeedback on ImageSaveFailureReason { + String message(AppLocalizations l10n) => switch (this) { + ImageSaveFailureReason.permissionDenied => + l10n.reportDetailImageSavePermissionDenied, + ImageSaveFailureReason.permissionSettingsRequired => + l10n.reportDetailImageSaveSettingsRequired, + ImageSaveFailureReason.permissionRestricted => + l10n.reportDetailImageSaveRestricted, + ImageSaveFailureReason.unavailable => l10n.reportDetailImageSaveUnavailable, + ImageSaveFailureReason.failed => l10n.reportDetailImageSaveFailed, + }; +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 32a97bb94..6dcf0768d 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -4492,5 +4492,110 @@ "seismometerAlgorithm": "Computed with the JMA instrumental intensity method used by ES-Net", "@seismometerAlgorithm": { "description": "Names the JMA instrumental-intensity method used to compute the reading" + }, + "reportDetailMaximumIntensityLabel": "Maximum intensity", + "reportDetailMaximumIntensity": "Maximum intensity {intensity}", + "reportDetailStoryObservations": "{count, plural, one{1 observation, intensity {intensity}} other{{count} observations, maximum intensity {intensity}}}", + "reportDetailStoryLayoutUnavailable": "This report cannot fit in a Story. Choose 4:5 or open Details.", + "@reportDetailMaximumIntensity": { + "description": "Spoken or plain text label and value for observed maximum intensity.", + "placeholders": { + "intensity": { + "type": "String" + } + } + }, + "@reportDetailStoryObservations": { + "description": "Accessible label for one Story marker, with the number of observations and its highest observed intensity.", + "placeholders": { + "count": { + "type": "int" + }, + "intensity": { + "type": "String" + } + } + }, + "reportDetailStoryLegendCount": "Badge: observation count", + "reportDetailStoryLegendIntensity": "Icon: group maximum intensity", + "reportDetailStoryObservationGroup": "{count} observations, group maximum intensity {intensity}, representative observation location {location}", + "reportDetailStorySingleObservation": "{location}, intensity {intensity}, one observation", + "@reportDetailStoryObservationGroup": { + "description": "Spoken label for a Story cluster. Count is the number of source observation records. Location is the representative observation location.", + "placeholders": { + "count": { + "type": "int" + }, + "intensity": { + "type": "String" + }, + "location": { + "type": "String" + } + } + }, + "@reportDetailStorySingleObservation": { + "description": "Spoken label for a single Story observation.", + "placeholders": { + "location": { + "type": "String" + }, + "intensity": { + "type": "String" + } + } + }, + "reportDetailSharePreview": "Preview share card", + "@reportDetailSharePreview": { + "description": "Button in the earthquake report detail that opens the sharing preview." + }, + "reportDetailShareRichterScale": "Richter scale", + "@reportDetailShareRichterScale": { + "description": "Caption below the magnitude value in the 4:5 artwork." + }, + "reportDetailShareObservedIntensity": "Observed intensity", + "@reportDetailShareObservedIntensity": { + "description": "Caption below the maximum intensity in the 4:5 artwork." + }, + "reportDetailShareKilometers": "km", + "@reportDetailShareKilometers": { + "description": "Unit under the focal depth in the 4:5 artwork." + }, + "reportDetailShareSource": "Source: Taiwan Central Weather Administration (MOTC)", + "@reportDetailShareSource": { + "description": "Attribution for CWA earthquake data in both artworks. Preserve the agency identity." + }, + "reportDetailSharePreparedBy": "Prepared by DPIP", + "@reportDetailSharePreparedBy": { + "description": "Credit for DPIP preparing the earthquake artwork." + }, + "reportDetailStoryAttribution": "{source}\nBasemap: ExpTech Studio", + "@reportDetailStoryAttribution": { + "description": "Story artwork credits. The source placeholder is the localized earthquake data attribution. Preserve ExpTech Studio.", + "placeholders": { + "source": { + "type": "String" + } + } + }, + "reportDetailShareImageInvalid": "This image format cannot be displayed.", + "@reportDetailShareImageInvalid": { + "description": "The app retrieved the official report image but cannot display its format." + }, + "reportDetailImageSaveSettingsRequired": "Allow photo access in Settings, then try saving again.", + "@reportDetailImageSaveSettingsRequired": { + "description": "A gallery permission must be enabled in system settings before retrying." + }, + "reportDetailImageSaveUnavailable": "Saving to photos is unavailable on this device.", + "@reportDetailImageSaveUnavailable": { + "description": "The platform does not offer gallery saving." + }, + "reportDetailImageSaveRestricted": "Your device restricts access to photos.", + "@reportDetailImageSaveRestricted": { + "description": "OS restrictions prevent access to the gallery without an app-level recovery." + }, + "reportDetailImageSaveSettingsFailed": "Could not open Settings. Open your device settings to allow photo access.", + "@reportDetailImageSaveSettingsFailed": { + "description": "The app could not navigate to system settings." } } diff --git a/lib/l10n/app_fil.arb b/lib/l10n/app_fil.arb index c2d5c0d45..3c33c0f91 100644 --- a/lib/l10n/app_fil.arb +++ b/lib/l10n/app_fil.arb @@ -2140,5 +2140,25 @@ "seismometerSampleRate": "Rate ng sampling", "seismometerReset": "I-reset", "seismometerDisclaimer": "Ihiga nang patag ang telepono sa matatag na ibabaw. Limitado ang katumpakan ng sensor ng telepono, kaya sanggunian lang ang pagbasang ito at hindi ito opisyal na intensidad ng CWA.", - "seismometerAlgorithm": "Kinukuwenta gamit ang paraan ng instrumental intensity ng JMA na ginagamit ng ES-Net" + "seismometerAlgorithm": "Kinukuwenta gamit ang paraan ng instrumental intensity ng JMA na ginagamit ng ES-Net", + "reportDetailMaximumIntensityLabel": "Pinakamataas na lakas", + "reportDetailMaximumIntensity": "Pinakamataas na lakas {intensity}", + "reportDetailStoryObservations": "{count} obserbasyon, pinakamataas na lakas {intensity}", + "reportDetailStoryLayoutUnavailable": "Hindi magkasya ang ulat sa Story. Piliin ang 4:5 o buksan ang Mga Detalye.", + "reportDetailStoryLegendCount": "Badge: bilang ng obserbasyon", + "reportDetailStoryLegendIntensity": "Icon: sukdulang tindi sa grupo", + "reportDetailStoryObservationGroup": "{count} obserbasyon, pinakamataas na tindi sa grupo {intensity}, kinatawang lokasyon ng obserbasyon {location}", + "reportDetailStorySingleObservation": "{location}, tindi {intensity}, isang obserbasyon", + "reportDetailSharePreview": "I-preview ang kard na ibabahagi", + "reportDetailShareRichterScale": "Iskalang Richter", + "reportDetailShareObservedIntensity": "Naitalang intensidad", + "reportDetailShareKilometers": "km", + "reportDetailShareSource": "Pinagmulan: Central Weather Administration ng Taiwan (MOTC)", + "reportDetailSharePreparedBy": "Inihanda ng DPIP", + "reportDetailStoryAttribution": "{source}\nBatayang mapa: ExpTech Studio", + "reportDetailShareImageInvalid": "Hindi maipakita ang format ng larawang ito.", + "reportDetailImageSaveSettingsRequired": "Payagan ang access sa mga larawan sa Mga Setting, saka subukang mag-save muli.", + "reportDetailImageSaveUnavailable": "Hindi puwedeng mag-save sa mga larawan sa device na ito.", + "reportDetailImageSaveRestricted": "Nililimitahan ng device mo ang access sa mga larawan.", + "reportDetailImageSaveSettingsFailed": "Hindi mabuksan ang Mga Setting. Buksan ang mga setting ng device para payagan ang access sa mga larawan." } diff --git a/lib/l10n/app_id.arb b/lib/l10n/app_id.arb index ac95fb5d9..662bbfe12 100644 --- a/lib/l10n/app_id.arb +++ b/lib/l10n/app_id.arb @@ -2140,5 +2140,25 @@ "seismometerSampleRate": "Laju sampel", "seismometerReset": "Atur ulang", "seismometerDisclaimer": "Letakkan ponsel rata di permukaan yang stabil. Sensor ponsel tidak presisi, jadi pembacaan ini hanya referensi dan bukan intensitas resmi CWA.", - "seismometerAlgorithm": "Dihitung dengan metode intensitas instrumental JMA yang dipakai ES-Net" + "seismometerAlgorithm": "Dihitung dengan metode intensitas instrumental JMA yang dipakai ES-Net", + "reportDetailMaximumIntensityLabel": "Intensitas maksimum", + "reportDetailMaximumIntensity": "Intensitas maksimum {intensity}", + "reportDetailStoryObservations": "{count} pengamatan, intensitas maksimum {intensity}", + "reportDetailStoryLayoutUnavailable": "Laporan ini tidak muat dalam Story. Pilih 4:5 atau buka Detail.", + "reportDetailStoryLegendCount": "Lencana: jumlah pengamatan", + "reportDetailStoryLegendIntensity": "Ikon: intensitas tertinggi grup", + "reportDetailStoryObservationGroup": "{count} pengamatan, intensitas tertinggi di grup {intensity}, lokasi pengamatan perwakilan {location}", + "reportDetailStorySingleObservation": "{location}, intensitas {intensity}, satu pengamatan", + "reportDetailSharePreview": "Pratinjau kartu berbagi", + "reportDetailShareRichterScale": "Skala Richter", + "reportDetailShareObservedIntensity": "Intensitas teramati", + "reportDetailShareKilometers": "km", + "reportDetailShareSource": "Sumber: Administrasi Cuaca Pusat Taiwan (MOTC)", + "reportDetailSharePreparedBy": "Disusun oleh DPIP", + "reportDetailStoryAttribution": "{source}\nPeta dasar: ExpTech Studio", + "reportDetailShareImageInvalid": "Format gambar ini tidak dapat ditampilkan.", + "reportDetailImageSaveSettingsRequired": "Izinkan akses foto di Pengaturan, lalu coba simpan lagi.", + "reportDetailImageSaveUnavailable": "Penyimpanan ke galeri tidak tersedia di perangkat ini.", + "reportDetailImageSaveRestricted": "Perangkat Anda membatasi akses ke foto.", + "reportDetailImageSaveSettingsFailed": "Pengaturan tidak dapat dibuka. Buka pengaturan perangkat untuk mengizinkan akses foto." } diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 68d6e3688..818e0affb 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -2140,5 +2140,25 @@ "seismometerSampleRate": "サンプリングレート", "seismometerReset": "リセット", "seismometerDisclaimer": "スマートフォンを安定した平らな面に置いてください。端末のセンサー精度には限界があるため、この値は参考であり、中央気象署が発表する震度ではありません。", - "seismometerAlgorithm": "ES-Net が用いる気象庁の計測震度の方法で計算しています" + "seismometerAlgorithm": "ES-Net が用いる気象庁の計測震度の方法で計算しています", + "reportDetailMaximumIntensityLabel": "最大震度", + "reportDetailMaximumIntensity": "最大震度 {intensity}", + "reportDetailStoryObservations": "観測 {count} 件、グループ内の最大震度 {intensity}", + "reportDetailStoryLayoutUnavailable": "この地震レポートはストーリーに収まりません。4:5 を選ぶか、詳細情報を開いてください。", + "reportDetailStoryLegendCount": "数字バッジ:観測件数", + "reportDetailStoryLegendIntensity": "震度アイコン:グループ内の最大震度", + "reportDetailStoryObservationGroup": "観測 {count} 件、グループ内の最大震度 {intensity}、代表観測地点は{location}", + "reportDetailStorySingleObservation": "{location}、震度 {intensity}、観測1件", + "reportDetailSharePreview": "共有カードをプレビュー", + "reportDetailShareRichterScale": "リヒタースケール", + "reportDetailShareObservedIntensity": "観測震度", + "reportDetailShareKilometers": "km", + "reportDetailShareSource": "出典:台湾交通部中央気象署", + "reportDetailSharePreparedBy": "DPIPが作成", + "reportDetailStoryAttribution": "{source}|ベースマップ:ExpTech Studio", + "reportDetailShareImageInvalid": "この画像形式は表示できません。", + "reportDetailImageSaveSettingsRequired": "設定で写真へのアクセスを許可してから、もう一度保存してください。", + "reportDetailImageSaveUnavailable": "この端末では写真に保存できません。", + "reportDetailImageSaveRestricted": "この端末では写真へのアクセスが制限されています。", + "reportDetailImageSaveSettingsFailed": "設定を開けませんでした。端末の設定を開いて写真へのアクセスを許可してください。" } diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index 78ff85bb3..e687514ae 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -2140,5 +2140,25 @@ "seismometerSampleRate": "샘플링 레이트", "seismometerReset": "초기화", "seismometerDisclaimer": "휴대전화를 단단한 평면에 평평하게 놓으세요. 휴대전화 센서의 정밀도는 제한되어 있어 이 값은 참고용이며, 중앙기상서가 발표하는 진도가 아닙니다.", - "seismometerAlgorithm": "ES-Net에서 쓰는 일본 기상청 계측진도 방법으로 계산합니다" + "seismometerAlgorithm": "ES-Net에서 쓰는 일본 기상청 계측진도 방법으로 계산합니다", + "reportDetailMaximumIntensityLabel": "최대 진도", + "reportDetailMaximumIntensity": "최대 진도 {intensity}", + "reportDetailStoryObservations": "관측 {count}건, 그룹 내 최대 진도 {intensity}", + "reportDetailStoryLayoutUnavailable": "이 보고서를 스토리에 담을 수 없습니다. 4:5를 선택하거나 상세 정보를 확인하세요.", + "reportDetailStoryLegendCount": "숫자 배지: 관측 건수", + "reportDetailStoryLegendIntensity": "진도 아이콘: 그룹 내 최대 진도", + "reportDetailStoryObservationGroup": "관측 {count}건, 그룹 내 최대 진도 {intensity}, 대표 관측 위치는 {location}", + "reportDetailStorySingleObservation": "{location}, 진도 {intensity}, 관측 1건", + "reportDetailSharePreview": "공유 카드 미리보기", + "reportDetailShareRichterScale": "리히터 규모", + "reportDetailShareObservedIntensity": "관측 진도", + "reportDetailShareKilometers": "km", + "reportDetailShareSource": "출처: 대만 교통부 중앙기상서", + "reportDetailSharePreparedBy": "DPIP에서 정리", + "reportDetailStoryAttribution": "{source} | 배경 지도: ExpTech Studio", + "reportDetailShareImageInvalid": "이 이미지 형식은 표시할 수 없습니다.", + "reportDetailImageSaveSettingsRequired": "설정에서 사진 접근을 허용한 뒤 다시 저장해 주세요.", + "reportDetailImageSaveUnavailable": "이 기기에서는 사진에 저장할 수 없습니다.", + "reportDetailImageSaveRestricted": "이 기기에서는 사진 접근이 제한되어 있습니다.", + "reportDetailImageSaveSettingsFailed": "설정을 열 수 없습니다. 기기 설정을 열어 사진 접근을 허용해 주세요." } diff --git a/lib/l10n/app_th.arb b/lib/l10n/app_th.arb index 65eb0abf8..010bfd538 100644 --- a/lib/l10n/app_th.arb +++ b/lib/l10n/app_th.arb @@ -2140,5 +2140,25 @@ "seismometerSampleRate": "อัตราการเก็บตัวอย่าง", "seismometerReset": "รีเซ็ต", "seismometerDisclaimer": "วางโทรศัพท์ราบลงบนพื้นผิวที่มั่นคง เซ็นเซอร์ของโทรศัพท์มีความละเอียดจำกัด ค่านี้ใช้ประกอบการพิจารณาเท่านั้น ไม่ใช่ความรุนแรงอย่างเป็นทางการของ CWA", - "seismometerAlgorithm": "คำนวณด้วยวิธีความรุนแรงที่วัดด้วยเครื่องมือของ JMA ซึ่ง ES-Net ใช้" + "seismometerAlgorithm": "คำนวณด้วยวิธีความรุนแรงที่วัดด้วยเครื่องมือของ JMA ซึ่ง ES-Net ใช้", + "reportDetailMaximumIntensityLabel": "ความเข้มสูงสุด", + "reportDetailMaximumIntensity": "ความเข้มสูงสุด {intensity}", + "reportDetailStoryObservations": "การสังเกต {count} รายการ ความเข้มสูงสุดในกลุ่ม {intensity}", + "reportDetailStoryLayoutUnavailable": "ไม่สามารถจัดรายงานนี้ลงในสตอรี่ได้ เลือก 4:5 หรือเปิดรายละเอียด", + "reportDetailStoryLegendCount": "ป้ายเลข: จำนวนการสังเกต", + "reportDetailStoryLegendIntensity": "ไอคอน: ความรุนแรงสูงสุดในกลุ่ม", + "reportDetailStoryObservationGroup": "การสังเกต {count} รายการ ระดับความรุนแรงสูงสุดในกลุ่ม {intensity} จุดสังเกตตัวแทนที่ {location}", + "reportDetailStorySingleObservation": "{location} ระดับความรุนแรง {intensity} การสังเกตหนึ่งรายการ", + "reportDetailSharePreview": "ดูตัวอย่างการ์ดสำหรับแชร์", + "reportDetailShareRichterScale": "มาตราริกเตอร์", + "reportDetailShareObservedIntensity": "ความรุนแรงที่ตรวจวัดได้", + "reportDetailShareKilometers": "กม.", + "reportDetailShareSource": "แหล่งข้อมูล: สำนักอุตุนิยมวิทยากลางไต้หวัน (MOTC)", + "reportDetailSharePreparedBy": "จัดทำโดย DPIP", + "reportDetailStoryAttribution": "{source}\nแผนที่ฐาน: ExpTech Studio", + "reportDetailShareImageInvalid": "ไม่สามารถแสดงรูปภาพรูปแบบนี้ได้", + "reportDetailImageSaveSettingsRequired": "อนุญาตให้เข้าถึงรูปภาพในการตั้งค่า แล้วลองบันทึกอีกครั้ง", + "reportDetailImageSaveUnavailable": "อุปกรณ์นี้ไม่รองรับการบันทึกลงในคลังรูปภาพ", + "reportDetailImageSaveRestricted": "อุปกรณ์ของคุณจำกัดการเข้าถึงรูปภาพ", + "reportDetailImageSaveSettingsFailed": "เปิดการตั้งค่าไม่ได้ โปรดเปิดการตั้งค่าของอุปกรณ์เพื่ออนุญาตให้เข้าถึงรูปภาพ" } diff --git a/lib/l10n/app_vi.arb b/lib/l10n/app_vi.arb index 8b66d3657..baf230af5 100644 --- a/lib/l10n/app_vi.arb +++ b/lib/l10n/app_vi.arb @@ -2140,5 +2140,25 @@ "seismometerSampleRate": "Tốc độ lấy mẫu", "seismometerReset": "Đặt lại", "seismometerDisclaimer": "Đặt điện thoại nằm phẳng trên mặt phẳng vững. Cảm biến điện thoại có độ chính xác hạn chế, nên kết quả chỉ để tham khảo và không phải cường độ chính thức của CWA.", - "seismometerAlgorithm": "Tính bằng phương pháp cường độ đo bằng máy của JMA mà ES-Net dùng" + "seismometerAlgorithm": "Tính bằng phương pháp cường độ đo bằng máy của JMA mà ES-Net dùng", + "reportDetailMaximumIntensityLabel": "Cường độ tối đa", + "reportDetailMaximumIntensity": "Cường độ tối đa {intensity}", + "reportDetailStoryObservations": "{count} quan sát, cường độ tối đa trong nhóm {intensity}", + "reportDetailStoryLayoutUnavailable": "Báo cáo này không vừa với Story. Hãy chọn 4:5 hoặc mở Chi tiết.", + "reportDetailStoryLegendCount": "Huy hiệu: số lượt quan sát", + "reportDetailStoryLegendIntensity": "Biểu tượng: cường độ đỉnh nhóm", + "reportDetailStoryObservationGroup": "{count} lượt quan sát, cường độ cao nhất trong nhóm {intensity}, địa điểm quan sát đại diện là {location}", + "reportDetailStorySingleObservation": "{location}, cường độ {intensity}, một lượt quan sát", + "reportDetailSharePreview": "Xem trước thẻ chia sẻ", + "reportDetailShareRichterScale": "Thang Richter", + "reportDetailShareObservedIntensity": "Cường độ quan trắc", + "reportDetailShareKilometers": "km", + "reportDetailShareSource": "Nguồn: Cơ quan Khí tượng Trung ương Đài Loan (MOTC)", + "reportDetailSharePreparedBy": "Do DPIP tổng hợp", + "reportDetailStoryAttribution": "{source}\nBản đồ nền: ExpTech Studio", + "reportDetailShareImageInvalid": "Không thể hiển thị định dạng ảnh này.", + "reportDetailImageSaveSettingsRequired": "Cho phép truy cập ảnh trong Cài đặt rồi thử lưu lại.", + "reportDetailImageSaveUnavailable": "Thiết bị này không hỗ trợ lưu vào thư viện ảnh.", + "reportDetailImageSaveRestricted": "Thiết bị của bạn hạn chế quyền truy cập ảnh.", + "reportDetailImageSaveSettingsFailed": "Không thể mở Cài đặt. Hãy mở cài đặt thiết bị để cho phép truy cập ảnh." } diff --git a/lib/l10n/app_yue.arb b/lib/l10n/app_yue.arb index 0ea250dae..8e869afed 100644 --- a/lib/l10n/app_yue.arb +++ b/lib/l10n/app_yue.arb @@ -2140,5 +2140,25 @@ "seismometerSampleRate": "取樣率", "seismometerReset": "重設", "seismometerDisclaimer": "請將手機平放喺穩固嘅平面上面。手機感測器精度有限,量測結果只供參考,唔代表中央氣象署發布嘅震度。", - "seismometerAlgorithm": "用 ES-Net 嗰套 JMA 計測震度演算法計" + "seismometerAlgorithm": "用 ES-Net 嗰套 JMA 計測震度演算法計", + "reportDetailMaximumIntensityLabel": "最大震度", + "reportDetailMaximumIntensity": "最大震度 {intensity}", + "reportDetailStoryObservations": "{count} 筆觀測,組內最大震度 {intensity}", + "reportDetailStoryLayoutUnavailable": "呢份報告放唔入 Story。請揀 4:5 或開啟詳細資訊。", + "reportDetailStoryLegendCount": "數字徽章:觀測筆數", + "reportDetailStoryLegendIntensity": "震度圖示:組內最大震度", + "reportDetailStoryObservationGroup": "{count} 筆觀測,組內最大震度 {intensity},代表觀測地點係{location}", + "reportDetailStorySingleObservation": "{location},震度 {intensity},一筆觀測", + "reportDetailSharePreview": "預覽分享卡", + "reportDetailShareRichterScale": "黎克特制", + "reportDetailShareObservedIntensity": "觀測烈度", + "reportDetailShareKilometers": "公里", + "reportDetailShareSource": "資料來源:台灣交通部中央氣象署", + "reportDetailSharePreparedBy": "由 DPIP 整理", + "reportDetailStoryAttribution": "{source}|底圖:ExpTech Studio", + "reportDetailShareImageInvalid": "顯示唔到呢種圖片格式。", + "reportDetailImageSaveSettingsRequired": "請喺設定允許取用相片,再試儲存。", + "reportDetailImageSaveUnavailable": "呢部裝置唔支援儲存到相簿。", + "reportDetailImageSaveRestricted": "裝置限制咗相片存取權限。", + "reportDetailImageSaveSettingsFailed": "開唔到設定。請開啟裝置設定,允許取用相片。" } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 6e511473c..335ceb16d 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -2132,5 +2132,25 @@ "seismometerSampleRate": "取樣率", "seismometerReset": "重設", "seismometerDisclaimer": "請將手機平放在穩固的平面上。手機感測器精度有限,量測結果僅供參考,不代表中央氣象署發布的震度。", - "seismometerAlgorithm": "依 ES-Net 的 JMA 計測震度演算法計算" + "seismometerAlgorithm": "依 ES-Net 的 JMA 計測震度演算法計算", + "reportDetailMaximumIntensityLabel": "最大震度", + "reportDetailMaximumIntensity": "最大震度 {intensity}", + "reportDetailStoryObservations": "{count} 筆觀測,群內最大震度 {intensity}", + "reportDetailStoryLayoutUnavailable": "這份報告無法排入 Story。請切換至 4:5 或展開詳細資訊。", + "reportDetailStoryLegendCount": "數字徽章:觀測筆數", + "reportDetailStoryLegendIntensity": "震度圖示:群內最大震度", + "reportDetailStoryObservationGroup": "{count} 筆觀測,群內最大震度 {intensity},代表觀測地點為{location}", + "reportDetailStorySingleObservation": "{location},震度 {intensity},一筆觀測", + "reportDetailSharePreview": "預覽分享卡片", + "reportDetailShareRichterScale": "芮氏規模", + "reportDetailShareObservedIntensity": "觀測震度", + "reportDetailShareKilometers": "公里", + "reportDetailShareSource": "資料來源:交通部中央氣象署", + "reportDetailSharePreparedBy": "由 DPIP 整理呈現", + "reportDetailStoryAttribution": "{source}|底圖:ExpTech Studio", + "reportDetailShareImageInvalid": "無法顯示此圖片格式。", + "reportDetailImageSaveSettingsRequired": "請在設定中允許取用照片,再試一次儲存。", + "reportDetailImageSaveUnavailable": "這部裝置不支援儲存到相簿。", + "reportDetailImageSaveRestricted": "這部裝置限制了相簿取用權限。", + "reportDetailImageSaveSettingsFailed": "無法開啟設定。請開啟裝置設定,允許取用照片。" } diff --git a/lib/l10n/app_zh_Hans.arb b/lib/l10n/app_zh_Hans.arb index a3b453ef7..895469e62 100644 --- a/lib/l10n/app_zh_Hans.arb +++ b/lib/l10n/app_zh_Hans.arb @@ -2140,5 +2140,25 @@ "seismometerSampleRate": "采样率", "seismometerReset": "重置", "seismometerDisclaimer": "请将手机平放在稳固的平面上。手机传感器精度有限,测量结果仅供参考,不代表中央气象署发布的震度。", - "seismometerAlgorithm": "依 ES-Net 的 JMA 计测震度算法计算" + "seismometerAlgorithm": "依 ES-Net 的 JMA 计测震度算法计算", + "reportDetailMaximumIntensityLabel": "最大震度", + "reportDetailMaximumIntensity": "最大震度 {intensity}", + "reportDetailStoryObservations": "{count} 条观测,组内最大震度 {intensity}", + "reportDetailStoryLayoutUnavailable": "此报告无法排入 Story。请选择 4:5 或展开详细信息。", + "reportDetailStoryLegendCount": "数字徽章:观测条数", + "reportDetailStoryLegendIntensity": "烈度图标:组内最大烈度", + "reportDetailStoryObservationGroup": "{count} 条观测,组内最大烈度 {intensity},代表观测地点为{location}", + "reportDetailStorySingleObservation": "{location},烈度 {intensity},一条观测", + "reportDetailSharePreview": "预览分享卡片", + "reportDetailShareRichterScale": "里氏震级", + "reportDetailShareObservedIntensity": "观测烈度", + "reportDetailShareKilometers": "公里", + "reportDetailShareSource": "数据来源:台湾交通部中央气象署", + "reportDetailSharePreparedBy": "由 DPIP 整理呈现", + "reportDetailStoryAttribution": "{source}|底图:ExpTech Studio", + "reportDetailShareImageInvalid": "无法显示此图片格式。", + "reportDetailImageSaveSettingsRequired": "请在设置中允许访问照片,然后重新保存。", + "reportDetailImageSaveUnavailable": "此设备不支持保存到相册。", + "reportDetailImageSaveRestricted": "设备限制了照片访问权限。", + "reportDetailImageSaveSettingsFailed": "无法打开设置。请打开设备设置以允许访问照片。" } diff --git a/lib/l10n/app_zh_Hant_HK.arb b/lib/l10n/app_zh_Hant_HK.arb index 0decca079..738c80ba0 100644 --- a/lib/l10n/app_zh_Hant_HK.arb +++ b/lib/l10n/app_zh_Hant_HK.arb @@ -2140,5 +2140,25 @@ "seismometerSampleRate": "取樣率", "seismometerReset": "重設", "seismometerDisclaimer": "請將手機平放在穩固的平面上。手機感測器精度有限,量測結果僅供參考,並不代表中央氣象署發布的震度。", - "seismometerAlgorithm": "依 ES-Net 的 JMA 計測震度演算法計算" + "seismometerAlgorithm": "依 ES-Net 的 JMA 計測震度演算法計算", + "reportDetailMaximumIntensityLabel": "最大震度", + "reportDetailMaximumIntensity": "最大震度 {intensity}", + "reportDetailStoryObservations": "{count} 筆觀測,群內最大震度 {intensity}", + "reportDetailStoryLayoutUnavailable": "這份報告無法排入 Story。請切換至 4:5 或展開詳細資訊。", + "reportDetailStoryLegendCount": "數字徽章:觀測筆數", + "reportDetailStoryLegendIntensity": "震度圖示:組內最大震度", + "reportDetailStoryObservationGroup": "{count} 筆觀測,組內最大震度 {intensity},代表觀測地點為{location}", + "reportDetailStorySingleObservation": "{location},震度 {intensity},一筆觀測", + "reportDetailSharePreview": "預覽分享卡片", + "reportDetailShareRichterScale": "黎克特制", + "reportDetailShareObservedIntensity": "觀測烈度", + "reportDetailShareKilometers": "公里", + "reportDetailShareSource": "資料來源:台灣交通部中央氣象署", + "reportDetailSharePreparedBy": "由 DPIP 整理呈現", + "reportDetailStoryAttribution": "{source}|底圖:ExpTech Studio", + "reportDetailShareImageInvalid": "無法顯示此圖片格式。", + "reportDetailImageSaveSettingsRequired": "請在設定中允許取用相片,再試儲存。", + "reportDetailImageSaveUnavailable": "此裝置不支援儲存至相簿。", + "reportDetailImageSaveRestricted": "裝置限制了相片存取權限。", + "reportDetailImageSaveSettingsFailed": "無法開啟設定。請開啟裝置設定以允許取用相片。" } diff --git a/lib/l10n/app_zh_TW.arb b/lib/l10n/app_zh_TW.arb index b2452a8fc..934c58537 100644 --- a/lib/l10n/app_zh_TW.arb +++ b/lib/l10n/app_zh_TW.arb @@ -2140,5 +2140,25 @@ "seismometerSampleRate": "取樣率", "seismometerReset": "重設", "seismometerDisclaimer": "請將手機平放在穩固的平面上。手機感測器精度有限,量測結果僅供參考,不代表中央氣象署發布的震度。", - "seismometerAlgorithm": "依 ES-Net 的 JMA 計測震度演算法計算" + "seismometerAlgorithm": "依 ES-Net 的 JMA 計測震度演算法計算", + "reportDetailMaximumIntensityLabel": "最大震度", + "reportDetailMaximumIntensity": "最大震度 {intensity}", + "reportDetailStoryObservations": "{count} 筆觀測,群內最大震度 {intensity}", + "reportDetailStoryLayoutUnavailable": "這份報告無法排入 Story。請切換至 4:5 或展開詳細資訊。", + "reportDetailStoryLegendCount": "數字徽章:觀測筆數", + "reportDetailStoryLegendIntensity": "震度圖示:群內最大震度", + "reportDetailStoryObservationGroup": "{count} 筆觀測,群內最大震度 {intensity},代表觀測地點為{location}", + "reportDetailStorySingleObservation": "{location},震度 {intensity},一筆觀測", + "reportDetailSharePreview": "預覽分享卡片", + "reportDetailShareRichterScale": "芮氏規模", + "reportDetailShareObservedIntensity": "觀測震度", + "reportDetailShareKilometers": "公里", + "reportDetailShareSource": "資料來源:交通部中央氣象署", + "reportDetailSharePreparedBy": "由 DPIP 整理呈現", + "reportDetailStoryAttribution": "{source}|底圖:ExpTech Studio", + "reportDetailShareImageInvalid": "無法顯示此圖片格式。", + "reportDetailImageSaveSettingsRequired": "請在設定中允許取用照片,再試一次儲存。", + "reportDetailImageSaveUnavailable": "這部裝置不支援儲存到相簿。", + "reportDetailImageSaveRestricted": "這部裝置限制了相簿取用權限。", + "reportDetailImageSaveSettingsFailed": "無法開啟設定。請開啟裝置設定,允許取用照片。" } diff --git a/lib/l10n/gen/app_localizations.dart b/lib/l10n/gen/app_localizations.dart index 2554f1abb..393c20db4 100644 --- a/lib/l10n/gen/app_localizations.dart +++ b/lib/l10n/gen/app_localizations.dart @@ -6947,6 +6947,130 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Computed with the JMA instrumental intensity method used by ES-Net'** String get seismometerAlgorithm; + + /// No description provided for @reportDetailMaximumIntensityLabel. + /// + /// In en, this message translates to: + /// **'Maximum intensity'** + String get reportDetailMaximumIntensityLabel; + + /// Spoken or plain text label and value for observed maximum intensity. + /// + /// In en, this message translates to: + /// **'Maximum intensity {intensity}'** + String reportDetailMaximumIntensity(String intensity); + + /// Accessible label for one Story marker, with the number of observations and its highest observed intensity. + /// + /// In en, this message translates to: + /// **'{count, plural, one{1 observation, intensity {intensity}} other{{count} observations, maximum intensity {intensity}}}'** + String reportDetailStoryObservations(int count, String intensity); + + /// No description provided for @reportDetailStoryLayoutUnavailable. + /// + /// In en, this message translates to: + /// **'This report cannot fit in a Story. Choose 4:5 or open Details.'** + String get reportDetailStoryLayoutUnavailable; + + /// No description provided for @reportDetailStoryLegendCount. + /// + /// In en, this message translates to: + /// **'Badge: observation count'** + String get reportDetailStoryLegendCount; + + /// No description provided for @reportDetailStoryLegendIntensity. + /// + /// In en, this message translates to: + /// **'Icon: group maximum intensity'** + String get reportDetailStoryLegendIntensity; + + /// Spoken label for a Story cluster. Count is the number of source observation records. Location is the representative observation location. + /// + /// In en, this message translates to: + /// **'{count} observations, group maximum intensity {intensity}, representative observation location {location}'** + String reportDetailStoryObservationGroup( + int count, + String intensity, + String location, + ); + + /// Spoken label for a single Story observation. + /// + /// In en, this message translates to: + /// **'{location}, intensity {intensity}, one observation'** + String reportDetailStorySingleObservation(String location, String intensity); + + /// Button in the earthquake report detail that opens the sharing preview. + /// + /// In en, this message translates to: + /// **'Preview share card'** + String get reportDetailSharePreview; + + /// Caption below the magnitude value in the 4:5 artwork. + /// + /// In en, this message translates to: + /// **'Richter scale'** + String get reportDetailShareRichterScale; + + /// Caption below the maximum intensity in the 4:5 artwork. + /// + /// In en, this message translates to: + /// **'Observed intensity'** + String get reportDetailShareObservedIntensity; + + /// Unit under the focal depth in the 4:5 artwork. + /// + /// In en, this message translates to: + /// **'km'** + String get reportDetailShareKilometers; + + /// Attribution for CWA earthquake data in both artworks. Preserve the agency identity. + /// + /// In en, this message translates to: + /// **'Source: Taiwan Central Weather Administration (MOTC)'** + String get reportDetailShareSource; + + /// Credit for DPIP preparing the earthquake artwork. + /// + /// In en, this message translates to: + /// **'Prepared by DPIP'** + String get reportDetailSharePreparedBy; + + /// Story artwork credits. The source placeholder is the localized earthquake data attribution. Preserve ExpTech Studio. + /// + /// In en, this message translates to: + /// **'{source}\nBasemap: ExpTech Studio'** + String reportDetailStoryAttribution(String source); + + /// The app retrieved the official report image but cannot display its format. + /// + /// In en, this message translates to: + /// **'This image format cannot be displayed.'** + String get reportDetailShareImageInvalid; + + /// A gallery permission must be enabled in system settings before retrying. + /// + /// In en, this message translates to: + /// **'Allow photo access in Settings, then try saving again.'** + String get reportDetailImageSaveSettingsRequired; + + /// The platform does not offer gallery saving. + /// + /// In en, this message translates to: + /// **'Saving to photos is unavailable on this device.'** + String get reportDetailImageSaveUnavailable; + + /// OS restrictions prevent access to the gallery without an app-level recovery. + /// + /// In en, this message translates to: + /// **'Your device restricts access to photos.'** + String get reportDetailImageSaveRestricted; + + /// The app could not navigate to system settings. + /// + /// In en, this message translates to: + /// **'Could not open Settings. Open your device settings to allow photo access.'** + String get reportDetailImageSaveSettingsFailed; } class _AppLocalizationsDelegate diff --git a/lib/l10n/gen/app_localizations_en.dart b/lib/l10n/gen/app_localizations_en.dart index 3e8da7f9f..92c55e812 100644 --- a/lib/l10n/gen/app_localizations_en.dart +++ b/lib/l10n/gen/app_localizations_en.dart @@ -3715,4 +3715,92 @@ class AppLocalizationsEn extends AppLocalizations { @override String get seismometerAlgorithm => 'Computed with the JMA instrumental intensity method used by ES-Net'; + + @override + String get reportDetailMaximumIntensityLabel => 'Maximum intensity'; + + @override + String reportDetailMaximumIntensity(String intensity) { + return 'Maximum intensity $intensity'; + } + + @override + String reportDetailStoryObservations(int count, String intensity) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: '$count observations, maximum intensity $intensity', + one: '1 observation, intensity $intensity', + ); + return '$_temp0'; + } + + @override + String get reportDetailStoryLayoutUnavailable => + 'This report cannot fit in a Story. Choose 4:5 or open Details.'; + + @override + String get reportDetailStoryLegendCount => 'Badge: observation count'; + + @override + String get reportDetailStoryLegendIntensity => + 'Icon: group maximum intensity'; + + @override + String reportDetailStoryObservationGroup( + int count, + String intensity, + String location, + ) { + return '$count observations, group maximum intensity $intensity, representative observation location $location'; + } + + @override + String reportDetailStorySingleObservation(String location, String intensity) { + return '$location, intensity $intensity, one observation'; + } + + @override + String get reportDetailSharePreview => 'Preview share card'; + + @override + String get reportDetailShareRichterScale => 'Richter scale'; + + @override + String get reportDetailShareObservedIntensity => 'Observed intensity'; + + @override + String get reportDetailShareKilometers => 'km'; + + @override + String get reportDetailShareSource => + 'Source: Taiwan Central Weather Administration (MOTC)'; + + @override + String get reportDetailSharePreparedBy => 'Prepared by DPIP'; + + @override + String reportDetailStoryAttribution(String source) { + return '$source\nBasemap: ExpTech Studio'; + } + + @override + String get reportDetailShareImageInvalid => + 'This image format cannot be displayed.'; + + @override + String get reportDetailImageSaveSettingsRequired => + 'Allow photo access in Settings, then try saving again.'; + + @override + String get reportDetailImageSaveUnavailable => + 'Saving to photos is unavailable on this device.'; + + @override + String get reportDetailImageSaveRestricted => + 'Your device restricts access to photos.'; + + @override + String get reportDetailImageSaveSettingsFailed => + 'Could not open Settings. Open your device settings to allow photo access.'; } diff --git a/lib/l10n/gen/app_localizations_fil.dart b/lib/l10n/gen/app_localizations_fil.dart index 4cafad404..85f19d466 100644 --- a/lib/l10n/gen/app_localizations_fil.dart +++ b/lib/l10n/gen/app_localizations_fil.dart @@ -3738,4 +3738,86 @@ class AppLocalizationsFil extends AppLocalizations { @override String get seismometerAlgorithm => 'Kinukuwenta gamit ang paraan ng instrumental intensity ng JMA na ginagamit ng ES-Net'; + + @override + String get reportDetailMaximumIntensityLabel => 'Pinakamataas na lakas'; + + @override + String reportDetailMaximumIntensity(String intensity) { + return 'Pinakamataas na lakas $intensity'; + } + + @override + String reportDetailStoryObservations(int count, String intensity) { + return '$count obserbasyon, pinakamataas na lakas $intensity'; + } + + @override + String get reportDetailStoryLayoutUnavailable => + 'Hindi magkasya ang ulat sa Story. Piliin ang 4:5 o buksan ang Mga Detalye.'; + + @override + String get reportDetailStoryLegendCount => 'Badge: bilang ng obserbasyon'; + + @override + String get reportDetailStoryLegendIntensity => + 'Icon: sukdulang tindi sa grupo'; + + @override + String reportDetailStoryObservationGroup( + int count, + String intensity, + String location, + ) { + return '$count obserbasyon, pinakamataas na tindi sa grupo $intensity, kinatawang lokasyon ng obserbasyon $location'; + } + + @override + String reportDetailStorySingleObservation(String location, String intensity) { + return '$location, tindi $intensity, isang obserbasyon'; + } + + @override + String get reportDetailSharePreview => 'I-preview ang kard na ibabahagi'; + + @override + String get reportDetailShareRichterScale => 'Iskalang Richter'; + + @override + String get reportDetailShareObservedIntensity => 'Naitalang intensidad'; + + @override + String get reportDetailShareKilometers => 'km'; + + @override + String get reportDetailShareSource => + 'Pinagmulan: Central Weather Administration ng Taiwan (MOTC)'; + + @override + String get reportDetailSharePreparedBy => 'Inihanda ng DPIP'; + + @override + String reportDetailStoryAttribution(String source) { + return '$source\nBatayang mapa: ExpTech Studio'; + } + + @override + String get reportDetailShareImageInvalid => + 'Hindi maipakita ang format ng larawang ito.'; + + @override + String get reportDetailImageSaveSettingsRequired => + 'Payagan ang access sa mga larawan sa Mga Setting, saka subukang mag-save muli.'; + + @override + String get reportDetailImageSaveUnavailable => + 'Hindi puwedeng mag-save sa mga larawan sa device na ito.'; + + @override + String get reportDetailImageSaveRestricted => + 'Nililimitahan ng device mo ang access sa mga larawan.'; + + @override + String get reportDetailImageSaveSettingsFailed => + 'Hindi mabuksan ang Mga Setting. Buksan ang mga setting ng device para payagan ang access sa mga larawan.'; } diff --git a/lib/l10n/gen/app_localizations_id.dart b/lib/l10n/gen/app_localizations_id.dart index fef76ac2e..8160da6e5 100644 --- a/lib/l10n/gen/app_localizations_id.dart +++ b/lib/l10n/gen/app_localizations_id.dart @@ -3729,4 +3729,86 @@ class AppLocalizationsId extends AppLocalizations { @override String get seismometerAlgorithm => 'Dihitung dengan metode intensitas instrumental JMA yang dipakai ES-Net'; + + @override + String get reportDetailMaximumIntensityLabel => 'Intensitas maksimum'; + + @override + String reportDetailMaximumIntensity(String intensity) { + return 'Intensitas maksimum $intensity'; + } + + @override + String reportDetailStoryObservations(int count, String intensity) { + return '$count pengamatan, intensitas maksimum $intensity'; + } + + @override + String get reportDetailStoryLayoutUnavailable => + 'Laporan ini tidak muat dalam Story. Pilih 4:5 atau buka Detail.'; + + @override + String get reportDetailStoryLegendCount => 'Lencana: jumlah pengamatan'; + + @override + String get reportDetailStoryLegendIntensity => + 'Ikon: intensitas tertinggi grup'; + + @override + String reportDetailStoryObservationGroup( + int count, + String intensity, + String location, + ) { + return '$count pengamatan, intensitas tertinggi di grup $intensity, lokasi pengamatan perwakilan $location'; + } + + @override + String reportDetailStorySingleObservation(String location, String intensity) { + return '$location, intensitas $intensity, satu pengamatan'; + } + + @override + String get reportDetailSharePreview => 'Pratinjau kartu berbagi'; + + @override + String get reportDetailShareRichterScale => 'Skala Richter'; + + @override + String get reportDetailShareObservedIntensity => 'Intensitas teramati'; + + @override + String get reportDetailShareKilometers => 'km'; + + @override + String get reportDetailShareSource => + 'Sumber: Administrasi Cuaca Pusat Taiwan (MOTC)'; + + @override + String get reportDetailSharePreparedBy => 'Disusun oleh DPIP'; + + @override + String reportDetailStoryAttribution(String source) { + return '$source\nPeta dasar: ExpTech Studio'; + } + + @override + String get reportDetailShareImageInvalid => + 'Format gambar ini tidak dapat ditampilkan.'; + + @override + String get reportDetailImageSaveSettingsRequired => + 'Izinkan akses foto di Pengaturan, lalu coba simpan lagi.'; + + @override + String get reportDetailImageSaveUnavailable => + 'Penyimpanan ke galeri tidak tersedia di perangkat ini.'; + + @override + String get reportDetailImageSaveRestricted => + 'Perangkat Anda membatasi akses ke foto.'; + + @override + String get reportDetailImageSaveSettingsFailed => + 'Pengaturan tidak dapat dibuka. Buka pengaturan perangkat untuk mengizinkan akses foto.'; } diff --git a/lib/l10n/gen/app_localizations_ja.dart b/lib/l10n/gen/app_localizations_ja.dart index 09cb50396..84f3658ab 100644 --- a/lib/l10n/gen/app_localizations_ja.dart +++ b/lib/l10n/gen/app_localizations_ja.dart @@ -3641,4 +3641,81 @@ class AppLocalizationsJa extends AppLocalizations { @override String get seismometerAlgorithm => 'ES-Net が用いる気象庁の計測震度の方法で計算しています'; + + @override + String get reportDetailMaximumIntensityLabel => '最大震度'; + + @override + String reportDetailMaximumIntensity(String intensity) { + return '最大震度 $intensity'; + } + + @override + String reportDetailStoryObservations(int count, String intensity) { + return '観測 $count 件、グループ内の最大震度 $intensity'; + } + + @override + String get reportDetailStoryLayoutUnavailable => + 'この地震レポートはストーリーに収まりません。4:5 を選ぶか、詳細情報を開いてください。'; + + @override + String get reportDetailStoryLegendCount => '数字バッジ:観測件数'; + + @override + String get reportDetailStoryLegendIntensity => '震度アイコン:グループ内の最大震度'; + + @override + String reportDetailStoryObservationGroup( + int count, + String intensity, + String location, + ) { + return '観測 $count 件、グループ内の最大震度 $intensity、代表観測地点は$location'; + } + + @override + String reportDetailStorySingleObservation(String location, String intensity) { + return '$location、震度 $intensity、観測1件'; + } + + @override + String get reportDetailSharePreview => '共有カードをプレビュー'; + + @override + String get reportDetailShareRichterScale => 'リヒタースケール'; + + @override + String get reportDetailShareObservedIntensity => '観測震度'; + + @override + String get reportDetailShareKilometers => 'km'; + + @override + String get reportDetailShareSource => '出典:台湾交通部中央気象署'; + + @override + String get reportDetailSharePreparedBy => 'DPIPが作成'; + + @override + String reportDetailStoryAttribution(String source) { + return '$source|ベースマップ:ExpTech Studio'; + } + + @override + String get reportDetailShareImageInvalid => 'この画像形式は表示できません。'; + + @override + String get reportDetailImageSaveSettingsRequired => + '設定で写真へのアクセスを許可してから、もう一度保存してください。'; + + @override + String get reportDetailImageSaveUnavailable => 'この端末では写真に保存できません。'; + + @override + String get reportDetailImageSaveRestricted => 'この端末では写真へのアクセスが制限されています。'; + + @override + String get reportDetailImageSaveSettingsFailed => + '設定を開けませんでした。端末の設定を開いて写真へのアクセスを許可してください。'; } diff --git a/lib/l10n/gen/app_localizations_ko.dart b/lib/l10n/gen/app_localizations_ko.dart index c5fb075bb..4f4f09455 100644 --- a/lib/l10n/gen/app_localizations_ko.dart +++ b/lib/l10n/gen/app_localizations_ko.dart @@ -3643,4 +3643,81 @@ class AppLocalizationsKo extends AppLocalizations { @override String get seismometerAlgorithm => 'ES-Net에서 쓰는 일본 기상청 계측진도 방법으로 계산합니다'; + + @override + String get reportDetailMaximumIntensityLabel => '최대 진도'; + + @override + String reportDetailMaximumIntensity(String intensity) { + return '최대 진도 $intensity'; + } + + @override + String reportDetailStoryObservations(int count, String intensity) { + return '관측 $count건, 그룹 내 최대 진도 $intensity'; + } + + @override + String get reportDetailStoryLayoutUnavailable => + '이 보고서를 스토리에 담을 수 없습니다. 4:5를 선택하거나 상세 정보를 확인하세요.'; + + @override + String get reportDetailStoryLegendCount => '숫자 배지: 관측 건수'; + + @override + String get reportDetailStoryLegendIntensity => '진도 아이콘: 그룹 내 최대 진도'; + + @override + String reportDetailStoryObservationGroup( + int count, + String intensity, + String location, + ) { + return '관측 $count건, 그룹 내 최대 진도 $intensity, 대표 관측 위치는 $location'; + } + + @override + String reportDetailStorySingleObservation(String location, String intensity) { + return '$location, 진도 $intensity, 관측 1건'; + } + + @override + String get reportDetailSharePreview => '공유 카드 미리보기'; + + @override + String get reportDetailShareRichterScale => '리히터 규모'; + + @override + String get reportDetailShareObservedIntensity => '관측 진도'; + + @override + String get reportDetailShareKilometers => 'km'; + + @override + String get reportDetailShareSource => '출처: 대만 교통부 중앙기상서'; + + @override + String get reportDetailSharePreparedBy => 'DPIP에서 정리'; + + @override + String reportDetailStoryAttribution(String source) { + return '$source | 배경 지도: ExpTech Studio'; + } + + @override + String get reportDetailShareImageInvalid => '이 이미지 형식은 표시할 수 없습니다.'; + + @override + String get reportDetailImageSaveSettingsRequired => + '설정에서 사진 접근을 허용한 뒤 다시 저장해 주세요.'; + + @override + String get reportDetailImageSaveUnavailable => '이 기기에서는 사진에 저장할 수 없습니다.'; + + @override + String get reportDetailImageSaveRestricted => '이 기기에서는 사진 접근이 제한되어 있습니다.'; + + @override + String get reportDetailImageSaveSettingsFailed => + '설정을 열 수 없습니다. 기기 설정을 열어 사진 접근을 허용해 주세요.'; } diff --git a/lib/l10n/gen/app_localizations_th.dart b/lib/l10n/gen/app_localizations_th.dart index 46a4b9bc0..80418074a 100644 --- a/lib/l10n/gen/app_localizations_th.dart +++ b/lib/l10n/gen/app_localizations_th.dart @@ -3705,4 +3705,85 @@ class AppLocalizationsTh extends AppLocalizations { @override String get seismometerAlgorithm => 'คำนวณด้วยวิธีความรุนแรงที่วัดด้วยเครื่องมือของ JMA ซึ่ง ES-Net ใช้'; + + @override + String get reportDetailMaximumIntensityLabel => 'ความเข้มสูงสุด'; + + @override + String reportDetailMaximumIntensity(String intensity) { + return 'ความเข้มสูงสุด $intensity'; + } + + @override + String reportDetailStoryObservations(int count, String intensity) { + return 'การสังเกต $count รายการ ความเข้มสูงสุดในกลุ่ม $intensity'; + } + + @override + String get reportDetailStoryLayoutUnavailable => + 'ไม่สามารถจัดรายงานนี้ลงในสตอรี่ได้ เลือก 4:5 หรือเปิดรายละเอียด'; + + @override + String get reportDetailStoryLegendCount => 'ป้ายเลข: จำนวนการสังเกต'; + + @override + String get reportDetailStoryLegendIntensity => + 'ไอคอน: ความรุนแรงสูงสุดในกลุ่ม'; + + @override + String reportDetailStoryObservationGroup( + int count, + String intensity, + String location, + ) { + return 'การสังเกต $count รายการ ระดับความรุนแรงสูงสุดในกลุ่ม $intensity จุดสังเกตตัวแทนที่ $location'; + } + + @override + String reportDetailStorySingleObservation(String location, String intensity) { + return '$location ระดับความรุนแรง $intensity การสังเกตหนึ่งรายการ'; + } + + @override + String get reportDetailSharePreview => 'ดูตัวอย่างการ์ดสำหรับแชร์'; + + @override + String get reportDetailShareRichterScale => 'มาตราริกเตอร์'; + + @override + String get reportDetailShareObservedIntensity => 'ความรุนแรงที่ตรวจวัดได้'; + + @override + String get reportDetailShareKilometers => 'กม.'; + + @override + String get reportDetailShareSource => + 'แหล่งข้อมูล: สำนักอุตุนิยมวิทยากลางไต้หวัน (MOTC)'; + + @override + String get reportDetailSharePreparedBy => 'จัดทำโดย DPIP'; + + @override + String reportDetailStoryAttribution(String source) { + return '$source\nแผนที่ฐาน: ExpTech Studio'; + } + + @override + String get reportDetailShareImageInvalid => 'ไม่สามารถแสดงรูปภาพรูปแบบนี้ได้'; + + @override + String get reportDetailImageSaveSettingsRequired => + 'อนุญาตให้เข้าถึงรูปภาพในการตั้งค่า แล้วลองบันทึกอีกครั้ง'; + + @override + String get reportDetailImageSaveUnavailable => + 'อุปกรณ์นี้ไม่รองรับการบันทึกลงในคลังรูปภาพ'; + + @override + String get reportDetailImageSaveRestricted => + 'อุปกรณ์ของคุณจำกัดการเข้าถึงรูปภาพ'; + + @override + String get reportDetailImageSaveSettingsFailed => + 'เปิดการตั้งค่าไม่ได้ โปรดเปิดการตั้งค่าของอุปกรณ์เพื่ออนุญาตให้เข้าถึงรูปภาพ'; } diff --git a/lib/l10n/gen/app_localizations_vi.dart b/lib/l10n/gen/app_localizations_vi.dart index ab2a86dd5..ded305279 100644 --- a/lib/l10n/gen/app_localizations_vi.dart +++ b/lib/l10n/gen/app_localizations_vi.dart @@ -3718,4 +3718,86 @@ class AppLocalizationsVi extends AppLocalizations { @override String get seismometerAlgorithm => 'Tính bằng phương pháp cường độ đo bằng máy của JMA mà ES-Net dùng'; + + @override + String get reportDetailMaximumIntensityLabel => 'Cường độ tối đa'; + + @override + String reportDetailMaximumIntensity(String intensity) { + return 'Cường độ tối đa $intensity'; + } + + @override + String reportDetailStoryObservations(int count, String intensity) { + return '$count quan sát, cường độ tối đa trong nhóm $intensity'; + } + + @override + String get reportDetailStoryLayoutUnavailable => + 'Báo cáo này không vừa với Story. Hãy chọn 4:5 hoặc mở Chi tiết.'; + + @override + String get reportDetailStoryLegendCount => 'Huy hiệu: số lượt quan sát'; + + @override + String get reportDetailStoryLegendIntensity => + 'Biểu tượng: cường độ đỉnh nhóm'; + + @override + String reportDetailStoryObservationGroup( + int count, + String intensity, + String location, + ) { + return '$count lượt quan sát, cường độ cao nhất trong nhóm $intensity, địa điểm quan sát đại diện là $location'; + } + + @override + String reportDetailStorySingleObservation(String location, String intensity) { + return '$location, cường độ $intensity, một lượt quan sát'; + } + + @override + String get reportDetailSharePreview => 'Xem trước thẻ chia sẻ'; + + @override + String get reportDetailShareRichterScale => 'Thang Richter'; + + @override + String get reportDetailShareObservedIntensity => 'Cường độ quan trắc'; + + @override + String get reportDetailShareKilometers => 'km'; + + @override + String get reportDetailShareSource => + 'Nguồn: Cơ quan Khí tượng Trung ương Đài Loan (MOTC)'; + + @override + String get reportDetailSharePreparedBy => 'Do DPIP tổng hợp'; + + @override + String reportDetailStoryAttribution(String source) { + return '$source\nBản đồ nền: ExpTech Studio'; + } + + @override + String get reportDetailShareImageInvalid => + 'Không thể hiển thị định dạng ảnh này.'; + + @override + String get reportDetailImageSaveSettingsRequired => + 'Cho phép truy cập ảnh trong Cài đặt rồi thử lưu lại.'; + + @override + String get reportDetailImageSaveUnavailable => + 'Thiết bị này không hỗ trợ lưu vào thư viện ảnh.'; + + @override + String get reportDetailImageSaveRestricted => + 'Thiết bị của bạn hạn chế quyền truy cập ảnh.'; + + @override + String get reportDetailImageSaveSettingsFailed => + 'Không thể mở Cài đặt. Hãy mở cài đặt thiết bị để cho phép truy cập ảnh.'; } diff --git a/lib/l10n/gen/app_localizations_yue.dart b/lib/l10n/gen/app_localizations_yue.dart index 9129a7ba9..f0c762f08 100644 --- a/lib/l10n/gen/app_localizations_yue.dart +++ b/lib/l10n/gen/app_localizations_yue.dart @@ -3618,4 +3618,79 @@ class AppLocalizationsYue extends AppLocalizations { @override String get seismometerAlgorithm => '用 ES-Net 嗰套 JMA 計測震度演算法計'; + + @override + String get reportDetailMaximumIntensityLabel => '最大震度'; + + @override + String reportDetailMaximumIntensity(String intensity) { + return '最大震度 $intensity'; + } + + @override + String reportDetailStoryObservations(int count, String intensity) { + return '$count 筆觀測,組內最大震度 $intensity'; + } + + @override + String get reportDetailStoryLayoutUnavailable => + '呢份報告放唔入 Story。請揀 4:5 或開啟詳細資訊。'; + + @override + String get reportDetailStoryLegendCount => '數字徽章:觀測筆數'; + + @override + String get reportDetailStoryLegendIntensity => '震度圖示:組內最大震度'; + + @override + String reportDetailStoryObservationGroup( + int count, + String intensity, + String location, + ) { + return '$count 筆觀測,組內最大震度 $intensity,代表觀測地點係$location'; + } + + @override + String reportDetailStorySingleObservation(String location, String intensity) { + return '$location,震度 $intensity,一筆觀測'; + } + + @override + String get reportDetailSharePreview => '預覽分享卡'; + + @override + String get reportDetailShareRichterScale => '黎克特制'; + + @override + String get reportDetailShareObservedIntensity => '觀測烈度'; + + @override + String get reportDetailShareKilometers => '公里'; + + @override + String get reportDetailShareSource => '資料來源:台灣交通部中央氣象署'; + + @override + String get reportDetailSharePreparedBy => '由 DPIP 整理'; + + @override + String reportDetailStoryAttribution(String source) { + return '$source|底圖:ExpTech Studio'; + } + + @override + String get reportDetailShareImageInvalid => '顯示唔到呢種圖片格式。'; + + @override + String get reportDetailImageSaveSettingsRequired => '請喺設定允許取用相片,再試儲存。'; + + @override + String get reportDetailImageSaveUnavailable => '呢部裝置唔支援儲存到相簿。'; + + @override + String get reportDetailImageSaveRestricted => '裝置限制咗相片存取權限。'; + + @override + String get reportDetailImageSaveSettingsFailed => '開唔到設定。請開啟裝置設定,允許取用相片。'; } diff --git a/lib/l10n/gen/app_localizations_zh.dart b/lib/l10n/gen/app_localizations_zh.dart index 4aad366ca..09ca99b9a 100644 --- a/lib/l10n/gen/app_localizations_zh.dart +++ b/lib/l10n/gen/app_localizations_zh.dart @@ -3618,6 +3618,81 @@ class AppLocalizationsZh extends AppLocalizations { @override String get seismometerAlgorithm => '依 ES-Net 的 JMA 計測震度演算法計算'; + + @override + String get reportDetailMaximumIntensityLabel => '最大震度'; + + @override + String reportDetailMaximumIntensity(String intensity) { + return '最大震度 $intensity'; + } + + @override + String reportDetailStoryObservations(int count, String intensity) { + return '$count 筆觀測,群內最大震度 $intensity'; + } + + @override + String get reportDetailStoryLayoutUnavailable => + '這份報告無法排入 Story。請切換至 4:5 或展開詳細資訊。'; + + @override + String get reportDetailStoryLegendCount => '數字徽章:觀測筆數'; + + @override + String get reportDetailStoryLegendIntensity => '震度圖示:群內最大震度'; + + @override + String reportDetailStoryObservationGroup( + int count, + String intensity, + String location, + ) { + return '$count 筆觀測,群內最大震度 $intensity,代表觀測地點為$location'; + } + + @override + String reportDetailStorySingleObservation(String location, String intensity) { + return '$location,震度 $intensity,一筆觀測'; + } + + @override + String get reportDetailSharePreview => '預覽分享卡片'; + + @override + String get reportDetailShareRichterScale => '芮氏規模'; + + @override + String get reportDetailShareObservedIntensity => '觀測震度'; + + @override + String get reportDetailShareKilometers => '公里'; + + @override + String get reportDetailShareSource => '資料來源:交通部中央氣象署'; + + @override + String get reportDetailSharePreparedBy => '由 DPIP 整理呈現'; + + @override + String reportDetailStoryAttribution(String source) { + return '$source|底圖:ExpTech Studio'; + } + + @override + String get reportDetailShareImageInvalid => '無法顯示此圖片格式。'; + + @override + String get reportDetailImageSaveSettingsRequired => '請在設定中允許取用照片,再試一次儲存。'; + + @override + String get reportDetailImageSaveUnavailable => '這部裝置不支援儲存到相簿。'; + + @override + String get reportDetailImageSaveRestricted => '這部裝置限制了相簿取用權限。'; + + @override + String get reportDetailImageSaveSettingsFailed => '無法開啟設定。請開啟裝置設定,允許取用照片。'; } /// The translations for Chinese, using the Han script (`zh_Hans`). @@ -7230,6 +7305,81 @@ class AppLocalizationsZhHans extends AppLocalizationsZh { @override String get seismometerAlgorithm => '依 ES-Net 的 JMA 计测震度算法计算'; + + @override + String get reportDetailMaximumIntensityLabel => '最大震度'; + + @override + String reportDetailMaximumIntensity(String intensity) { + return '最大震度 $intensity'; + } + + @override + String reportDetailStoryObservations(int count, String intensity) { + return '$count 条观测,组内最大震度 $intensity'; + } + + @override + String get reportDetailStoryLayoutUnavailable => + '此报告无法排入 Story。请选择 4:5 或展开详细信息。'; + + @override + String get reportDetailStoryLegendCount => '数字徽章:观测条数'; + + @override + String get reportDetailStoryLegendIntensity => '烈度图标:组内最大烈度'; + + @override + String reportDetailStoryObservationGroup( + int count, + String intensity, + String location, + ) { + return '$count 条观测,组内最大烈度 $intensity,代表观测地点为$location'; + } + + @override + String reportDetailStorySingleObservation(String location, String intensity) { + return '$location,烈度 $intensity,一条观测'; + } + + @override + String get reportDetailSharePreview => '预览分享卡片'; + + @override + String get reportDetailShareRichterScale => '里氏震级'; + + @override + String get reportDetailShareObservedIntensity => '观测烈度'; + + @override + String get reportDetailShareKilometers => '公里'; + + @override + String get reportDetailShareSource => '数据来源:台湾交通部中央气象署'; + + @override + String get reportDetailSharePreparedBy => '由 DPIP 整理呈现'; + + @override + String reportDetailStoryAttribution(String source) { + return '$source|底图:ExpTech Studio'; + } + + @override + String get reportDetailShareImageInvalid => '无法显示此图片格式。'; + + @override + String get reportDetailImageSaveSettingsRequired => '请在设置中允许访问照片,然后重新保存。'; + + @override + String get reportDetailImageSaveUnavailable => '此设备不支持保存到相册。'; + + @override + String get reportDetailImageSaveRestricted => '设备限制了照片访问权限。'; + + @override + String get reportDetailImageSaveSettingsFailed => '无法打开设置。请打开设备设置以允许访问照片。'; } /// The translations for Chinese, as used in Hong Kong, using the Han script (`zh_Hant_HK`). @@ -10843,6 +10993,81 @@ class AppLocalizationsZhHantHk extends AppLocalizationsZh { @override String get seismometerAlgorithm => '依 ES-Net 的 JMA 計測震度演算法計算'; + + @override + String get reportDetailMaximumIntensityLabel => '最大震度'; + + @override + String reportDetailMaximumIntensity(String intensity) { + return '最大震度 $intensity'; + } + + @override + String reportDetailStoryObservations(int count, String intensity) { + return '$count 筆觀測,群內最大震度 $intensity'; + } + + @override + String get reportDetailStoryLayoutUnavailable => + '這份報告無法排入 Story。請切換至 4:5 或展開詳細資訊。'; + + @override + String get reportDetailStoryLegendCount => '數字徽章:觀測筆數'; + + @override + String get reportDetailStoryLegendIntensity => '震度圖示:組內最大震度'; + + @override + String reportDetailStoryObservationGroup( + int count, + String intensity, + String location, + ) { + return '$count 筆觀測,組內最大震度 $intensity,代表觀測地點為$location'; + } + + @override + String reportDetailStorySingleObservation(String location, String intensity) { + return '$location,震度 $intensity,一筆觀測'; + } + + @override + String get reportDetailSharePreview => '預覽分享卡片'; + + @override + String get reportDetailShareRichterScale => '黎克特制'; + + @override + String get reportDetailShareObservedIntensity => '觀測烈度'; + + @override + String get reportDetailShareKilometers => '公里'; + + @override + String get reportDetailShareSource => '資料來源:台灣交通部中央氣象署'; + + @override + String get reportDetailSharePreparedBy => '由 DPIP 整理呈現'; + + @override + String reportDetailStoryAttribution(String source) { + return '$source|底圖:ExpTech Studio'; + } + + @override + String get reportDetailShareImageInvalid => '無法顯示此圖片格式。'; + + @override + String get reportDetailImageSaveSettingsRequired => '請在設定中允許取用相片,再試儲存。'; + + @override + String get reportDetailImageSaveUnavailable => '此裝置不支援儲存至相簿。'; + + @override + String get reportDetailImageSaveRestricted => '裝置限制了相片存取權限。'; + + @override + String get reportDetailImageSaveSettingsFailed => '無法開啟設定。請開啟裝置設定以允許取用相片。'; } /// The translations for Chinese, as used in Taiwan (`zh_TW`). @@ -14456,4 +14681,79 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { @override String get seismometerAlgorithm => '依 ES-Net 的 JMA 計測震度演算法計算'; + + @override + String get reportDetailMaximumIntensityLabel => '最大震度'; + + @override + String reportDetailMaximumIntensity(String intensity) { + return '最大震度 $intensity'; + } + + @override + String reportDetailStoryObservations(int count, String intensity) { + return '$count 筆觀測,群內最大震度 $intensity'; + } + + @override + String get reportDetailStoryLayoutUnavailable => + '這份報告無法排入 Story。請切換至 4:5 或展開詳細資訊。'; + + @override + String get reportDetailStoryLegendCount => '數字徽章:觀測筆數'; + + @override + String get reportDetailStoryLegendIntensity => '震度圖示:群內最大震度'; + + @override + String reportDetailStoryObservationGroup( + int count, + String intensity, + String location, + ) { + return '$count 筆觀測,群內最大震度 $intensity,代表觀測地點為$location'; + } + + @override + String reportDetailStorySingleObservation(String location, String intensity) { + return '$location,震度 $intensity,一筆觀測'; + } + + @override + String get reportDetailSharePreview => '預覽分享卡片'; + + @override + String get reportDetailShareRichterScale => '芮氏規模'; + + @override + String get reportDetailShareObservedIntensity => '觀測震度'; + + @override + String get reportDetailShareKilometers => '公里'; + + @override + String get reportDetailShareSource => '資料來源:交通部中央氣象署'; + + @override + String get reportDetailSharePreparedBy => '由 DPIP 整理呈現'; + + @override + String reportDetailStoryAttribution(String source) { + return '$source|底圖:ExpTech Studio'; + } + + @override + String get reportDetailShareImageInvalid => '無法顯示此圖片格式。'; + + @override + String get reportDetailImageSaveSettingsRequired => '請在設定中允許取用照片,再試一次儲存。'; + + @override + String get reportDetailImageSaveUnavailable => '這部裝置不支援儲存到相簿。'; + + @override + String get reportDetailImageSaveRestricted => '這部裝置限制了相簿取用權限。'; + + @override + String get reportDetailImageSaveSettingsFailed => '無法開啟設定。請開啟裝置設定,允許取用照片。'; } diff --git a/lib/shared/widgets/intensity_badge.dart b/lib/shared/widgets/intensity_badge.dart index f0deb8088..36953bbc9 100644 --- a/lib/shared/widgets/intensity_badge.dart +++ b/lib/shared/widgets/intensity_badge.dart @@ -25,6 +25,7 @@ class IntensityBadge extends StatelessWidget { required this.color, this.size = 48, this.outlined = false, + this.expandForText = false, }); /// Text drawn on the badge (see [Intensity.displayForReport]). @@ -34,12 +35,15 @@ class IntensityBadge extends StatelessWidget { /// must already be colour-vision corrected at its own definition. final Color color; - /// Edge length of the square badge. + /// Edge length of the square badge at its default size. final double size; /// Hollow-ring form (border only, no fill) — see the class doc. final bool outlined; + /// Allows text in a scrollable report to grow beyond the default bounds. + final bool expandForText; + @override Widget build(BuildContext context) { final onBadge = @@ -57,26 +61,31 @@ class IntensityBadge extends StatelessWidget { borderRadius: AppRadius.small, ) : BoxDecoration(color: color, borderRadius: AppRadius.small); + final text = Text( + label, + style: titleLarge?.copyWith( + // The hollow ring sits on the surface, so use the surface's text color. + color: outlined ? null : onBadge, + fontWeight: FontWeight.w900, + height: 1, + fontSize: fontSize, + fontFeatures: const [FontFeature.tabularFigures()], + ), + ); return DecoratedBox( decoration: decoration, - child: SizedBox( - width: size, - height: size, - child: Center( - child: Text( - label, - style: titleLarge?.copyWith( - // The hollow ring sits on the surface — its label must read in - // the surface's own text colour, not guess from the ring colour. - color: outlined ? null : onBadge, - fontWeight: FontWeight.w900, - height: 1, - fontSize: fontSize, - fontFeatures: const [FontFeature.tabularFigures()], + child: expandForText + ? ConstrainedBox( + constraints: BoxConstraints(minWidth: size, minHeight: size), + child: Padding( + padding: const EdgeInsets.all(4), + child: Center(widthFactor: 1, heightFactor: 1, child: text), + ), + ) + : SizedBox.square( + dimension: size, + child: Center(child: text), ), - ), - ), - ), ); } } diff --git a/test/features/earthquake/presentation/fixtures/story_map_blue.png b/test/features/earthquake/presentation/fixtures/story_map_blue.png new file mode 100644 index 0000000000000000000000000000000000000000..6112b365977010651b756ff9043299e225e187ac GIT binary patch literal 4542 zcmeAS@N?(olHy`uVBq!ia0y~yV7kD-z{EvBrvsbhbA;Cu|^(793mnQ6tTD>4-~PuB5%|>c!t0m zn9i)QtbipnC&05FMsR}i2{hU;Vh@@h5%!MeKzK1j>+)qZ2g2$Iq{;y!g(8yXz?Uzh zIdFK@@S{0!GzVg-dq?ZQ(K-;)Rl(J48cdZEyn}?LRfxM$NOqMwS_h8Sf!O-;BREUY fAqPI#&U)>|)|+AXez*h2Wf(kN{an^LB{Ts58f899 literal 0 HcmV?d00001 diff --git a/test/features/earthquake/presentation/fixtures/story_map_green.png b/test/features/earthquake/presentation/fixtures/story_map_green.png new file mode 100644 index 0000000000000000000000000000000000000000..fba6ad39c6a1fe4afee61ada43feef5c9a780b27 GIT binary patch literal 4542 zcmeAS@N?(olHy`uVBq!ia0y~yV7kD-z{e2^I_tKpu!X%!o!w@PP$^ z)PVv922`qz87v5-fEF;IP@~pS5|~=JLlYX6SR)T34iS+DidbBc2Z~r+kvD1`JVW3O zOlMYDR=^UP6X017BRE0%1R8A^u?NkM2zy6!AiS8Nb@?)y17URpQssb=LJ>)G;LDfM z95}pc_|Y6Vngg-ay`y#DXdMXYs^Dri4W>#7-a*3BD#YC=B)iHTtpi8vKx}>a5u7FH ekOLoVXXX2 precacheImage(EarthquakeShareCard.brandImage, cardContext), + ); + await tester.pump(); + final l10n = AppLocalizations.of(cardContext); + for (final value in [ + l10n.reportDetailSharePreview, + l10n.reportDetailImageSave, + l10n.reportDetailImageSavePermissionDenied, + l10n.reportDetailImageSaveSettingsRequired, + l10n.reportDetailImageSaveUnavailable, + l10n.reportDetailImageSaveRestricted, + l10n.reportDetailImageSaveSettingsFailed, + l10n.reportDetailStoryLegendCount, + l10n.reportDetailStoryLegendIntensity, + ]) { + expect(value.trim(), isNotEmpty); + expect(value, isNot(contains('{'))); + } + expect(find.text(report.location), findsOneWidget); + expect(find.text(report.shortLocation), findsExactly(2)); + expect(find.text(l10n.reportDetailShareRichterScale), findsOneWidget); + expect( + find.text(l10n.reportDetailShareObservedIntensity), + findsOneWidget, + ); + expect(find.text(l10n.reportDetailShareSource), findsOneWidget); + final attribution = l10n.reportDetailStoryAttribution( + l10n.reportDetailShareSource, + ); + expect(attribution, contains('ExpTech Studio')); + expect(attribution, contains(l10n.reportDetailShareSource)); + expect(find.text(attribution), findsOneWidget); + + Future capture(GlobalKey key, int width, int height) async { + final boundary = tester.renderObject( + find.byKey(key), + ); + return (await tester.runAsync(() async { + final image = await boundary.toImage(pixelRatio: 3); + try { + expect((image.width, image.height), (width, height)); + final png = (await image.toByteData( + format: ui.ImageByteFormat.png, + ))!; + return png.buffer.asUint8List(png.offsetInBytes, png.lengthInBytes); + } finally { + image.dispose(); + } + }))!; + } + + final maxTextPngs = <(GlobalKey, int, int), Uint8List>{}; + for (final (key, width, height) in [ + (post, 1080, 1350), + (story, 1080, 1920), + ]) { + final artwork = find.byKey(key); + final canvas = tester.getRect(artwork); + final text = find.descendant( + of: artwork, + matching: find.byType(RichText), + ); + for (final paragraph in tester.renderObjectList( + text, + )) { + expect( + paragraph.didExceedMaxLines, + isFalse, + reason: paragraph.text.toPlainText(), + ); + final topLeft = paragraph.localToGlobal(Offset.zero); + final bottomRight = paragraph.localToGlobal( + paragraph.size.bottomRight(Offset.zero), + ); + expect( + (canvas.inflate(0.01)).contains(topLeft) && + (canvas.inflate(0.01)).contains(bottomRight), + isTrue, + reason: paragraph.text.toPlainText(), + ); + } + maxTextPngs[(key, width, height)] = await capture(key, width, height); + } + + tester.platformDispatcher.textScaleFactorTestValue = 1; + await tester.pump(); + for (final entry in maxTextPngs.entries) { + final (key, width, height) = entry.key; + expect(await capture(key, width, height), orderedEquals(entry.value)); + } + expect(tester.takeException(), isNull); + }); + } + + testWidgets( + 'both artworks preserve the historical and split intensity labels', + (tester) async { + useSurface(tester); + for (final (year, value, label) in [ + (2018, 5, '5'), + (2018, 6, '6'), + (2018, 9, '7'), + (2026, 5, '5⁻'), + (2026, 6, '5⁺'), + (2026, 7, '6⁻'), + (2026, 8, '6⁺'), + ]) { + final report = _report( + origin: DateTime.utc(year), + list: { + '花蓮縣': AreaIntensity( + intensity: value, + town: { + '花蓮市': StationIntensity( + longitude: 121.6, + latitude: 23.98, + intensity: value, + ), + }, + ), + }, + ); + await tester.pumpWidget( + MaterialApp( + locale: const Locale('zh', 'TW'), + localizationsDelegates: appLocalizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Row( + children: [ + SizedBox( + width: 360, + height: 450, + child: EarthquakeShareCard(report: report), + ), + SizedBox( + width: 360, + height: 640, + child: EarthquakeShareStoryCard(report: report), + ), + ], + ), + ), + ); + expect( + tester + .widgetList(find.byType(IntensityBadge)) + .map((badge) => badge.label), + [label, label], + ); + } + }, + ); + + group('Story sharing', () { + const snapshotChannel = MethodChannel('com.exptech.dpip/map_snapshot'); + const imageChannel = MethodChannel('com.exptech.dpip/image_saver'); + final save = find.widgetWithText(FilledButton, 'Save image'); + final retry = find.widgetWithText(TextButton, 'Retry'); + final captureError = find.text("Couldn't load data. Please try again."); + final card = find.byType(EarthquakeShareStoryCard); + late _RecordingSaver saver; + late List<_SnapshotCall> captures; + + Future mountReport( + WidgetTester tester, { + ImageSaver? imageSaver, + Size size = const Size(900, 1600), + }) async { + captures = []; + saver = _RecordingSaver(); + final messenger = tester.binding.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(snapshotChannel, (call) { + expect(call.method, 'captureWithProjection'); + final capture = _SnapshotCall(call); + captures.add(capture); + return capture.response.future; + }); + addTearDown(() { + messenger.setMockMethodCallHandler(snapshotChannel, null); + messenger.setMockMethodCallHandler(imageChannel, null); + }); + + final reports = _Reports()..next = Ok(_report()); + final settings = SettingsStore.inMemory(); + await pumpPage( + tester, + reports: reports, + client: _BytesClient(RegionSelection(settings)), + settings: settings, + regions: RegionStore(settings), + towns: const TownDirectory({}), + router: nestedRouter(reports, imageSaver: imageSaver ?? saver), + size: size, + ); + await tester.pump(); + await tester.pump(); + final sheet = tester.widget( + find.byType(DraggableScrollableSheet), + ); + sheet.controller!.jumpTo(sheet.maxChildSize); + await tester.pump(); + } + + Future select(WidgetTester tester, String format) async { + await tester.tap(find.text(format)); + await tester.pump(); + await tester.pump(); + } + + Future open(WidgetTester tester) async { + final preview = find.widgetWithText(OutlinedButton, 'Preview share card'); + await Scrollable.ensureVisible(tester.element(preview), alignment: 0.5); + await tester.pump(); + await tester.tap(preview); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + } + + void close(WidgetTester tester) => + Navigator.of(tester.element(find.byType(Dialog))).pop(); + + bool enabled(WidgetTester tester) => + tester.widget(save).onPressed != null; + + Future pumpUntil( + WidgetTester tester, + bool Function() condition, + ) async { + for (var frame = 0; frame < 100; frame++) { + await tester.pump(); + if (condition()) return; + // The engine decodes, rasterizes and encodes outside the fake clock. + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 10)), + ); + } + expect(condition(), isTrue); + } + + Future waitForReady(WidgetTester tester) => + pumpUntil(tester, () => enabled(tester)); + + Future openWithBrandBundle( + WidgetTester tester, + _ShareBrandBundle bundle, + ) async { + unawaited( + showDialog( + context: tester.element(find.byType(ReportDetailPage)), + builder: (_) => DefaultAssetBundle( + bundle: bundle, + child: EarthquakeShareDialog( + report: _report(), + saver: saver, + isReportCurrent: () => true, + ), + ), + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + await pumpUntil(tester, () => bundle.loads.isNotEmpty); + } + + void expectFailure(WidgetTester tester) { + expect(captureError, findsOneWidget); + expect(retry, findsOneWidget); + expect(enabled(tester), isFalse); + expect( + find.descendant( + of: find.byType(Dialog), + matching: find.byType(CircularProgressIndicator), + ), + findsNothing, + ); + expect(saver.saved, isEmpty); + } + + testWidgets('the report opens share preview without a diagnostic entry', ( + tester, + ) async { + await mountReport(tester); + expect(find.textContaining('MapLibre Snapshot'), findsNothing); + expect(find.byIcon(Icons.visibility_outlined), findsOneWidget); + await open(tester); + expect(find.text('4:5'), findsOneWidget); + expect(find.text('9:16'), findsOneWidget); + expect(find.textContaining('Snapshot'), findsNothing); + + await select(tester, '9:16'); + expect(captures, hasLength(1)); + expect( + tester.widget(card).showSafeAreaGuides, + isFalse, + ); + }); + + testWidgets('slow capture and composition gate Save, with 4:5 preserved', ( + tester, + ) async { + await mountReport(tester); + await open(tester); + expect(find.byType(EarthquakeShareCard), findsOneWidget); + expect(save, findsOneWidget); + expect(captures, isEmpty); + + await select(tester, '9:16'); + expect(captures, hasLength(1)); + expect(enabled(tester), isFalse); + await tester.tap(save); + await tester.pump(const Duration(seconds: 5)); + expect(saver.saved, isEmpty); + + captures.single.succeed(); + await tester.pump(); + expect(enabled(tester), isFalse); + await waitForReady(tester); + expect(saver.saved, isEmpty); + + await select(tester, '4:5'); + expect(find.byType(EarthquakeShareCard), findsOneWidget); + expect(card, findsNothing); + await waitForReady(tester); + }); + + testWidgets('default 4:5 saves the opaque artwork at fixed 3x', ( + tester, + ) async { + await mountReport(tester, size: const Size(320, 568)); + tester.view.devicePixelRatio = 2; + tester.view.physicalSize = const Size(640, 1136); + await open(tester); + await waitForReady(tester); + await tester.tap(save); + await tester.pump(); + final write = saver.saved.single; + expect(write.fileName, 'dpip-card-115053-2026-0310-140000.png'); + expect(captures, isEmpty); + + final dispatcher = tester.platformDispatcher; + dispatcher.textScaleFactorTestValue = 3; + addTearDown(dispatcher.clearTextScaleFactorTestValue); + await tester.pump(); + final close = find.byTooltip('Close'); + await tester.ensureVisible(close); + await tester.pump(); + expect(close.hitTestable(), findsOneWidget); + final postSelector = find.text('4:5'); + await tester.ensureVisible(postSelector); + await tester.pump(); + expect(postSelector.hitTestable(), findsOneWidget); + expect(save.hitTestable(), findsOneWidget); + expect(MediaQuery.textScalerOf(tester.element(save)).scale(14), 42); + final preview = find.byType(EarthquakeShareCard); + final credit = find.descendant( + of: preview, + matching: find.text('Prepared by DPIP'), + ); + expect(credit, findsOneWidget); + expect(MediaQuery.textScalerOf(tester.element(credit)).scale(14), 14); + await tester.tap(save); + await tester.pump(); + expect(saver.saved.last.bytes, same(write.bytes)); + + final boundary = tester.renderObject( + find + .ancestor(of: preview, matching: find.byType(RepaintBoundary)) + .first, + ); + await tester.runAsync(() async { + final image = await boundary.toImage(pixelRatio: 3); + try { + expect((image.width, image.height), (1080, 1350)); + final png = (await image.toByteData(format: ui.ImageByteFormat.png))!; + expect(write.bytes, orderedEquals(png.buffer.asUint8List())); + final rgba = (await image.toByteData())!.buffer.asUint8List(); + var opaque = true; + for (var index = 3; index < rgba.length; index += 4) { + opaque = opaque && rgba[index] == 255; + } + expect(opaque, isTrue); + } finally { + image.dispose(); + } + }); + }); + + testWidgets('stale Story cannot replace a cached and reselected 4:5', ( + tester, + ) async { + await mountReport(tester); + await open(tester); + await waitForReady(tester); + final postSave = tester.widget(save).onPressed!; + await tester.tap(save); + await tester.pump(); + final post = saver.saved.single.bytes; + + await select(tester, '9:16'); + postSave(); + expect(saver.saved, hasLength(1)); + captures.first.succeed(green: true); + await waitForReady(tester); + final storySave = tester.widget(save).onPressed!; + await tester.tap(save); + await tester.pump(); + await _expectExport(tester, saver.saved.last.bytes, green: true); + + for (var i = 0; i < 3; i++) { + await select(tester, '4:5'); + await select(tester, '9:16'); + } + await select(tester, '4:5'); + storySave(); + for (final obsolete in captures.skip(1)) { + obsolete.succeed(); + } + await tester.pump(); + expect(saver.saved, hasLength(2)); + expect(enabled(tester), isTrue); + await tester.tap(save); + await tester.pump(); + expect(saver.saved, hasLength(3)); + expect(saver.saved.last.bytes, same(post)); + }); + + testWidgets('late 4:5 asset cannot enable Save for a pending Story', ( + tester, + ) async { + await mountReport(tester); + final bundle = _ShareBrandBundle( + (await tester.runAsync(() => rootBundle.load('assets/DPIP.png')))!, + ); + await openWithBrandBundle(tester, bundle); + expect(enabled(tester), isFalse); + await select(tester, '9:16'); + bundle.succeed(); + await tester.pump(); + expect(enabled(tester), isFalse); + expect(saver.saved, isEmpty); + captures.single.succeed(green: true); + await waitForReady(tester); + await tester.tap(save); + await tester.pump(); + await _expectExport(tester, saver.saved.single.bytes, green: true); + }); + + testWidgets('4:5 decode failure and close require a fresh attempt', ( + tester, + ) async { + await mountReport(tester); + final bytes = (await tester.runAsync( + () => rootBundle.load('assets/DPIP.png'), + ))!; + final bundle = _ShareBrandBundle(bytes); + await openWithBrandBundle(tester, bundle); + bundle.loads.single.completeError(StateError('Missing QA brand image')); + await pumpUntil(tester, () => captureError.evaluate().isNotEmpty); + expectFailure(tester); + + await tester.tap(retry); + await pumpUntil(tester, () => bundle.loads.length == 2); + expect(enabled(tester), isFalse); + bundle.succeed(); + await waitForReady(tester); + close(tester); + await tester.pumpAndSettle(); + + final pending = _ShareBrandBundle(bytes); + await openWithBrandBundle(tester, pending); + close(tester); + pending.succeed(); + await tester.pumpAndSettle(); + expect(find.byType(Dialog), findsNothing); + expect(saver.saved, isEmpty); + + await open(tester); + await waitForReady(tester); + expect(captures, isEmpty); + }); + + testWidgets('large text keeps share controls and the same Story PNG', ( + tester, + ) async { + final semantics = tester.ensureSemantics(); + try { + await mountReport(tester, size: const Size(320, 568)); + await open(tester); + await select(tester, '9:16'); + final loading = find.bySemanticsLabel('Loading…'); + expect(loading, findsOneWidget); + expect( + tester + .getSemantics(loading) + .getSemanticsData() + .flagsCollection + .isLiveRegion, + isTrue, + ); + expect( + tester + .getSemantics(find.text('9:16')) + .getSemanticsData() + .flagsCollection + .isSelected, + ui.Tristate.isTrue, + ); + expect( + tester + .getSemantics(find.text('4:5')) + .getSemanticsData() + .flagsCollection + .isSelected, + ui.Tristate.isFalse, + ); + captures.single.succeed(); + await waitForReady(tester); + expect(find.bySemanticsLabel('Epicenter'), findsOneWidget); + final candidate = tester + .widget(card) + .useD75Compact; + expect(candidate, const bool.fromEnvironment('DPIP_STORY_D75_COMPACT')); + expect( + find.text('Badge: observation count'), + candidate ? findsOneWidget : findsNothing, + ); + expect( + find.bySemanticsLabel( + candidate + ? '2 observations, group maximum intensity 4, ' + 'representative observation location 宜蘭縣頭城鎮' + : '2 observations, group maximum intensity five upper, ' + 'representative observation location 花蓮縣花蓮市', + ), + findsOneWidget, + ); + if (candidate) { + expect( + find.bySemanticsLabel( + '花蓮縣花蓮市, intensity five upper, one observation', + ), + findsOneWidget, + ); + } + await tester.ensureVisible(save); + await tester.tap(save); + await tester.pump(); + final original = saver.saved.single.bytes; + + tester.platformDispatcher.textScaleFactorTestValue = 3; + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + await tester.pump(); + await tester.pump(); + expect(captures, hasLength(1)); + expect(enabled(tester), isTrue); + expect(save.hitTestable(), findsOneWidget); + final pinnedSave = tester.getRect(save); + await tester.tap(save); + await tester.pump(); + expect(saver.saved.last.bytes, same(original)); + + final details = find.descendant( + of: find.byType(Dialog), + matching: find.text('Details'), + ); + await tester.ensureVisible(details); + await tester.tap(details); + await tester.pump(const Duration(milliseconds: 300)); + final location = find.descendant( + of: find.byType(Dialog), + matching: find.text(_report().location), + ); + await tester.ensureVisible(location); + await tester.pump(); + final viewport = find.descendant( + of: find.byType(Dialog), + matching: find.byType(Scrollable), + ); + expect( + tester.getRect(viewport).contains(tester.getCenter(location)), + isTrue, + ); + final context = tester.element(location); + expect(MediaQuery.textScalerOf(context).scale(14), 42); + expect(tester.getRect(save), pinnedSave); + final closeButton = find.byTooltip('Close'); + await tester.ensureVisible(closeButton); + await tester.tap(closeButton); + await tester.pumpAndSettle(); + expect(find.byType(Dialog), findsNothing); + } finally { + semantics.dispose(); + } + }); + + testWidgets('an unplaceable legend invalidates the Story before Save', ( + tester, + ) async { + await mountReport(tester); + unawaited( + showDialog( + context: tester.element(find.byType(ReportDetailPage)), + builder: (context) => Localizations.override( + context: context, + delegates: const [_OversizeStoryLegendDelegate()], + child: EarthquakeShareDialog( + report: _report(), + saver: saver, + isReportCurrent: () => true, + useD75Compact: true, + ), + ), + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + await select(tester, '9:16'); + expect(captures, hasLength(1)); + expect(enabled(tester), isFalse); + captures.single.succeed(); + final unavailable = find.text( + 'This report cannot fit in a Story. Choose 4:5 or open Details.', + ); + for (var frame = 0; frame < 100; frame++) { + await tester.pump(); + expect(enabled(tester), isFalse); + if (unavailable.evaluate().isNotEmpty) break; + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 10)), + ); + } + expect(unavailable, findsOneWidget); + expect(card, findsNothing); + expect(retry, findsNothing); + expect(captures, hasLength(1)); + expect(saver.saved, isEmpty); + await select(tester, '4:5'); + expect(find.byType(EarthquakeShareCard), findsOneWidget); + expect(captures, hasLength(1)); + }); + + testWidgets('an unfittable Story offers Details, 4:5 and Close', ( + tester, + ) async { + tester.platformDispatcher.textScaleFactorTestValue = 3; + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + await mountReport(tester, size: const Size(320, 568)); + await open(tester); + await select(tester, '9:16'); + final current = tester.widget(card); + current.onMapLayout!((mapRegion: Rect.zero, anchorRegion: Rect.zero)); + await tester.pump(); + expect( + find.text( + 'This report cannot fit in a Story. Choose 4:5 or open Details.', + ), + findsOneWidget, + ); + expect(enabled(tester), isFalse); + expect(retry, findsNothing); + expect(card, findsNothing); + final close = find.byTooltip('Close'); + await tester.ensureVisible(close); + await tester.pumpAndSettle(); + expect(close.hitTestable(), findsOneWidget); + await tester.ensureVisible(find.text('4:5')); + await tester.pump(); + await select(tester, '4:5'); + expect(find.byType(EarthquakeShareCard), findsOneWidget); + expect(saver.saved, isEmpty); + }); + + testWidgets('capture error stays out of UI, Retry creates a fresh export', ( + tester, + ) async { + await mountReport(tester); + await open(tester); + await select(tester, '9:16'); + captures.single.fail('native_error'); + await tester.pump(); + expectFailure(tester); + expect(find.textContaining('native_error'), findsNothing); + await tester.tap(save); + expect(saver.saved, isEmpty); + + await tester.tap(retry); + await tester.pump(); + await tester.pump(); + expect(captures, hasLength(2)); + expect(captureError, findsNothing); + expect(enabled(tester), isFalse); + + captures.last.succeed(); + await waitForReady(tester); + await tester.tap(save); + await tester.pump(); + expect( + saver.saved.single.fileName, + 'dpip-story-115053-2026-0310-140000.png', + ); + expect(find.text('Saved to your photos'), findsOneWidget); + await _expectExport(tester, saver.saved.single.bytes, green: false); + }); + + testWidgets('4:5 → 9:16 → 4:5 → 9:16 discards a failed capture', ( + tester, + ) async { + await mountReport(tester); + await open(tester); + await select(tester, '9:16'); + captures.single.fail(); + await tester.pump(); + expectFailure(tester); + await select(tester, '4:5'); + await select(tester, '9:16'); + expect(captures, hasLength(2)); + expect(captureError, findsNothing); + expect(enabled(tester), isFalse); + captures.last.succeed(green: true); + await waitForReady(tester); + }); + + for (final lateFailure in [false, true]) { + testWidgets( + 'late ${lateFailure ? 'failure' : 'image'} cannot supersede a ready Story', + (tester) async { + await mountReport(tester); + await open(tester); + await select(tester, '9:16'); + await select(tester, '4:5'); + await select(tester, '9:16'); + expect(captures, hasLength(2)); + + captures[1].succeed(green: true); + await waitForReady(tester); + final ready = tester.widget(card); + final obsolete = captures[0]; + if (lateFailure) { + obsolete.fail(); + } else { + obsolete.succeed(); + } + await tester.pump(); + + final visible = tester.widget(card); + expect(visible.mapPng, same(ready.mapPng)); + expect(visible.mapPng, orderedEquals(_greenStoryMap)); + expect(visible.epicenterPosition, const Offset(230, 150)); + expect(visible.stationMarkers.first.position, const Offset(230, 207)); + expect(captureError, findsNothing); + expect(saver.saved, isEmpty); + await tester.tap(save); + await tester.pump(); + await _expectExport(tester, saver.saved.single.bytes, green: true); + }, + ); + } + + testWidgets('close invalidates capture before its exit animation ends', ( + tester, + ) async { + await mountReport(tester); + await open(tester); + await select(tester, '9:16'); + close(tester); + captures.first.succeed(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(find.byType(Dialog), findsNothing); + expect(saver.saved, isEmpty); + expect(find.text('Saved to your photos'), findsNothing); + + await open(tester); + await select(tester, '9:16'); + expect(captures, hasLength(2)); + expect(tester.widget(card).mapPng, isNull); + captures.last.succeed(green: true); + await waitForReady(tester); + }); + + testWidgets('double Save is single-flight and saving keeps format locked', ( + tester, + ) async { + await mountReport(tester); + await open(tester); + await select(tester, '9:16'); + captures.single.succeed(); + await waitForReady(tester); + + final write = saver.pending = Completer>(); + await tester.tap(save); + await tester.tap(save); // The old button callback is still on screen. + await tester.pump(); + expect(saver.saved, hasLength(1)); + expect(enabled(tester), isFalse); + await select(tester, '4:5'); + expect(card, findsOneWidget); + expect(find.text('Saved to your photos'), findsNothing); + + write.complete(const Ok(null)); + await tester.pump(); + expect(enabled(tester), isTrue); + expect(saver.saved, hasLength(1)); + }); + + for (final story in [false, true]) { + testWidgets( + '${story ? '9:16' : '4:5'} gallery errors retry the same PNG', + (tester) async { + await mountReport(tester); + await open(tester); + if (story) { + await select(tester, '9:16'); + captures.single.succeed(); + } + await waitForReady(tester); + + for (final (reason, text) in [ + (ImageSaveFailureReason.failed, "Couldn't save the image"), + ( + ImageSaveFailureReason.permissionDenied, + 'Allow photo access to save the image', + ), + ]) { + saver.result = Err(ImageSaveFailure(reason, 'internal failure')); + await tester.tap(save); + await tester.pump(); + expect(find.text(text), findsOneWidget); + expect(find.textContaining('internal failure'), findsNothing); + expect(find.text('Saved to your photos'), findsNothing); + expect(retry, findsNothing); + expect(enabled(tester), isTrue); + } + + final pending = saver.pending = Completer>(); + await tester.tap(save); + await tester.tap(save); + await tester.pump(); + expect(enabled(tester), isFalse); + pending.complete(const Ok(null)); + await tester.pump(); + expect(captures, hasLength(story ? 1 : 0)); + expect(saver.saved, hasLength(3)); + expect( + saver.saved.map((write) => write.bytes), + everyElement(same(saver.saved.first.bytes)), + ); + expect(find.text("Couldn't save the image"), findsNothing); + expect( + find.text('Allow photo access to save the image'), + findsNothing, + ); + expect(find.text('Saved to your photos'), findsOneWidget); + }, + ); + } + + testWidgets( + 'settings recovery keeps Save reachable at large text and reuses PNG', + (tester) async { + const settingsChannel = MethodChannel( + 'flutter.baseflow.com/permissions/methods', + ); + var settingsOpened = false; + var settingsCalls = 0; + final messenger = tester.binding.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(settingsChannel, (call) async { + expect(call.method, 'openAppSettings'); + settingsCalls++; + return settingsOpened; + }); + addTearDown( + () => messenger.setMockMethodCallHandler(settingsChannel, null), + ); + + await mountReport(tester, size: const Size(320, 568)); + await open(tester); + await select(tester, '9:16'); + captures.single.succeed(); + await waitForReady(tester); + tester.platformDispatcher.textScaleFactorTestValue = 3; + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + await tester.pump(); + + saver.result = const Err( + ImageSaveFailure( + ImageSaveFailureReason.permissionSettingsRequired, + 'private', + ), + ); + await tester.tap(save); + await tester.pump(); + final settings = find.widgetWithText(TextButton, 'Open Settings'); + expect( + find.text('Allow photo access in Settings, then try saving again.'), + findsOneWidget, + ); + expect(find.text('Saved to your photos'), findsNothing); + expect(retry, findsNothing); + expect(save.hitTestable(), findsOneWidget); + await tester.ensureVisible(settings); + await tester.tap(settings); + await tester.pump(); + expect(settingsCalls, 1); + expect(find.textContaining('Could not open Settings.'), findsOneWidget); + + settingsOpened = true; + await tester.ensureVisible(settings); + await tester.tap(settings); + await tester.pump(); + expect(settingsCalls, 2); + expect(find.textContaining('Could not open Settings.'), findsNothing); + expect( + saver.saved, + hasLength(1), + reason: 'Returning from Settings must not save automatically', + ); + + saver.result = const Ok(null); + await tester.tap(save); + await tester.pump(); + expect(captures, hasLength(1)); + expect(saver.saved, hasLength(2)); + expect(saver.saved.last.bytes, same(saver.saved.first.bytes)); + expect(settings, findsNothing); + expect(find.text('Saved to your photos'), findsOneWidget); + expect(tester.takeException(), isNull); + }, + ); + + for (final (reason, message) in [ + ( + ImageSaveFailureReason.unavailable, + 'Saving to photos is unavailable on this device.', + ), + ( + ImageSaveFailureReason.permissionRestricted, + 'Your device restricts access to photos.', + ), + ]) { + testWidgets('${reason.name} has no futile gallery recovery action', ( + tester, + ) async { + await mountReport(tester); + await open(tester); + await select(tester, '9:16'); + captures.single.succeed(); + await waitForReady(tester); + saver.result = Err(ImageSaveFailure(reason, 'internal')); + await tester.tap(save); + await tester.pump(); + + expect(find.text(message), findsOneWidget); + expect(enabled(tester), isFalse); + expect(find.text('Open Settings'), findsNothing); + expect(find.text('Saved to your photos'), findsNothing); + expect(saver.saved, hasLength(1)); + }); + } + + testWidgets('timeout is recoverable and ignores the late PNG', ( + tester, + ) async { + await mountReport(tester); + await open(tester); + await select(tester, '9:16'); + await tester.pump(const Duration(seconds: 19)); + expect(enabled(tester), isFalse); + expect(retry, findsNothing); + await tester.pump(const Duration(seconds: 1)); + expectFailure(tester); + + await tester.tap(retry); + await tester.pump(); + await tester.pump(); + expect(captures, hasLength(2)); + captures.first.succeed(); + await tester.pump(); + expect(tester.widget(card).mapPng, isNull); + expect(enabled(tester), isFalse); + + captures.last.succeed(green: true); + await waitForReady(tester); + }); + + for (final corrupt in [false, true]) { + testWidgets( + corrupt + ? 'PNG header alone does not enable Save' + : 'PNG/projection mismatch cannot export', + (tester) async { + await mountReport(tester); + await open(tester); + await select(tester, '9:16'); + final response = captures.single.makeResponse(); + if (corrupt) { + response['png'] = Uint8List.sublistView(_blueStoryMap, 0, 24); + } else { + (response['points']! as Map).remove('epicenter'); + } + captures.single.response.complete(response); + for ( + var frame = 0; + frame < 100 && retry.evaluate().isEmpty; + frame++ + ) { + await tester.pump(); + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 10)), + ); + } + expectFailure(tester); + await tester.tap(save); + expect(saver.saved, isEmpty); + }, + ); + } + + testWidgets( + 'rapid raster input updates keep the active PNG and markers together', + (tester) async { + await mountReport(tester); + await open(tester); + await select(tester, '9:16'); + final dispatcher = tester.platformDispatcher; + addTearDown(dispatcher.clearAccessibilityFeaturesTestValue); + for (final bold in [true, false]) { + dispatcher.accessibilityFeaturesTestValue = FakeAccessibilityFeatures( + boldText: bold, + ); + await tester.pump(); + await tester.pump(); + } + expect(captures, hasLength(3)); + + captures.last.succeed(green: true); + await waitForReady(tester); + captures.first.succeed(); + captures[1].succeed(); + await tester.pump(); + + final visible = tester.widget(card); + expect(visible.mapPng, orderedEquals(_greenStoryMap)); + expect(visible.epicenterPosition, const Offset(230, 150)); + expect(visible.stationMarkers.first.position, const Offset(230, 207)); + final oldSave = tester.widget(save).onPressed!; + dispatcher.accessibilityFeaturesTestValue = + const FakeAccessibilityFeatures(boldText: true); + await tester.pump(); + await tester.pump(); + expect(captures, hasLength(4)); + oldSave(); + expect(enabled(tester), isFalse); + expect(tester.widget(card).mapPng, isNull); + expect(saver.saved, isEmpty); + + captures.last.succeed(); + await waitForReady(tester); + await tester.tap(save); + await tester.pump(); + await _expectExport(tester, saver.saved.single.bytes, green: false); + }, + ); + + for (final closeAfterWrite in [false, true]) { + testWidgets( + closeAfterWrite + ? 'close after native write starts ignores its result' + : 'close during native permission cannot dispatch a write', + (tester) async { + final gate = Completer(); + var requests = 0; + var writes = 0; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + imageChannel, + (call) { + switch (call.method) { + case 'status': + return Future.value( + closeAfterWrite ? 'granted' : 'notDetermined', + ); + case 'request': + requests++; + return gate.future; + case 'save': + writes++; + return gate.future; + default: + fail('Unexpected call ${call.method}'); + } + }, + ); + await mountReport( + tester, + imageSaver: IosImageSaver( + channel: imageChannel, + isSupportedPlatform: true, + ), + ); + await open(tester); + await select(tester, '9:16'); + captures.single.succeed(); + await waitForReady(tester); + await tester.tap(save); + await tester.pump(); + expect(writes, closeAfterWrite ? 1 : 0); + expect(requests, closeAfterWrite ? 0 : 1); + + close(tester); + gate.complete(closeAfterWrite ? null : 'granted'); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(writes, closeAfterWrite ? 1 : 0); + expect(find.text('Saved to your photos'), findsNothing); + expect(find.byType(Dialog), findsNothing); + }, + ); + } + }); + testWidgets('the report image saves to the photo library', (tester) async { final reports = _Reports()..next = Ok(_report()); final settings = SettingsStore.inMemory(); @@ -874,16 +2053,124 @@ void main() { // A refusal must say so in its own words, and offer the only way out: // Settings, not another tap. saver.result = const Err( - ImageSaveFailure(ImageSaveFailureReason.permissionDenied, 'refused'), + ImageSaveFailure( + ImageSaveFailureReason.permissionSettingsRequired, + 'refused', + ), ); await tester.tap(find.byTooltip('Save image')); await tester.pump(); - expect(find.text('Allow photo access to save the image'), findsOneWidget); + expect( + find.text('Allow photo access in Settings, then try saving again.'), + findsOneWidget, + ); expect(find.text('Open Settings'), findsOneWidget); }); } +class _OversizeStoryLegendDelegate + extends LocalizationsDelegate { + const _OversizeStoryLegendDelegate(); + + @override + bool isSupported(Locale locale) => locale.languageCode == 'en'; + + @override + Future load(Locale locale) => + SynchronousFuture(_OversizeStoryLegend()); + + @override + bool shouldReload(_OversizeStoryLegendDelegate old) => false; +} + +class _OversizeStoryLegend extends AppLocalizationsEn { + @override + String get reportDetailStoryLegendCount => + super.reportDetailStoryLegendCount * 25; +} + +const _fixtures = 'test/features/earthquake/presentation/fixtures'; +final _blueStoryMap = File('$_fixtures/story_map_blue.png').readAsBytesSync(); +final _greenStoryMap = File('$_fixtures/story_map_green.png').readAsBytesSync(); + +class _SnapshotCall { + _SnapshotCall(this.call); + + final MethodCall call; + final response = Completer(); + + Map makeResponse({bool green = false}) { + final queries = (call.arguments as Map)['points'] as List; + final x = green ? 230.0 : 120.0; + final stations = queries.skip(1).indexed; + return { + 'png': green ? _greenStoryMap : _blueStoryMap, + 'pngWidth': 720, + 'pngHeight': 1280, + 'logicalWidth': 360.0, + 'logicalHeight': 640.0, + 'points': { + 'epicenter': [x, 150.0], + for (final (i, point) in stations) + (point as Map)['id']: [x, 207.0 + 36 * i], + }, + }; + } + + void succeed({bool green = false}) => + response.complete(makeResponse(green: green)); + + void fail([String code = 'snapshot_failed']) => + response.completeError(PlatformException(code: code)); +} + +Future _expectExport( + WidgetTester tester, + Uint8List png, { + required bool green, +}) async { + await tester.runAsync(() async { + final codec = await ui.instantiateImageCodec(png); + try { + final image = (await codec.getNextFrame()).image; + try { + expect(image.width, 1080); + expect(image.height, 1920); + final data = (await image.toByteData())!; + int pixel(int x, int y) => data.getUint32((y * image.width + x) * 4); + final background = green ? 0x10ac58ff : 0x1880e0ff; + expect(pixel(12, 12), background); + expect(pixel(12, 56 * 3), background); // Guide excluded. + expect(pixel((green ? 230 : 120) * 3, 150 * 3), isNot(background)); + expect(pixel((green ? 120 : 230) * 3, 150 * 3), background); + } finally { + image.dispose(); + } + } finally { + codec.dispose(); + } + }); +} + +/// Holds the artwork asset at a controlled point in composition. +class _ShareBrandBundle extends CachingAssetBundle { + _ShareBrandBundle(this.bytes); + + final ByteData bytes; + final loads = >[]; + + @override + Future load(String key) { + if (key != 'assets/DPIP.png') return rootBundle.load(key); + final load = Completer(); + loads.add(load); + return load.future; + } + + void succeed() => loads.last.complete(bytes); +} + /// Records what the save button hands over, and answers with [result]. /// /// The permission gate itself is covered by `image_saver_test.dart`; here it @@ -891,6 +2178,7 @@ void main() { class _RecordingSaver implements ImageSaver { final saved = <({Uint8List bytes, String fileName})>[]; Result result = const Ok(null); + Completer>? pending; @override Future> ensurePermission() async => const Ok(null); @@ -902,7 +2190,7 @@ class _RecordingSaver implements ImageSaver { String mimeType = 'image/png', }) async { saved.add((bytes: bytes, fileName: fileName)); - return result; + return pending?.future ?? result; } } diff --git a/test/features/earthquake/presentation/story_camera_fit_test.dart b/test/features/earthquake/presentation/story_camera_fit_test.dart new file mode 100644 index 000000000..3e12fe9d3 --- /dev/null +++ b/test/features/earthquake/presentation/story_camera_fit_test.dart @@ -0,0 +1,198 @@ +import 'dart:math' as math; + +import 'package:dpip/features/earthquake/domain/earthquake_report.dart'; +import 'package:dpip/features/earthquake/presentation/story_camera_fit.dart'; +import 'package:dpip/features/earthquake/presentation/story_map_snapshot.dart'; +import 'package:dpip/features/earthquake/presentation/widgets/earthquake_share_story_card.dart'; +import 'package:dpip/l10n/gen/app_localizations.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; + +const _report = EarthquakeReport( + id: '115075-2026-1101-162007', + longitude: 122.56, + latitude: 23.9, + location: '臺灣東部', + depth: 19.0, + magnitude: 5.6, + time: 1793521200000, + trem: 0, + list: {}, +); + +StoryCameraLayout _layout(double hudTop) => storyCameraLayout( + canvas: StoryMapSnapshot.canvas, + safeTop: 56, + safeBottom: 40, + hud: Rect.fromLTRB(16, hudTop, 344, 592), + footprint: const Rect.fromLTRB(-18, -18, 19, 18), + gap: 8, +); + +EarthquakeReport _withStations(Map stations) => + _report.copyWith( + list: {'area': AreaIntensity(intensity: 4, town: stations)}, + ); + +Offset _mercatorPoint(double latitude, double longitude, StoryCamera camera) { + double y(double latitude) { + final s = math.sin(latitude * math.pi / 180); + return 0.5 - math.log((1 + s) / (1 - s)) / (4 * math.pi); + } + + final world = 512 * math.pow(2, camera.zoom); + return StoryMapSnapshot.canvas.center(Offset.zero) + + Offset( + (longitude - camera.target.longitude) * world / 360, + (y(latitude) - y(camera.target.latitude)) * world, + ); +} + +void main() { + test('reserves the symbol box and breathing room within the map band', () { + final layout = _layout(395); + expect(layout.mapRegion, const Rect.fromLTRB(0, 56, 360, 395)); + expect(layout.anchorRegion, const Rect.fromLTRB(27, 82, 333, 369)); + expect(_layout(625).mapRegion.bottom, 600); + expect(() => fitStoryCamera(_report, _layout(107)), throwsStateError); + }); + + test('FULL fits the offshore epicenter and both weaker extremes', () { + const west = StationIntensity( + longitude: 118.22, + latitude: 24.43, + intensity: 1, + ); + const south = StationIntensity( + longitude: 121.3, + latitude: 21.84, + intensity: 2, + ); + const invalid = StationIntensity(longitude: 199, latitude: 0, intensity: 4); + final report = _withStations({'west': west, 'south': south}); + final wide = _layout(395); + final expandedHud = _layout(235); + final normalCamera = fitStoryCamera(report, wide); + final compactCamera = fitStoryCamera(report, expandedHud); + expect(compactCamera.zoom, lessThan(normalCamera.zoom)); + for (final (camera, layout) in [ + (normalCamera, wide), + (compactCamera, expandedHud), + ]) { + for (final (lat, lon) in [ + (report.latitude, report.longitude), + (west.latitude, west.longitude), + (south.latitude, south.longitude), + ]) { + expect( + layout.anchorRegion + .inflate(1e-7) + .contains(_mercatorPoint(lat, lon, camera)), + isTrue, + ); + } + } + expect( + fitStoryCamera( + _withStations({'south': south, 'bad': invalid, 'west': west}), + wide, + ), + normalCamera, + ); + }); + + test('caps zoom for zero and single nearby observations', () { + final layout = _layout(395); + final empty = fitStoryCamera(_report, layout); + expect(empty.zoom, 7); + expect( + (_mercatorPoint(_report.latitude, _report.longitude, empty) - + layout.anchorRegion.center) + .distance, + lessThan(0.001), + ); + final one = fitStoryCamera( + _withStations({ + 'nearby': const StationIntensity( + longitude: 122.5, + latitude: 23.88, + intensity: 2, + ), + }), + layout, + ); + expect(one.zoom, 7); + }); + + test( + 'keeps minimum zoom for an impossible span and rejects bad epicenter', + () { + final layout = _layout(395); + final wide = _withStations({ + 'distant': const StationIntensity( + longitude: -40, + latitude: 23, + intensity: 1, + ), + }); + expect(fitStoryCamera(wide, layout).zoom, 2); + expect( + () => fitStoryCamera(_report.copyWith(latitude: double.nan), layout), + throwsFormatException, + ); + }, + ); + + testWidgets('measures wrapped locations at the fixed Story text size', ( + tester, + ) async { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = StoryMapSnapshot.canvas; + addTearDown(tester.view.reset); + final layouts = []; + Future render(String location, double scale) async { + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Material( + child: Center( + child: MediaQuery( + data: MediaQueryData(textScaler: TextScaler.linear(scale)), + child: EarthquakeShareStoryCard( + report: _report.copyWith(location: location), + showSafeAreaGuides: true, + onMapLayout: layouts.add, + ), + ), + ), + ), + ), + ); + final card = tester.getRect(find.byType(EarthquakeShareStoryCard)); + final hud = tester.getRect(find.byType(ClipRRect)).shift(-card.topLeft); + expect(layouts.last.mapRegion.bottom, hud.top); + expect(hud.bottom, 592); + expect(layouts.last.mapRegion.top, 56); + return hud; + } + + final oneLine = await render('臺灣東部', 1); + await render('臺灣東部', 1); + expect(layouts, hasLength(1)); + final twoLines = await render('臺灣東部\n外海', 1); + expect(twoLines.height, greaterThan(oneLine.height)); + final long = List.filled(10, '臺灣東部外海').join(); + final standard = await render(long, 1); + final scaled = await render(long, 3); + expect(scaled.height, greaterThan(twoLines.height)); + expect(scaled, standard); + final paragraph = tester.renderObject(find.text(long)); + expect(paragraph.didExceedMaxLines, isFalse); + expect(layouts.last.anchorRegion.isEmpty, isFalse); + await render(List.filled(40, '臺灣東部外海').join(), 3); + expect(layouts.last.anchorRegion.isEmpty, isTrue); + expect(tester.takeException(), isNull); + }); +} diff --git a/test/features/earthquake/presentation/story_marker_layout_test.dart b/test/features/earthquake/presentation/story_marker_layout_test.dart new file mode 100644 index 000000000..33f076d50 --- /dev/null +++ b/test/features/earthquake/presentation/story_marker_layout_test.dart @@ -0,0 +1,528 @@ +import 'package:dpip/core/settings/locale_config.dart'; +import 'package:dpip/features/earthquake/domain/earthquake_report.dart'; +import 'package:dpip/features/earthquake/presentation/story_marker_layout.dart'; +import 'package:dpip/features/earthquake/presentation/story_observation_clustering.dart'; +import 'package:dpip/features/earthquake/presentation/widgets/earthquake_share_story_card.dart'; +import 'package:dpip/l10n/gen/app_localizations.dart'; +import 'package:dpip/shared/seismic/intensity_icon_renderer.dart'; +import 'package:dpip/shared/widgets/intensity_badge.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +const _canvas = Rect.fromLTWH(0, 0, 360, 640); +const _report = EarthquakeReport( + id: '115000-2026-0909-192104', + longitude: 120.76, + latitude: 24.54, + location: '苗栗縣西湖鄉', + depth: 11.1, + magnitude: 2.7, + time: 1788956464000, + trem: 0, + list: {}, +); +final _icon = StoryMarkerFootprint(icon: const Size.square(22)); + +void main() { + test('component bounds preserve the unused corners of the envelope', () { + final footprint = StoryMarkerFootprint( + icon: const Size.square(22), + badge: const Size(24, 13), + ); + expect(footprint.components, [ + const Rect.fromLTRB(-11, -18, 11, 4), + const Rect.fromLTRB(-5, 5, 19, 18), + ]); + expect(footprint.envelope, const Rect.fromLTRB(-11, -18, 19, 18)); + + const first = Offset(100, 100); + const second = Offset(80, 124); + expect(_place([(anchor: first, footprint: footprint), _at(second)]), [ + first, + second, + ]); + }); + + test('a single unblocked observation stays at its projected anchor', () { + const point = Offset(123.5, 212.25); + expect(_place([_at(point)]), [point]); + }); + + test('legend avoids original points, connectors and rendered components', () { + const safe = Rect.fromLTWH(16, 57, 328, 543); + const legend = Size(100, 24); + final placement = layoutStoryLegend( + legend: legend, + safeRegion: safe, + occupied: const [Rect.fromLTWH(130, 57, 102, 24)], + observations: const [Offset(42, 74)], + connectors: const [StoryConnector(Offset(256, 54), Offset(267, 90))], + ); + expect(placement, const Rect.fromLTWH(16, 78, 100, 24)); + expect( + layoutStoryLegend( + legend: legend, + safeRegion: safe, + occupied: const [safe], + observations: const [], + connectors: const [], + ), + isNull, + ); + }); + + test('the canvas contains both components at the right and bottom edges', () { + final wide = StoryMarkerFootprint( + icon: const Size.square(22), + badge: const Size(34, 14), + ); + const anchor = Offset(359, 639); + final center = _place([(anchor: anchor, footprint: wide)]).single; + final bounds = wide.envelope.shift(center); + expect(bounds.right, _canvas.right); + expect(bounds.bottom, _canvas.bottom); + + const farOutside = Offset(-120, 200); + expect(_place([_at(farOutside)]).single, const Offset(11, 200)); + }); + + test('epicenter and HUD take priority over an observation', () { + const epicenter = Rect.fromLTWH(162, 162, 36, 36); + const hud = Rect.fromLTRB(16, 202, 344, 592); + const anchor = Offset(180, 184); + final center = _place([_at(anchor)], epicenter: epicenter, hud: hud).single; + final icon = _icon.envelope.shift(center); + expect(icon.overlaps(epicenter), isFalse); + expect(icon.overlaps(hud), isFalse); + expect((center - anchor).distance, lessThanOrEqualTo(48)); + }); + + test('dense conflicts retain all markers within the displacement budget', () { + const anchor = Offset(180, 180); + final anchors = List.generate(20, (_) => _at(anchor)); + final centers = _place(anchors); + expect(centers, hasLength(anchors.length)); + expect(centers.first, anchor); + expect(centers.toSet().length, greaterThan(1)); + for (final center in centers) { + expect( + (center - anchor).distance, + lessThanOrEqualTo(storyMarkerDisplacementLimit + 1e-9), + ); + } + expect(_place(anchors), centers); + }); + + test( + 'displaced marker connects to its anchor without crossing a neighbor', + () { + const anchor = Offset(180, 180); + const neighbor = Offset(220, 180); + const epicenter = Rect.fromLTWH(162, 162, 36, 36); + final [first, moved] = _place([ + _at(neighbor), + _at(anchor), + ], epicenter: epicenter); + expect(first, neighbor); + expect(moved, isNot(anchor)); + expect( + StoryConnector( + anchor, + moved, + ).intersects(_icon.envelope.shift(neighbor)), + isFalse, + ); + }, + ); + + test( + 'connector checks detect stroke near a badge and interior crossings', + () { + const line = StoryConnector(Offset(0, 10), Offset(20, 10)); + expect(line.intersects(const Rect.fromLTWH(4, 10.5, 6, 4)), isTrue); + expect(line.intersects(const Rect.fromLTWH(4, 11, 6, 4)), isFalse); + expect(line.intersects(const Rect.fromLTWH(22, 8, 3, 4)), isFalse); + expect( + line.crosses(const StoryConnector(Offset(8, 0), Offset(8, 20))), + isTrue, + ); + expect( + line.crosses(const StoryConnector(Offset(4, 10), Offset(8, 10))), + isTrue, + ); + expect( + line.crosses(const StoryConnector(Offset(20, 10), Offset(20, 20))), + isFalse, + ); + }, + ); + + testWidgets('the count has its measured footprint clear of its own icon', ( + tester, + ) async { + _setViewport(tester); + final map = await _image(tester); + final icon = find.byWidgetPredicate( + (w) => w is IntensityBadge && w.size == 22, + ); + const point = Offset(345, 200); + for (final count in [1, 9, 10, 100]) { + final markers = [ + for (var i = 0; i < count; i++) + _marker('station-$i', point, intensity: 3), + ]; + double? unscaledWidth; + for (final scale in [1.0, 1.3, 1.6, 2.0, 3.0]) { + await _pump(tester, map, markers, scale: scale, useD75Compact: true); + final card = tester.getRect(find.byType(EarthquakeShareStoryCard)); + final iconRect = tester.getRect(icon); + expect(iconRect.size, const Size.square(22)); + if (count == 1) { + expect(_countBadge('$count'), findsNothing); + continue; + } + final badge = tester.getRect(_countBadge('$count')); + final label = tester.getRect(find.text('$count')); + expect(badge.right, iconRect.right + 8); + expect(badge.top, iconRect.bottom + 1); + expect(badge.overlaps(iconRect), isFalse); + expect( + badge.width, + label.width + 8, + ); // 3 px padding + 1 px border per side. + expect(badge.height, label.height + 4); + expect(badge.right, lessThanOrEqualTo(card.right)); + expect(badge.overlaps(tester.getRect(find.byType(ClipRRect))), isFalse); + if (unscaledWidth == null) { + unscaledWidth = badge.width; + } else { + expect(badge.width, unscaledWidth); + } + } + } + }); + + testWidgets( + 'all locales fit two fixed-size legend lines without hiding the map', + (tester) async { + _setViewport(tester); + final map = await _image(tester); + final markers = [ + _marker('in the first legend slot', const Offset(22, 65), intensity: 4), + _marker('elsewhere', const Offset(180, 220), intensity: 3), + ]; + final icon = find.byWidgetPredicate( + (widget) => widget is IntensityBadge && widget.size == 22, + ); + for (final locale in appSupportedLocales) { + await _pump( + tester, + map, + markers, + locale: locale, + scale: 3, + useD75Compact: true, + onLayoutUnavailable: () => fail('Legend should fit $locale'), + ); + final l10n = AppLocalizations.of( + tester.element(find.byType(EarthquakeShareStoryCard)), + ); + final count = l10n.reportDetailStoryLegendCount; + final intensity = l10n.reportDetailStoryLegendIntensity; + final semantic = find.bySemanticsLabel('$count\n$intensity'); + expect(semantic, findsOneWidget); + expect(find.bySemanticsLabel(count), findsNothing); + expect(find.bySemanticsLabel(intensity), findsNothing); + final box = tester.getRect(semantic); + expect(const Rect.fromLTRB(16, 57, 344, 600).intersect(box), box); + expect(box.topLeft, isNot(const Offset(16, 57))); + expect( + icon + .evaluate() + .map((e) => tester.getRect(find.byWidget(e.widget))) + .any(box.overlaps), + isFalse, + ); + expect(box.overlaps(tester.getRect(find.byType(ClipRRect))), isFalse); + for (final line in [count, intensity]) { + final text = find.text(line); + expect(MediaQuery.textScalerOf(tester.element(text)).scale(10), 10); + expect(box.intersect(tester.getRect(text)), tester.getRect(text)); + } + } + }, + ); + + testWidgets( + 'Story reads representative and single locations with report-specific intensity', + (tester) async { + _setViewport(tester); + final map = await _image(tester); + final report = _report.copyWith( + list: { + '宜蘭縣': AreaIntensity( + intensity: 9, + town: { + '南澳': StationIntensity( + latitude: 24, + longitude: 121, + intensity: 9, + ), + '南山': StationIntensity( + latitude: 24, + longitude: 120.9, + intensity: 1, + ), + '頭城': StationIntensity( + latitude: 24, + longitude: 121.2, + intensity: 3, + ), + }, + ), + }, + ); + for (final (level, label, spoken) in [ + (5, '5⁻', '五弱等級'), + (6, '5⁺', '五強等級'), + (7, '6⁻', '六弱等級'), + (8, '6⁺', '六強等級'), + (9, '7', '7'), + ]) { + final markers = [ + _marker('["宜蘭縣","南澳"]', const Offset(180, 220), intensity: level), + _marker( + '["宜蘭縣","南山"]', + const Offset(187, 222), + intensity: 1, + longitude: 120.9, + ), + _marker( + '["宜蘭縣","頭城"]', + const Offset(260, 270), + intensity: 3, + longitude: 121.2, + ), + ]; + await _pump( + tester, + map, + markers, + report: level == 9 + ? report.copyWith( + time: DateTime.utc(2018, 2, 6).millisecondsSinceEpoch, + ) + : report, + locale: const Locale('zh', 'TW'), + useD75Compact: true, + ); + expect( + find.bySemanticsLabel('2 筆觀測,群內最大震度 $spoken,代表觀測地點為宜蘭縣南澳'), + findsOneWidget, + ); + expect( + find.byWidgetPredicate( + (widget) => + widget is IntensityBadge && + widget.size == 22 && + widget.label == label, + ), + findsOneWidget, + ); + expect(find.bySemanticsLabel('宜蘭縣頭城,震度 3,一筆觀測'), findsOneWidget); + expect(find.bySemanticsLabel('2'), findsNothing); + expect(find.bySemanticsLabel('宜蘭縣南山'), findsNothing); + } + }, + ); + + testWidgets('system scaling leaves HUD and observation placement fixed', ( + tester, + ) async { + _setViewport(tester); + final map = await _image(tester); + final icon = find.byWidgetPredicate( + (w) => w is IntensityBadge && w.size == 22, + ); + const point = Offset(180, 363); + final markers = [_marker('station', point, intensity: 3)]; + await _pump(tester, map, markers); + final beforeHud = tester.getRect(find.byType(ClipRRect)); + final beforeIcon = tester.getRect(icon); + await _pump(tester, map, markers, scale: 1.15); + final afterHud = tester.getRect(find.byType(ClipRRect)); + final afterIcon = tester.getRect(icon); + expect(afterHud, beforeHud); + expect(afterIcon, beforeIcon); + expect(afterIcon.overlaps(afterHud), isFalse); + expect(markers.single.position, point); + }); + + testWidgets('the overlay paints a line only after moving a marker', ( + tester, + ) async { + _setViewport(tester); + final map = await _image(tester); + final cross = (await tester.runAsync( + () => IntensityIconRenderer.render('cross'), + ))!; + const anchor = Offset(180, 180); + final markers = [_marker('station', anchor, intensity: 3)]; + final icon = find.byWidgetPredicate( + (w) => w is IntensityBadge && w.size == 22, + ); + List lines() { + final overlay = find.ancestor( + of: icon, + matching: find.byWidgetPredicate( + (w) => + w is Stack && + w.children.any( + (child) => child is Positioned && child.width == 22, + ), + ), + ); + final canvas = TestRecordingCanvas(); + tester + .renderObject(overlay) + .paint(TestRecordingPaintingContext(canvas), Offset.zero); + return [ + for (final call in canvas.invocations) + if (call.invocation.memberName == #drawLine && + (call.invocation.positionalArguments[2] as Paint).strokeWidth == + StoryConnector.strokeWidth) + call.invocation, + ]; + } + + await _pump(tester, map, markers); + expect(lines(), isEmpty); + await _pump(tester, map, markers, epicenter: anchor, cross: cross); + final crossImage = find.byWidgetPredicate( + (w) => w is Image && w.width == 36, + ); + expect(tester.getCenter(crossImage), anchor); + expect(tester.getRect(crossImage).overlaps(tester.getRect(icon)), isFalse); + expect(lines().single.positionalArguments.take(2), [ + anchor, + tester.getCenter(icon), + ]); + }); + + testWidgets('equal-intensity placement follows canonical anchor priority', ( + tester, + ) async { + _setViewport(tester); + final map = await _image(tester); + const east = Offset(120, 180); + const west = Offset(91, 152); + final markers = [ + _marker('east', east, intensity: 3, longitude: 122), + for (var i = 0; i < 100; i++) _marker('west-$i', west, intensity: 3), + ]; + final icon = find.byWidgetPredicate( + (w) => w is IntensityBadge && w.size == 22, + ); + Iterable centers() { + final origin = tester.getTopLeft(find.byType(EarthquakeShareStoryCard)); + return [ + for (final e in icon.evaluate()) + tester.getCenter(find.byWidget(e.widget)) - origin, + ]; + } + + await _pump(tester, map, markers, scale: 2); + final positions = centers(); + expect(positions.last, east); + final badgeHeight = tester.getSize(_countBadge('100')).height; + expect(positions.first, isNot(west - Offset(0, (badgeHeight + 1) / 2))); + expect( + tester.getRect(_countBadge('100')).overlaps(tester.getRect(icon.last)), + isFalse, + ); + await _pump(tester, map, markers.reversed.toList(), scale: 2); + expect(centers(), positions); + }); +} + +StoryMarkerAnchor _at(Offset point) => (anchor: point, footprint: _icon); + +List _place( + List markers, { + Rect? epicenter, + Rect hud = Rect.zero, +}) => layoutStoryMarkers( + markers: markers, + canvas: _canvas, + epicenter: epicenter, + hud: hud, +); + +StoryStationMarker _marker( + String id, + Offset point, { + required int intensity, + double longitude = 121, +}) => StoryStationMarker( + sourceId: id, + latitude: 24, + longitude: longitude, + position: point, + intensity: intensity, +); + +Finder _countBadge(String count) => find.ancestor( + of: find.text(count), + matching: find.byWidgetPredicate( + (w) => w is Container && w.decoration is BoxDecoration, + ), +); + +void _setViewport(WidgetTester tester) { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = _canvas.size; + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.view.resetPhysicalSize); +} + +Future _image(WidgetTester tester) async => + (await tester.runAsync(() => IntensityIconRenderer.render('intensity-1')))!; + +Future _pump( + WidgetTester tester, + Uint8List map, + List markers, { + double scale = 1, + Offset? epicenter, + Uint8List? cross, + bool useD75Compact = false, + VoidCallback? onLayoutUnavailable, + Locale? locale, + EarthquakeReport report = _report, +}) => tester.pumpWidget( + MaterialApp( + locale: locale, + localizationsDelegates: appLocalizationsDelegates, + supportedLocales: appSupportedLocales, + home: Material( + child: Builder( + builder: (context) => MediaQuery( + data: MediaQuery.of(context) + .copyWith(textScaler: TextScaler.linear(scale)), + child: Center( + child: EarthquakeShareStoryCard( + report: report, + mapPng: map, + stationMarkers: markers, + epicenterPosition: epicenter, + markerIcons: {'cross': ?cross}, + useD75Compact: useD75Compact, + onLayoutUnavailable: onLayoutUnavailable, + ), + ), + ), + ), + ), + ), +);