# server.R server <- function(input, output, session) { stations <- reactive({ st <- get_imgw_stations() if (!"station_uid" %in% names(st)) { st$station_uid <- paste(st$id, st$name, sep = "|") } st }) # Map state style_change_trigger <- reactiveVal(0) stations_before_id <- reactiveVal("waterway_line_label") current_raster_layers <- reactiveVal(character(0)) map_initialized <- reactiveVal(FALSE) # Dashboard station state current_station_uid <- reactiveVal(NULL) station_data <- reactiveVal(NULL) station_fetching <- reactiveVal(FALSE) station_fetch_message <- reactiveVal("") station_fetch_error <- reactiveVal(NULL) prev_dates <- reactiveVal(NULL) monthly_auto_shifted <- reactiveVal(FALSE) active_fetch_dates <- reactiveVal(NULL) # Fetch Async State Machine Variables fetch_stage <- reactiveVal(0) # 0=Idle, 1=Init, 2=Next, 4=Download/Parse, 6=Merge fetch_queue <- reactiveVal(NULL) fetch_queue_idx <- reactiveVal(0) parsed_data_list <- reactiveVal(list()) fetch_current_token <- reactiveVal(NULL) # Track if URL params have been applied url_initialized <- reactiveVal(FALSE) has_url_dates <- reactiveVal(FALSE) is_session_closed <- function(sess = session) { tryCatch(!is.null(sess) && is.function(sess$isClosed) && isTRUE(sess$isClosed()), error = function(e) FALSE) } # Map bounds for Poland map_bounds <- list( lng_min = 14.0, lat_min = 49.0, lng_max = 24.5, lat_max = 55.0 ) # --- Midnight Rollover: keep end date current across days --- # The default_end_date in global.R is frozen at container startup. # This handles TWO scenarios: # A) New session opened days after container start → fix on session init # B) Long-lived session staying open past midnight → fix via hourly poll # Poll every hour for scenario B day_tick <- reactiveTimer(3600000) observe({ day_tick() # re-fire every hour # Also depend on url_initialized so we fire once on session start req(url_initialized(), input$date_range) if (identical(isolate(selected_resolution()), "monthly")) { return() } if (isTRUE(has_url_dates())) { return() } pd_cur <- isolate(prev_dates()) if (!is.null(pd_cur) && length(pd_cur) >= 2 && !any(is.na(pd_cur)) && length(input$date_range) >= 2 && !any(is.na(input$date_range)) && !identical(as.Date(pd_cur[1:2]), as.Date(input$date_range[1:2]))) { return() } today <- Sys.Date() # Read current end date from the widget, coerce explicitly to Date current_end <- tryCatch(as.Date(input$date_range[2]), error = function(e) NA) if (is.null(current_end) || is.na(current_end)) { return() } # Only auto-advance if the end date is in the past (stale) if (current_end >= today) { return() } # Only auto-advance if end date is very recent (within 2 days of today). # This handles genuine midnight rollover (session stayed open past midnight) # without resetting intentionally historical date ranges chosen by the user. days_behind <- as.numeric(difftime(today, current_end, units = "days")) if (!is.na(days_behind) && days_behind > 2) { return() } # Maintain the same window width (start -> end distance) current_start <- tryCatch(as.Date(input$date_range[1]), error = function(e) today - 366) window_days <- as.numeric(difftime(current_end, current_start, units = "days")) new_end <- today new_start <- new_end - window_days message( "[midnight-rollover] Updating date range: ", current_end, " -> ", new_end, " (start: ", current_start, " -> ", new_start, ")" ) updateDateRangeInput(session, "date_range", start = new_start, end = new_end, max = today ) prev_dates(c(new_start, new_end)) }) # --- Loading State & Freeze Window --- loading_status <- reactiveVal(FALSE) selected_county <- reactiveVal("All") selected_resolution <- reactiveVal("daily") suppress_next_county_effect <- reactiveVal(FALSE) suppress_selectize_empty <- reactiveVal(FALSE) selectize_suppress_token <- reactiveVal(0L) client_station_synced <- reactiveVal(NULL) arm_suppress_selectize <- function(duration = 1.5) { tok <- isolate(selectize_suppress_token()) + 1L selectize_suppress_token(tok) suppress_selectize_empty(TRUE) current_session <- session session$onFlushed(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({ if (identical(selectize_suppress_token(), tok)) { suppress_selectize_empty(FALSE) } })) }, error = function(e) NULL) }, duration) }, once = TRUE) } clear_suppress_selectize <- function() { selectize_suppress_token(isolate(selectize_suppress_token()) + 1L) suppress_selectize_empty(FALSE) } has_county_filter <- function(val) { is_valid_str(val) && !identical(trimws(as.character(val[1])), "All") } set_county_filter <- function(val, update_input = TRUE, suppress_effect = FALSE) { clean_val <- if (has_county_filter(val)) as.character(val[1]) else "All" if (isTRUE(suppress_effect) && isTRUE(isolate(url_initialized())) && !identical(isolate(selected_county()), clean_val)) { suppress_next_county_effect(TRUE) } selected_county(clean_val) if (isTRUE(update_input)) { updateSelectizeInput(session, "county_filter", selected = clean_val) } } # Observer: Freeze UI during loading observe({ is_loading <- loading_status() # List of inputs to disable/enable inputs_to_toggle <- c( "county_filter", "temporal_resolution", "date_range", "zoom_home", "main_nav", "basemap", "show_labels", "stations_table" # Also disable table interaction if possible (though specific row clicks are hard to prevent, visual disable is good) ) if (is_loading) { for (inp in inputs_to_toggle) { shinyjs::disable(inp) } # Optional: Show a global loading notification or overlay if desired, # but the inputs being disabled is the primary visual cue + the spinner in dashboard. } else { for (inp in inputs_to_toggle) { shinyjs::enable(inp) } } }) # Helper: Parse URL query string parse_url_params <- function(query_string) { if (is.null(query_string) || query_string == "" || query_string == "?") { return(list()) } # Remove leading "?" qs <- sub("^\\?", "", query_string) if (qs == "") { return(list()) } pairs <- strsplit(qs, "&")[[1]] params <- list() for (pair in pairs) { kv <- strsplit(pair, "=")[[1]] if (length(kv) == 2) { params[[kv[1]]] <- URLdecode(kv[2]) } } params } imgw_coalesce_code <- function(id_val, id_9_val) { v1 <- if (!is.null(id_val) && length(id_val) > 0 && !is.na(id_val[1]) && nzchar(trimws(as.character(id_val[1])))) trimws(as.character(id_val[1])) else NULL if (!is.null(v1)) return(v1) if (!is.null(id_9_val) && length(id_9_val) > 0 && !is.na(id_9_val[1]) && nzchar(trimws(as.character(id_9_val[1])))) trimws(as.character(id_9_val[1])) else NULL } imgw_disambiguated_slug <- function(name_val, id_val, id_9_val, st_all) { if (!is_valid_str(name_val)) return(NULL) base_slug <- imgw_slugify(name_val) if (is.null(st_all) || nrow(st_all) == 0 || !"name" %in% names(st_all)) return(base_slug) dup_count <- sum(imgw_slugify(st_all$name) == base_slug, na.rm = TRUE) if (dup_count > 1L) { code_part <- imgw_coalesce_code(id_val, id_9_val) if (!is.null(code_part)) { return(paste0(base_slug, "-", imgw_slugify(code_part))) } } base_slug } latest_monthly_archive_date <- function() { cur_yr <- as.integer(format(Sys.Date(), "%Y")) dirs <- tryCatch( imgw_list_source_dirs(imgw_raw_sources$monthly$synop$base_url), error = function(e) character(0) ) yr_nums <- integer(0) for (d in dirs) { yr <- imgw_parse_year_range(d) if (!is.na(yr[["end_year"]])) yr_nums <- c(yr_nums, as.integer(yr[["end_year"]])) } yr_nums <- yr_nums[yr_nums <= cur_yr] max_yr <- if (length(yr_nums) > 0) max(yr_nums, na.rm = TRUE) else (cur_yr - 2L) as.Date(sprintf("%04d-12-31", max_yr)) } # Helper to calculate and enforce resolution span & archive availability bounds check_and_limit_dates <- function(start, end, resolution, anchor = "end", from_resolution_switch = FALSE) { res_norm <- if (is_valid_str(resolution)) tolower(trimws(as.character(resolution[1]))) else "daily" if (identical(res_norm, "monthly")) { latest_m <- latest_monthly_archive_date() if (end > latest_m) { if (isTRUE(from_resolution_switch) || start > latest_m || as.numeric(latest_m - start) < 365) { new_end <- latest_m new_start <- new_end - 2191 return(list( start = new_start, end = new_end, limited = TRUE, clamped_monthly_archive = TRUE, msg = paste0("latest published monthly archives (through ", format(latest_m, "%Y"), ")") )) } else { new_end <- latest_m new_start <- if (as.numeric(new_end - start) > 2191) new_end - 2191 else start return(list( start = new_start, end = new_end, limited = TRUE, clamped_monthly_archive = FALSE, msg = paste0("latest published monthly archives (through ", format(latest_m, "%Y"), ")") )) } } } limit_days <- Inf limit_msg <- "" if (identical(res_norm, "hourly")) { limit_days <- 93 limit_msg <- "3 months" } else if (identical(res_norm, "daily")) { limit_days <- 366 limit_msg <- "1 year" } else if (identical(res_norm, "monthly")) { limit_days <- 2191 limit_msg <- "6 years" } diff <- as.numeric(end - start) if (diff > limit_days) { new_start <- start new_end <- end if (anchor == "start") { new_end <- start + limit_days } else { new_start <- end - limit_days } return(list(start = new_start, end = new_end, limited = TRUE, clamped_monthly_archive = FALSE, msg = limit_msg)) } return(list(start = start, end = end, limited = FALSE, clamped_monthly_archive = FALSE, msg = "")) } # Authoritative date range (reflects server-clamped prev_dates immediately without waiting for client round-trip) effective_date_range <- reactive({ pd <- prev_dates() if (!is.null(pd) && length(pd) >= 2 && !any(is.na(pd))) { d1 <- tryCatch(as.Date(pd[1]), error = function(e) NA) d2 <- tryCatch(as.Date(pd[2]), error = function(e) NA) if (!is.na(d1) && !is.na(d2)) { return(c(d1, d2)) } } dr <- input$date_range if (!is.null(dr) && length(dr) >= 2) { d1 <- tryCatch(as.Date(dr[1]), error = function(e) NA) d2 <- tryCatch(as.Date(dr[2]), error = function(e) NA) if (!is.na(d1) && !is.na(d2)) { return(c(d1, d2)) } } c(default_start_date, default_end_date) }) # Helper: Broadcast current state to parent page broadcast_state <- function(view_override = NULL) { st <- tryCatch(isolate(selected_station()), error = function(e) NULL) res_key <- tryCatch(isolate(resolution_key()), error = function(e) "daily") st_all <- tryCatch(isolate(stations()), error = function(e) NULL) # Extract scalar values from tibble row (coalescing 9-digit CBDH code when short id is missing) has_st <- !is.null(st) && nrow(st) > 0 station_id <- if (has_st) { imgw_coalesce_code( if ("id" %in% names(st)) st$id[1] else NULL, if ("id_9" %in% names(st)) st$id_9[1] else NULL ) } else NULL station_name <- if (has_st && "name" %in% names(st) && !is.na(st$name[1])) as.character(st$name[1]) else NULL station_uid <- if (has_st && "station_uid" %in% names(st) && is_valid_str(st$station_uid[1])) as.character(st$station_uid[1]) else if (!is.null(station_id) && !is.null(station_name)) paste(station_id, station_name, sep = "|") else NULL station_slug <- if (has_st) { imgw_disambiguated_slug( station_name, if ("id" %in% names(st)) st$id[1] else NULL, if ("id_9" %in% names(st)) st$id_9[1] else NULL, st_all ) } else NULL station_type <- if (has_st && "station_type" %in% names(st) && !is.na(st$station_type[1])) as.character(st$station_type[1]) else NULL landname <- if (has_st && "station_type" %in% names(st) && "data_order" %in% names(st) && !is.na(st$station_type[1]) && !is.na(st$data_order[1])) paste0(st$station_type[1], "-", st$data_order[1]) else NULL elevation <- if (!is.null(st) && nrow(st) > 0 && "elevation" %in% names(st) && !is.na(st$elevation[1])) { suppressWarnings(as.numeric(st$elevation[1])) } else { NULL } lat <- if (!is.null(st) && nrow(st) > 0 && "lat" %in% names(st) && !is.na(st$lat[1])) { round(suppressWarnings(as.numeric(st$lat[1])), 5) } else { NULL } lon <- if (!is.null(st) && nrow(st) > 0 && "lon" %in% names(st) && !is.na(st$lon[1])) { round(suppressWarnings(as.numeric(st$lon[1])), 5) } else { NULL } res_start_col <- paste0("date_start_", res_key) res_end_col <- paste0("date_end_", res_key) overall_start <- if (!is.null(st) && nrow(st) > 0) { if (res_start_col %in% names(st) && !is.na(st[[res_start_col]][1])) { as.character(st[[res_start_col]][1]) } else if ("date_start" %in% names(st) && !is.na(st$date_start[1])) { as.character(st$date_start[1]) } else { NULL } } else { NULL } overall_end <- if (!is.null(st) && nrow(st) > 0) { if (res_end_col %in% names(st) && !is.na(st[[res_end_col]][1])) { as.character(st[[res_end_col]][1]) } else if ("date_end" %in% names(st) && !is.na(st$date_end[1])) { as.character(st$date_end[1]) } else { NULL } } else { NULL } available_params <- if (!is.null(st) && nrow(st) > 0) { order_key <- tolower(trimws(if ("data_order" %in% names(st) && !is.na(st$data_order[1])) as.character(st$data_order[1]) else "")) res_map <- tryCatch(params_by_resolution[[res_key]], error = function(e) NULL) if (!is.null(res_map) && order_key %in% names(res_map)) { unname(res_map[[order_key]]) } else if ("params_summary" %in% names(st) && is_valid_str(st$params_summary[1])) { as.character(st$params_summary[1]) } else if (!is.null(res_map) && "klimat" %in% names(res_map)) { unname(res_map[["klimat"]]) } else { NULL } } else { NULL } active_cf <- isolate(selected_county()) county_val <- if (!is.null(st) && nrow(st) > 0 && "voivodeship" %in% names(st) && is_valid_str(st$voivodeship[1])) { as.character(st$voivodeship[1]) } else if (has_county_filter(active_cf)) { as.character(active_cf[1]) } else { NULL } county_slug <- if (is_valid_str(county_val)) imgw_slugify(county_val) else NULL resolution <- switch(res_key, hourly = "Hourly", daily = "Daily", monthly = "Monthly", "Daily" ) pd <- isolate(prev_dates()) date_range_val <- if (!is.null(pd) && length(pd) >= 2 && !any(is.na(pd))) pd else isolate(input$date_range) start_date <- if (!is.null(date_range_val) && length(date_range_val) >= 1 && !is.na(date_range_val[1])) as.character(date_range_val[1]) else NULL end_date <- if (!is.null(date_range_val) && length(date_range_val) >= 2 && !is.na(date_range_val[2])) as.character(date_range_val[2]) else NULL # Compute total and active station counts and Voivodeship station list st_res <- if (!is.null(st_all) && nrow(st_all) > 0 && res_start_col %in% names(st_all)) { st_all[!is.na(st_all[[res_start_col]]), , drop = FALSE] } else { st_all } st_scope <- if (is_valid_str(county_val) && !is.null(st_res) && "voivodeship" %in% names(st_res)) { st_res[!is.na(st_res$voivodeship) & st_res$voivodeship == county_val, , drop = FALSE] } else { st_res } total_count <- if (!is.null(st_scope)) nrow(st_scope) else 0L active_count <- if (!is.null(st_scope) && nrow(st_scope) > 0 && !is.null(start_date) && !is.null(end_date)) { u_start <- tryCatch(as.Date(start_date), error = function(e) NA) u_end <- tryCatch(as.Date(end_date), error = function(e) NA) s_col <- st_scope[[res_start_col]] e_col <- if (res_end_col %in% names(st_scope)) st_scope[[res_end_col]] else st_scope$date_end if (!is.na(u_start) && !is.na(u_end) && !is.null(s_col)) { sum(!is.na(s_col) & s_col <= u_end & (is.na(e_col) | e_col >= u_start), na.rm = TRUE) } else { total_count } } else { total_count } county_station_list <- if (is.null(station_id) && is_valid_str(county_val) && !is.null(st_scope) && nrow(st_scope) > 0) { st_sorted <- st_scope[order(st_scope$name), , drop = FALSE] lapply(seq_len(nrow(st_sorted)), function(i) { c_id <- imgw_coalesce_code( if ("id" %in% names(st_sorted)) st_sorted$id[i] else NULL, if ("id_9" %in% names(st_sorted)) st_sorted$id_9[i] else NULL ) list( id = c_id, name = as.character(st_sorted$name[i]), slug = imgw_disambiguated_slug( st_sorted$name[i], if ("id" %in% names(st_sorted)) st_sorted$id[i] else NULL, if ("id_9" %in% names(st_sorted)) st_sorted$id_9[i] else NULL, st_all ) ) }) } else { NULL } # Determine current view main_tab <- isolate(input$main_nav) view <- if (!is.null(view_override)) { view_override } else if (!is.null(main_tab)) { if (main_tab == "Map View") { "map" } else if (main_tab == "Stations Info") { "station-info" } else if (main_tab == "Dashboard") { subtab <- isolate(input$dashboard_subtabs) if (!is.null(subtab) && subtab == "Data") { "dashboard-data" } else { "dashboard-plots" } } else { "map" } } else { "map" } session$sendCustomMessage("updateParentURL", list( station = station_id, stationId = station_id, stationUid = station_uid, stationName = station_name, stationSlug = station_slug, stationType = station_type, county = county_val, countySlug = county_slug, voivodeship = county_val, landname = landname, resolution = resolution, view = view, start = start_date, end = end_date, elevation = elevation, lat = lat, lon = lon, overallStart = overall_start, overallEnd = overall_end, availableParams = available_params, activeCount = active_count, totalCount = total_count, countyStationList = county_station_list )) } # Observer: Apply URL params on app startup (runs once) observe({ req(!url_initialized()) # Use invalidateLater to retry if clientData isn't ready yet query <- session$clientData$url_search if (is.null(query)) { # clientData not ready yet — set initialized anyway to unblock url_initialized(TRUE) return() } params <- parse_url_params(query) if (length(params) == 0) { url_initialized(TRUE) broadcast_state() return() } # Apply resolution synchronously via selected_resolution and update UI if (!is.null(params$resolution) && length(params$resolution) > 0 && !is.na(params$resolution[1]) && nzchar(trimws(as.character(params$resolution[1])))) { res_lower <- tolower(trimws(as.character(params$resolution[1]))) if (res_lower %in% c("hourly", "daily", "monthly")) { selected_resolution(res_lower) updateRadioGroupButtons(session, "temporal_resolution", selected = res_lower) } } # Apply Voivodeship / county filter if present in URL url_county_applied <- FALSE raw_county_param <- if (is_valid_str(params$county)) { params$county[1] } else if (is_valid_str(params$voivodeship)) { params$voivodeship[1] } else if (is_valid_str(params$region)) { params$region[1] } else { NULL } if (is_valid_str(raw_county_param)) { all_st <- stations() avail_voiv <- if ("voivodeship" %in% names(all_st)) unique(na.omit(as.character(all_st$voivodeship))) else NULL matched_voiv <- resolve_imgw_voivodeship(raw_county_param, available = avail_voiv) if (is_valid_str(matched_voiv)) { set_county_filter(matched_voiv, update_input = TRUE) url_county_applied <- TRUE } } # Apply date range (validated and clamped against active resolution & monthly archive limits) active_res_init <- isolate(selected_resolution()) if (!active_res_init %in% c("hourly", "daily", "monthly")) active_res_init <- "daily" today <- Sys.Date() init_max_date <- if (identical(active_res_init, "monthly")) latest_monthly_archive_date() else today if (!is.null(params$start) && !is.null(params$end)) { start_date <- tryCatch(as.Date(params$start), error = function(e) NA) end_date <- tryCatch(as.Date(params$end), error = function(e) NA) if (!is.na(start_date) && !is.na(end_date)) { if (start_date > end_date) { tmp_d <- start_date; start_date <- end_date; end_date <- tmp_d } if (end_date > today) end_date <- today if (start_date > end_date) start_date <- end_date clamped <- check_and_limit_dates(start_date, end_date, active_res_init, anchor = "end", from_resolution_switch = FALSE) has_url_dates(TRUE) monthly_auto_shifted(isTRUE(clamped$clamped_monthly_archive)) prev_dates(c(clamped$start, clamped$end)) updateDateRangeInput(session, "date_range", start = clamped$start, end = clamped$end, max = init_max_date ) } } else { # No URL dates — choose resolution-appropriate active window if (identical(active_res_init, "hourly")) { new_end <- today new_start <- new_end - 90 monthly_auto_shifted(FALSE) } else if (identical(active_res_init, "monthly")) { new_end <- init_max_date new_start <- new_end - 2191 monthly_auto_shifted(TRUE) } else { new_end <- today new_start <- new_end - 366 monthly_auto_shifted(FALSE) } prev_dates(c(new_start, new_end)) updateDateRangeInput(session, "date_range", start = new_start, end = new_end, max = init_max_date ) } # Apply station selection (scoped to matched voivodeship first for duplicate names, falling back to full catalog) url_station_applied <- FALSE if (is_valid_str(params$station)) { station <- trimws(as.character(params$station[1])) all_stations <- stations() find_station_match <- function(pool) { if (is.null(pool) || nrow(pool) == 0) return(pool) prefer_active <- function(cand) { if (nrow(cand) <= 1) return(cand) is_act <- is.na(cand$date_end) cand[order(!is_act, cand$date_end, decreasing = FALSE, na.last = FALSE), , drop = FALSE][1, , drop = FALSE] } m <- pool[pool$station_uid == station, , drop = FALSE] if (nrow(m) > 0) return(prefer_active(m)) st_slug <- imgw_slugify(station) if (nzchar(st_slug)) { disambig <- vapply(seq_len(nrow(pool)), function(i) { imgw_disambiguated_slug(pool$name[i], pool$id[i], pool$id_9[i], all_stations) %||% "" }, character(1)) m <- pool[disambig == st_slug, , drop = FALSE] if (nrow(m) > 0) return(prefer_active(m)) } m <- pool[(!is.na(pool$id) & pool$id == station) | (!is.na(pool$id_9) & pool$id_9 == station), , drop = FALSE] if (nrow(m) > 0) return(prefer_active(m)) m <- pool[!is.na(pool$name) & pool$name == station, , drop = FALSE] if (nrow(m) > 0) return(prefer_active(m)) if (nzchar(st_slug)) { m <- pool[imgw_slugify(pool$name) == st_slug, , drop = FALSE] if (nrow(m) > 0) return(prefer_active(m)) } pool[0, , drop = FALSE] } cf_init <- isolate(selected_county()) st <- if (has_county_filter(cf_init) && "voivodeship" %in% names(all_stations)) { pool_v <- all_stations[!is.na(all_stations$voivodeship) & all_stations$voivodeship == cf_init, , drop = FALSE] res_v <- find_station_match(pool_v) if (nrow(res_v) > 0) res_v else find_station_match(all_stations) } else { find_station_match(all_stations) } if (nrow(st) > 0) { url_station_applied <- TRUE uid <- if ("station_uid" %in% names(st) && is_valid_str(st$station_uid[1])) { as.character(st$station_uid[1]) } else { paste(imgw_coalesce_code(st$id[1], st$id_9[1]), st$name[1], sep = "|") } cf_now <- isolate(selected_county()) if (has_county_filter(cf_now) && "voivodeship" %in% names(st) && !identical(as.character(st$voivodeship[1]), as.character(cf_now[1]))) { set_county_filter("All", update_input = TRUE, suppress_effect = FALSE) } current_station_uid(uid) shinyjs::delay(200, { current_station_uid(uid) arm_suppress_selectize(1.5) updateSelectizeInput(session, "station_selector", selected = uid) highlight_selected_station(st, move_map = TRUE) }) } } # Apply view/tab navigation (deferred) url_view_override <- NULL if (is_valid_str(params$view)) { view <- as.character(params$view[1]) if (view %in% c("map", "station-info", "dashboard-plots", "dashboard-data")) { url_view_override <- view } shinyjs::delay(600, { if (view == "map") { session$sendCustomMessage("switchTab", list(tabId = "Map View")) } else if (view == "station-info") { session$sendCustomMessage("switchTab", list(tabId = "Stations Info")) } else if (view %in% c("dashboard-plots", "dashboard-data")) { session$sendCustomMessage("switchTab", list(tabId = "Dashboard")) if (view == "dashboard-data") { shinyjs::delay(800, { shinyjs::runjs("$('a[data-value=\"Data\"]').tab('show');") }) } } }) } url_initialized(TRUE) if (url_county_applied && !url_station_applied) { zoom_to_active_extent(force_full_poland = !has_county_filter(isolate(selected_county())), clear_highlight = FALSE) } broadcast_state(view_override = url_view_override) }) resolution_key <- reactive({ res <- selected_resolution() if (is.null(res) || !res %in% c("hourly", "daily", "monthly")) { raw <- input$temporal_resolution res <- if (is_valid_str(raw)) tolower(trimws(as.character(raw[1]))) else "daily" } if (!res %in% c("hourly", "daily", "monthly")) "daily" else res }) params_by_resolution <- list( hourly = c( synop = "Temperature, humidity, wind, pressure, clouds, visibility, precipitation, snow, sunshine, soil", klimat = "Temperature, humidity, wind, clouds, visibility", opad = "Not available for hourly", `tylko dok. papierowe` = "Paper archives only" ), daily = c( synop = "Temperature, precipitation, snow, wind, humidity, pressure, cloudiness, sunshine, weather phenomena, soil", klimat = "Temperature, precipitation, snow, wind, humidity, cloudiness", opad = "Precipitation, snow depth, snowfall type", `tylko dok. papierowe` = "Paper archives only" ), monthly = c( synop = "Temperature, precipitation, snow, sunshine, wind, humidity, cloudiness, weather days", klimat = "Temperature, precipitation, snow, wind, humidity, cloudiness", opad = "Precipitation, snow days, snow cover days", `tylko dok. papierowe` = "Paper archives only" ) ) parse_station_uid <- function(uid) { uid <- as.character(uid)[1] if (is.na(uid) || uid == "") { return(list(id = NA_character_, name = NA_character_)) } if (!grepl("|", uid, fixed = TRUE)) { clean_id <- if (uid == "NA" || !nzchar(uid)) NA_character_ else uid return(list(id = clean_id, name = NA_character_)) } raw_id <- sub("\\|.*$", "", uid) raw_name <- sub("^[^|]*\\|", "", uid) list( id = if (raw_id == "NA" || !nzchar(raw_id)) NA_character_ else raw_id, name = if (raw_name == "NA" || !nzchar(raw_name)) NA_character_ else raw_name ) } build_station_popup <- function(st_row, res = NULL) { if (is.null(res)) res <- resolution_key() if (is.null(st_row) || nrow(st_row) == 0) { return("Station") } resolution_label <- switch(res, hourly = "Hourly", daily = "Daily", monthly = "Monthly", "Daily" ) selected_start <- switch(res, hourly = if ("date_start_hourly" %in% names(st_row)) st_row$date_start_hourly[1] else NA, daily = if ("date_start_daily" %in% names(st_row)) st_row$date_start_daily[1] else NA, monthly = if ("date_start_monthly" %in% names(st_row)) st_row$date_start_monthly[1] else NA, if ("date_start" %in% names(st_row)) st_row$date_start[1] else NA ) selected_end <- switch(res, hourly = if ("date_end_hourly" %in% names(st_row)) st_row$date_end_hourly[1] else NA, daily = if ("date_end_daily" %in% names(st_row)) st_row$date_end_daily[1] else NA, monthly = if ("date_end_monthly" %in% names(st_row)) st_row$date_end_monthly[1] else NA, if ("date_end" %in% names(st_row)) st_row$date_end[1] else NA ) if (is.na(selected_start) && "date_start" %in% names(st_row)) selected_start <- st_row$date_start[1] if (is.na(selected_end) && "date_end" %in% names(st_row)) selected_end <- st_row$date_end[1] if (!is.na(selected_end) && !is.na(selected_start) && selected_end < selected_start) selected_end <- NA start_fmt <- if (is.na(selected_start)) "Unknown" else as.character(selected_start) end_fmt <- if (is.na(selected_end)) "Present" else as.character(selected_end) date_range <- paste0(start_fmt, " to ", end_fmt) station_name <- if ("name" %in% names(st_row)) as.character(st_row$name[1]) else "Unknown" station_id <- if ("id" %in% names(st_row) && !is.na(st_row$id[1]) && nzchar(trimws(as.character(st_row$id[1])))) as.character(st_row$id[1]) else "N/A" station_cbdh <- if ("id_9" %in% names(st_row) && !is.na(st_row$id_9[1]) && nzchar(trimws(as.character(st_row$id_9[1])))) as.character(st_row$id_9[1]) else "N/A" station_type <- if ("station_type" %in% names(st_row)) as.character(st_row$station_type[1]) else "Unknown" voivodeship <- if ("voivodeship" %in% names(st_row) && is_valid_str(st_row$voivodeship[1])) as.character(st_row$voivodeship[1]) else NULL params_summary <- if ("params_summary" %in% names(st_row)) as.character(st_row$params_summary[1]) else "Unknown" elevation <- if ("elevation" %in% names(st_row)) as.character(st_row$elevation[1]) else "" elev_fmt <- if (is.na(elevation) || elevation == "") "N/A" else paste0(elevation, " m") voiv_line <- if (!is.null(voivodeship)) { paste0("Voivodeship: ", htmltools::htmlEscape(voivodeship), "
") } else { "" } paste0( "
", "", htmltools::htmlEscape(station_name), "
", "Code: ", htmltools::htmlEscape(station_id), "
", "CBDH Code: ", htmltools::htmlEscape(station_cbdh), "
", voiv_line, "Type: ", htmltools::htmlEscape(station_type), "
", "Parameters (", resolution_label, "): ", htmltools::htmlEscape(params_summary), "
", "Active: ", date_range, "
", "Elevation: ", elev_fmt, "", "
" ) } # Populate Voivodeship / Region dropdown choices from station metadata observe({ df <- stations() req(!is.null(df) && nrow(df) > 0 && "voivodeship" %in% names(df)) voivs <- sort(unique(na.omit(as.character(df$voivodeship)))) voivs <- voivs[nzchar(trimws(voivs))] choices <- c("All Voivodeships" = "All", setNames(voivs, voivs)) curr_cf <- isolate(selected_county()) sel_cf <- if (has_county_filter(curr_cf) && curr_cf[1] %in% voivs) { as.character(curr_cf[1]) } else { "All" } updateSelectizeInput(session, "county_filter", choices = choices, selected = sel_cf) }) # Sync input$county_filter into selected_county reactiveVal observeEvent(input$county_filter, { cf <- input$county_filter if (!is_valid_str(cf)) { return() } avail_voiv <- tryCatch(isolate(stations()$voivodeship), error = function(e) NULL) resolved <- resolve_imgw_voivodeship(cf[1], available = avail_voiv) target_voiv <- if (is_valid_str(resolved)) resolved else trimws(as.character(cf[1])) if (!identical(isolate(selected_county()), target_voiv)) { selected_county(target_voiv) } }, ignoreNULL = TRUE, ignoreInit = TRUE) filtered_stations <- reactive({ req(stations()) edr <- effective_date_range() req(length(edr) >= 2 && !any(is.na(edr))) st_data <- stations() res <- resolution_key() user_start <- edr[1] user_end <- edr[2] res_start_col <- paste0("date_start_", res) res_end_col <- paste0("date_end_", res) if (!res_end_col %in% names(st_data)) st_data[[res_end_col]] <- st_data$date_end if (!"date_end_hourly" %in% names(st_data)) st_data$date_end_hourly <- st_data$date_end if (!"date_end_daily" %in% names(st_data)) st_data$date_end_daily <- st_data$date_end if (!"date_end_monthly" %in% names(st_data)) st_data$date_end_monthly <- st_data$date_end st_data <- st_data %>% filter( !is.na(!!sym(res_start_col)), !!sym(res_start_col) <= user_end, is.na(!!sym(res_end_col)) | !!sym(res_end_col) >= user_start ) # Filter by Polish Voivodeship (county_filter) cf <- selected_county() if (has_county_filter(cf) && "voivodeship" %in% names(st_data)) { st_data <- st_data %>% filter(!is.na(voivodeship) & voivodeship == as.character(cf[1])) } if (!"data_order" %in% names(st_data)) st_data$data_order <- NA_character_ if (nrow(st_data) > 0) { data_order_trim <- tolower(trimws(st_data$data_order)) params_by_data_order <- params_by_resolution[[res]] params_by_station_type <- c( Synoptic = params_by_data_order[["synop"]], Climatological = params_by_data_order[["klimat"]], Precipitation = params_by_data_order[["opad"]] ) st_data$params_summary <- unname(params_by_data_order[data_order_trim]) missing_params <- is.na(st_data$params_summary) | st_data$params_summary == "" st_data$params_summary[missing_params] <- unname(params_by_station_type[st_data$station_type[missing_params]]) st_data$params_summary[is.na(st_data$params_summary) | st_data$params_summary == ""] <- "Unknown" st_data$station_uid <- paste(st_data$id, st_data$name, sep = "|") } else { st_data$params_summary <- character(0) st_data$station_uid <- character(0) } st_data }) # Selectize for station search (populated from master stations(), filtered only by Voivodeship; # server = FALSE avoids client-side selectize.clear() / transient "" events on choice updates) observe({ df <- stations() req(!is.null(df) && nrow(df) > 0) cf <- selected_county() if (has_county_filter(cf) && "voivodeship" %in% names(df)) { df <- df %>% filter(!is.na(voivodeship) & voivodeship == as.character(cf[1])) } # De-duplicate by station_uid so choices are unique df_unique <- df %>% distinct(station_uid, .keep_all = TRUE) # Create named choices: display "Name (ID)" but value is station_uid if (nrow(df_unique) > 0) { stn_labels <- ifelse(!is.na(df_unique$id) & nzchar(df_unique$id) & df_unique$id != "NA", paste0(df_unique$name, " (", df_unique$id, ")"), df_unique$name) choices <- setNames(df_unique$station_uid, stn_labels) } else { choices <- character(0) } curr_uid <- isolate(current_station_uid()) selected_val <- if (is_valid_str(curr_uid) && curr_uid[1] %in% df_unique$station_uid) { as.character(curr_uid[1]) } else { "" } arm_suppress_selectize(1.5) updateSelectizeInput(session, "station_selector", choices = c("All" = "", choices), selected = selected_val, server = FALSE ) }) # Helper: Compute map bounding box for current Voivodeship filter (or full Poland) get_active_map_bbox <- function(force_full_poland = FALSE) { default_bbox <- c(14.1, 49.0, 24.1, 54.9) if (isTRUE(force_full_poland)) return(default_bbox) cf <- isolate(selected_county()) if (!has_county_filter(cf)) return(default_bbox) df_sub <- tryCatch(isolate(filtered_stations()), error = function(e) NULL) if (is.null(df_sub) || nrow(df_sub) == 0) { st_all <- tryCatch(isolate(stations()), error = function(e) NULL) if (!is.null(st_all) && "voivodeship" %in% names(st_all)) { df_sub <- st_all %>% filter(!is.na(voivodeship) & voivodeship == as.character(cf[1])) } } if (is.null(df_sub) || nrow(df_sub) == 0) return(default_bbox) lons <- suppressWarnings(as.numeric(df_sub$lon)) lats <- suppressWarnings(as.numeric(df_sub$lat)) valid <- !is.na(lons) & !is.na(lats) if (!any(valid)) return(default_bbox) min_lon <- min(lons[valid]) max_lon <- max(lons[valid]) min_lat <- min(lats[valid]) max_lat <- max(lats[valid]) lon_pad <- max(0.15, (max_lon - min_lon) * 0.15) lat_pad <- max(0.10, (max_lat - min_lat) * 0.15) c(min_lon - lon_pad, min_lat - lat_pad, max_lon + lon_pad, max_lat + lat_pad) } zoom_to_active_extent <- function(force_full_poland = FALSE, clear_highlight = FALSE) { bbox <- get_active_map_bbox(force_full_poland = force_full_poland) proxy <- mapgl::maplibre_proxy("map") if (isTRUE(clear_highlight)) { proxy <- proxy %>% mapgl::clear_layer("selected-highlight") } proxy %>% mapgl::fit_bounds(bbox = bbox, animate = TRUE) js_cmd <- sprintf(" setTimeout(function() { if (typeof document !== 'undefined') { document.querySelectorAll('.maplibregl-popup').forEach(function(el) { el.remove(); }); } var mapInstance = null; if (window.HTMLWidgets && HTMLWidgets.find) { var w = HTMLWidgets.find('#map'); if (w && w.getMap) mapInstance = w.getMap(); } if (!mapInstance) { var mapEl = document.getElementById('map'); if (mapEl && mapEl.__mapgl) mapInstance = mapEl.__mapgl; } if (mapInstance) { mapInstance.resize(); mapInstance.fitBounds([[%f, %f], [%f, %f]], { padding: 20, duration: 800 }); } }, 150); ", bbox[1], bbox[2], bbox[3], bbox[4]) shinyjs::runjs(js_cmd) } # --- Centralized Deselection State & Map Reset --- clear_station_selection <- function(jump_to_map = TRUE, reset_county = FALSE) { clear_suppress_selectize() client_station_synced(NULL) current_station_uid(NULL) station_fetch_error(NULL) station_data(NULL) loading_status(FALSE) station_fetching(FALSE) reset_fetch() if (isTRUE(reset_county) && has_county_filter(isolate(selected_county()))) { set_county_filter("All", update_input = TRUE, suppress_effect = TRUE) } sel <- isolate(input$station_selector) if (!is.null(sel) && length(sel) > 0 && !is.na(sel[1]) && nzchar(trimws(as.character(sel[1]))) && !identical(as.character(sel[1]), "All")) { updateSelectizeInput(session, "station_selector", selected = "") } # When deselecting a station while on Dashboard, jump to Map View curr_tab <- isolate(input$main_nav) will_jump <- isTRUE(jump_to_map) && !is.null(curr_tab) && length(curr_tab) > 0 && !is.na(curr_tab[1]) && identical(as.character(curr_tab[1]), "Dashboard") if (will_jump) { bslib::nav_select("main_nav", "Map View") broadcast_state(view_override = "map") } else { broadcast_state() } zoom_to_active_extent(force_full_poland = isTRUE(reset_county), clear_highlight = TRUE) } # React to Voivodeship filter changes: auto-deselect station only if outside selected Voivodeship observeEvent(selected_county(), { if (isTRUE(isolate(suppress_next_county_effect()))) { suppress_next_county_effect(FALSE) return() } target_voiv <- selected_county() has_filter <- has_county_filter(target_voiv) curr_uid <- isolate(current_station_uid()) station_cleared <- FALSE if (has_filter && is_valid_str(curr_uid)) { st_all <- isolate(stations()) st_row <- st_all %>% filter(station_uid == curr_uid[1]) %>% slice(1) if (nrow(st_row) == 0) { parsed <- parse_station_uid(curr_uid[1]) if (!is.na(parsed$id) && nzchar(parsed$id)) { st_row <- st_all %>% filter(id == parsed$id) %>% slice(1) } } if (nrow(st_row) > 0 && "voivodeship" %in% names(st_row)) { if (!identical(as.character(st_row$voivodeship[1]), as.character(target_voiv[1]))) { clear_station_selection(jump_to_map = TRUE) station_cleared <- TRUE } } } if (!station_cleared) { if (!is_valid_str(isolate(current_station_uid()))) { zoom_to_active_extent(force_full_poland = !has_filter, clear_highlight = FALSE) } if (isolate(url_initialized())) { broadcast_state() } } }, ignoreInit = TRUE) 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 Chip UI Overlay on Map output$station_chip_ui <- renderUI({ uid <- current_station_uid() if (is.null(uid) || length(uid) == 0 || is.na(uid[1]) || !nzchar(trimws(as.character(uid[1])))) { return(NULL) } meta <- tryCatch(selected_station(), error = function(e) NULL) if (is.null(meta) || nrow(meta) == 0) return(NULL) elev_num <- if ("elevation" %in% names(meta) && !is.na(meta$elevation[[1]])) { suppressWarnings(as.numeric(as.character(meta$elevation[[1]]))) } else { NA_real_ } elev_val <- if (!is.na(elev_num)) paste0(" (", round(elev_num, 0), " m)") else "" name_val <- if ("name" %in% names(meta) && !is.na(meta$name[[1]])) as.character(meta$name[[1]]) else "" id_val <- if ("id" %in% names(meta) && !is.na(meta$id[[1]])) as.character(meta$id[[1]]) else "" chip_parts <- c() if (nzchar(name_val)) chip_parts <- c(chip_parts, enc2utf8(name_val)) if (nzchar(id_val) && id_val != "NA") chip_parts <- c(chip_parts, id_val) base_label <- if (length(chip_parts) > 0) paste(chip_parts, collapse = " - ") else "Station" chip_label <- paste0(base_label, 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", onclick = "event.stopPropagation(); Shiny.setInputValue('clear_station_chip', Date.now(), {priority: 'event'});", tags$span("Deselect") ) ) }) outputOptions(output, "station_chip_ui", suspendWhenHidden = FALSE) # Handle station selection from dropdown observeEvent(input$station_selector, { stn_id <- input$station_selector if (!is.null(stn_id) && length(stn_id) > 0 && !is.na(stn_id[1]) && nzchar(trimws(as.character(stn_id[1]))) && !identical(as.character(stn_id[1]), "All")) { uid <- as.character(stn_id[1]) client_station_synced(uid) if (!identical(isolate(current_station_uid()), uid)) { clear_suppress_selectize() current_station_uid(uid) station_fetch_error(NULL) st <- selected_station() if (!is.null(st) && nrow(st) > 0) { cf <- isolate(selected_county()) if (has_county_filter(cf) && "voivodeship" %in% names(st) && !identical(as.character(st$voivodeship[1]), as.character(cf[1]))) { set_county_filter("All", update_input = TRUE, suppress_effect = TRUE) } highlight_selected_station(st, move_map = TRUE) } # Trigger broadcast broadcast_state() bslib::nav_select("main_nav", "Dashboard") } } else if (!is.null(stn_id) && length(stn_id) > 0 && !is.na(stn_id[1]) && identical(as.character(stn_id[1]), "All")) { clear_suppress_selectize() client_station_synced(NULL) if (!is.null(isolate(current_station_uid()))) { clear_station_selection(jump_to_map = TRUE) } } else { cur_uid <- isolate(current_station_uid()) if (is.null(cur_uid) || !nzchar(trimws(as.character(cur_uid[1])))) { return() } if (isTRUE(suppress_selectize_empty()) || !identical(as.character(isolate(client_station_synced())), as.character(cur_uid[1]))) { return() } client_station_synced(NULL) clear_station_selection(jump_to_map = TRUE) } }, ignoreInit = TRUE) selected_station <- reactive({ uid <- current_station_uid() if (is.null(uid) || length(uid) == 0 || is.na(uid[1]) || !nzchar(trimws(as.character(uid[1])))) { return(NULL) } # 1. First attempt direct match on filtered_stations by station_uid st_filt <- tryCatch(filtered_stations(), error = function(e) NULL) if (!is.null(st_filt) && "station_uid" %in% names(st_filt)) { row <- st_filt %>% filter(station_uid == uid) %>% slice(1) if (nrow(row) > 0) return(row) } # 2. Fall back to parsing UID and searching full stations() parsed <- parse_station_uid(uid) st <- stations() # If UID has a name, try matching name (and id if available) row <- NULL if (!is.na(parsed$name) && parsed$name != "" && parsed$name != "NA") { if (!is.na(parsed$id) && parsed$id != "" && parsed$id != "NA") { row <- st %>% filter(id == parsed$id, name == parsed$name) %>% slice(1) } else { row <- st %>% filter(name == parsed$name) %>% slice(1) } } # Match by ID alone if ID is valid and name match was not found if ((is.null(row) || nrow(row) == 0) && !is.na(parsed$id) && parsed$id != "" && parsed$id != "NA") { row <- st %>% filter(id == parsed$id) %>% slice(1) } if (!is.null(row) && nrow(row) > 0) { if (!"station_uid" %in% names(row)) { row$station_uid <- uid } return(row) } NULL }) highlight_selected_station <- function(st_row, move_map = TRUE) { req(nrow(st_row) > 0) lon_val <- suppressWarnings(as.numeric(st_row$lon[1])) lat_val <- suppressWarnings(as.numeric(st_row$lat[1])) if (is.na(lon_val) || is.na(lat_val)) { return(invisible(NULL)) } popup_html <- NULL if ("popup_content" %in% names(st_row)) { popup_candidate <- as.character(st_row$popup_content[1]) if (!is.na(popup_candidate) && nzchar(popup_candidate)) { popup_html <- popup_candidate } } if (is.null(popup_html)) { popup_html <- build_station_popup(st_row, res = isolate(resolution_key())) } highlight_df <- data.frame( popup_content = popup_html, lon = lon_val, lat = lat_val, stringsAsFactors = FALSE ) highlight_sf <- sf::st_as_sf(highlight_df, coords = c("lon", "lat"), crs = 4326) proxy <- maplibre_proxy("map") if (move_map) { proxy <- proxy %>% fly_to(center = c(lon_val, lat_val), zoom = 8) } proxy %>% clear_layer("selected-highlight") %>% add_circle_layer( id = "selected-highlight", source = highlight_sf, circle_color = "#e53935", circle_radius = 10, circle_stroke_color = "#b71c1c", circle_stroke_width = 2, circle_opacity = 0.45, tooltip = get_column("popup_content") ) } output$station_count <- renderText({ req(!is.null(filtered_stations())) paste(nrow(filtered_stations()), "stations displayed.") }) # Initialize Map output$map <- renderMaplibre({ maplibre( style = ofm_positron_style, center = c(19.1451, 51.9194), zoom = 5.5 ) %>% add_navigation_control(show_compass = FALSE, visualize_pitch = FALSE, position = "top-left") }) # Invalidate map size when switching to Map View tab observeEvent(input$main_nav, { if (!is.null(input$main_nav) && length(input$main_nav) > 0 && !is.na(input$main_nav[1]) && identical(as.character(input$main_nav[1]), "Map View")) { shinyjs::runjs(" setTimeout(function() { var mapInstance = null; if (window.HTMLWidgets && HTMLWidgets.find) { var w = HTMLWidgets.find('#map'); if (w && w.getMap) mapInstance = w.getMap(); } if (!mapInstance) { var mapEl = document.getElementById('map'); if (mapEl && mapEl.__mapgl) mapInstance = mapEl.__mapgl; } if (mapInstance) { mapInstance.resize(); } }, 150); ") } }) # Zoom to extent of all stations (home button) observeEvent(input$zoom_home, { clear_station_selection(jump_to_map = TRUE, reset_county = TRUE) }) # --- 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 (sometimes used in different versions) "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", # Legacy/Carto/OSM label names (for compatibility) "place_villages", "place_town", "place_country_2", "place_country_1", "place_state", "place_continent", "place_city_r6", "place_city_r5", "place_city_dot_r7", "place_city_dot_r4", "place_city_dot_r2", "place_city_dot_z7", "place_capital_dot_z7", "place_capital", "roadname_minor", "roadname_sec", "roadname_pri", "roadname_major", "motorway_name", "watername_ocean", "watername_sea", "watername_lake", "watername_lake_line", "poi_stadium", "poi_park", "poi_zoo", "airport_label", "country-label", "state-label", "settlement-major-label", "settlement-minor-label", "settlement-subdivision-label", "road-label", "waterway-label", "natural-point-label", "poi-label", "airport-label" ) # Layers to hide in Satellite (Hybrid) mode to let the raster shows through # This includes all non-symbol layers (background, water, roads, boundaries, etc.) 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) { # Layer may not exist in current style, ignore silently } ) } } observeEvent(input$basemap, { proxy <- maplibre_proxy("map") basemap <- input$basemap # Explicitly remove any previously added raster layers old_layers <- isolate(current_raster_layers()) if (length(old_layers) > 0) { for (layer_id in old_layers) { proxy %>% clear_layer(layer_id) } current_raster_layers(character(0)) } if (basemap %in% c("ofm_positron", "ofm_bright")) { # VECTOR LOGIC (OpenFreeMap styles) style_url <- switch(basemap, "ofm_positron" = ofm_positron_style, "ofm_bright" = ofm_bright_style ) proxy %>% set_style(style_url, preserve_layers = FALSE) # For OpenFreeMap sandwich, we want stations below labels stations_before_id("waterway_line_label") current_session <- session selected_basemap <- basemap later::later(function() { tryCatch({ if (is_session_closed(current_session)) return() shiny::withReactiveDomain(current_session, shiny::isolate({ # Race condition check current_basemap <- input$basemap if (!identical(current_basemap, selected_basemap)) { return() } # Trigger re-render of stations and apply label visibility apply_label_visibility(maplibre_proxy("map"), input$show_labels) style_change_trigger(style_change_trigger() + 1) })) }, error = function(e) NULL) }, delay = 0.5) } else if (basemap == "sentinel") { # HYBRID LOGIC (EOX Sentinel-2 Satellite + OpenFreeMap Labels/Roads) # Use Positron as the base for labels/roads 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({ current_basemap <- input$basemap if (!identical(current_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) # Add Sentinel layer at the very bottom (before 'background') maplibre_proxy("map") %>% add_raster_source(id = source_id, tiles = 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" ) # Hide all non-label vector layers so only satellite + symbols show for (layer_id_kill in non_label_layer_ids) { tryCatch( { maplibre_proxy("map") %>% set_layout_property(layer_id_kill, "visibility", "none") }, error = function(e) { # Layer might not exist, ignore } ) } # Ensure labels according to user preference apply_label_visibility(maplibre_proxy("map"), input$show_labels) # Stations should be above the satellite layer stations_before_id("waterway_line_label") current_raster_layers(c(layer_id)) style_change_trigger(style_change_trigger() + 1) })) }, error = function(e) NULL) }, delay = 0.5) } }, ignoreInit = TRUE ) # Auto-refetch and adjust date window when resolution changes (single authoritative handler) observeEvent(input$temporal_resolution, { req(input$temporal_resolution) res_val <- tolower(trimws(as.character(input$temporal_resolution[1]))) if (!res_val %in% c("hourly", "daily", "monthly")) { return() } prev_res <- isolate(selected_resolution()) if (!identical(prev_res, res_val)) { has_url_dates(FALSE) selected_resolution(res_val) } edr <- isolate(effective_date_range()) if (length(edr) < 2 || any(is.na(edr))) return() start <- edr[1] end <- edr[2] if (start > end) { tmp_d <- start; start <- end; end <- tmp_d } today <- Sys.Date() max_date <- if (identical(res_val, "monthly")) latest_monthly_archive_date() else today if (identical(res_val, "monthly")) { res <- check_and_limit_dates(start, end, "monthly", anchor = "end", from_resolution_switch = TRUE) monthly_auto_shifted(isTRUE(res$clamped_monthly_archive)) } else if (identical(prev_res, "monthly") && isTRUE(isolate(monthly_auto_shifted()))) { monthly_auto_shifted(FALSE) new_end <- today new_start <- new_end - (if (identical(res_val, "hourly")) 90 else 366) res <- list(start = new_start, end = new_end, limited = TRUE, silent_restore = TRUE, msg = "") } else { res <- check_and_limit_dates(start, end, res_val, anchor = "end", from_resolution_switch = TRUE) } if (isTRUE(res$limited)) { prev_dates(c(res$start, res$end)) updateDateRangeInput(session, "date_range", start = res$start, end = res$end, max = max_date) if (!isTRUE(res$silent_restore) && nzchar(res$msg)) { showNotification(paste0("Range adjusted to ", res$msg, " for ", res_val, " resolution."), type = "warning") } } else { prev_dates(c(start, end)) updateDateRangeInput(session, "date_range", max = max_date) } if (isTRUE(isolate(url_initialized()))) { broadcast_state() } }, ignoreInit = TRUE ) # Auto-refetch and Smart Limit when Date Range Changes (single authoritative handler) observeEvent(input$date_range, { req(input$date_range) if (length(input$date_range) < 2) return() current_dates <- input$date_range current_start <- tryCatch(as.Date(current_dates[1]), error = function(e) NA) current_end <- tryCatch(as.Date(current_dates[2]), error = function(e) NA) if (is.na(current_start) || is.na(current_end)) { return() } if (current_start > current_end) { tmp_d <- current_start; current_start <- current_end; current_end <- tmp_d } last_dates <- isolate(prev_dates()) if (!is.null(last_dates) && length(last_dates) >= 2 && !any(is.na(last_dates))) { last_pair <- tryCatch(as.Date(last_dates[1:2]), error = function(e) c(NA, NA)) if (!any(is.na(last_pair)) && identical(c(current_start, current_end), last_pair)) { # Programmatic echo from updateDateRangeInput — preserve monthly_auto_shifted flag if (isTRUE(isolate(url_initialized()))) { broadcast_state() } return() } } # Genuine user edit (or testServer setInputs) — clear monthly auto-shift and URL date locks monthly_auto_shifted(FALSE) has_url_dates(FALSE) anchor <- "end" if (!is.null(last_dates) && length(last_dates) >= 2 && !any(is.na(last_dates))) { last_start <- tryCatch(as.Date(last_dates[1]), error = function(e) NA) if (!is.na(last_start) && current_start != last_start) { anchor <- "start" } } active_res <- isolate(resolution_key()) max_date <- if (identical(active_res, "monthly")) latest_monthly_archive_date() else Sys.Date() res <- check_and_limit_dates(current_start, current_end, active_res, anchor = anchor, from_resolution_switch = FALSE) if (isTRUE(res$limited)) { prev_dates(c(res$start, res$end)) updateDateRangeInput(session, "date_range", start = res$start, end = res$end, max = max_date) showNotification(paste0("Range adjusted to ", res$msg, "."), type = "warning") } else { prev_dates(c(current_start, current_end)) } if (isTRUE(isolate(url_initialized()))) { broadcast_state() } }, ignoreInit = TRUE ) # Toggle Labels visibility observeEvent(input$show_labels, { apply_label_visibility(maplibre_proxy("map"), input$show_labels) }, ignoreInit = TRUE ) # Add Stations Layer observe({ req(!is.null(filtered_stations())) style_change_trigger() st_data <- filtered_stations() current_session <- session if (nrow(st_data) == 0) { later::later(function() { tryCatch({ if (is_session_closed(current_session)) return() shiny::withReactiveDomain(current_session, shiny::isolate({ maplibre_proxy("map") %>% clear_layer("stations_layer") %>% clear_layer("selected-highlight") })) }, error = function(e) NULL) }, delay = 1.2) return() } res <- resolution_key() resolution_label <- switch(res, hourly = "Hourly", daily = "Daily", monthly = "Monthly", "Daily" ) st_data$popup_content <- vapply( seq_len(nrow(st_data)), function(i) build_station_popup(st_data[i, , drop = FALSE], res = res), FUN.VALUE = character(1) ) st_sf <- st_as_sf(st_data, coords = c("lon", "lat"), crs = 4326) st_sf$circle_color <- "navy" st_sf$circle_radius <- 6 st_sf$circle_stroke_width <- 0 st_sf$circle_opacity <- 0.7 before_id_value <- stations_before_id() later::later(function() { tryCatch({ if (is_session_closed(current_session)) return() shiny::withReactiveDomain(current_session, shiny::isolate({ maplibre_proxy("map") %>% clear_layer("stations_layer") %>% add_circle_layer( id = "stations_layer", source = st_sf, circle_color = get_column("circle_color"), circle_radius = get_column("circle_radius"), circle_stroke_width = get_column("circle_stroke_width"), circle_opacity = 0.7, tooltip = get_column("popup_content"), before_id = before_id_value ) })) }, error = function(e) NULL) }, delay = 1.2) selected_uid <- isolate(current_station_uid()) if (!is.null(selected_uid) && selected_uid != "") { sel <- st_data %>% filter(station_uid == selected_uid) %>% slice(1) if (nrow(sel) > 0) { later::later(function() { tryCatch({ if (is_session_closed(current_session)) return() shiny::withReactiveDomain(current_session, shiny::isolate({ highlight_selected_station(sel, move_map = FALSE) })) }, error = function(e) NULL) }, delay = 1.25) } else { later::later(function() { tryCatch({ if (is_session_closed(current_session)) return() shiny::withReactiveDomain(current_session, shiny::isolate({ maplibre_proxy("map") %>% clear_layer("selected-highlight") })) }, error = function(e) NULL) }, delay = 1.25) } } }) # Selection from map click observeEvent(input$map_feature_click, { clicked <- input$map_feature_click if (is.null(clicked)) { return() } layer_name <- clicked$layer_id if (is.null(layer_name) || length(layer_name) == 0 || is.na(layer_name[1])) { layer_name <- clicked$layer } if (is.null(layer_name) || length(layer_name) == 0 || is.na(layer_name[1]) || !identical(as.character(layer_name[1]), "stations_layer")) { return() } props <- clicked$properties if (is.null(props)) { return() } uid <- props$station_uid if (is.null(uid) || length(uid) == 0 || is.na(uid[1]) || !nzchar(trimws(as.character(uid[1])))) { id_val <- props$id name_val <- props$name if (!is.null(id_val) && length(id_val) > 0 && !is.na(id_val[1]) && !is.null(name_val) && length(name_val) > 0 && !is.na(name_val[1])) { uid <- paste0(id_val[1], "|", name_val[1]) } else if (!is.null(id_val) && length(id_val) > 0 && !is.na(id_val[1])) { uid <- as.character(id_val[1]) } } if (is.null(uid) || length(uid) == 0 || is.na(uid[1]) || !nzchar(trimws(as.character(uid[1])))) { return() } uid <- as.character(uid)[1] current_station_uid(uid) station_fetch_error(NULL) st <- selected_station() if (!is.null(st) && nrow(st) > 0) { cf <- isolate(selected_county()) if (has_county_filter(cf) && "voivodeship" %in% names(st) && !identical(as.character(st$voivodeship[1]), as.character(cf[1]))) { set_county_filter("All", update_input = TRUE, suppress_effect = TRUE) } highlight_selected_station(st, move_map = TRUE) broadcast_state() } arm_suppress_selectize(1.5) updateSelectizeInput(session, "station_selector", selected = uid) bslib::nav_select("main_nav", "Dashboard") }) # Stations table with double-click selection output$stations_table <- DT::renderDataTable({ req(!is.null(filtered_stations()), input$temporal_resolution) st_data <- filtered_stations() resolution_col <- paste0("date_start_", resolution_key()) end_col <- paste0("date_end_", resolution_key()) if (!end_col %in% names(st_data)) st_data[[end_col]] <- st_data$date_end if (!"voivodeship" %in% names(st_data)) st_data$voivodeship <- NA_character_ display_df <- st_data %>% transmute( UID = station_uid, ID = id, Name = name, Voivodeship = voivodeship, `CBDH Code` = id_9, Type = station_type, Parameters = params_summary, Lat = round(lat, 4), Lon = round(lon, 4), `Elevation (m)` = elevation, `Data Start` = as.character(!!sym(resolution_col)), `Data End` = ifelse(is.na(!!sym(end_col)), "Present", as.character(!!sym(end_col))) ) DT::datatable( display_df, selection = "none", rownames = FALSE, options = list( pageLength = 25, scrollX = TRUE, dom = "frtip", order = list(list(2, "asc")), columnDefs = list(list(visible = FALSE, targets = 0)) ), class = "compact stripe hover", callback = DT::JS(" table.on('dblclick', 'tr', function() { var rowData = table.row(this).data(); if (rowData !== undefined && rowData !== null) { Shiny.setInputValue('table_station_dblclick', rowData[0], {priority: 'event'}); } }); ") ) }) observeEvent(input$table_station_dblclick, { uid <- input$table_station_dblclick req(uid) uid <- as.character(uid)[1] current_station_uid(uid) station_fetch_error(NULL) st <- selected_station() if (!is.null(st) && nrow(st) > 0) { cf <- isolate(selected_county()) if (has_county_filter(cf) && "voivodeship" %in% names(st) && !identical(as.character(st$voivodeship[1]), as.character(cf[1]))) { set_county_filter("All", update_input = TRUE, suppress_effect = TRUE) } highlight_selected_station(st, move_map = TRUE) broadcast_state(view_override = "dashboard-plots") } arm_suppress_selectize(1.5) updateSelectizeInput(session, "station_selector", selected = uid) bslib::nav_select("main_nav", "Dashboard") }) reset_fetch <- function() { fetch_stage(0) station_fetch_message("") fetch_current_token(as.numeric(Sys.time())) session$sendCustomMessage("unfreezeUI", list()) } # Cancel loading handler observeEvent(input$cancel_loading, { loading_status(FALSE) station_fetching(FALSE) reset_fetch() showNotification("Loading cancelled by user.", type = "warning") }) # Group fetch inputs using authoritative server-clamped resolution & date range fetch_trigger <- reactive({ list( uid = current_station_uid(), res = resolution_key(), dr = effective_date_range() ) }) %>% debounce(500) # Fetch station data using the debounced trigger observeEvent(fetch_trigger(), { req(url_initialized()) # Ensure URL params are applied first uid <- current_station_uid() edr <- effective_date_range() req(uid, length(edr) >= 2 && !any(is.na(edr))) st <- selected_station() req(!is.null(st), nrow(st) > 0) station_data(NULL) station_fetching(TRUE) loading_status(TRUE) station_fetch_error(NULL) # Broadcast state on re-fetch broadcast_state() start_date <- edr[1] end_date <- edr[2] active_fetch_dates(c(start_date, end_date)) res <- resolution_key() msg_init <- paste0("Initializing fetch for ", st$name[1], "...") station_fetch_message(msg_init) session$sendCustomMessage("freezeUI", list( text = msg_init, station = st$name[1] )) # Stage 1: Init - Find files queue filesQueue <- imgw_fetch_station_data( station_id = st$id[1], resolution = res, start_date = start_date, end_date = end_date, data_order = st$data_order[1], station_type = st$station_type[1], station_id_9 = st$id_9[1] ) if (is.null(filesQueue) || nrow(filesQueue) == 0) { if (isTRUE(attr(filesQueue, "server_unreachable"))) { station_fetch_error("The IMGW data server (danepubliczne.imgw.pl) is currently unavailable. Please try again later.") } else if (identical(res, "monthly")) { station_fetch_error("No downloadable IMGW monthly archives were found for this station within the selected date range. Try widening the start date to an earlier year.") } else { station_fetch_error("No downloadable IMGW files were found for this station within the selected date range.") } station_fetching(FALSE) loading_status(FALSE) reset_fetch() if (!is.null(isolate(current_station_uid()))) { bslib::nav_select("main_nav", "Dashboard") } return() } fetch_queue(filesQueue) fetch_queue_idx(1) parsed_data_list(list()) fetch_current_token(as.numeric(Sys.time())) fetch_stage(2) # Go to Next }, ignoreInit = TRUE ) # Stage 2: Next File observe({ req(fetch_stage() == 2) q <- fetch_queue() req(!is.null(q) && nrow(q) > 0) idx <- fetch_queue_idx() if (idx > nrow(q)) { fetch_stage(6) # Merge } else { # UI Update item <- q[idx, ] msg <- sprintf("Fetching %s (%d/%d)...", basename(item$url), idx, nrow(q)) station_fetch_message(msg) st <- selected_station() session$sendCustomMessage("freezeUI", list( text = msg, station = if (!is.null(st) && nrow(st) > 0) st$name[1] else "" )) fetch_stage(4) # Download } }) # Stage 4: Download and Parse Configured File observe({ req(fetch_stage() == 4) q <- fetch_queue() req(!is.null(q) && nrow(q) > 0) idx <- fetch_queue_idx() item <- q[idx, ] token <- fetch_current_token() current_session <- session st <- selected_station() res <- resolution_key() # Yield thread later::later(function() { tryCatch({ if (is_session_closed(current_session)) return() shiny::withReactiveDomain(current_session, shiny::isolate({ if (fetch_current_token() != token) { return() } parsed_df <- tryCatch( { imgw_read_station_zip_url( zip_url = item$url, resolution = res, source_type = item$source, station_id = st$id[1], station_id_9 = st$id_9[1] ) }, error = function(e) { message("Error fetching data piece: ", conditionMessage(e)) NULL } ) if (!is.null(parsed_df) && nrow(parsed_df) > 0) { p_list <- parsed_data_list() p_list[[length(p_list) + 1]] <- parsed_df parsed_data_list(p_list) } # Advance fetch_queue_idx(idx + 1) fetch_stage(2) # Back to Next })) }, error = function(e) { message("[Stage 4 later error] ", conditionMessage(e)) if (!is_session_closed(current_session)) { tryCatch(shiny::withReactiveDomain(current_session, shiny::isolate({ station_fetching(FALSE) loading_status(FALSE) fetch_stage(0) current_session$sendCustomMessage("unfreezeUI", list()) })), error = function(err) NULL) } }) }, delay = 0.05) }) # Stage 6: Merge Files observe({ req(fetch_stage() == 6) token <- fetch_current_token() current_session <- session st <- selected_station() afd <- isolate(active_fetch_dates()) edr <- if (!is.null(afd) && length(afd) >= 2 && !any(is.na(afd))) afd else isolate(effective_date_range()) start_date <- edr[1] end_date <- edr[2] res <- resolution_key() msg_merge <- "Merging datasets..." station_fetch_message(msg_merge) session$sendCustomMessage("freezeUI", list( text = msg_merge, station = st$name[1] )) later::later(function() { tryCatch({ if (is_session_closed(current_session)) return() shiny::withReactiveDomain(current_session, shiny::isolate({ if (fetch_current_token() != token) { return() } p_list <- parsed_data_list() merged_df <- tryCatch( { imgw_process_downloaded_parts( parts = p_list, station_id_value = st$id[1], station_id_9_value = st$id_9[1], resolution = res, start_date = start_date, end_date = end_date, data_order = st$data_order[1], station_type = st$station_type[1] ) }, error = function(e) { message("Error merging chunks: ", conditionMessage(e)) NULL } ) if (is.null(merged_df) || nrow(merged_df) == 0) { if (identical(res, "monthly")) { station_fetch_error("No monthly observations found in this date window. IMGW's published monthly archives lag behind daily/hourly feeds — try widening the start date to an earlier year.") } else { station_fetch_error("No valid data rows found after merging files within this date range.") } station_data(NULL) } else { station_data(merged_df) } station_fetching(FALSE) loading_status(FALSE) fetch_stage(0) fetch_current_token(as.numeric(Sys.time())) if (!is.null(merged_df) && nrow(merged_df) > 0) { # Show "Plotting data..." while plots render current_session$sendCustomMessage("freezeUI", list( text = "Plotting data...", station = st$name[1] )) # Unfreeze after Shiny flush + client-side plotly rendering current_session$onFlushed(function() { if (!is_session_closed(current_session)) { current_session$sendCustomMessage("waitForPlots", list()) } }, once = TRUE) } else { current_session$sendCustomMessage("unfreezeUI", list()) } # Navigate to Dashboard only if station is still selected if (!is.null(current_station_uid())) { bslib::nav_select("main_nav", "Dashboard", session = current_session) broadcast_state() } })) }, error = function(e) { message("[Stage 6 later error] ", conditionMessage(e)) if (!is_session_closed(current_session)) { tryCatch(shiny::withReactiveDomain(current_session, shiny::isolate({ station_fetching(FALSE) loading_status(FALSE) fetch_stage(0) current_session$sendCustomMessage("unfreezeUI", list()) })), error = function(err) NULL) } }) }, delay = 0.05) }) # Listen for tab and subtab changes explicitly to broadcast observeEvent(input$main_nav, { req(url_initialized()) broadcast_state() }) observeEvent(input$dashboard_subtabs, { req(url_initialized()) broadcast_state() }) # Dashboard UI states output$dashboard_station_header <- renderUI({ st <- selected_station() if (is.null(st)) { return(NULL) } loaded <- station_data() # Determine Resolution Badge res_label <- switch(resolution_key(), hourly = "Hourly", daily = "Daily", monthly = "Monthly", "Daily" ) res_class <- if (res_label == "Hourly") "bg-primary" else "bg-success" # Data Range Text if (is.null(loaded) || nrow(loaded) == 0) { if (isTRUE(station_fetching())) { dates_text <- "Loading..." } else { dates_text <- "No data loaded" } } else { dates_text <- paste(min(loaded$date, na.rm = TRUE), "to", max(loaded$date, na.rm = TRUE)) dates_text <- paste0(dates_text, " (", nrow(loaded), " rows)") } # Helper for NULL/NA val_safe <- function(x, suffix = "") { if (is.null(x) || is.na(x) || x == "") { return("-") } paste0(x, suffix) } # Render Card card( style = "margin-bottom: 20px; border-left: 5px solid #007bff;", card_body( padding = 15, layout_columns( fill = FALSE, # Col 1: Station div( strong("Station"), br(), span(st$name[1], style = "font-size: 1.1rem;"), br(), tags$small(class = "text-muted", paste("ID:", val_safe(st$id[1]), "| CBDH:", val_safe(st$id_9[1]))) ), # Col 2: Location div( strong("Location"), br(), span(paste0(round(st$lat[1], 4), "\u00b0N, ", round(st$lon[1], 4), "\u00b0E")), br(), tags$small( class = "text-muted", paste0( if ("voivodeship" %in% names(st) && is_valid_str(st$voivodeship[1])) paste0("Voivodeship: ", st$voivodeship[1], " | ") else "", "Type: ", st$station_type[1] ) ) ), # Col 3: Technical div( strong("Technical"), br(), span(val_safe(st$elevation[1], " m")), br(), span(class = paste("badge", res_class), res_label) ), # Col 4: Period/Data div( strong("Data Selection"), br(), span(dates_text) ), # Col 5: Actions div( class = "d-flex align-items-center justify-content-end", downloadButton( "downloadData", label = "Export Excel", class = "btn-sm btn-primary", icon = icon("file-excel") ) ) ) ) ) }) # Helper to prepare plot & summary data with cleaned status flags and English column labels get_plot_df <- reactive({ df <- station_data() req(df) # Apply IMGW status rules (flag "8" -> NA; monthly phenomenon-day flag "9" -> NA) before translation df_clean_flags <- if (exists("clean_imgw_status_flags", mode = "function")) clean_imgw_status_flags(df) else df # Translate columns upfront for plotting so we have English labels df_translated <- translate_imgw_columns(df_clean_flags) # Ensure DateTime column exists for plotting functions if (!"DateTime" %in% names(df_translated)) { if ("Date/Time" %in% names(df_translated)) { df_translated$DateTime <- df_translated$`Date/Time` } else if ("Date" %in% names(df_translated)) { df_translated$DateTime <- as.POSIXct(df_translated$Date, tz = "UTC") } else if ("Year" %in% names(df_translated) && "Month" %in% names(df_translated) && "Day" %in% names(df_translated) && "Hour" %in% names(df_translated)) { df_translated$DateTime <- as.POSIXct(paste(df_translated$Year, df_translated$Month, df_translated$Day, df_translated$Hour, sep = "-"), format = "%Y-%m-%d-%H", tz = "UTC") } else if ("Year" %in% names(df_translated) && "Month" %in% names(df_translated) && "Day" %in% names(df_translated)) { df_translated$DateTime <- as.POSIXct(paste(df_translated$Year, df_translated$Month, df_translated$Day, sep = "-"), format = "%Y-%m-%d", tz = "UTC") } else if ("Year" %in% names(df_translated) && "Month" %in% names(df_translated)) { df_translated$DateTime <- as.POSIXct(paste(df_translated$Year, df_translated$Month, "01", sep = "-"), format = "%Y-%m-%d", tz = "UTC") } } if (exists("clean_imgw_data", mode = "function")) { df_translated <- clean_imgw_data(df_translated) } df_translated }) output$dashboard_plots_ui <- renderUI({ df <- get_plot_df() req(df) res <- resolution_key() # ----------------------------- # SUMMARY CARDS LOGIC # ----------------------------- format_ext_time <- function(idx) { if (length(idx) == 0 || is.na(idx) || is.na(idx[1])) return("") if (idx[1] > nrow(df) || idx[1] < 1) return("") t <- df$DateTime[idx[1]] if (is.null(t) || is.na(t)) return("") if (res %in% c("hourly", "synop")) format(t, "%b %d, %H:%M") else if (res == "annual") format(t, "%Y") else if (res == "monthly") format(t, "%b %Y") else format(t, "%b %d, %Y") } format_val <- function(val, suffix="", digits=1, divisor=1) { if (is.null(val) || is.na(val) || is.infinite(val)) return("—") paste0(round(val/divisor, digits), suffix) } cards <- tagList() add_card <- function(title, value, subtext, icon, color_class) { cards <<- tagList(cards, div( class = paste("glass-card", color_class), div(class = "glass-card-icon", bsicons::bs_icon(icon)), div( class = "glass-card-content", div(class = "glass-card-title", title), div(class = "glass-card-value", value), div(class = "glass-card-subtext", HTML(subtext)) ) )) } # Temperature temp_col <- if (identical(res, "monthly") && "Mean Monthly Temp [°C]" %in% names(df)) { "Mean Monthly Temp [°C]" } else if (identical(res, "daily") && "Mean Daily Temp [°C]" %in% names(df)) { "Mean Daily Temp [°C]" } else if ("Temp [°C]" %in% names(df)) { "Temp [°C]" } else if ("Mean Daily Temp [°C]" %in% names(df)) { "Mean Daily Temp [°C]" } else if ("Mean Monthly Temp [°C]" %in% names(df)) { "Mean Monthly Temp [°C]" } else { NULL } if (!is.null(temp_col) && any(!is.na(df[[temp_col]]))) { latest <- tail(na.omit(df[[temp_col]]), 1) avg_t <- mean(df[[temp_col]], na.rm = TRUE) min_col <- if ("Min Temp [°C]" %in% names(df) && any(!is.na(df[["Min Temp [°C]"]]))) "Min Temp [°C]" else temp_col max_col <- if ("Max Temp [°C]" %in% names(df) && any(!is.na(df[["Max Temp [°C]"]]))) "Max Temp [°C]" else temp_col min_t <- min(df[[min_col]], na.rm=TRUE) max_t <- max(df[[max_col]], na.rm=TRUE) min_idx <- which.min(df[[min_col]]) max_idx <- which.max(df[[max_col]]) add_card("Temperature", format_val(latest, "°C"), sprintf("Avg: %s | Min: %s (%s) | Max: %s (%s)", format_val(avg_t, "°C"), format_val(min_t, "°C"), format_ext_time(min_idx), format_val(max_t, "°C"), format_ext_time(max_idx)), "thermometer-half", "card-red") } # Precipitation p_col <- if ("Precip 6h [mm]" %in% names(df)) "Precip 6h [mm]" else if ("Daily Precip [mm]" %in% names(df)) "Daily Precip [mm]" else if ("Monthly Precip [mm]" %in% names(df)) "Monthly Precip [mm]" else NULL if (!is.null(p_col) && any(!is.na(df[[p_col]]))) { latest <- tail(na.omit(df[[p_col]]), 1) total_p <- if (res %in% c("annual", "monthly")) mean(df[[p_col]], na.rm = TRUE) else sum(df[[p_col]], na.rm = TRUE) p_label <- if (res %in% c("annual", "monthly")) "Avg" else "Total" max_p_col <- if ("Max Daily Precip [mm]" %in% names(df) && any(!is.na(df[["Max Daily Precip [mm]"]]))) "Max Daily Precip [mm]" else if ("Max Precip [mm]" %in% names(df) && any(!is.na(df[["Max Precip [mm]"]]))) "Max Precip [mm]" else p_col max_p <- max(df[[max_p_col]], na.rm = TRUE) max_idx <- which.max(df[[max_p_col]]) add_card("Precipitation", format_val(latest, " mm"), sprintf("%s: %s | Peak: %s (%s)", p_label, format_val(total_p, " mm"), format_val(max_p, " mm"), format_ext_time(max_idx)), "cloud-rain", "card-blue") } # Wind w_col <- if ("Wind Speed [m/s]" %in% names(df)) "Wind Speed [m/s]" else if ("Mean Wind Speed [m/s]" %in% names(df)) "Mean Wind Speed [m/s]" else NULL if (!is.null(w_col) && any(!is.na(df[[w_col]]))) { latest <- tail(na.omit(df[[w_col]]), 1) avg_w <- mean(df[[w_col]], na.rm=TRUE) max_w_col <- if ("Max Gust [m/s]" %in% names(df) && any(!is.na(df[["Max Gust [m/s]"]]))) "Max Gust [m/s]" else if ("Wind Gust [m/s]" %in% names(df) && any(!is.na(df[["Wind Gust [m/s]"]]))) "Wind Gust [m/s]" else w_col max_w <- max(df[[max_w_col]], na.rm=TRUE) max_idx <- which.max(df[[max_w_col]]) add_card("Wind Speed", format_val(latest, " m/s"), sprintf("Avg: %s | Max Gust: %s (%s)", format_val(avg_w, " m/s"), format_val(max_w, " m/s"), format_ext_time(max_idx)), "wind", "card-emerald") } # Humidity h_col <- if ("Relative Humidity [%]" %in% names(df)) "Relative Humidity [%]" else if ("Mean Rel Humidity [%]" %in% names(df)) "Mean Rel Humidity [%]" else NULL if (!is.null(h_col) && any(!is.na(df[[h_col]]))) { latest <- tail(na.omit(df[[h_col]]), 1) avg_h <- mean(df[[h_col]], na.rm=TRUE) min_h <- min(df[[h_col]], na.rm=TRUE) min_idx <- which.min(df[[h_col]]) add_card("Relative Humidity", format_val(latest, "%", 0), sprintf("Avg: %s | Min: %s (%s)", format_val(avg_h, "%", 0), format_val(min_h, "%", 0), format_ext_time(min_idx)), "droplet", "card-cyan") } # Pressure pr_col <- if ("Station Pressure [hPa]" %in% names(df) && any(!is.na(df[["Station Pressure [hPa]"]]))) { "Station Pressure [hPa]" } else if ("Sea Level Pressure [hPa]" %in% names(df) && any(!is.na(df[["Sea Level Pressure [hPa]"]]))) { "Sea Level Pressure [hPa]" } else { NULL } if (!is.null(pr_col) && any(!is.na(df[[pr_col]]))) { latest <- tail(na.omit(df[[pr_col]]), 1) avg_pr <- mean(df[[pr_col]], na.rm=TRUE) min_pr <- min(df[[pr_col]], na.rm=TRUE) max_pr <- max(df[[pr_col]], na.rm=TRUE) min_idx <- which.min(df[[pr_col]]) max_idx <- which.max(df[[pr_col]]) add_card(if(pr_col == "Station Pressure [hPa]") "Station Pressure" else "Sea Level Pressure", format_val(latest, " hPa", 0), sprintf("Avg: %s | Range: %s (%s) - %s (%s)", format_val(avg_pr, " hPa", 0), format_val(min_pr, " hPa", 0), format_ext_time(min_idx), format_val(max_pr, " hPa", 0), format_ext_time(max_idx)), "speedometer2", "card-purple") } # Snow s_col <- if ("Snow Depth [cm]" %in% names(df)) "Snow Depth [cm]" else NULL if (!is.null(s_col) && any(!is.na(df[[s_col]]))) { latest <- tail(na.omit(df[[s_col]]), 1) max_s <- max(df[[s_col]], na.rm=TRUE) max_idx <- which.max(df[[s_col]]) fresh_col <- "Fresh Snow Depth [cm]" fresh_sum <- if (fresh_col %in% names(df) && any(!is.na(df[[fresh_col]]))) { if (res %in% c("annual", "monthly")) mean(df[[fresh_col]], na.rm=TRUE) else sum(df[[fresh_col]], na.rm=TRUE) } else 0 fresh_label <- if (res %in% c("annual", "monthly")) "Avg Fresh" else "Fresh" add_card("Snow Cover", format_val(latest, " cm", 0), sprintf("Peak: %s (%s) | %s: %s", format_val(max_s, " cm", 0), format_ext_time(max_idx), fresh_label, format_val(fresh_sum, " cm", 0)), "snow", "card-sky") } # Sunshine sun_col <- if ("Sunshine [h]" %in% names(df)) "Sunshine [h]" else if ("Monthly Sunshine [h]" %in% names(df)) "Monthly Sunshine [h]" else NULL if (!is.null(sun_col) && any(!is.na(df[[sun_col]]))) { latest <- tail(na.omit(df[[sun_col]]), 1) total_sun <- if (res %in% c("annual", "monthly")) mean(df[[sun_col]], na.rm=TRUE) else sum(df[[sun_col]], na.rm=TRUE) sun_label <- if (res %in% c("annual", "monthly")) "Avg" else "Total" add_card("Sunshine", format_val(latest, " hrs", 1), sprintf("%s: %s", sun_label, format_val(total_sun, " hrs", 1)), "sun", "card-amber") } # Cloud Cover c_col <- if ("Total Cloud Cover [okta]" %in% names(df)) "Total Cloud Cover [okta]" else if ("Mean Cloud Cover [okta]" %in% names(df)) "Mean Cloud Cover [okta]" else NULL if (!is.null(c_col) && any(!is.na(df[[c_col]]))) { latest <- tail(na.omit(df[[c_col]]), 1) avg_c <- mean(df[[c_col]], na.rm=TRUE) add_card("Cloud Cover", format_val(latest, " /8", 1), sprintf("Avg: %s", format_val(avg_c, " /8", 1)), "clouds", "card-slate") } plot_list <- tagList() # Temperature temp_cols <- c("Temp [°C]", "Mean Daily Temp [°C]", "Mean Monthly Temp [°C]", "Max Temp [°C]", "Min Temp [°C]") has_temp <- any(temp_cols %in% names(df)) && any(vapply(intersect(temp_cols, names(df)), function(col) any(!is.na(df[[col]])), logical(1))) if (has_temp) { plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("temperature_plot", height = "320px"))) } # Precipitation precip_col <- if ("Precip 6h [mm]" %in% names(df)) "Precip 6h [mm]" else if ("Daily Precip [mm]" %in% names(df)) "Daily Precip [mm]" else if ("Monthly Precip [mm]" %in% names(df)) "Monthly Precip [mm]" else NULL has_precip <- !is.null(precip_col) && !all(is.na(df[[precip_col]])) if (has_precip) { plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("precipitation_plot", height = "320px"))) } # Wind wind_col <- if ("Wind Speed [m/s]" %in% names(df)) "Wind Speed [m/s]" else if ("Mean Wind Speed [m/s]" %in% names(df)) "Mean Wind Speed [m/s]" else NULL has_wind <- !is.null(wind_col) && !all(is.na(df[[wind_col]])) if (has_wind) { plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("wind_plot", height = "320px"))) } # Humidity hum_col <- if ("Relative Humidity [%]" %in% names(df)) "Relative Humidity [%]" else if ("Mean Rel Humidity [%]" %in% names(df)) "Mean Rel Humidity [%]" else NULL has_hum <- !is.null(hum_col) && !all(is.na(df[[hum_col]])) if (has_hum) { plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("humidity_plot", height = "320px"))) } # Pressure has_press <- any(vapply( intersect(c("Station Pressure [hPa]", "Sea Level Pressure [hPa]"), names(df)), function(col) any(!is.na(df[[col]])), logical(1) )) if (has_press) { plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("pressure_plot", height = "320px"))) } # Sunshine sun_col <- if ("Sunshine [h]" %in% names(df)) "Sunshine [h]" else if ("Monthly Sunshine [h]" %in% names(df)) "Monthly Sunshine [h]" else NULL has_sun <- !is.null(sun_col) && !all(is.na(df[[sun_col]])) if (has_sun) { plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("sunshine_plot", height = "320px"))) } # Solar Radiation / Actinometry has_solar <- any(vapply( intersect(c("Solar Radiation [MJ/m²]", "Actinometry [J/cm²]"), names(df)), function(col) any(!is.na(df[[col]])), logical(1) )) if (has_solar) { plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("solar_plot", height = "320px"))) } # Snow snow_col <- if ("Snow Depth [cm]" %in% names(df)) "Snow Depth [cm]" else if ("Fresh Snow Depth [cm]" %in% names(df)) "Fresh Snow Depth [cm]" else NULL has_snow <- !is.null(snow_col) && !all(is.na(df[[snow_col]])) if (has_snow) { plot_list <- tagList(plot_list, div(class = "col-12 col-lg-6", plotlyOutput("snow_plot", height = "320px"))) } date_range_str <- "" if (nrow(df) > 0) { date_range_str <- paste( format(min(df$DateTime, na.rm=TRUE), "%d %b %Y"), "-", format(max(df$DateTime, na.rm=TRUE), "%d %b %Y") ) } tagList( if (length(cards) > 0) { latest_obs_str <- if (nrow(df) > 0) paste("— Latest values as of:", format_ext_time(nrow(df))) else "" div( class = "w-100", div(class = "summary-cards-header", paste("Station Observations Summary", if (nchar(date_range_str) > 0) paste0("(", date_range_str, ")") else "", latest_obs_str)), div(class = "summary-cards-container", cards) ) } else NULL, div(class = "row g-3", plot_list) ) }) # Excel Download Handler output$downloadData <- downloadHandler( filename = function() { st <- selected_station() req(st) res <- resolution_key() file_id <- imgw_coalesce_code( if ("id" %in% names(st)) st$id[1] else NULL, if ("id_9" %in% names(st)) st$id_9[1] else NULL ) %||% imgw_slugify(st$name[1]) sprintf("imgw_%s_%s_%s.xlsx", file_id, res, format(Sys.Date(), "%Y%m%d")) }, content = function(file) { df <- station_data() req(df) # Use same translation as table df_export <- translate_imgw_columns(df) # Ensure Date/Time format is Excel friendly (POSIXct usually works, but string is safer if consistency needed) # writexl handles dates well, so we can keep them as is or format them. # Let's keep them as native types for Excel calculation potential. writexl::write_xlsx(df_export, path = file) } ) output$temperature_plot <- renderPlotly({ create_temperature_plot_imgw(get_plot_df(), resolution_key()) }) output$precipitation_plot <- renderPlotly({ create_precipitation_plot_imgw(get_plot_df(), resolution_key()) }) output$wind_plot <- renderPlotly({ res <- resolution_key() if (res == "hourly") { create_wind_rose_imgw(get_plot_df(), res) } else { create_wind_plot_imgw(get_plot_df(), res) } }) output$pressure_plot <- renderPlotly({ create_pressure_plot_imgw(get_plot_df(), resolution_key()) }) output$humidity_plot <- renderPlotly({ create_humidity_plot_imgw(get_plot_df(), resolution_key()) }) output$sunshine_plot <- renderPlotly({ create_sunshine_plot_imgw(get_plot_df(), resolution_key()) }) output$solar_plot <- renderPlotly({ create_solar_plot_imgw(get_plot_df(), resolution_key()) }) output$snow_plot <- renderPlotly({ create_snow_plot_imgw(get_plot_df(), resolution_key()) }) output$station_data_table <- DT::renderDataTable({ df <- station_data() req(df) df_display <- as.data.frame(df, stringsAsFactors = FALSE) # 1. Combine flags with paired measurement values via explicit IMGW_STATUS_TO_VALUE map raw_cols <- names(df_display) status_candidates <- intersect(names(IMGW_STATUS_TO_VALUE), raw_cols) for (scol in status_candidates) { base_var <- IMGW_STATUS_TO_VALUE[[scol]] if (!is.null(base_var) && base_var %in% raw_cols) { vals <- df_display[[base_var]] flags <- df_display[[scol]] formatted_vals <- vapply(seq_along(vals), function(i) { v <- vals[i] f <- flags[i] v_is_empty <- is.na(v) || trimws(as.character(v)) == "" f_is_empty <- is.na(f) || trimws(as.character(f)) == "" if (v_is_empty && f_is_empty) { return(NA_character_) } v_str <- if (v_is_empty) "" else as.character(v) # Translate precipitation type if (!v_is_empty && base_var == "ropt") { v_str <- switch(v_str, "5" = "Dew / Frost / Rime / Fog", "6" = "Rain / Drizzle", "7" = "Sleet / Snow / Ice Pellets", "8" = "Hail / Ice Grains", "9" = "Mixed Sleet / Hail / Snow", v_str ) } else if (!v_is_empty && base_var == "roop") { v_str <- switch(toupper(v_str), "S" = "Snow", "W" = "Rain / Water", "M" = "Mixed", "L" = "Lód / Ice", v_str ) } else if (!v_is_empty && base_var %in% c("rosw", "Dew Occurrence", "dzbl", "Lightning [0/1]", "dzps", "Snow Cover [0/1]", "Snow Cover")) { if (v_str == "0") { v_str <- "No" } else if (v_str == "1") v_str <- "Yes" } else if (!v_is_empty && base_var %in% c("sgr", "sgrn", "Ground State [code]", "Ground State")) { v_str <- switch(toupper(v_str), "Z" = "Frozen", "R" = "Thawed", v_str ) } else if (!v_is_empty && base_var %in% c("pksn", "Snow Depth [cm]")) { if (v_str == "997") { v_str <- "< 0.5" } else if (v_str == "998") { v_str <- "Patchy" } else if (v_str == "999") v_str <- "Unmeasurable" } else if (!v_is_empty && base_var %in% c("pogb", "pogu", "Current Weather [code]", "Past Weather [code]", "Current Weather", "Past Weather")) { if (exists("WMO_WEATHER_CODES")) { # Remove leading zeros to match the WMO_WEATHER_CODES index format num_key <- as.character(as.numeric(v_str)) if (num_key %in% names(WMO_WEATHER_CODES)) { v_str <- WMO_WEATHER_CODES[[num_key]] } } } if (!f_is_empty) { f_val <- trimws(as.character(f)) is_monthly_phenom_missing <- (f_val == "9") && (base_var %in% IMGW_MONTHLY_PHENOM_DAY_COLS) if (f_val == "8" || is_monthly_phenom_missing) { # Status "8" (no observation) / status "9" on monthly phenomenon counts: discard dummy 0 v_str <- "" f_html <- "no observations" } else if (f_val == "9" && v_is_empty) { # Daily/standard status 9 ("brak zjawiska" = phenomenon absent -> 0) v_str <- "0" f_html <- "" } else { f_display <- switch(f_val, "9" = "0", paste0("[", f_val, "]") ) # Only show as a superscript/muted flag if it's not "0" if (f_display == "0") { if (v_str == "") v_str <- "0" f_html <- "" } else { f_html <- paste0("", f_display, "") } } } else { f_html <- "" } paste0(v_str, f_html) }, character(1)) df_display[[base_var]] <- formatted_vals df_display[[scol]] <- NULL } } # Fallback translation for precipitation type columns without status flags for (col in c("ropt", "Precip Type 6h")) { if (col %in% names(df_display)) { df_display[[col]] <- vapply(df_display[[col]], function(v) { if (is.na(v) || trimws(as.character(v)) == "") { return("") } switch(trimws(as.character(v)), "5" = "Dew / Frost / Rime / Fog", "6" = "Rain / Drizzle", "7" = "Sleet / Snow / Ice Pellets", "8" = "Hail / Ice Grains", "9" = "Mixed Sleet / Hail / Snow", as.character(v) ) }, character(1)) } } for (col in c("roop", "Precip Type")) { if (col %in% names(df_display)) { df_display[[col]] <- vapply(df_display[[col]], function(v) { if (is.na(v) || trimws(as.character(v)) == "") { return("") } switch(trimws(toupper(as.character(v))), "S" = "Snow", "W" = "Rain / Water", "M" = "Mixed", "L" = "Lód / Ice", as.character(v) ) }, character(1)) } } for (col in c("rosw", "Dew Occurrence", "dzbl", "Lightning [0/1]", "dzps", "Snow Cover [0/1]", "Snow Cover")) { if (col %in% names(df_display)) { df_display[[col]] <- vapply(df_display[[col]], function(v) { if (is.na(v) || trimws(as.character(v)) == "") { return("") } val <- trimws(as.character(v)) if (val == "0") { return("No") } if (val == "1") { return("Yes") } return(val) }, character(1)) } } for (col in c("sgr", "sgrn", "Ground State [code]", "Ground State")) { if (col %in% names(df_display)) { df_display[[col]] <- vapply(df_display[[col]], function(v) { if (is.na(v) || trimws(as.character(v)) == "") { return("") } switch(trimws(toupper(as.character(v))), "Z" = "Frozen", "R" = "Thawed", as.character(v) ) }, character(1)) } } for (col in c("pksn", "Snow Depth [cm]")) { if (col %in% names(df_display)) { df_display[[col]] <- vapply(df_display[[col]], function(v) { if (is.na(v) || trimws(as.character(v)) == "") { return("") } val <- trimws(as.character(v)) if (val == "997") { return("< 0.5") } if (val == "998") { return("Patchy") } if (val == "999") { return("Unmeasurable") } return(val) }, character(1)) } } for (col in c("pogb", "pogu", "Current Weather [code]", "Past Weather [code]", "Current Weather", "Past Weather")) { if (col %in% names(df_display)) { df_display[[col]] <- vapply(df_display[[col]], function(v) { if (is.na(v) || trimws(as.character(v)) == "") { return("") } if (exists("WMO_WEATHER_CODES")) { num_key <- as.character(as.numeric(trimws(as.character(v)))) if (num_key %in% names(WMO_WEATHER_CODES)) { return(WMO_WEATHER_CODES[[num_key]]) } } return(as.character(v)) }, character(1)) } } # Use helper function for renaming df_display <- translate_imgw_columns(df_display) # Remove structural and status clutter from the UI table cols_to_remove <- c( "Station ID", "Station Name", "Year", "Month", "Day", "Hour", "Minute", "station_id", "station_name", "year", "month", "day", "hour", "minute", "Date", "date", "Source", "source", "Source File", "source_file", "Resolution", "resolution", "Source Rank", "source_rank" ) df_display <- df_display[, !names(df_display) %in% cols_to_remove, drop = FALSE] # Hide columns that are ALL NA or empty empty_cols <- names(df_display)[vapply(df_display, function(x) { if (is.character(x)) { all(is.na(x) | x == "") } else { all(is.na(x)) } }, logical(1))] if (length(empty_cols) > 0) { df_display <- df_display[, !names(df_display) %in% empty_cols, drop = FALSE] } # Clean up any leftover status columns status_cols <- grep("^Status:", names(df_display), value = TRUE) if (length(status_cols) > 0) { df_display <- df_display[, !names(df_display) %in% status_cols, drop = FALSE] } list_cols <- vapply(df_display, is.list, logical(1)) if (any(list_cols)) { df_display[list_cols] <- lapply(df_display[list_cols], function(x) { vapply(x, function(v) paste(v, collapse = ", "), character(1)) }) } if ("Date/Time" %in% names(df_display)) { df_display$`Date/Time` <- format(df_display$`Date/Time`, "%Y-%m-%d %H:%M:%S") } # Reorder columns by meteorological relevance col_priority_patterns <- c( "Date/Time", # Temperature "Temp \\[", "Max Temp", "Min Temp", "Mean.*Temp", "Dew Point", "Wet Bulb", # Precipitation "Precip", "Rain Duration", "Snow Duration", "Rain\\+Snow", # Pressure "Station Pressure", "Sea Level Pressure", "Pressure Tend", "Pressure Change", # Humidity "Relative Humidity", "Vapour Pressure", "Humidity Deficit", # Wind "Wind Speed", "Wind Dir", "Wind Gust", "Max Gust", "Gust Hour", "Gust Minute", "Wind >=", # Sunshine / Radiation "Sunshine", "Actinometry", # Snow "Snow Depth", "Snow Water", "Fresh Snow", "Snow Plot", "Snow Type", "Snow Cover", # Clouds / Visibility "Cloud", "Visibility", "Auto Visibility", # Ground / Soil temp "Ground State", "Soil Temp", "Lower Isotherm", "Upper Isotherm", # Ice / misc "Ice Indicator", "Ventilation", # Phenomena durations "Hail", "Fog", "Mist", "Rime", "Glaze", "Blizzard", "Haze", "Thunder", "Dew", "Frost", "Lightning", # Weather codes "Current Weather", "Past Weather", "Precip Type" ) current_cols <- names(df_display) ordered_cols <- character(0) for (pat in col_priority_patterns) { matches <- grep(pat, current_cols, ignore.case = TRUE, value = TRUE) matches <- setdiff(matches, ordered_cols) ordered_cols <- c(ordered_cols, matches) } remaining <- setdiff(current_cols, ordered_cols) df_display <- df_display[, c(ordered_cols, remaining), drop = FALSE] DT::datatable( df_display, escape = FALSE, options = list( pageLength = 25, scrollX = TRUE, dom = "frtip", order = if ("Date/Time" %in% names(df_display)) list(list(which(names(df_display) == "Date/Time") - 1, "desc")) else list(list(0, "asc")) ), rownames = FALSE, class = "compact stripe hover" ) }) output$dashboard_content <- renderUI({ uid <- current_station_uid() if (is.null(uid) || uid == "") { return( tags$div( style = "height: 560px; display: flex; align-items: center; justify-content: center; color: #999;", "Select a station from the map or Stations Info table to load data." ) ) } if (isTRUE(station_fetching())) { return( tags$div( style = "padding: 20px;", uiOutput("dashboard_station_header"), tags$div( class = "alert alert-info d-flex align-items-center gap-2", tags$div(class = "spinner-border spinner-border-sm", role = "status"), tags$span(station_fetch_message()) ) ) ) } err <- station_fetch_error() if (!is.null(err) && nzchar(err)) { return( tags$div( style = "padding: 20px;", uiOutput("dashboard_station_header"), tags$div(class = "alert alert-warning", err) ) ) } df <- station_data() if (is.null(df) || nrow(df) == 0) { return( tags$div( style = "padding: 20px;", uiOutput("dashboard_station_header"), tags$div(class = "alert alert-secondary", "No data loaded for the current selection.") ) ) } tagList( uiOutput("dashboard_station_header"), navset_card_pill( id = "dashboard_subtabs", nav_panel( title = "Plots", uiOutput("dashboard_plots_ui") ), nav_panel( title = "Data", div( style = "margin-top: 10px;", DT::dataTableOutput("station_data_table") ) ) ) ) }) }