view client/src/components/gauge/Waterlevel.vue @ 2715:8d96b9254465

client: waterlevel diagram: fixed console error when hovering the chart where no data is available
author Markus Kottlaender <markus@intevation.de>
date Mon, 18 Mar 2019 18:14:24 +0100
parents f393fabfdd35
children 18dc704e637e
line wrap: on
line source

<template>
  <div
    class="d-flex flex-fill justify-content-center align-items-center diagram-container"
  >
    <div v-if="!waterlevels.length">
      <translate>No data available.</translate>
    </div>
  </div>
</template>

<style lang="sass" scoped>
.diagram-container
  /deep/
    .main
      .line
        clip-path: url(#clip)
    .nav
      .line
        stroke: steelblue
        stroke-width: 2
        fill: transparent
        clip-path: url(#clip)

    .hdc-line,
    .ldc-line,
    .mw-line
      stroke-width: 1
      fill: transparent
      clip-path: url(#clip)
    .hdc-line
      stroke: red
    .ldc-line
      stroke: green
    .mw-line
      stroke: grey
    .ref-waterlevel-label
      font-size: 11px
      fill: #999
    .hdc-ldc-area
      fill: rgba(0, 255, 0, 0.15)

    .tick
      line
        stroke-dasharray: 5
        stroke: #ccc

    .zoom
      cursor: move
      fill: none
      pointer-events: all
    .brush
      .selection
        stroke: transparent
        fill-opacity: 0.2
      .handle
        stroke: rgba($color-info, 0.5)
        fill: rgba($color-info, 0.5)

    .chart-dots
      clip-path: url(#clip)
      .chart-dot
        fill: steelblue
        stroke: steelblue
        pointer-events: none
        opacity: 0
        transition: opacity 0.1s
    .chart-tooltip
      opacity: 0
      transition: opacity 0.3s
      rect
        fill: #fff
        stroke: #ccc
      text
        fill: #666
        font-size: 12px
</style>

<script>
/* This is Free Software under GNU Affero General Public License v >= 3.0
 * without warranty, see README.md and license for details.
 *
 * SPDX-License-Identifier: AGPL-3.0-or-later
 * License-Filename: LICENSES/AGPL-3.0.txt
 *
 * Copyright (C) 2018 by via donau
 *   – Österreichische Wasserstraßen-Gesellschaft mbH
 * Software engineering by Intevation GmbH
 *
 * Author(s):
 * Markus Kottländer <markus.kottlaender@intevation.de>
 */

import { mapState, mapGetters } from "vuex";
import * as d3Base from "d3";
import { lineChunked } from "d3-line-chunked";
import debounce from "debounce";

// we should load only d3 modules we need but for now we'll go with the lazy way
// https://www.giacomodebidda.com/how-to-import-d3-plugins-with-webpack/
const d3 = Object.assign(d3Base, { lineChunked });

export default {
  computed: {
    ...mapState("gauges", ["waterlevels", "dateFrom", "dateTo"]),
    ...mapGetters("gauges", ["selectedGauge"])
  },
  watch: {
    waterlevels() {
      this.drawDiagram();
    }
  },
  methods: {
    drawDiagram() {
      // remove old diagram
      d3.select(".diagram-container svg").remove();

      if (!this.selectedGauge || !this.waterlevels.length) return;

      // get HDC/LDC/MW of the gauge
      let refWaterLevels = JSON.parse(
        this.selectedGauge.properties.reference_water_levels
      );

      // CREATE SVG AND SET DIMENSIONS/MARGINS

      let svgWidth = document.querySelector(".diagram-container").clientWidth;
      let svgHeight = document.querySelector(".diagram-container").clientHeight;
      let svg = d3
        .select(".diagram-container")
        .append("svg")
        .attr("width", "100%")
        .attr("height", "100%");
      let mainMargin = { top: 20, right: 20, bottom: 110, left: 80 },
        navMargin = {
          top: svgHeight - mainMargin.top - 65,
          right: 20,
          bottom: 30,
          left: 80
        },
        width = +svgWidth - mainMargin.left - mainMargin.right,
        mainHeight = +svgHeight - mainMargin.top - mainMargin.bottom,
        navHeight = +svgHeight - navMargin.top - navMargin.bottom;

      // PREPARING AXES/SCALING

      // scaling helpers to convert real values to pixels
      // based on the diagrams dimensions
      let x = d3.scaleTime().range([0, width]),
        x2 = d3.scaleTime().range([0, width]),
        y = d3.scaleLinear().range([mainHeight, 0]),
        y2 = d3.scaleLinear().range([navHeight, 0]);
      // find min/max values for the waterlevel axis
      // including hdc/ldc (+/- 100 cm)
      let WaterlevelMinMax = d3.extent(
        [
          ...this.waterlevels,
          { waterlevel: refWaterLevels.HDC + 100 },
          { waterlevel: Math.max(refWaterLevels.LDC - 100, 0) }
        ],
        d => d.waterlevel
      );
      // setting the min and max values for the diagram axes
      let dateTo = new Date(this.dateTo.getTime() + 86400);
      x.domain(d3.extent([this.dateFrom, dateTo]));
      y.domain(WaterlevelMinMax);
      x2.domain(x.domain());
      y2.domain(y.domain());
      // creating the axes based on these scales
      let xAxis = d3
        .axisTop(x)
        .tickSizeInner(mainHeight)
        .tickSizeOuter(0);
      let xAxis2 = d3.axisBottom(x2);
      let yAxis = d3
        .axisRight(y)
        .tickSizeInner(width)
        .tickSizeOuter(0);

      // PREPARING CHART FUNCTIONS

      // waterlevel line in big chart
      // d3-line-chunked plugin: https://github.com/pbeshai/d3-line-chunked
      var mainLineChart = d3
        .lineChunked()
        .x(d => x(d.date))
        .y(d => y(d.waterlevel))
        .curve(d3.curveLinear)
        .isNext((prev, current) => {
          // points are "next to each other" when they are exactly 15 minutes apart
          return current.date - prev.date === 15 * 60 * 1000;
        })
        .lineStyles({ stroke: "steelblue" })
        .gapStyles({
          stroke: "steelblue",
          "stroke-opacity": 1,
          "stroke-dasharray": "3 3",
          "stroke-width": 1
        });
      // waterlevel line in small chart
      let navLineChart = d3
        .line()
        .curve(d3.curveMonotoneX)
        .x(d => x2(d.date))
        .y(d => y2(d.waterlevel));
      // hdc/ldc/mw
      let refWaterlevelLine = d3
        .line()
        .x(d => x(d.x))
        .y(d => y(d.y));

      // DRAWING MAINCHART

      // define visible chart area
      // everything outside this area will be hidden (clipped)
      svg
        .append("defs")
        .append("clipPath")
        .attr("id", "clip")
        .append("rect")
        .attr("width", width)
        .attr("height", mainHeight);

      let mainChart = svg
        .append("g")
        .attr("class", "main")
        .attr("transform", `translate(${mainMargin.left}, ${mainMargin.top})`);

      // axes
      mainChart
        .append("g")
        .attr("class", "axis--x")
        .attr("transform", `translate(0, ${mainHeight})`)
        .call(xAxis)
        .selectAll(".tick text")
        .attr("y", 15);
      mainChart // label
        .append("text")
        .text(this.$gettext("Waterlevel [cm]"))
        .attr("text-anchor", "middle")
        .attr("transform", `translate(-45, ${mainHeight / 2}) rotate(-90)`);
      mainChart
        .append("g")
        .call(yAxis)
        .selectAll(".tick text")
        .attr("x", -25);

      // reference waterlevels
      // filling area between HDC and LDC
      mainChart
        .append("rect")
        .attr("class", "hdc-ldc-area")
        .attr("x", 0)
        .attr("y", y(refWaterLevels.HDC))
        .attr("width", width)
        .attr("height", y(refWaterLevels.LDC) - y(refWaterLevels.HDC));

      // HDC
      mainChart
        .append("path")
        .datum([
          { x: 0, y: refWaterLevels.HDC },
          { x: dateTo, y: refWaterLevels.HDC }
        ])
        .attr("class", "hdc-line")
        .attr("d", refWaterlevelLine);
      mainChart // label
        .append("text")
        .text("HDC")
        .attr("class", "ref-waterlevel-label")
        .attr("x", x(dateTo) - 20)
        .attr("y", y(refWaterLevels.HDC) - 3);
      // LDC
      mainChart
        .append("path")
        .datum([
          { x: 0, y: refWaterLevels.LDC },
          { x: dateTo, y: refWaterLevels.LDC }
        ])
        .attr("class", "ldc-line")
        .attr("d", refWaterlevelLine);
      mainChart // label
        .append("text")
        .text("LDC")
        .attr("class", "ref-waterlevel-label")
        .attr("x", x(dateTo) - 20)
        .attr("y", y(refWaterLevels.LDC) - 3);
      // MW
      mainChart
        .append("path")
        .datum([
          { x: 0, y: refWaterLevels.MW },
          { x: dateTo, y: refWaterLevels.MW }
        ])
        .attr("class", "mw-line")
        .attr("d", refWaterlevelLine);
      mainChart // label
        .append("text")
        .text("MW")
        .attr("class", "ref-waterlevel-label")
        .attr("x", x(dateTo) - 20)
        .attr("y", y(refWaterLevels.MW) - 3);

      // waterlevel chart
      mainChart
        .append("g")
        .attr("class", "line")
        .datum(this.waterlevels)
        .transition()
        .duration(1000)
        .call(mainLineChart);

      // DRAWING NAVCHART

      let navChart = svg
        .append("g")
        .attr("class", "nav")
        .attr("transform", `translate(${navMargin.left}, ${navMargin.top})`);

      // axis (nav chart only has y-axis)
      navChart
        .append("g")
        .attr("class", "axis axis--x")
        .attr("transform", `translate(0, ${navHeight})`)
        .call(xAxis2);

      // waterlevel chart
      navChart
        .append("path")
        .datum(this.waterlevels)
        .attr("class", "line")
        .attr("d", navLineChart);

      // INTERACTIVITY

      // selecting time period in nav chart
      let brush = d3
        .brushX()
        .handleSize(4)
        .extent([[0, 0], [width, navHeight]])
        .on("brush end", () => {
          if (d3.event.sourceEvent && d3.event.sourceEvent.type === "zoom")
            return; // ignore brush-by-zoom
          let s = d3.event.selection || x2.range();
          x.domain(s.map(x2.invert, x2));
          mainChart.select(".line").call(mainLineChart);
          mainChart
            .select(".axis--x")
            .call(xAxis)
            .selectAll(".tick text")
            .attr("y", 15);
          svg
            .select(".zoom")
            .call(
              zoom.transform,
              d3.zoomIdentity.scale(width / (s[1] - s[0])).translate(-s[0], 0)
            );
        });

      // zooming with mousewheel in main chart
      let zoom = d3
        .zoom()
        .scaleExtent([1, Infinity])
        .translateExtent([[0, 0], [width, mainHeight]])
        .extent([[0, 0], [width, mainHeight]])
        .on("zoom", () => {
          if (d3.event.sourceEvent && d3.event.sourceEvent.type === "brush")
            return; // ignore zoom-by-brush
          let t = d3.event.transform;
          x.domain(t.rescaleX(x2).domain());
          mainChart.select(".line").call(mainLineChart);
          mainChart
            .select(".axis--x")
            .call(xAxis)
            .selectAll(".tick text")
            .attr("y", 15);
          navChart
            .select(".brush")
            .call(brush.move, x.range().map(t.invertX, t));
        })
        .on("start", () => {
          svg.select(".chart-dot").style("opacity", 0);
          svg.select(".chart-tooltip").style("opacity", 0);
        });

      navChart
        .append("g")
        .attr("class", "brush")
        .call(brush)
        .call(brush.move, x.range());

      let zoomRect = svg
        .append("rect")
        .attr("class", "zoom")
        .attr("width", width)
        .attr("height", mainHeight)
        .attr("transform", `translate(${mainMargin.left}, ${mainMargin.top})`)
        .call(zoom);

      // TOOLTIPS

      let dots = mainChart.append("g").attr("class", "chart-dots");
      dots
        .append("circle")
        .attr("class", "chart-dot")
        .attr("r", 4);
      let tooltips = mainChart.append("g").attr("class", "chart-tooltip");
      tooltips
        .append("rect")
        .attr("x", -25)
        .attr("y", -25)
        .attr("rx", 4)
        .attr("ry", 4)
        .attr("width", 105)
        .attr("height", 40);
      let tooltipText = tooltips.append("text");
      tooltipText
        .append("tspan")
        .attr("x", -15)
        .attr("y", -8);
      tooltipText
        .append("tspan")
        .attr("x", 8)
        .attr("y", 8)
        .style("font-weight", "bold");

      let bisectDate = d3.bisector(d => d.date).left;
      zoomRect
        .on("mouseover", () => {
          svg.select(".chart-dot").style("opacity", 1);
          svg.select(".chart-tooltip").style("opacity", 1);
        })
        .on("mouseout", () => {
          svg.select(".chart-dot").style("opacity", 0);
          svg.select(".chart-tooltip").style("opacity", 0);
        })
        .on("mousemove", () => {
          let x0 = x.invert(d3.mouse(document.querySelector(".zoom"))[0]),
            i = bisectDate(this.waterlevels, x0, 1),
            d0 = this.waterlevels[i - 1],
            d1 = this.waterlevels[i] || d0,
            d = x0 - d0.date > d1.date - x0 ? d1 : d0;

          svg
            .select(".chart-dot")
            .style("opacity", 1)
            .attr("transform", `translate(${x(d.date)}, ${y(d.waterlevel)})`);
          svg
            .select(".chart-tooltip")
            .style("opacity", 1)
            .attr(
              "transform",
              `translate(${x(d.date) - 25}, ${y(d.waterlevel) - 25})`
            );
          svg.select(".chart-tooltip text tspan:first-child").text(
            d.date.toLocaleString([], {
              year: "2-digit",
              month: "2-digit",
              day: "2-digit",
              hour: "2-digit",
              minute: "2-digit"
            })
          );
          svg
            .select(".chart-tooltip text tspan:last-child")
            .text(d.waterlevel + " cm");
        });
    }
  },
  created() {
    window.addEventListener("resize", debounce(this.drawDiagram), 100);
  },
  mounted() {
    this.drawDiagram();
  },
  updated() {
    this.drawDiagram();
  }
};
</script>