Hydrograph Example Code


This javascript code displayed here is currently publicly accessible from the map view as well as the gauge view on NWPS. I did about 90% of the Official and NWM hydrograph code and about 30% of the HEFS hydrograph using Highcharts version 11.4.8 and SvelteJS 4.2.20.


Examples:


One example of a problem that another developer was having with the HEFS hydrograph that I figure out was the hydrograph was showing the same gauge on multiple tabs from the map view. The solution which I was able to figure out was that the creation of each chart object had to have an index for it each gauge to be unique.

Sample 1: This is an example of some of the code I wrote for NOAA Office of Water Prediction Official Hydrograph application. The example code here shows how the "Latest Observed Value" widget was done by myself. The request in the ticket details wanted the ability to expand and contract this information when viewing the hydrogaph. The functionality shows data values for the specific hydrograph's latest observed value in flood and a formatted date and has the ability on click to expand and contract for viewing. This widget is used on both the Official and National Water Model hydrographs.


// From the frontend/components/hydrograph/src/Chart.svelte
...
series.latest_observed = getLatestObservedValues(series, gaugeConfig)
...

// From the frontend/components/hydrograph/src/base.js
...
/**
 * Latest observed value" message box on chart in upper left corner
 * @param object series
 * @param object gaugeConfig
 * @returns string msg
 */
export function getLatestObservedValues(series, gaugeConfig) {
  if (!series || !gaugeConfig || !series.y0.seriesData.observed || !series.y0.seriesData.observed.length) return

  let floodUnit = getFloodCatUnits(gaugeConfig)
  let stageOrFlow = series.y0.units === 'ft' ? 'stage' : 'flow'
  let floodValue = gaugeConfig.flood.categories.minor[stageOrFlow].value

  let obsData = series.y0.seriesData.observed
  let obsValue = obsData[obsData.length - 1][1]
  let obsTime = obsData[obsData.length - 1][0]
  let obsUnit = kcfsToCfsString(series.y0.units)
  let o = dayjs(obsTime).tz(series.timeZone)

  // Display correct unit when y0 is set to secondary (e.g. bigi1)
  if (series.y0UnitsIsSecondary == true && series.y0Enabled == true) {
    if (series.y0.units === 'ft') {
      floodUnit = 'ft'
    }
  }

  // When y0 is hidden (because data outside of ratings curve), display y1 data.
  if (series.y0Enabled == false) {
    floodUnit = series.y1.units
    obsUnit = series.y1.units

    // If needed, convert data to kcfs to ensure the data is correctly formatted.
    if (floodUnit == 'kcfs' && floodValue > -9999) {
      floodValue = cfsToKcfs(floodValue)
    }
  }

  let shortmsg = `⏱  ${obsValue} ${obsUnit}  ❯`
  let longmsg = `Latest Observed Value: ${obsValue} ${obsUnit} x
${o.format('h')}:${o.format('mm')} ${o.format('A')} ${o.format('z')} ${o.format('D')}-${o.format('MMM')}-${o.format('YYYY')}` if (!obsValue || !obsTime || isNaN(obsTime) || !o) return false if (!isFalsy(floodValue) && floodUnit) { longmsg += `
Flood ${ucFirst( stageOrFlow )} is ${floodValue} ${floodUnit}` } return { shortmsg: shortmsg, longmsg: longmsg } } ...

Sample 2: The hydrographs have a sub-heading below the chart that shows pertinant meta data associated with the display from the U.S. Geologocial Survey, the data timezone, PEDTS information and when the data's created and issued timestamps.


// Used in three places within the hydrograph gauge view and index view features panel: frontend/components/hydrograph/src/Chart.svelte
...
        getMetaDataSubHeading(this, series, gaugeConfig ? gaugeConfig : null)
...

// From frontend/components/hydrograph/src/base.js
...
/**
 * For the "Reformat Gauge Page" in OWP-795
 * This render displays metadata under the "Site Time" on the chart
 * @param {*} chart
 * @param {*} series
 * @returns
 */
export function getMetaDataSubHeading(chart, series, gaugeConfig) {
  const isMobile = window.innerWidth < 950
  if (series.dataExists == false || !series.gauge) return
  let attributions = gaugeConfig ? gaugeConfig.dataAttribution : null
  // Get the vertical datum index zero as the default gauge datum
  let datumOption =
    gaugeConfig && gaugeConfig.datums.vertical.value.length
      ? gaugeConfig.datums.vertical.options.filter((i) => i.id === gaugeConfig.datums.vertical.value[0].id)
      : null
  let datumOpt = datumOption ? datumOption[0].abbrev.replace('*', '') : 'N/A'
  let datumElev = datumOption ? gaugeConfig.datums.vertical.value[0].value : 'N/A'
  let attrTextArr = []

  // Calculate hydrograph width and height by pixels.
  let extX = chart.xAxis[0].getExtremes()
  //let extY = chart.yAxis[0].getExtremes()
  let xmaxP = chart.xAxis[0].toPixels(extX.max)
  //let xminP = chart.xAxis[0].toPixels(extX.min)

  // Display at most top two data attribution links on the hydrograph. (TM)
  if (attributions && attributions.value.length > 0) {
    attributions.value.slice(0, 2).forEach((a) => {
      attrTextArr.push(`${a.title.value}`)
    })
  }

  // TODO: If no attribution text, then no need to create label. (TM)
  let labelAttribution = chart.renderer
    .label(attrTextArr.join('
'), null, null, null, null, null, true) .css({ // width: 'min-content', border: '0', fontSize: isMobile ? '7px' : '10px', width: isMobile ? '100px' : 'auto', }) .attr({ class: 'metadataLabelOfficial', padding: 5, }) .add() let labelLidCSS = { width: isMobile ? '100px' : '180px', border: '0', fontSize: isMobile ? '7px' : '10px', } // Character at end of string literal template is a degree symbol (ascii: ˚) let labelLid = chart.renderer .label( `${series.gauge.lid.toUpperCase()} (plotting ${series.gauge.pedts.observed.toUpperCase()}) "Gage 0" Datum (${datumOpt}): ${datumElev}` + ''' ) .css(labelLidCSS) .attr({ class: 'metadataLabelOfficial', padding: 5, }) .add() // Hide the "Forecast Issued" text if the PEDTs is old (expired). let PEDTSExpired = false let labelForecastIssuedStr = ` - Forecast Issued (${getDateTimeStamp(series, 'fcst')})` if (series.gauge.status.forecast == null || series.gauge.status.forecast.floodCategory == 'old') { PEDTSExpired = true } else if ( series.gauge.status.forecast.floodCategory == '' || series.gauge.status.forecast.floodCategory == 'unknown' ) { if ( series.gauge.status.forecast != null && series.gauge.status.forecast.primary <= -999 && series.gauge.status.forecast.secondary <= -999 ) { PEDTSExpired = true } } if (PEDTSExpired || series.forecastIssuedTime == '0001-01-01T00:00:00Z') { labelForecastIssuedStr = '' } let labelTime = chart.renderer .label( `Graph Created: (${getDateTimeStamp(series, 'now')}) ${labelForecastIssuedStr}` ) .css({ border: '0', fontSize: isMobile ? '7px' : '10px', }) .attr({ class: 'metadataLabelOfficial', padding: 5, }) .add() // Default placement settings let labelLid_x = xmaxP / 3 let labelLid_y = -105 let labelAttribution_x = (xmaxP / 3) * -1 let labelAttribution_y = -100 let labelTime_x = -10 let labelTime_y = -90 labelAttribution.align( Highcharts.extend(labelAttribution.getBBox(), { align: 'center', x: labelAttribution_x, verticalAlign: 'bottom', y: labelAttribution_y, }), null, 'spacingBox' ) labelLid.align( Highcharts.extend(labelLid.getBBox(), { align: 'center', x: labelLid_x, verticalAlign: 'bottom', y: labelLid_y, }), null, 'spacingBox' ) labelTime.align( Highcharts.extend(labelTime.getBBox(), { align: 'center', x: labelTime_x, verticalAlign: 'bottom', y: labelTime_y, }), null, 'spacingBox' ) } ...

Sample 3: The NWPS website uses four different permalink instances for River-At-A-Glance (RAAG), Gauges, HDSC and the Map view for getting a configured settings of the views with selected options. I did most of the work on the HEFS within the Gauges view. I basically copied the Map view's source code and configured it for the HEFS hydrograph. I also did bugfixes and updates on the map permalink.


// From frontend/components/gauge/src/App.svelte
...

onMount(async () => {
    window.addEventListener('load', () => {
      // Tested using "await tick()" here and it did not work. MS
      setTimeout(() => {
        const {
          hydrograph: { enabled: officailEnabled },
          hydrographNWM: { enabled: NWMEnabled },
          hefs: { enabled: HEFSEnabled },
        } = gaugeConfig
        permalink = new Permalink({ official: officailEnabled, nwm: NWMEnabled, hefs: HEFSEnabled })
        permalink.setHydrograph(document.documentElement)
      }, 300)
})
...

// From frontend/components/gauge/permalink.js
...
export class Permalink {
  // There are three parts to maintaining state via the URL:
  //   1. Creating a query string that encodes the current hydrograph version and state.
  //   2. Parsing the query string and restoring hydrograph state.
  //
  //  NOTE the standard URI:    /gauges/JRSP1#v=official
  //                            /gauges/JRSP1#v=hefs
  //                            /gauges/JRSP1#v=nwm
  //

  // Used to identify within the class if HEFS data is available.
  hefsEnabled = false

  /**
   * Initialize a Permalink instance.
   * Reads the initial URL hash (if present) and sets up a popstate handler
   * to detect browser forward/back navigation.
   * The parameter hefsEnabled is used to check if there is HEFS data avaiable.
   */
  constructor(enabledHGTypes) {
    this.enabledHGTypes = enabledHGTypes
    this.validHGParams = ['official', 'nwm', 'hefs']
    let queryString = window.location.hash.substring(1)
    if (queryString == '') {
      queryString = `${hydrographVersion}=official`
    }
    let params = new URLSearchParams(queryString)
    this.parseHydrographConfig(params)
  }


  /**
   * Will parse the URL parameters and update the frontend.
   * @param {*} param - hydrograph `official`, `hefs`, or `nwm`
   * @returns
   */
  parseHydrographConfig(params) {
    let newHG = params.get(hydrographVersion)
    // check the param passed in
    if(!this.validHGParams.includes(newHG)) newHG = 'official'
    // make sure hg is enabled
    if (!this.isValidHG(newHG)) {
      newHG = this.getNextValidHG()
      if (!newHG) {
        // there is no valid hg type. very rare
        newHG = 'official'
      }
    }
    currentHGView.set(newHG)
    this.showHydrograph(newHG)
  }

  isValidHG(HGType) {
    return !!this.enabledHGTypes[HGType]
  }

  getNextValidHG() {
    const stack = Array.from(this.validHGParams)
    while (stack.length > 0) {
      const hg = stack.shift()
      if(this.isValidHG(hg)) return hg
    }
    return null
  }

  /**
   * Handles the actual hydrograph display. We have to use the click because of the way the hydrographs show within the html.
   * @param {*} param - hydrograph `official`, `hefs`, or `nwm`
   * @returns
   */
  async showHydrograph(param) {
    let tab, id
    switch (param) {
      case 'hefs':
        id = `#HEFSHGbutton`
        break
      case 'nwm':
        id = `#NWMHGbutton`
        break
      case 'official': // official hydrograph
        id = `#DefaultHGbutton`
        break
    }
    // NOTE: this is important with non-windows google chrome versions. MS and MSA
    setTimeout(() => {
      tab = document.querySelector(id)
      if (tab) {
        tab.click()
      } else {
        // rare case where NWM and hydrograph and hefs enabled is set to false
        return
      }
    }, 300)
  }

  /**
   * Registers the highcharts instance and sets up event listeners for state changes.
   */
  setHydrograph() {
      currentHGView.subscribe((value) => {
        this.replaceState()
      })
      this.pushState()
  }

  /**
   * Replace the current history entry with the URL/state representing
   * the current hydrograph view.
   * @returns {void}
   */
  replaceState() {
    const { qs, state } = this.getHydrographState()
    history.replaceState(state, null, qs)
  }

  /**
   * Push a new history entry for the current hydrograph view.
   * @returns {void}
   */
  pushState() {
    const { qs, state } = this.getHydrographState()
    history.pushState(state, null, qs)
  }

  /**
   * @typedef {Object} HydroState
   * @property {string} qs - The query string/hash to use in the URL
   * @property {Object} state - The state object to attach to history
   * @returns {HydroState}
   */
  getHydrographState() {
    // Holds the URL parameters that we create.
    let params = []
    // State object that can be passed to the history pushState and
    // replaceState methods.
    let state = {}

    state.hydrographVersion = get(currentHGView)
    params.push(`${hydrographVersion}=${state.hydrographVersion}`)
    const qs = `#${params.join('&')}`
    return { qs, state }
  }

  /**
   *  Check if HEFS data is available with HEFS param
   * @param {*} param
   * @returns
   */
  isHEFSAvailable(param) {
    if (param === 'hefs' && !this.hefsEnabled) {
        return false
    }
    return true
  }
}
...