From 1317ed8d81c5f6e17dbc701d0b2a5aab796a8d99 Mon Sep 17 00:00:00 2001 From: somethingGit <113336038+somethingGit@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:28:03 -0600 Subject: [PATCH 1/7] Replace the Leaflet WebView map with native MapLibre The OpenStreetMap fallback was the last HTML/CSS/JS in the app. It is now drawn natively by MapLibre, which is faster than a WebView. - Maps fall back to OpenStreetMap only when there is no API key; a failed Places search now switches only the search to Photon - Tile requests send the app's User-Agent, which OpenStreetMap requires - Fix RegistrationStatusScreenTest to expect the screen's real wording ("Won the Lottery" / "Lost the Lottery"), which failed every PR's UI tests Co-Authored-By: Claude Opus 5.5 --- code/app/build.gradle.kts | 1 + .../bookings/RegistrationStatusScreenTest.kt | 4 +- .../ui/campsites/OpenStreetMapUITest.kt | 130 ++-- code/app/src/main/assets/leaflet/LICENSE | 26 - code/app/src/main/assets/leaflet/leaflet.css | 661 ------------------ code/app/src/main/assets/leaflet/leaflet.js | 6 - .../model/services/MapProvider.kt | 18 +- .../view/ui/components/map/CampsiteMap.kt | 55 +- .../view/ui/components/map/ClickableMap.kt | 46 +- .../view/ui/components/map/GoogleMapViews.kt | 6 +- .../ui/components/map/MapsJavaScriptView.kt | 175 ----- .../ui/components/map/OpenStreetMapPage.kt | 171 ----- .../ui/components/map/OpenStreetMapViews.kt | 372 ++++++++++ .../services/FallbackPlaceSearchUnitTest.kt | 12 + code/gradle/libs.versions.toml | 2 + 15 files changed, 444 insertions(+), 1241 deletions(-) delete mode 100644 code/app/src/main/assets/leaflet/LICENSE delete mode 100644 code/app/src/main/assets/leaflet/leaflet.css delete mode 100644 code/app/src/main/assets/leaflet/leaflet.js delete mode 100644 code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/MapsJavaScriptView.kt delete mode 100644 code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/OpenStreetMapPage.kt create mode 100644 code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/OpenStreetMapViews.kt diff --git a/code/app/build.gradle.kts b/code/app/build.gradle.kts index edd08090..f90a8690 100644 --- a/code/app/build.gradle.kts +++ b/code/app/build.gradle.kts @@ -97,6 +97,7 @@ dependencies { implementation(libs.coil.network.okhttp) implementation(libs.libphonenumber) implementation(libs.maps.compose) + implementation(libs.maplibre.android) testImplementation(libs.kotlinx.coroutines.test) testImplementation(libs.junit) testImplementation(libs.mockk) diff --git a/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/bookings/RegistrationStatusScreenTest.kt b/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/bookings/RegistrationStatusScreenTest.kt index 0e0a683c..12a35e8b 100644 --- a/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/bookings/RegistrationStatusScreenTest.kt +++ b/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/bookings/RegistrationStatusScreenTest.kt @@ -107,8 +107,8 @@ class RegistrationStatusScreenTest { @Test fun showsMessageForEachStatus() { val expected = mapOf( - WaitlistStatus.WON to "Lottery Won", - WaitlistStatus.LOST to "Lottery Lost", + WaitlistStatus.WON to "Won the Lottery", + WaitlistStatus.LOST to "Lost the Lottery", WaitlistStatus.ACCEPTED to "Reservation Accepted", WaitlistStatus.DECLINED to "Reservation Declined" ) diff --git a/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/campsites/OpenStreetMapUITest.kt b/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/campsites/OpenStreetMapUITest.kt index 781087b6..2bb6bd1e 100644 --- a/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/campsites/OpenStreetMapUITest.kt +++ b/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/campsites/OpenStreetMapUITest.kt @@ -1,35 +1,29 @@ package com.example.lambda_bbb_events.ui.campsites import androidx.compose.foundation.layout.size -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.click import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.performTouchInput import androidx.compose.ui.unit.dp import androidx.test.ext.junit.runners.AndroidJUnit4 import com.example.lambda_bbb_events.model.campsite.Campsite -import com.example.lambda_bbb_events.view.ui.components.map.MapCommand -import com.example.lambda_bbb_events.view.ui.components.map.MapsJavaScriptView -import com.example.lambda_bbb_events.view.ui.components.map.osmCampsiteMapScript -import com.example.lambda_bbb_events.view.ui.components.map.osmClickableMapScript -import com.example.lambda_bbb_events.view.ui.components.map.osmPageHtml +import com.example.lambda_bbb_events.view.ui.components.map.OpenStreetCampsiteMap +import com.example.lambda_bbb_events.view.ui.components.map.OpenStreetClickableMap import com.google.android.gms.maps.model.LatLng -import org.json.JSONObject import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** - * Tests the OpenStreetMap pages in a real WebView with the bundled Leaflet. The map images are - * left out, so nothing is loaded from OpenStreetMap. + * Tests the native OpenStreetMap maps drawn by MapLibre. */ @RunWith(AndroidJUnit4::class) class OpenStreetMapUITest { @@ -37,94 +31,48 @@ class OpenStreetMapUITest { @get:Rule val composeTestRule = createComposeRule() - private val events = mutableListOf>() - private var command by mutableStateOf(null) - - private fun named(name: String) = events.filter { it.first == name }.map { it.second } - - private fun show(script: String) { - val page = osmPageHtml(script).replace("https://tile.openstreetmap.org/{z}/{x}/{y}.png", "data:,") - composeTestRule.setContent { - MapsJavaScriptView( - html = page, - modifier = Modifier.size(300.dp).testTag("map"), - command = command, - onEvent = { name, data -> events.add(name to data) } - ) + private val start = LatLng(51.1869, -115.5323) + + private val campsites = listOf( + Campsite(campsiteId = "a", campsiteName = "Lake", address = "1 Lake Rd", latitude = 51.18, longitude = -115.53), + Campsite(campsiteId = "b", campsiteName = "Ridge", address = "2 Ridge Rd", latitude = 51.25, longitude = -115.6) + ) + + /** + * Taps the picker beside its marker until the map is ready and reports the tap, then returns + * where it was reported. + */ + private fun tapPickerUntilSelected(selected: () -> LatLng?): LatLng? { + repeat(20) { + composeTestRule.onNodeWithTag("osm_picker").performTouchInput { click(centerLeft + (center - centerLeft) / 2f) } + composeTestRule.waitForIdle() + selected()?.let { return it } + Thread.sleep(500) } - } - - private fun waitFor(name: String) { - composeTestRule.waitUntil(15_000) { named(name).isNotEmpty() } - } - - private fun run(script: String) { - composeTestRule.runOnIdle { command = MapCommand(script) } - } - - private fun showLocationMap() { - show(osmClickableMapScript(LatLng(51.0, -115.0))) - waitFor("mapReady") - } - - @Test - fun tappingTheMapSelectsThatLocation() { - showLocationMap() - composeTestRule.onNodeWithTag("map").performTouchInput { click(percentOffset(0.75f, 0.75f)) } - waitFor("locationSelected") - - // Down and to the right of where the map starts - val location = named("locationSelected").last() - assertTrue("$location", location.getDouble("lat") in 50.9..50.9999) - assertTrue("$location", location.getDouble("lng") in -114.9999..-114.9) + return null } @Test - fun movingTheMapDoesNotSelectTheLocation() { - showLocationMap() - run("showLocation(52.9, -118.1); send('moved', { html: document.querySelectorAll('.leaflet-marker-icon').length });") - waitFor("moved") - assertFalse(events.any { it.first == "locationSelected" }) + fun campsiteMapShowsOpenStreetMapCredit() { + composeTestRule.setContent { + OpenStreetCampsiteMap(campsites, Modifier.size(300.dp), onCampsiteClick = null) + } - // The map is now centred on the new location, so tapping the middle area selects near it - composeTestRule.onNodeWithTag("map").performTouchInput { click(percentOffset(0.6f, 0.6f)) } - waitFor("locationSelected") - val location = named("locationSelected").last() - assertEquals(52.9, location.getDouble("lat"), 0.05) - assertEquals(-118.1, location.getDouble("lng"), 0.05) + composeTestRule.onNodeWithText("© OpenStreetMap contributors").assertIsDisplayed() } @Test - fun openStreetMapIsCredited() { - showLocationMap() - run("send('credit', { text: document.querySelector('.leaflet-control-attribution').textContent });") - waitFor("credit") - - assertTrue(named("credit").last().getString("text").contains("OpenStreetMap contributors")) - } + fun tappingThePickerSelectsWhereItWasTapped() { + var selected: LatLng? = null + composeTestRule.setContent { + OpenStreetClickableMap(start, null, Modifier.size(300.dp).testTag("osm_picker")) { selected = it } + } - @Test - fun campsiteMarkersOpenTheCampsite() { - val sneaky = "Bob's \"Camp\" " - show( - osmCampsiteMapScript( - listOf( - Campsite(campsiteId = "a", campsiteName = sneaky, address = "1 Lake Rd", latitude = 53.5, longitude = -113.5), - Campsite(campsiteId = "b", campsiteName = "Forest", address = "9 Pine St", latitude = 51.2, longitude = -115.6) - ) - ) + "\nconst drawn = initMap; initMap = function () { drawn(); send('drawn'); };" - ) - waitFor("drawn") - run( - "const pins = document.querySelectorAll('.leaflet-marker-icon'); pins[0].click();" + - "send('pins', { count: pins.length, name: document.querySelector('.info b').textContent });" + - "document.querySelector('.info a').click();" - ) - waitFor("campsiteClick") + val tapped = tapPickerUntilSelected { selected } - assertEquals(2, named("pins").last().getInt("count")) - assertEquals(sneaky, named("pins").last().getString("name")) - assertEquals("a", named("campsiteClick").last().getString("id")) - assertFalse(events.any { it.first == "hacked" }) + assertNotNull(tapped) + assertEquals(start.latitude, tapped!!.latitude, 0.01) + assertTrue(tapped.longitude < start.longitude) + assertTrue(tapped.longitude > start.longitude - 0.05) } } diff --git a/code/app/src/main/assets/leaflet/LICENSE b/code/app/src/main/assets/leaflet/LICENSE deleted file mode 100644 index bcb3ba1a..00000000 --- a/code/app/src/main/assets/leaflet/LICENSE +++ /dev/null @@ -1,26 +0,0 @@ -BSD 2-Clause License - -Copyright (c) 2010-2023, Volodymyr Agafonkin -Copyright (c) 2010-2011, CloudMade -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/code/app/src/main/assets/leaflet/leaflet.css b/code/app/src/main/assets/leaflet/leaflet.css deleted file mode 100644 index 2961b761..00000000 --- a/code/app/src/main/assets/leaflet/leaflet.css +++ /dev/null @@ -1,661 +0,0 @@ -/* required styles */ - -.leaflet-pane, -.leaflet-tile, -.leaflet-marker-icon, -.leaflet-marker-shadow, -.leaflet-tile-container, -.leaflet-pane > svg, -.leaflet-pane > canvas, -.leaflet-zoom-box, -.leaflet-image-layer, -.leaflet-layer { - position: absolute; - left: 0; - top: 0; - } -.leaflet-container { - overflow: hidden; - } -.leaflet-tile, -.leaflet-marker-icon, -.leaflet-marker-shadow { - -webkit-user-select: none; - -moz-user-select: none; - user-select: none; - -webkit-user-drag: none; - } -/* Prevents IE11 from highlighting tiles in blue */ -.leaflet-tile::selection { - background: transparent; -} -/* Safari renders non-retina tile on retina better with this, but Chrome is worse */ -.leaflet-safari .leaflet-tile { - image-rendering: -webkit-optimize-contrast; - } -/* hack that prevents hw layers "stretching" when loading new tiles */ -.leaflet-safari .leaflet-tile-container { - width: 1600px; - height: 1600px; - -webkit-transform-origin: 0 0; - } -.leaflet-marker-icon, -.leaflet-marker-shadow { - display: block; - } -/* .leaflet-container svg: reset svg max-width decleration shipped in Joomla! (joomla.org) 3.x */ -/* .leaflet-container img: map is broken in FF if you have max-width: 100% on tiles */ -.leaflet-container .leaflet-overlay-pane svg { - max-width: none !important; - max-height: none !important; - } -.leaflet-container .leaflet-marker-pane img, -.leaflet-container .leaflet-shadow-pane img, -.leaflet-container .leaflet-tile-pane img, -.leaflet-container img.leaflet-image-layer, -.leaflet-container .leaflet-tile { - max-width: none !important; - max-height: none !important; - width: auto; - padding: 0; - } - -.leaflet-container img.leaflet-tile { - /* See: https://bugs.chromium.org/p/chromium/issues/detail?id=600120 */ - mix-blend-mode: plus-lighter; -} - -.leaflet-container.leaflet-touch-zoom { - -ms-touch-action: pan-x pan-y; - touch-action: pan-x pan-y; - } -.leaflet-container.leaflet-touch-drag { - -ms-touch-action: pinch-zoom; - /* Fallback for FF which doesn't support pinch-zoom */ - touch-action: none; - touch-action: pinch-zoom; -} -.leaflet-container.leaflet-touch-drag.leaflet-touch-zoom { - -ms-touch-action: none; - touch-action: none; -} -.leaflet-container { - -webkit-tap-highlight-color: transparent; -} -.leaflet-container a { - -webkit-tap-highlight-color: rgba(51, 181, 229, 0.4); -} -.leaflet-tile { - filter: inherit; - visibility: hidden; - } -.leaflet-tile-loaded { - visibility: inherit; - } -.leaflet-zoom-box { - width: 0; - height: 0; - -moz-box-sizing: border-box; - box-sizing: border-box; - z-index: 800; - } -/* workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=888319 */ -.leaflet-overlay-pane svg { - -moz-user-select: none; - } - -.leaflet-pane { z-index: 400; } - -.leaflet-tile-pane { z-index: 200; } -.leaflet-overlay-pane { z-index: 400; } -.leaflet-shadow-pane { z-index: 500; } -.leaflet-marker-pane { z-index: 600; } -.leaflet-tooltip-pane { z-index: 650; } -.leaflet-popup-pane { z-index: 700; } - -.leaflet-map-pane canvas { z-index: 100; } -.leaflet-map-pane svg { z-index: 200; } - -.leaflet-vml-shape { - width: 1px; - height: 1px; - } -.lvml { - behavior: url(#default#VML); - display: inline-block; - position: absolute; - } - - -/* control positioning */ - -.leaflet-control { - position: relative; - z-index: 800; - pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */ - pointer-events: auto; - } -.leaflet-top, -.leaflet-bottom { - position: absolute; - z-index: 1000; - pointer-events: none; - } -.leaflet-top { - top: 0; - } -.leaflet-right { - right: 0; - } -.leaflet-bottom { - bottom: 0; - } -.leaflet-left { - left: 0; - } -.leaflet-control { - float: left; - clear: both; - } -.leaflet-right .leaflet-control { - float: right; - } -.leaflet-top .leaflet-control { - margin-top: 10px; - } -.leaflet-bottom .leaflet-control { - margin-bottom: 10px; - } -.leaflet-left .leaflet-control { - margin-left: 10px; - } -.leaflet-right .leaflet-control { - margin-right: 10px; - } - - -/* zoom and fade animations */ - -.leaflet-fade-anim .leaflet-popup { - opacity: 0; - -webkit-transition: opacity 0.2s linear; - -moz-transition: opacity 0.2s linear; - transition: opacity 0.2s linear; - } -.leaflet-fade-anim .leaflet-map-pane .leaflet-popup { - opacity: 1; - } -.leaflet-zoom-animated { - -webkit-transform-origin: 0 0; - -ms-transform-origin: 0 0; - transform-origin: 0 0; - } -svg.leaflet-zoom-animated { - will-change: transform; -} - -.leaflet-zoom-anim .leaflet-zoom-animated { - -webkit-transition: -webkit-transform 0.25s cubic-bezier(0,0,0.25,1); - -moz-transition: -moz-transform 0.25s cubic-bezier(0,0,0.25,1); - transition: transform 0.25s cubic-bezier(0,0,0.25,1); - } -.leaflet-zoom-anim .leaflet-tile, -.leaflet-pan-anim .leaflet-tile { - -webkit-transition: none; - -moz-transition: none; - transition: none; - } - -.leaflet-zoom-anim .leaflet-zoom-hide { - visibility: hidden; - } - - -/* cursors */ - -.leaflet-interactive { - cursor: pointer; - } -.leaflet-grab { - cursor: -webkit-grab; - cursor: -moz-grab; - cursor: grab; - } -.leaflet-crosshair, -.leaflet-crosshair .leaflet-interactive { - cursor: crosshair; - } -.leaflet-popup-pane, -.leaflet-control { - cursor: auto; - } -.leaflet-dragging .leaflet-grab, -.leaflet-dragging .leaflet-grab .leaflet-interactive, -.leaflet-dragging .leaflet-marker-draggable { - cursor: move; - cursor: -webkit-grabbing; - cursor: -moz-grabbing; - cursor: grabbing; - } - -/* marker & overlays interactivity */ -.leaflet-marker-icon, -.leaflet-marker-shadow, -.leaflet-image-layer, -.leaflet-pane > svg path, -.leaflet-tile-container { - pointer-events: none; - } - -.leaflet-marker-icon.leaflet-interactive, -.leaflet-image-layer.leaflet-interactive, -.leaflet-pane > svg path.leaflet-interactive, -svg.leaflet-image-layer.leaflet-interactive path { - pointer-events: visiblePainted; /* IE 9-10 doesn't have auto */ - pointer-events: auto; - } - -/* visual tweaks */ - -.leaflet-container { - background: #ddd; - outline-offset: 1px; - } -.leaflet-container a { - color: #0078A8; - } -.leaflet-zoom-box { - border: 2px dotted #38f; - background: rgba(255,255,255,0.5); - } - - -/* general typography */ -.leaflet-container { - font-family: "Helvetica Neue", Arial, Helvetica, sans-serif; - font-size: 12px; - font-size: 0.75rem; - line-height: 1.5; - } - - -/* general toolbar styles */ - -.leaflet-bar { - box-shadow: 0 1px 5px rgba(0,0,0,0.65); - border-radius: 4px; - } -.leaflet-bar a { - background-color: #fff; - border-bottom: 1px solid #ccc; - width: 26px; - height: 26px; - line-height: 26px; - display: block; - text-align: center; - text-decoration: none; - color: black; - } -.leaflet-bar a, -.leaflet-control-layers-toggle { - background-position: 50% 50%; - background-repeat: no-repeat; - display: block; - } -.leaflet-bar a:hover, -.leaflet-bar a:focus { - background-color: #f4f4f4; - } -.leaflet-bar a:first-child { - border-top-left-radius: 4px; - border-top-right-radius: 4px; - } -.leaflet-bar a:last-child { - border-bottom-left-radius: 4px; - border-bottom-right-radius: 4px; - border-bottom: none; - } -.leaflet-bar a.leaflet-disabled { - cursor: default; - background-color: #f4f4f4; - color: #bbb; - } - -.leaflet-touch .leaflet-bar a { - width: 30px; - height: 30px; - line-height: 30px; - } -.leaflet-touch .leaflet-bar a:first-child { - border-top-left-radius: 2px; - border-top-right-radius: 2px; - } -.leaflet-touch .leaflet-bar a:last-child { - border-bottom-left-radius: 2px; - border-bottom-right-radius: 2px; - } - -/* zoom control */ - -.leaflet-control-zoom-in, -.leaflet-control-zoom-out { - font: bold 18px 'Lucida Console', Monaco, monospace; - text-indent: 1px; - } - -.leaflet-touch .leaflet-control-zoom-in, .leaflet-touch .leaflet-control-zoom-out { - font-size: 22px; - } - - -/* layers control */ - -.leaflet-control-layers { - box-shadow: 0 1px 5px rgba(0,0,0,0.4); - background: #fff; - border-radius: 5px; - } -.leaflet-control-layers-toggle { - background-image: url(images/layers.png); - width: 36px; - height: 36px; - } -.leaflet-retina .leaflet-control-layers-toggle { - background-image: url(images/layers-2x.png); - background-size: 26px 26px; - } -.leaflet-touch .leaflet-control-layers-toggle { - width: 44px; - height: 44px; - } -.leaflet-control-layers .leaflet-control-layers-list, -.leaflet-control-layers-expanded .leaflet-control-layers-toggle { - display: none; - } -.leaflet-control-layers-expanded .leaflet-control-layers-list { - display: block; - position: relative; - } -.leaflet-control-layers-expanded { - padding: 6px 10px 6px 6px; - color: #333; - background: #fff; - } -.leaflet-control-layers-scrollbar { - overflow-y: scroll; - overflow-x: hidden; - padding-right: 5px; - } -.leaflet-control-layers-selector { - margin-top: 2px; - position: relative; - top: 1px; - } -.leaflet-control-layers label { - display: block; - font-size: 13px; - font-size: 1.08333em; - } -.leaflet-control-layers-separator { - height: 0; - border-top: 1px solid #ddd; - margin: 5px -10px 5px -6px; - } - -/* Default icon URLs */ -.leaflet-default-icon-path { /* used only in path-guessing heuristic, see L.Icon.Default */ - background-image: url(images/marker-icon.png); - } - - -/* attribution and scale controls */ - -.leaflet-container .leaflet-control-attribution { - background: #fff; - background: rgba(255, 255, 255, 0.8); - margin: 0; - } -.leaflet-control-attribution, -.leaflet-control-scale-line { - padding: 0 5px; - color: #333; - line-height: 1.4; - } -.leaflet-control-attribution a { - text-decoration: none; - } -.leaflet-control-attribution a:hover, -.leaflet-control-attribution a:focus { - text-decoration: underline; - } -.leaflet-attribution-flag { - display: inline !important; - vertical-align: baseline !important; - width: 1em; - height: 0.6669em; - } -.leaflet-left .leaflet-control-scale { - margin-left: 5px; - } -.leaflet-bottom .leaflet-control-scale { - margin-bottom: 5px; - } -.leaflet-control-scale-line { - border: 2px solid #777; - border-top: none; - line-height: 1.1; - padding: 2px 5px 1px; - white-space: nowrap; - -moz-box-sizing: border-box; - box-sizing: border-box; - background: rgba(255, 255, 255, 0.8); - text-shadow: 1px 1px #fff; - } -.leaflet-control-scale-line:not(:first-child) { - border-top: 2px solid #777; - border-bottom: none; - margin-top: -2px; - } -.leaflet-control-scale-line:not(:first-child):not(:last-child) { - border-bottom: 2px solid #777; - } - -.leaflet-touch .leaflet-control-attribution, -.leaflet-touch .leaflet-control-layers, -.leaflet-touch .leaflet-bar { - box-shadow: none; - } -.leaflet-touch .leaflet-control-layers, -.leaflet-touch .leaflet-bar { - border: 2px solid rgba(0,0,0,0.2); - background-clip: padding-box; - } - - -/* popup */ - -.leaflet-popup { - position: absolute; - text-align: center; - margin-bottom: 20px; - } -.leaflet-popup-content-wrapper { - padding: 1px; - text-align: left; - border-radius: 12px; - } -.leaflet-popup-content { - margin: 13px 24px 13px 20px; - line-height: 1.3; - font-size: 13px; - font-size: 1.08333em; - min-height: 1px; - } -.leaflet-popup-content p { - margin: 17px 0; - margin: 1.3em 0; - } -.leaflet-popup-tip-container { - width: 40px; - height: 20px; - position: absolute; - left: 50%; - margin-top: -1px; - margin-left: -20px; - overflow: hidden; - pointer-events: none; - } -.leaflet-popup-tip { - width: 17px; - height: 17px; - padding: 1px; - - margin: -10px auto 0; - pointer-events: auto; - - -webkit-transform: rotate(45deg); - -moz-transform: rotate(45deg); - -ms-transform: rotate(45deg); - transform: rotate(45deg); - } -.leaflet-popup-content-wrapper, -.leaflet-popup-tip { - background: white; - color: #333; - box-shadow: 0 3px 14px rgba(0,0,0,0.4); - } -.leaflet-container a.leaflet-popup-close-button { - position: absolute; - top: 0; - right: 0; - border: none; - text-align: center; - width: 24px; - height: 24px; - font: 16px/24px Tahoma, Verdana, sans-serif; - color: #757575; - text-decoration: none; - background: transparent; - } -.leaflet-container a.leaflet-popup-close-button:hover, -.leaflet-container a.leaflet-popup-close-button:focus { - color: #585858; - } -.leaflet-popup-scrolled { - overflow: auto; - } - -.leaflet-oldie .leaflet-popup-content-wrapper { - -ms-zoom: 1; - } -.leaflet-oldie .leaflet-popup-tip { - width: 24px; - margin: 0 auto; - - -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)"; - filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678); - } - -.leaflet-oldie .leaflet-control-zoom, -.leaflet-oldie .leaflet-control-layers, -.leaflet-oldie .leaflet-popup-content-wrapper, -.leaflet-oldie .leaflet-popup-tip { - border: 1px solid #999; - } - - -/* div icon */ - -.leaflet-div-icon { - background: #fff; - border: 1px solid #666; - } - - -/* Tooltip */ -/* Base styles for the element that has a tooltip */ -.leaflet-tooltip { - position: absolute; - padding: 6px; - background-color: #fff; - border: 1px solid #fff; - border-radius: 3px; - color: #222; - white-space: nowrap; - -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; - pointer-events: none; - box-shadow: 0 1px 3px rgba(0,0,0,0.4); - } -.leaflet-tooltip.leaflet-interactive { - cursor: pointer; - pointer-events: auto; - } -.leaflet-tooltip-top:before, -.leaflet-tooltip-bottom:before, -.leaflet-tooltip-left:before, -.leaflet-tooltip-right:before { - position: absolute; - pointer-events: none; - border: 6px solid transparent; - background: transparent; - content: ""; - } - -/* Directions */ - -.leaflet-tooltip-bottom { - margin-top: 6px; -} -.leaflet-tooltip-top { - margin-top: -6px; -} -.leaflet-tooltip-bottom:before, -.leaflet-tooltip-top:before { - left: 50%; - margin-left: -6px; - } -.leaflet-tooltip-top:before { - bottom: 0; - margin-bottom: -12px; - border-top-color: #fff; - } -.leaflet-tooltip-bottom:before { - top: 0; - margin-top: -12px; - margin-left: -6px; - border-bottom-color: #fff; - } -.leaflet-tooltip-left { - margin-left: -6px; -} -.leaflet-tooltip-right { - margin-left: 6px; -} -.leaflet-tooltip-left:before, -.leaflet-tooltip-right:before { - top: 50%; - margin-top: -6px; - } -.leaflet-tooltip-left:before { - right: 0; - margin-right: -12px; - border-left-color: #fff; - } -.leaflet-tooltip-right:before { - left: 0; - margin-left: -12px; - border-right-color: #fff; - } - -/* Printing */ - -@media print { - /* Prevent printers from removing background-images of controls. */ - .leaflet-control { - -webkit-print-color-adjust: exact; - print-color-adjust: exact; - } - } diff --git a/code/app/src/main/assets/leaflet/leaflet.js b/code/app/src/main/assets/leaflet/leaflet.js deleted file mode 100644 index a3bf693d..00000000 --- a/code/app/src/main/assets/leaflet/leaflet.js +++ /dev/null @@ -1,6 +0,0 @@ -/* @preserve - * Leaflet 1.9.4, a JS library for interactive maps. https://leafletjs.com - * (c) 2010-2023 Vladimir Agafonkin, (c) 2010-2011 CloudMade - */ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).leaflet={})}(this,function(t){"use strict";function l(t){for(var e,i,n=1,o=arguments.length;n=this.min.x&&i.x<=this.max.x&&e.y>=this.min.y&&i.y<=this.max.y},intersects:function(t){t=_(t);var e=this.min,i=this.max,n=t.min,t=t.max,o=t.x>=e.x&&n.x<=i.x,t=t.y>=e.y&&n.y<=i.y;return o&&t},overlaps:function(t){t=_(t);var e=this.min,i=this.max,n=t.min,t=t.max,o=t.x>e.x&&n.xe.y&&n.y=n.lat&&i.lat<=o.lat&&e.lng>=n.lng&&i.lng<=o.lng},intersects:function(t){t=g(t);var e=this._southWest,i=this._northEast,n=t.getSouthWest(),t=t.getNorthEast(),o=t.lat>=e.lat&&n.lat<=i.lat,t=t.lng>=e.lng&&n.lng<=i.lng;return o&&t},overlaps:function(t){t=g(t);var e=this._southWest,i=this._northEast,n=t.getSouthWest(),t=t.getNorthEast(),o=t.lat>e.lat&&n.late.lng&&n.lng","http://www.w3.org/2000/svg"===(Wt.firstChild&&Wt.firstChild.namespaceURI));function y(t){return 0<=navigator.userAgent.toLowerCase().indexOf(t)}var b={ie:pt,ielt9:mt,edge:n,webkit:ft,android:gt,android23:vt,androidStock:yt,opera:xt,chrome:wt,gecko:bt,safari:Pt,phantom:Lt,opera12:o,win:Tt,ie3d:Mt,webkit3d:zt,gecko3d:_t,any3d:Ct,mobile:Zt,mobileWebkit:St,mobileWebkit3d:Et,msPointer:kt,pointer:Ot,touch:Bt,touchNative:At,mobileOpera:It,mobileGecko:Rt,retina:Nt,passiveEvents:Dt,canvas:jt,svg:Ht,vml:!Ht&&function(){try{var t=document.createElement("div"),e=(t.innerHTML='',t.firstChild);return e.style.behavior="url(#default#VML)",e&&"object"==typeof e.adj}catch(t){return!1}}(),inlineSvg:Wt,mac:0===navigator.platform.indexOf("Mac"),linux:0===navigator.platform.indexOf("Linux")},Ft=b.msPointer?"MSPointerDown":"pointerdown",Ut=b.msPointer?"MSPointerMove":"pointermove",Vt=b.msPointer?"MSPointerUp":"pointerup",qt=b.msPointer?"MSPointerCancel":"pointercancel",Gt={touchstart:Ft,touchmove:Ut,touchend:Vt,touchcancel:qt},Kt={touchstart:function(t,e){e.MSPOINTER_TYPE_TOUCH&&e.pointerType===e.MSPOINTER_TYPE_TOUCH&&O(e);ee(t,e)},touchmove:ee,touchend:ee,touchcancel:ee},Yt={},Xt=!1;function Jt(t,e,i){return"touchstart"!==e||Xt||(document.addEventListener(Ft,$t,!0),document.addEventListener(Ut,Qt,!0),document.addEventListener(Vt,te,!0),document.addEventListener(qt,te,!0),Xt=!0),Kt[e]?(i=Kt[e].bind(this,i),t.addEventListener(Gt[e],i,!1),i):(console.warn("wrong event specified:",e),u)}function $t(t){Yt[t.pointerId]=t}function Qt(t){Yt[t.pointerId]&&(Yt[t.pointerId]=t)}function te(t){delete Yt[t.pointerId]}function ee(t,e){if(e.pointerType!==(e.MSPOINTER_TYPE_MOUSE||"mouse")){for(var i in e.touches=[],Yt)e.touches.push(Yt[i]);e.changedTouches=[e],t(e)}}var ie=200;function ne(t,i){t.addEventListener("dblclick",i);var n,o=0;function e(t){var e;1!==t.detail?n=t.detail:"mouse"===t.pointerType||t.sourceCapabilities&&!t.sourceCapabilities.firesTouchEvents||((e=Ne(t)).some(function(t){return t instanceof HTMLLabelElement&&t.attributes.for})&&!e.some(function(t){return t instanceof HTMLInputElement||t instanceof HTMLSelectElement})||((e=Date.now())-o<=ie?2===++n&&i(function(t){var e,i,n={};for(i in t)e=t[i],n[i]=e&&e.bind?e.bind(t):e;return(t=n).type="dblclick",n.detail=2,n.isTrusted=!1,n._simulated=!0,n}(t)):n=1,o=e))}return t.addEventListener("click",e),{dblclick:i,simDblclick:e}}var oe,se,re,ae,he,le,ue=we(["transform","webkitTransform","OTransform","MozTransform","msTransform"]),ce=we(["webkitTransition","transition","OTransition","MozTransition","msTransition"]),de="webkitTransition"===ce||"OTransition"===ce?ce+"End":"transitionend";function _e(t){return"string"==typeof t?document.getElementById(t):t}function pe(t,e){var i=t.style[e]||t.currentStyle&&t.currentStyle[e];return"auto"===(i=i&&"auto"!==i||!document.defaultView?i:(t=document.defaultView.getComputedStyle(t,null))?t[e]:null)?null:i}function P(t,e,i){t=document.createElement(t);return t.className=e||"",i&&i.appendChild(t),t}function T(t){var e=t.parentNode;e&&e.removeChild(t)}function me(t){for(;t.firstChild;)t.removeChild(t.firstChild)}function fe(t){var e=t.parentNode;e&&e.lastChild!==t&&e.appendChild(t)}function ge(t){var e=t.parentNode;e&&e.firstChild!==t&&e.insertBefore(t,e.firstChild)}function ve(t,e){return void 0!==t.classList?t.classList.contains(e):0<(t=xe(t)).length&&new RegExp("(^|\\s)"+e+"(\\s|$)").test(t)}function M(t,e){var i;if(void 0!==t.classList)for(var n=F(e),o=0,s=n.length;othis.options.maxZoom)?this.setZoom(t):this},panInsideBounds:function(t,e){this._enforcingBounds=!0;var i=this.getCenter(),t=this._limitCenter(i,this._zoom,g(t));return i.equals(t)||this.panTo(t,e),this._enforcingBounds=!1,this},panInside:function(t,e){var i=m((e=e||{}).paddingTopLeft||e.padding||[0,0]),n=m(e.paddingBottomRight||e.padding||[0,0]),o=this.project(this.getCenter()),t=this.project(t),s=this.getPixelBounds(),i=_([s.min.add(i),s.max.subtract(n)]),s=i.getSize();return i.contains(t)||(this._enforcingBounds=!0,n=t.subtract(i.getCenter()),i=i.extend(t).getSize().subtract(s),o.x+=n.x<0?-i.x:i.x,o.y+=n.y<0?-i.y:i.y,this.panTo(this.unproject(o),e),this._enforcingBounds=!1),this},invalidateSize:function(t){if(!this._loaded)return this;t=l({animate:!1,pan:!0},!0===t?{animate:!0}:t);var e=this.getSize(),i=(this._sizeChanged=!0,this._lastCenter=null,this.getSize()),n=e.divideBy(2).round(),o=i.divideBy(2).round(),n=n.subtract(o);return n.x||n.y?(t.animate&&t.pan?this.panBy(n):(t.pan&&this._rawPanBy(n),this.fire("move"),t.debounceMoveend?(clearTimeout(this._sizeTimer),this._sizeTimer=setTimeout(a(this.fire,this,"moveend"),200)):this.fire("moveend")),this.fire("resize",{oldSize:e,newSize:i})):this},stop:function(){return this.setZoom(this._limitZoom(this._zoom)),this.options.zoomSnap||this.fire("viewreset"),this._stop()},locate:function(t){var e,i;return t=this._locateOptions=l({timeout:1e4,watch:!1},t),"geolocation"in navigator?(e=a(this._handleGeolocationResponse,this),i=a(this._handleGeolocationError,this),t.watch?this._locationWatchId=navigator.geolocation.watchPosition(e,i,t):navigator.geolocation.getCurrentPosition(e,i,t)):this._handleGeolocationError({code:0,message:"Geolocation not supported."}),this},stopLocate:function(){return navigator.geolocation&&navigator.geolocation.clearWatch&&navigator.geolocation.clearWatch(this._locationWatchId),this._locateOptions&&(this._locateOptions.setView=!1),this},_handleGeolocationError:function(t){var e;this._container._leaflet_id&&(e=t.code,t=t.message||(1===e?"permission denied":2===e?"position unavailable":"timeout"),this._locateOptions.setView&&!this._loaded&&this.fitWorld(),this.fire("locationerror",{code:e,message:"Geolocation error: "+t+"."}))},_handleGeolocationResponse:function(t){if(this._container._leaflet_id){var e,i,n=new v(t.coords.latitude,t.coords.longitude),o=n.toBounds(2*t.coords.accuracy),s=this._locateOptions,r=(s.setView&&(e=this.getBoundsZoom(o),this.setView(n,s.maxZoom?Math.min(e,s.maxZoom):e)),{latlng:n,bounds:o,timestamp:t.timestamp});for(i in t.coords)"number"==typeof t.coords[i]&&(r[i]=t.coords[i]);this.fire("locationfound",r)}},addHandler:function(t,e){return e&&(e=this[t]=new e(this),this._handlers.push(e),this.options[t]&&e.enable()),this},remove:function(){if(this._initEvents(!0),this.options.maxBounds&&this.off("moveend",this._panInsideMaxBounds),this._containerId!==this._container._leaflet_id)throw new Error("Map container is being reused by another instance");try{delete this._container._leaflet_id,delete this._containerId}catch(t){this._container._leaflet_id=void 0,this._containerId=void 0}for(var t in void 0!==this._locationWatchId&&this.stopLocate(),this._stop(),T(this._mapPane),this._clearControlPos&&this._clearControlPos(),this._resizeRequest&&(r(this._resizeRequest),this._resizeRequest=null),this._clearHandlers(),this._loaded&&this.fire("unload"),this._layers)this._layers[t].remove();for(t in this._panes)T(this._panes[t]);return this._layers=[],this._panes=[],delete this._mapPane,delete this._renderer,this},createPane:function(t,e){e=P("div","leaflet-pane"+(t?" leaflet-"+t.replace("Pane","")+"-pane":""),e||this._mapPane);return t&&(this._panes[t]=e),e},getCenter:function(){return this._checkIfLoaded(),this._lastCenter&&!this._moved()?this._lastCenter.clone():this.layerPointToLatLng(this._getCenterLayerPoint())},getZoom:function(){return this._zoom},getBounds:function(){var t=this.getPixelBounds();return new s(this.unproject(t.getBottomLeft()),this.unproject(t.getTopRight()))},getMinZoom:function(){return void 0===this.options.minZoom?this._layersMinZoom||0:this.options.minZoom},getMaxZoom:function(){return void 0===this.options.maxZoom?void 0===this._layersMaxZoom?1/0:this._layersMaxZoom:this.options.maxZoom},getBoundsZoom:function(t,e,i){t=g(t),i=m(i||[0,0]);var n=this.getZoom()||0,o=this.getMinZoom(),s=this.getMaxZoom(),r=t.getNorthWest(),t=t.getSouthEast(),i=this.getSize().subtract(i),t=_(this.project(t,n),this.project(r,n)).getSize(),r=b.any3d?this.options.zoomSnap:1,a=i.x/t.x,i=i.y/t.y,t=e?Math.max(a,i):Math.min(a,i),n=this.getScaleZoom(t,n);return r&&(n=Math.round(n/(r/100))*(r/100),n=e?Math.ceil(n/r)*r:Math.floor(n/r)*r),Math.max(o,Math.min(s,n))},getSize:function(){return this._size&&!this._sizeChanged||(this._size=new p(this._container.clientWidth||0,this._container.clientHeight||0),this._sizeChanged=!1),this._size.clone()},getPixelBounds:function(t,e){t=this._getTopLeftPoint(t,e);return new f(t,t.add(this.getSize()))},getPixelOrigin:function(){return this._checkIfLoaded(),this._pixelOrigin},getPixelWorldBounds:function(t){return this.options.crs.getProjectedBounds(void 0===t?this.getZoom():t)},getPane:function(t){return"string"==typeof t?this._panes[t]:t},getPanes:function(){return this._panes},getContainer:function(){return this._container},getZoomScale:function(t,e){var i=this.options.crs;return e=void 0===e?this._zoom:e,i.scale(t)/i.scale(e)},getScaleZoom:function(t,e){var i=this.options.crs,t=(e=void 0===e?this._zoom:e,i.zoom(t*i.scale(e)));return isNaN(t)?1/0:t},project:function(t,e){return e=void 0===e?this._zoom:e,this.options.crs.latLngToPoint(w(t),e)},unproject:function(t,e){return e=void 0===e?this._zoom:e,this.options.crs.pointToLatLng(m(t),e)},layerPointToLatLng:function(t){t=m(t).add(this.getPixelOrigin());return this.unproject(t)},latLngToLayerPoint:function(t){return this.project(w(t))._round()._subtract(this.getPixelOrigin())},wrapLatLng:function(t){return this.options.crs.wrapLatLng(w(t))},wrapLatLngBounds:function(t){return this.options.crs.wrapLatLngBounds(g(t))},distance:function(t,e){return this.options.crs.distance(w(t),w(e))},containerPointToLayerPoint:function(t){return m(t).subtract(this._getMapPanePos())},layerPointToContainerPoint:function(t){return m(t).add(this._getMapPanePos())},containerPointToLatLng:function(t){t=this.containerPointToLayerPoint(m(t));return this.layerPointToLatLng(t)},latLngToContainerPoint:function(t){return this.layerPointToContainerPoint(this.latLngToLayerPoint(w(t)))},mouseEventToContainerPoint:function(t){return De(t,this._container)},mouseEventToLayerPoint:function(t){return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(t))},mouseEventToLatLng:function(t){return this.layerPointToLatLng(this.mouseEventToLayerPoint(t))},_initContainer:function(t){t=this._container=_e(t);if(!t)throw new Error("Map container not found.");if(t._leaflet_id)throw new Error("Map container is already initialized.");S(t,"scroll",this._onScroll,this),this._containerId=h(t)},_initLayout:function(){var t=this._container,e=(this._fadeAnimated=this.options.fadeAnimation&&b.any3d,M(t,"leaflet-container"+(b.touch?" leaflet-touch":"")+(b.retina?" leaflet-retina":"")+(b.ielt9?" leaflet-oldie":"")+(b.safari?" leaflet-safari":"")+(this._fadeAnimated?" leaflet-fade-anim":"")),pe(t,"position"));"absolute"!==e&&"relative"!==e&&"fixed"!==e&&"sticky"!==e&&(t.style.position="relative"),this._initPanes(),this._initControlPos&&this._initControlPos()},_initPanes:function(){var t=this._panes={};this._paneRenderers={},this._mapPane=this.createPane("mapPane",this._container),Z(this._mapPane,new p(0,0)),this.createPane("tilePane"),this.createPane("overlayPane"),this.createPane("shadowPane"),this.createPane("markerPane"),this.createPane("tooltipPane"),this.createPane("popupPane"),this.options.markerZoomAnimation||(M(t.markerPane,"leaflet-zoom-hide"),M(t.shadowPane,"leaflet-zoom-hide"))},_resetView:function(t,e,i){Z(this._mapPane,new p(0,0));var n=!this._loaded,o=(this._loaded=!0,e=this._limitZoom(e),this.fire("viewprereset"),this._zoom!==e);this._moveStart(o,i)._move(t,e)._moveEnd(o),this.fire("viewreset"),n&&this.fire("load")},_moveStart:function(t,e){return t&&this.fire("zoomstart"),e||this.fire("movestart"),this},_move:function(t,e,i,n){void 0===e&&(e=this._zoom);var o=this._zoom!==e;return this._zoom=e,this._lastCenter=t,this._pixelOrigin=this._getNewPixelOrigin(t),n?i&&i.pinch&&this.fire("zoom",i):((o||i&&i.pinch)&&this.fire("zoom",i),this.fire("move",i)),this},_moveEnd:function(t){return t&&this.fire("zoomend"),this.fire("moveend")},_stop:function(){return r(this._flyToFrame),this._panAnim&&this._panAnim.stop(),this},_rawPanBy:function(t){Z(this._mapPane,this._getMapPanePos().subtract(t))},_getZoomSpan:function(){return this.getMaxZoom()-this.getMinZoom()},_panInsideMaxBounds:function(){this._enforcingBounds||this.panInsideBounds(this.options.maxBounds)},_checkIfLoaded:function(){if(!this._loaded)throw new Error("Set map center and zoom first.")},_initEvents:function(t){this._targets={};var e=t?k:S;e((this._targets[h(this._container)]=this)._container,"click dblclick mousedown mouseup mouseover mouseout mousemove contextmenu keypress keydown keyup",this._handleDOMEvent,this),this.options.trackResize&&e(window,"resize",this._onResize,this),b.any3d&&this.options.transform3DLimit&&(t?this.off:this.on).call(this,"moveend",this._onMoveEnd)},_onResize:function(){r(this._resizeRequest),this._resizeRequest=x(function(){this.invalidateSize({debounceMoveend:!0})},this)},_onScroll:function(){this._container.scrollTop=0,this._container.scrollLeft=0},_onMoveEnd:function(){var t=this._getMapPanePos();Math.max(Math.abs(t.x),Math.abs(t.y))>=this.options.transform3DLimit&&this._resetView(this.getCenter(),this.getZoom())},_findEventTargets:function(t,e){for(var i,n=[],o="mouseout"===e||"mouseover"===e,s=t.target||t.srcElement,r=!1;s;){if((i=this._targets[h(s)])&&("click"===e||"preclick"===e)&&this._draggableMoved(i)){r=!0;break}if(i&&i.listens(e,!0)){if(o&&!We(s,t))break;if(n.push(i),o)break}if(s===this._container)break;s=s.parentNode}return n=n.length||r||o||!this.listens(e,!0)?n:[this]},_isClickDisabled:function(t){for(;t&&t!==this._container;){if(t._leaflet_disable_click)return!0;t=t.parentNode}},_handleDOMEvent:function(t){var e,i=t.target||t.srcElement;!this._loaded||i._leaflet_disable_events||"click"===t.type&&this._isClickDisabled(i)||("mousedown"===(e=t.type)&&Me(i),this._fireDOMEvent(t,e))},_mouseEvents:["click","dblclick","mouseover","mouseout","contextmenu"],_fireDOMEvent:function(t,e,i){"click"===t.type&&((a=l({},t)).type="preclick",this._fireDOMEvent(a,a.type,i));var n=this._findEventTargets(t,e);if(i){for(var o=[],s=0;sthis.options.zoomAnimationThreshold)return!1;var n=this.getZoomScale(e),n=this._getCenterOffset(t)._divideBy(1-1/n);if(!0!==i.animate&&!this.getSize().contains(n))return!1;x(function(){this._moveStart(!0,i.noMoveStart||!1)._animateZoom(t,e,!0)},this)}return!0},_animateZoom:function(t,e,i,n){this._mapPane&&(i&&(this._animatingZoom=!0,this._animateToCenter=t,this._animateToZoom=e,M(this._mapPane,"leaflet-zoom-anim")),this.fire("zoomanim",{center:t,zoom:e,noUpdate:n}),this._tempFireZoomEvent||(this._tempFireZoomEvent=this._zoom!==this._animateToZoom),this._move(this._animateToCenter,this._animateToZoom,void 0,!0),setTimeout(a(this._onZoomTransitionEnd,this),250))},_onZoomTransitionEnd:function(){this._animatingZoom&&(this._mapPane&&z(this._mapPane,"leaflet-zoom-anim"),this._animatingZoom=!1,this._move(this._animateToCenter,this._animateToZoom,void 0,!0),this._tempFireZoomEvent&&this.fire("zoom"),delete this._tempFireZoomEvent,this.fire("move"),this._moveEnd(!0))}});function Ue(t){return new B(t)}var B=et.extend({options:{position:"topright"},initialize:function(t){c(this,t)},getPosition:function(){return this.options.position},setPosition:function(t){var e=this._map;return e&&e.removeControl(this),this.options.position=t,e&&e.addControl(this),this},getContainer:function(){return this._container},addTo:function(t){this.remove(),this._map=t;var e=this._container=this.onAdd(t),i=this.getPosition(),t=t._controlCorners[i];return M(e,"leaflet-control"),-1!==i.indexOf("bottom")?t.insertBefore(e,t.firstChild):t.appendChild(e),this._map.on("unload",this.remove,this),this},remove:function(){return this._map&&(T(this._container),this.onRemove&&this.onRemove(this._map),this._map.off("unload",this.remove,this),this._map=null),this},_refocusOnMap:function(t){this._map&&t&&0",e=document.createElement("div");return e.innerHTML=t,e.firstChild},_addItem:function(t){var e,i=document.createElement("label"),n=this._map.hasLayer(t.layer),n=(t.overlay?((e=document.createElement("input")).type="checkbox",e.className="leaflet-control-layers-selector",e.defaultChecked=n):e=this._createRadioElement("leaflet-base-layers_"+h(this),n),this._layerControlInputs.push(e),e.layerId=h(t.layer),S(e,"click",this._onInputClick,this),document.createElement("span")),o=(n.innerHTML=" "+t.name,document.createElement("span"));return i.appendChild(o),o.appendChild(e),o.appendChild(n),(t.overlay?this._overlaysList:this._baseLayersList).appendChild(i),this._checkDisabledLayers(),i},_onInputClick:function(){if(!this._preventClick){var t,e,i=this._layerControlInputs,n=[],o=[];this._handlingClick=!0;for(var s=i.length-1;0<=s;s--)t=i[s],e=this._getLayer(t.layerId).layer,t.checked?n.push(e):t.checked||o.push(e);for(s=0;se.options.maxZoom},_expandIfNotCollapsed:function(){return this._map&&!this.options.collapsed&&this.expand(),this},_expandSafely:function(){var t=this._section,e=(this._preventClick=!0,S(t,"click",O),this.expand(),this);setTimeout(function(){k(t,"click",O),e._preventClick=!1})}})),qe=B.extend({options:{position:"topleft",zoomInText:'',zoomInTitle:"Zoom in",zoomOutText:'',zoomOutTitle:"Zoom out"},onAdd:function(t){var e="leaflet-control-zoom",i=P("div",e+" leaflet-bar"),n=this.options;return this._zoomInButton=this._createButton(n.zoomInText,n.zoomInTitle,e+"-in",i,this._zoomIn),this._zoomOutButton=this._createButton(n.zoomOutText,n.zoomOutTitle,e+"-out",i,this._zoomOut),this._updateDisabled(),t.on("zoomend zoomlevelschange",this._updateDisabled,this),i},onRemove:function(t){t.off("zoomend zoomlevelschange",this._updateDisabled,this)},disable:function(){return this._disabled=!0,this._updateDisabled(),this},enable:function(){return this._disabled=!1,this._updateDisabled(),this},_zoomIn:function(t){!this._disabled&&this._map._zoomthis._map.getMinZoom()&&this._map.zoomOut(this._map.options.zoomDelta*(t.shiftKey?3:1))},_createButton:function(t,e,i,n,o){i=P("a",i,n);return i.innerHTML=t,i.href="#",i.title=e,i.setAttribute("role","button"),i.setAttribute("aria-label",e),Ie(i),S(i,"click",Re),S(i,"click",o,this),S(i,"click",this._refocusOnMap,this),i},_updateDisabled:function(){var t=this._map,e="leaflet-disabled";z(this._zoomInButton,e),z(this._zoomOutButton,e),this._zoomInButton.setAttribute("aria-disabled","false"),this._zoomOutButton.setAttribute("aria-disabled","false"),!this._disabled&&t._zoom!==t.getMinZoom()||(M(this._zoomOutButton,e),this._zoomOutButton.setAttribute("aria-disabled","true")),!this._disabled&&t._zoom!==t.getMaxZoom()||(M(this._zoomInButton,e),this._zoomInButton.setAttribute("aria-disabled","true"))}}),Ge=(A.mergeOptions({zoomControl:!0}),A.addInitHook(function(){this.options.zoomControl&&(this.zoomControl=new qe,this.addControl(this.zoomControl))}),B.extend({options:{position:"bottomleft",maxWidth:100,metric:!0,imperial:!0},onAdd:function(t){var e="leaflet-control-scale",i=P("div",e),n=this.options;return this._addScales(n,e+"-line",i),t.on(n.updateWhenIdle?"moveend":"move",this._update,this),t.whenReady(this._update,this),i},onRemove:function(t){t.off(this.options.updateWhenIdle?"moveend":"move",this._update,this)},_addScales:function(t,e,i){t.metric&&(this._mScale=P("div",e,i)),t.imperial&&(this._iScale=P("div",e,i))},_update:function(){var t=this._map,e=t.getSize().y/2,t=t.distance(t.containerPointToLatLng([0,e]),t.containerPointToLatLng([this.options.maxWidth,e]));this._updateScales(t)},_updateScales:function(t){this.options.metric&&t&&this._updateMetric(t),this.options.imperial&&t&&this._updateImperial(t)},_updateMetric:function(t){var e=this._getRoundNum(t);this._updateScale(this._mScale,e<1e3?e+" m":e/1e3+" km",e/t)},_updateImperial:function(t){var e,i,t=3.2808399*t;5280'+(b.inlineSvg?' ':"")+"Leaflet"},initialize:function(t){c(this,t),this._attributions={}},onAdd:function(t){for(var e in(t.attributionControl=this)._container=P("div","leaflet-control-attribution"),Ie(this._container),t._layers)t._layers[e].getAttribution&&this.addAttribution(t._layers[e].getAttribution());return this._update(),t.on("layeradd",this._addAttribution,this),this._container},onRemove:function(t){t.off("layeradd",this._addAttribution,this)},_addAttribution:function(t){t.layer.getAttribution&&(this.addAttribution(t.layer.getAttribution()),t.layer.once("remove",function(){this.removeAttribution(t.layer.getAttribution())},this))},setPrefix:function(t){return this.options.prefix=t,this._update(),this},addAttribution:function(t){return t&&(this._attributions[t]||(this._attributions[t]=0),this._attributions[t]++,this._update()),this},removeAttribution:function(t){return t&&this._attributions[t]&&(this._attributions[t]--,this._update()),this},_update:function(){if(this._map){var t,e=[];for(t in this._attributions)this._attributions[t]&&e.push(t);var i=[];this.options.prefix&&i.push(this.options.prefix),e.length&&i.push(e.join(", ")),this._container.innerHTML=i.join(' ')}}}),n=(A.mergeOptions({attributionControl:!0}),A.addInitHook(function(){this.options.attributionControl&&(new Ke).addTo(this)}),B.Layers=Ve,B.Zoom=qe,B.Scale=Ge,B.Attribution=Ke,Ue.layers=function(t,e,i){return new Ve(t,e,i)},Ue.zoom=function(t){return new qe(t)},Ue.scale=function(t){return new Ge(t)},Ue.attribution=function(t){return new Ke(t)},et.extend({initialize:function(t){this._map=t},enable:function(){return this._enabled||(this._enabled=!0,this.addHooks()),this},disable:function(){return this._enabled&&(this._enabled=!1,this.removeHooks()),this},enabled:function(){return!!this._enabled}})),ft=(n.addTo=function(t,e){return t.addHandler(e,this),this},{Events:e}),Ye=b.touch?"touchstart mousedown":"mousedown",Xe=it.extend({options:{clickTolerance:3},initialize:function(t,e,i,n){c(this,n),this._element=t,this._dragStartTarget=e||t,this._preventOutline=i},enable:function(){this._enabled||(S(this._dragStartTarget,Ye,this._onDown,this),this._enabled=!0)},disable:function(){this._enabled&&(Xe._dragging===this&&this.finishDrag(!0),k(this._dragStartTarget,Ye,this._onDown,this),this._enabled=!1,this._moved=!1)},_onDown:function(t){var e,i;this._enabled&&(this._moved=!1,ve(this._element,"leaflet-zoom-anim")||(t.touches&&1!==t.touches.length?Xe._dragging===this&&this.finishDrag():Xe._dragging||t.shiftKey||1!==t.which&&1!==t.button&&!t.touches||((Xe._dragging=this)._preventOutline&&Me(this._element),Le(),re(),this._moving||(this.fire("down"),i=t.touches?t.touches[0]:t,e=Ce(this._element),this._startPoint=new p(i.clientX,i.clientY),this._startPos=Pe(this._element),this._parentScale=Ze(e),i="mousedown"===t.type,S(document,i?"mousemove":"touchmove",this._onMove,this),S(document,i?"mouseup":"touchend touchcancel",this._onUp,this)))))},_onMove:function(t){var e;this._enabled&&(t.touches&&1e&&(i.push(t[n]),o=n);oe.max.x&&(i|=2),t.ye.max.y&&(i|=8),i}function ri(t,e,i,n){var o=e.x,e=e.y,s=i.x-o,r=i.y-e,a=s*s+r*r;return 0this._layersMaxZoom&&this.setZoom(this._layersMaxZoom),void 0===this.options.minZoom&&this._layersMinZoom&&this.getZoom()t.y!=n.y>t.y&&t.x<(n.x-i.x)*(t.y-i.y)/(n.y-i.y)+i.x&&(l=!l);return l||yi.prototype._containsPoint.call(this,t,!0)}});var wi=ci.extend({initialize:function(t,e){c(this,e),this._layers={},t&&this.addData(t)},addData:function(t){var e,i,n,o=d(t)?t:t.features;if(o){for(e=0,i=o.length;es.x&&(r=i.x+a-s.x+o.x),i.x-r-n.x<(a=0)&&(r=i.x-n.x),i.y+e+o.y>s.y&&(a=i.y+e-s.y+o.y),i.y-a-n.y<0&&(a=i.y-n.y),(r||a)&&(this.options.keepInView&&(this._autopanning=!0),t.fire("autopanstart").panBy([r,a]))))},_getAnchor:function(){return m(this._source&&this._source._getPopupAnchor?this._source._getPopupAnchor():[0,0])}})),Ii=(A.mergeOptions({closePopupOnClick:!0}),A.include({openPopup:function(t,e,i){return this._initOverlay(Bi,t,e,i).openOn(this),this},closePopup:function(t){return(t=arguments.length?t:this._popup)&&t.close(),this}}),o.include({bindPopup:function(t,e){return this._popup=this._initOverlay(Bi,this._popup,t,e),this._popupHandlersAdded||(this.on({click:this._openPopup,keypress:this._onKeyPress,remove:this.closePopup,move:this._movePopup}),this._popupHandlersAdded=!0),this},unbindPopup:function(){return this._popup&&(this.off({click:this._openPopup,keypress:this._onKeyPress,remove:this.closePopup,move:this._movePopup}),this._popupHandlersAdded=!1,this._popup=null),this},openPopup:function(t){return this._popup&&(this instanceof ci||(this._popup._source=this),this._popup._prepareOpen(t||this._latlng)&&this._popup.openOn(this._map)),this},closePopup:function(){return this._popup&&this._popup.close(),this},togglePopup:function(){return this._popup&&this._popup.toggle(this),this},isPopupOpen:function(){return!!this._popup&&this._popup.isOpen()},setPopupContent:function(t){return this._popup&&this._popup.setContent(t),this},getPopup:function(){return this._popup},_openPopup:function(t){var e;this._popup&&this._map&&(Re(t),e=t.layer||t.target,this._popup._source!==e||e instanceof fi?(this._popup._source=e,this.openPopup(t.latlng)):this._map.hasLayer(this._popup)?this.closePopup():this.openPopup(t.latlng))},_movePopup:function(t){this._popup.setLatLng(t.latlng)},_onKeyPress:function(t){13===t.originalEvent.keyCode&&this._openPopup(t)}}),Ai.extend({options:{pane:"tooltipPane",offset:[0,0],direction:"auto",permanent:!1,sticky:!1,opacity:.9},onAdd:function(t){Ai.prototype.onAdd.call(this,t),this.setOpacity(this.options.opacity),t.fire("tooltipopen",{tooltip:this}),this._source&&(this.addEventParent(this._source),this._source.fire("tooltipopen",{tooltip:this},!0))},onRemove:function(t){Ai.prototype.onRemove.call(this,t),t.fire("tooltipclose",{tooltip:this}),this._source&&(this.removeEventParent(this._source),this._source.fire("tooltipclose",{tooltip:this},!0))},getEvents:function(){var t=Ai.prototype.getEvents.call(this);return this.options.permanent||(t.preclick=this.close),t},_initLayout:function(){var t="leaflet-tooltip "+(this.options.className||"")+" leaflet-zoom-"+(this._zoomAnimated?"animated":"hide");this._contentNode=this._container=P("div",t),this._container.setAttribute("role","tooltip"),this._container.setAttribute("id","leaflet-tooltip-"+h(this))},_updateLayout:function(){},_adjustPan:function(){},_setPosition:function(t){var e,i=this._map,n=this._container,o=i.latLngToContainerPoint(i.getCenter()),i=i.layerPointToContainerPoint(t),s=this.options.direction,r=n.offsetWidth,a=n.offsetHeight,h=m(this.options.offset),l=this._getAnchor(),i="top"===s?(e=r/2,a):"bottom"===s?(e=r/2,0):(e="center"===s?r/2:"right"===s?0:"left"===s?r:i.xthis.options.maxZoom||nthis.options.maxZoom||void 0!==this.options.minZoom&&oi.max.x)||!e.wrapLat&&(t.yi.max.y))return!1}return!this.options.bounds||(e=this._tileCoordsToBounds(t),g(this.options.bounds).overlaps(e))},_keyToBounds:function(t){return this._tileCoordsToBounds(this._keyToTileCoords(t))},_tileCoordsToNwSe:function(t){var e=this._map,i=this.getTileSize(),n=t.scaleBy(i),i=n.add(i);return[e.unproject(n,t.z),e.unproject(i,t.z)]},_tileCoordsToBounds:function(t){t=this._tileCoordsToNwSe(t),t=new s(t[0],t[1]);return t=this.options.noWrap?t:this._map.wrapLatLngBounds(t)},_tileCoordsToKey:function(t){return t.x+":"+t.y+":"+t.z},_keyToTileCoords:function(t){var t=t.split(":"),e=new p(+t[0],+t[1]);return e.z=+t[2],e},_removeTile:function(t){var e=this._tiles[t];e&&(T(e.el),delete this._tiles[t],this.fire("tileunload",{tile:e.el,coords:this._keyToTileCoords(t)}))},_initTile:function(t){M(t,"leaflet-tile");var e=this.getTileSize();t.style.width=e.x+"px",t.style.height=e.y+"px",t.onselectstart=u,t.onmousemove=u,b.ielt9&&this.options.opacity<1&&C(t,this.options.opacity)},_addTile:function(t,e){var i=this._getTilePos(t),n=this._tileCoordsToKey(t),o=this.createTile(this._wrapCoords(t),a(this._tileReady,this,t));this._initTile(o),this.createTile.length<2&&x(a(this._tileReady,this,t,null,o)),Z(o,i),this._tiles[n]={el:o,coords:t,current:!0},e.appendChild(o),this.fire("tileloadstart",{tile:o,coords:t})},_tileReady:function(t,e,i){e&&this.fire("tileerror",{error:e,tile:i,coords:t});var n=this._tileCoordsToKey(t);(i=this._tiles[n])&&(i.loaded=+new Date,this._map._fadeAnimated?(C(i.el,0),r(this._fadeFrame),this._fadeFrame=x(this._updateOpacity,this)):(i.active=!0,this._pruneTiles()),e||(M(i.el,"leaflet-tile-loaded"),this.fire("tileload",{tile:i.el,coords:t})),this._noTilesToLoad()&&(this._loading=!1,this.fire("load"),b.ielt9||!this._map._fadeAnimated?x(this._pruneTiles,this):setTimeout(a(this._pruneTiles,this),250)))},_getTilePos:function(t){return t.scaleBy(this.getTileSize()).subtract(this._level.origin)},_wrapCoords:function(t){var e=new p(this._wrapX?H(t.x,this._wrapX):t.x,this._wrapY?H(t.y,this._wrapY):t.y);return e.z=t.z,e},_pxBoundsToTileRange:function(t){var e=this.getTileSize();return new f(t.min.unscaleBy(e).floor(),t.max.unscaleBy(e).ceil().subtract([1,1]))},_noTilesToLoad:function(){for(var t in this._tiles)if(!this._tiles[t].loaded)return!1;return!0}});var Di=Ni.extend({options:{minZoom:0,maxZoom:18,subdomains:"abc",errorTileUrl:"",zoomOffset:0,tms:!1,zoomReverse:!1,detectRetina:!1,crossOrigin:!1,referrerPolicy:!1},initialize:function(t,e){this._url=t,(e=c(this,e)).detectRetina&&b.retina&&0')}}catch(t){}return function(t){return document.createElement("<"+t+' xmlns="urn:schemas-microsoft.com:vml" class="lvml">')}}(),zt={_initContainer:function(){this._container=P("div","leaflet-vml-container")},_update:function(){this._map._animatingZoom||(Wi.prototype._update.call(this),this.fire("update"))},_initPath:function(t){var e=t._container=Vi("shape");M(e,"leaflet-vml-shape "+(this.options.className||"")),e.coordsize="1 1",t._path=Vi("path"),e.appendChild(t._path),this._updateStyle(t),this._layers[h(t)]=t},_addPath:function(t){var e=t._container;this._container.appendChild(e),t.options.interactive&&t.addInteractiveTarget(e)},_removePath:function(t){var e=t._container;T(e),t.removeInteractiveTarget(e),delete this._layers[h(t)]},_updateStyle:function(t){var e=t._stroke,i=t._fill,n=t.options,o=t._container;o.stroked=!!n.stroke,o.filled=!!n.fill,n.stroke?(e=e||(t._stroke=Vi("stroke")),o.appendChild(e),e.weight=n.weight+"px",e.color=n.color,e.opacity=n.opacity,n.dashArray?e.dashStyle=d(n.dashArray)?n.dashArray.join(" "):n.dashArray.replace(/( *, *)/g," "):e.dashStyle="",e.endcap=n.lineCap.replace("butt","flat"),e.joinstyle=n.lineJoin):e&&(o.removeChild(e),t._stroke=null),n.fill?(i=i||(t._fill=Vi("fill")),o.appendChild(i),i.color=n.fillColor||n.color,i.opacity=n.fillOpacity):i&&(o.removeChild(i),t._fill=null)},_updateCircle:function(t){var e=t._point.round(),i=Math.round(t._radius),n=Math.round(t._radiusY||i);this._setPath(t,t._empty()?"M0 0":"AL "+e.x+","+e.y+" "+i+","+n+" 0,23592600")},_setPath:function(t,e){t._path.v=e},_bringToFront:function(t){fe(t._container)},_bringToBack:function(t){ge(t._container)}},qi=b.vml?Vi:ct,Gi=Wi.extend({_initContainer:function(){this._container=qi("svg"),this._container.setAttribute("pointer-events","none"),this._rootGroup=qi("g"),this._container.appendChild(this._rootGroup)},_destroyContainer:function(){T(this._container),k(this._container),delete this._container,delete this._rootGroup,delete this._svgSize},_update:function(){var t,e,i;this._map._animatingZoom&&this._bounds||(Wi.prototype._update.call(this),e=(t=this._bounds).getSize(),i=this._container,this._svgSize&&this._svgSize.equals(e)||(this._svgSize=e,i.setAttribute("width",e.x),i.setAttribute("height",e.y)),Z(i,t.min),i.setAttribute("viewBox",[t.min.x,t.min.y,e.x,e.y].join(" ")),this.fire("update"))},_initPath:function(t){var e=t._path=qi("path");t.options.className&&M(e,t.options.className),t.options.interactive&&M(e,"leaflet-interactive"),this._updateStyle(t),this._layers[h(t)]=t},_addPath:function(t){this._rootGroup||this._initContainer(),this._rootGroup.appendChild(t._path),t.addInteractiveTarget(t._path)},_removePath:function(t){T(t._path),t.removeInteractiveTarget(t._path),delete this._layers[h(t)]},_updatePath:function(t){t._project(),t._update()},_updateStyle:function(t){var e=t._path,t=t.options;e&&(t.stroke?(e.setAttribute("stroke",t.color),e.setAttribute("stroke-opacity",t.opacity),e.setAttribute("stroke-width",t.weight),e.setAttribute("stroke-linecap",t.lineCap),e.setAttribute("stroke-linejoin",t.lineJoin),t.dashArray?e.setAttribute("stroke-dasharray",t.dashArray):e.removeAttribute("stroke-dasharray"),t.dashOffset?e.setAttribute("stroke-dashoffset",t.dashOffset):e.removeAttribute("stroke-dashoffset")):e.setAttribute("stroke","none"),t.fill?(e.setAttribute("fill",t.fillColor||t.color),e.setAttribute("fill-opacity",t.fillOpacity),e.setAttribute("fill-rule",t.fillRule||"evenodd")):e.setAttribute("fill","none"))},_updatePoly:function(t,e){this._setPath(t,dt(t._parts,e))},_updateCircle:function(t){var e=t._point,i=Math.max(Math.round(t._radius),1),n="a"+i+","+(Math.max(Math.round(t._radiusY),1)||i)+" 0 1,0 ",e=t._empty()?"M0 0":"M"+(e.x-i)+","+e.y+n+2*i+",0 "+n+2*-i+",0 ";this._setPath(t,e)},_setPath:function(t,e){t._path.setAttribute("d",e)},_bringToFront:function(t){fe(t._path)},_bringToBack:function(t){ge(t._path)}});function Ki(t){return b.svg||b.vml?new Gi(t):null}b.vml&&Gi.include(zt),A.include({getRenderer:function(t){t=(t=t.options.renderer||this._getPaneRenderer(t.options.pane)||this.options.renderer||this._renderer)||(this._renderer=this._createRenderer());return this.hasLayer(t)||this.addLayer(t),t},_getPaneRenderer:function(t){var e;return"overlayPane"!==t&&void 0!==t&&(void 0===(e=this._paneRenderers[t])&&(e=this._createRenderer({pane:t}),this._paneRenderers[t]=e),e)},_createRenderer:function(t){return this.options.preferCanvas&&Ui(t)||Ki(t)}});var Yi=xi.extend({initialize:function(t,e){xi.prototype.initialize.call(this,this._boundsToLatLngs(t),e)},setBounds:function(t){return this.setLatLngs(this._boundsToLatLngs(t))},_boundsToLatLngs:function(t){return[(t=g(t)).getSouthWest(),t.getNorthWest(),t.getNorthEast(),t.getSouthEast()]}});Gi.create=qi,Gi.pointsToPath=dt,wi.geometryToLayer=bi,wi.coordsToLatLng=Li,wi.coordsToLatLngs=Ti,wi.latLngToCoords=Mi,wi.latLngsToCoords=zi,wi.getFeature=Ci,wi.asFeature=Zi,A.mergeOptions({boxZoom:!0});var _t=n.extend({initialize:function(t){this._map=t,this._container=t._container,this._pane=t._panes.overlayPane,this._resetStateTimeout=0,t.on("unload",this._destroy,this)},addHooks:function(){S(this._container,"mousedown",this._onMouseDown,this)},removeHooks:function(){k(this._container,"mousedown",this._onMouseDown,this)},moved:function(){return this._moved},_destroy:function(){T(this._pane),delete this._pane},_resetState:function(){this._resetStateTimeout=0,this._moved=!1},_clearDeferredResetState:function(){0!==this._resetStateTimeout&&(clearTimeout(this._resetStateTimeout),this._resetStateTimeout=0)},_onMouseDown:function(t){if(!t.shiftKey||1!==t.which&&1!==t.button)return!1;this._clearDeferredResetState(),this._resetState(),re(),Le(),this._startPoint=this._map.mouseEventToContainerPoint(t),S(document,{contextmenu:Re,mousemove:this._onMouseMove,mouseup:this._onMouseUp,keydown:this._onKeyDown},this)},_onMouseMove:function(t){this._moved||(this._moved=!0,this._box=P("div","leaflet-zoom-box",this._container),M(this._container,"leaflet-crosshair"),this._map.fire("boxzoomstart")),this._point=this._map.mouseEventToContainerPoint(t);var t=new f(this._point,this._startPoint),e=t.getSize();Z(this._box,t.min),this._box.style.width=e.x+"px",this._box.style.height=e.y+"px"},_finish:function(){this._moved&&(T(this._box),z(this._container,"leaflet-crosshair")),ae(),Te(),k(document,{contextmenu:Re,mousemove:this._onMouseMove,mouseup:this._onMouseUp,keydown:this._onKeyDown},this)},_onMouseUp:function(t){1!==t.which&&1!==t.button||(this._finish(),this._moved&&(this._clearDeferredResetState(),this._resetStateTimeout=setTimeout(a(this._resetState,this),0),t=new s(this._map.containerPointToLatLng(this._startPoint),this._map.containerPointToLatLng(this._point)),this._map.fitBounds(t).fire("boxzoomend",{boxZoomBounds:t})))},_onKeyDown:function(t){27===t.keyCode&&(this._finish(),this._clearDeferredResetState(),this._resetState())}}),Ct=(A.addInitHook("addHandler","boxZoom",_t),A.mergeOptions({doubleClickZoom:!0}),n.extend({addHooks:function(){this._map.on("dblclick",this._onDoubleClick,this)},removeHooks:function(){this._map.off("dblclick",this._onDoubleClick,this)},_onDoubleClick:function(t){var e=this._map,i=e.getZoom(),n=e.options.zoomDelta,i=t.originalEvent.shiftKey?i-n:i+n;"center"===e.options.doubleClickZoom?e.setZoom(i):e.setZoomAround(t.containerPoint,i)}})),Zt=(A.addInitHook("addHandler","doubleClickZoom",Ct),A.mergeOptions({dragging:!0,inertia:!0,inertiaDeceleration:3400,inertiaMaxSpeed:1/0,easeLinearity:.2,worldCopyJump:!1,maxBoundsViscosity:0}),n.extend({addHooks:function(){var t;this._draggable||(t=this._map,this._draggable=new Xe(t._mapPane,t._container),this._draggable.on({dragstart:this._onDragStart,drag:this._onDrag,dragend:this._onDragEnd},this),this._draggable.on("predrag",this._onPreDragLimit,this),t.options.worldCopyJump&&(this._draggable.on("predrag",this._onPreDragWrap,this),t.on("zoomend",this._onZoomEnd,this),t.whenReady(this._onZoomEnd,this))),M(this._map._container,"leaflet-grab leaflet-touch-drag"),this._draggable.enable(),this._positions=[],this._times=[]},removeHooks:function(){z(this._map._container,"leaflet-grab"),z(this._map._container,"leaflet-touch-drag"),this._draggable.disable()},moved:function(){return this._draggable&&this._draggable._moved},moving:function(){return this._draggable&&this._draggable._moving},_onDragStart:function(){var t,e=this._map;e._stop(),this._map.options.maxBounds&&this._map.options.maxBoundsViscosity?(t=g(this._map.options.maxBounds),this._offsetLimit=_(this._map.latLngToContainerPoint(t.getNorthWest()).multiplyBy(-1),this._map.latLngToContainerPoint(t.getSouthEast()).multiplyBy(-1).add(this._map.getSize())),this._viscosity=Math.min(1,Math.max(0,this._map.options.maxBoundsViscosity))):this._offsetLimit=null,e.fire("movestart").fire("dragstart"),e.options.inertia&&(this._positions=[],this._times=[])},_onDrag:function(t){var e,i;this._map.options.inertia&&(e=this._lastTime=+new Date,i=this._lastPos=this._draggable._absPos||this._draggable._newPos,this._positions.push(i),this._times.push(e),this._prunePositions(e)),this._map.fire("move",t).fire("drag",t)},_prunePositions:function(t){for(;1e.max.x&&(t.x=this._viscousLimit(t.x,e.max.x)),t.y>e.max.y&&(t.y=this._viscousLimit(t.y,e.max.y)),this._draggable._newPos=this._draggable._startPos.add(t))},_onPreDragWrap:function(){var t=this._worldWidth,e=Math.round(t/2),i=this._initialWorldOffset,n=this._draggable._newPos.x,o=(n-e+i)%t+e-i,n=(n+e+i)%t-e-i,t=Math.abs(o+i)e.getMaxZoom()&&1): JSONArray { - val markers = JSONArray() - for (campsite in campsites) { - val marker = JSONObject() - marker.put("id", campsite.campsiteId) - marker.put("name", campsite.campsiteName) - marker.put("address", campsite.address) - marker.put("lat", campsite.latitude) - marker.put("lng", campsite.longitude) - markers.put(marker) - } - return markers -} - /** * Displays a map with a marker for each campsite that has a location. * * The map frames every marker, or zooms in on the campsite when there is only one. * Tapping a marker shows the campsite's name and address, with a link that opens it. The map is - * Google's, or OpenStreetMap's once Google has stopped working. + * Google's, or OpenStreetMap's when there is no Google API key. * * @param campsites The campsites to mark on the map. * @param modifier Sets the size and shape of the map. @@ -85,38 +64,8 @@ fun CampsiteMap( } val mapModifier = modifier.testTag("campsite_map") - when (MapFallback.shared.provider) { + when (MapFallback.shared.mapProvider) { MapProvider.GOOGLE -> GoogleCampsiteMap(located, mapModifier, onCampsiteClick) MapProvider.OPEN_STREET_MAP -> OpenStreetCampsiteMap(located, mapModifier, onCampsiteClick) } } - -/** - * The OpenStreetMap version of [GoogleCampsiteMap], drawn by a web page. - * - * @param campsites The campsites to mark, all with a location. - * @param modifier Sets the size and shape of the map. - * @param onCampsiteClick Called when a campsite's link is tapped, or `null` to do nothing. - */ -@Composable -private fun OpenStreetCampsiteMap( - campsites: List, - modifier: Modifier, - onCampsiteClick: ((Campsite) -> Unit)? -) { - val html = remember(campsites) { osmPageHtml(osmCampsiteMapScript(campsites)) } - - MapsJavaScriptView( - html = html, - modifier = modifier, - onEvent = { name, data -> - if (name == "campsiteClick" && onCampsiteClick != null) { - val id = data.optString("id") - val campsite = campsites.find { it.campsiteId == id } - if (campsite != null) { - onCampsiteClick(campsite) - } - } - } - ) -} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/ClickableMap.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/ClickableMap.kt index 3b9da22a..9263837c 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/ClickableMap.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/ClickableMap.kt @@ -52,7 +52,6 @@ fun ClickableMap( ) { val context = LocalContext.current - // Where the marker is, so that it stays there if the map is switched to another provider var markerLocation by remember(initialLocation) { mutableStateOf(initialLocation) } // A move the user has since replaced by tapping the map, which must not be made again var replacedMove by remember { mutableStateOf(null) } @@ -77,56 +76,15 @@ fun ClickableMap( .height(height.dp), shape = RoundedCornerShape(12.dp) ) { - when (MapFallback.shared.provider) { + when (MapFallback.shared.mapProvider) { MapProvider.GOOGLE -> GoogleClickableMap(markerLocation, pendingMove, Modifier.fillMaxSize(), select) MapProvider.OPEN_STREET_MAP -> - OpenStreetClickableMap(initialLocation, markerLocation, pendingMove, select) + OpenStreetClickableMap(markerLocation, pendingMove, Modifier.fillMaxSize(), select) } } } -/** - * The OpenStreetMap version of [GoogleClickableMap], drawn by a web page. - * - * @param initialLocation The page is only rebuilt when this changes, so choosing a location - * does not reload it. - * @param markerLocation Where the marker starts when the page is built. - * @param move Moves the marker and map when it changes, without calling [onSelect]. A move made - * before the page has loaded waits until it is ready. - * @param onSelect Called with the marker's location when the user taps the map or drops the marker. - */ -@Composable -private fun OpenStreetClickableMap( - initialLocation: LatLng, - markerLocation: LatLng, - move: MapMove?, - onSelect: (LatLng) -> Unit -) { - val html = remember(initialLocation) { osmPageHtml(osmClickableMapScript(markerLocation)) } - var isReady by remember(html) { mutableStateOf(false) } - val command = remember(move, isReady) { - if (move != null && isReady) { - MapCommand("showLocation(${move.location.latitude}, ${move.location.longitude});") - } else { - null - } - } - - MapsJavaScriptView( - html = html, - modifier = Modifier.fillMaxSize(), - command = command, - onEvent = { name, data -> - if (name == "mapReady") { - isReady = true - } else if (name == "locationSelected") { - onSelect(LatLng(data.optDouble("lat"), data.optDouble("lng"))) - } - } - ) -} - /** * Performs reverse geocoding to retrieve the address and postal code for the given [LatLng] coordinates. * diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/GoogleMapViews.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/GoogleMapViews.kt index 6398d874..a1a4507e 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/GoogleMapViews.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/GoogleMapViews.kt @@ -45,7 +45,7 @@ import kotlinx.coroutines.flow.filter /* * Shows Google Maps with the native Maps SDK for Android. The OpenStreetMap versions are in - * OpenStreetMapPage.kt. + * OpenStreetMapViews.kt. * * No map ID is set and no advanced markers are used, so loading a map stays on Google's free * "Maps SDK" SKU instead of being billed as Dynamic Maps. @@ -57,10 +57,10 @@ import kotlinx.coroutines.flow.filter /** Zoom used by the location picker, the same as the OpenStreetMap picker. */ private const val PICKER_ZOOM = 13f -/** Colour of the "View campsite" link, the same as on the OpenStreetMap pages. */ +/** Colour of the "View campsite" link, the same as on the OpenStreetMap map. */ private val LINK_COLOR = Color(0xFF2C5C7C) -/** Text size in a campsite's bubble, the same as on the OpenStreetMap pages. */ +/** Text size in a campsite's bubble, the same as on the OpenStreetMap map. */ private val INFO_TEXT_SIZE = 14.sp /** diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/MapsJavaScriptView.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/MapsJavaScriptView.kt deleted file mode 100644 index aa221fcc..00000000 --- a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/MapsJavaScriptView.kt +++ /dev/null @@ -1,175 +0,0 @@ -package com.example.lambda_bbb_events.view.ui.components.map - -import android.annotation.SuppressLint -import android.content.ActivityNotFoundException -import android.content.Context -import android.content.Intent -import android.os.Handler -import android.os.Looper -import android.view.ViewGroup -import android.webkit.JavascriptInterface -import android.webkit.WebResourceRequest -import android.webkit.WebResourceResponse -import android.webkit.WebView -import android.webkit.WebViewClient -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberUpdatedState -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import androidx.compose.ui.viewinterop.AndroidView -import com.example.lambda_bbb_events.model.services.MAP_USER_AGENT -import org.json.JSONException -import org.json.JSONObject - -/* - * Shows the OpenStreetMap pages, which are built in OpenStreetMapPage.kt, in a WebView. Google - * maps are drawn natively instead, in GoogleMapViews.kt. - */ - -/** - * Receives events from the map page's JavaScript. Calls arrive on a background thread and - * are passed on to the main thread. - */ -private class MapBridge( - private val onEvent: (name: String, data: JSONObject) -> Unit -) { - private val mainHandler = Handler(Looper.getMainLooper()) - - /** Set on the main thread once the page is gone, after which its late events are ignored. */ - var isClosed = false - - @JavascriptInterface - fun post(name: String, json: String) { - var data = JSONObject() - try { - data = JSONObject(json) - } catch (e: JSONException) { - // Send the event without data rather than dropping it - } - mainHandler.post { - if (!isClosed) { - onEvent(name, data) - } - } - } -} - -/** The bundled files that map pages can load, with their types. */ -private val BUNDLED_FILES = mapOf( - "leaflet/leaflet.js" to "text/javascript", - "leaflet/leaflet.css" to "text/css" -) - -/** - * Loads Leaflet from the app's files, and opens links tapped on the map page in the phone's - * browser instead of inside the map. - */ -private class MapPageClient(context: Context) : WebViewClient() { - private val assets = context.applicationContext.assets - - override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? { - val url = request.url.toString() - val path = url.removePrefix(OSM_PAGE_BASE_URL) - val type = BUNDLED_FILES[path] - if (path == url || type == null) { - return null // not a bundled file, so it loads from the internet - } - return WebResourceResponse(type, "utf-8", assets.open(path)) - } - - override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { - if (!request.isForMainFrame) { - return false - } - try { - view.context.startActivity(Intent(Intent.ACTION_VIEW, request.url)) - } catch (e: ActivityNotFoundException) { - // No app can open the link, so ignore the tap - } - return true - } -} - -/** - * JavaScript to run on a map page that is already open. Every instance is run once, even if an - * earlier one had the same script. - */ -internal class MapCommand(val script: String) - -/** - * Displays a map page built with [osmPageHtml] and passes its events to [onEvent]. - * - * Drags on the map pan the map instead of scrolling the screen it is in. - * - * @param html The map page. - * @param modifier Sets the size and shape of the map. - * @param command Run on the page when it changes. The page must have finished loading. - * @param onEvent Called on the main thread with each event the page sends. - */ -@SuppressLint("SetJavaScriptEnabled", "ClickableViewAccessibility") -@Composable -internal fun MapsJavaScriptView( - html: String, - modifier: Modifier = Modifier, - command: MapCommand? = null, - onEvent: (name: String, data: JSONObject) -> Unit = { _, _ -> } -) { - // The page is only created once, so it must always call the newest onEvent - val currentOnEvent by rememberUpdatedState(onEvent) - val bridge = remember { MapBridge { name, data -> currentOnEvent(name, data) } } - var shownWebView by remember { mutableStateOf(null) } - - LaunchedEffect(shownWebView, command) { - if (command != null) { - shownWebView?.evaluateJavascript(command.script, null) - } - } - - AndroidView( - modifier = modifier, - factory = { context -> - val webView = WebView(context) - - // A WebView with wrap-content height gives its page a 0px tall viewport, - // which collapses the map; Compose still sizes it from the modifier - webView.layoutParams = ViewGroup.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, - ViewGroup.LayoutParams.MATCH_PARENT - ) - webView.settings.javaScriptEnabled = true - webView.settings.domStorageEnabled = true - webView.addJavascriptInterface(bridge, "Android") - - webView.settings.userAgentString = MAP_USER_AGENT - - // Links such as OpenStreetMap's credit open in the browser instead of replacing the map - webView.webViewClient = MapPageClient(context) - - // Keep scrolling parents from taking over drags meant for the map - webView.setOnTouchListener { view, _ -> - view.parent?.requestDisallowInterceptTouchEvent(true) - false - } - - webView.tag = html - webView.loadDataWithBaseURL(OSM_PAGE_BASE_URL, html, "text/html", "utf-8", null) - shownWebView = webView - webView - }, - update = { webView -> - if (webView.tag != html) { - webView.tag = html - webView.loadDataWithBaseURL(OSM_PAGE_BASE_URL, html, "text/html", "utf-8", null) - } - }, - onRelease = { webView -> - bridge.isClosed = true - shownWebView = null - webView.destroy() - } - ) -} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/OpenStreetMapPage.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/OpenStreetMapPage.kt deleted file mode 100644 index de6049be..00000000 --- a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/OpenStreetMapPage.kt +++ /dev/null @@ -1,171 +0,0 @@ -package com.example.lambda_bbb_events.view.ui.components.map - -import com.example.lambda_bbb_events.model.campsite.Campsite -import com.google.android.gms.maps.model.LatLng - -/* - * Builds the pages that show OpenStreetMap maps, drawn by Leaflet. - * - * Leaflet is bundled with the app, in assets/leaflet. - * - * Reference: - * https://leafletjs.com/reference.html - */ - -/** - * The address the pages and Leaflet are loaded under. Nothing is loaded from it over the - * internet: Android reserves it for files bundled with apps. - */ -internal const val OSM_PAGE_BASE_URL = "https://appassets.androidplatform.net/" - -/** - * Builds a map page that loads Leaflet and then runs [script]. - * - * [script] must define a `function initMap()`. It can send events to the app with - * `send(name, data)`, make a map with `createMap()`, and make marker icons with `pin`. - * - * @param script JavaScript that creates the map. - */ -internal fun osmPageHtml(script: String): String = """ - - - - - - - - -
-
Map unavailable. Check your connection.
- - - - -""".trimIndent() - -/** - * Builds the JavaScript for the OpenStreetMap version of [GoogleCampsiteMap]. Tapping a marker - * shows the campsite's name and address, and tapping "View campsite" sends a `campsiteClick` - * event with the campsite's ID. - * - * @param campsites The campsites to mark, all with a location. - */ -internal fun osmCampsiteMapScript(campsites: List): String = """ - const campsites = ${campsiteMarkers(campsites)}; - - function initMap() { - const map = createMap(); - map.setView([campsites[0].lat, campsites[0].lng], $SINGLE_CAMPSITE_ZOOM); - const bounds = L.latLngBounds([]); - - campsites.forEach(function (campsite) { - const position = [campsite.lat, campsite.lng]; - bounds.extend(position); - - const content = document.createElement('div'); - content.className = 'info'; - const name = document.createElement('b'); - name.textContent = campsite.name; - const address = document.createElement('div'); - address.textContent = campsite.address; - const link = document.createElement('a'); - link.href = '#'; - link.textContent = 'View campsite'; - link.onclick = function (event) { - event.preventDefault(); - send('campsiteClick', { id: campsite.id }); - }; - content.append(name, address, link); - L.marker(position, { icon: pin, title: campsite.name }).addTo(map).bindPopup(content); - }); - - if (campsites.length > 1) { - map.fitBounds(bounds, { padding: [$BOUNDS_PADDING, $BOUNDS_PADDING], maxZoom: $MAX_FRAMING_ZOOM, animate: false }); - } - } -""".trimIndent() - -/** - * Builds the JavaScript for the OpenStreetMap version of [GoogleClickableMap]. Tapping the map or - * dragging the marker moves it and sends a `locationSelected` event with its coordinates. - * - * Sends a `mapReady` event once the app can call `showLocation(lat, lng)`, which moves the marker - * and map there without sending a `locationSelected` event. - * - * @param initialLocation Where the marker and map start. - */ -internal fun osmClickableMapScript(initialLocation: LatLng): String = """ - const start = { lat: ${initialLocation.latitude}, lng: ${initialLocation.longitude} }; - - function initMap() { - const map = createMap(); - map.setView(start, 13); - const marker = L.marker(start, { icon: pin, title: 'Selected Location', draggable: true }).addTo(map); - - function select(latLng) { - // The map repeats sideways, so longitudes can be outside of -180 to 180 - const position = latLng.wrap(); - marker.setLatLng(latLng); - send('locationSelected', { lat: position.lat, lng: position.lng }); - } - - map.on('click', function (event) { select(event.latlng); }); - marker.on('dragend', function () { select(marker.getLatLng()); }); - - window.showLocation = function (lat, lng) { - marker.setLatLng([lat, lng]); - map.setView([lat, lng], 13); - }; - send('mapReady'); - } -""".trimIndent() diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/OpenStreetMapViews.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/OpenStreetMapViews.kt new file mode 100644 index 00000000..06d2592e --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/OpenStreetMapViews.kt @@ -0,0 +1,372 @@ +package com.example.lambda_bbb_events.view.ui.components.map + +import android.content.Context +import android.graphics.Typeface +import android.view.MotionEvent +import android.view.View +import android.widget.LinearLayout +import android.widget.TextView +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalUriHandler +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.ui.viewinterop.AndroidView +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.compose.LocalLifecycleOwner +import com.example.lambda_bbb_events.model.campsite.Campsite +import com.example.lambda_bbb_events.model.services.MAP_USER_AGENT +import okhttp3.OkHttpClient +import org.maplibre.android.MapLibre +import org.maplibre.android.annotations.Marker +import org.maplibre.android.annotations.MarkerOptions +import org.maplibre.android.camera.CameraPosition +import org.maplibre.android.camera.CameraUpdateFactory +import org.maplibre.android.geometry.LatLng +import org.maplibre.android.geometry.LatLngBounds +import org.maplibre.android.maps.MapLibreMap +import org.maplibre.android.maps.MapLibreMapOptions +import org.maplibre.android.maps.MapView +import org.maplibre.android.maps.Style +import org.maplibre.android.module.http.HttpRequestUtil +import org.maplibre.android.style.layers.RasterLayer +import org.maplibre.android.style.sources.RasterSource +import org.maplibre.android.style.sources.TileSet +import com.google.android.gms.maps.model.LatLng as GoogleLatLng + +/* + * Shows OpenStreetMap maps natively with MapLibre, for when there is no Google API key. The + * Google versions are in GoogleMapViews.kt. + * + * The tile policy is at https://operations.osmfoundation.org/policies/tiles/. + * + * Reference: + * https://maplibre.org/maplibre-native/android/api/ + */ + +/** OpenStreetMap's tile server. */ +private const val OSM_TILE_URL = "https://tile.openstreetmap.org/{z}/{x}/{y}.png" + +/** The closest zoom OpenStreetMap draws tiles for. */ +private const val OSM_MAX_ZOOM = 19f + +/** Size in pixels of OpenStreetMap's tiles. */ +private const val OSM_TILE_SIZE = 256 + +/** Zoom used by the location picker, the same as the Google picker. */ +private const val OSM_PICKER_ZOOM = 13.0 + +/** The page OpenStreetMap's credit links to. */ +private const val OSM_COPYRIGHT_URL = "https://www.openstreetmap.org/copyright" + +/** Colour of the "View campsite" link, the same as on the Google map. */ +private const val OSM_LINK_COLOR = 0xFF2C5C7C.toInt() + +/** Text size in sp in a campsite's bubble, the same as on the Google map. */ +private const val OSM_INFO_TEXT_SIZE = 14f + +/** + * Sends tile requests with the app's own User-Agent. OpenStreetMap blocks MapLibre's default + * one, because its tile policy requires each app to identify itself. + */ +private val osmHttpClient: OkHttpClient by lazy { + OkHttpClient.Builder() + .addInterceptor { chain -> + chain.proceed(chain.request().newBuilder().header("User-Agent", MAP_USER_AGENT).build()) + } + .build() +} + +/** Starts MapLibre, which must happen before a map view is made. */ +private fun startMapLibre(context: Context) { + MapLibre.getInstance(context) + HttpRequestUtil.setOkHttpClient(osmHttpClient) +} + +/** Converts to the LatLng MapLibre uses. */ +private fun GoogleLatLng.toMapLibre(): LatLng = LatLng(latitude, longitude) + +/** Converts to the LatLng the rest of the app uses. */ +private fun LatLng.toGoogle(): GoogleLatLng = GoogleLatLng(latitude, longitude) + +/** Where the campsite is on the map. */ +private fun Campsite.osmPosition(): LatLng = LatLng(latitude, longitude) + +/** A map style with only OpenStreetMap's tiles in it. */ +private fun osmStyle(): Style.Builder { + val tiles = TileSet("2.2.0", OSM_TILE_URL) + tiles.maxZoom = OSM_MAX_ZOOM + return Style.Builder() + .withSource(RasterSource("osm", tiles, OSM_TILE_SIZE)) + .withLayer(RasterLayer("osm", "osm")) +} + +/** + * The map's settings. MapLibre's own logo and credit button are hidden because [OsmMap] shows + * OpenStreetMap's credit, and tilting and rotating only make a flat map harder to read. + */ +private fun osmMapOptions(context: Context, start: CameraPosition): MapLibreMapOptions = + MapLibreMapOptions.createFromAttributes(context) + .camera(start) + .textureMode(true) + .logoEnabled(false) + .attributionEnabled(false) + .compassEnabled(false) + .rotateGesturesEnabled(false) + .tiltGesturesEnabled(false) + +/** + * A [MapView] that keeps scrolling screens it is in from taking over drags meant for the map. + */ +private class ScrollGuardOsmMapView(context: Context, options: MapLibreMapOptions) : MapView(context, options) { + override fun dispatchTouchEvent(event: MotionEvent): Boolean { + parent?.requestDisallowInterceptTouchEvent(true) + return super.dispatchTouchEvent(event) + } +} + +/** Passes a screen's lifecycle [event] on to [mapView], which needs it to draw and to clean up. */ +private fun forwardLifecycle(mapView: MapView, event: Lifecycle.Event) { + when (event) { + Lifecycle.Event.ON_CREATE -> mapView.onCreate(null) + Lifecycle.Event.ON_START -> mapView.onStart() + Lifecycle.Event.ON_RESUME -> mapView.onResume() + Lifecycle.Event.ON_PAUSE -> mapView.onPause() + Lifecycle.Event.ON_STOP -> mapView.onStop() + else -> Unit + } +} + +/** Takes [mapView] down from [state] and frees it, once the map has left the screen. */ +private fun closeMapView(mapView: MapView, state: Lifecycle.State) { + if (state.isAtLeast(Lifecycle.State.RESUMED)) { + mapView.onPause() + } + if (state.isAtLeast(Lifecycle.State.STARTED)) { + mapView.onStop() + } + mapView.onDestroy() +} + +/** + * Makes a MapLibre map view that follows the screen's lifecycle and is freed when it leaves + * the screen. + * + * @param start Where the map looks first. + */ +@Composable +private fun rememberOsmMapView(start: CameraPosition): MapView { + val context = LocalContext.current + val mapView = remember { + startMapLibre(context) + ScrollGuardOsmMapView(context, osmMapOptions(context, start)) + } + val lifecycle = LocalLifecycleOwner.current.lifecycle + DisposableEffect(lifecycle, mapView) { + val observer = LifecycleEventObserver { _, event -> forwardLifecycle(mapView, event) } + lifecycle.addObserver(observer) + onDispose { + lifecycle.removeObserver(observer) + closeMapView(mapView, lifecycle.currentState) + } + } + return mapView +} + +/** + * OpenStreetMap's credit, which its licence requires to stay visible. Tapping it opens + * OpenStreetMap's copyright page. + */ +@Composable +private fun OsmCredit(modifier: Modifier) { + val uriHandler = LocalUriHandler.current + Text( + text = "© OpenStreetMap contributors", + fontSize = 11.sp, + color = Color.DarkGray, + modifier = modifier + .background(Color.White.copy(alpha = 0.8f)) + .clickable { uriHandler.openUri(OSM_COPYRIGHT_URL) } + .padding(horizontal = 4.dp, vertical = 1.dp) + ) +} + +/** + * An OpenStreetMap map with the app's settings. [onReady] is called once, when the tiles have + * been added and markers can be placed. + * + * @param start Where the map looks first. + * @param modifier Sets the size and shape of the map. + * @param onReady Sets up the map's markers and listeners. + */ +@Composable +private fun OsmMap(start: CameraPosition, modifier: Modifier, onReady: (MapLibreMap) -> Unit) { + val mapView = rememberOsmMapView(start) + val currentOnReady by rememberUpdatedState(onReady) + LaunchedEffect(mapView) { + mapView.getMapAsync { map -> map.setStyle(osmStyle()) { currentOnReady(map) } } + } + Box(modifier = modifier) { + AndroidView(factory = { mapView }, modifier = Modifier.matchParentSize()) + OsmCredit(Modifier.align(Alignment.BottomEnd)) + } +} + +/** Makes a line of text for a campsite's bubble. */ +private fun infoLine(context: Context, text: String, color: Int, style: Int): TextView { + val line = TextView(context) + line.text = text + line.textSize = OSM_INFO_TEXT_SIZE + line.setTextColor(color) + line.setTypeface(null, style) + return line +} + +/** + * The bubble shown above a tapped campsite marker, laid out like the Google map's. + * + * @param showLink Whether to show "View campsite", for maps where tapping the bubble opens it. + */ +private fun campsiteInfoView(context: Context, campsite: Campsite, showLink: Boolean): View { + val padding = (8 * context.resources.displayMetrics.density).toInt() + val bubble = LinearLayout(context) + bubble.orientation = LinearLayout.VERTICAL + bubble.setBackgroundColor(android.graphics.Color.WHITE) + bubble.setPadding(padding, padding, padding, padding) + bubble.addView(infoLine(context, campsite.campsiteName, android.graphics.Color.BLACK, Typeface.BOLD)) + bubble.addView(infoLine(context, campsite.address, android.graphics.Color.DKGRAY, Typeface.NORMAL)) + if (showLink) { + val link = infoLine(context, "View campsite", OSM_LINK_COLOR, Typeface.BOLD) + link.setPadding(0, padding, 0, 0) + bubble.addView(link) + } + return bubble +} + +/** + * Moves [map] to show every campsite, or to zoom in on the campsite when there is only one. + * + * @param paddingPx Space kept between the outermost campsites and the edge of the map. + */ +private fun frameOsmCampsites(map: MapLibreMap, campsites: List, paddingPx: Int) { + if (campsites.size == 1) { + map.moveCamera(CameraUpdateFactory.newLatLngZoom(campsites[0].osmPosition(), SINGLE_CAMPSITE_ZOOM.toDouble())) + return + } + val bounds = LatLngBounds.Builder() + campsites.forEach { bounds.include(it.osmPosition()) } + map.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds.build(), paddingPx)) + if (map.cameraPosition.zoom > MAX_FRAMING_ZOOM) { + map.moveCamera(CameraUpdateFactory.zoomTo(MAX_FRAMING_ZOOM.toDouble())) + } +} + +/** + * Adds a marker for each campsite to [map], with a bubble that calls [onCampsiteClick] when + * tapped. + */ +private fun addCampsiteMarkers( + context: Context, + map: MapLibreMap, + campsites: List, + onCampsiteClick: ((Campsite) -> Unit)? +) { + val byMarker = mutableMapOf() + for (campsite in campsites) { + val marker = map.addMarker(MarkerOptions().position(campsite.osmPosition()).title(campsite.campsiteName)) + byMarker[marker] = campsite + } + map.setInfoWindowAdapter { marker -> + byMarker[marker]?.let { campsiteInfoView(context, it, showLink = onCampsiteClick != null) } + } + map.setOnInfoWindowClickListener { marker -> + byMarker[marker]?.let { onCampsiteClick?.invoke(it) } + true + } +} + +/** + * The OpenStreetMap version of [GoogleCampsiteMap]: a marker for each campsite, framed to show + * them all. + * + * @param campsites The campsites to mark, all with a location. + * @param modifier Sets the size and shape of the map. + * @param onCampsiteClick Called when a campsite's bubble is tapped, or `null` to do nothing. + */ +@Composable +internal fun OpenStreetCampsiteMap( + campsites: List, + modifier: Modifier, + onCampsiteClick: ((Campsite) -> Unit)? +) { + val context = LocalContext.current + val paddingPx = with(LocalDensity.current) { BOUNDS_PADDING.dp.roundToPx() } + val currentOnCampsiteClick by rememberUpdatedState(onCampsiteClick) + val start = CameraPosition.Builder() + .target(campsites[0].osmPosition()) + .zoom(SINGLE_CAMPSITE_ZOOM.toDouble()) + .build() + + key(campsites) { + OsmMap(start, modifier) { map -> + addCampsiteMarkers(context, map, campsites) { currentOnCampsiteClick?.invoke(it) } + frameOsmCampsites(map, campsites, paddingPx) + } + } +} + +/** + * The OpenStreetMap version of [GoogleClickableMap]: one marker, which tapping the map moves. + * + * @param start Where the marker and map start. + * @param move Moves the marker and map when it changes, without calling [onSelect]. + * @param modifier Sets the size and shape of the map. + * @param onSelect Called with the marker's location when the user taps the map. + */ +@Composable +internal fun OpenStreetClickableMap( + start: GoogleLatLng, + move: MapMove?, + modifier: Modifier, + onSelect: (GoogleLatLng) -> Unit +) { + val currentOnSelect by rememberUpdatedState(onSelect) + var ready by remember { mutableStateOf?>(null) } + val camera = CameraPosition.Builder().target(start.toMapLibre()).zoom(OSM_PICKER_ZOOM).build() + + LaunchedEffect(ready, move) { + val (map, marker) = ready ?: return@LaunchedEffect + if (move != null) { + marker.position = move.location.toMapLibre() + map.moveCamera(CameraUpdateFactory.newLatLngZoom(move.location.toMapLibre(), OSM_PICKER_ZOOM)) + } + } + + OsmMap(camera, modifier) { map -> + val marker = map.addMarker(MarkerOptions().position(start.toMapLibre())) + map.addOnMapClickListener { location -> + marker.position = location + currentOnSelect(location.toGoogle()) + true + } + ready = map to marker + } +} diff --git a/code/app/src/test/java/com/example/lambda_bbb_events/model/services/FallbackPlaceSearchUnitTest.kt b/code/app/src/test/java/com/example/lambda_bbb_events/model/services/FallbackPlaceSearchUnitTest.kt index a46c192d..761fb552 100644 --- a/code/app/src/test/java/com/example/lambda_bbb_events/model/services/FallbackPlaceSearchUnitTest.kt +++ b/code/app/src/test/java/com/example/lambda_bbb_events/model/services/FallbackPlaceSearchUnitTest.kt @@ -116,6 +116,18 @@ class FallbackPlaceSearchUnitTest { assertEquals(details, search.getPlace(photonPlace, "token")) } + @Test + fun searchFailureKeepsTheGoogleMap() { + fallback.reportGoogleFailure() + + assertEquals(MapProvider.GOOGLE, fallback.mapProvider) + } + + @Test + fun missingKeyUsesTheOpenStreetMap() { + assertEquals(MapProvider.OPEN_STREET_MAP, MapFallback(apiKey = "").mapProvider) + } + @Test fun missingKeyNeverTriesGoogle() { assertEquals(MapProvider.OPEN_STREET_MAP, MapFallback(apiKey = "").provider) diff --git a/code/gradle/libs.versions.toml b/code/gradle/libs.versions.toml index 599c7667..1702b6c2 100644 --- a/code/gradle/libs.versions.toml +++ b/code/gradle/libs.versions.toml @@ -14,6 +14,7 @@ fragment = "1.5.4" kotlin = "2.4.21" libphonenumber = "9.0.43" composeBom = "2026.11.01" +mapLibre = "13.7.1" mapsCompose = "9.0.1" mockk = "1.14.12" mockkAndroid = "1.14.12" @@ -50,6 +51,7 @@ androidx-material-icons-extended = { group = "androidx.compose.material", name = androidx-compose-foundation = { group = "androidx.compose.foundation", name = "foundation" } kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinxCoroutinesTest" } libphonenumber = { module = "com.googlecode.libphonenumber:libphonenumber", version.ref = "libphonenumber" } +maplibre-android = { module = "org.maplibre.gl:android-sdk", version.ref = "mapLibre" } maps-compose = { module = "com.google.maps.android:maps-compose", version.ref = "mapsCompose" } mockk = { module = "io.mockk:mockk", version.ref = "mockk" } mockk-android = { module = "io.mockk:mockk-android", version.ref = "mockkAndroid" } From 1ddc6d4b231210dd6721859725f897e23b0f5d3a Mon Sep 17 00:00:00 2001 From: somethingGit <113336038+somethingGit@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:47:51 -0600 Subject: [PATCH 2/7] Updates OSM --- .../admin/AdminProfileDetailsScreenUITest.kt | 1 - .../ui/campsites/OpenStreetMapUITest.kt | 23 ++ .../ui/components/admin/MakeAdminDialog.kt | 20 +- .../view/ui/components/logs/AdminLogCard.kt | 4 +- .../ui/components/map/OpenStreetMapViews.kt | 337 ++++++++---------- .../notification/NotificationsScreen.kt | 2 +- .../store/CampsiteStoreUnitTest.kt | 2 +- 7 files changed, 180 insertions(+), 209 deletions(-) diff --git a/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/admin/AdminProfileDetailsScreenUITest.kt b/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/admin/AdminProfileDetailsScreenUITest.kt index 5674c4ce..de49e0ed 100644 --- a/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/admin/AdminProfileDetailsScreenUITest.kt +++ b/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/admin/AdminProfileDetailsScreenUITest.kt @@ -250,7 +250,6 @@ class AdminProfileDetailsScreenUITest { composeTestRule.onNodeWithTag("adminPasswordInput") .assert(SemanticsMatcher.keyIsDefined(SemanticsProperties.Password)) - .assertTextContains("••••••••") } @Test diff --git a/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/campsites/OpenStreetMapUITest.kt b/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/campsites/OpenStreetMapUITest.kt index 2bb6bd1e..657f0ff7 100644 --- a/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/campsites/OpenStreetMapUITest.kt +++ b/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/campsites/OpenStreetMapUITest.kt @@ -5,7 +5,9 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.click import androidx.compose.ui.test.junit4.v2.createComposeRule +import androidx.compose.ui.test.onAllNodesWithTag import androidx.compose.ui.test.onNodeWithTag +import androidx.compose.ui.test.performClick import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.performTouchInput @@ -61,6 +63,27 @@ class OpenStreetMapUITest { composeTestRule.onNodeWithText("© OpenStreetMap contributors").assertIsDisplayed() } + @Test + fun tappingACampsiteShowsItsNameAndAddress() { + var opened: Campsite? = null + composeTestRule.setContent { + OpenStreetCampsiteMap(campsites.take(1), Modifier.size(300.dp).testTag("osm_campsites")) { opened = it } + } + + repeat(20) { + composeTestRule.onNodeWithTag("osm_campsites").performTouchInput { click(center) } + composeTestRule.waitForIdle() + if (composeTestRule.onAllNodesWithTag("osm_campsite_card").fetchSemanticsNodes().isNotEmpty()) { + return@repeat + } + Thread.sleep(500) + } + composeTestRule.onNodeWithText("1 Lake Rd").assertIsDisplayed() + composeTestRule.onNodeWithText("View campsite").performClick() + + assertEquals("a", opened?.campsiteId) + } + @Test fun tappingThePickerSelectsWhereItWasTapped() { var selected: LatLng? = null diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/admin/MakeAdminDialog.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/admin/MakeAdminDialog.kt index b0bcc1f4..b37ccf48 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/admin/MakeAdminDialog.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/admin/MakeAdminDialog.kt @@ -6,18 +6,15 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.AlertDialog import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField +import androidx.compose.foundation.text.input.TextObfuscationMode +import androidx.compose.foundation.text.input.rememberTextFieldState +import androidx.compose.material3.OutlinedSecureTextField import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.input.KeyboardType -import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.unit.dp /** @@ -38,7 +35,8 @@ fun MakeAdminDialog( onConfirm: (password: String) -> Unit, onDismiss: () -> Unit ) { - var password by remember { mutableStateOf("") } + val passwordState = rememberTextFieldState() + val password = passwordState.text.toString() AlertDialog( containerColor = MaterialTheme.colorScheme.surface, @@ -54,14 +52,12 @@ fun MakeAdminDialog( "$name will be able to manage all campsites and profiles, including " + "removing them. Enter the admin password to continue." ) - OutlinedTextField( - value = password, - onValueChange = { password = it }, + OutlinedSecureTextField( + state = passwordState, + textObfuscationMode = TextObfuscationMode.Hidden, label = { Text("Admin password") }, - singleLine = true, enabled = !isSaving, isError = isPasswordWrong, - visualTransformation = PasswordVisualTransformation(), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), modifier = Modifier .fillMaxWidth() diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/logs/AdminLogCard.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/logs/AdminLogCard.kt index 62056281..d6290356 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/logs/AdminLogCard.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/logs/AdminLogCard.kt @@ -7,7 +7,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Email import androidx.compose.material.icons.filled.Notifications -import androidx.compose.material.icons.filled.KeyboardArrowRight +import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment @@ -117,7 +117,7 @@ fun AdminLogCard( } Icon( - imageVector = Icons.Default.KeyboardArrowRight, + imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = "View log details", tint = MaterialTheme.colorScheme.onSurfaceVariant ) diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/OpenStreetMapViews.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/OpenStreetMapViews.kt index 06d2592e..b455e411 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/OpenStreetMapViews.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/OpenStreetMapViews.kt @@ -1,15 +1,17 @@ package com.example.lambda_bbb_events.view.ui.components.map import android.content.Context -import android.graphics.Typeface +import android.graphics.RectF import android.view.MotionEvent -import android.view.View -import android.widget.LinearLayout -import android.widget.TextView import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.material3.Card +import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect @@ -26,18 +28,15 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalUriHandler +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.viewinterop.AndroidView -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.LifecycleEventObserver -import androidx.lifecycle.compose.LocalLifecycleOwner import com.example.lambda_bbb_events.model.campsite.Campsite import com.example.lambda_bbb_events.model.services.MAP_USER_AGENT import okhttp3.OkHttpClient import org.maplibre.android.MapLibre -import org.maplibre.android.annotations.Marker -import org.maplibre.android.annotations.MarkerOptions import org.maplibre.android.camera.CameraPosition import org.maplibre.android.camera.CameraUpdateFactory import org.maplibre.android.geometry.LatLng @@ -47,41 +46,38 @@ import org.maplibre.android.maps.MapLibreMapOptions import org.maplibre.android.maps.MapView import org.maplibre.android.maps.Style import org.maplibre.android.module.http.HttpRequestUtil +import org.maplibre.android.style.layers.CircleLayer +import org.maplibre.android.style.layers.PropertyFactory.circleColor +import org.maplibre.android.style.layers.PropertyFactory.circleRadius +import org.maplibre.android.style.layers.PropertyFactory.circleStrokeColor +import org.maplibre.android.style.layers.PropertyFactory.circleStrokeWidth import org.maplibre.android.style.layers.RasterLayer +import org.maplibre.android.style.sources.GeoJsonSource import org.maplibre.android.style.sources.RasterSource import org.maplibre.android.style.sources.TileSet +import org.maplibre.geojson.Feature +import org.maplibre.geojson.FeatureCollection +import org.maplibre.geojson.Point import com.google.android.gms.maps.model.LatLng as GoogleLatLng /* * Shows OpenStreetMap maps natively with MapLibre, for when there is no Google API key. The * Google versions are in GoogleMapViews.kt. * - * The tile policy is at https://operations.osmfoundation.org/policies/tiles/. + * Markers are drawn as a circle layer over the tiles, which is MapLibre's current way of + * marking points. * - * Reference: - * https://maplibre.org/maplibre-native/android/api/ + * The tile policy is at https://operations.osmfoundation.org/policies/tiles/. */ -/** OpenStreetMap's tile server. */ -private const val OSM_TILE_URL = "https://tile.openstreetmap.org/{z}/{x}/{y}.png" - -/** The closest zoom OpenStreetMap draws tiles for. */ -private const val OSM_MAX_ZOOM = 19f - -/** Size in pixels of OpenStreetMap's tiles. */ -private const val OSM_TILE_SIZE = 256 - /** Zoom used by the location picker, the same as the Google picker. */ private const val OSM_PICKER_ZOOM = 13.0 -/** The page OpenStreetMap's credit links to. */ -private const val OSM_COPYRIGHT_URL = "https://www.openstreetmap.org/copyright" +/** The ID of the source and layer that hold the markers. */ +private const val MARKERS = "markers" -/** Colour of the "View campsite" link, the same as on the Google map. */ -private const val OSM_LINK_COLOR = 0xFF2C5C7C.toInt() - -/** Text size in sp in a campsite's bubble, the same as on the Google map. */ -private const val OSM_INFO_TEXT_SIZE = 14f +/** How far in pixels from a marker a tap still selects it. */ +private const val TAP_SLOP_PX = 32f /** * Sends tile requests with the app's own User-Agent. OpenStreetMap blocks MapLibre's default @@ -95,35 +91,36 @@ private val osmHttpClient: OkHttpClient by lazy { .build() } -/** Starts MapLibre, which must happen before a map view is made. */ -private fun startMapLibre(context: Context) { - MapLibre.getInstance(context) - HttpRequestUtil.setOkHttpClient(osmHttpClient) -} - -/** Converts to the LatLng MapLibre uses. */ -private fun GoogleLatLng.toMapLibre(): LatLng = LatLng(latitude, longitude) - -/** Converts to the LatLng the rest of the app uses. */ -private fun LatLng.toGoogle(): GoogleLatLng = GoogleLatLng(latitude, longitude) +/** A point on the map, as the marker source needs it. */ +private fun markerPoint(latitude: Double, longitude: Double): Point = Point.fromLngLat(longitude, latitude) /** Where the campsite is on the map. */ private fun Campsite.osmPosition(): LatLng = LatLng(latitude, longitude) -/** A map style with only OpenStreetMap's tiles in it. */ +/** OpenStreetMap's tiles, with an empty marker layer drawn over them. */ private fun osmStyle(): Style.Builder { - val tiles = TileSet("2.2.0", OSM_TILE_URL) - tiles.maxZoom = OSM_MAX_ZOOM + val tiles = TileSet("2.2.0", "https://tile.openstreetmap.org/{z}/{x}/{y}.png") + tiles.maxZoom = 19f + val markers = CircleLayer(MARKERS, MARKERS).withProperties( + circleRadius(9f), + circleColor("#2C5C7C"), + circleStrokeColor("#FFFFFF"), + circleStrokeWidth(2f) + ) return Style.Builder() - .withSource(RasterSource("osm", tiles, OSM_TILE_SIZE)) + .withSource(RasterSource("osm", tiles, 256)) .withLayer(RasterLayer("osm", "osm")) + .withSource(GeoJsonSource(MARKERS)) + .withLayer(markers) } /** - * The map's settings. MapLibre's own logo and credit button are hidden because [OsmMap] shows - * OpenStreetMap's credit, and tilting and rotating only make a flat map harder to read. + * A [MapView] that keeps scrolling screens it is in from taking over drags meant for the map. + * MapLibre's logo and credit button are hidden because [OsmMap] shows OpenStreetMap's credit, + * and tilting and rotating only make a flat map harder to read. */ -private fun osmMapOptions(context: Context, start: CameraPosition): MapLibreMapOptions = +private class OsmMapView(context: Context, start: CameraPosition) : MapView( + context, MapLibreMapOptions.createFromAttributes(context) .camera(start) .textureMode(true) @@ -132,133 +129,64 @@ private fun osmMapOptions(context: Context, start: CameraPosition): MapLibreMapO .compassEnabled(false) .rotateGesturesEnabled(false) .tiltGesturesEnabled(false) - -/** - * A [MapView] that keeps scrolling screens it is in from taking over drags meant for the map. - */ -private class ScrollGuardOsmMapView(context: Context, options: MapLibreMapOptions) : MapView(context, options) { +) { override fun dispatchTouchEvent(event: MotionEvent): Boolean { parent?.requestDisallowInterceptTouchEvent(true) return super.dispatchTouchEvent(event) } } -/** Passes a screen's lifecycle [event] on to [mapView], which needs it to draw and to clean up. */ -private fun forwardLifecycle(mapView: MapView, event: Lifecycle.Event) { - when (event) { - Lifecycle.Event.ON_CREATE -> mapView.onCreate(null) - Lifecycle.Event.ON_START -> mapView.onStart() - Lifecycle.Event.ON_RESUME -> mapView.onResume() - Lifecycle.Event.ON_PAUSE -> mapView.onPause() - Lifecycle.Event.ON_STOP -> mapView.onStop() - else -> Unit - } -} - -/** Takes [mapView] down from [state] and frees it, once the map has left the screen. */ -private fun closeMapView(mapView: MapView, state: Lifecycle.State) { - if (state.isAtLeast(Lifecycle.State.RESUMED)) { - mapView.onPause() - } - if (state.isAtLeast(Lifecycle.State.STARTED)) { - mapView.onStop() - } - mapView.onDestroy() -} - /** - * Makes a MapLibre map view that follows the screen's lifecycle and is freed when it leaves - * the screen. + * An OpenStreetMap map with the app's settings and OpenStreetMap's credit, which its licence + * requires to stay visible. [onReady] is called once the style has loaded, with the source that + * holds the markers. * * @param start Where the map looks first. + * @param modifier Sets the size and shape of the map. + * @param overlay Drawn on top of the map. + * @param onReady Sets up the map's markers and listeners. */ @Composable -private fun rememberOsmMapView(start: CameraPosition): MapView { +private fun OsmMap( + start: CameraPosition, + modifier: Modifier, + overlay: @Composable BoxScope.() -> Unit = {}, + onReady: (MapLibreMap, GeoJsonSource) -> Unit +) { val context = LocalContext.current + val uriHandler = LocalUriHandler.current + val currentOnReady by rememberUpdatedState(onReady) val mapView = remember { - startMapLibre(context) - ScrollGuardOsmMapView(context, osmMapOptions(context, start)) + MapLibre.getInstance(context) + HttpRequestUtil.setOkHttpClient(osmHttpClient) + OsmMapView(context, start) } - val lifecycle = LocalLifecycleOwner.current.lifecycle - DisposableEffect(lifecycle, mapView) { - val observer = LifecycleEventObserver { _, event -> forwardLifecycle(mapView, event) } - lifecycle.addObserver(observer) + DisposableEffect(mapView) { + mapView.onStart() + mapView.getMapAsync { map -> + map.setStyle(osmStyle()) { style -> + style.getSourceAs(MARKERS)?.let { currentOnReady(map, it) } + } + } onDispose { - lifecycle.removeObserver(observer) - closeMapView(mapView, lifecycle.currentState) + mapView.onStop() + mapView.onDestroy() } } - return mapView -} - -/** - * OpenStreetMap's credit, which its licence requires to stay visible. Tapping it opens - * OpenStreetMap's copyright page. - */ -@Composable -private fun OsmCredit(modifier: Modifier) { - val uriHandler = LocalUriHandler.current - Text( - text = "© OpenStreetMap contributors", - fontSize = 11.sp, - color = Color.DarkGray, - modifier = modifier - .background(Color.White.copy(alpha = 0.8f)) - .clickable { uriHandler.openUri(OSM_COPYRIGHT_URL) } - .padding(horizontal = 4.dp, vertical = 1.dp) - ) -} - -/** - * An OpenStreetMap map with the app's settings. [onReady] is called once, when the tiles have - * been added and markers can be placed. - * - * @param start Where the map looks first. - * @param modifier Sets the size and shape of the map. - * @param onReady Sets up the map's markers and listeners. - */ -@Composable -private fun OsmMap(start: CameraPosition, modifier: Modifier, onReady: (MapLibreMap) -> Unit) { - val mapView = rememberOsmMapView(start) - val currentOnReady by rememberUpdatedState(onReady) - LaunchedEffect(mapView) { - mapView.getMapAsync { map -> map.setStyle(osmStyle()) { currentOnReady(map) } } - } Box(modifier = modifier) { AndroidView(factory = { mapView }, modifier = Modifier.matchParentSize()) - OsmCredit(Modifier.align(Alignment.BottomEnd)) - } -} - -/** Makes a line of text for a campsite's bubble. */ -private fun infoLine(context: Context, text: String, color: Int, style: Int): TextView { - val line = TextView(context) - line.text = text - line.textSize = OSM_INFO_TEXT_SIZE - line.setTextColor(color) - line.setTypeface(null, style) - return line -} - -/** - * The bubble shown above a tapped campsite marker, laid out like the Google map's. - * - * @param showLink Whether to show "View campsite", for maps where tapping the bubble opens it. - */ -private fun campsiteInfoView(context: Context, campsite: Campsite, showLink: Boolean): View { - val padding = (8 * context.resources.displayMetrics.density).toInt() - val bubble = LinearLayout(context) - bubble.orientation = LinearLayout.VERTICAL - bubble.setBackgroundColor(android.graphics.Color.WHITE) - bubble.setPadding(padding, padding, padding, padding) - bubble.addView(infoLine(context, campsite.campsiteName, android.graphics.Color.BLACK, Typeface.BOLD)) - bubble.addView(infoLine(context, campsite.address, android.graphics.Color.DKGRAY, Typeface.NORMAL)) - if (showLink) { - val link = infoLine(context, "View campsite", OSM_LINK_COLOR, Typeface.BOLD) - link.setPadding(0, padding, 0, 0) - bubble.addView(link) + Text( + text = "© OpenStreetMap contributors", + fontSize = 11.sp, + color = Color.DarkGray, + modifier = Modifier + .align(Alignment.BottomEnd) + .background(Color.White.copy(alpha = 0.8f)) + .clickable { uriHandler.openUri("https://www.openstreetmap.org/copyright") } + .padding(horizontal = 4.dp, vertical = 1.dp) + ) + overlay() } - return bubble } /** @@ -279,37 +207,57 @@ private fun frameOsmCampsites(map: MapLibreMap, campsites: List, paddi } } +/** The markers for [campsites], each tagged with its campsite's ID. */ +private fun campsiteFeatures(campsites: List): FeatureCollection = + FeatureCollection.fromFeatures( + campsites.map { campsite -> + val feature = Feature.fromGeometry(markerPoint(campsite.latitude, campsite.longitude)) + feature.addStringProperty("id", campsite.campsiteId) + feature + } + ) + +/** The campsite whose marker is at [location] on [map], or `null` if the tap missed them all. */ +private fun campsiteAt(map: MapLibreMap, location: LatLng, campsites: List): Campsite? { + val point = map.projection.toScreenLocation(location) + val area = RectF(point.x - TAP_SLOP_PX, point.y - TAP_SLOP_PX, point.x + TAP_SLOP_PX, point.y + TAP_SLOP_PX) + val id = map.queryRenderedFeatures(area, MARKERS).firstOrNull()?.getStringProperty("id") + return campsites.find { it.campsiteId == id } +} + /** - * Adds a marker for each campsite to [map], with a bubble that calls [onCampsiteClick] when - * tapped. + * The card shown over the map for a tapped campsite, with the same text as the Google map's + * bubble. + * + * @param onClick Called when "View campsite" is tapped, or `null` to leave the link out. */ -private fun addCampsiteMarkers( - context: Context, - map: MapLibreMap, - campsites: List, - onCampsiteClick: ((Campsite) -> Unit)? -) { - val byMarker = mutableMapOf() - for (campsite in campsites) { - val marker = map.addMarker(MarkerOptions().position(campsite.osmPosition()).title(campsite.campsiteName)) - byMarker[marker] = campsite - } - map.setInfoWindowAdapter { marker -> - byMarker[marker]?.let { campsiteInfoView(context, it, showLink = onCampsiteClick != null) } - } - map.setOnInfoWindowClickListener { marker -> - byMarker[marker]?.let { onCampsiteClick?.invoke(it) } - true +@Composable +private fun CampsiteCard(campsite: Campsite, onClick: ((Campsite) -> Unit)?, modifier: Modifier) { + Card(modifier = modifier.widthIn(max = 240.dp).testTag("osm_campsite_card")) { + Column(modifier = Modifier.padding(12.dp)) { + Text(text = campsite.campsiteName, fontWeight = FontWeight.Bold) + Text(text = campsite.address, style = MaterialTheme.typography.bodyMedium) + if (onClick != null) { + Text( + text = "View campsite", + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier + .padding(top = 6.dp) + .clickable { onClick(campsite) } + ) + } + } } } /** * The OpenStreetMap version of [GoogleCampsiteMap]: a marker for each campsite, framed to show - * them all. + * them all. Tapping a marker shows the campsite's name and address over the map. * * @param campsites The campsites to mark, all with a location. * @param modifier Sets the size and shape of the map. - * @param onCampsiteClick Called when a campsite's bubble is tapped, or `null` to do nothing. + * @param onCampsiteClick Called when "View campsite" is tapped, or `null` to leave it out. */ @Composable internal fun OpenStreetCampsiteMap( @@ -317,17 +265,23 @@ internal fun OpenStreetCampsiteMap( modifier: Modifier, onCampsiteClick: ((Campsite) -> Unit)? ) { - val context = LocalContext.current val paddingPx = with(LocalDensity.current) { BOUNDS_PADDING.dp.roundToPx() } - val currentOnCampsiteClick by rememberUpdatedState(onCampsiteClick) - val start = CameraPosition.Builder() - .target(campsites[0].osmPosition()) - .zoom(SINGLE_CAMPSITE_ZOOM.toDouble()) - .build() + var selected by remember(campsites) { mutableStateOf(null) } + val start = CameraPosition.Builder().target(campsites[0].osmPosition()).zoom(SINGLE_CAMPSITE_ZOOM.toDouble()).build() key(campsites) { - OsmMap(start, modifier) { map -> - addCampsiteMarkers(context, map, campsites) { currentOnCampsiteClick?.invoke(it) } + OsmMap( + start = start, + modifier = modifier, + overlay = { + selected?.let { CampsiteCard(it, onCampsiteClick, Modifier.align(Alignment.TopCenter).padding(8.dp)) } + } + ) { map, markers -> + markers.setGeoJson(campsiteFeatures(campsites)) + map.addOnMapClickListener { location -> + selected = campsiteAt(map, location, campsites) + true + } frameOsmCampsites(map, campsites, paddingPx) } } @@ -349,22 +303,21 @@ internal fun OpenStreetClickableMap( onSelect: (GoogleLatLng) -> Unit ) { val currentOnSelect by rememberUpdatedState(onSelect) - var ready by remember { mutableStateOf?>(null) } - val camera = CameraPosition.Builder().target(start.toMapLibre()).zoom(OSM_PICKER_ZOOM).build() + var ready by remember { mutableStateOf?>(null) } LaunchedEffect(ready, move) { val (map, marker) = ready ?: return@LaunchedEffect - if (move != null) { - marker.position = move.location.toMapLibre() - map.moveCamera(CameraUpdateFactory.newLatLngZoom(move.location.toMapLibre(), OSM_PICKER_ZOOM)) - } + val location = move?.location ?: return@LaunchedEffect + marker.setGeoJson(markerPoint(location.latitude, location.longitude)) + map.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(location.latitude, location.longitude), OSM_PICKER_ZOOM)) } - OsmMap(camera, modifier) { map -> - val marker = map.addMarker(MarkerOptions().position(start.toMapLibre())) + val camera = CameraPosition.Builder().target(LatLng(start.latitude, start.longitude)).zoom(OSM_PICKER_ZOOM).build() + OsmMap(camera, modifier) { map, marker -> + marker.setGeoJson(markerPoint(start.latitude, start.longitude)) map.addOnMapClickListener { location -> - marker.position = location - currentOnSelect(location.toGoogle()) + marker.setGeoJson(markerPoint(location.latitude, location.longitude)) + currentOnSelect(GoogleLatLng(location.latitude, location.longitude)) true } ready = map to marker diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/notification/NotificationsScreen.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/notification/NotificationsScreen.kt index 5750fbaa..511e9e4b 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/notification/NotificationsScreen.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/notification/NotificationsScreen.kt @@ -190,7 +190,7 @@ fun NotificationsScreen( showBack = true ) - TabRow( + PrimaryTabRow( selectedTabIndex = selectedTab, containerColor = MaterialTheme.colorScheme.background, diff --git a/code/app/src/test/java/com/example/lambda_bbb_events/store/CampsiteStoreUnitTest.kt b/code/app/src/test/java/com/example/lambda_bbb_events/store/CampsiteStoreUnitTest.kt index 3bf8dd74..d0aa9bee 100644 --- a/code/app/src/test/java/com/example/lambda_bbb_events/store/CampsiteStoreUnitTest.kt +++ b/code/app/src/test/java/com/example/lambda_bbb_events/store/CampsiteStoreUnitTest.kt @@ -21,8 +21,8 @@ import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test -import org.junit.Assert.assertTrue +@OptIn(ExperimentalCoroutinesApi::class) class CampsiteStoreUnitTest { private val repo = mockk() private val lotteries = mockk() From 2df8beb393ab6702459ff32bb6fa0c0dd235820e Mon Sep 17 00:00:00 2001 From: somethingGit <113336038+somethingGit@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:54:16 -0600 Subject: [PATCH 3/7] Prevent thread blocking --- .../view/ui/components/map/ClickableMap.kt | 71 ++++++++++++------- 1 file changed, 47 insertions(+), 24 deletions(-) diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/ClickableMap.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/ClickableMap.kt index 9263837c..adeea47e 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/ClickableMap.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/map/ClickableMap.kt @@ -1,8 +1,10 @@ package com.example.lambda_bbb_events.view.ui.components.map import android.content.Context +import android.location.Address import android.location.Geocoder import android.os.Build +import androidx.annotation.RequiresApi import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height @@ -13,6 +15,7 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext @@ -20,7 +23,14 @@ import androidx.compose.ui.unit.dp import com.example.lambda_bbb_events.model.services.MapFallback import com.example.lambda_bbb_events.model.services.MapProvider import com.google.android.gms.maps.model.LatLng +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withContext +import java.io.IOException import java.util.Locale +import kotlin.coroutines.resume /* @@ -62,10 +72,15 @@ fun ClickableMap( } val pendingMove = move?.takeIf { it !== replacedMove } + val scope = rememberCoroutineScope() + var lookup by remember { mutableStateOf(null) } + val select = { latLng: LatLng -> markerLocation = latLng replacedMove = move - fetchAddressAndPostalCodeFromLatLng(context, latLng) { fetchedAddress, fetchedPostalCode -> + lookup?.cancel() + lookup = scope.launch { + val (fetchedAddress, fetchedPostalCode) = fetchAddressAndPostalCodeFromLatLng(context, latLng) onLocationSelected(latLng, fetchedAddress, fetchedPostalCode) } } @@ -85,37 +100,45 @@ fun ClickableMap( } } +/** The first address Android's geocoder finds at [location], or `null` if it finds none. */ +@RequiresApi(Build.VERSION_CODES.TIRAMISU) +private suspend fun geocodeWithListener(geocoder: Geocoder, location: LatLng): Address? = + suspendCancellableCoroutine { continuation -> + geocoder.getFromLocation(location.latitude, location.longitude, 1, object : Geocoder.GeocodeListener { + override fun onGeocode(addresses: MutableList
) = continuation.resume(addresses.firstOrNull()) + override fun onError(errorMessage: String?) = continuation.resume(null) + }) + } + +/** + * The first address Android's geocoder finds at [location], or `null` if it finds none. Before + * Android 13 the geocoder can only wait for its answer, so it is asked on a background thread. + */ +private suspend fun geocodeOnBackgroundThread(geocoder: Geocoder, location: LatLng): Address? = + withContext(Dispatchers.IO) { + @Suppress("DEPRECATION") + geocoder.getFromLocation(location.latitude, location.longitude, 1)?.firstOrNull() + } + /** - * Performs reverse geocoding to retrieve the address and postal code for the given [LatLng] coordinates. + * Looks up the address and postal code at [location] without blocking the main thread. * * @param context The current Android [Context]. * @param location The [LatLng] coordinates to reverse-geocode. - * @param callback Callback returning the retrieved full address and postal code. + * @return The full address and postal code, or empty strings if none is found or the lookup fails. */ -fun fetchAddressAndPostalCodeFromLatLng( - context: Context, - location: LatLng, - callback: (address: String, postalCode: String) -> Unit -) { +suspend fun fetchAddressAndPostalCodeFromLatLng(context: Context, location: LatLng): Pair { val geocoder = Geocoder(context, Locale.getDefault()) - try { + val address = try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - geocoder.getFromLocation(location.latitude, location.longitude, 1) { addresses -> - val addrObj = addresses.firstOrNull() - val fullAddress = addrObj?.getAddressLine(0) ?: "" - val postalCode = addrObj?.postalCode ?: "" - callback(fullAddress, postalCode) - } + geocodeWithListener(geocoder, location) } else { - @Suppress("DEPRECATION") - val addresses = geocoder.getFromLocation(location.latitude, location.longitude, 1) - val addrObj = addresses?.firstOrNull() - val fullAddress = addrObj?.getAddressLine(0) ?: "" - val postalCode = addrObj?.postalCode ?: "" - callback(fullAddress, postalCode) + geocodeOnBackgroundThread(geocoder, location) } - } catch (e: Exception) { - e.printStackTrace() - callback("", "") + } catch (e: IOException) { + null + } catch (e: IllegalArgumentException) { + null } + return Pair(address?.getAddressLine(0) ?: "", address?.postalCode ?: "") } From 3220be5738acf8c7f1809fc82a0850b3d3624497 Mon Sep 17 00:00:00 2001 From: somethingGit <113336038+somethingGit@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:05:23 -0600 Subject: [PATCH 4/7] WOW factor --- .../ui/review/ReviewSectionUITest.kt | 144 +++++++++++++++++- .../controller/AppControllers.kt | 4 + .../controller/ReviewReactionController.kt | 107 +++++++++++++ .../controller/ReviewReplyController.kt | 91 +++++++++++ .../repository/ReviewReactionRepository.kt | 43 ++++++ .../model/repository/ReviewReplyRepository.kt | 46 ++++++ .../model/review/ReviewReaction.kt | 45 ++++++ .../model/review/ReviewReply.kt | 37 +++++ .../components/review/ReactableReviewCard.kt | 142 +++++++++++++++++ .../ui/components/review/ReactionSpots.kt | 63 ++++++++ .../view/ui/components/review/ReviewCard.kt | 6 +- .../ui/components/review/ReviewReactions.kt | 125 +++++++++++++++ .../ui/components/review/ReviewReplies.kt | 114 ++++++++++++++ .../ui/components/review/ReviewSection.kt | 8 +- .../ReviewReactionControllerUnitTest.kt | 104 +++++++++++++ .../ReviewReplyControllerUnitTest.kt | 77 ++++++++++ .../model/review/ReviewReactionUnitTest.kt | 33 ++++ .../model/review/ReviewReplyUnitTest.kt | 32 ++++ .../review/ReactionSpotsUnitTest.kt | 51 +++++++ code/firestore.rules | 42 +++++ 20 files changed, 1310 insertions(+), 4 deletions(-) create mode 100644 code/app/src/main/java/com/example/lambda_bbb_events/controller/ReviewReactionController.kt create mode 100644 code/app/src/main/java/com/example/lambda_bbb_events/controller/ReviewReplyController.kt create mode 100644 code/app/src/main/java/com/example/lambda_bbb_events/model/repository/ReviewReactionRepository.kt create mode 100644 code/app/src/main/java/com/example/lambda_bbb_events/model/repository/ReviewReplyRepository.kt create mode 100644 code/app/src/main/java/com/example/lambda_bbb_events/model/review/ReviewReaction.kt create mode 100644 code/app/src/main/java/com/example/lambda_bbb_events/model/review/ReviewReply.kt create mode 100644 code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReactableReviewCard.kt create mode 100644 code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReactionSpots.kt create mode 100644 code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewReactions.kt create mode 100644 code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewReplies.kt create mode 100644 code/app/src/test/java/com/example/lambda_bbb_events/controller/ReviewReactionControllerUnitTest.kt create mode 100644 code/app/src/test/java/com/example/lambda_bbb_events/controller/ReviewReplyControllerUnitTest.kt create mode 100644 code/app/src/test/java/com/example/lambda_bbb_events/model/review/ReviewReactionUnitTest.kt create mode 100644 code/app/src/test/java/com/example/lambda_bbb_events/model/review/ReviewReplyUnitTest.kt create mode 100644 code/app/src/test/java/com/example/lambda_bbb_events/view/ui/components/review/ReactionSpotsUnitTest.kt diff --git a/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/review/ReviewSectionUITest.kt b/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/review/ReviewSectionUITest.kt index 2b2af545..ba89dc55 100644 --- a/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/review/ReviewSectionUITest.kt +++ b/code/app/src/androidTest/java/com/example/lambda_bbb_events/ui/review/ReviewSectionUITest.kt @@ -7,12 +7,14 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.assertHasNoClickAction import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsEnabled import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.assertIsNotSelected import androidx.compose.ui.test.assertIsSelected +import androidx.compose.ui.test.getUnclippedBoundsInRoot import androidx.compose.ui.test.assertTextContains -import androidx.compose.ui.test.assertIsNotSelected import androidx.compose.ui.test.isDialog import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.test.onAllNodesWithTag @@ -25,9 +27,15 @@ import androidx.compose.ui.test.performTextReplacement import androidx.test.ext.junit.runners.AndroidJUnit4 import com.example.lambda_bbb_events.controller.AppControllers import com.example.lambda_bbb_events.controller.ReviewController +import com.example.lambda_bbb_events.controller.ReviewReactionController +import com.example.lambda_bbb_events.controller.ReviewReplyController import com.example.lambda_bbb_events.model.campsite.Campsite +import com.example.lambda_bbb_events.model.repository.ReviewReactionRepository +import com.example.lambda_bbb_events.model.repository.ReviewReplyRepository import com.example.lambda_bbb_events.model.repository.ReviewRepository import com.example.lambda_bbb_events.model.review.Review +import com.example.lambda_bbb_events.model.review.ReviewReaction +import com.example.lambda_bbb_events.model.review.ReviewReply import com.example.lambda_bbb_events.model.user.Admin import com.example.lambda_bbb_events.model.user.CampsiteOwner import com.example.lambda_bbb_events.model.user.Entrant @@ -41,10 +49,12 @@ import io.mockk.mockk import io.mockk.unmockkAll import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import java.util.Date +import kotlin.math.abs /** * Tests reading, writing, editing, and deleting reviews on a campsite's page. The repository is @@ -62,12 +72,25 @@ class ReviewSectionUITest { /** The stored reviews. Compose state, like the repository's cache. */ private var stored by mutableStateOf>(emptyList()) + private val replyRepository = mockk() + private val reactionRepository = mockk() + private var storedReplies by mutableStateOf>(emptyList()) + private var storedReactions by mutableStateOf>(emptyList()) + private val campsite = Campsite(campsiteId = "site-1", ownerId = "owner-1", campsiteName = "Lakeside") private val ed = Entrant(deviceId = "user-1", name = "Ed") private fun review(userId: String, rating: Int, comment: String = "", day: Long = 1) = Review("site-1_$userId", "site-1", userId, rating, comment, Date(day * 86_400_000)) + private fun centerOf(tag: String): Pair { + val bounds = composeTestRule.onNodeWithTag(tag).getUnclippedBoundsInRoot() + return (bounds.left + bounds.right).value / 2 to (bounds.top + bounds.bottom).value / 2 + } + + private fun reactionBy(userId: String, emoji: String) = + ReviewReaction(ReviewReaction.idFor("site-1_user-3", userId), "site-1_user-3", userId, emoji) + private fun showSection(signedIn: User?, vararg reviews: Review) { stored = reviews.toList() every { repository.getReviewsForCampsite("site-1") } answers { stored } @@ -82,6 +105,22 @@ class ReviewSectionUITest { stored = stored.filter { it.reviewId != firstArg() } } every { controllers.reviews } returns ReviewController(repository) + storedReplies = emptyList() + storedReactions = emptyList() + every { replyRepository.newReplyId() } returns "reply-1" + every { replyRepository.getRepliesFor(any()) } answers { storedReplies.filter { it.reviewId == firstArg() } } + coEvery { replyRepository.add(any()) } answers { storedReplies = storedReplies + firstArg() } + every { reactionRepository.getReactionsFor(any()) } answers { storedReactions.filter { it.reviewId == firstArg() } } + every { reactionRepository.getCached(any()) } answers { storedReactions.find { it.reactionId == firstArg() } } + coEvery { reactionRepository.add(any()) } answers { + val saved = firstArg() + storedReactions = storedReactions.filter { it.reactionId != saved.reactionId } + saved + } + coEvery { reactionRepository.delete(any()) } answers { + storedReactions = storedReactions.filter { it.reactionId != firstArg() } + } + every { controllers.reviewReplies } returns ReviewReplyController(replyRepository) + every { controllers.reviewReactions } returns ReviewReactionController(reactionRepository) every { controllers.users.currentUser } returns signedIn every { controllers.users.getCachedUser(any()) } returns null every { controllers.users.getCachedUser("user-1") } returns ed @@ -106,6 +145,109 @@ class ReviewSectionUITest { clearAllMocks() } + @Test + fun emojiTrayStaysHiddenUntilTheReactButtonIsTapped() { + showSection(ed, review("user-3", 5, "Lovely")) + + composeTestRule.onNodeWithTag("emojiTray").assertDoesNotExist() + click("addReaction") + composeTestRule.onNodeWithTag("emojiTray").assertIsDisplayed() + click("addReaction") + composeTestRule.onNodeWithTag("emojiTray").assertDoesNotExist() + } + + @Test + fun tappedEmojiIsPlacedOnTheReviewAndTappingItRemovesIt() { + showSection(ed, review("user-3", 5, "Lovely")) + + click("addReaction") + click("pickReaction_👍") + composeTestRule.onNodeWithTag("placedReaction_👍").assertIsDisplayed() + composeTestRule.onNodeWithTag("emojiTray").assertDoesNotExist() + + click("placedReaction_👍") + composeTestRule.onNodeWithTag("placedReaction_👍").assertDoesNotExist() + } + + @Test + fun sameEmojisShareOneSpotWithTheirCount() { + showSection(ed, review("user-3", 5, "Lovely")) + storedReactions = listOf(reactionBy("user-7", "😂"), reactionBy("user-8", "😂"), reactionBy("user-9", "😮")) + + composeTestRule.onNodeWithTag("placedReaction_😂").assertTextContains("2", substring = true) + composeTestRule.onNodeWithTag("placedReaction_😮").assertIsDisplayed() + } + + @Test + fun emojisStayPutWhenTheTrayOpensAndOnlyBottomOnesFollowTheBottomEdge() { + showSection(ed, review("user-3", 5, "Lovely")) + storedReactions = ReviewReaction.EMOJIS.mapIndexed { i, emoji -> reactionBy("user-${i + 10}", emoji) } + val before = ReviewReaction.EMOJIS.associateWith { centerOf("placedReaction_$it") } + + click("addReaction") + + val cardBottom = composeTestRule.onNodeWithTag("reviewCard").getUnclippedBoundsInRoot().bottom.value + val stayed = ReviewReaction.EMOJIS.filter { abs(centerOf("placedReaction_$it").second - cardBottom) > 1f } + assertTrue(stayed.isNotEmpty()) + for (emoji in stayed) { + val (x, y) = centerOf("placedReaction_$emoji") + assertEquals(emoji, before.getValue(emoji).first, x, 1f) + assertEquals(emoji, before.getValue(emoji).second, y, 1f) + } + } + + @Test + fun pickingTheSameEmojiFromTheTrayAgainRemovesIt() { + showSection(ed, review("user-3", 5, "Lovely")) + + click("addReaction") + click("pickReaction_😮") + composeTestRule.onNodeWithTag("placedReaction_😮").assertIsDisplayed() + + click("addReaction") + click("pickReaction_😮") + composeTestRule.onNodeWithTag("placedReaction_😮").assertDoesNotExist() + } + + @Test + fun tappingSomeoneElsesEmojiAddsYoursToIt() { + showSection(ed, review("user-3", 5, "Lovely")) + storedReactions = listOf(reactionBy("user-9", "❤️")) + + click("placedReaction_❤️") + + composeTestRule.onNodeWithTag("placedReaction_❤️").assertTextContains("2", substring = true) + } + + @Test + fun signedOutUsersCannotTapEmojis() { + showSection(null, review("user-3", 5, "Lovely")) + storedReactions = listOf(reactionBy("user-9", "❤️")) + + composeTestRule.onNodeWithTag("placedReaction_❤️").assertIsDisplayed().assertHasNoClickAction() + } + + @Test + fun replyIsShownUnderTheReviewWithItsAuthor() { + showSection(ed, review("user-3", 5, "Lovely")) + + click("replyButton") + composeTestRule.onNodeWithTag("replyInput").performTextInput("Thanks for the tip") + click("sendReply") + + composeTestRule.onNodeWithTag("replyItem").assertIsDisplayed() + composeTestRule.onNodeWithText("Thanks for the tip").assertIsDisplayed() + composeTestRule.onNodeWithTag("replyInput").assertDoesNotExist() + } + + @Test + fun signedOutUsersCannotReactOrReply() { + showSection(null, review("user-3", 5, "Lovely")) + + composeTestRule.onNodeWithTag("addReaction").assertDoesNotExist() + composeTestRule.onNodeWithTag("replyButton").assertDoesNotExist() + } + @Test fun campsiteWithoutReviewsSaysSo() { showSection(ed) diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/controller/AppControllers.kt b/code/app/src/main/java/com/example/lambda_bbb_events/controller/AppControllers.kt index 966414c3..d7d727cf 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/controller/AppControllers.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/controller/AppControllers.kt @@ -16,6 +16,8 @@ import com.example.lambda_bbb_events.model.services.PlaceSearch * @property waitlistEntries Controller for waitlist operations. * @property images Service for image processing. * @property reviews Controller for campsite reviews. + * @property reviewReplies Controller for the replies under reviews. + * @property reviewReactions Controller for the emoji reactions to reviews. * @property places Searches for places by name. * @property messages Controller for messaging operations. * @property notificationPreferences Controller for notification preferences. @@ -31,6 +33,8 @@ class AppControllers( val waitlistEntries: WaitlistEntryController, val images: ImageProcessor, val reviews: ReviewController, + val reviewReplies: ReviewReplyController = ReviewReplyController(), + val reviewReactions: ReviewReactionController = ReviewReactionController(), val places: PlaceSearch = FallbackPlaceSearch(), val notifications: NotificationController, val messages: MessageController = MessageController(users), diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/controller/ReviewReactionController.kt b/code/app/src/main/java/com/example/lambda_bbb_events/controller/ReviewReactionController.kt new file mode 100644 index 00000000..796446e4 --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/controller/ReviewReactionController.kt @@ -0,0 +1,107 @@ +package com.example.lambda_bbb_events.controller + +import com.example.lambda_bbb_events.model.repository.ReviewReactionRepository +import com.example.lambda_bbb_events.model.review.Review +import com.example.lambda_bbb_events.model.review.ReviewReaction +import com.example.lambda_bbb_events.model.user.User + +/** + * Controller for the emoji reactions to campsite reviews. + * + * @property reactionRepository The repository for [ReviewReaction]. + */ +class ReviewReactionController( + val reactionRepository: ReviewReactionRepository = ReviewReactionRepository() +) { + /** + * Checks if a user can react to reviews. Anyone who is signed in can. + * + * @param user The user, or `null` if nobody is signed in. + */ + fun canReact(user: User?): Boolean = user != null + + /** + * Counts how many users picked each emoji for a review, in the order of + * [ReviewReaction.EMOJIS]. Emojis nobody picked are left out. + * + * @param review The review. + */ + fun reactionCounts(review: Review): Map { + val reactions = reactionRepository.getReactionsFor(review.reviewId) + return ReviewReaction.EMOJIS + .associateWith { emoji -> reactions.count { it.emoji == emoji } } + .filterValues { it > 0 } + } + + /** + * Gets a user's reaction to a review. + * + * @param review The review. + * @param user The user, or `null` if nobody is signed in. + * @return The reaction, or `null` if the user has not reacted. + */ + fun reactionOf(review: Review, user: User?): ReviewReaction? { + if (user == null) { + return null + } + return reactionRepository.getCached(ReviewReaction.idFor(review.reviewId, user.deviceId)) + } + + /** + * Reacts to a review with an emoji. A user has one reaction per review, so this replaces + * any emoji they picked before. + * + * @param review The review to react to. + * @param user The user reacting, or `null` if nobody is signed in. + * @param emoji The emoji picked, one of [ReviewReaction.EMOJIS]. + * @return `true` if the reaction was saved, `false` otherwise. + */ + suspend fun react(review: Review, user: User?, emoji: String): Boolean { + if (user == null || emoji !in ReviewReaction.EMOJIS) { + return false + } + val reactionId = ReviewReaction.idFor(review.reviewId, user.deviceId) + return try { + reactionRepository.add(ReviewReaction(reactionId, review.reviewId, user.deviceId, emoji)) + true + } catch (_: Exception) { + false + } + } + + /** + * Removes a user's reaction from a review. + * + * @param review The review. + * @param user The user, or `null` if nobody is signed in. + * @return `true` if the reaction was removed, `false` otherwise. + */ + suspend fun removeReaction(review: Review, user: User?): Boolean { + if (user == null) { + return false + } + return try { + reactionRepository.delete(ReviewReaction.idFor(review.reviewId, user.deviceId)) + true + } catch (_: Exception) { + false + } + } + + /** + * Reacts to a review with an emoji, or removes the user's reaction if it is the emoji they + * already picked. + * + * @param review The review. + * @param user The user reacting, or `null` if nobody is signed in. + * @param emoji The emoji picked, one of [ReviewReaction.EMOJIS]. + * @return `true` if the reaction was saved or removed, `false` otherwise. + */ + suspend fun toggleReaction(review: Review, user: User?, emoji: String): Boolean { + return if (reactionOf(review, user)?.emoji == emoji) { + removeReaction(review, user) + } else { + react(review, user, emoji) + } + } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/controller/ReviewReplyController.kt b/code/app/src/main/java/com/example/lambda_bbb_events/controller/ReviewReplyController.kt new file mode 100644 index 00000000..07e2e1a3 --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/controller/ReviewReplyController.kt @@ -0,0 +1,91 @@ +package com.example.lambda_bbb_events.controller + +import com.example.lambda_bbb_events.model.repository.ReviewReplyRepository +import com.example.lambda_bbb_events.model.review.Review +import com.example.lambda_bbb_events.model.review.ReviewReply +import com.example.lambda_bbb_events.model.user.User +import com.example.lambda_bbb_events.model.user.UserRole + +/** + * Controller for the replies under campsite reviews. + * + * @property replyRepository The repository for [ReviewReply]. + */ +class ReviewReplyController( + val replyRepository: ReviewReplyRepository = ReviewReplyRepository() +) { + /** + * Gets the replies to a review, oldest first, so they read like a conversation. + * + * @param review The review. + */ + fun getReplies(review: Review): List { + return replyRepository.getRepliesFor(review.reviewId).sortedBy { it.repliedAt } + } + + /** + * Checks if a user can reply to reviews. Anyone who is signed in can. + * + * @param user The user, or `null` if nobody is signed in. + */ + fun canReply(user: User?): Boolean = user != null + + /** + * Checks if a user can delete a reply. Users can delete their own replies, and admins can + * delete anyone's. + * + * @param reply The reply to delete. + * @param user The user, or `null` if nobody is signed in. + */ + fun canDeleteReply(reply: ReviewReply, user: User?): Boolean { + return user != null && (reply.authorId == user.deviceId || user.role == UserRole.ADMIN) + } + + /** + * Saves a reply to a review. Spaces around the text are removed. + * + * @param review The review being replied to. + * @param user The user replying, or `null` if nobody is signed in. + * @param text What the user wrote. + * @return `null` if the reply was saved. An error message otherwise. + */ + suspend fun submitReply(review: Review, user: User?, text: String): String? { + if (user == null) { + return "Sign in to reply." + } + val trimmed = text.trim() + if (trimmed.isEmpty()) { + return "Please write a reply." + } + if (trimmed.length > ReviewReply.MAX_TEXT_LENGTH) { + return "Your reply must be at most ${ReviewReply.MAX_TEXT_LENGTH} characters." + } + val reply = ReviewReply(replyRepository.newReplyId(), review.reviewId, user.deviceId, trimmed) + return try { + replyRepository.add(reply) + null + } catch (_: Exception) { + "Could not send your reply. Please try again." + } + } + + /** + * Deletes a reply. + * + * @param reply The reply to delete. + * @param user The user deleting it, or `null` if nobody is signed in. + * @return `true` if the reply was deleted, `false` if the user cannot delete it or + * deleting it failed. + */ + suspend fun deleteReply(reply: ReviewReply, user: User?): Boolean { + if (!canDeleteReply(reply, user)) { + return false + } + return try { + replyRepository.delete(reply.replyId) + true + } catch (_: Exception) { + false + } + } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/model/repository/ReviewReactionRepository.kt b/code/app/src/main/java/com/example/lambda_bbb_events/model/repository/ReviewReactionRepository.kt new file mode 100644 index 00000000..17d26970 --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/model/repository/ReviewReactionRepository.kt @@ -0,0 +1,43 @@ +package com.example.lambda_bbb_events.model.repository + +import android.util.Log +import com.example.lambda_bbb_events.model.review.ReviewReaction +import com.google.firebase.Firebase +import com.google.firebase.firestore.DocumentSnapshot +import com.google.firebase.firestore.FirebaseFirestore +import com.google.firebase.firestore.FirebaseFirestoreException +import com.google.firebase.firestore.firestore + +/* + * Manages emoji reactions to campsite reviews in Firestore. + */ + +/** + * Handles the data in the Firestore database for the [ReviewReaction] class. + */ +class ReviewReactionRepository( + db: FirebaseFirestore = Firebase.firestore +) : Repository("reviewReactions", db) { + + init { + startListening() + } + + override fun idOf(item: ReviewReaction) = item.reactionId + + override fun fromDocument(document: DocumentSnapshot): ReviewReaction? = + document.toObject(ReviewReaction::class.java)?.takeIf { it.isValid() } + + override fun onListenError(error: FirebaseFirestoreException) { + Log.e("ReviewReactionRepository", "listener error", error) + } + + /** + * Gets every reaction to a review from the cache. + * + * @param reviewId The ID of the review. + * @return The reactions, in no particular order. + */ + fun getReactionsFor(reviewId: String): List = + cached.filter { it.reviewId == reviewId } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/model/repository/ReviewReplyRepository.kt b/code/app/src/main/java/com/example/lambda_bbb_events/model/repository/ReviewReplyRepository.kt new file mode 100644 index 00000000..8f33c938 --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/model/repository/ReviewReplyRepository.kt @@ -0,0 +1,46 @@ +package com.example.lambda_bbb_events.model.repository + +import android.util.Log +import com.example.lambda_bbb_events.model.review.ReviewReply +import com.google.firebase.Firebase +import com.google.firebase.firestore.DocumentSnapshot +import com.google.firebase.firestore.FirebaseFirestore +import com.google.firebase.firestore.FirebaseFirestoreException +import com.google.firebase.firestore.firestore + +/* + * Manages replies to campsite reviews in Firestore. + */ + +/** + * Handles the data in the Firestore database for the [ReviewReply] class. + */ +class ReviewReplyRepository( + db: FirebaseFirestore = Firebase.firestore +) : Repository("reviewReplies", db) { + + init { + startListening() + } + + override fun idOf(item: ReviewReply) = item.replyId + + override fun fromDocument(document: DocumentSnapshot): ReviewReply? = + document.toObject(ReviewReply::class.java)?.takeIf { it.isValid() } + + override fun onListenError(error: FirebaseFirestoreException) { + Log.e("ReviewReplyRepository", "listener error", error) + } + + /** Makes a new, unused ID for a reply. */ + fun newReplyId(): String = collectionRef.document().id + + /** + * Gets every reply to a review from the cache. + * + * @param reviewId The ID of the review. + * @return The replies, in no particular order. + */ + fun getRepliesFor(reviewId: String): List = + cached.filter { it.reviewId == reviewId } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/model/review/ReviewReaction.kt b/code/app/src/main/java/com/example/lambda_bbb_events/model/review/ReviewReaction.kt new file mode 100644 index 00000000..b4581203 --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/model/review/ReviewReaction.kt @@ -0,0 +1,45 @@ +package com.example.lambda_bbb_events.model.review + +import com.google.firebase.firestore.Exclude + +/* + * Defines the emoji reactions users leave on campsite reviews. + */ + +/** + * A user's emoji reaction to a [Review]. Each user has at most one reaction per review. + * + * @property reactionId The unique ID of the reaction, from [ReviewReaction.idFor]. + * @property reviewId The ID of the review reacted to. + * @property reactorId The device ID of the user who reacted. + * @property emoji The emoji the user picked, one of [EMOJIS]. + */ +data class ReviewReaction( + val reactionId: String = "", + val reviewId: String = "", + val reactorId: String = "", + val emoji: String = "" +) { + /** Whether the reaction has the right ID for its review and user, and an allowed emoji. */ + @Exclude + fun isValid(): Boolean { + return reviewId.isNotBlank() && reactorId.isNotBlank() && + reactionId == idFor(reviewId, reactorId) && emoji in EMOJIS + } + + companion object { + /** The emojis users can react with, in the order they are shown. */ + val EMOJIS = listOf("👍", "❤️", "😂", "😮", "😢", "👎") + + /** + * Gets the ID of a user's reaction to a review. It is always the same for the same + * user and review, so reacting again replaces the first reaction. + * + * @param reviewId The ID of the review. + * @param reactorId The device ID of the user. + */ + fun idFor(reviewId: String, reactorId: String): String { + return reviewId + "_" + reactorId + } + } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/model/review/ReviewReply.kt b/code/app/src/main/java/com/example/lambda_bbb_events/model/review/ReviewReply.kt new file mode 100644 index 00000000..5343c52f --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/model/review/ReviewReply.kt @@ -0,0 +1,37 @@ +package com.example.lambda_bbb_events.model.review + +import com.google.firebase.firestore.Exclude +import java.util.Date + +/* + * Defines the replies users write under campsite reviews. + */ + +/** + * A reply to a [Review]. Replies are listed under the review in the order they were written. + * + * @property replyId The unique ID of the reply. + * @property reviewId The ID of the review being replied to. + * @property authorId The device ID of the user who wrote the reply. + * @property text What the user wrote. + * @property repliedAt When the reply was written. + */ +data class ReviewReply( + val replyId: String = "", + val reviewId: String = "", + val authorId: String = "", + val text: String = "", + val repliedAt: Date = Date() +) { + /** Whether the reply has its IDs, and text that is not blank or too long. */ + @Exclude + fun isValid(): Boolean { + return replyId.isNotBlank() && reviewId.isNotBlank() && authorId.isNotBlank() && + text.isNotBlank() && text.length <= MAX_TEXT_LENGTH + } + + companion object { + /** The longest reply, in characters. */ + const val MAX_TEXT_LENGTH = 300 + } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReactableReviewCard.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReactableReviewCard.kt new file mode 100644 index 00000000..ecb24316 --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReactableReviewCard.kt @@ -0,0 +1,142 @@ +package com.example.lambda_bbb_events.view.ui.components.review + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.AddReaction +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.dp +import com.example.lambda_bbb_events.controller.ReviewReactionController +import com.example.lambda_bbb_events.controller.ReviewReplyController +import com.example.lambda_bbb_events.model.review.Review +import com.example.lambda_bbb_events.model.user.User +import kotlinx.coroutines.launch + +/* + * Shows a campsite review with the emoji reactions around it and the replies under it. + */ + +/** + * The buttons to open the emoji tray and the reply box. + * + * @param onReact Called when the react button is tapped, or `null` to show no button. + * @param onReply Called when the reply button is tapped, or `null` to show no button. + */ +@Composable +private fun ThreadButtons(onReact: (() -> Unit)?, onReply: (() -> Unit)?) { + Row(verticalAlignment = Alignment.CenterVertically) { + if (onReact != null) { + IconButton(onClick = onReact, modifier = Modifier.testTag("addReaction")) { + Icon(Icons.Outlined.AddReaction, contentDescription = "React") + } + } + if (onReply != null) { + TextButton(onClick = onReply, modifier = Modifier.testTag("replyButton")) { + Text("Reply") + } + } + } +} + +/** + * Displays a review card with the emojis users reacted with placed around its edge, and its + * replies under it. Each emoji has its own spot, the same on every screen. Signed-in users can + * pick an emoji from the tray or tap one on the card to pick it too, and picking the emoji they + * already picked removes it. The emoji tray and the reply box stay hidden until their button is + * tapped. Updates by itself when reactions or replies change. + * + * @param review The review to show. + * @param reviewer The user who wrote it, or `null` if their account was deleted. + * @param onDelete Called when the review's delete button is tapped, or `null` to show no button. + * @param user The signed-in user, or `null` if nobody is signed in. + * @param replies Gets, sends, and deletes the replies. + * @param reactions Gets, saves, and removes the reactions. + * @param nameOf Gets a user's name from their device ID, or `null` if their account was deleted. + */ +@Composable +fun ReactableReviewCard( + review: Review, + reviewer: User?, + onDelete: (() -> Unit)?, + user: User?, + replies: ReviewReplyController, + reactions: ReviewReactionController, + nameOf: (String) -> String? +) { + val scope = rememberCoroutineScope() + var cardSize by remember { mutableStateOf(IntSize.Zero) } + var footerHeight by remember { mutableIntStateOf(0) } + var isPicking by rememberSaveable(review.reviewId) { mutableStateOf(false) } + var isReplying by rememberSaveable(review.reviewId) { mutableStateOf(false) } + var error by remember(review.reviewId) { mutableStateOf(null) } + val toggleReaction: (String) -> Unit = { emoji -> + scope.launch { error = if (reactions.toggleReaction(review, user, emoji)) null else "Could not save your reaction." } + } + + Box(modifier = Modifier.onSizeChanged { cardSize = it }) { + ReviewCard(review, reviewer, onDelete) { + Column( + modifier = Modifier + .fillMaxWidth() + .onSizeChanged { footerHeight = it.height }, + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + for (reply in replies.getReplies(review)) { + ReplyItem( + reply = reply, + authorName = nameOf(reply.authorId), + onDelete = if (replies.canDeleteReply(reply, user)) { + { scope.launch { error = if (replies.deleteReply(reply, user)) null else "Could not delete the reply." } } + } else { + null + } + ) + } + ThreadButtons( + onReact = if (reactions.canReact(user)) ({ isPicking = !isPicking }) else null, + onReply = if (replies.canReply(user)) ({ isReplying = !isReplying }) else null + ) + if (isPicking) { + EmojiTray(onPick = { emoji -> + isPicking = false + toggleReaction(emoji) + }) + } + if (isReplying) { + ReplyComposer(onSend = { text -> replies.submitReply(review, user, text) }, onSent = { isReplying = false }) + } + error?.let { + Text(text = it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) + } + } + } + PlacedReactions( + counts = reactions.reactionCounts(review), + mine = reactions.reactionOf(review, user)?.emoji, + spotOf = { emoji -> + spotOnCard(review.reviewId, emoji, cardSize.width.toFloat(), cardSize.height.toFloat(), footerHeight.toFloat()) + }, + onTap = if (reactions.canReact(user)) toggleReaction else null + ) + } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReactionSpots.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReactionSpots.kt new file mode 100644 index 00000000..c5480fdb --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReactionSpots.kt @@ -0,0 +1,63 @@ +package com.example.lambda_bbb_events.view.ui.components.review + +import com.example.lambda_bbb_events.model.review.ReviewReaction +import kotlin.random.Random + +/* + * Works out where emoji reactions sit around the edge of a review card. + */ + +/** + * Picks a spot on the edge of a review for an emoji. Each emoji gets its own part of the edge, + * so different emojis never share a spot, and sits at a random place in it. The spots are + * random but come from the review's ID, so they are the same on every screen and every time + * the review is shown. + * + * @param reviewId The ID of the review. + * @param emoji The emoji, one of [ReviewReaction.EMOJIS]. + * @param width How wide the review is. + * @param height How tall the review is. + * @return How far across and down the review the spot is. + */ +internal fun spotAround(reviewId: String, emoji: String, width: Float, height: Float): Pair { + val random = Random(reviewId.hashCode()) + val part = ReviewReaction.EMOJIS.shuffled(random).indexOf(emoji) + val placeInPart = List(ReviewReaction.EMOJIS.size) { 0.2f + 0.6f * random.nextFloat() }[part] + val perimeter = 2 * (width + height) + return pointOnEdge((part + placeInPart) / ReviewReaction.EMOJIS.size * perimeter, width, height) +} + +/** + * Finds a spot on the edge of a review card whose bottom part grows and shrinks. Spots on the + * top and sides are worked out from the part above the bottom part, so they stay put when it + * changes size. Spots on the bottom stay on the bottom edge. + * + * @param reviewId The ID of the review. + * @param emoji The emoji, one of [ReviewReaction.EMOJIS]. + * @param width How wide the card is. + * @param height How tall the whole card is. + * @param growingHeight How tall the bottom part that grows and shrinks is. + * @return How far across and down the card the spot is. + */ +internal fun spotOnCard(reviewId: String, emoji: String, width: Float, height: Float, growingHeight: Float): Pair { + val steadyHeight = height - growingHeight + val (x, y) = spotAround(reviewId, emoji, width, steadyHeight) + return x to if (y == steadyHeight) height else y +} + +/** + * Finds the point on the edge of a rectangle reached by going clockwise from its top left + * corner. + * + * @param distance How far to go along the edge. + * @param width How wide the rectangle is. + * @param height How tall the rectangle is. + */ +private fun pointOnEdge(distance: Float, width: Float, height: Float): Pair { + return when { + distance < width -> distance to 0f + distance < width + height -> width to distance - width + distance < 2 * width + height -> 2 * width + height - distance to height + else -> 0f to 2 * (width + height) - distance + } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewCard.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewCard.kt index 6ee8f78c..259a4664 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewCard.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewCard.kt @@ -40,13 +40,15 @@ import java.util.Locale * @param reviewer The user who wrote it, or `null` if their account was deleted. * @param onDelete Called when the delete button is tapped, or `null` to show no button. * @param modifier Customizes the card's layout. + * @param footer Shown at the bottom of the card, such as the review's reactions and replies. */ @Composable fun ReviewCard( review: Review, reviewer: User?, onDelete: (() -> Unit)?, - modifier: Modifier = Modifier + modifier: Modifier = Modifier, + footer: @Composable () -> Unit = {} ) { Card( modifier = modifier @@ -110,6 +112,8 @@ fun ReviewCard( color = MaterialTheme.colorScheme.onSurface ) } + + footer() } } } diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewReactions.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewReactions.kt new file mode 100644 index 00000000..a9fbe8a4 --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewReactions.kt @@ -0,0 +1,125 @@ +package com.example.lambda_bbb_events.view.ui.components.review + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.layout.layout +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.example.lambda_bbb_events.model.review.ReviewReaction +import kotlin.math.roundToInt + +/* + * Shows the emoji reactions around a campsite review, and the tray to pick one. + */ + +/** + * Places content so its center is at a point, measured from the parent's top left corner. + * + * @param center Gets how far across and down the point is. It is read while placing, so + * changes only move the content. + */ +private fun Modifier.centeredAt(center: () -> Pair): Modifier = layout { measurable, constraints -> + val placeable = measurable.measure(constraints.copy(minWidth = 0, minHeight = 0)) + layout(placeable.width, placeable.height) { + val (x, y) = center() + placeable.place(x.roundToInt() - placeable.width / 2, y.roundToInt() - placeable.height / 2) + } +} + +/** + * Displays an emoji at its spot on a review, with how many users picked it when more than one + * did. + * + * @param emoji The emoji. + * @param count How many users picked it. + * @param isMine Whether the user picked it, which highlights it. + * @param spot Gets how far across and down the review the emoji goes. + * @param onTap Called when the emoji is tapped, or `null` if it cannot be. + */ +@Composable +private fun PlacedEmoji(emoji: String, count: Int, isMine: Boolean, spot: () -> Pair, onTap: (() -> Unit)?) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .centeredAt(spot) + .then(if (isMine) Modifier.background(MaterialTheme.colorScheme.secondaryContainer, CircleShape) else Modifier) + .then(if (onTap != null) Modifier.clip(CircleShape).clickable(onClick = onTap) else Modifier) + .padding(horizontal = 2.dp) + .semantics(mergeDescendants = true) {} + .testTag("placedReaction_$emoji") + ) { + Text(text = emoji, style = MaterialTheme.typography.headlineSmall) + if (count > 1) { + Text( + text = count.toString(), + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurface + ) + } + } +} + +/** + * Displays the emojis users reacted to a review with, each at its own spot. Meant to be drawn + * over the review, in a box the size of the review. + * + * @param counts How many users picked each emoji. + * @param mine The emoji the user picked, or `null` if they have not reacted. + * @param spotOf Gets how far across and down the review an emoji goes. + * @param onTap Called with the emoji tapped, or `null` if they cannot be tapped. + */ +@Composable +internal fun PlacedReactions( + counts: Map, + mine: String?, + spotOf: (String) -> Pair, + onTap: ((String) -> Unit)? +) { + for ((emoji, count) in counts) { + PlacedEmoji( + emoji = emoji, + count = count, + isMine = emoji == mine, + spot = { spotOf(emoji) }, + onTap = onTap?.let { { it(emoji) } } + ) + } +} + +/** + * Displays every emoji users can react with side by side. + * + * @param onPick Called with the emoji tapped. + */ +@Composable +internal fun EmojiTray(onPick: (String) -> Unit) { + Row(modifier = Modifier.testTag("emojiTray"), horizontalArrangement = Arrangement.spacedBy(4.dp)) { + for (emoji in ReviewReaction.EMOJIS) { + Box( + contentAlignment = Alignment.Center, + modifier = Modifier + .size(40.dp) + .clip(CircleShape) + .clickable { onPick(emoji) } + .testTag("pickReaction_$emoji") + ) { + Text(emoji, style = MaterialTheme.typography.titleLarge) + } + } + } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewReplies.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewReplies.kt new file mode 100644 index 00000000..f57ffdbe --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewReplies.kt @@ -0,0 +1,114 @@ +package com.example.lambda_bbb_events.view.ui.components.review + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.Send +import androidx.compose.material.icons.outlined.Delete +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.example.lambda_bbb_events.model.review.ReviewReply +import kotlinx.coroutines.launch + +/* + * Shows the replies under a campsite review, and the box to write one. + */ + +/** + * Displays one reply, indented under its review. + * + * @param reply The reply to show. + * @param authorName The name of who wrote it, or `null` if their account was deleted. + * @param onDelete Called when the delete button is tapped, or `null` to show no button. + */ +@Composable +internal fun ReplyItem(reply: ReviewReply, authorName: String?, onDelete: (() -> Unit)?) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(start = 16.dp) + .background(MaterialTheme.colorScheme.surfaceVariant, RoundedCornerShape(8.dp)) + .padding(start = 12.dp, top = 8.dp, bottom = 8.dp) + .testTag("replyItem"), + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = authorName ?: "Deleted user", + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Text(text = reply.text, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + if (onDelete != null) { + IconButton(onClick = onDelete, modifier = Modifier.testTag("deleteReply")) { + Icon(Icons.Outlined.Delete, contentDescription = "Delete reply", tint = MaterialTheme.colorScheme.error) + } + } + } +} + +/** + * A box to write a reply and send it. + * + * @param onSend Sends what was written. Returns `null` if it was sent, or an error message. + * @param onSent Called once the reply was sent. + */ +@Composable +internal fun ReplyComposer(onSend: suspend (String) -> String?, onSent: () -> Unit) { + var draft by rememberSaveable { mutableStateOf("") } + var isSending by remember { mutableStateOf(false) } + var error by remember { mutableStateOf(null) } + val scope = rememberCoroutineScope() + + OutlinedTextField( + value = draft, + onValueChange = { draft = it.take(ReviewReply.MAX_TEXT_LENGTH) }, + placeholder = { Text("Write a reply") }, + isError = error != null, + supportingText = error?.let { { Text(it) } }, + enabled = !isSending, + trailingIcon = { + IconButton( + onClick = { + isSending = true + scope.launch { + error = onSend(draft) + isSending = false + if (error == null) { + draft = "" + onSent() + } + } + }, + enabled = draft.isNotBlank() && !isSending, + modifier = Modifier.testTag("sendReply") + ) { + Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send reply") + } + }, + modifier = Modifier + .fillMaxWidth() + .testTag("replyInput") + ) +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewSection.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewSection.kt index 42c8cf92..07bc9064 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewSection.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/review/ReviewSection.kt @@ -128,7 +128,7 @@ fun ReviewSection( val shownReviews = if (showAll) reviews else reviews.take(REVIEWS_SHOWN_AT_FIRST) for (review in shownReviews) { - ReviewCard( + ReactableReviewCard( review = review, reviewer = controllers.users.getCachedUser(review.reviewerId), onDelete = if (controllers.reviews.canDelete(review, user)) { @@ -138,7 +138,11 @@ fun ReviewSection( } } else { null - } + }, + user = user, + replies = controllers.reviewReplies, + reactions = controllers.reviewReactions, + nameOf = { controllers.users.getCachedUser(it)?.name } ) } diff --git a/code/app/src/test/java/com/example/lambda_bbb_events/controller/ReviewReactionControllerUnitTest.kt b/code/app/src/test/java/com/example/lambda_bbb_events/controller/ReviewReactionControllerUnitTest.kt new file mode 100644 index 00000000..819305bb --- /dev/null +++ b/code/app/src/test/java/com/example/lambda_bbb_events/controller/ReviewReactionControllerUnitTest.kt @@ -0,0 +1,104 @@ +package com.example.lambda_bbb_events.controller + +import com.example.lambda_bbb_events.model.repository.ReviewReactionRepository +import com.example.lambda_bbb_events.model.review.Review +import com.example.lambda_bbb_events.model.review.ReviewReaction +import com.example.lambda_bbb_events.model.user.Entrant +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.just +import io.mockk.mockk +import io.mockk.runs +import io.mockk.slot +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +class ReviewReactionControllerUnitTest { + private val reactions = mockk() + private val controller = ReviewReactionController(reactions) + + private val review = Review("site-1_user-1", "site-1", "user-1", rating = 4) + private val ed = Entrant(deviceId = "user-2") + private val edsReactionId = ReviewReaction.idFor(review.reviewId, "user-2") + private val savedReaction = slot() + + private fun reaction(userId: String, emoji: String) = + ReviewReaction(ReviewReaction.idFor(review.reviewId, userId), review.reviewId, userId, emoji) + + @Before + fun setup() { + coEvery { reactions.add(capture(savedReaction)) } just runs + coEvery { reactions.delete(any()) } just runs + every { reactions.getCached(any()) } returns null + } + + @Test + fun signedOutUsersCannotReact() = runTest { + assertFalse(controller.canReact(null)) + assertFalse(controller.react(review, null, "👍")) + assertFalse(controller.removeReaction(review, null)) + } + + @Test + fun reactionCountsFollowTheEmojiOrderAndSkipUnused() { + every { reactions.getReactionsFor(review.reviewId) } returns listOf( + reaction("a", "😂"), reaction("b", "👍"), reaction("c", "😂") + ) + + assertEquals(listOf("👍" to 1, "😂" to 2), controller.reactionCounts(review).toList()) + } + + @Test + fun reactingSavesTheEmoji() = runTest { + assertTrue(controller.react(review, ed, "👍")) + + assertEquals(reaction("user-2", "👍"), savedReaction.captured) + } + + @Test + fun reactingAgainReplacesTheFirstReaction() = runTest { + every { reactions.getCached(edsReactionId) } returns reaction("user-2", "👍") + + assertTrue(controller.react(review, ed, "😂")) + + assertEquals(reaction("user-2", "😂"), savedReaction.captured) + } + + @Test + fun removingAReactionDeletesIt() = runTest { + assertTrue(controller.removeReaction(review, ed)) + + coVerify(exactly = 1) { reactions.delete(edsReactionId) } + } + + @Test + fun togglingANewEmojiSavesIt() = runTest { + every { reactions.getCached(edsReactionId) } returns reaction("user-2", "👍") + + assertTrue(controller.toggleReaction(review, ed, "😂")) + + assertEquals(reaction("user-2", "😂"), savedReaction.captured) + coVerify(exactly = 0) { reactions.delete(any()) } + } + + @Test + fun togglingTheSameEmojiRemovesIt() = runTest { + every { reactions.getCached(edsReactionId) } returns reaction("user-2", "👍") + + assertTrue(controller.toggleReaction(review, ed, "👍")) + + coVerify(exactly = 1) { reactions.delete(edsReactionId) } + coVerify(exactly = 0) { reactions.add(any()) } + } + + @Test + fun emojiOutsideTheSetIsRefused() = runTest { + assertFalse(controller.react(review, ed, "🔥")) + coVerify(exactly = 0) { reactions.add(any()) } + } +} diff --git a/code/app/src/test/java/com/example/lambda_bbb_events/controller/ReviewReplyControllerUnitTest.kt b/code/app/src/test/java/com/example/lambda_bbb_events/controller/ReviewReplyControllerUnitTest.kt new file mode 100644 index 00000000..ccee542a --- /dev/null +++ b/code/app/src/test/java/com/example/lambda_bbb_events/controller/ReviewReplyControllerUnitTest.kt @@ -0,0 +1,77 @@ +package com.example.lambda_bbb_events.controller + +import com.example.lambda_bbb_events.model.repository.ReviewReplyRepository +import com.example.lambda_bbb_events.model.review.Review +import com.example.lambda_bbb_events.model.review.ReviewReply +import com.example.lambda_bbb_events.model.user.Admin +import com.example.lambda_bbb_events.model.user.Entrant +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.just +import io.mockk.mockk +import io.mockk.runs +import io.mockk.slot +import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import java.util.Date + +class ReviewReplyControllerUnitTest { + private val replies = mockk() + private val controller = ReviewReplyController(replies) + + private val review = Review("site-1_user-1", "site-1", "user-1", rating = 4) + private val ed = Entrant(deviceId = "user-2") + private val admin = Admin(deviceId = "admin-1") + private val savedReply = slot() + + @Before + fun setup() { + every { replies.newReplyId() } returns "reply-1" + coEvery { replies.add(capture(savedReply)) } just runs + coEvery { replies.delete(any()) } just runs + } + + @Test + fun repliesAreOldestFirst() { + val older = ReviewReply("a", review.reviewId, "user-2", "First", Date(1_000)) + val newer = ReviewReply("b", review.reviewId, "user-3", "Second", Date(2_000)) + every { replies.getRepliesFor(review.reviewId) } returns listOf(newer, older) + + assertEquals(listOf(older, newer), controller.getReplies(review)) + } + + @Test + fun replyIsTrimmedAndSaved() = runTest { + assertNull(controller.submitReply(review, ed, " Agreed! ")) + + assertEquals(ReviewReply("reply-1", review.reviewId, "user-2", "Agreed!", savedReply.captured.repliedAt), savedReply.captured) + } + + @Test + fun blankOrTooLongRepliesAreRefused() = runTest { + assertEquals("Please write a reply.", controller.submitReply(review, ed, " ")) + assertTrue(controller.submitReply(review, ed, "a".repeat(ReviewReply.MAX_TEXT_LENGTH + 1))!!.contains("at most")) + coVerify(exactly = 0) { replies.add(any()) } + } + + @Test + fun signedOutUsersCannotReply() = runTest { + assertFalse(controller.canReply(null)) + assertEquals("Sign in to reply.", controller.submitReply(review, null, "Hi")) + } + + @Test + fun onlyTheAuthorOrAnAdminCanDeleteAReply() = runTest { + val reply = ReviewReply("reply-1", review.reviewId, "user-2", "Hi") + + assertFalse(controller.deleteReply(reply, Entrant(deviceId = "someone-else"))) + assertTrue(controller.deleteReply(reply, ed)) + assertTrue(controller.deleteReply(reply, admin)) + } +} diff --git a/code/app/src/test/java/com/example/lambda_bbb_events/model/review/ReviewReactionUnitTest.kt b/code/app/src/test/java/com/example/lambda_bbb_events/model/review/ReviewReactionUnitTest.kt new file mode 100644 index 00000000..a13409ae --- /dev/null +++ b/code/app/src/test/java/com/example/lambda_bbb_events/model/review/ReviewReactionUnitTest.kt @@ -0,0 +1,33 @@ +package com.example.lambda_bbb_events.model.review + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ReviewReactionUnitTest { + private val reaction = ReviewReaction("site-1_user-1_user-2", "site-1_user-1", "user-2", "👍") + + @Test + fun idCombinesTheReviewAndUser() { + assertEquals("site-1_user-1_user-2", ReviewReaction.idFor("site-1_user-1", "user-2")) + } + + @Test + fun everyAllowedEmojiIsValid() { + for (emoji in ReviewReaction.EMOJIS) { + assertTrue(emoji, reaction.copy(emoji = emoji).isValid()) + } + } + + @Test + fun otherEmojiIsNotValid() { + assertFalse(reaction.copy(emoji = "🔥").isValid()) + assertFalse(reaction.copy(emoji = "").isValid()) + } + + @Test + fun wrongIdIsNotValid() { + assertFalse(reaction.copy(reactionId = "other").isValid()) + } +} diff --git a/code/app/src/test/java/com/example/lambda_bbb_events/model/review/ReviewReplyUnitTest.kt b/code/app/src/test/java/com/example/lambda_bbb_events/model/review/ReviewReplyUnitTest.kt new file mode 100644 index 00000000..4433c9d6 --- /dev/null +++ b/code/app/src/test/java/com/example/lambda_bbb_events/model/review/ReviewReplyUnitTest.kt @@ -0,0 +1,32 @@ +package com.example.lambda_bbb_events.model.review + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ReviewReplyUnitTest { + private val reply = ReviewReply("reply-1", "site-1_user-1", "user-2", "Agreed!") + + @Test + fun completeReplyIsValid() { + assertTrue(reply.isValid()) + } + + @Test + fun blankTextIsNotValid() { + assertFalse(reply.copy(text = " ").isValid()) + } + + @Test + fun textAtTheLimitIsValidButLongerIsNot() { + assertTrue(reply.copy(text = "a".repeat(ReviewReply.MAX_TEXT_LENGTH)).isValid()) + assertFalse(reply.copy(text = "a".repeat(ReviewReply.MAX_TEXT_LENGTH + 1)).isValid()) + } + + @Test + fun missingIdsAreNotValid() { + assertFalse(reply.copy(replyId = "").isValid()) + assertFalse(reply.copy(reviewId = "").isValid()) + assertFalse(reply.copy(authorId = "").isValid()) + } +} diff --git a/code/app/src/test/java/com/example/lambda_bbb_events/view/ui/components/review/ReactionSpotsUnitTest.kt b/code/app/src/test/java/com/example/lambda_bbb_events/view/ui/components/review/ReactionSpotsUnitTest.kt new file mode 100644 index 00000000..1ef2ac87 --- /dev/null +++ b/code/app/src/test/java/com/example/lambda_bbb_events/view/ui/components/review/ReactionSpotsUnitTest.kt @@ -0,0 +1,51 @@ +package com.example.lambda_bbb_events.view.ui.components.review + +import com.example.lambda_bbb_events.model.review.ReviewReaction +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class ReactionSpotsUnitTest { + @Test + fun spotIsOnTheEdgeOfTheReview() { + for (review in 1..20) { + for (emoji in ReviewReaction.EMOJIS) { + val (x, y) = spotAround("site-$review", emoji, 300f, 200f) + assertTrue("($x, $y)", x in 0f..300f && y in 0f..200f) + assertTrue("($x, $y)", x == 0f || x == 300f || y == 0f || y == 200f) + } + } + } + + @Test + fun spotIsTheSameEveryTime() { + assertEquals(spotAround("site-1_user-1", "👍", 300f, 200f), spotAround("site-1_user-1", "👍", 300f, 200f)) + } + + @Test + fun everyEmojiHasItsOwnSpot() { + val spots = ReviewReaction.EMOJIS.map { spotAround("site-1_user-1", it, 300f, 200f) } + assertEquals(ReviewReaction.EMOJIS.size, spots.toSet().size) + } + + @Test + fun spotsChangeFromReviewToReview() { + val spots = (1..10).map { spotAround("site-$it", "👍", 300f, 200f) } + assertTrue(spots.toSet().size > 1) + } + + @Test + fun onlyBottomSpotsMoveWhenTheBottomPartGrows() { + for (review in 1..20) { + for (emoji in ReviewReaction.EMOJIS) { + val small = spotOnCard("site-$review", emoji, 300f, 200f, 40f) + val grown = spotOnCard("site-$review", emoji, 300f, 260f, 100f) + if (small.second == 200f) { + assertEquals(small.first to 260f, grown) + } else { + assertEquals(small, grown) + } + } + } + } +} diff --git a/code/firestore.rules b/code/firestore.rules index 41ddbd9f..529e3f65 100644 --- a/code/firestore.rules +++ b/code/firestore.rules @@ -109,6 +109,38 @@ service cloud.firestore { ); } + // One emoji reaction per user and review. + match /reviewReactions/{id} { + + allow read, delete: if true; + + allow create, update: + if id == request.resource.data.reviewId + + '_' + + request.resource.data.reactorId + && request.resource.data.reactionId == id + && request.resource.data.emoji in ['👍', '❤️', '😂', '😮', '😢', '👎'] + && exists( + /databases/$(database)/documents/reviews/$(request.resource.data.reviewId) + ); + } + + // Replies to reviews. + match /reviewReplies/{id} { + + allow read, delete: if true; + + allow create, update: + if request.resource.data.replyId == id + && request.resource.data.authorId is string + && request.resource.data.text is string + && request.resource.data.text.size() > 0 + && request.resource.data.text.size() <= 300 + && exists( + /databases/$(database)/documents/reviews/$(request.resource.data.reviewId) + ); + } + // Campsite management. match /campsites/{id} { allow read, write: if true; @@ -197,5 +229,15 @@ service cloud.firestore { allow delete: if false; } + + // Firebase Cloud Messaging registration tokens. + // Prevents unauthorized clients from reading, + // modifying, or deleting device registration tokens. + // + // Trusted backend services using the Firebase Admin SDK + // can still access this collection. + match /fcmTokens/{deviceId} { + allow read, write: if false; + } } } From 0c0ebb2256df012956d58eba2f51d186ed37de78 Mon Sep 17 00:00:00 2001 From: somethingGit <113336038+somethingGit@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:04:51 -0600 Subject: [PATCH 5/7] Makes changes to the feeling of app App can now do system themes but also switch between light and dark while keeping these settings across app opening. Changes the colour of settings delete account and logout in order to deter users from utilizing the buttons. --- .../data/ThemePreferenceDatabaseTest.kt | 103 +++++++++++++ .../lambda_bbb_events/LambdaEventsApp.kt | 18 +-- .../example/lambda_bbb_events/MainActivity.kt | 42 ++++-- .../model/local/RecentlyViewedStore.kt | 46 +++++- .../model/local/ThemePreferenceStore.kt | 98 +++++++++++++ .../ui/components/profile/TogglableButton.kt | 135 ++++++++++++------ .../ui/user_screens/profile/SettingsScreen.kt | 27 +++- .../user_screens/profile/ThemeToggleScreen.kt | 36 +++-- 8 files changed, 428 insertions(+), 77 deletions(-) create mode 100644 code/app/src/androidTest/java/com/example/lambda_bbb_events/data/ThemePreferenceDatabaseTest.kt create mode 100644 code/app/src/main/java/com/example/lambda_bbb_events/model/local/ThemePreferenceStore.kt diff --git a/code/app/src/androidTest/java/com/example/lambda_bbb_events/data/ThemePreferenceDatabaseTest.kt b/code/app/src/androidTest/java/com/example/lambda_bbb_events/data/ThemePreferenceDatabaseTest.kt new file mode 100644 index 00000000..d875f79a --- /dev/null +++ b/code/app/src/androidTest/java/com/example/lambda_bbb_events/data/ThemePreferenceDatabaseTest.kt @@ -0,0 +1,103 @@ +package com.example.lambda_bbb_events.data + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.example.lambda_bbb_events.model.local.LocalDatabase +import com.example.lambda_bbb_events.model.local.SqliteRecentlyViewedStore +import com.example.lambda_bbb_events.model.local.SqliteThemePreferenceStore +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith + +/** + * Tests [SqliteThemePreferenceStore] against a real SQLite database held in memory, + * and that upgrading [LocalDatabase] from version 1 keeps recently viewed campsites. + * + * Reference: + * Anthropic. (2026). Claude Code (Claude Opus 5.5) [Large language model]. + * https://claude.com/claude-code + * Written with the help of this AI tool. + * Prompts: + * - "Okay so one thing I found was that dark mode doesn't stay if you select dark mode within + * the app. it disapears after app resets. Let's save it into the sqlite3 db we already have." + * - "Please make sure to also document and cite your changes." + * - "And then add a third button to the settings as system settings." + */ +@RunWith(AndroidJUnit4::class) +class ThemePreferenceDatabaseTest { + private val context = ApplicationProvider.getApplicationContext() + private lateinit var database: LocalDatabase + private lateinit var store: SqliteThemePreferenceStore + + @Before + fun setUp() { + database = LocalDatabase(context, name = null) + store = SqliteThemePreferenceStore(database) + } + + @After + fun cleanUp() { + database.close() + } + + @Test + fun nothingSavedFollowsSystem() { + assertNull(store.load()) + } + + @Test + fun savesDarkTheme() { + store.save(true) + + assertTrue(store.load()!!) + } + + @Test + fun laterChoiceReplacesEarlierOne() { + store.save(true) + store.save(false) + + assertFalse(store.load()!!) + } + + @Test + fun choosingSystemClearsSavedChoice() { + store.save(true) + store.save(null) + + assertNull(store.load()) + } + + @Test + fun choiceSurvivesReopeningDatabase() { + val name = "theme_test_${System.nanoTime()}.db" + try { + LocalDatabase(context, name).use { SqliteThemePreferenceStore(it).save(true) } + + LocalDatabase(context, name).use { + assertTrue(SqliteThemePreferenceStore(it).load()!!) + } + } finally { + context.deleteDatabase(name) + } + } + + @Test + fun upgradeFromVersionOneKeepsRecentlyViewed() { + SqliteRecentlyViewedStore(database).record("a", viewedAt = 1L, limit = 10) + val db = database.writableDatabase + db.execSQL("DROP TABLE ${LocalDatabase.SETTINGS_TABLE}") + + database.onUpgrade(db, 1, LocalDatabase.DATABASE_VERSION) + store.save(true) + + assertEquals(listOf("a"), SqliteRecentlyViewedStore(database).load(10)) + assertTrue(store.load()!!) + } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/LambdaEventsApp.kt b/code/app/src/main/java/com/example/lambda_bbb_events/LambdaEventsApp.kt index f4bd9741..25f08abe 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/LambdaEventsApp.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/LambdaEventsApp.kt @@ -92,14 +92,15 @@ import com.example.lambda_bbb_events.view.ui.user_screens.explore.SeeAllCampsite * Manages application startup such as loading, signup, or main application screens. * * @param controllers Shared application controllers. - * @param darkTheme Whether dark mode is enabled. - * @param onDarkThemeChange Updates the application's theme. + * @param darkTheme The theme the user picked: `true` for dark, `false` for light, + * or `null` to follow Android's setting. + * @param onDarkThemeChange Updates the application's theme with the picked option. */ @Composable fun LambdaEventsApp( controllers: AppControllers, - darkTheme: Boolean, - onDarkThemeChange: (Boolean) -> Unit + darkTheme: Boolean?, + onDarkThemeChange: (Boolean?) -> Unit ) { if (!controllers.users.usersFullyLoaded) { // Shown while checking whether this device already has an account @@ -156,14 +157,15 @@ fun LambdaEventsApp( * Defines routes for browsing, bookings, and account management. * * @param controllers Shared application controllers. - * @param darkTheme Whether dark mode is enabled. - * @param onDarkThemeChange Updates the application's theme. + * @param darkTheme The theme the user picked: `true` for dark, `false` for light, + * or `null` to follow Android's setting. + * @param onDarkThemeChange Updates the application's theme with the picked option. */ @Composable private fun MainApp( controllers: AppControllers, - darkTheme: Boolean, - onDarkThemeChange: (Boolean) -> Unit + darkTheme: Boolean?, + onDarkThemeChange: (Boolean?) -> Unit ) { val navController = rememberNavController() val currentUser = controllers.users.currentUser diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/MainActivity.kt b/code/app/src/main/java/com/example/lambda_bbb_events/MainActivity.kt index 72e93968..946a1b44 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/MainActivity.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/MainActivity.kt @@ -32,6 +32,7 @@ import com.example.lambda_bbb_events.controller.NotificationController import com.example.lambda_bbb_events.model.local.LocalDatabase import com.example.lambda_bbb_events.model.local.SharedPreferencesSessionStore import com.example.lambda_bbb_events.model.local.SqliteRecentlyViewedStore +import com.example.lambda_bbb_events.model.local.SqliteThemePreferenceStore import com.example.lambda_bbb_events.model.repository.LotteryRepository import com.example.lambda_bbb_events.model.repository.ReservationRepository import com.example.lambda_bbb_events.model.repository.ReviewRepository @@ -80,6 +81,24 @@ class MainActivity : ComponentActivity() { } } + /** + * Builds the repositories and controllers, then shows the app. + * + * Opens one [LocalDatabase] shared by the recently viewed campsites and the + * saved theme. The theme the user picked in the app (light, dark, or System to + * follow Android) is loaded from it before the first frame, and saved to it in + * the background whenever they change it. + * + * Reference: + * Anthropic. (2026). Claude Code (Claude Opus 5.5) [Large language model]. + * https://claude.com/claude-code + * Changed with the help of this AI tool (saving the theme choice, System option). + * Prompts: + * - "Okay so one thing I found was that dark mode doesn't stay if you select dark mode within + * the app. it disapears after app resets. Let's save it into the sqlite3 db we already have." + * - "Please make sure to also document and cite your changes." + * - "And then add a third button to the settings as system settings." + */ @SuppressLint("HardwareIds") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -104,6 +123,9 @@ class MainActivity : ComponentActivity() { val waitlistEntryRepository = WaitlistEntryRepository() val reviewRepository = ReviewRepository() val imageProcessor = ImageProcessor() + val localDatabase = LocalDatabase(applicationContext) + val themePreferenceStore = SqliteThemePreferenceStore(localDatabase) + val savedDarkTheme = themePreferenceStore.load() val userController = UserController(userRepository, deviceId,SharedPreferencesSessionStore(applicationContext)) val notifications = NotificationController(applicationContext,userController) notifications.createNotificationChannel() @@ -121,9 +143,7 @@ class MainActivity : ComponentActivity() { users = userController, campsites = CampsiteController( campsiteStore, - SqliteRecentlyViewedStore( - LocalDatabase(applicationContext) - ), + SqliteRecentlyViewedStore(localDatabase), lotteriesForCampsite = lotteryRepository::getLotteriesForCampsite ), lotteries = LotteryController(lotteryRepository), @@ -244,10 +264,11 @@ class MainActivity : ComponentActivity() { // Follow Android's dark mode setting, unless the // user picked a theme in the app. - // Only their choice is saved, so changing Android's - // setting still takes effect. + // Only their choice is saved (in the local SQLite + // database), so changing Android's setting still + // takes effect until they pick one. var chosenDarkTheme by rememberSaveable { - mutableStateOf(null) + mutableStateOf(savedDarkTheme) } val darkTheme = @@ -276,9 +297,12 @@ class MainActivity : ComponentActivity() { ) { LambdaEventsApp( controllers = controllers, - darkTheme = darkTheme, - onDarkThemeChange = { - chosenDarkTheme = it + darkTheme = chosenDarkTheme, + onDarkThemeChange = { choice -> + chosenDarkTheme = choice + lifecycleScope.launch(Dispatchers.IO) { + themePreferenceStore.save(choice) + } } ) } diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/model/local/RecentlyViewedStore.kt b/code/app/src/main/java/com/example/lambda_bbb_events/model/local/RecentlyViewedStore.kt index 17d2c8ff..31335145 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/model/local/RecentlyViewedStore.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/model/local/RecentlyViewedStore.kt @@ -64,8 +64,22 @@ class InMemoryRecentlyViewedStore : RecentlyViewedStore { /** * The app's local SQLite database on this device. * + * Tables: + * - [RECENTLY_VIEWED_TABLE]: campsites viewed on this device, used by [SqliteRecentlyViewedStore]. + * - [SETTINGS_TABLE]: device settings as key-value pairs, such as the theme saved by + * [SqliteThemePreferenceStore]. Added in version 2. + * * @param context The application context. * @param name The database file name, or `null` for a database held in memory. + * + * Reference: + * Anthropic. (2026). Claude Code (Claude Opus 5.5) [Large language model]. + * https://claude.com/claude-code + * Changed with the help of this AI tool (settings table, version 2 upgrade). + * Prompts: + * - "Okay so one thing I found was that dark mode doesn't stay if you select dark mode within + * the app. it disapears after app resets. Let's save it into the sqlite3 db we already have." + * - "Please make sure to also document and cite your changes." */ class LocalDatabase( context: Context, @@ -74,11 +88,15 @@ class LocalDatabase( companion object { const val DATABASE_NAME = "lambda_local.db" - const val DATABASE_VERSION = 1 + const val DATABASE_VERSION = 2 const val RECENTLY_VIEWED_TABLE = "recently_viewed" const val COLUMN_CAMPSITE_ID = "campsite_id" const val COLUMN_VIEWED_AT = "viewed_at" + + const val SETTINGS_TABLE = "settings" + const val COLUMN_KEY = "key" + const val COLUMN_VALUE = "value" } override fun onCreate(db: SQLiteDatabase) { @@ -90,11 +108,33 @@ class LocalDatabase( ) """.trimIndent() ) + createSettingsTable(db) } + /** + * Adds the settings table to databases made before version 2, + * keeping the recently viewed campsites already saved. + */ override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { - db.execSQL("DROP TABLE IF EXISTS $RECENTLY_VIEWED_TABLE") - onCreate(db) + if (oldVersion < 2) { + createSettingsTable(db) + } + } + + /** + * Creates the table of device settings, one value per key. + * + * @param db The database to create the table in. + */ + private fun createSettingsTable(db: SQLiteDatabase) { + db.execSQL( + """ + CREATE TABLE IF NOT EXISTS $SETTINGS_TABLE ( + $COLUMN_KEY TEXT PRIMARY KEY NOT NULL, + $COLUMN_VALUE TEXT NOT NULL + ) + """.trimIndent() + ) } } diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/model/local/ThemePreferenceStore.kt b/code/app/src/main/java/com/example/lambda_bbb_events/model/local/ThemePreferenceStore.kt new file mode 100644 index 00000000..8f48fcd4 --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/model/local/ThemePreferenceStore.kt @@ -0,0 +1,98 @@ +package com.example.lambda_bbb_events.model.local + +import android.content.ContentValues +import android.database.sqlite.SQLiteDatabase + +/** + * Saves the theme the user picked in the app in the [LocalDatabase], + * so it survives app restarts. + * + * When nothing is saved, the app follows Android's dark mode setting. + * The choice is one row in the [LocalDatabase.SETTINGS_TABLE], stored as + * "dark" or "light" under [DARK_THEME_KEY]. + * + * Calls read and write the disk. [load] is one small query, made once at + * startup so the first frame already uses the saved theme; [save] should be + * made off the main thread. + * + * @param database The local database to store the choice in. + * + * Reference: + * Anthropic. (2026). Claude Code (Claude Opus 5.5) [Large language model]. + * https://claude.com/claude-code + * Written with the help of this AI tool. + * Prompts: + * - "Okay so one thing I found was that dark mode doesn't stay if you select dark mode within + * the app. it disapears after app resets. Let's save it into the sqlite3 db we already have." + * - "Please make sure to also document and cite your changes." + * - "And then add a third button to the settings as system settings." + */ +class SqliteThemePreferenceStore( + private val database: LocalDatabase +) { + + companion object { + const val DARK_THEME_KEY = "dark_theme" + private const val DARK = "dark" + private const val LIGHT = "light" + } + + /** + * Loads the saved theme choice. + * + * @return `true` for dark mode, `false` for light mode, + * or `null` if the user never picked one. + */ + fun load(): Boolean? { + val cursor = database.readableDatabase.query( + LocalDatabase.SETTINGS_TABLE, + arrayOf(LocalDatabase.COLUMN_VALUE), + "${LocalDatabase.COLUMN_KEY} = ?", + arrayOf(DARK_THEME_KEY), + null, + null, + null + ) + val value = cursor.use { + if (it.moveToFirst()) it.getString(0) else null + } + return when (value) { + DARK -> true + LIGHT -> false + else -> null + } + } + + /** + * Saves the user's theme choice, replacing any earlier choice. + * + * @param darkTheme `true` for dark mode, `false` for light mode, + * or `null` to clear the choice and follow Android's setting again. + */ + fun save(darkTheme: Boolean?) { + if (darkTheme == null) { + clear() + return + } + val values = ContentValues() + values.put(LocalDatabase.COLUMN_KEY, DARK_THEME_KEY) + values.put(LocalDatabase.COLUMN_VALUE, if (darkTheme) DARK else LIGHT) + database.writableDatabase.insertWithOnConflict( + LocalDatabase.SETTINGS_TABLE, + null, + values, + SQLiteDatabase.CONFLICT_REPLACE + ) + } + + /** + * Removes the saved choice, so the app follows Android's setting. + */ + private fun clear() { + database.writableDatabase.delete( + LocalDatabase.SETTINGS_TABLE, + "${LocalDatabase.COLUMN_KEY} = ?", + arrayOf(DARK_THEME_KEY) + ) + } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/profile/TogglableButton.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/profile/TogglableButton.kt index c84e0bb3..eb40185f 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/profile/TogglableButton.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/components/profile/TogglableButton.kt @@ -14,11 +14,13 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shape import androidx.compose.ui.semantics.Role +import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp /* -Provides togglable button to be re-used throughout the app to switch between two options +Provides togglable buttons to be re-used throughout the app to switch between options */ /** @@ -37,6 +39,39 @@ fun ToggleButton( modifier: Modifier = Modifier, onText: String, offText: String, +) { + ChoiceToggle( + options = listOf(true to onText, false to offText), + selected = isOn, + onSelect = onToggle, + modifier = modifier + ) +} + +/** + * Displays a pill-shaped row of options where exactly one is selected. + * The selected option is highlighted and shows a check mark. + * + * @param options Each option's value and the text shown on its button, in display order. + * @param selected The value of the selected option. + * @param onSelect Called with an option's value when it is tapped. + * @param modifier Modifier applied to the row. + * @param optionPadding Horizontal padding inside each option; smaller fits more options. + * + * Reference: + * Anthropic. (2026). Claude Code (Claude Opus 5.5) [Large language model]. + * https://claude.com/claude-code + * Changed with the help of this AI tool (generalized from two options to any number). + * Prompts: + * - "And then add a third button to the settings as system settings." + */ +@Composable +fun ChoiceToggle( + options: List>, + selected: T, + onSelect: (T) -> Unit, + modifier: Modifier = Modifier, + optionPadding: Dp = 28.dp ) { val shape = RoundedCornerShape(50) @@ -47,46 +82,66 @@ fun ToggleButton( .border(1.dp, MaterialTheme.colorScheme.outlineVariant, shape), verticalAlignment = Alignment.CenterVertically ) { - // create two toggle options and checks which one is selected. - listOf(true to onText, false to offText).forEach { (value, title) -> - val selected = isOn == value - // checks if current state of button is equal to truth value of button - - // button row where icon and text are housed - Row( - modifier = Modifier - .clip(shape) - .background( - if (selected) MaterialTheme.colorScheme.primaryContainer - else Color.Transparent // highlight the button if selected - ) - .selectable( - selected = selected, - role = Role.RadioButton, - onClick = { onToggle(value) } - ) - .padding(horizontal = 28.dp, vertical = 14.dp), - verticalAlignment = Alignment.CenterVertically - ) { - // add check-mark icon if selected - if (selected) { - Icon( - imageVector = Icons.Default.Check, - contentDescription = null, - modifier = Modifier.size(14.dp), - tint = MaterialTheme.colorScheme.onPrimaryContainer - ) - Spacer(modifier = Modifier.width(4.dp)) - } + options.forEach { (value, title) -> + ChoiceOption( + title = title, + isSelected = selected == value, + onClick = { onSelect(value) }, + shape = shape, + horizontalPadding = optionPadding + ) + } + } +} - Text( - text = title, - style = MaterialTheme.typography.labelSmall, - color = if (selected) - MaterialTheme.colorScheme.onPrimaryContainer - else MaterialTheme.colorScheme.onSurface - ) - } +/** + * Displays one option of a [ChoiceToggle]. + * + * @param title The text shown on the option. + * @param isSelected Whether this option is the selected one. + * @param onClick Called when the option is tapped. + * @param shape The shape of the option's highlight. + * @param horizontalPadding Horizontal padding inside the option. + */ +@Composable +private fun ChoiceOption( + title: String, + isSelected: Boolean, + onClick: () -> Unit, + shape: Shape, + horizontalPadding: Dp +) { + Row( + modifier = Modifier + .clip(shape) + .background( + if (isSelected) MaterialTheme.colorScheme.primaryContainer + else Color.Transparent + ) + .selectable( + selected = isSelected, + role = Role.RadioButton, + onClick = onClick + ) + .padding(horizontal = horizontalPadding, vertical = 14.dp), + verticalAlignment = Alignment.CenterVertically + ) { + if (isSelected) { + Icon( + imageVector = Icons.Default.Check, + contentDescription = null, + modifier = Modifier.size(14.dp), + tint = MaterialTheme.colorScheme.onPrimaryContainer + ) + Spacer(modifier = Modifier.width(4.dp)) } + + Text( + text = title, + style = MaterialTheme.typography.labelSmall, + color = if (isSelected) + MaterialTheme.colorScheme.onPrimaryContainer + else MaterialTheme.colorScheme.onSurface + ) } } diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/profile/SettingsScreen.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/profile/SettingsScreen.kt index fa5f6230..5c7b7e44 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/profile/SettingsScreen.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/profile/SettingsScreen.kt @@ -40,6 +40,21 @@ import com.example.lambda_bbb_events.view.ui.components.common.ProfilePicture * * TODO: no test tags for log out or delete dialogs yet */ + +/** + * Settings routes for account actions that are shown in the error colour, + * matching the Logout icon on the profile screen. + * + * Reference: + * Anthropic. (2026). Claude Code (Claude Opus 5.5) [Large language model]. + * https://claude.com/claude-code + * Written with the help of this AI tool. + * Prompts: + * - "One thing is that in the edit profile screen vs settings screen the logout colour for icon + * is different. we want to make them the same also to set the same colour for delete account." + */ +private val DESTRUCTIVE_ROUTES = setOf("log_out", "delete_account") + /** * Displays user information and app settings. * @@ -187,7 +202,11 @@ fun Settings( modifier = Modifier .size(38.dp) .background( - MaterialTheme.colorScheme.primaryContainer, + if (route in DESTRUCTIVE_ROUTES) { + MaterialTheme.colorScheme.errorContainer + } else { + MaterialTheme.colorScheme.primaryContainer + }, CircleShape ), contentAlignment = Alignment.Center @@ -196,7 +215,11 @@ fun Settings( imageVector = icon, contentDescription = null, modifier = Modifier.size(20.dp), - tint = MaterialTheme.colorScheme.primary + tint = if (route in DESTRUCTIVE_ROUTES) { + MaterialTheme.colorScheme.error + } else { + MaterialTheme.colorScheme.primary + } ) } diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/profile/ThemeToggleScreen.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/profile/ThemeToggleScreen.kt index 1460c4ce..9fb80085 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/profile/ThemeToggleScreen.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/profile/ThemeToggleScreen.kt @@ -11,25 +11,34 @@ import androidx.navigation.NavController import com.example.lambda_bbb_events.controller.AppControllers import com.example.lambda_bbb_events.view.ui.components.common.ScreenTitle import com.example.lambda_bbb_events.view.ui.components.navigation.BottomNavigationBar -import com.example.lambda_bbb_events.view.ui.components.profile.ToggleButton +import com.example.lambda_bbb_events.view.ui.components.profile.ChoiceToggle /* -Provides togglable button to switch between dark and light mode throughout the app +Provides togglable buttons to switch between light mode, dark mode, and Android's setting */ /** - * Displays togglable appearance settings for switching themes. + * Displays togglable appearance settings for switching themes: light, dark, + * or System, which follows Android's dark mode setting. * * @param navController Handles navigation. * @param controllers Application controllers. - * @param darkTheme Whether dark mode is enabled. - * @param onDarkThemeChange Updates the app theme. + * @param darkTheme The theme the user picked: `true` for dark, `false` for light, + * or `null` to follow Android's setting. + * @param onDarkThemeChange Updates the app theme with the picked option. + * + * Reference: + * Anthropic. (2026). Claude Code (Claude Opus 5.5) [Large language model]. + * https://claude.com/claude-code + * Changed with the help of this AI tool (added the System option). + * Prompts: + * - "And then add a third button to the settings as system settings." */ @Composable fun Theme_Toggle( navController: NavController, controllers: AppControllers, - darkTheme: Boolean, - onDarkThemeChange: (Boolean) -> Unit + darkTheme: Boolean?, + onDarkThemeChange: (Boolean?) -> Unit ) { Scaffold( containerColor = MaterialTheme.colorScheme.background, @@ -52,14 +61,11 @@ fun Theme_Toggle( ) Spacer(modifier = Modifier.height(24.dp)) - // use button function, default value set to light-mode on - ToggleButton( - isOn = !darkTheme, - onToggle = { isLightMode -> - onDarkThemeChange(!isLightMode) - }, - onText = "Light Mode", - offText = "Dark Mode", + ChoiceToggle( + options = listOf(false to "Light", true to "Dark", null to "System"), + selected = darkTheme, + onSelect = onDarkThemeChange, + optionPadding = 20.dp, modifier = Modifier.testTag("toggle_theme") ) } From c0b24b6f7ad70b8996f8bb6fcb84549abbda16c2 Mon Sep 17 00:00:00 2001 From: Wesley William Supangat <44500655+supwess@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:05:59 -0600 Subject: [PATCH 6/7] Added choose reservation dates screen after use wins lottery. --- .../lambda_bbb_events/LambdaEventsApp.kt | 7 + .../CampsiteWinnerAvailabilityScreen.kt | 213 ++++++++++++++++++ .../lottery/RegistrationStatusScreen.kt | 74 +----- 3 files changed, 228 insertions(+), 66 deletions(-) create mode 100644 code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/bookings/CampsiteWinnerAvailabilityScreen.kt diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/LambdaEventsApp.kt b/code/app/src/main/java/com/example/lambda_bbb_events/LambdaEventsApp.kt index 25f08abe..4a4f9b7a 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/LambdaEventsApp.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/LambdaEventsApp.kt @@ -76,6 +76,7 @@ import com.example.lambda_bbb_events.view.ui.user_screens.notification.ChatRoute import kotlinx.coroutines.CancellationException import androidx.compose.runtime.rememberCoroutineScope import com.example.lambda_bbb_events.view.ui.owner_screens.LotteryRequestsScreen +import com.example.lambda_bbb_events.view.ui.user_screens.bookings.CampsiteWinnerAvailabilityScreen import kotlinx.coroutines.launch import com.example.lambda_bbb_events.view.ui.user_screens.explore.CampsiteSection import com.example.lambda_bbb_events.view.ui.user_screens.explore.SeeAllCampsitesScreen @@ -285,6 +286,12 @@ private fun MainApp( ) } + composable("winner_availability/{entryId}/{campsiteId}") { backStackEntry -> + val entryId = backStackEntry.arguments?.getString("entryId") ?: "" + val campsiteId = backStackEntry.arguments?.getString("campsiteId") ?: "" + CampsiteWinnerAvailabilityScreen(navController, controllers, entryId, campsiteId) + } + composable("booking_receipt/{reservationId}") { backStackEntry -> val reservationId = diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/bookings/CampsiteWinnerAvailabilityScreen.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/bookings/CampsiteWinnerAvailabilityScreen.kt new file mode 100644 index 00000000..6b301e9e --- /dev/null +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/bookings/CampsiteWinnerAvailabilityScreen.kt @@ -0,0 +1,213 @@ + +package com.example.lambda_bbb_events.view.ui.user_screens.bookings + +import com.example.lambda_bbb_events.model.formatting.parseDateOrNull +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.LocationOn +import androidx.compose.material.icons.outlined.Person +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.navigation.NavController +import com.example.lambda_bbb_events.controller.AppControllers +import com.example.lambda_bbb_events.view.ui.components.calendar.CampsiteAvailabilityCalendar +import com.example.lambda_bbb_events.view.ui.components.calendar.DatePickerField +import com.example.lambda_bbb_events.view.ui.components.rating.RatingSummary +import com.example.lambda_bbb_events.view.ui.components.common.ScreenTitle +import com.example.lambda_bbb_events.view.ui.components.common.FormTextFieldWithTitle +import java.time.LocalDate +import java.time.YearMonth +import com.example.lambda_bbb_events.view.ui.components.common.CampsiteThumbnail +import androidx.compose.ui.draw.clip +import com.example.lambda_bbb_events.controller.ReservationFilter +import com.example.lambda_bbb_events.view.ui.components.campsite.VerticalCampsiteCard +import kotlinx.coroutines.launch + +/* + * Allows users to select campsite reservation dates + * and guest counts before registration. + * + * TODO: Integrate the campsite's availability schedule + * into calendar selection and reservation validation. + */ + +/** + * Displays campsite information and a form for selecting their + * reservation dates. + * + * Navigates to the booking receipt status screen when the + * entered dates and guest count pass validation. + * + * @param navController Handles screen navigation. + * @param controllers Retrieves campsite information. + * @param entryId The ID of the waitlist entry. + * @param campsiteId The ID of the selected campsite. + */ +@Composable +fun CampsiteWinnerAvailabilityScreen( + navController: NavController, + controllers: AppControllers, + entryId: String, + campsiteId: String +) { + val entry = controllers.waitlistEntries.getEntryById(entryId) + val campsite = controllers.campsites.getCampsite(campsiteId) + var isLoading by remember { mutableStateOf(true) } + val scope = rememberCoroutineScope() + + var startDate by remember { mutableStateOf(null) } + var endDate by remember { mutableStateOf(null) } + var unavailableDates by remember { mutableStateOf>(emptySet()) } + var errorMessage by remember { mutableStateOf(null) } + var isConfirming by remember { mutableStateOf(false) } + + // Find the days this campsite is already full on. + LaunchedEffect(campsiteId, campsite != null) { + val maxOccupancy = campsite?.maxOccupancy ?: return@LaunchedEffect + + unavailableDates = try { + controllers.reservations.getFullyBookedDates( + controllers.reservations.getReservationsForCampsite( + campsiteId, + ReservationFilter.ALL + ), + maxOccupancy + ) + } catch (e: Exception) { // if fails then no unavailable + emptySet() + } + isLoading = false + } + + Column( + modifier = Modifier.fillMaxSize() + ) { + ScreenTitle( + title = "Choose Reservation Dates", + navController = navController, + showBack = true + ) + + if (entry == null || campsite == null || isLoading) { + Box( + modifier = Modifier + .fillMaxWidth() + .weight(1f), + contentAlignment = Alignment.Center + ) { + CircularProgressIndicator( + color = MaterialTheme.colorScheme.primary + ) + } + } else { + val fitsGuests = entry.numberOfGuests <= campsite.maxOccupancy + val start = startDate + val end = endDate + + Column( + modifier = Modifier + .fillMaxSize() + .background(MaterialTheme.colorScheme.background) + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + VerticalCampsiteCard( + campsite = campsite, + onClick = {} + ) + + Text( + text = "Number of Guests: ${entry.numberOfGuests}", + style = MaterialTheme.typography.bodyMedium + ) + + if (!fitsGuests) { + Text( + text = "You have more people than the max occupancy (${campsite.maxOccupancy}.", + color = MaterialTheme.colorScheme.error + ) + } + + Text( + text = "Select Dates", + style = MaterialTheme.typography.titleMedium + ) + + CampsiteAvailabilityCalendar( + initialMonth = YearMonth.now(), + unavailableDates = unavailableDates, + startDate = startDate, + endDate = endDate, + onDateRangeChange = { s, e -> + startDate = s + endDate = e + } + ) + + Text( + text = if (start != null && end != null) { + "Selected: $start to $end" + } else { + "Pick a start and end date." + }, + style = MaterialTheme.typography.bodyMedium + ) + + errorMessage?.let { + Text(text = it, color = MaterialTheme.colorScheme.error) + } + + Button( + onClick = { + if (start != null && end != null && !isConfirming) { + isConfirming = true + errorMessage = null + + scope.launch { + try { + controllers.reservations.confirmLotteryReservation( + entryId = entryId, + entrantId = controllers.users.user.deviceId, + campsiteId = campsiteId, + fromDate = start, + endDate = end, + numberOfGuests = entry.numberOfGuests + ) + + navController.navigate("booking_receipt/lottery_$entryId") { + popUpTo("registrationStatus/{entryId}") { + inclusive = true + } + launchSingleTop = true + } + } catch (e: Exception) { + errorMessage = e.message ?: "Failed to confirm reservation." + } finally { + isConfirming = false + } + } + } + }, + enabled = start != null && end != null && fitsGuests && !isConfirming, + modifier = Modifier.fillMaxWidth() + ) { + Text( + text = if (isConfirming) "Confirming..." else "Confirm Reservation", + style = MaterialTheme.typography.labelLarge + ) + } + + Spacer(modifier = Modifier.height(16.dp)) + } + } + } +} diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/bookings/lottery/RegistrationStatusScreen.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/bookings/lottery/RegistrationStatusScreen.kt index 863db59b..698a91e8 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/bookings/lottery/RegistrationStatusScreen.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/bookings/lottery/RegistrationStatusScreen.kt @@ -300,77 +300,19 @@ fun RegistrationStatusScreen( if (entry.status == WaitlistStatus.WON) { Button( - onClick = confirmClick@{ - - val selectedCampsiteId = - campsiteId ?: return@confirmClick - - val selectedFromDate = - fromDate ?: return@confirmClick - - val selectedEndDate = - endDate ?: return@confirmClick - - val confirmReservation = - onConfirmReservation - - if (confirmReservation == null) { - errorMessage = - "Reservation confirmation is not connected yet." - return@confirmClick - } - - if (isConfirming) return@confirmClick - - isConfirming = true - errorMessage = null - - scope.launch { - try { - - // Save the confirmed reservation. - confirmReservation( - entryId, - selectedCampsiteId, - selectedFromDate, - selectedEndDate, - entry.numberOfGuests - ) - - // Navigate directly to Booking Receipt. - navController.navigate("booking_receipt/lottery_$entryId") { - popUpTo("registrationStatus/{entryId}") { - inclusive = true - } - - launchSingleTop = true - } - - } catch (e: CancellationException) { - throw e - - } catch (e: Exception) { - errorMessage = e.message - ?: "Failed to confirm reservation." - - } finally { - isConfirming = false - } + onClick = { + val selectedCampsiteId = campsiteId + if (selectedCampsiteId != null) { + navController.navigate( + "winner_availability/$entryId/$selectedCampsiteId" + ) } }, - enabled = !isConfirming && - !isDeclining && - campsiteId != null && - fromDate != null && - endDate != null, + enabled = !isDeclining && campsiteId != null, modifier = Modifier.fillMaxWidth() ) { Text( - text = if (isConfirming) { - "Confirming..." - } else { - "Confirm Reservation" - }, + text = "Choose Reservation Dates", style = MaterialTheme.typography.labelLarge ) } From f010c495682df9aacb5b2f5982aad34100632846 Mon Sep 17 00:00:00 2001 From: Wesley William Supangat <44500655+supwess@users.noreply.github.com> Date: Sat, 28 Nov 2026 17:17:59 -0600 Subject: [PATCH 7/7] made it so that guests cant reserve dates if reserving that date will go over the max capacity for example: a campsite has a max capacity of 8 and 5 guests are already booked on a day. if there is winner with 4 guests, they will see that date as unavailable bcs $5 + 4 > 8$. a winner with 3 guests can still book it. --- .../controller/ReservationController.kt | 12 ++++++++++-- .../bookings/CampsiteWinnerAvailabilityScreen.kt | 5 +++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/controller/ReservationController.kt b/code/app/src/main/java/com/example/lambda_bbb_events/controller/ReservationController.kt index 3ad801bd..9f67f738 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/controller/ReservationController.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/controller/ReservationController.kt @@ -141,11 +141,18 @@ class ReservationController( * * @param reservations The reservations of the campsite. * @param maxOccupancy The max occupancy of the campsite. + * @param newGuests How many more guests need room. A day is unavailable if its booked + * guests plus these would go over the max occupancy. The default of 1 gives the days + * that are completely full. * @return The set of fully booked days. * * Reference: Claude created this function. */ - fun getFullyBookedDates(reservations: List, maxOccupancy: Int): Set { + fun getFullyBookedDates( + reservations: List, + maxOccupancy: Int, + newGuests: Int = 1 + ): Set { val guestsPerDay = mutableMapOf() for (reservation in reservations) { @@ -162,7 +169,8 @@ class ReservationController( } } - return guestsPerDay.filter { it.value >= maxOccupancy }.keys + // guests can't reserve date if their num of guests + current booked guests in that day is over max capacity + return guestsPerDay.filter { it.value + newGuests > maxOccupancy }.keys } diff --git a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/bookings/CampsiteWinnerAvailabilityScreen.kt b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/bookings/CampsiteWinnerAvailabilityScreen.kt index 6b301e9e..c4308fa7 100644 --- a/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/bookings/CampsiteWinnerAvailabilityScreen.kt +++ b/code/app/src/main/java/com/example/lambda_bbb_events/view/ui/user_screens/bookings/CampsiteWinnerAvailabilityScreen.kt @@ -71,7 +71,7 @@ fun CampsiteWinnerAvailabilityScreen( var isConfirming by remember { mutableStateOf(false) } // Find the days this campsite is already full on. - LaunchedEffect(campsiteId, campsite != null) { + LaunchedEffect(campsiteId, campsite != null, entry?.numberOfGuests) { val maxOccupancy = campsite?.maxOccupancy ?: return@LaunchedEffect unavailableDates = try { @@ -80,7 +80,8 @@ fun CampsiteWinnerAvailabilityScreen( campsiteId, ReservationFilter.ALL ), - maxOccupancy + maxOccupancy, + entry?.numberOfGuests ?: 1 ) } catch (e: Exception) { // if fails then no unavailable emptySet()