📚 AtmoSwing Web Viewer Docs

← Back to Home

Utils

Files


Modules

utils/urlWorkspaceUtils

Helpers for syncing workspace selection with URL query parameters. Enables shareable URLs and browser back/forward navigation for workspace changes.

utils/targetDateUtils

Utility helpers for lead time calculations and date comparisons. Centralizes logic for working with forecast target dates and lead times.

utils/formattingUtils

Generic formatting utilities for dates, numbers, and entity names. Provides consistent formatting across the application for display purposes.

utils/forecastDateUtils

Date parsing and formatting utilities for forecast dates. Handles various date formats used by the API and provides consistent parsing/formatting.

utils/contextGuards

Common guard and helper functions shared across context providers. Reduces duplication and provides validation logic for method/workspace selections.

utils/colorUtils

Color utilities for visualizing forecast values on maps and charts. Provides a color gradient from white -> cyan -> green -> yellow -> red based on normalized values.

utils/cacheTTLs

Central TTL (Time-To-Live) presets for cached API requests. All values are in milliseconds. Adjust these if backend freshness requirements change.

utils/apiNormalization

Helpers to normalize varied API response shapes into predictable structures. The API may return data in different formats depending on the endpoint or version. These functions ensure consistent data structures for the UI layer.

utils/urlWorkspaceUtils

Helpers for syncing workspace selection with URL query parameters. Enables shareable URLs and browser back/forward navigation for workspace changes.

utils/urlWorkspaceUtils.readWorkspaceFromUrl() ⇒ string

Reads the workspace key from the current URL query parameters.

Kind: static method of utils/urlWorkspaceUtils
Returns: string - Workspace key from URL, or empty string if not present
Example

// URL: /?workspace=demo
readWorkspaceFromUrl() // Returns: "demo"

utils/urlWorkspaceUtils.writeWorkspaceToUrl(next)

Updates the URL query parameter with the selected workspace key. Uses pushState to update the URL without page reload.

Kind: static method of utils/urlWorkspaceUtils

Param Type Description
next string Workspace key to set, or empty/null to remove parameter

Example

writeWorkspaceToUrl('demo') // Updates URL to: /?workspace=demo
writeWorkspaceToUrl(null)   // Removes workspace parameter from URL

utils/urlWorkspaceUtils.onWorkspacePopState(handler) ⇒ function

Registers a handler for browser back/forward navigation to sync workspace changes.

Kind: static method of utils/urlWorkspaceUtils
Returns: function - Cleanup function to remove the event listener

Param Type Description
handler function Callback function that receives the workspace key from URL

Example

const cleanup = onWorkspacePopState((workspaceKey) => {
  console.log('Workspace changed via navigation:', workspaceKey);
  setCurrentWorkspace(workspaceKey);
});

// Later, when component unmounts:
cleanup();

utils/targetDateUtils

Utility helpers for lead time calculations and date comparisons. Centralizes logic for working with forecast target dates and lead times.

utils/targetDateUtils.SUB_HOURS : Array.<number>

Sub-daily hour intervals for forecast resolution.

Kind: static constant of utils/targetDateUtils

utils/targetDateUtils.makeDayKey(date) ⇒ string

Creates a stable YYYY-M-D key string for a date. Note: Month is 0-based as per JavaScript Date API.

Kind: static method of utils/targetDateUtils
Returns: string - Date key in format "YYYY-M-D", or empty string if invalid

Param Type Description
date Date Date object to convert to key

Example

makeDayKey(new Date(2025, 10, 5)) // Returns: "2025-10-5"

utils/targetDateUtils.parseDayKey(key) ⇒ Date

Parses a YYYY-M-D key string back to a Date object. Month is treated as 0-based (JavaScript Date convention).

Kind: static method of utils/targetDateUtils
Returns: Date - Date object, or Invalid Date if parsing fails

Param Type Description
key string Date key in format "YYYY-M-D"

Example

parseDayKey("2025-10-5") // Returns: Date object for November 5, 2025

utils/targetDateUtils.computeLeadHours(forecastBaseDate, selectedTargetDate, leadResolution, selectedLead, dailyLeads, subDailyLeads) ⇒ number

Compute lead hours given either a base date + target date (preferred) or fallback indices. Applies timezone offset adjustment when both dates are provided to keep consistent hour differences.

Kind: static method of utils/targetDateUtils
Returns: number - non-negative integer lead hours

Param Type
forecastBaseDate Date | null
selectedTargetDate Date | null
leadResolution 'daily' | 'sub'
selectedLead number
dailyLeads Array.<{time_step:number, date:Date}>
subDailyLeads Array.<{time_step:number, date:Date}>

utils/targetDateUtils.isSameDay()

Compare two dates on calendar day only.

Kind: static method of utils/targetDateUtils

utils/targetDateUtils.isSameInstant()

Strict timestamp equality (ms).

Kind: static method of utils/targetDateUtils

utils/targetDateUtils.hasTargetDate()

Determine if target date is present among leads given resolution.

Kind: static method of utils/targetDateUtils

utils/formattingUtils

Generic formatting utilities for dates, numbers, and entity names. Provides consistent formatting across the application for display purposes.

utils/formattingUtils.formatDateDDMMYYYY(dateLike) ⇒ string

Format a Date or date-like value to DD.MM.YYYY format (e.g., 05.11.2025). Returns empty string on invalid input.

Kind: static method of utils/formattingUtils
Returns: string - Formatted date string or empty string if invalid

Param Type Description
dateLike Date | string | number Date object, timestamp, or date string

Example

formatDateDDMMYYYY(new Date('2025-11-05')) // Returns: "05.11.2025"
formatDateDDMMYYYY('2025-11-05') // Returns: "05.11.2025"
formatDateDDMMYYYY(null) // Returns: ""

utils/formattingUtils.formatPrecipitation(value) ⇒ string

Formats precipitation value to string with one decimal place.

Kind: static method of utils/formattingUtils
Returns: string - Formatted string: number with 1 decimal, '0' for zero, '-' for null/undefined

Param Type Description
value number | string | null Precipitation value to format

Example

formatPrecipitation(25.67) // Returns: "25.7"
formatPrecipitation(0) // Returns: "0"
formatPrecipitation(null) // Returns: "-"

utils/formattingUtils.formatCriteria(value) ⇒ string

Formats a criteria/score value to string with two decimal places.

Kind: static method of utils/formattingUtils
Returns: string - Formatted string with 2 decimals, or '-' for null/undefined

Param Type Description
value number | string | null Criteria value to format

Example

formatCriteria(0.12345) // Returns: "0.12"
formatCriteria(null) // Returns: "-"

utils/formattingUtils.compareEntitiesByName(a, b) ⇒ number

Compares two entity objects by name for sorting, case-insensitive. Falls back to comparing by id if name is not available.

Kind: static method of utils/formattingUtils
Returns: number - -1 if a < b, 1 if a > b, 0 if equal

Param Type Description
a Object First entity with name and/or id
b Object Second entity with name and/or id

Example

const entities = [{name: "Station B"}, {name: "Station A"}];
entities.sort(compareEntitiesByName);
// Results in: [{name: "Station A"}, {name: "Station B"}]

utils/formattingUtils.formatDateLabel(date) ⇒ string

Formats a Date into a display label with optional time component. Includes time (HH:MM) only if hours or minutes are non-zero.

Kind: static method of utils/formattingUtils
Returns: string - Formatted string "DD.MM.YYYY" or "DD.MM.YYYY HH:MM"

Param Type Description
date Date | string | number Date object, timestamp, or date string

Example

formatDateLabel(new Date('2025-11-05T00:00')) // Returns: "05.11.2025"
formatDateLabel(new Date('2025-11-05T14:30')) // Returns: "05.11.2025 14:30"

utils/forecastDateUtils

Date parsing and formatting utilities for forecast dates. Handles various date formats used by the API and provides consistent parsing/formatting.

utils/forecastDateUtils.parseForecastDate(str) ⇒ Date | null

Parses various forecast date string formats into a JavaScript Date object.

Supported formats:

Kind: static method of utils/forecastDateUtils
Returns: Date | null - Parsed Date object, or null if parsing fails

Param Type Description
str string Date string to parse

Example

parseForecastDate("2023-01-15T12") // Returns: Date object for Jan 15, 2023 12:00
parseForecastDate("2023011512") // Returns: Date object for Jan 15, 2023 12:00
parseForecastDate("invalid") // Returns: null

utils/forecastDateUtils.formatForecastDateForApi(dateObj, [reference]) ⇒ string | null

Formats a Date object to a string format suitable for API requests. The output format is determined by examining a reference string format.

Output formats based on reference:

Kind: static method of utils/forecastDateUtils
Returns: string | null - Formatted date string, or null if invalid date

Param Type Description
dateObj Date Date object to format
[reference] string Reference format string to match

Example

formatForecastDateForApi(new Date('2023-01-15T12:00'), '2023-01-01T00')
// Returns: "2023-01-15T12"

formatForecastDateForApi(new Date('2023-01-15T12:00'), '2023-01-01')
// Returns: "2023-01-15 12:00"

utils/contextGuards

Common guard and helper functions shared across context providers. Reduces duplication and provides validation logic for method/workspace selections.

utils/contextGuards.isMethodSelectionValid(selectedMethodConfig, workspace) ⇒ boolean

Validates that a selected method/config belongs to the current workspace.

Kind: static method of utils/contextGuards
Returns: boolean - True if selection is valid for this workspace

Param Type Description
selectedMethodConfig Object The selected method and config object
workspace string Current workspace key

utils/contextGuards.methodExists(methodConfigTree, methodId) ⇒ boolean

Checks if a method ID exists in the method configuration tree.

Kind: static method of utils/contextGuards
Returns: boolean - True if method exists in tree

Param Type Description
methodConfigTree Array Array of method objects with id property
methodId string | number Method ID to search for

utils/contextGuards.deriveConfigId(selectedMethodConfig, methodConfigTree) ⇒ string | number | null

Derives a configuration ID from selected method, falling back to first config.

Kind: static method of utils/contextGuards
Returns: string | number | null - Configuration ID, or null if not found

Param Type Description
selectedMethodConfig Object Selected method and config object
methodConfigTree Array Full method configuration tree

utils/contextGuards.keyForEntities(workspace, forecastDate, methodId, configId) ⇒ string

Composes a cache key for entities data.

Kind: static method of utils/contextGuards
Returns: string - Composed cache key

Param Type Description
workspace string Workspace key
forecastDate string Forecast date string
methodId string | number Method ID
configId string | number Configuration ID

utils/contextGuards.keyForRelevantEntities(workspace, forecastDate, methodId, configId) ⇒ string

Composes a cache key for relevant entities data.

Kind: static method of utils/contextGuards
Returns: string - Composed cache key

Param Type Description
workspace string Workspace key
forecastDate string Forecast date string
methodId string | number Method ID
configId string | number Configuration ID

utils/contextGuards.keyForForecastValues(workspace, forecastDate, methodId, configId, leadHours, percentile, normalizationRef) ⇒ string

Composes a cache key for forecast values data.

Kind: static method of utils/contextGuards
Returns: string - Composed cache key

Param Type Description
workspace string Workspace key
forecastDate string Forecast date string
methodId string | number Method ID
configId string | number Configuration ID (defaults to 'agg')
leadHours number Lead time in hours
percentile number Percentile value
normalizationRef string Normalization reference (defaults to 'raw')

utils/colorUtils

Color utilities for visualizing forecast values on maps and charts. Provides a color gradient from white -> cyan -> green -> yellow -> red based on normalized values.

utils/colorUtils.valueToColor(value, maxValue) ⇒ Array.<number>

Converts a numeric value to an RGB color array based on a gradient scale.

Color scale:

Kind: static method of utils/colorUtils
Returns: Array.<number> - RGB color array [r, g, b] with values 0-255

Param Type Description
value number | null The value to convert to color
maxValue number The maximum value for normalization

Example

valueToColor(50, 100) // Returns [255, 255, 0] (yellow)
valueToColor(0, 100)  // Returns [255, 255, 255] (white)

utils/colorUtils.valueToColorCSS(value, maxValue) ⇒ string

Converts a numeric value to a CSS rgb() color string. Convenience wrapper around valueToColor() that returns a CSS-ready string.

Kind: static method of utils/colorUtils
Returns: string - CSS rgb() color string, e.g., "rgb(255,128,0)"

Param Type Description
value number | null The value to convert to color
maxValue number The maximum value for normalization

Example

valueToColorCSS(75, 100) // Returns "rgb(255,191,0)"

utils/cacheTTLs

Central TTL (Time-To-Live) presets for cached API requests. All values are in milliseconds. Adjust these if backend freshness requirements change.

utils/cacheTTLs.SHORT_TTL : number

Short TTL for frequently changing data (2 minutes). Use for exploratory data with high churn rate like analog dates and lead times.

Kind: static constant of utils/cacheTTLs

utils/cacheTTLs.DEFAULT_TTL : number

Default TTL for typical API data (5 minutes). Use for methods, entities, and synthesis data that changes moderately.

Kind: static constant of utils/cacheTTLs

utils/cacheTTLs.LONG_TTL : number

Long TTL for very static data (15 minutes). Use for configuration and rarely-changing reference data.

Kind: static constant of utils/cacheTTLs

utils/apiNormalization

Helpers to normalize varied API response shapes into predictable structures. The API may return data in different formats depending on the endpoint or version. These functions ensure consistent data structures for the UI layer.

utils/apiNormalization.normalizeEntitiesResponse(resp) ⇒ Array.<Object>

Normalizes entities response to a consistent array format.

Kind: static method of utils/apiNormalization
Returns: Array.<Object> - Array of entity objects with {id, name?, x?, y?}

Param Type Description
resp * Raw API response (can be array, object with entities property, or null)

Example

// Returns [{id: 1, name: "Station A"}]
normalizeEntitiesResponse({entities: [{id: 1, name: "Station A"}]})

utils/apiNormalization.normalizeRelevantEntityIds(resp) ⇒ Set.<(string|number)>

Extracts and normalizes relevant entity IDs from various response formats.

Kind: static method of utils/apiNormalization
Returns: Set.<(string|number)> - Set of entity IDs

Param Type Description
resp * Raw API response

Example

normalizeRelevantEntityIds({entity_ids: [1, 2, 3]}) // Returns Set(1, 2, 3)

utils/apiNormalization.normalizeAnalogsResponse(resp) ⇒ Array.<Object>

Normalizes analog data from various response formats.

Kind: static method of utils/apiNormalization
Returns: Array.<Object> - Array of analog objects with {rank, date, value, criteria}

Param Type Description
resp * Raw API response containing analog data

Example

normalizeAnalogsResponse({analogs: [{rank: 1, date: "2020-01-15", value: 25.3}]})

utils/apiNormalization.extractTargetDatesArray(resp) ⇒ Array.<string>

Extracts target dates array from various API response formats.

Kind: static method of utils/apiNormalization
Returns: Array.<string> - Array of target date strings, or empty array if not found

Param Type Description
resp * Raw API response (can be object, array, or nested structure)

Example

extractTargetDatesArray({series_values: {target_dates: ['2023-01-15', '2023-01-16']}})
// Returns: ['2023-01-15', '2023-01-16']

utils/apiNormalization.normalizeForecastValuesResponse(resp) ⇒ Object | Object | Object | boolean

Normalizes forecast values response into separate normalized and raw value maps.

Kind: static method of utils/apiNormalization
Returns: Object - Object with {norm: Object, raw: Object, unavailable: boolean}Object - returns.norm - Map of entity ID to normalized valueObject - returns.raw - Map of entity ID to raw valueboolean - returns.unavailable - True if data is missing or malformed

Param Type Description
resp Object Raw API response with entity_ids, values_normalized, and values arrays

Example

normalizeForecastValuesResponse({
  entity_ids: [1, 2],
  values_normalized: [0.5, 0.8],
  values: [25.5, 40.2]
})
// Returns: {
//   norm: {1: 0.5, 2: 0.8},
//   raw: {1: 25.5, 2: 40.2},
//   unavailable: false
// }

utils/apiNormalization.normalizeMethodsAndConfigs(resp) ⇒ Array.<Object>

Normalizes methods and configurations response into a tree structure. Each method contains nested configuration objects.

Kind: static method of utils/apiNormalization
Returns: Array.<Object> - Array of method objects with nested children configs

Param Type Description
resp Object Raw API response with methods array

Example

normalizeMethodsAndConfigs({
  methods: [{id: 1, name: "Method A", configs: [{id: 10, name: "Config 1"}]}]
})
// Returns: [{id: 1, name: "Method A", children: [{id: 10, name: "Config 1"}]}]