All files / app/components TimeplotGraph.tsx

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343          3x             3x                                                 3x           3x         3x         3x                 3x         3x         3x 3x                               4x 4x   4x 4x             4x 4x       5x           2x 2x 2x 3x               2x       2x       9x   9x       9x     9x                                         4x           11x           4x           4x 4x       4x   31x                               3x 3x           3x 3x     3x         3x 3x   3x           3x 3x   3x       1x 1x 1x       5x 5x 5x 5x 36x 5x 5x   5x       5x       5x               3x 3x 3x   3x         3x         3x 3x       4x         26x 26x 26x       26x       3x 3x 3x 3x 3x 3x   3x 3x   3x     4x 1x     4x 1x     4x 1x     1x 1x 1x   4x 1x     1x 1x     4x 1x     1x 1x      
import React from 'react';
import { throttle } from 'lodash';
import { debug } from 'app/utilities/logger';
import { style, getStyleVar } from 'app/styles';
import * as d3 from 'd3';
require('d3-selection-multi');
 
import { ICommit } from 'app/interfaces';
import { addMoveToFront } from 'app/utilities/d3';
import { dateFromEpochDate } from 'app/utilities/dates';
import { getUTCDateOfCommit, getHourOfCommit } from 'app/utilities/commits';
 
addMoveToFront(d3);
 
export interface TimeplotGraphProps {
  // The children are the menu content
  commits: ICommit[];
  startDate: number;
  endDate: number;
 
  // used for the x scale range
  earliestCommitDate: number;
  latestCommitDate: number;
 
  // increment or change the value passed to force a rerender of the graph
  // for zoom or resize changes
  forceRender?: number;
  height?: number;
  highlightedCommitIds?: string[];
  style?: string | object;
  onMouseEnter?: (evt, date?) => void;
  onMouseLeave?: (evt, date?) => void;
  onMouseMove?: (evt, date) => void;
  onMouseDown?: (evt, date) => void;
  onMouseUp?: (evt, date) => void;
}
 
const outerStyle = {
  _extends: 'fill',
  position: 'relative',
  overflow: 'hidden',
};
 
const blobStyle = {
  fill: '@colors.blobColor',
  opacity: 0.2,
};
 
const highlightedBlobStyle = {
  fill: '@colors.selected',
  opacity: 0.5,
};
 
const markerStyle = {
  position: 'absolute',
  height: 130,
  width: 3,
  opacity: 0.5,
  zIndex: 1,
  top: 0,
};
 
const startDateMarkerStyle = {
  _extends: markerStyle,
  backgroundColor: '@colors.leftRevColor',
};
 
const endDateMarkerStyle = {
  _extends: markerStyle,
  backgroundColor: '@colors.rightRevColor',
};
 
const LEFT_PADDING = 20;
const PADDING = 20;
 
//
// This class is just the timeplot display element.  See ./Timeplot for
// markers, hover popup, zoom and other features
//
export class TimeplotGraph extends React.Component<TimeplotGraphProps> {
  private timeplotGraphRef;
 
  private svg;
  public xScale;
  public yScale;
  public rScale;
  private updateTimeplotGraphThrottled;
 
  constructor(props) {
    super(props);
    this.timeplotGraphRef = React.createRef();
 
    this.renderTimeplotGraph = this.renderTimeplotGraph.bind(this);
    this.updateTimeplotGraphThrottled = throttle(
      this.updateTimeplotGraph,
      1000
    );
  }
 
  componentDidMount() {
    this.renderTimeplotGraph();
    window && window.addEventListener('resize', this.renderTimeplotGraph);
  }
 
  componentDidUpdate(prevProps) {
    if (
      prevProps.forceRender !== this.props.forceRender ||
      prevProps.earliestCommitDate !== this.props.earliestCommitDate ||
      prevProps.latestCommitDate !== this.props.latestCommitDate ||
      JSON.stringify(prevProps.commits) !== JSON.stringify(this.props.commits)
    ) {
      this.renderTimeplotGraph();
      this.forceUpdate();
      this.updateTimeplotGraphThrottled();
    } else Iif (
      prevProps.highlightedCommitIds !== this.props.highlightedCommitIds
    ) {
      this.updateHighlightedCommits();
    }
  }
 
  componentWillUnmount() {
    window && window.removeEventListener('resize', this.renderTimeplotGraph);
  }
 
  focus() {
    this.timeplotGraphRef.current.focus();
  }
 
  render() {
    const { startDate, endDate } = this.props;
    const startDateStyle =
      startDate && this.xScale
        ? { left: this.xScale && this.xScale(dateFromEpochDate(startDate)) }
        : {};
    const endDateStyle =
      endDate && this.xScale
        ? { left: this.xScale(dateFromEpochDate(endDate)) }
        : {};
    return (
      <div
        style={style(outerStyle, this.props.style)}
        onMouseEnter={this.onMouseEnter}
        onMouseLeave={this.onMouseLeave}
        onMouseMove={this.onMouseMove}
        onMouseDown={this.onMouseDown}
        onMouseUp={this.onMouseUp}
        data-testid="timeplotGraph"
      >
        <div style={style('fill')} ref={this.timeplotGraphRef} />
        {startDate ? (
          <div style={style(startDateMarkerStyle, startDateStyle)} />
        ) : null}
        {endDate ? (
          <div style={style(endDateMarkerStyle, endDateStyle)} />
        ) : null}
      </div>
    );
  }
 
  public getScrollWidth = () => {
    const element = this.timeplotGraphRef.current;
    return element && element.scrollWidth;
  };
 
  private getHeight(): number {
    return (
      (this.props.height && this.props.height) ||
      this.timeplotGraphRef.current.clientHeight
    );
  }
 
  public scrollLeft = newScrollLeft => {
    const element = this.timeplotGraphRef.current;
    element.scrollLeft = newScrollLeft;
  };
 
  private updateHighlightedCommits() {
    const explosionFactor = this.props.highlightedCommitIds.length < 5 ? 25 : 5;
    this.svg
      .selectAll('circle[data-selected="true"]')
      .styles(style(blobStyle))
      .attr('data-selected', false);
    this.svg
      .selectAll(`circle`)
      .filter(d => this.props.highlightedCommitIds.includes(d.id))
      .moveToFront()
      .styles(style(highlightedBlobStyle))
      .attr('data-selected', true)
      .transition()
      .duration(300)
      .attr(
        'r',
        d => this.rScale(d.linesAdded + d.linesDeleted || 0) * explosionFactor
      )
      .transition()
      .duration(800)
      .attr('r', d => this.rScale(d.linesAdded + d.linesDeleted || 0));
  }
 
  private clearTimeplotGraph() {
    const element = this.timeplotGraphRef.current;
    while (element.firstChild) {
      element.removeChild(element.firstChild);
    }
  }
 
  private renderTimeplotGraph() {
    const element = this.timeplotGraphRef.current;
    this.clearTimeplotGraph();
 
    // this.$element.width(this.zoom * 100 + '%');
    this.svg = d3
      .select(element)
      .append('svg')
      .attr('width', element.clientWidth)
      .attr('height', this.getHeight());
    this.calibrateScales();
    this.renderAxis();
 
    Iif (this.props.commits.length <= 0) {
      element.innerHtml =
        "<div class='placeholder'>No commits, nothing to see here.</div>";
      return;
    }
 
    this.renderBlobs();
    this.updateHighlightedCommits();
 
    debug(`TimeplotGraph: rendered`);
  }
 
  private updateTimeplotGraph() {
    this.calibrateScales();
    this.renderBlobs();
    this.updateHighlightedCommits();
  }
 
  private calibrateScales() {
    const element = this.timeplotGraphRef.current;
    const { earliestCommitDate, latestCommitDate, commits } = this.props;
    const w = element.clientWidth;
    const h = this.getHeight();
    const maxImpact = d3.max(commits.map(d => d.linesAdded + d.linesDeleted));
    const minDate = dateFromEpochDate(earliestCommitDate);
    const maxDate = dateFromEpochDate(latestCommitDate);
 
    this.xScale = d3
      .scaleTime()
      .domain([minDate, maxDate])
      .range([LEFT_PADDING, w - PADDING]);
    this.yScale = d3
      .scaleLinear()
      .domain([0, 25])
      .range([10, h - PADDING * 2 - 20]);
    this.rScale = d3
      .scalePow(10)
      .domain([1, maxImpact > 10000 ? 10000 : maxImpact])
      .range([3, 40])
      .clamp(true);
  }
 
  private renderAxis() {
    const element = this.timeplotGraphRef.current;
    const h = this.getHeight();
    const textColor = getStyleVar('colors', 'text');
 
    const xAxis = d3
      .axisBottom()
      .scale(this.xScale)
      .ticks(element.scrollWidth / 100);
 
    const renderedXaxis = this.svg
      .append('g')
      .attr('class', 'axis')
      .attr('transform', `translate(0, ${h - PADDING})`)
      .call(xAxis);
    renderedXaxis.selectAll('path,line').style('stroke', textColor);
    renderedXaxis.selectAll('text').style('fill', textColor);
  }
 
  private renderBlobs() {
    return this.svg
      .selectAll('circle')
      .data(this.props.commits)
      .enter()
      .append('circle')
      .attr('data-id', d => d.id)
      .attr('cx', d => this.xScale(getUTCDateOfCommit(d)))
      .attr('cy', d => this.yScale(getHourOfCommit(d) + 10))
      .styles(style(blobStyle))
      .transition()
      .duration(1000)
      .attr('r', d => this.rScale(d.linesAdded + d.linesDeleted));
  }
 
  private getDatesForMouseEvent(evt) {
    const element = this.timeplotGraphRef.current;
    const rect = element.getBoundingClientRect();
    const relativeLeft = evt.clientX - rect.x + element.scrollLeft;
    const exactDate = this.xScale.invert(relativeLeft);
    const startLeft = relativeLeft < 0 ? 0 : relativeLeft;
    const startDate = this.xScale.invert(startLeft);
    const endLeft =
      relativeLeft + 10 > element.width ? element.width : relativeLeft + 10;
    const endDate = this.xScale.invert(endLeft);
 
    return { exactDate, startDate, endDate, relativeLeft };
  }
 
  private onMouseEnter = evt => {
    this.props.onMouseEnter && this.props.onMouseEnter(evt);
  };
 
  private onMouseLeave = evt => {
    this.props.onMouseLeave && this.props.onMouseLeave(evt);
  };
 
  private onMouseMove = evt => {
    Iif (!this.props.onMouseMove) {
      return;
    }
    const dates = this.getDatesForMouseEvent(evt);
    this.setState({ hoverMarkerLeft: dates.relativeLeft });
    this.props.onMouseMove(evt, dates);
  };
  private onMouseDown = evt => {
    Iif (!this.props.onMouseDown) {
      return;
    }
    const dates = this.getDatesForMouseEvent(evt);
    this.props.onMouseDown(evt, dates);
  };
 
  private onMouseUp = evt => {
    Iif (!this.props.onMouseUp) {
      return;
    }
    const dates = this.getDatesForMouseEvent(evt);
    this.props.onMouseUp(evt, dates);
  };
}