alexdum commited on
Commit
2b6afec
·
1 Parent(s): 1e54cf9

feat: add station deselection controls, floating chip, and keyboard shortcut support

Browse files
Files changed (7) hide show
  1. .gitignore +6 -0
  2. data/dataset_status_cache.rds +2 -2
  3. server.R +474 -152
  4. tests/test_station_deselection.R +602 -0
  5. ui.R +21 -0
  6. www/app.js +86 -8
  7. www/custom.css +101 -0
.gitignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ .agents/
2
+ agents/
3
+ .Rhistory
4
+ .RData
5
+ .Rproj.user
6
+ .DS_Store
data/dataset_status_cache.rds CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:2b6286e94902fc649a1d9d8b07139107641e4b3d84ec7fcf4b7912850157dc47
3
- size 144
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:daac7aaf6399087251793dcd864f7e13b5eb4ca00f25d2dd0441f1387b6fe360
3
+ size 254
server.R CHANGED
@@ -1,13 +1,24 @@
1
  server <- function(input, output, session) {
2
 
 
 
 
 
 
 
 
 
3
  # Show loading spinner on startup until stations are drawn
4
  session$sendCustomMessage("freezeUI", list(text = "Loading stations..."))
5
 
6
- # URL Deep-Linking State
7
  pending_station <- reactiveVal(NULL)
8
  pending_country <- reactiveVal(NULL)
9
  active_station_name <- reactiveVal(NULL)
10
  active_country <- reactiveVal(NULL)
 
 
 
11
 
12
  observe({
13
  query <- parseQueryString(isolate(session$clientData$url_search))
@@ -21,47 +32,68 @@ server <- function(input, output, session) {
21
  }) %>% bindEvent(session$clientData$url_search, ignoreNULL = FALSE, once = TRUE)
22
 
23
  # Emit state to parent iframe for URL synchronization
24
- observe({
25
- req(input$parameter, input$time_period, input$country)
 
26
 
27
- # Prefer the map-click tracked name, fall back to dropdown
28
- stn <- active_station_name()
29
- if (is.null(stn) || stn == "") {
30
- stn <- input$station
31
- if (is.null(stn)) stn <- "All"
 
 
 
 
 
 
 
 
32
  }
33
 
34
- # If we are waiting for a deep-link station to apply, use it
35
- if (!is.null(pending_station())) {
36
- if (isTRUE(input$station == pending_station())) {
37
- pending_station(NULL)
38
- } else {
39
- stn <- pending_station()
40
- }
41
  }
42
 
43
- cntry <- active_country()
44
- if (is.null(cntry) || cntry == "") cntry <- input$country
 
 
 
 
 
 
 
45
 
46
  session$sendCustomMessage("updateParentURL", list(
47
- parameter = input$parameter,
48
- time_period = input$time_period,
49
  country = cntry,
50
- station = stn
 
51
  ))
 
 
 
 
52
  })
53
 
54
  # Base dataset dependent on the selected parameter
55
  active_dataset <- reactive({
56
  param <- input$parameter
57
- if (param == "TAVG" && exists("tavg_sf")) return(tavg_sf)
58
- if (param == "TMAX" && exists("tmax_sf")) return(tmax_sf)
59
- if (param == "TMIN" && exists("tmin_sf")) return(tmin_sf)
60
- if (param == "PRCP" && exists("prcp_sf")) return(prcp_sf)
61
- if (param == "MSLP" && exists("mslp_sf")) return(mslp_sf)
62
- if (param == "MNVP" && exists("mnvp_sf")) return(mnvp_sf)
63
- if (param == "DP01" && exists("dp01_sf")) return(dp01_sf)
64
- if (param == "TSUN" && exists("tsun_sf")) return(tsun_sf)
 
65
  return(NULL)
66
  })
67
 
@@ -69,19 +101,20 @@ server <- function(input, output, session) {
69
  filtered_stations_by_country <- reactive({
70
  req(active_dataset())
71
  stations_sf <- active_dataset()
72
- if (input$country == "All") {
 
73
  stations_sf
74
  } else {
75
- stations_sf %>% filter(Country == input$country)
76
  }
77
  })
78
 
79
- # Update Station choices based on selected Country
80
- observeEvent(input$country, {
81
  if (!is.null(pending_country())) {
82
  if (!(pending_country() %in% countries_list)) {
83
  pending_country(NULL)
84
- } else if (input$country != pending_country()) {
85
  return()
86
  } else {
87
  pending_country(NULL)
@@ -90,50 +123,298 @@ server <- function(input, output, session) {
90
 
91
  filtered_data <- filtered_stations_by_country()
92
 
93
- # Reset choices for Station dropdown using SERVER-SIDE processing for performance
94
- if (!is.null(filtered_data) && nrow(filtered_data) > 0) {
95
- station_choices <- c("All Stations" = "All", unique(sort(filtered_data$Station_Name)))
96
-
97
- sel <- if (!is.null(pending_station())) pending_station() else "All"
98
-
99
- updateSelectizeInput(session, "station", choices = station_choices, selected = sel, server = FALSE)
 
 
 
 
 
100
  }
 
 
101
  }, ignoreInit = FALSE)
102
 
103
- # Jump back to Map View when a user changes the country filter
104
- observeEvent(input$country, {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  active_station_name(NULL)
106
  active_country(NULL)
107
- nav_select("main_nav", "Map View")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  }, ignoreInit = TRUE)
109
 
110
  # Jump back to Map View when parameter or time period changes while on Dashboard
111
  observeEvent(input$parameter, {
112
  if (identical(input$main_nav, "Dashboard")) {
113
- active_station_name(NULL)
114
- clicked_wmo_id(NULL)
115
- nav_select("main_nav", "Map View")
116
  }
117
  }, ignoreInit = TRUE)
118
 
119
  observeEvent(input$time_period, {
120
  if (identical(input$main_nav, "Dashboard")) {
121
- active_station_name(NULL)
122
- clicked_wmo_id(NULL)
123
- nav_select("main_nav", "Map View")
124
  }
125
  }, ignoreInit = TRUE)
126
-
127
- # Final reactive dataset based on both filters a user selects
128
- final_filtered_stations <- reactive({
129
- data <- filtered_stations_by_country()
130
- req(!is.null(data))
131
- data
132
- })
133
-
134
- # --- Map Initialization Variables ---
135
- initial_lng <- 0
136
- initial_lat <- 30
137
  initial_zoom <- 3
138
 
139
  # Reactive values for map state
@@ -154,16 +435,21 @@ server <- function(input, output, session) {
154
 
155
  # Initialize map bounds / Home Zoom
156
  observeEvent(input$home_zoom, {
157
- if (input$country != "All") {
158
- country_sel <- filtered_stations_by_country()
159
- if (!is.null(country_sel) && nrow(country_sel) > 0) {
160
- maplibre_proxy("station_map") %>% fit_bounds(country_sel, padding = 100, animate = TRUE)
 
 
 
 
 
 
 
161
  } else {
162
- maplibre_proxy("station_map") %>% fly_to(center = c(initial_lng, initial_lat), zoom = initial_zoom)
 
163
  }
164
- } else {
165
- maplibre_proxy("station_map") %>%
166
- fly_to(center = c(initial_lng, initial_lat), zoom = initial_zoom)
167
  }
168
  })
169
 
@@ -397,45 +683,31 @@ server <- function(input, output, session) {
397
  before_id = isolate(stations_before_id())
398
  )
399
 
400
- # Navigation lock bounds logic
401
- if (input$station != "All") {
402
- target_station <- data %>% filter(Station_Name == input$station)
403
- if (nrow(target_station) > 0) {
404
- sta_lon <- target_station$Longitude[1]
405
- sta_lat <- target_station$Latitude[1]
406
- click_id <- target_station$WMO_ID[1]
407
-
408
- clicked_wmo_id(click_id)
409
- active_station_name(input$station)
410
- active_country(target_station$Country[1])
411
-
412
- hl_pt <- sf::st_as_sf(
413
- data.frame(x = sta_lon, y = sta_lat),
414
- coords = c("x", "y"),
415
- crs = 4326
416
- )
417
-
418
- map %>%
419
- clear_layer("selected_highlight") %>%
420
- add_circle_layer(
421
- id = "selected_highlight",
422
- source = hl_pt,
423
- circle_color = "red",
424
- circle_radius = 12,
425
- circle_stroke_color = "white",
426
- circle_stroke_width = 2,
427
- circle_opacity = 0.4
428
- ) %>%
429
- fly_to(center = c(sta_lon, sta_lat), zoom = 8)
430
-
431
- nav_select("main_nav", "Dashboard")
432
- }
433
- } else if (input$country != "All") {
434
- map %>% clear_layer("selected_highlight")
435
- map %>% fit_bounds(data, padding = 100, animate = TRUE)
436
  } else {
437
- map %>% clear_layer("selected_highlight")
438
- map %>% fly_to(center = c(initial_lng, initial_lat), zoom = initial_zoom)
439
  }
440
  } else {
441
  map %>% clear_layer("wmo_stations")
@@ -447,9 +719,6 @@ server <- function(input, output, session) {
447
  # -----------------------------------------------------------------------------------
448
  # Dashboard Interaction & Reactivity
449
  # -----------------------------------------------------------------------------------
450
-
451
- # Reactive value to store selected WMO ID
452
- clicked_wmo_id <- reactiveVal(NULL)
453
 
454
  observeEvent(input$station_map_feature_click, {
455
  clicked <- input$station_map_feature_click
@@ -461,48 +730,54 @@ server <- function(input, output, session) {
461
 
462
  # If the user clicks the highlight, take them to the Dashboard (fallback)
463
  if (layer_id == "selected_highlight") {
464
- nav_select("main_nav", "Dashboard")
465
  return()
466
  }
467
 
468
  # If the user clicks a station, highlight it, zoom, AND go to dashboard
469
  if (layer_id == "wmo_stations") {
470
  props <- clicked$properties
471
- # WMO_ID extraction
472
  click_id <- if (!is.null(props$WMO_ID)) props$WMO_ID else props$wmo_id
 
473
 
474
- if (!is.null(click_id)) {
475
- clicked_wmo_id(click_id)
476
-
477
- # Track station name & country for parent URL sync
478
- if (!is.null(props$Station_Name)) active_station_name(props$Station_Name)
479
- if (!is.null(props$Country)) active_country(props$Country)
480
-
481
- # Use exact station coordinates from properties so the ring perfectly wraps the station
482
- sta_lon <- if (!is.null(props$Longitude)) props$Longitude else clicked$lng
483
- sta_lat <- if (!is.null(props$Latitude)) props$Latitude else clicked$lat
484
-
485
- hl_pt <- sf::st_as_sf(
486
- data.frame(x = sta_lon, y = sta_lat),
487
- coords = c("x", "y"),
488
- crs = 4326
489
- )
490
-
491
- maplibre_proxy("station_map") %>%
492
- clear_layer("selected_highlight") %>%
493
- add_circle_layer(
494
- id = "selected_highlight",
495
- source = hl_pt,
496
- circle_color = "red",
497
- circle_radius = 12,
498
- circle_stroke_color = "white",
499
- circle_stroke_width = 2,
500
- circle_opacity = 0.4
501
- ) %>%
502
- fly_to(center = c(sta_lon, sta_lat), zoom = 8)
503
 
504
- # Automatically transition to Dashboard Tab immediately
505
- nav_select("main_nav", "Dashboard")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
506
  }
507
  }
508
  })
@@ -510,15 +785,31 @@ server <- function(input, output, session) {
510
  # Render Station Metadata Header mimicking GHCNM
511
  output$dashboard_header <- renderUI({
512
  wmo <- clicked_wmo_id()
513
- if (is.null(wmo)) {
 
514
  return(h4(class="text-muted", "Please click a station on the interactive map to view its complete Normal arrays."))
515
  }
516
 
517
  # Fetch top-level metadata from TAVG, else fallback to PRCP
518
- meta_df <- if(inherits(tavg_sf, "sf") && nrow(tavg_sf) > 0) st_drop_geometry(tavg_sf) %>% filter(WMO_ID == wmo) else data.frame()
519
- if (nrow(meta_df) == 0 && inherits(prcp_sf, "sf") && nrow(prcp_sf) > 0) {
520
- meta_df <- st_drop_geometry(prcp_sf) %>% filter(WMO_ID == wmo)
 
 
 
 
 
 
 
 
 
 
 
 
 
521
  }
 
 
522
 
523
  if (nrow(meta_df) > 0) {
524
  station_name <- meta_df$Station_Name[1]
@@ -572,13 +863,24 @@ server <- function(input, output, session) {
572
 
573
  # Cross-Dataset Extraction
574
  station_dashboard_data <- reactive({
575
- req(clicked_wmo_id())
576
  sid <- clicked_wmo_id()
 
577
 
578
  extract_param <- function(df_sf, param_name) {
579
  if(is.null(df_sf) || inherits(df_sf, "sfc") || nrow(df_sf) == 0) return(NULL)
580
  df <- st_drop_geometry(df_sf)
581
- row <- df %>% filter(WMO_ID == sid)
 
 
 
 
 
 
 
 
 
 
582
  if(nrow(row) == 0) return(NULL)
583
 
584
  res <- data.frame(Parameter = param_name, stringsAsFactors = FALSE)
@@ -662,12 +964,32 @@ server <- function(input, output, session) {
662
  req(df)
663
 
664
  wmo <- clicked_wmo_id()
 
665
 
666
- meta_df <- if(inherits(tavg_sf, "sf") && nrow(tavg_sf) > 0) st_drop_geometry(tavg_sf) %>% filter(WMO_ID == wmo) else data.frame()
667
- if (nrow(meta_df) == 0 && inherits(prcp_sf, "sf") && nrow(prcp_sf) > 0) {
668
- meta_df <- st_drop_geometry(prcp_sf) %>% filter(WMO_ID == wmo)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
669
  }
670
- s_name <- if(nrow(meta_df) > 0) meta_df$Station_Name[1] else as.character(wmo)
671
 
672
  render_station_plots(df, s_name)
673
  })
 
1
  server <- function(input, output, session) {
2
 
3
+ # Defensive string validator
4
+ is_valid_str <- function(x) !is.null(x) && length(x) > 0 && !is.na(x[1]) && nzchar(trimws(as.character(x[1])))
5
+
6
+ # Map Initialization Variables
7
+ initial_lng <- 0
8
+ initial_lat <- 30
9
+ initial_zoom <- 3
10
+
11
  # Show loading spinner on startup until stations are drawn
12
  session$sendCustomMessage("freezeUI", list(text = "Loading stations..."))
13
 
14
+ # URL Deep-Linking & Station State
15
  pending_station <- reactiveVal(NULL)
16
  pending_country <- reactiveVal(NULL)
17
  active_station_name <- reactiveVal(NULL)
18
  active_country <- reactiveVal(NULL)
19
+ active_elevation <- reactiveVal(NULL)
20
+ clicked_wmo_id <- reactiveVal(NULL)
21
+ skip_country_clear <- reactiveVal(FALSE)
22
 
23
  observe({
24
  query <- parseQueryString(isolate(session$clientData$url_search))
 
32
  }) %>% bindEvent(session$clientData$url_search, ignoreNULL = FALSE, once = TRUE)
33
 
34
  # Emit state to parent iframe for URL synchronization
35
+ broadcast_parent_url <- function(tab_override = NULL) {
36
+ param <- if (is_valid_str(input$parameter)) input$parameter else "TAVG"
37
+ time_p <- if (is_valid_str(input$time_period)) input$time_period else "Annual"
38
 
39
+ # Check pending deep-link first, then active station, else default to "All"
40
+ stn <- if (!is.null(pending_station())) {
41
+ if (isTRUE(identical(input$station, pending_station()))) {
42
+ cur_pend <- pending_station()
43
+ pending_station(NULL)
44
+ cur_pend
45
+ } else {
46
+ pending_station()
47
+ }
48
+ } else if (is_valid_str(active_station_name())) {
49
+ active_station_name()
50
+ } else {
51
+ "All"
52
  }
53
 
54
+ cntry <- if (is_valid_str(active_country())) {
55
+ active_country()
56
+ } else if (is_valid_str(input$country)) {
57
+ input$country
58
+ } else {
59
+ "All"
 
60
  }
61
 
62
+ tab_val <- if (!is.null(tab_override)) {
63
+ tab_override
64
+ } else if (!is_valid_str(active_station_name()) && identical(input$main_nav, "Dashboard")) {
65
+ "Map View"
66
+ } else if (is_valid_str(input$main_nav)) {
67
+ input$main_nav
68
+ } else {
69
+ "Map View"
70
+ }
71
 
72
  session$sendCustomMessage("updateParentURL", list(
73
+ parameter = param,
74
+ time_period = time_p,
75
  country = cntry,
76
+ station = stn,
77
+ tab = tab_val
78
  ))
79
+ }
80
+
81
+ observe({
82
+ broadcast_parent_url()
83
  })
84
 
85
  # Base dataset dependent on the selected parameter
86
  active_dataset <- reactive({
87
  param <- input$parameter
88
+ if (!is_valid_str(param)) param <- "TAVG"
89
+ if (identical(param, "TAVG") && exists("tavg_sf")) return(tavg_sf)
90
+ if (identical(param, "TMAX") && exists("tmax_sf")) return(tmax_sf)
91
+ if (identical(param, "TMIN") && exists("tmin_sf")) return(tmin_sf)
92
+ if (identical(param, "PRCP") && exists("prcp_sf")) return(prcp_sf)
93
+ if (identical(param, "MSLP") && exists("mslp_sf")) return(mslp_sf)
94
+ if (identical(param, "MNVP") && exists("mnvp_sf")) return(mnvp_sf)
95
+ if (identical(param, "DP01") && exists("dp01_sf")) return(dp01_sf)
96
+ if (identical(param, "TSUN") && exists("tsun_sf")) return(tsun_sf)
97
  return(NULL)
98
  })
99
 
 
101
  filtered_stations_by_country <- reactive({
102
  req(active_dataset())
103
  stations_sf <- active_dataset()
104
+ cntry <- input$country
105
+ if (!is_valid_str(cntry) || identical(cntry, "All")) {
106
  stations_sf
107
  } else {
108
+ stations_sf %>% filter(Country == cntry)
109
  }
110
  })
111
 
112
+ # Update Station choices based on selected Country or Parameter
113
+ observeEvent(list(input$country, input$parameter), {
114
  if (!is.null(pending_country())) {
115
  if (!(pending_country() %in% countries_list)) {
116
  pending_country(NULL)
117
+ } else if (!identical(input$country, pending_country())) {
118
  return()
119
  } else {
120
  pending_country(NULL)
 
123
 
124
  filtered_data <- filtered_stations_by_country()
125
 
126
+ station_choices <- if (!is.null(filtered_data) && nrow(filtered_data) > 0) {
127
+ c("All Stations" = "All", unique(sort(filtered_data$Station_Name)))
128
+ } else {
129
+ c("All Stations" = "All")
130
+ }
131
+
132
+ sel <- if (!is.null(pending_station())) {
133
+ pending_station()
134
+ } else if (!is.null(active_station_name()) && active_station_name() %in% station_choices) {
135
+ active_station_name()
136
+ } else {
137
+ "All"
138
  }
139
+
140
+ updateSelectizeInput(session, "station", choices = station_choices, selected = sel, server = FALSE)
141
  }, ignoreInit = FALSE)
142
 
143
+ # Final reactive dataset based on both filters a user selects
144
+ final_filtered_stations <- reactive({
145
+ data <- filtered_stations_by_country()
146
+ req(!is.null(data))
147
+ data
148
+ })
149
+
150
+ # Selected Station Metadata Reactive
151
+ selected_station_meta <- reactive({
152
+ wmo <- clicked_wmo_id()
153
+ stn_name <- active_station_name()
154
+ if (!is_valid_str(wmo) && !is_valid_str(stn_name)) return(NULL)
155
+
156
+ candidate_dfs <- list(
157
+ active_dataset(),
158
+ if (exists("tavg_sf")) tavg_sf else NULL,
159
+ if (exists("prcp_sf")) prcp_sf else NULL,
160
+ if (exists("tmax_sf")) tmax_sf else NULL,
161
+ if (exists("tmin_sf")) tmin_sf else NULL,
162
+ if (exists("mslp_sf")) mslp_sf else NULL,
163
+ if (exists("mnvp_sf")) mnvp_sf else NULL,
164
+ if (exists("dp01_sf")) dp01_sf else NULL,
165
+ if (exists("tsun_sf")) tsun_sf else NULL
166
+ )
167
+ for (cdf in candidate_dfs) {
168
+ if (!is.null(cdf) && inherits(cdf, "sf") && nrow(cdf) > 0) {
169
+ # Try exact match on both Station_Name and WMO_ID first
170
+ if (is_valid_str(stn_name) && is_valid_str(wmo)) {
171
+ idx <- which(!is.na(cdf$WMO_ID) & !is.na(cdf$Station_Name) & as.character(cdf$WMO_ID) == as.character(wmo) & as.character(cdf$Station_Name) == as.character(stn_name))
172
+ if (length(idx) > 0) return(sf::st_drop_geometry(cdf[idx[1], ]))
173
+ }
174
+ # Fall back to Station_Name if available
175
+ if (is_valid_str(stn_name)) {
176
+ idx <- which(!is.na(cdf$Station_Name) & as.character(cdf$Station_Name) == as.character(stn_name))
177
+ if (length(idx) > 0) return(sf::st_drop_geometry(cdf[idx[1], ]))
178
+ }
179
+ # Fall back to WMO_ID
180
+ if (is_valid_str(wmo)) {
181
+ idx <- which(!is.na(cdf$WMO_ID) & as.character(cdf$WMO_ID) == as.character(wmo))
182
+ if (length(idx) > 0) return(sf::st_drop_geometry(cdf[idx[1], ]))
183
+ }
184
+ }
185
+ }
186
+
187
+ # Fallback dataframe if station was clicked/selected but not found in sf composites
188
+ if (is_valid_str(stn_name) || is_valid_str(wmo)) {
189
+ return(data.frame(
190
+ Station_Name = if (is_valid_str(stn_name)) stn_name else as.character(wmo),
191
+ WMO_ID = if (is_valid_str(wmo)) as.character(wmo) else "",
192
+ Country = if (is_valid_str(active_country())) active_country() else "",
193
+ Elevation = if (!is.null(active_elevation())) suppressWarnings(as.numeric(active_elevation())) else NA,
194
+ Longitude = NA,
195
+ Latitude = NA,
196
+ stringsAsFactors = FALSE
197
+ ))
198
+ }
199
+ return(NULL)
200
+ })
201
+
202
+ # Helper: Highlight Station on Map
203
+ highlight_station <- function(proxy, lon, lat, move_map = TRUE) {
204
+ proxy %>% mapgl::clear_layer("selected_highlight")
205
+
206
+ if (is.null(lon) || is.null(lat) || length(lon) == 0 || length(lat) == 0 || is.na(lon[1]) || is.na(lat[1])) {
207
+ return(proxy)
208
+ }
209
+ num_lon <- suppressWarnings(as.numeric(lon[1]))
210
+ num_lat <- suppressWarnings(as.numeric(lat[1]))
211
+ if (is.na(num_lon) || is.na(num_lat)) {
212
+ return(proxy)
213
+ }
214
+
215
+ hl_pt <- sf::st_as_sf(
216
+ data.frame(x = num_lon, y = num_lat),
217
+ coords = c("x", "y"),
218
+ crs = 4326
219
+ )
220
+
221
+ proxy <- proxy %>%
222
+ mapgl::add_circle_layer(
223
+ id = "selected_highlight",
224
+ source = hl_pt,
225
+ circle_color = "red",
226
+ circle_radius = 12,
227
+ circle_stroke_color = "white",
228
+ circle_stroke_width = 2,
229
+ circle_opacity = 0.4
230
+ )
231
+
232
+ if (isTRUE(move_map)) {
233
+ proxy <- proxy %>% mapgl::fly_to(center = c(num_lon, num_lat), zoom = 8)
234
+ }
235
+ proxy
236
+ }
237
+
238
+ # Centralized Deselection Logic
239
+ clear_station_selection <- function(jump_to_map = TRUE) {
240
+ was_selected <- !is.null(clicked_wmo_id()) || !is.null(active_station_name()) || (is_valid_str(input$station) && !identical(input$station, "All"))
241
+
242
+ clicked_wmo_id(NULL)
243
  active_station_name(NULL)
244
  active_country(NULL)
245
+ active_elevation(NULL)
246
+
247
+ if (!identical(input$station, "All")) {
248
+ updateSelectizeInput(session, "station", selected = "All")
249
+ }
250
+
251
+ # When deselecting a station while on Dashboard, jump to Map View
252
+ curr_tab <- isolate(input$main_nav)
253
+ new_tab <- if (isTRUE(jump_to_map) && is_valid_str(curr_tab) && identical(curr_tab, "Dashboard")) {
254
+ bslib::nav_select("main_nav", "Map View")
255
+ "Map View"
256
+ } else if (is_valid_str(curr_tab)) {
257
+ curr_tab
258
+ } else {
259
+ "Map View"
260
+ }
261
+
262
+ proxy <- mapgl::maplibre_proxy("station_map")
263
+ proxy %>% mapgl::clear_layer("selected_highlight")
264
+
265
+ # Only re-center / fit bounds if a station was actively selected
266
+ if (isTRUE(was_selected)) {
267
+ cntry <- isolate(input$country)
268
+ if (is_valid_str(cntry) && !identical(cntry, "All")) {
269
+ country_sel <- filtered_stations_by_country()
270
+ if (!is.null(country_sel) && nrow(country_sel) > 0) {
271
+ proxy %>% mapgl::fit_bounds(country_sel, padding = 100, animate = TRUE, maxZoom = 8, max_zoom = 8)
272
+ } else {
273
+ proxy %>% mapgl::fly_to(center = c(initial_lng, initial_lat), zoom = initial_zoom)
274
+ }
275
+ } else {
276
+ proxy %>% mapgl::fly_to(center = c(initial_lng, initial_lat), zoom = initial_zoom)
277
+ }
278
+ }
279
+
280
+ # Trigger map resize after tab transition
281
+ session$sendCustomMessage("resizeMap", list())
282
+
283
+ # Broadcast state to parent immediately to prevent any stale station leak
284
+ broadcast_parent_url(tab_override = new_tab)
285
+ }
286
+
287
+ # Station Selection Helper
288
+ select_station_helper <- function(station_row, move_map = TRUE) {
289
+ if (is.null(station_row) || nrow(station_row) == 0) return()
290
+
291
+ click_id <- station_row$WMO_ID[1]
292
+ stn_name <- station_row$Station_Name[1]
293
+ stn_country <- station_row$Country[1]
294
+ sta_lon <- station_row$Longitude[1]
295
+ sta_lat <- station_row$Latitude[1]
296
+ sta_elev <- if ("Elevation" %in% names(station_row) && !is.null(station_row$Elevation)) station_row$Elevation[1] else NULL
297
+
298
+ clicked_wmo_id(click_id)
299
+ active_station_name(stn_name)
300
+ active_country(stn_country)
301
+ active_elevation(sta_elev)
302
+
303
+ if (is_valid_str(input$country) && !identical(input$country, "All") && !identical(input$country, stn_country)) {
304
+ skip_country_clear(TRUE)
305
+ updateSelectInput(session, "country", selected = "All")
306
+ }
307
+
308
+ if (!identical(input$station, stn_name)) {
309
+ current_data <- final_filtered_stations()
310
+ base_choices <- if (!is.null(current_data) && nrow(current_data) > 0) current_data$Station_Name else character(0)
311
+ station_choices <- c("All Stations" = "All", unique(sort(c(base_choices, stn_name))))
312
+ updateSelectizeInput(session, "station", choices = station_choices, selected = stn_name, server = FALSE)
313
+ }
314
+
315
+ highlight_station(mapgl::maplibre_proxy("station_map"), sta_lon, sta_lat, move_map = move_map)
316
+ bslib::nav_select("main_nav", "Dashboard")
317
+ broadcast_parent_url(tab_override = "Dashboard")
318
+ }
319
+
320
+ # Deselection Observers (Sidebar Button, Floating Chip, Escape Key)
321
+ observeEvent(input$clear_station_sidebar, {
322
+ clear_station_selection(jump_to_map = TRUE)
323
+ })
324
+
325
+ observeEvent(input$clear_station_chip, {
326
+ clear_station_selection(jump_to_map = TRUE)
327
+ })
328
+
329
+ observeEvent(input$esc_clear_station, {
330
+ clear_station_selection(jump_to_map = TRUE)
331
+ })
332
+
333
+ # Station Dropdown Selection Observer
334
+ observeEvent(input$station, {
335
+ stn <- input$station
336
+ if (is_valid_str(stn) && !identical(stn, "All")) {
337
+ if (!identical(active_station_name(), stn)) {
338
+ data <- final_filtered_stations()
339
+ if (!is.null(data) && nrow(data) > 0) {
340
+ target_station <- data %>% filter(Station_Name == stn)
341
+ if (nrow(target_station) > 0) {
342
+ select_station_helper(target_station[1, ], move_map = TRUE)
343
+ }
344
+ }
345
+ }
346
+ } else if (identical(stn, "All")) {
347
+ if (!is.null(clicked_wmo_id()) || !is.null(active_station_name())) {
348
+ clear_station_selection(jump_to_map = TRUE)
349
+ }
350
+ }
351
+ }, ignoreInit = TRUE)
352
+
353
+ # Station Chip UI Overlay on Map View
354
+ output$station_chip_ui <- renderUI({
355
+ meta <- selected_station_meta()
356
+ if (is.null(meta)) return(NULL)
357
+
358
+ elev_num <- if (!is.null(meta$Elevation)) suppressWarnings(as.numeric(meta$Elevation[[1]])) else NA
359
+ elev_val <- if (!is.null(elev_num) && length(elev_num) > 0 && !is.na(elev_num) && elev_num > -500) {
360
+ paste0(" (", round(elev_num, 0), " m)")
361
+ } else {
362
+ ""
363
+ }
364
+ stn_name_str <- if (!is.null(meta$Station_Name) && length(meta$Station_Name) > 0 && !is.na(meta$Station_Name[[1]])) {
365
+ enc2utf8(as.character(meta$Station_Name[[1]]))
366
+ } else {
367
+ "Station"
368
+ }
369
+ wmo_id_str <- if (!is.null(meta$WMO_ID) && length(meta$WMO_ID) > 0 && !is.na(meta$WMO_ID[[1]])) {
370
+ as.character(meta$WMO_ID[[1]])
371
+ } else {
372
+ ""
373
+ }
374
+ chip_label <- if (nzchar(wmo_id_str)) {
375
+ paste0(stn_name_str, " - ", wmo_id_str, elev_val)
376
+ } else {
377
+ paste0(stn_name_str, elev_val)
378
+ }
379
+
380
+ tags$div(
381
+ class = "station-floating-chip",
382
+ tags$span(class = "chip-dot"),
383
+ tags$span(class = "chip-text", title = chip_label, chip_label),
384
+ tags$button(
385
+ type = "button",
386
+ class = "btn-chip-clear",
387
+ `aria-label` = "Deselect active station",
388
+ onclick = "event.stopPropagation(); Shiny.setInputValue('clear_station_chip', Date.now(), {priority: 'event'});",
389
+ tags$span("Deselect ", tags$kbd(class = "chip-kbd", "Esc"))
390
+ )
391
+ )
392
+ })
393
+ outputOptions(output, "station_chip_ui", suspendWhenHidden = FALSE)
394
+
395
+
396
+ # Deselect and jump back to Map View when a user changes the country filter
397
+ observeEvent(input$country, {
398
+ if (isTRUE(skip_country_clear())) {
399
+ skip_country_clear(FALSE)
400
+ return()
401
+ }
402
+ clear_station_selection(jump_to_map = TRUE)
403
  }, ignoreInit = TRUE)
404
 
405
  # Jump back to Map View when parameter or time period changes while on Dashboard
406
  observeEvent(input$parameter, {
407
  if (identical(input$main_nav, "Dashboard")) {
408
+ clear_station_selection(jump_to_map = TRUE)
 
 
409
  }
410
  }, ignoreInit = TRUE)
411
 
412
  observeEvent(input$time_period, {
413
  if (identical(input$main_nav, "Dashboard")) {
414
+ clear_station_selection(jump_to_map = TRUE)
 
 
415
  }
416
  }, ignoreInit = TRUE)
417
+
 
 
 
 
 
 
 
 
 
 
418
  initial_zoom <- 3
419
 
420
  # Reactive values for map state
 
435
 
436
  # Initialize map bounds / Home Zoom
437
  observeEvent(input$home_zoom, {
438
+ if (!is.null(clicked_wmo_id()) || !is.null(active_station_name())) {
439
+ clear_station_selection(jump_to_map = FALSE)
440
+ } else {
441
+ cntry <- input$country
442
+ if (is_valid_str(cntry) && !identical(cntry, "All")) {
443
+ country_sel <- filtered_stations_by_country()
444
+ if (!is.null(country_sel) && nrow(country_sel) > 0) {
445
+ maplibre_proxy("station_map") %>% fit_bounds(country_sel, padding = 100, animate = TRUE, maxZoom = 8, max_zoom = 8)
446
+ } else {
447
+ maplibre_proxy("station_map") %>% fly_to(center = c(initial_lng, initial_lat), zoom = initial_zoom)
448
+ }
449
  } else {
450
+ maplibre_proxy("station_map") %>%
451
+ fly_to(center = c(initial_lng, initial_lat), zoom = initial_zoom)
452
  }
 
 
 
453
  }
454
  })
455
 
 
683
  before_id = isolate(stations_before_id())
684
  )
685
 
686
+ # Maintain highlight layer if a station is selected
687
+ stn_active <- active_station_name()
688
+ wmo_active <- clicked_wmo_id()
689
+ if (!is_valid_str(stn_active) && is_valid_str(input$station) && !identical(input$station, "All")) {
690
+ stn_active <- input$station
691
+ }
692
+ if (is_valid_str(stn_active) || is_valid_str(wmo_active)) {
693
+ target_station <- NULL
694
+ if (is_valid_str(stn_active) && is_valid_str(wmo_active)) {
695
+ matches <- data %>% filter(WMO_ID == wmo_active & Station_Name == stn_active)
696
+ if (nrow(matches) > 0) target_station <- matches[1, ]
697
+ }
698
+ if (is.null(target_station) && is_valid_str(stn_active)) {
699
+ matches <- data %>% filter(Station_Name == stn_active)
700
+ if (nrow(matches) > 0) target_station <- matches[1, ]
701
+ }
702
+ if (is.null(target_station) && is_valid_str(wmo_active)) {
703
+ matches <- data %>% filter(WMO_ID == wmo_active)
704
+ if (nrow(matches) > 0) target_station <- matches[1, ]
705
+ }
706
+ if (!is.null(target_station) && nrow(target_station) > 0) {
707
+ highlight_station(map, target_station$Longitude[1], target_station$Latitude[1], move_map = FALSE)
708
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
709
  } else {
710
+ map %>% clear_layer("selected_highlight")
 
711
  }
712
  } else {
713
  map %>% clear_layer("wmo_stations")
 
719
  # -----------------------------------------------------------------------------------
720
  # Dashboard Interaction & Reactivity
721
  # -----------------------------------------------------------------------------------
 
 
 
722
 
723
  observeEvent(input$station_map_feature_click, {
724
  clicked <- input$station_map_feature_click
 
730
 
731
  # If the user clicks the highlight, take them to the Dashboard (fallback)
732
  if (layer_id == "selected_highlight") {
733
+ bslib::nav_select("main_nav", "Dashboard")
734
  return()
735
  }
736
 
737
  # If the user clicks a station, highlight it, zoom, AND go to dashboard
738
  if (layer_id == "wmo_stations") {
739
  props <- clicked$properties
 
740
  click_id <- if (!is.null(props$WMO_ID)) props$WMO_ID else props$wmo_id
741
+ stn_prop <- if (!is.null(props$Station_Name)) props$Station_Name else NULL
742
 
743
+ if (!is.null(click_id) || !is.null(stn_prop)) {
744
+ data <- final_filtered_stations()
745
+ target_station <- NULL
746
+ if (!is.null(data) && nrow(data) > 0) {
747
+ if (is_valid_str(stn_prop) && !is.null(click_id)) {
748
+ matches <- data %>% filter(WMO_ID == click_id & Station_Name == stn_prop)
749
+ if (nrow(matches) > 0) target_station <- matches[1, ]
750
+ }
751
+ if (is.null(target_station) && is_valid_str(stn_prop)) {
752
+ matches <- data %>% filter(Station_Name == stn_prop)
753
+ if (nrow(matches) > 0) target_station <- matches[1, ]
754
+ }
755
+ if (is.null(target_station) && !is.null(click_id)) {
756
+ matches <- data %>% filter(WMO_ID == click_id)
757
+ if (nrow(matches) > 0) target_station <- matches[1, ]
758
+ }
759
+ }
 
 
 
 
 
 
 
 
 
 
 
 
760
 
761
+ if (!is.null(target_station)) {
762
+ select_station_helper(target_station, move_map = TRUE)
763
+ } else {
764
+ stn_name <- if (!is.null(props$Station_Name)) props$Station_Name else as.character(click_id)
765
+ stn_country <- if (!is.null(props$Country)) props$Country else ""
766
+ sta_lon <- if (!is.null(props$Longitude)) as.numeric(props$Longitude) else clicked$lng
767
+ sta_lat <- if (!is.null(props$Latitude)) as.numeric(props$Latitude) else clicked$lat
768
+ sta_elev <- if (!is.null(props$Elevation)) suppressWarnings(as.numeric(props$Elevation)) else NA
769
+
770
+ fallback_row <- data.frame(
771
+ WMO_ID = if (!is.null(click_id)) as.character(click_id) else "",
772
+ Station_Name = as.character(stn_name),
773
+ Country = as.character(stn_country),
774
+ Elevation = if (!is.na(sta_elev)) sta_elev else NA_real_,
775
+ Longitude = as.numeric(sta_lon),
776
+ Latitude = as.numeric(sta_lat),
777
+ stringsAsFactors = FALSE
778
+ )
779
+ select_station_helper(fallback_row, move_map = TRUE)
780
+ }
781
  }
782
  }
783
  })
 
785
  # Render Station Metadata Header mimicking GHCNM
786
  output$dashboard_header <- renderUI({
787
  wmo <- clicked_wmo_id()
788
+ stn <- active_station_name()
789
+ if (!is_valid_str(wmo) && !is_valid_str(stn)) {
790
  return(h4(class="text-muted", "Please click a station on the interactive map to view its complete Normal arrays."))
791
  }
792
 
793
  # Fetch top-level metadata from TAVG, else fallback to PRCP
794
+ find_station_meta <- function(df_sf) {
795
+ if (!inherits(df_sf, "sf") || nrow(df_sf) == 0) return(data.frame())
796
+ df <- st_drop_geometry(df_sf)
797
+ if (is_valid_str(stn) && is_valid_str(wmo)) {
798
+ r <- df %>% filter(WMO_ID == wmo & Station_Name == stn)
799
+ if (nrow(r) > 0) return(r[1, ])
800
+ }
801
+ if (is_valid_str(stn)) {
802
+ r <- df %>% filter(Station_Name == stn)
803
+ if (nrow(r) > 0) return(r[1, ])
804
+ }
805
+ if (is_valid_str(wmo)) {
806
+ r <- df %>% filter(WMO_ID == wmo)
807
+ if (nrow(r) > 0) return(r[1, ])
808
+ }
809
+ data.frame()
810
  }
811
+ meta_df <- find_station_meta(if (exists("tavg_sf")) tavg_sf else NULL)
812
+ if (nrow(meta_df) == 0) meta_df <- find_station_meta(if (exists("prcp_sf")) prcp_sf else NULL)
813
 
814
  if (nrow(meta_df) > 0) {
815
  station_name <- meta_df$Station_Name[1]
 
863
 
864
  # Cross-Dataset Extraction
865
  station_dashboard_data <- reactive({
866
+ req(is_valid_str(clicked_wmo_id()) || is_valid_str(active_station_name()))
867
  sid <- clicked_wmo_id()
868
+ stn <- active_station_name()
869
 
870
  extract_param <- function(df_sf, param_name) {
871
  if(is.null(df_sf) || inherits(df_sf, "sfc") || nrow(df_sf) == 0) return(NULL)
872
  df <- st_drop_geometry(df_sf)
873
+ row <- if (is_valid_str(stn) && is_valid_str(sid)) {
874
+ r <- df %>% filter(WMO_ID == sid & Station_Name == stn)
875
+ if (nrow(r) > 0) r else {
876
+ r_stn <- df %>% filter(Station_Name == stn)
877
+ if (nrow(r_stn) > 0) r_stn else df %>% filter(WMO_ID == sid)
878
+ }
879
+ } else if (is_valid_str(stn)) {
880
+ df %>% filter(Station_Name == stn)
881
+ } else {
882
+ df %>% filter(WMO_ID == sid)
883
+ }
884
  if(nrow(row) == 0) return(NULL)
885
 
886
  res <- data.frame(Parameter = param_name, stringsAsFactors = FALSE)
 
964
  req(df)
965
 
966
  wmo <- clicked_wmo_id()
967
+ stn <- active_station_name()
968
 
969
+ find_name <- function(df_sf) {
970
+ if (!inherits(df_sf, "sf") || nrow(df_sf) == 0) return(NULL)
971
+ d <- st_drop_geometry(df_sf)
972
+ if (is_valid_str(stn) && is_valid_str(wmo)) {
973
+ r <- d %>% filter(WMO_ID == wmo & Station_Name == stn)
974
+ if (nrow(r) > 0) return(r$Station_Name[1])
975
+ }
976
+ if (is_valid_str(stn)) {
977
+ r <- d %>% filter(Station_Name == stn)
978
+ if (nrow(r) > 0) return(r$Station_Name[1])
979
+ }
980
+ if (is_valid_str(wmo)) {
981
+ r <- d %>% filter(WMO_ID == wmo)
982
+ if (nrow(r) > 0) return(r$Station_Name[1])
983
+ }
984
+ NULL
985
+ }
986
+ s_name <- if (is_valid_str(stn)) {
987
+ stn
988
+ } else {
989
+ n <- find_name(if (exists("tavg_sf")) tavg_sf else NULL)
990
+ if (is.null(n)) n <- find_name(if (exists("prcp_sf")) prcp_sf else NULL)
991
+ if (!is.null(n)) n else as.character(wmo)
992
  }
 
993
 
994
  render_station_plots(df, s_name)
995
  })
tests/test_station_deselection.R ADDED
@@ -0,0 +1,602 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # tests/test_station_deselection.R
2
+ # Comprehensive programmatic test suite for station deselection and view jumping behavior
3
+
4
+ suppressPackageStartupMessages({
5
+ library(testthat)
6
+ library(shiny)
7
+ library(bslib)
8
+ library(sf)
9
+ library(dplyr)
10
+ })
11
+
12
+ cat("=================================================================\n")
13
+ cat("Starting WMO Normals Station Deselection Verification Suite\n")
14
+ cat("=================================================================\n\n")
15
+
16
+ # Load application global environment
17
+ source("global.R")
18
+
19
+ # Mock get_dataset_status to prevent network hang in automated testing
20
+ get_dataset_status <- function() {
21
+ list(local_date = Sys.Date(), online_date = Sys.Date(), status = "Up-to-date", error = NULL, cached = TRUE)
22
+ }
23
+
24
+ test_that("1. Static Code and Asset Integrity Checks", {
25
+ cat("[TEST] Checking UI component definitions and asset files...\n")
26
+
27
+ # Check ui.R
28
+ ui_content <- readLines("ui.R", warn = FALSE)
29
+ ui_str <- paste(ui_content, collapse = "\n")
30
+
31
+ expect_true(grepl("clear_station_sidebar", ui_str), info = "clear_station_sidebar must be present in ui.R")
32
+ expect_true(grepl("station_chip_ui", ui_str), info = "station_chip_ui must be present in ui.R")
33
+ expect_true(grepl("station_chip_panel", ui_str), info = "station_chip_panel must be present in ui.R")
34
+
35
+ # Check server.R
36
+ server_content <- readLines("server.R", warn = FALSE)
37
+ server_str <- paste(server_content, collapse = "\n")
38
+
39
+ expect_true(grepl("clear_station_sidebar", server_str), info = "clear_station_sidebar observer must be in server.R")
40
+ expect_true(grepl("clear_station_chip", server_str), info = "clear_station_chip observer must be in server.R")
41
+ expect_true(grepl("esc_clear_station", server_str), info = "esc_clear_station observer must be in server.R")
42
+ expect_true(grepl("clear_station_selection", server_str), info = "clear_station_selection function must be in server.R")
43
+ expect_true(grepl("output\\$station_chip_ui", server_str), info = "output$station_chip_ui must be defined in server.R")
44
+ expect_true(grepl("active_country\\(NULL\\)", server_str), info = "active_country(NULL) must be called upon deselection")
45
+ expect_true(grepl("active_elevation\\(NULL\\)", server_str), info = "active_elevation(NULL) must be called upon deselection")
46
+ expect_true(grepl("maxZoom", server_str), info = "fit_bounds MapLibre camelCase maxZoom option must be set")
47
+ expect_true(grepl("max_zoom", server_str), info = "fit_bounds max_zoom guardrail must be set")
48
+
49
+ # Check www/app.js
50
+ app_js <- paste(readLines("www/app.js", warn = FALSE), collapse = "\n")
51
+ expect_true(grepl("esc_clear_station", app_js), info = "esc_clear_station event dispatch must exist in app.js")
52
+ expect_true(grepl("Escape", app_js) || grepl("27", app_js), info = "Escape key listener must exist in app.js")
53
+ expect_true(grepl("resizeMap", app_js), info = "resizeMap handler must exist in app.js")
54
+ expect_true(grepl("triggerMapResize", app_js), info = "triggerMapResize helper must exist in app.js")
55
+ expect_true(grepl("registerShinyHandler", app_js), info = "registerShinyHandler helper must exist in app.js")
56
+
57
+ # Check www/custom.css
58
+ css <- paste(readLines("www/custom.css", warn = FALSE), collapse = "\n")
59
+ expect_true(grepl("\\.station-floating-chip", css), info = ".station-floating-chip CSS rule must exist in custom.css")
60
+ expect_true(grepl("\\.chip-dot", css), info = ".chip-dot CSS rule must exist in custom.css")
61
+ expect_true(grepl("\\.btn-chip-clear", css), info = ".btn-chip-clear CSS rule must exist in custom.css")
62
+ expect_true(grepl("\\.sidebar-station-clear-btn", css), info = ".sidebar-station-clear-btn CSS rule must exist in custom.css")
63
+
64
+ # Check R syntax
65
+ expect_no_error(parse("ui.R"))
66
+ expect_no_error(parse("server.R"))
67
+ expect_no_error(parse("global.R"))
68
+
69
+ cat(" -> All static component, JS, CSS, and syntax checks passed.\n")
70
+ })
71
+
72
+ test_that("2. Reactive Server Deselection and Jumping Behavior", {
73
+ cat("[TEST] Executing testServer reactive behavioral verification...\n")
74
+ source("server.R")
75
+
76
+ testServer(server, {
77
+ # Set up message spying on session
78
+ input_messages <- list()
79
+ custom_messages <- list()
80
+ orig_sendInputMessage <- session$sendInputMessage
81
+ orig_sendCustomMessage <- session$sendCustomMessage
82
+ session$sendInputMessage <- function(inputId, message) {
83
+ input_messages <<- c(input_messages, list(list(id = inputId, message = message)))
84
+ orig_sendInputMessage(inputId, message)
85
+ }
86
+ session$sendCustomMessage <- function(type, message) {
87
+ custom_messages <<- c(custom_messages, list(list(type = type, message = message)))
88
+ orig_sendCustomMessage(type, message)
89
+ }
90
+ clear_spies <- function() {
91
+ input_messages <<- list()
92
+ custom_messages <<- list()
93
+ }
94
+ has_nav_to_map <- function() {
95
+ any(sapply(input_messages, function(m) identical(m$id, "main_nav") && identical(m$message$value, "Map View")))
96
+ }
97
+ has_resize_map <- function() {
98
+ any(sapply(custom_messages, function(m) identical(m$type, "resizeMap")))
99
+ }
100
+
101
+ # -------------------------------------------------------------
102
+ # 2.1 Initial Startup State
103
+ # -------------------------------------------------------------
104
+ expect_null(clicked_wmo_id(), "Initially clicked_wmo_id must be NULL")
105
+ expect_null(active_station_name(), "Initially active_station_name must be NULL")
106
+ expect_null(active_country(), "Initially active_country must be NULL")
107
+ expect_null(output$station_chip_ui, "Initially station_chip_ui must be NULL")
108
+
109
+ # -------------------------------------------------------------
110
+ # 2.2 Select Station via Dropdown
111
+ # -------------------------------------------------------------
112
+ # Pick a known station in Algeria ("Adrar", WMO_ID: 60620)
113
+ session$setInputs(
114
+ parameter = "TAVG",
115
+ time_period = "Annual",
116
+ country = "Algeria",
117
+ main_nav = "Map View"
118
+ )
119
+ session$setInputs(station = "Adrar")
120
+
121
+ expect_equal(active_station_name(), "Adrar")
122
+ expect_false(is.null(clicked_wmo_id()), "clicked_wmo_id must be set when station selected")
123
+ expect_equal(as.character(clicked_wmo_id()), "60620")
124
+ expect_equal(active_country(), "Algeria")
125
+
126
+ # Check station chip output
127
+ chip_html <- paste(as.character(output$station_chip_ui), collapse = " ")
128
+ expect_true(grepl("Adrar", chip_html), info = "Station chip must contain station name")
129
+ expect_true(grepl("60620", chip_html), info = "Station chip must contain station WMO ID")
130
+ expect_true(grepl("station-floating-chip", chip_html), info = "Station chip must use .station-floating-chip class")
131
+ expect_true(grepl("btn-chip-clear", chip_html), info = "Station chip must have .btn-chip-clear button")
132
+ expect_true(grepl('type="button"', chip_html), info = "Station chip button must have explicit type='button'")
133
+ expect_true(grepl('aria-label=', chip_html), info = "Station chip button must have aria-label")
134
+
135
+ # -------------------------------------------------------------
136
+ # 2.3 Pathway 1: Deselect via Sidebar Button (clear_station_sidebar)
137
+ # -------------------------------------------------------------
138
+ session$setInputs(main_nav = "Dashboard")
139
+ clear_spies()
140
+ session$setInputs(clear_station_sidebar = 1)
141
+
142
+ expect_null(clicked_wmo_id(), "Sidebar deselect must reset clicked_wmo_id to NULL")
143
+ expect_null(active_station_name(), "Sidebar deselect must reset active_station_name to NULL")
144
+ expect_null(active_country(), "Sidebar deselect must reset active_country to NULL")
145
+ expect_null(output$station_chip_ui, "Sidebar deselect must hide station chip")
146
+ expect_true(has_nav_to_map(), "Sidebar deselect while on Dashboard must navigate to Map View")
147
+ expect_true(has_resize_map(), "Sidebar deselect must dispatch resizeMap")
148
+
149
+ # -------------------------------------------------------------
150
+ # 2.4 Pathway 2: Deselect via Floating Map Chip Button (clear_station_chip)
151
+ # -------------------------------------------------------------
152
+ session$setInputs(station = "Adrar")
153
+ expect_equal(as.character(clicked_wmo_id()), "60620")
154
+ expect_false(is.null(output$station_chip_ui))
155
+
156
+ session$setInputs(main_nav = "Dashboard")
157
+ clear_spies()
158
+ session$setInputs(clear_station_chip = 100)
159
+
160
+ expect_null(clicked_wmo_id(), "Chip button deselect must reset clicked_wmo_id to NULL")
161
+ expect_null(active_station_name(), "Chip button deselect must reset active_station_name to NULL")
162
+ expect_null(active_country(), "Chip button deselect must reset active_country to NULL")
163
+ expect_null(output$station_chip_ui, "Chip button deselect must hide station chip")
164
+ expect_true(has_nav_to_map(), "Chip button deselect while on Dashboard must navigate to Map View")
165
+ expect_true(has_resize_map(), "Chip button deselect must dispatch resizeMap")
166
+
167
+ # -------------------------------------------------------------
168
+ # 2.5 Pathway 3: Deselect via Escape Key (esc_clear_station)
169
+ # -------------------------------------------------------------
170
+ session$setInputs(station = "Adrar")
171
+ expect_equal(as.character(clicked_wmo_id()), "60620")
172
+
173
+ session$setInputs(main_nav = "Dashboard")
174
+ clear_spies()
175
+ session$setInputs(esc_clear_station = as.numeric(Sys.time()))
176
+
177
+ expect_null(clicked_wmo_id(), "Esc key deselect must reset clicked_wmo_id to NULL")
178
+ expect_null(active_station_name(), "Esc key deselect must reset active_station_name to NULL")
179
+ expect_null(active_country(), "Esc key deselect must reset active_country to NULL")
180
+ expect_null(output$station_chip_ui, "Esc key deselect must hide station chip")
181
+ expect_true(has_nav_to_map(), "Esc key deselect while on Dashboard must navigate to Map View")
182
+ expect_true(has_resize_map(), "Esc key deselect must dispatch resizeMap")
183
+
184
+ # -------------------------------------------------------------
185
+ # 2.6 Pathway 4: Deselect via Dropdown Selection ('All')
186
+ # -------------------------------------------------------------
187
+ session$setInputs(station = "Adrar")
188
+ expect_equal(as.character(clicked_wmo_id()), "60620")
189
+
190
+ session$setInputs(main_nav = "Dashboard")
191
+ clear_spies()
192
+ session$setInputs(station = "All")
193
+
194
+ expect_null(clicked_wmo_id(), "Selecting 'All' in dropdown must execute deselection flow")
195
+ expect_null(active_station_name(), "Selecting 'All' in dropdown must reset active_station_name")
196
+ expect_null(active_country(), "Selecting 'All' in dropdown must reset active_country")
197
+ expect_null(output$station_chip_ui, "Selecting 'All' must hide station chip")
198
+ expect_true(has_nav_to_map(), "Selecting 'All' in dropdown while on Dashboard must navigate to Map View")
199
+ expect_true(has_resize_map(), "Selecting 'All' must dispatch resizeMap")
200
+
201
+ # -------------------------------------------------------------
202
+ # 2.7 Map Feature Click Selection and Deselection
203
+ # -------------------------------------------------------------
204
+ session$setInputs(station_map_feature_click = list(
205
+ layer_id = "wmo_stations",
206
+ properties = list(
207
+ WMO_ID = "60620",
208
+ Station_Name = "Adrar",
209
+ Country = "Algeria",
210
+ Longitude = -0.194,
211
+ Latitude = 27.837
212
+ )
213
+ ))
214
+
215
+ expect_equal(as.character(clicked_wmo_id()), "60620")
216
+ expect_equal(active_station_name(), "Adrar")
217
+ expect_equal(active_country(), "Algeria")
218
+ expect_false(is.null(output$station_chip_ui))
219
+
220
+ # Clean deselection via Esc
221
+ session$setInputs(esc_clear_station = 99999)
222
+ expect_null(clicked_wmo_id())
223
+ expect_null(active_station_name())
224
+ expect_null(active_country())
225
+ expect_null(output$station_chip_ui)
226
+
227
+ # -------------------------------------------------------------
228
+ # 2.8 Country Filter Switch clears active selection
229
+ # -------------------------------------------------------------
230
+ session$setInputs(station = "Adrar")
231
+ expect_equal(as.character(clicked_wmo_id()), "60620")
232
+
233
+ # User manually changing country
234
+ session$setInputs(country = "Albania")
235
+ expect_null(clicked_wmo_id(), "Country change must clear active station selection")
236
+ expect_null(active_station_name())
237
+ expect_null(active_country())
238
+
239
+ # -------------------------------------------------------------
240
+ # 2.9 Programmatic Country Synchronization does NOT cancel selection
241
+ # -------------------------------------------------------------
242
+ # Simulate map click on a station in Albania while country is currently "Algeria"
243
+ session$setInputs(country = "Algeria")
244
+ session$setInputs(station_map_feature_click = list(
245
+ layer_id = "wmo_stations",
246
+ properties = list(
247
+ WMO_ID = "13615",
248
+ Station_Name = "Tirana",
249
+ Country = "Albania",
250
+ Longitude = 19.8,
251
+ Latitude = 41.3
252
+ )
253
+ ))
254
+ expect_equal(as.character(clicked_wmo_id()), "13615")
255
+ # Client echoes back country = "All"
256
+ session$setInputs(country = "All")
257
+ expect_equal(as.character(clicked_wmo_id()), "13615", "Programmatic country update to 'All' must preserve station")
258
+ expect_equal(active_station_name(), "Tirana")
259
+ # Now clean deselect
260
+ session$setInputs(esc_clear_station = 12345)
261
+ expect_null(clicked_wmo_id())
262
+ expect_null(active_station_name())
263
+
264
+ # -------------------------------------------------------------
265
+ # 2.10 Parameter Change while on Dashboard clears selection
266
+ # -------------------------------------------------------------
267
+ session$setInputs(country = "Algeria", station = "Adrar")
268
+ expect_equal(as.character(clicked_wmo_id()), "60620")
269
+ session$setInputs(main_nav = "Dashboard")
270
+ session$setInputs(parameter = "PRCP")
271
+ expect_null(clicked_wmo_id(), "Changing parameter while on Dashboard must clear station")
272
+ expect_null(active_station_name())
273
+ expect_null(active_country())
274
+
275
+ # -------------------------------------------------------------
276
+ # 2.11 Time Period Change while on Dashboard clears selection
277
+ # -------------------------------------------------------------
278
+ session$setInputs(country = "Algeria", station = "Adrar")
279
+ expect_equal(as.character(clicked_wmo_id()), "60620")
280
+ session$setInputs(main_nav = "Dashboard")
281
+ session$setInputs(time_period = "Jan")
282
+ expect_null(clicked_wmo_id(), "Changing time period while on Dashboard must clear station")
283
+ expect_null(active_station_name())
284
+ expect_null(active_country())
285
+
286
+ # -------------------------------------------------------------
287
+ # 2.12 Missing Elevation Guard in Station Chip
288
+ # -------------------------------------------------------------
289
+ # Pick a station with missing elevation (-9999) if available, or simulate
290
+ session$setInputs(station_map_feature_click = list(
291
+ layer_id = "wmo_stations",
292
+ properties = list(
293
+ WMO_ID = "99999",
294
+ Station_Name = "GhostStation",
295
+ Country = "Nowhere",
296
+ Elevation = -9999,
297
+ Longitude = 10,
298
+ Latitude = 20
299
+ )
300
+ ))
301
+ chip_html <- paste(as.character(output$station_chip_ui), collapse = " ")
302
+ expect_false(grepl("-9999 m", chip_html), info = "Floating chip must suppress missing elevation like -9999 m")
303
+ expect_true(grepl("GhostStation", chip_html))
304
+ session$setInputs(esc_clear_station = 54321)
305
+ expect_null(clicked_wmo_id())
306
+
307
+ # -------------------------------------------------------------
308
+ # 2.13 Metadata Resolution across Non-TAVG/Non-PRCP parameters
309
+ # -------------------------------------------------------------
310
+ # Test that selected_station_meta() returns valid metadata for non-TAVG stations
311
+ if (exists("mslp_sf") && nrow(mslp_sf) > 0) {
312
+ mslp_stn <- mslp_sf[1, ]
313
+ session$setInputs(station_map_feature_click = list(
314
+ layer_id = "wmo_stations",
315
+ properties = list(
316
+ WMO_ID = as.character(mslp_stn$WMO_ID[[1]]),
317
+ Station_Name = as.character(mslp_stn$Station_Name[[1]]),
318
+ Country = as.character(mslp_stn$Country[[1]]),
319
+ Longitude = as.numeric(mslp_stn$Longitude[[1]]),
320
+ Latitude = as.numeric(mslp_stn$Latitude[[1]])
321
+ )
322
+ ))
323
+ meta <- selected_station_meta()
324
+ expect_false(is.null(meta), info = "Station meta must resolve for MSLP station")
325
+ expect_equal(as.character(meta$WMO_ID[[1]]), as.character(mslp_stn$WMO_ID[[1]]))
326
+ session$setInputs(esc_clear_station = 777)
327
+ }
328
+
329
+ # -------------------------------------------------------------
330
+ # 2.14 Edge Cases: Empty values, Rapid Esc dispatches, Invalid Events
331
+ # -------------------------------------------------------------
332
+ # Empty string or NULL inputs
333
+ expect_no_error(session$setInputs(station = ""))
334
+ expect_no_error(session$setInputs(station = NULL))
335
+
336
+ # Rapid Esc / Deselect dispatches when already deselected
337
+ expect_no_error(session$setInputs(esc_clear_station = 1))
338
+ expect_no_error(session$setInputs(esc_clear_station = 2))
339
+ expect_no_error(session$setInputs(clear_station_sidebar = 2))
340
+ expect_no_error(session$setInputs(clear_station_chip = 3))
341
+
342
+ # Deselection while on Map View (does not re-navigate to Map View)
343
+ clear_spies()
344
+ session$setInputs(country = "Algeria", station = "Adrar", main_nav = "Map View")
345
+ expect_equal(active_station_name(), "Adrar")
346
+ session$setInputs(esc_clear_station = 4)
347
+ expect_null(clicked_wmo_id())
348
+ expect_false(has_nav_to_map(), "Deselecting while on Map View must not dispatch redundant navigation")
349
+
350
+ # Deselection with country = 'All' (global extent path)
351
+ session$setInputs(country = "All", station = "Adrar", main_nav = "Dashboard")
352
+ session$setInputs(clear_station_sidebar = 5)
353
+ expect_null(clicked_wmo_id())
354
+
355
+ # Map click with invalid or missing layer / properties (must not crash)
356
+ expect_no_error(session$setInputs(station_map_feature_click = list(layer_id = "unknown_layer")))
357
+ expect_no_error(session$setInputs(station_map_feature_click = list(layer_id = "wmo_stations", properties = list())))
358
+ expect_no_error(session$setInputs(station_map_feature_click = list(layer_id = "wmo_stations", properties = list(WMO_ID = NULL))))
359
+
360
+ # Highlight layer click fallback (navigates to Dashboard without crash)
361
+ expect_no_error(session$setInputs(station_map_feature_click = list(layer_id = "selected_highlight")))
362
+
363
+ # Selecting station with special chars or accents
364
+ session$setInputs(country = "All", station = "AinSefra")
365
+ expect_equal(active_station_name(), "AinSefra")
366
+ session$setInputs(station = "All")
367
+ expect_null(clicked_wmo_id())
368
+
369
+ # -------------------------------------------------------------
370
+ # 2.15 Parent URL Synchronization on Deselection (No Stale Leak)
371
+ # -------------------------------------------------------------
372
+ # Select station "Adrar"
373
+ session$setInputs(country = "Algeria", station = "Adrar")
374
+ expect_equal(active_station_name(), "Adrar")
375
+
376
+ # Deselect via sidebar and verify updateParentURL reports station = "All"
377
+ clear_spies()
378
+ session$setInputs(clear_station_sidebar = 101)
379
+ url_msgs <- Filter(function(m) identical(m$type, "updateParentURL"), custom_messages)
380
+ expect_true(length(url_msgs) > 0, info = "updateParentURL must be dispatched upon sidebar deselection")
381
+ latest_url <- url_msgs[[length(url_msgs)]]$message
382
+ expect_equal(latest_url$station, "All", info = "Sidebar deselection must report station = 'All' to parent URL")
383
+ expect_equal(latest_url$tab, "Map View", info = "Sidebar deselection must report tab = 'Map View'")
384
+
385
+ # Re-select "Adrar" and deselect via chip
386
+ session$setInputs(station = "Adrar")
387
+ expect_equal(active_station_name(), "Adrar")
388
+ clear_spies()
389
+ session$setInputs(clear_station_chip = 102)
390
+ url_msgs <- Filter(function(m) identical(m$type, "updateParentURL"), custom_messages)
391
+ expect_true(length(url_msgs) > 0, info = "updateParentURL must be dispatched upon chip deselection")
392
+ expect_equal(url_msgs[[length(url_msgs)]]$message$station, "All", info = "Chip deselection must report station = 'All'")
393
+
394
+ # Re-select "Adrar" and deselect via Esc
395
+ session$setInputs(station = "Adrar")
396
+ expect_equal(active_station_name(), "Adrar")
397
+ clear_spies()
398
+ session$setInputs(esc_clear_station = 103)
399
+ url_msgs <- Filter(function(m) identical(m$type, "updateParentURL"), custom_messages)
400
+ expect_true(length(url_msgs) > 0, info = "updateParentURL must be dispatched upon Esc deselection")
401
+ expect_equal(url_msgs[[length(url_msgs)]]$message$station, "All", info = "Esc deselection must report station = 'All'")
402
+
403
+ # -------------------------------------------------------------
404
+ # 2.16 Disambiguation of Duplicate WMO_ID ('99999999')
405
+ # -------------------------------------------------------------
406
+ # Click BYUMBA_MET in Rwanda (WMO_ID: 99999999, Elev: 2235)
407
+ session$setInputs(country = "Rwanda")
408
+ session$setInputs(station_map_feature_click = list(
409
+ layer_id = "wmo_stations",
410
+ properties = list(
411
+ WMO_ID = "99999999",
412
+ Station_Name = "BYUMBA_MET",
413
+ Country = "Rwanda",
414
+ Elevation = 2235,
415
+ Longitude = 30.05,
416
+ Latitude = -1.6
417
+ )
418
+ ))
419
+ expect_equal(active_station_name(), "BYUMBA_MET", info = "Clicking BYUMBA_MET must select BYUMBA_MET, not BUGARAMA_RIZ")
420
+ meta <- selected_station_meta()
421
+ expect_false(is.null(meta), info = "selected_station_meta must resolve for BYUMBA_MET")
422
+ expect_equal(as.character(meta$Station_Name[[1]]), "BYUMBA_MET")
423
+ elev_val <- as.numeric(meta$Elevation[[1]])
424
+ expect_true(!is.na(elev_val) && elev_val > 2000, info = "Elevation for BYUMBA_MET must be ~2235 m")
425
+
426
+ # Clean deselect
427
+ session$setInputs(esc_clear_station = 104)
428
+ expect_null(clicked_wmo_id())
429
+
430
+ # -------------------------------------------------------------
431
+ # 2.17 Escape when NO station is selected is Safe and Harmless
432
+ # -------------------------------------------------------------
433
+ expect_null(clicked_wmo_id())
434
+ expect_null(active_station_name())
435
+ clear_spies()
436
+ expect_no_error(session$setInputs(esc_clear_station = 999))
437
+ expect_null(clicked_wmo_id())
438
+
439
+ # -------------------------------------------------------------
440
+ # 2.18 Defensive Reactives: NULL / Uninitialized Parameters
441
+ # -------------------------------------------------------------
442
+ expect_no_error({
443
+ d <- active_dataset()
444
+ expect_true(inherits(d, "sf"))
445
+ })
446
+ expect_no_error({
447
+ f <- filtered_stations_by_country()
448
+ expect_true(inherits(f, "sf"))
449
+ })
450
+
451
+ # -------------------------------------------------------------
452
+ # 2.19 Home Zoom with Country Filter & Max Zoom Guard
453
+ # -------------------------------------------------------------
454
+ session$setInputs(country = "Albania")
455
+ expect_no_error(session$setInputs(home_zoom = 1))
456
+ session$setInputs(country = "All")
457
+ expect_no_error(session$setInputs(home_zoom = 2))
458
+
459
+ # -------------------------------------------------------------
460
+ # 2.20 Duplicate Station Name Disambiguation (e.g. Mercedes)
461
+ # -------------------------------------------------------------
462
+ # Click Mercedes in Uruguay (WMO_ID: 86490, Lat: -33.25, Lon: -58.069)
463
+ session$setInputs(station_map_feature_click = list(
464
+ layer_id = "wmo_stations",
465
+ properties = list(
466
+ WMO_ID = "86490",
467
+ Station_Name = "Mercedes",
468
+ Country = "Uruguay",
469
+ Longitude = -58.069,
470
+ Latitude = -33.250
471
+ )
472
+ ))
473
+ expect_equal(active_station_name(), "Mercedes")
474
+ expect_equal(as.character(clicked_wmo_id()), "86490")
475
+ expect_equal(active_country(), "Uruguay")
476
+ meta <- selected_station_meta()
477
+ expect_false(is.null(meta))
478
+ expect_equal(as.character(meta$Country[[1]]), "Uruguay", info = "Must resolve to Uruguay, not Colombia")
479
+ expect_equal(as.character(meta$WMO_ID[[1]]), "86490")
480
+ # Clean deselect
481
+ session$setInputs(esc_clear_station = 501)
482
+ expect_null(clicked_wmo_id())
483
+
484
+ # -------------------------------------------------------------
485
+ # 2.21 Defensive highlight_station Coordinates Handling
486
+ # -------------------------------------------------------------
487
+ # Simulate station click with NA coordinates in properties
488
+ expect_no_error({
489
+ session$setInputs(station_map_feature_click = list(
490
+ layer_id = "wmo_stations",
491
+ properties = list(
492
+ WMO_ID = "99998",
493
+ Station_Name = "MissingCoords",
494
+ Country = "Nowhere",
495
+ Longitude = NA,
496
+ Latitude = NA
497
+ )
498
+ ))
499
+ })
500
+ session$setInputs(esc_clear_station = 502)
501
+ expect_null(clicked_wmo_id())
502
+
503
+ # -------------------------------------------------------------
504
+ # 2.22 broadcast_parent_url Robustness with NULL Inputs
505
+ # -------------------------------------------------------------
506
+ expect_no_error({
507
+ session$setInputs(parameter = NULL)
508
+ session$setInputs(time_period = NULL)
509
+ clear_station_selection(jump_to_map = FALSE)
510
+ })
511
+ # Restore standard inputs
512
+ session$setInputs(parameter = "TAVG", time_period = "Annual", country = "All")
513
+
514
+ # -------------------------------------------------------------
515
+ # 2.23 Station State Synchronization across Select and Deselect
516
+ # -------------------------------------------------------------
517
+ expect_null(active_station_name())
518
+ session$setInputs(country = "Algeria", station = "Adrar")
519
+ expect_equal(active_station_name(), "Adrar")
520
+ session$setInputs(clear_station_sidebar = 503)
521
+ expect_null(active_station_name())
522
+ expect_null(clicked_wmo_id())
523
+
524
+ # -------------------------------------------------------------
525
+ # -------------------------------------------------------------
526
+ # 2.24 Station Dropdown Synchronization on Selection and Deselection
527
+ # -------------------------------------------------------------
528
+ session$setInputs(country = "Algeria", station = "Adrar")
529
+ expect_equal(active_station_name(), "Adrar")
530
+ # Sidebar deselect must set station back to 'All'
531
+ session$setInputs(clear_station_sidebar = 504)
532
+ expect_null(active_station_name(), info = "Deselecting must reset active_station_name")
533
+ expect_null(clicked_wmo_id())
534
+
535
+ # -------------------------------------------------------------
536
+ # 2.25 Parameter Switch to MSLP Updates Choices & Supports Deselection
537
+ # -------------------------------------------------------------
538
+ # MSLP has stations like ABIDJAN not present in TAVG
539
+ session$setInputs(country = "All", parameter = "MSLP")
540
+ # Verify MSLP station can be selected via map click
541
+ session$setInputs(station_map_feature_click = list(
542
+ layer_id = "wmo_stations",
543
+ properties = list(
544
+ WMO_ID = "65578",
545
+ Station_Name = "ABIDJAN",
546
+ Country = "Ivory_Coast",
547
+ Elevation = 8,
548
+ Longitude = -4.01,
549
+ Latitude = 5.25
550
+ )
551
+ ))
552
+ expect_equal(active_station_name(), "ABIDJAN")
553
+ expect_equal(as.character(clicked_wmo_id()), "65578")
554
+ chip_html <- paste(as.character(output$station_chip_ui), collapse = " ")
555
+ expect_true(grepl("ABIDJAN", chip_html))
556
+ # Clean deselect via Esc
557
+ session$setInputs(esc_clear_station = 505)
558
+ expect_null(active_station_name())
559
+ expect_null(clicked_wmo_id())
560
+ # Restore parameter to TAVG
561
+ session$setInputs(parameter = "TAVG")
562
+
563
+ # -------------------------------------------------------------
564
+ # 2.26 Fallback Map Feature Click Retains Elevation Metadata
565
+ # -------------------------------------------------------------
566
+ session$setInputs(station_map_feature_click = list(
567
+ layer_id = "wmo_stations",
568
+ properties = list(
569
+ WMO_ID = "998877",
570
+ Station_Name = "FallbackHighland",
571
+ Country = "Testland",
572
+ Elevation = 1540,
573
+ Longitude = 15.5,
574
+ Latitude = 45.2
575
+ )
576
+ ))
577
+ expect_equal(active_station_name(), "FallbackHighland")
578
+ meta <- selected_station_meta()
579
+ expect_false(is.null(meta))
580
+ expect_equal(as.numeric(meta$Elevation[[1]]), 1540, info = "Fallback station must retain 1540 m elevation")
581
+ chip_html <- paste(as.character(output$station_chip_ui), collapse = " ")
582
+ expect_true(grepl("1540 m", chip_html), info = "Floating chip must show '(1540 m)'")
583
+ session$setInputs(clear_station_chip = 506)
584
+ expect_null(active_station_name())
585
+ expect_null(active_elevation())
586
+
587
+ # -------------------------------------------------------------
588
+ # 2.27 Home Zoom Clears Active Selection (HungaroMet Parity)
589
+ # -------------------------------------------------------------
590
+ session$setInputs(country = "Algeria", station = "Adrar")
591
+ expect_equal(active_station_name(), "Adrar")
592
+ # Clicking home_zoom resets map AND clears active station selection
593
+ session$setInputs(home_zoom = 99)
594
+ expect_null(active_station_name(), info = "Home zoom must deselect active station")
595
+ expect_null(clicked_wmo_id())
596
+ })
597
+ cat(" -> All reactive tests passed successfully!\n")
598
+ })
599
+
600
+ cat("\n=================================================================\n")
601
+ cat("ALL TESTS PASSED! Station deselection & jumping fully verified.\n")
602
+ cat("=================================================================\n")
ui.R CHANGED
@@ -90,6 +90,19 @@ ui <- page_navbar(
90
  choices = c("All Stations" = "All"),
91
  selected = "All"),
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  hr(),
94
  div(
95
  class = "data-info-box",
@@ -108,6 +121,14 @@ ui <- page_navbar(
108
  style = "position: relative; height: 100%; width: 100%;",
109
  maplibreOutput("station_map", width = "100%", height = "100%"),
110
 
 
 
 
 
 
 
 
 
111
  # Layer Control Panel (Collapsible)
112
  absolutePanel(
113
  top = 130, left = 10, right = "auto",
 
90
  choices = c("All Stations" = "All"),
91
  selected = "All"),
92
 
93
+ conditionalPanel(
94
+ condition = "input.station && input.station !== 'All'",
95
+ div(
96
+ class = "mt-1 mb-2",
97
+ actionButton(
98
+ "clear_station_sidebar",
99
+ label = span(bsicons::bs_icon("x-circle-fill", class = "me-1"), "Deselect Station (Esc)"),
100
+ class = "sidebar-station-clear-btn",
101
+ onclick = "Shiny.setInputValue('clear_station_sidebar', Date.now(), {priority: 'event'});"
102
+ )
103
+ )
104
+ ),
105
+
106
  hr(),
107
  div(
108
  class = "data-info-box",
 
121
  style = "position: relative; height: 100%; width: 100%;",
122
  maplibreOutput("station_map", width = "100%", height = "100%"),
123
 
124
+ # Floating Station Chip
125
+ absolutePanel(
126
+ id = "station_chip_panel",
127
+ top = 15, left = 60,
128
+ style = "z-index: 1000; pointer-events: none;",
129
+ uiOutput("station_chip_ui")
130
+ ),
131
+
132
  # Layer Control Panel (Collapsible)
133
  absolutePanel(
134
  top = 130, left = 10, right = "auto",
www/app.js CHANGED
@@ -4,30 +4,42 @@ $(document).on('shiny:connected', function () {
4
  // console.log("Shiny connected to bridge");
5
  });
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  // Freeze/Unfreeze UI (loading spinner overlay)
8
- Shiny.addCustomMessageHandler('freezeUI', function (message) {
9
  $('body').addClass('ui-frozen');
10
  $('.frozen-overlay').addClass('active');
11
  $('.frozen-overlay-message').html(message.text || 'Loading data...');
12
  });
13
 
14
- Shiny.addCustomMessageHandler('unfreezeUI', function (message) {
15
  $('body').removeClass('ui-frozen');
16
  $('.frozen-overlay').removeClass('active');
17
  });
18
 
19
  // Update parent page URL and context
20
- Shiny.addCustomMessageHandler('updateParentURL', function (message) {
21
- // console.log("Updating parent URL with WMO Normals state:", message);
22
-
23
  // Send message to parent window (Quarto page)
24
  if (window.parent !== window) {
25
  window.parent.postMessage({
26
  type: 'wmonormals-state-update',
27
- station: message.station || null,
28
- country: message.country || null,
29
  parameter: message.parameter || null,
30
- time_period: message.time_period || null
 
31
  }, '*');
32
  }
33
  });
@@ -45,4 +57,70 @@ $(document).ready(function () {
45
  $(document).on('change', '.map-layer-control input[type="radio"]', function () {
46
  $('.map-layer-control').removeClass('expanded');
47
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  // console.log("Shiny connected to bridge");
5
  });
6
 
7
+ // Helper for resilient custom message handler registration
8
+ function registerShinyHandler(name, handler) {
9
+ if (window.Shiny && typeof Shiny.addCustomMessageHandler === 'function') {
10
+ Shiny.addCustomMessageHandler(name, handler);
11
+ } else {
12
+ $(document).on('shiny:connected', function () {
13
+ if (window.Shiny && typeof Shiny.addCustomMessageHandler === 'function') {
14
+ Shiny.addCustomMessageHandler(name, handler);
15
+ }
16
+ });
17
+ }
18
+ }
19
+
20
  // Freeze/Unfreeze UI (loading spinner overlay)
21
+ registerShinyHandler('freezeUI', function (message) {
22
  $('body').addClass('ui-frozen');
23
  $('.frozen-overlay').addClass('active');
24
  $('.frozen-overlay-message').html(message.text || 'Loading data...');
25
  });
26
 
27
+ registerShinyHandler('unfreezeUI', function (message) {
28
  $('body').removeClass('ui-frozen');
29
  $('.frozen-overlay').removeClass('active');
30
  });
31
 
32
  // Update parent page URL and context
33
+ registerShinyHandler('updateParentURL', function (message) {
 
 
34
  // Send message to parent window (Quarto page)
35
  if (window.parent !== window) {
36
  window.parent.postMessage({
37
  type: 'wmonormals-state-update',
38
+ station: (message.station && message.station !== 'All') ? message.station : null,
39
+ country: (message.country && message.country !== 'All') ? message.country : null,
40
  parameter: message.parameter || null,
41
+ time_period: message.time_period || null,
42
+ tab: message.tab || null
43
  }, '*');
44
  }
45
  });
 
57
  $(document).on('change', '.map-layer-control input[type="radio"]', function () {
58
  $('.map-layer-control').removeClass('expanded');
59
  });
60
+
61
+ // Global keyboard shortcut: Esc to clear active station selection
62
+ // Using window capture-phase (true) so MapLibre canvas cannot stop propagation
63
+ window.addEventListener('keydown', function (e) {
64
+ if (e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27) {
65
+ // If freeze overlay is active, let existing close handler handle it
66
+ if (document.body.classList.contains('ui-frozen')) {
67
+ return;
68
+ }
69
+ // If modal is open, let standard modal dismiss handle it
70
+ if ($('.modal.show:visible').length > 0) {
71
+ return;
72
+ }
73
+
74
+ // Clean up any maplibregl popup on screen
75
+ $('.maplibregl-popup').remove();
76
+
77
+ // Unfocus active inputs
78
+ if (document.activeElement && typeof document.activeElement.blur === 'function') {
79
+ document.activeElement.blur();
80
+ }
81
+
82
+ // Notify Shiny
83
+ if (window.Shiny && typeof window.Shiny.setInputValue === 'function') {
84
+ Shiny.setInputValue('esc_clear_station', Date.now(), { priority: 'event' });
85
+ }
86
+ }
87
+ }, true);
88
+
89
+ // Trigger map resize when switching to Map View tab
90
+ $(document).on('shown.bs.tab', 'a[data-bs-toggle="tab"], button[data-bs-toggle="tab"]', function (e) {
91
+ var targetText = $(e.target).text().trim();
92
+ if (targetText.indexOf('Map View') !== -1) {
93
+ triggerMapResize();
94
+ }
95
+ });
96
  });
97
+
98
+ // Resize MapLibre map helper (dual-tick to accommodate CSS fade transitions)
99
+ function triggerMapResize() {
100
+ [100, 300].forEach(function (delay) {
101
+ setTimeout(function () {
102
+ var mapInstance = null;
103
+ if (window.HTMLWidgets && HTMLWidgets.find) {
104
+ var w = HTMLWidgets.find('#station_map');
105
+ if (w && w.getMap) mapInstance = w.getMap();
106
+ }
107
+ if (!mapInstance) {
108
+ var mapEl = document.getElementById('station_map');
109
+ if (mapEl) {
110
+ if (mapEl.map) mapInstance = mapEl.map;
111
+ else if (mapEl.__mapgl) mapInstance = mapEl.__mapgl;
112
+ }
113
+ }
114
+ if (mapInstance && typeof mapInstance.resize === 'function') {
115
+ mapInstance.resize();
116
+ }
117
+ window.dispatchEvent(new Event('resize'));
118
+ }, delay);
119
+ });
120
+ }
121
+
122
+ // Custom message handler for resizing map
123
+ registerShinyHandler('resizeMap', function (message) {
124
+ triggerMapResize();
125
+ });
126
+
www/custom.css CHANGED
@@ -228,4 +228,105 @@ body.ui-frozen .navbar {
228
 
229
  .fw-bold {
230
  color: #343a40;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
  }
 
228
 
229
  .fw-bold {
230
  color: #343a40;
231
+ }
232
+
233
+ /* Floating station selection badge / chip */
234
+ .station-floating-chip {
235
+ display: flex;
236
+ align-items: center;
237
+ gap: 8px;
238
+ background: rgba(255, 255, 255, 0.95);
239
+ backdrop-filter: blur(8px);
240
+ -webkit-backdrop-filter: blur(8px);
241
+ border: 1px solid rgba(203, 213, 225, 0.8);
242
+ border-radius: 9999px;
243
+ padding: 6px 14px;
244
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12), 0 2px 4px rgba(0, 0, 0, 0.06);
245
+ pointer-events: auto;
246
+ transition: all 0.2s ease;
247
+ max-width: calc(100vw - 80px);
248
+ }
249
+
250
+ .station-floating-chip:hover {
251
+ box-shadow: 0 6px 16px rgba(0, 0, 0, 0.16);
252
+ border-color: #cbd5e1;
253
+ }
254
+
255
+ .chip-dot {
256
+ width: 8px;
257
+ height: 8px;
258
+ border-radius: 50%;
259
+ background-color: #dc2626;
260
+ box-shadow: 0 0 0 2px rgba(220, 38, 38, 0.2);
261
+ flex-shrink: 0;
262
+ animation: pulse-dot 2s infinite;
263
+ }
264
+
265
+ @keyframes pulse-dot {
266
+ 0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(220, 38, 38, 0.7); }
267
+ 70% { transform: scale(1); box-shadow: 0 0 0 6px rgba(220, 38, 38, 0); }
268
+ 100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(220, 38, 38, 0); }
269
+ }
270
+
271
+ .chip-text {
272
+ font-size: 0.875rem;
273
+ font-weight: 600;
274
+ color: #1e293b;
275
+ white-space: nowrap;
276
+ max-width: 260px;
277
+ overflow: hidden;
278
+ text-overflow: ellipsis;
279
+ }
280
+
281
+ .btn-chip-clear {
282
+ display: inline-flex;
283
+ align-items: center;
284
+ gap: 4px;
285
+ background-color: #fee2e2;
286
+ color: #b91c1c;
287
+ border: 1px solid #fca5a5;
288
+ border-radius: 9999px;
289
+ padding: 2px 8px;
290
+ font-size: 0.75rem;
291
+ font-weight: 600;
292
+ cursor: pointer;
293
+ transition: background-color 0.15s ease, color 0.15s ease;
294
+ line-height: 1.2;
295
+ }
296
+
297
+ .btn-chip-clear:hover {
298
+ background-color: #ef4444;
299
+ color: #ffffff;
300
+ border-color: #ef4444;
301
+ }
302
+
303
+ .chip-kbd {
304
+ font-family: inherit;
305
+ font-size: 0.6875rem;
306
+ padding: 1px 4px;
307
+ border-radius: 4px;
308
+ background: rgba(0, 0, 0, 0.08);
309
+ border: 1px solid rgba(0, 0, 0, 0.15);
310
+ }
311
+
312
+ .sidebar-station-clear-btn {
313
+ display: inline-flex;
314
+ align-items: center;
315
+ justify-content: center;
316
+ width: 100%;
317
+ padding: 5px 12px;
318
+ font-size: 0.825rem;
319
+ font-weight: 500;
320
+ color: #b91c1c;
321
+ background-color: #fee2e2;
322
+ border: 1px solid #fca5a5;
323
+ border-radius: 6px;
324
+ cursor: pointer;
325
+ transition: all 0.15s ease-in-out;
326
+ }
327
+
328
+ .sidebar-station-clear-btn:hover {
329
+ background-color: #ef4444;
330
+ color: #ffffff;
331
+ border-color: #ef4444;
332
  }