wmonormals / server.R
alexdum's picture
fix: isolate post-flush callbacks and unfreeze UI on direct Dashboard deep links
403744a
Raw History Blame Contribute Delete
59.6 kB
server <- function(input, output, session) { # Defensive string validator is_valid_str <- function(x) !is.null(x) && length(x) > 0 && !is.na(x[1]) && nzchar(trimws(as.character(x[1]))) normalize_period_param <- function(x) { if (!is_valid_str(x)) return(NULL) p <- gsub("[\u2013\u2014_]", "-", trimws(as.character(x[1]))) m <- regmatches(p, regexpr("((?:19|20)\\d{2})\\s*-\\s*((?:19|20)\\d{2})", p, perl = TRUE)) if (length(m) > 0 && nzchar(m[1])) { return(gsub("\\s+", "", m[1])) } p } normalize_tab_param <- function(x) { if (!is_valid_str(x)) return(NULL) v <- tolower(trimws(as.character(x[1]))) switch(v, "map" = "Map View", "map view" = "Map View", "dashboard" = "Dashboard", "dashboard-plots" = "Dashboard", "dashboard-data" = "Dashboard", NULL ) } # Map Initialization Variables initial_lng <- 0 initial_lat <- 30 initial_zoom <- 3 # Show loading spinner on startup until stations are drawn session$sendCustomMessage("freezeUI", list(text = "Loading stations...")) # URL Deep-Linking & Station State pending_station <- reactiveVal(NULL) pending_country <- reactiveVal(NULL) pending_tab <- reactiveVal(NULL) active_station_name <- reactiveVal(NULL) active_country <- reactiveVal(NULL) active_elevation <- reactiveVal(NULL) active_longitude <- reactiveVal(NULL) active_latitude <- reactiveVal(NULL) clicked_wmo_id <- reactiveVal(NULL) skip_country_clear <- reactiveVal(FALSE) url_initialized <- reactiveVal(FALSE) pending_map_fly <- reactiveVal(NULL) # Token-guarded echo state for async client widget round-trips pending_url_period_echo <- reactiveVal(NULL) url_period_echo_token <- reactiveVal(0L) pending_url_param_echo <- reactiveVal(NULL) url_param_echo_token <- reactiveVal(0L) pending_url_time_echo <- reactiveVal(NULL) url_time_echo_token <- reactiveVal(0L) pending_url_country_echo <- reactiveVal(NULL) url_country_echo_token <- reactiveVal(0L) pending_url_station_echo <- reactiveVal(NULL) url_station_echo_token <- reactiveVal(0L) is_session_closed <- function(sess = session) { tryCatch(!is.null(sess) && is.function(sess$isClosed) && isTRUE(sess$isClosed()), error = function(e) FALSE) } schedule_post_flush <- function(fn, delay_sec) { current_session <- session run_later <- function() { if (is_session_closed(current_session)) return() later::later(function() { tryCatch({ if (is_session_closed(current_session)) return() shiny::withReactiveDomain(current_session, shiny::isolate(fn())) }, error = function(e) NULL) }, delay_sec) } if (!is.null(current_session) && is.function(current_session$onFlushed)) { current_session$onFlushed(run_later, once = TRUE) } else { run_later() } } arm_token_rv <- function(val_rv, tok_rv, value, clear_value, duration) { tok <- isolate(tok_rv()) + 1L tok_rv(tok) val_rv(value) schedule_post_flush(function() { if (identical(isolate(tok_rv()), tok)) { val_rv(clear_value) } }, duration) } clear_token_rv <- function(val_rv, tok_rv, clear_value) { tok_rv(isolate(tok_rv()) + 1L) val_rv(clear_value) } arm_url_period_echo <- function(val, duration = 3.0) arm_token_rv(pending_url_period_echo, url_period_echo_token, as.character(val[1]), NULL, duration) clear_url_period_echo <- function() clear_token_rv(pending_url_period_echo, url_period_echo_token, NULL) arm_url_param_echo <- function(val, duration = 3.0) arm_token_rv(pending_url_param_echo, url_param_echo_token, as.character(val[1]), NULL, duration) clear_url_param_echo <- function() clear_token_rv(pending_url_param_echo, url_param_echo_token, NULL) arm_url_time_echo <- function(val, duration = 3.0) arm_token_rv(pending_url_time_echo, url_time_echo_token, as.character(val[1]), NULL, duration) clear_url_time_echo <- function() clear_token_rv(pending_url_time_echo, url_time_echo_token, NULL) arm_url_country_echo <- function(val, duration = 3.0) arm_token_rv(pending_url_country_echo, url_country_echo_token, as.character(val[1]), NULL, duration) clear_url_country_echo <- function() clear_token_rv(pending_url_country_echo, url_country_echo_token, NULL) arm_url_station_echo <- function(val, duration = 3.0) arm_token_rv(pending_url_station_echo, url_station_echo_token, as.character(val[1]), NULL, duration) clear_url_station_echo <- function() clear_token_rv(pending_url_station_echo, url_station_echo_token, NULL) effective_period <- function() { pend <- pending_url_period_echo() if (is_valid_str(pend)) return(as.character(pend[1])) if (is_valid_str(input$normals_period)) as.character(input$normals_period[1]) else "1991-2020" } effective_param <- function() { pend <- pending_url_param_echo() if (is_valid_str(pend)) return(as.character(pend[1])) if (is_valid_str(input$parameter)) as.character(input$parameter[1]) else "TAVG" } effective_time <- function() { pend <- pending_url_time_echo() if (is_valid_str(pend)) return(as.character(pend[1])) if (is_valid_str(input$time_period)) as.character(input$time_period[1]) else "Annual" } effective_country <- function() { pend <- pending_url_country_echo() if (is_valid_str(pend)) return(as.character(pend[1])) if (is_valid_str(input$country)) as.character(input$country[1]) else "All" } observe({ raw_qs <- isolate(session$clientData$url_search) query <- parseQueryString(if (is.null(raw_qs)) "" else raw_qs) raw_period <- query$normals_period if (!is_valid_str(raw_period)) raw_period <- query[["normals-period"]] if (!is_valid_str(raw_period)) raw_period <- query$normalsPeriod norm_req_period <- normalize_period_param(raw_period) req_period <- if (is_valid_str(norm_req_period) && isTRUE(norm_req_period %in% unname(NORMALS_PERIOD_CHOICES))) { updateSelectInput(session, "normals_period", selected = norm_req_period) if (!identical(norm_req_period, "1991-2020")) { arm_url_period_echo(norm_req_period, 3.0) } norm_req_period } else { "1991-2020" } valid_params <- c("TAVG", "TMAX", "TMIN", "PRCP", "DP01", "MSLP", "MNVP", "TSUN") req_param <- "TAVG" if (!is.null(query$parameter) && is_valid_str(query$parameter)) { p_match <- valid_params[toupper(valid_params) == toupper(trimws(as.character(query$parameter[1])))] if (length(p_match) > 0) { req_param <- p_match[1] updateSelectInput(session, "parameter", selected = req_param) if (!identical(req_param, "TAVG")) { arm_url_param_echo(req_param, 3.0) } } } valid_times <- c("Annual", month.abb) req_time <- "Annual" if (!is.null(query$time_period) && is_valid_str(query$time_period)) { t_match <- valid_times[tolower(valid_times) == tolower(trimws(as.character(query$time_period[1])))] if (length(t_match) > 0) { req_time <- t_match[1] updateSelectInput(session, "time_period", selected = req_time) if (!identical(req_time, "Annual")) { arm_url_time_echo(req_time, 3.0) } } } valid_countries <- get_countries_for_period(req_period) resolved_country <- if (!is.null(query$country) && is_valid_str(query$country)) { resolve_wmo_country(query$country, valid_countries) } else { NULL } resolved_station_row <- if (!is.null(query$station) && is_valid_str(query$station)) { resolve_wmo_station(query$station, query$country, req_period, req_param) } else { NULL } if (!is.null(resolved_station_row) && nrow(resolved_station_row) > 0) { stn_country <- as.character(resolved_station_row$Country[1]) if (is_valid_str(stn_country) && isTRUE(stn_country %in% valid_countries)) { resolved_country <- stn_country } else if (!is.null(resolved_country) && !identical(resolved_country, "All")) { resolved_country <- "All" } } if (!is.null(resolved_country)) { if (!identical(req_period, "1991-2020")) { updateSelectInput(session, "country", choices = c("All Countries" = "All", valid_countries), selected = resolved_country) } else { updateSelectInput(session, "country", selected = resolved_country) } pending_country(resolved_country) if (!identical(resolved_country, "All")) { arm_url_country_echo(resolved_country, 3.0) } } target_url_tab <- normalize_tab_param(query$tab) if (is.null(target_url_tab)) { target_url_tab <- normalize_tab_param(query$view) } if (!is.null(target_url_tab)) { pending_tab(target_url_tab) bslib::nav_select("main_nav", target_url_tab) } url_initialized(TRUE) if (!is.null(resolved_station_row) && nrow(resolved_station_row) > 0) { stn_name <- as.character(resolved_station_row$Station_Name[1]) pending_station(stn_name) arm_url_station_echo(stn_name, 3.0) select_station_helper(resolved_station_row, move_map = TRUE, is_url_init = TRUE) } else { if (!is.null(query$station) && is_valid_str(query$station)) { pending_station(NULL) } broadcast_parent_url() } }) %>% bindEvent(session$clientData$url_search, ignoreNULL = FALSE, once = TRUE) # Emit state to parent iframe for URL synchronization broadcast_parent_url <- function(tab_override = NULL) { norm_p <- effective_period() param <- effective_param() time_p <- effective_time() # Check active station first, then pending deep-link, else default to "All" stn <- if (is_valid_str(active_station_name())) { active_station_name() } else if (!is.null(pending_station()) && is_valid_str(pending_station())) { pending_station() } else { "All" } cntry <- canonical_wmo_parent_country(if (is_valid_str(active_country())) { active_country() } else { effective_country() }) has_station <- is_valid_str(active_station_name()) || is_valid_str(pending_station()) tab_val <- if (!is.null(tab_override)) { tab_override } else if (is_valid_str(pending_tab())) { pending_tab() } else if (!has_station && identical(input$main_nav, "Dashboard")) { "Map View" } else if (is_valid_str(input$main_nav)) { input$main_nav } else { "Map View" } session$sendCustomMessage("updateParentURL", list( normals_period = norm_p, parameter = param, time_period = time_p, country = cntry, station = stn, tab = tab_val )) } observe({ req(url_initialized()) broadcast_parent_url() }) # Base dataset dependent on the selected period and parameter active_dataset <- reactive({ norm_p <- effective_period() param <- effective_param() get_wmo_dataset(norm_p, param) }) # Reactive to filter stations by Country filtered_stations_by_country <- reactive({ req(active_dataset()) stations_sf <- active_dataset() cntry <- effective_country() if (!is_valid_str(cntry) || identical(cntry, "All")) { stations_sf } else { stations_sf %>% filter(Country == cntry) } }) # Synchronize Country dropdown choices when Normals Period changes observeEvent(input$normals_period, { pend_np <- isolate(pending_url_period_echo()) if (is_valid_str(pend_np)) { if (identical(input$normals_period, pend_np)) { clear_url_period_echo() } else if (identical(input$normals_period, "1991-2020")) { updateSelectInput(session, "normals_period", selected = pend_np) return() } else { clear_url_period_echo() } } norm_p <- effective_period() c_list <- get_countries_for_period(norm_p) target_c <- if (is_valid_str(pending_url_country_echo())) { pending_url_country_echo() } else if (is_valid_str(pending_country())) { pending_country() } else { input$country } resolved_c <- if (is_valid_str(target_c)) resolve_wmo_country(target_c, c_list) else NULL cur_sel <- if (is_valid_str(resolved_c)) resolved_c else "All" if (is_valid_str(input$country) && !identical(input$country, cur_sel)) { skip_country_clear(TRUE) } updateSelectInput(session, "country", choices = c("All Countries" = "All", c_list), selected = cur_sel) }, ignoreInit = TRUE) # Update Station choices based on selected Country, Parameter, or Period observeEvent(list(input$country, input$parameter, input$normals_period), { norm_p <- effective_period() valid_countries <- get_countries_for_period(norm_p) if (is_valid_str(pending_country())) { if (!isTRUE(pending_country() %in% c("All", valid_countries))) { pending_country(NULL) } else if (identical(input$country, pending_country())) { pending_country(NULL) } } filtered_data <- filtered_stations_by_country() stn_active <- active_station_name() stn_pend <- pending_station() stn_echo <- pending_url_station_echo() extra_stns <- c(stn_active, stn_pend, stn_echo) extra_stns <- extra_stns[vapply(extra_stns, is_valid_str, logical(1))] station_choices <- if (!is.null(filtered_data) && inherits(filtered_data, "sf") && nrow(filtered_data) > 0) { names_list <- c(filtered_data$Station_Name, extra_stns) c("All Stations" = "All", unique(sort(names_list))) } else if (length(extra_stns) > 0) { c("All Stations" = "All", unique(extra_stns)) } else { c("All Stations" = "All") } sel <- if (is_valid_str(stn_echo)) { stn_echo } else if (is_valid_str(stn_pend)) { stn_pend } else if (is_valid_str(stn_active)) { stn_active } else { "All" } updateSelectizeInput(session, "station", choices = station_choices, selected = sel, server = TRUE) }, ignoreInit = FALSE) # Final reactive dataset based on both filters a user selects final_filtered_stations <- reactive({ data <- filtered_stations_by_country() req(!is.null(data)) data }) # Selected Station Metadata Reactive selected_station_meta <- reactive({ wmo <- clicked_wmo_id() stn_name <- active_station_name() if (!is_valid_str(wmo) && !is_valid_str(stn_name)) return(NULL) norm_p <- effective_period() candidate_dfs <- list( active_dataset(), get_wmo_dataset(norm_p, "TAVG"), get_wmo_dataset(norm_p, "PRCP"), get_wmo_dataset(norm_p, "TMAX"), get_wmo_dataset(norm_p, "TMIN"), get_wmo_dataset(norm_p, "MSLP"), get_wmo_dataset(norm_p, "MNVP"), get_wmo_dataset(norm_p, "DP01"), get_wmo_dataset(norm_p, "TSUN"), # Cross-period fallback to preserve metadata when station is absent from active baseline get_wmo_dataset("1991-2020", "TAVG"), get_wmo_dataset("1991-2020", "PRCP"), get_wmo_dataset("1961-1990", "TAVG"), get_wmo_dataset("1981-2010", "TAVG") ) for (cdf in candidate_dfs) { if (!is.null(cdf) && inherits(cdf, "sf") && nrow(cdf) > 0) { # Try exact match on both Station_Name and WMO_ID first if (is_valid_str(stn_name) && is_valid_str(wmo)) { 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)) if (length(idx) > 0) return(sf::st_drop_geometry(cdf[idx[1], ])) } # Fall back to Station_Name if available if (is_valid_str(stn_name)) { idx <- which(!is.na(cdf$Station_Name) & as.character(cdf$Station_Name) == as.character(stn_name)) if (length(idx) > 0) return(sf::st_drop_geometry(cdf[idx[1], ])) } # Fall back to WMO_ID if (is_valid_str(wmo)) { idx <- which(!is.na(cdf$WMO_ID) & as.character(cdf$WMO_ID) == as.character(wmo)) if (length(idx) > 0) return(sf::st_drop_geometry(cdf[idx[1], ])) } } } # Fallback dataframe if station was clicked/selected but not found in sf composites if (is_valid_str(stn_name) || is_valid_str(wmo)) { return(data.frame( Station_Name = if (is_valid_str(stn_name)) stn_name else as.character(wmo), WMO_ID = if (is_valid_str(wmo)) as.character(wmo) else "", Country = if (is_valid_str(active_country())) active_country() else "", Elevation = if (!is.null(active_elevation())) suppressWarnings(as.numeric(active_elevation())) else NA, Longitude = if (!is.null(active_longitude())) suppressWarnings(as.numeric(active_longitude())) else NA, Latitude = if (!is.null(active_latitude())) suppressWarnings(as.numeric(active_latitude())) else NA, stringsAsFactors = FALSE )) } return(NULL) }) # Helper: Highlight Station on Map highlight_station <- function(proxy, lon, lat, move_map = TRUE) { proxy %>% mapgl::clear_layer("selected_highlight") if (is.null(lon) || is.null(lat) || length(lon) == 0 || length(lat) == 0 || is.na(lon[1]) || is.na(lat[1])) { return(proxy) } num_lon <- suppressWarnings(as.numeric(lon[1])) num_lat <- suppressWarnings(as.numeric(lat[1])) if (is.na(num_lon) || is.na(num_lat)) { return(proxy) } hl_pt <- sf::st_as_sf( data.frame(x = num_lon, y = num_lat), coords = c("x", "y"), crs = 4326 ) proxy <- proxy %>% mapgl::add_circle_layer( id = "selected_highlight", source = hl_pt, circle_color = "red", circle_radius = 12, circle_stroke_color = "white", circle_stroke_width = 2, circle_opacity = 0.4 ) if (isTRUE(move_map)) { proxy <- proxy %>% mapgl::fly_to(center = c(num_lon, num_lat), zoom = 8) } proxy } # Centralized Deselection Logic clear_station_selection <- function(jump_to_map = TRUE) { was_selected <- !is.null(clicked_wmo_id()) || !is.null(active_station_name()) || (is_valid_str(input$station) && !identical(input$station, "All")) clicked_wmo_id(NULL) active_station_name(NULL) active_country(NULL) active_elevation(NULL) active_longitude(NULL) active_latitude(NULL) pending_station(NULL) clear_url_station_echo() pending_tab(NULL) pending_map_fly(NULL) if (!identical(input$station, "All")) { updateSelectizeInput(session, "station", selected = "All") } # When deselecting a station while on Dashboard, jump to Map View curr_tab <- isolate(input$main_nav) new_tab <- if (isTRUE(jump_to_map) && is_valid_str(curr_tab) && identical(curr_tab, "Dashboard")) { bslib::nav_select("main_nav", "Map View") "Map View" } else if (is_valid_str(curr_tab)) { curr_tab } else { "Map View" } proxy <- mapgl::maplibre_proxy("station_map") proxy %>% mapgl::clear_layer("selected_highlight") # Only re-center / fit bounds if a station was actively selected if (isTRUE(was_selected)) { cntry <- isolate(effective_country()) if (is_valid_str(cntry) && !identical(cntry, "All")) { country_sel <- isolate(filtered_stations_by_country()) if (!is.null(country_sel) && nrow(country_sel) > 0) { proxy %>% mapgl::fit_bounds(country_sel, padding = 100, animate = TRUE, maxZoom = 8, max_zoom = 8) } else { proxy %>% mapgl::fly_to(center = c(initial_lng, initial_lat), zoom = initial_zoom) } } else { proxy %>% mapgl::fly_to(center = c(initial_lng, initial_lat), zoom = initial_zoom) } } # Trigger map resize after tab transition session$sendCustomMessage("resizeMap", list()) # Broadcast state to parent immediately to prevent any stale station leak broadcast_parent_url(tab_override = new_tab) } # Station Selection Helper select_station_helper <- function(station_row, move_map = TRUE, is_url_init = FALSE) { if (is.null(station_row) || nrow(station_row) == 0) return() click_id <- station_row$WMO_ID[1] stn_name <- station_row$Station_Name[1] stn_country <- station_row$Country[1] sta_lon <- station_row$Longitude[1] sta_lat <- station_row$Latitude[1] sta_elev <- if ("Elevation" %in% names(station_row) && !is.null(station_row$Elevation)) station_row$Elevation[1] else NULL clicked_wmo_id(click_id) active_station_name(stn_name) active_country(stn_country) active_elevation(sta_elev) active_longitude(sta_lon) active_latitude(sta_lat) if (!isTRUE(is_url_init) && is_valid_str(pending_station())) { p_stn <- pending_station() if (identical(p_stn, stn_name) || (!is.null(click_id) && sub("^0+", "", trimws(p_stn)) == sub("^0+", "", trimws(as.character(click_id))))) { pending_station(NULL) } } if (!isTRUE(is_url_init) && is_valid_str(input$country) && !identical(input$country, "All") && !identical(input$country, stn_country)) { skip_country_clear(TRUE) updateSelectInput(session, "country", selected = "All") } if (!identical(input$station, stn_name)) { current_data <- final_filtered_stations() base_choices <- if (!is.null(current_data) && nrow(current_data) > 0) current_data$Station_Name else character(0) station_choices <- c("All Stations" = "All", unique(sort(c(base_choices, stn_name)))) updateSelectizeInput(session, "station", choices = station_choices, selected = stn_name, server = TRUE) } if (isTRUE(move_map)) { if (isTRUE(isolate(map_initialized()))) { highlight_station(mapgl::maplibre_proxy("station_map"), sta_lon, sta_lat, move_map = TRUE) } else { pending_map_fly(list(lon = sta_lon, lat = sta_lat)) highlight_station(mapgl::maplibre_proxy("station_map"), sta_lon, sta_lat, move_map = FALSE) } } else { highlight_station(mapgl::maplibre_proxy("station_map"), sta_lon, sta_lat, move_map = FALSE) } target_tab <- if (is_valid_str(pending_tab())) { t <- pending_tab() if (!isTRUE(is_url_init) && !is_valid_str(pending_url_station_echo())) { pending_tab(NULL) } t } else { "Dashboard" } bslib::nav_select("main_nav", target_tab) if (!identical(target_tab, "Map View") && !isTRUE(isolate(map_initialized()))) { session$sendCustomMessage("unfreezeUI", list()) } broadcast_parent_url(tab_override = target_tab) } # Deselection Observers (Sidebar Button, Floating Chip) observeEvent(input$clear_station_sidebar, { clear_station_selection(jump_to_map = TRUE) }) observeEvent(input$clear_station_chip, { clear_station_selection(jump_to_map = TRUE) }) # Station Dropdown Selection Observer observeEvent(input$station, { stn <- input$station pend_s <- isolate(pending_url_station_echo()) if (is_valid_str(stn) && !identical(stn, "All")) { is_url_echo <- is_valid_str(pend_s) && identical(as.character(stn[1]), as.character(pend_s[1])) if (is_url_echo) { clear_url_station_echo() } if (!identical(active_station_name(), stn)) { target_station <- resolve_wmo_station( stn, country_param = isolate(effective_country()), norm_period = isolate(effective_period()), active_param = isolate(effective_param()) ) if (!is.null(target_station)) { if (!is_url_echo && !is_valid_str(pend_s)) { pending_tab(NULL) } select_station_helper(target_station, move_map = TRUE) } else { pending_station(NULL) clear_url_station_echo() updateSelectizeInput(session, "station", selected = "All") } } } else if (identical(stn, "All")) { if (is_valid_str(pend_s)) { updateSelectizeInput(session, "station", selected = pend_s) return() } if (!is.null(clicked_wmo_id()) || !is.null(active_station_name())) { clear_station_selection(jump_to_map = TRUE) } } }, ignoreInit = FALSE) observeEvent(input$main_nav, { if (is_valid_str(pending_tab()) && is_valid_str(input$main_nav) && !is_valid_str(isolate(pending_url_station_echo()))) { if (identical(input$main_nav, pending_tab()) || identical(input$main_nav, "Dashboard")) { pending_tab(NULL) } } }, ignoreInit = TRUE) # Station Chip UI Overlay on Map View output$station_chip_ui <- renderUI({ meta <- selected_station_meta() if (is.null(meta)) return(NULL) elev_num <- if (!is.null(meta$Elevation)) suppressWarnings(as.numeric(meta$Elevation[[1]])) else NA elev_val <- if (!is.null(elev_num) && length(elev_num) > 0 && !is.na(elev_num) && elev_num > -500) { paste0(" (", round(elev_num, 0), " m)") } else { "" } stn_name_str <- if (!is.null(meta$Station_Name) && length(meta$Station_Name) > 0 && !is.na(meta$Station_Name[[1]])) { enc2utf8(as.character(meta$Station_Name[[1]])) } else { "Station" } wmo_id_str <- if (!is.null(meta$WMO_ID) && length(meta$WMO_ID) > 0 && !is.na(meta$WMO_ID[[1]])) { as.character(meta$WMO_ID[[1]]) } else { "" } chip_label <- if (nzchar(wmo_id_str)) { paste0(stn_name_str, " - ", wmo_id_str, elev_val) } else { paste0(stn_name_str, elev_val) } tags$div( class = "station-floating-chip", tags$span(class = "chip-dot"), tags$span(class = "chip-text", title = chip_label, chip_label), tags$button( type = "button", class = "btn-chip-clear", `aria-label` = "Deselect active station", onclick = "event.stopPropagation(); Shiny.setInputValue('clear_station_chip', Date.now(), {priority: 'event'});", tags$span("Deselect") ) ) }) outputOptions(output, "station_chip_ui", suspendWhenHidden = FALSE) # Deselect and jump back to Map View when a user changes the country filter observeEvent(input$country, { pend_c <- isolate(pending_url_country_echo()) if (is_valid_str(pend_c)) { if (identical(input$country, pend_c)) { clear_url_country_echo() if (!is_valid_str(isolate(active_station_name())) && !is_valid_str(isolate(clicked_wmo_id())) && isTRUE(isolate(map_initialized()))) { country_sel <- isolate(filtered_stations_by_country()) if (!is.null(country_sel) && nrow(country_sel) > 0) { maplibre_proxy("station_map") %>% fit_bounds(country_sel, padding = 100, animate = TRUE, maxZoom = 8, max_zoom = 8) } } return() } else if (identical(input$country, "All")) { updateSelectInput(session, "country", selected = pend_c) return() } else { clear_url_country_echo() } } if (isTRUE(skip_country_clear())) { skip_country_clear(FALSE) return() } pending_tab(NULL) had_station <- !is.null(clicked_wmo_id()) || !is.null(active_station_name()) || (is_valid_str(input$station) && !identical(input$station, "All")) clear_station_selection(jump_to_map = TRUE) if (!had_station && is_valid_str(input$country) && !identical(input$country, "All")) { country_sel <- filtered_stations_by_country() if (!is.null(country_sel) && nrow(country_sel) > 0) { maplibre_proxy("station_map") %>% fit_bounds(country_sel, padding = 100, animate = TRUE, maxZoom = 8, max_zoom = 8) } } }, ignoreInit = TRUE) # Jump back to Map View when parameter or time period changes while on Dashboard observeEvent(input$parameter, { pend_p <- isolate(pending_url_param_echo()) if (is_valid_str(pend_p)) { if (identical(input$parameter, pend_p)) { clear_url_param_echo() return() } else if (identical(input$parameter, "TAVG")) { updateSelectInput(session, "parameter", selected = pend_p) return() } else { clear_url_param_echo() } } if (identical(input$main_nav, "Dashboard")) { clear_station_selection(jump_to_map = TRUE) } }, ignoreInit = TRUE) observeEvent(input$time_period, { pend_t <- isolate(pending_url_time_echo()) if (is_valid_str(pend_t)) { if (identical(input$time_period, pend_t)) { clear_url_time_echo() return() } else if (identical(input$time_period, "Annual")) { updateSelectInput(session, "time_period", selected = pend_t) return() } else { clear_url_time_echo() } } if (identical(input$main_nav, "Dashboard")) { clear_station_selection(jump_to_map = TRUE) } }, ignoreInit = TRUE) initial_zoom <- 3 # Reactive values for map state style_change_trigger <- reactiveVal(0) stations_before_id <- reactiveVal(NULL) stations_loaded <- reactiveVal(FALSE) basemap_debounced <- shiny::debounce(reactive(input$basemap), 200) # Output the base maplibre map output$station_map <- renderMaplibre({ maplibre( style = ofm_positron_style, center = c(initial_lng, initial_lat), zoom = initial_zoom ) %>% add_navigation_control(show_compass = FALSE, visualize_pitch = FALSE, position = "top-left") }) # Initialize map bounds / Home Zoom observeEvent(input$home_zoom, { if (!is.null(clicked_wmo_id()) || !is.null(active_station_name())) { clear_station_selection(jump_to_map = FALSE) } else { cntry <- input$country if (is_valid_str(cntry) && !identical(cntry, "All")) { country_sel <- filtered_stations_by_country() if (!is.null(country_sel) && nrow(country_sel) > 0) { maplibre_proxy("station_map") %>% fit_bounds(country_sel, padding = 100, animate = TRUE, maxZoom = 8, max_zoom = 8) } else { maplibre_proxy("station_map") %>% fly_to(center = c(initial_lng, initial_lat), zoom = initial_zoom) } } else { maplibre_proxy("station_map") %>% fly_to(center = c(initial_lng, initial_lat), zoom = initial_zoom) } } }) # --- Basemap Switching Logic --- label_layer_ids <- c( # OpenFreeMap Positron & Bright common labels "waterway_line_label", "water_name_point_label", "water_name_line_label", "highway-name-path", "highway-name-minor", "highway-name-major", "highway-shield-non-us", "highway-shield-us-interstate", "road_shield_us", "airport", "label_other", "label_village", "label_town", "label_state", "label_city", "label_city_capital", "label_country_3", "label_country_2", "label_country_1", # Bright specific labels (POIs & Directions) "road_oneway", "road_oneway_opposite", "poi_r20", "poi_r7", "poi_r1", "poi_transit", # Dash variants "waterway-line-label", "water-name-point-label", "water-name-line-label", "highway-shield-non-us", "highway-shield-us-interstate", "road-shield-us", "label-other", "label-village", "label-town", "label-state", "label-city", "label-city-capital", "label-country-3", "label-country-2", "label-country-1" ) non_label_layer_ids <- c( "background", "park", "water", "landcover_ice_shelf", "landcover_glacier", "landuse_residential", "landcover_wood", "waterway", "building", "tunnel_motorway_casing", "tunnel_motorway_inner", "aeroway-taxiway", "aeroway-runway-casing", "aeroway-area", "aeroway-runway", "road_area_pier", "road_pier", "highway_path", "highway_minor", "highway_major_casing", "highway_major_inner", "highway_major_subtle", "highway_motorway_casing", "highway_motorway_inner", "highway_motorway_subtle", "railway_transit", "railway_transit_dashline", "railway_service", "railway_service_dashline", "railway", "railway_dashline", "highway_motorway_bridge_casing", "highway_motorway_bridge_inner", "boundary_3", "boundary_2", "boundary_disputed" ) apply_label_visibility <- function(proxy, show_labels) { visibility <- if (isTRUE(show_labels)) "visible" else "none" for (layer_id in label_layer_ids) { tryCatch({ proxy %>% set_layout_property(layer_id, "visibility", visibility) }, error = function(e) {}) } } observeEvent(basemap_debounced(), { req(input$basemap) basemap <- basemap_debounced() proxy <- maplibre_proxy("station_map") if (is_valid_str(basemap) && isTRUE(basemap %in% c("ofm_positron", "ofm_bright"))) { style_url <- if (identical(basemap, "ofm_positron")) ofm_positron_style else ofm_bright_style proxy %>% set_style(style_url, preserve_layers = FALSE) stations_before_id("waterway_line_label") current_session <- session selected_basemap <- basemap # Restore labels state later::later(function() { tryCatch({ if (is_session_closed(current_session)) return() shiny::withReactiveDomain(current_session, shiny::isolate({ if (!identical(input$basemap, selected_basemap)) return() apply_label_visibility(maplibre_proxy("station_map"), input$show_labels) style_change_trigger(style_change_trigger() + 1) })) }, error = function(e) NULL) }, delay = 1.0) } else if (basemap == "sentinel") { proxy %>% set_style(ofm_positron_style, preserve_layers = FALSE) current_session <- session selected_basemap <- basemap later::later(function() { tryCatch({ if (is_session_closed(current_session)) return() shiny::withReactiveDomain(current_session, shiny::isolate({ if (!identical(input$basemap, selected_basemap)) return() unique_suffix <- as.numeric(Sys.time()) * 1000 source_id <- paste0("sentinel_source_", unique_suffix) layer_id <- paste0("sentinel_layer_", unique_suffix) maplibre_proxy("station_map") %>% add_raster_source(id = source_id, tiles = c(sentinel_url), tileSize = 256, attribution = sentinel_attribution) %>% add_layer(id = layer_id, type = "raster", source = source_id, paint = list("raster-opacity" = 1), before_id = "background") for (layer_id_kill in non_label_layer_ids) { tryCatch({ maplibre_proxy("station_map") %>% set_layout_property(layer_id_kill, "visibility", "none") }, error = function(e) {}) } apply_label_visibility(maplibre_proxy("station_map"), input$show_labels) stations_before_id("waterway_line_label") style_change_trigger(style_change_trigger() + 1) })) }, error = function(e) NULL) }, delay = 1.2) } }, ignoreInit = TRUE) observeEvent(input$show_labels, { req(input$basemap %in% c("ofm_positron", "ofm_bright", "sentinel")) apply_label_visibility(maplibre_proxy("station_map"), input$show_labels) }, ignoreInit = TRUE) # Flags map_initialized <- reactiveVal(FALSE) observe({ req(input$station_map_zoom) if (!map_initialized()) { current_session <- session later::later(function() { tryCatch({ if (is_session_closed(current_session)) return() shiny::withReactiveDomain(current_session, shiny::isolate({ map_initialized(TRUE) fly <- pending_map_fly() if (!is.null(fly)) { highlight_station(maplibre_proxy("station_map"), fly$lon, fly$lat, move_map = TRUE) pending_map_fly(NULL) } else if (!is_valid_str(active_station_name())) { eff_c <- effective_country() if (is_valid_str(eff_c) && !identical(eff_c, "All")) { country_sel <- filtered_stations_by_country() if (!is.null(country_sel) && nrow(country_sel) > 0) { maplibre_proxy("station_map") %>% fit_bounds(country_sel, padding = 100, animate = TRUE, maxZoom = 8, max_zoom = 8) } } } })) }, error = function(e) NULL) }, delay = 1.5) } }) # Dynamically update the points layer whenever the filter changes observe({ req(map_initialized()) req(final_filtered_stations()) style_change_trigger() # Trigger re-draw if map style changes session$sendCustomMessage("freezeUI", list(text = "Loading data...")) data <- final_filtered_stations() map <- maplibre_proxy("station_map") if (nrow(data) > 0) { param <- effective_param() time <- effective_time() # Ensure data column exists and extract cleanly if (!is_valid_str(time) || !isTRUE(time %in% colnames(data))) { map %>% clear_layer("wmo_stations") session$sendCustomMessage("unfreezeUI", list()) return() } # Drop stations missing data for the specifically requested Time Period data <- data %>% filter(!is.na(.data[[time]])) if (nrow(data) == 0) { map %>% clear_layer("wmo_stations") session$sendCustomMessage("unfreezeUI", list()) return() } # Determine Color Palette and popups if (is_valid_str(param) && isTRUE(param %in% c("TAVG", "TMAX", "TMIN"))) { bins <- c(-Inf, -35, -30, -25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40, Inf) # ECMWF Magics temperature style: Purple -> Blue -> Cyan -> Green/Yellow -> Orange -> Red -> Dark Red base_cols <- c("#4B0082", "#800080", "#0000FF", "#00FFFF", "#90EE90", "#FFFF00", "#FFA500", "#FF0000", "#8B0000") palette_colors <- colorRampPalette(base_cols)(length(bins) - 1) units <- "°C" label_map <- c(TAVG="Mean Temp", TMAX="Max Temp", TMIN="Min Temp") prefix <- paste(time, label_map[param], sep=" ") } else if (identical(param, "PRCP")) { if (identical(time, "Annual")) { bins <- c(0, 50, 100, 250, 500, 750, 1000, 1500, 2000, 3000, 5000, 10000, Inf) } else { bins <- c(0, 10, 25, 50, 75, 100, 150, 200, 300, 500, 1000, 2000, Inf) } # Exact 12-stage ECMWF precipitation scale (pale green -> magenta -> white) palette_colors <- c("#e4facc", "#aadc8c", "#68b444", "#28841c", "#00734c", "#0096c8", "#0046b4", "#500096", "#b40096", "#ff00b4", "#ffb4ff", "#ffffff") units <- "mm" prefix <- paste(time, "Precip") } else if (identical(param, "DP01")) { if (identical(time, "Annual")) { bins <- c(0, 10, 25, 50, 75, 100, 125, 150, 200, 250, 300, 365) } else { bins <- c(0, 1, 3, 5, 7, 10, 12, 15, 20, 25, 28, 31) } palette_colors <- colorRampPalette(c("#ffffff", "#d0d1e6", "#a6bddb", "#74a9cf", "#3690c0", "#0570b0", "#045a8d", "#023858"))(length(bins) - 1) units <- "days" prefix <- paste(time, "Precip Days") } else if (identical(param, "TSUN")) { if (identical(time, "Annual")) { bins <- c(0, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, Inf) } else { bins <- c(0, 25, 50, 100, 150, 200, 250, 300, 350, Inf) } palette_colors <- colorRampPalette(c("#ffffcc", "#ffeda0", "#fed976", "#feb24c", "#fd8d3c", "#fc4e2a", "#e31a1c", "#bd0026", "#800026"))(length(bins) - 1) units <- "hours" prefix <- paste(time, "Sunshine") } else if (is_valid_str(param) && isTRUE(param %in% c("MSLP", "MNVP"))) { if(identical(param, "MSLP")) { bins <- c(980, 990, 1000, 1005, 1010, 1015, 1020, 1025, 1030, Inf) palette_colors <- colorRampPalette(c("#0000ff", "#4444ff", "#8888ff", "#ffffff", "#ff8888", "#ff4444", "#ff0000", "#880000", "#440000"))(length(bins) - 1) prefix <- paste(time, "Mean SL Pressure") } else { bins <- c(0, 2.5, 5, 7.5, 10, 12.5, 15, 20, 25, 30, Inf) palette_colors <- colorRampPalette(c("#f7fcfd", "#e5f5f9", "#ccece6", "#99d8c9", "#66c2a4", "#41ae76", "#238b45", "#006d2c", "#00441b"))(length(bins) - 1) prefix <- paste(time, "Mean Vapor Pressure") } units <- "hPa" } else { # Fallback bins <- c(-Inf, 0, 100, Inf) palette_colors <- c("gray", "gray", "gray") units <- "" prefix <- paste(time, "Value") } # Let's write a simple R cut() logic instead to give us exact colors pal_fun <- leaflet::colorBin(palette_colors, domain = data[[time]], bins = bins, na.color = "gray") data$color_hex <- pal_fun(data[[time]]) # Popup HTML (just the dynamic Time Period value) elev_label <- ifelse(is.na(data$Elevation), "N/A", paste0(round(data$Elevation, 0), " m")) val_label <- ifelse(is.na(data[[time]]), "N/A", paste(round(data[[time]], 1), units)) data$popup_content <- paste0( "<strong>Station:</strong> ", data$Station_Name, "<br>", "<strong>Country:</strong> ", data$Country, "<br>", "<strong>WMO ID:</strong> ", data$WMO_ID, "<br>", "<strong>Elevation:</strong> ", elev_label, "<br>", "<strong>", prefix, ":</strong> ", val_label ) map %>% clear_layer("wmo_stations") %>% add_circle_layer( id = "wmo_stations", source = data, circle_color = get_column("color_hex"), circle_opacity = 0.8, circle_radius = 5, circle_stroke_color = "#333333", circle_stroke_width = 1, tooltip = "popup_content", before_id = isolate(stations_before_id()) ) # Maintain highlight layer if a station is selected stn_active <- active_station_name() wmo_active <- clicked_wmo_id() if (!is_valid_str(stn_active) && is_valid_str(input$station) && !identical(input$station, "All")) { stn_active <- input$station } if (is_valid_str(stn_active) || is_valid_str(wmo_active)) { target_station <- NULL if (is_valid_str(stn_active) && is_valid_str(wmo_active)) { matches <- data %>% filter(WMO_ID == wmo_active & Station_Name == stn_active) if (nrow(matches) > 0) target_station <- matches[1, ] } if (is.null(target_station) && is_valid_str(stn_active)) { matches <- data %>% filter(Station_Name == stn_active) if (nrow(matches) > 0) target_station <- matches[1, ] } if (is.null(target_station) && is_valid_str(wmo_active)) { matches <- data %>% filter(WMO_ID == wmo_active) if (nrow(matches) > 0) target_station <- matches[1, ] } if (!is.null(target_station) && nrow(target_station) > 0) { highlight_station(map, target_station$Longitude[1], target_station$Latitude[1], move_map = FALSE) } else if (!is.null(active_longitude()) && !is.null(active_latitude())) { highlight_station(map, active_longitude(), active_latitude(), move_map = FALSE) } } else { map %>% clear_layer("selected_highlight") } } else { map %>% clear_layer("wmo_stations") } session$sendCustomMessage("unfreezeUI", list()) }) # ----------------------------------------------------------------------------------- # Dashboard Interaction & Reactivity # ----------------------------------------------------------------------------------- observeEvent(input$station_map_feature_click, { clicked <- input$station_map_feature_click # Check layer ID (support both layer_id and layer) layer_id <- clicked$layer_id if (is.null(layer_id)) layer_id <- clicked$layer if (is.null(layer_id)) return() # If the user clicks the highlight, take them to the Dashboard (fallback) if (layer_id == "selected_highlight") { bslib::nav_select("main_nav", "Dashboard") return() } # If the user clicks a station, highlight it, zoom, AND go to dashboard if (layer_id == "wmo_stations") { props <- clicked$properties click_id <- if (!is.null(props$WMO_ID)) props$WMO_ID else props$wmo_id stn_prop <- if (!is.null(props$Station_Name)) props$Station_Name else NULL if (!is.null(click_id) || !is.null(stn_prop)) { data <- final_filtered_stations() target_station <- NULL if (!is.null(data) && nrow(data) > 0) { if (is_valid_str(stn_prop) && !is.null(click_id)) { matches <- data %>% filter(WMO_ID == click_id & Station_Name == stn_prop) if (nrow(matches) > 0) target_station <- matches[1, ] } if (is.null(target_station) && is_valid_str(stn_prop)) { matches <- data %>% filter(Station_Name == stn_prop) if (nrow(matches) > 0) target_station <- matches[1, ] } if (is.null(target_station) && !is.null(click_id)) { matches <- data %>% filter(WMO_ID == click_id) if (nrow(matches) > 0) target_station <- matches[1, ] } } if (!is.null(target_station)) { pending_tab(NULL) clear_url_station_echo() select_station_helper(target_station, move_map = TRUE) } else { stn_name <- if (!is.null(props$Station_Name)) props$Station_Name else as.character(click_id) stn_country <- if (!is.null(props$Country)) props$Country else "" sta_lon <- if (!is.null(props$Longitude)) as.numeric(props$Longitude) else clicked$lng sta_lat <- if (!is.null(props$Latitude)) as.numeric(props$Latitude) else clicked$lat sta_elev <- if (!is.null(props$Elevation)) suppressWarnings(as.numeric(props$Elevation)) else NA fallback_row <- data.frame( WMO_ID = if (!is.null(click_id)) as.character(click_id) else "", Station_Name = as.character(stn_name), Country = as.character(stn_country), Elevation = if (!is.na(sta_elev)) sta_elev else NA_real_, Longitude = as.numeric(sta_lon), Latitude = as.numeric(sta_lat), stringsAsFactors = FALSE ) pending_tab(NULL) clear_url_station_echo() select_station_helper(fallback_row, move_map = TRUE) } } } }) # Render Station Metadata Header mimicking GHCNM output$dashboard_header <- renderUI({ wmo <- clicked_wmo_id() stn <- active_station_name() if (!is_valid_str(wmo) && !is_valid_str(stn)) { return(h4(class="text-muted", "Please click a station on the interactive map to view its complete Normal arrays.")) } norm_p <- effective_period() meta_df <- selected_station_meta() if (!is.null(meta_df) && nrow(meta_df) > 0) { station_name <- if (is_valid_str(meta_df$Station_Name[1])) meta_df$Station_Name[1] else (if (is_valid_str(stn)) stn else as.character(wmo)) country <- if (is_valid_str(meta_df$Country[1])) meta_df$Country[1] else (if (is_valid_str(active_country())) active_country() else "") elev <- if (!is.null(meta_df$Elevation[1]) && !is.na(meta_df$Elevation[1]) && meta_df$Elevation[1] > -500) paste0(round(meta_df$Elevation[1], 0), " m") else "N/A" lat <- if (!is.null(meta_df$Latitude[1]) && !is.na(meta_df$Latitude[1])) round(meta_df$Latitude[1], 3) else "N/A" lon <- if (!is.null(meta_df$Longitude[1]) && !is.na(meta_df$Longitude[1])) round(meta_df$Longitude[1], 3) else "N/A" card( style = "margin-bottom: 20px; border-left: 5px solid #007bff;", card_body( padding = 15, layout_columns( fill = FALSE, col_widths = breakpoints(sm = c(6, 6, 6, 12), lg = c(4, 3, 3, 2)), # Col 1: Station div( strong("Station"), br(), span(if (nzchar(country)) paste0(station_name, " (", country, ")") else station_name, style = "font-size: 1.1rem;"), br(), tags$small(class = "text-muted", paste("WMO ID:", if (is_valid_str(wmo)) wmo else meta_df$WMO_ID[1])) ), # Col 2: Location div( strong("Location"), br(), span(if (nzchar(country)) country else "N/A"), br(), tags$small(class = "text-muted", if (lat != "N/A" && lon != "N/A") paste0(lat, "°N, ", lon, "°E") else "Coordinates N/A") ), # Col 3: Technical div( strong("Technical"), br(), span(paste0("Elevation: ", elev)), br(), span(class = "badge bg-primary", paste("WMO Normals", norm_p)) ), # Col 4: Actions div( class = "d-flex align-items-center justify-content-end", downloadButton( "download_normals", label = "Export CSV", class = "btn-sm btn-outline-primary", icon = icon("file-csv") ) ) ) ) ) } else { h4(class="text-danger", "Station metadata not found in primary composite matrices.") } }) # Cross-Dataset Extraction station_dashboard_data <- reactive({ req(is_valid_str(clicked_wmo_id()) || is_valid_str(active_station_name())) sid <- clicked_wmo_id() stn <- active_station_name() norm_p <- effective_period() extract_param <- function(df_sf, param_name) { if(is.null(df_sf) || inherits(df_sf, "sfc") || nrow(df_sf) == 0) return(NULL) df <- st_drop_geometry(df_sf) row <- if (is_valid_str(stn) && is_valid_str(sid)) { r <- df %>% filter(WMO_ID == sid & Station_Name == stn) if (nrow(r) > 0) r else { r_stn <- df %>% filter(Station_Name == stn) if (nrow(r_stn) > 0) r_stn else df %>% filter(WMO_ID == sid) } } else if (is_valid_str(stn)) { df %>% filter(Station_Name == stn) } else { df %>% filter(WMO_ID == sid) } if(nrow(row) == 0) return(NULL) res <- data.frame(Parameter = param_name, stringsAsFactors = FALSE) cols <- c(month.abb, "Annual") for(m in cols) { val <- if(m %in% colnames(row)) row[[m]][1] else NA res[[m]] <- if (is.na(val) || val <= -99) NA else round(as.numeric(val), 1) } return(res) } res_list <- list( extract_param(get_wmo_dataset(norm_p, "TAVG"), "Mean Temperature (°C)"), extract_param(get_wmo_dataset(norm_p, "TMAX"), "Max Temperature (°C)"), extract_param(get_wmo_dataset(norm_p, "TMIN"), "Min Temperature (°C)"), extract_param(get_wmo_dataset(norm_p, "PRCP"), "Precipitation (mm)"), extract_param(get_wmo_dataset(norm_p, "DP01"), "Precipitation Days (>=1mm)"), extract_param(get_wmo_dataset(norm_p, "MSLP"), "Mean Sea Level Pressure (hPa)"), extract_param(get_wmo_dataset(norm_p, "MNVP"), "Mean Vapor Pressure (hPa)"), extract_param(get_wmo_dataset(norm_p, "TSUN"), "Sunshine Duration (hours)") ) # Filter out NULL elements final_list <- Filter(Negate(is.null), res_list) if (length(final_list) == 0) return(NULL) final_df <- do.call(rbind, final_list) return(final_df) }) # Output the table beautifully output$dashboard_data <- DT::renderDataTable({ df <- station_dashboard_data() if (is.null(df) || !is.data.frame(df) || nrow(df) == 0) { norm_p <- effective_period() stn_name <- if (is_valid_str(active_station_name())) active_station_name() else clicked_wmo_id() return(DT::datatable( data.frame(Notice = paste0("No climatological normal records found for station '", stn_name, "' in the ", norm_p, " baseline period.")), options = list(dom = 't', paging = FALSE, ordering = FALSE), rownames = FALSE, class = 'display compact cell-border stripe' )) } DT::datatable( df, options = list( dom = 't', paging = FALSE, ordering = FALSE, scrollX = TRUE ), rownames = FALSE, class = 'display compact cell-border stripe hover' ) %>% DT::formatStyle( 'Parameter', fontWeight = 'bold', backgroundColor = '#f4f6f9', borderRight = '2px solid #ddd' ) %>% DT::formatStyle( 'Annual', fontWeight = 'bold', color = '#0056b3', borderLeft = '2px solid #ddd' ) }, server = FALSE) # ----------------------------------------------------------------------------------- # Data Export & Plotly Graphing # ----------------------------------------------------------------------------------- # Download Handler output$download_normals <- downloadHandler( filename = function() { sid <- clicked_wmo_id() stn <- active_station_name() norm_p <- effective_period() id_part <- if (is_valid_str(sid)) gsub("[^A-Za-z0-9_-]", "_", sid) else (if (is_valid_str(stn)) gsub("[^A-Za-z0-9_-]", "_", stn) else "station") paste0("WMO_Normals_", norm_p, "_", id_part, ".csv") }, content = function(file) { df <- station_dashboard_data() if (is.null(df) || !is.data.frame(df)) df <- data.frame(Notice = "No records found") write.csv(df, file, row.names = FALSE) } ) # Reactive: compute all station plots as a named list station_plots <- reactive({ df <- station_dashboard_data() if (is.null(df) || !is.data.frame(df) || nrow(df) == 0) return(list()) wmo <- clicked_wmo_id() stn <- active_station_name() norm_p <- effective_period() find_name <- function(df_sf) { if (!inherits(df_sf, "sf") || nrow(df_sf) == 0) return(NULL) d <- st_drop_geometry(df_sf) if (is_valid_str(stn) && is_valid_str(wmo)) { r <- d %>% filter(WMO_ID == wmo & Station_Name == stn) if (nrow(r) > 0) return(r$Station_Name[1]) } if (is_valid_str(stn)) { r <- d %>% filter(Station_Name == stn) if (nrow(r) > 0) return(r$Station_Name[1]) } if (is_valid_str(wmo)) { r <- d %>% filter(WMO_ID == wmo) if (nrow(r) > 0) return(r$Station_Name[1]) } NULL } s_name <- if (is_valid_str(stn)) { stn } else { n <- find_name(get_wmo_dataset(norm_p, "TAVG")) if (is.null(n)) n <- find_name(get_wmo_dataset(norm_p, "PRCP")) if (is.null(n)) n <- find_name(active_dataset()) if (!is.null(n)) n else as.character(wmo) } render_station_plots(df, s_name) }) # Dynamic plot grid: only show panels for available parameters output$plots_grid <- renderUI({ plots <- station_plots() norm_p <- effective_period() stn <- active_station_name() wmo <- clicked_wmo_id() # Canonical order of parameters plot_order <- c("walter_lieth", "temperature", "prcp", "dp01", "mslp", "mnvp", "tsun") available <- plot_order[plot_order %in% names(plots)] if (length(available) == 0) { stn_name <- if (is_valid_str(stn)) stn else as.character(wmo) return(div( class = "alert alert-light text-center border mt-3 p-4", h5(class = "text-muted", "No Climatograms Available"), p(class = "text-muted mb-0", paste0("No climatological normal parameters found for station '", stn_name, "' in the ", norm_p, " baseline period.")) )) } # Heights per plot type heights <- c(walter_lieth = "380px", temperature = "380px", prcp = "340px", dp01 = "340px", mslp = "340px", mnvp = "340px", tsun = "340px") # Build rows of 2 columns, only for available plots rows <- list() for (i in seq(1, length(available), by = 2)) { h <- heights[available[i]] cols <- list(column(6, plotlyOutput(paste0("dyn_", available[i]), height = h))) if (i + 1 <= length(available)) { cols[[2]] <- column(6, plotlyOutput(paste0("dyn_", available[i + 1]), height = heights[available[i + 1]])) } else { cols[[2]] <- column(6) } rows[[length(rows) + 1]] <- do.call(fluidRow, cols) } do.call(tagList, rows) }) # Render each plot output statically once per session to prevent observer accumulation / memory leak for (pname in c("walter_lieth", "temperature", "prcp", "dp01", "mslp", "mnvp", "tsun")) { local({ my_name <- pname output[[paste0("dyn_", my_name)]] <- renderPlotly({ plots <- station_plots() req(my_name %in% names(plots)) plots[[my_name]] }) }) } # ----------------------------------------------------------------------------------- # Dataset Version Controller & Info Box # ----------------------------------------------------------------------------------- output$dataset_info_box <- renderUI({ norm_p <- effective_period() period_title <- switch(norm_p, "1991-2020" = "1991–2020 (Current Standard)", "1981-2010" = "1981–2010 (Previous Standard)", "1961-1990" = "1961–1990 (Reference Baseline)", norm_p ) source_desc <- switch(norm_p, "1991-2020" = "WMO Standard Normals (NCEI Accession 0253808)", "1981-2010" = "WMO Standard Normals (NCEI Archive)", "1961-1990" = "WMO-No. 847 / CLINO Reference Normals", "WMO Climatological Normals" ) stns_data <- filtered_stations_by_country() stns_count <- if (!is.null(stns_data) && inherits(stns_data, "sf")) nrow(stns_data) else 0 div( class = "data-info-box", div(class = "data-info-title", "Dataset Information"), div(class = "data-info-item", span(class = "fw-bold", "Reference Period:"), paste(" ", period_title)), div(class = "data-info-item", span(class = "fw-bold", "Source:"), paste(" ", source_desc)), div(class = "data-info-item", span(class = "fw-bold", "Stations:"), paste(" ", format(stns_count, big.mark = ","))), if (identical(norm_p, "1991-2020")) { uiOutput("dataset_update_status") } else { div( class = "mt-2", div(class = "data-info-item mb-1", span(class = "fw-bold", "Archive Status:"), " Historical Reference Baseline"), div(class = "mt-1", span(class = "badge bg-secondary", "Frozen Archive")) ) } ) }) output$dataset_update_status <- renderUI({ status_info <- get_dataset_status() local_txt <- if (!is.na(status_info$local_date)) as.character(status_info$local_date) else "Unknown" online_txt <- if (!is.na(status_info$online_date)) as.character(status_info$online_date) else "Pending/Error" badge_class <- "bg-secondary" status_msg <- "Checking..." if (status_info$status == "Up-to-date") { badge_class <- "bg-success" status_msg <- "Up to date" } else if (status_info$status == "Update Available") { badge_class <- "bg-warning text-dark" status_msg <- "Update Available" } else if (status_info$status == "Unknown") { badge_class <- "bg-secondary" status_msg <- "Status Unknown" } div( class = "mt-2", div(class = "data-info-item mb-1", span(class = "fw-bold", "NOAA latest update:"), paste(" ", online_txt)), div(class = "mt-1", span(class = paste("badge", badge_class), status_msg)) ) }) }
server <- function(input, output, session) {
# Defensive string validator
is_valid_str <- function(x) !is.null(x) && length(x) > 0 && !is.na(x[1]) && nzchar(trimws(as.character(x[1])))
normalize_period_param <- function(x) {
if (!is_valid_str(x)) return(NULL)
p <- gsub("[\u2013\u2014_]", "-", trimws(as.character(x[1])))
m <- regmatches(p, regexpr("((?:19|20)\\d{2})\\s*-\\s*((?:19|20)\\d{2})", p, perl = TRUE))
if (length(m) > 0 && nzchar(m[1])) {
return(gsub("\\s+", "", m[1]))
}
p
}
normalize_tab_param <- function(x) {
if (!is_valid_str(x)) return(NULL)
v <- tolower(trimws(as.character(x[1])))
switch(v,
"map" = "Map View",
"map view" = "Map View",
"dashboard" = "Dashboard",
"dashboard-plots" = "Dashboard",
"dashboard-data" = "Dashboard",
NULL
)
}
# Map Initialization Variables
initial_lng <- 0
initial_lat <- 30
initial_zoom <- 3
# Show loading spinner on startup until stations are drawn
session$sendCustomMessage("freezeUI", list(text = "Loading stations..."))
# URL Deep-Linking & Station State
pending_station <- reactiveVal(NULL)
pending_country <- reactiveVal(NULL)
pending_tab <- reactiveVal(NULL)
active_station_name <- reactiveVal(NULL)
active_country <- reactiveVal(NULL)
active_elevation <- reactiveVal(NULL)
active_longitude <- reactiveVal(NULL)
active_latitude <- reactiveVal(NULL)
clicked_wmo_id <- reactiveVal(NULL)
skip_country_clear <- reactiveVal(FALSE)
url_initialized <- reactiveVal(FALSE)
pending_map_fly <- reactiveVal(NULL)
# Token-guarded echo state for async client widget round-trips
pending_url_period_echo <- reactiveVal(NULL)
url_period_echo_token <- reactiveVal(0L)
pending_url_param_echo <- reactiveVal(NULL)
url_param_echo_token <- reactiveVal(0L)
pending_url_time_echo <- reactiveVal(NULL)
url_time_echo_token <- reactiveVal(0L)
pending_url_country_echo <- reactiveVal(NULL)
url_country_echo_token <- reactiveVal(0L)
pending_url_station_echo <- reactiveVal(NULL)
url_station_echo_token <- reactiveVal(0L)
is_session_closed <- function(sess = session) {
tryCatch(!is.null(sess) && is.function(sess$isClosed) && isTRUE(sess$isClosed()), error = function(e) FALSE)
}
schedule_post_flush <- function(fn, delay_sec) {
current_session <- session
run_later <- function() {
if (is_session_closed(current_session)) return()
later::later(function() {
tryCatch({
if (is_session_closed(current_session)) return()
shiny::withReactiveDomain(current_session, shiny::isolate(fn()))
}, error = function(e) NULL)
}, delay_sec)
}
if (!is.null(current_session) && is.function(current_session$onFlushed)) {
current_session$onFlushed(run_later, once = TRUE)
} else {
run_later()
}
}
arm_token_rv <- function(val_rv, tok_rv, value, clear_value, duration) {
tok <- isolate(tok_rv()) + 1L
tok_rv(tok)
val_rv(value)
schedule_post_flush(function() {
if (identical(isolate(tok_rv()), tok)) {
val_rv(clear_value)
}
}, duration)
}
clear_token_rv <- function(val_rv, tok_rv, clear_value) {
tok_rv(isolate(tok_rv()) + 1L)
val_rv(clear_value)
}