All files / Canvas SequenceViewer.js

53.01% Statements 44/83
13.64% Branches 3/22
55% Functions 11/20
53.01% Lines 44/83
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 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385                                                                        7x   7x   7x   7x         7x 7x 7x       7x 7x                   7x 7x 7x     7x     7x       117x 117x         117x     117x                                   7x 7x 7x 7x   7x 15x 117x 117x 117x 117x 117x 117x                                                         7x                                                                                                                                     4x 4x       7x       7x           7x       4x           4x                                 4x                                                                                                                                                                                           4x   4x   7x       7x       7x                                                  
/**
* Copyright 2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
 
import PropTypes from 'prop-types';
 
import {
  clamp,
  floor,
  isEqual,
  pick,
} from 'lodash-es';
 
import DraggingComponent from './DraggingComponent';
import TilingGrid from './CanvasTilingGrid';
import CanvasCache from './CanvasCache';
 
import { movePosition } from '../../store/positionReducers';
import positionStoreMixin from '../../store/positionStoreMixin';
import msaConnect from '../../store/connect'
 
import Mouse from '../../utils/mouse';
import { roundMod } from '../../utils/math';
 
import debug from '../../debug';
 
/**
 * Component to draw the main sequence alignment.
 */
class SequenceViewerComponent extends DraggingComponent {
 
  constructor(props) {
    super(props);
    // cache fully drawn tiles
    this.tileCache = new CanvasCache();
    // cache individual residue cells
    this.residueTileCache = new CanvasCache();
    // the manager which is in charge of drawing residues
    this.tilingGridManager = new TilingGrid();
  }
 
  // starts the drawing process
  drawScene() {
    const positions = this.getTilePositions();
    this.updateTileSpecs();
    Iif (debug) {
      this.redrawStarted = Date.now();
      this.redrawnTiles = 0;
    }
    this.drawTiles(positions);
    Iif (debug) {
      const elapsed = Date.now() - this.redrawStarted;
      if (elapsed > 5) {
        console.log(`Took ${elapsed} msecs to redraw for ${positions.startXTile} ${positions.startYTile} (redrawnTiles: ${this.redrawnTiles})`);
      }
    }
  }
 
  // figures out from where to start drawing
  getTilePositions() {
    const startXTile = Math.max(0, this.position.currentViewSequencePosition - this.props.cacheElements);
    const startYTile = Math.max(0, this.position.currentViewSequence - this.props.cacheElements);
    const endYTile = Math.min(this.props.sequences.length,
      startYTile + this.props.nrYTiles + 2 * this.props.cacheElements,
    );
    const endXTile = Math.min(this.props.sequences.maxLength,
      startXTile + this.props.nrXTiles + 2 * this.props.cacheElements,
    );
    return {startXTile, startYTile, endXTile, endYTile};
  }
 
  renderTile = ({row, column}) => {
    const key = row + "-" + column;
    return this.tileCache.createTile({
      key: key,
      tileWidth: this.props.tileWidth * this.props.xGridSize,
      tileHeight: this.props.tileHeight * this.props.yGridSize,
      create: ({canvas}) => {
        Iif (debug) {
          this.redrawnTiles++;
        }
        this.tilingGridManager.draw({
          ctx: canvas,
          startYTile:row,
          startXTile:column,
          residueTileCache: this.residueTileCache,
          endYTile:row + this.props.yGridSize,
          endXTile:column + this.props.xGridSize,
          ...pick(this.props, [
            "sequences", "colorScheme", "textFont", "textColor",
            "tileHeight", "tileWidth", "border", "borderWidth", "borderColor",
          ])
        });
      },
    });
  }
 
 
  drawTiles({startXTile, startYTile, endXTile, endYTile}) {
    const xGridSize = this.props.xGridSize;
    const yGridSize = this.props.yGridSize;
    const startY = roundMod(startYTile, yGridSize);
    const startX = roundMod(startXTile, xGridSize);
 
    for (let i = startY; i < endYTile; i = i + yGridSize) {
      for (let j = startX; j < endXTile; j = j + xGridSize) {
        const canvas = this.renderTile({row: i, column: j, canvas: this.ctx});
        const width = xGridSize * this.props.tileWidth;
        const height = yGridSize * this.props.tileHeight;
        const yPos = (i - this.position.currentViewSequence) * this.props.tileHeight + this.position.yPosOffset;
        const xPos = (j - this.position.currentViewSequencePosition) * this.props.tileWidth + this.position.xPosOffset;
        this.ctx.drawImage(canvas, 0, 0, width, height,
          xPos, yPos, width, height);
      }
    }
  }
 
  onPositionUpdate = (oldPos, newPos) => {
    const relativeMovement = {
      xMovement: oldPos[0] - newPos[0],
      yMovement: oldPos[1] - newPos[1],
    };
    this.dispatch(movePosition(relativeMovement));
  }
 
  positionToSequence(pos) {
    const sequences = this.props.sequences.raw;
    const seqNr = clamp(floor((this.position.yPos + pos.yPos) / this.props.tileHeight), 0, sequences.length - 1);
    const sequence = sequences[seqNr];
 
    const position = clamp(floor((this.position.xPos + pos.xPos) / this.props.tileWidth), 0, sequence.sequence.length - 1);
    return {
      i: seqNr,
      sequence,
      position,
      residue: sequence.sequence[position],
    }
  }
 
  updateScrollPosition = () => {
    this.draw();
  }
 
  componentDidUpdate() {
    this.draw();
  }
 
  /**
   * Returns the position of the mouse position relative to the sequences
   */
  currentPointerPosition(e) {
    const [x, y] = Mouse.rel(e);
    return this.positionToSequence({
      xPos: x,
      yPos: y,
    });
  }
 
  /**
   * Only sends an event if the actual function is set.
   */
  sendEvent(name, data) {
    if (this.props[name] !== undefined) {
      this.props[name](data);
    }
  }
 
  onMouseMove = (e) => {
    if (typeof this.isInDragPhase === "undefined") {
      if (this.props.onResidueMouseEnter !== undefined ||
          this.props.onResidueMouseLeave !== undefined) {
        const eventData = this.currentPointerPosition(e);
        const lastValue = this.currentMouseSequencePosition;
        if (!isEqual(lastValue, eventData)) {
          if (lastValue !== undefined) {
            this.sendEvent('onResidueMouseLeave', lastValue);
          }
          this.currentMouseSequencePosition = eventData;
          this.sendEvent('onResidueMouseEnter', eventData);
        }
      }
    }
    super.onMouseMove(e);
  }
 
  onMouseLeave = (e) => {
    this.sendEvent('onResidueMouseLeave', this.currentMouseSequencePosition);
    this.currentMouseSequencePosition = undefined;
    super.onMouseLeave(e);
  }
 
  onClick = (e) => {
    console.log("onCLICK");
    if (!this.mouseHasMoved) {
      const eventData = this.currentPointerPosition(e);
      this.sendEvent('onResidueClick', eventData);
    }
    super.onClick(e);
  }
 
  onDoubleClick = (e) => {
    const eventData = this.currentPointerPosition(e);
    this.sendEvent('onResidueDoubleClick', eventData);
    super.onDoubleClick(e);
  }
 
  componentWillUnmount() {
    this.tileCache.invalidate();
    this.residueTileCache.invalidate();
  }
 
  updateTileSpecs() {
    this.tileCache.updateTileSpecs(pick(this.props, [
      'tileWidth', 'tileHeight', 'colorScheme', 'textFont',
      'xGridSize', 'yGridSize', 'sequences',
    ]));
    this.residueTileCache.updateTileSpecs(pick(this.props, [
      'tileWidth', 'tileHeight', 'colorScheme', 'textFont'
    ]));
  }
 
  render() {
    return super.render();
  }
}
 
positionStoreMixin(SequenceViewerComponent, {
  withX: true,
  withY: true,
  withPosition: true,
});
 
SequenceViewerComponent.defaultProps = {
  showModBar: false,
  xGridSize: 10,
  yGridSize: 10,
  border: false,
  borderColor: "black",
  borderWidth: 1,
  cacheElements: 20,
  textColor: "black",
  textFont: "18px Arial",
  overflow: "hidden",
  overflowX: "auto",
  overflowY: "auto",
  scrollBarPositionX: "bottom",
  scrollBarPositionY: "right",
};
 
SequenceViewerComponent.propTypes = {
  /**
   * Show the custom ModBar
   */
  showModBar: PropTypes.bool,
 
  /**
   * Callback fired when the mouse pointer is entering a residue.
   */
  onResidueMouseEnter: PropTypes.func,
 
  /**
   * Callback fired when the mouse pointer is leaving a residue.
   */
  onResidueMouseLeave: PropTypes.func,
 
  /**
   * Callback fired when the mouse pointer clicked a residue.
   */
  onResidueClick: PropTypes.func,
 
  /**
   * Callback fired when the mouse pointer clicked a residue.
   */
  onResidueDoubleClick: PropTypes.func,
 
  /**
   * Number of residues to cluster in one tile (x-axis) (default: 10)
   */
  xGridSize: PropTypes.number.isRequired,
 
  /**
   * Number of residues to cluster in one tile (y-axis) (default: 10)
   */
  yGridSize: PropTypes.number.isRequired,
 
  /**
   * Number of residues to prerender outside of the visible viewbox.
   */
  cacheElements: PropTypes.number.isRequired,
 
  /**
   * Whether to draw a border.
   */
  border: PropTypes.bool,
 
  /**
   * Color of the border. Name, hex or RGB value.
   */
  borderColor: PropTypes.string,
 
  /**
   * Width of the border.
   */
  borderWidth: PropTypes.number,
 
  /**
   * Color of the text residue letters (name, hex or RGB value)
   */
  textColor: PropTypes.string,
 
  /**
   * Font to use when drawing the individual residues.
   */
  textFont: PropTypes.string,
 
  /**
   * What should happen if content overflows.
   */
  overflow: PropTypes.oneOf(["hidden", "auto", "scroll"]),
 
  /**
   * What should happen if x-axis content overflows (overwrites "overflow")
   */
  overflowX: PropTypes.oneOf(["hidden", "auto", "scroll", "initial"]),
 
  /**
   * What should happen if y-axis content overflows (overwrites "overflow")
   */
  overflowY: PropTypes.oneOf(["hidden", "auto", "scroll", "initial"]),
 
  /**
   * X Position of the scroll bar ("top or "bottom")
   */
  scrollBarPositionX: PropTypes.oneOf(["top", "bottom"]),
 
  /**
   * Y Position of the scroll bar ("left" or "right")
   */
  scrollBarPositionY: PropTypes.oneOf(["left", "right"]),
};
 
// hoist the list of accepted properties to the parent
// eslint-disable-next-line react/forbid-foreign-prop-types
SequenceViewerComponent.propKeys = Object.keys(SequenceViewerComponent.propTypes);
 
const mapStateToProps = state => {
  // Fallback to a smaller size if the given area is too large
  const width = Math.min(
    state.props.width,
    state.sequences.maxLength * state.props.tileWidth
  );
  const height = Math.min(
    state.props.height,
    state.sequences.length * state.props.tileHeight
  );
  return {
    sequences: state.sequences,
    width,
    height,
    tileWidth: state.props.tileWidth,
    tileHeight: state.props.tileHeight,
    colorScheme: state.props.colorScheme,
    nrXTiles: state.sequenceStats.nrXTiles,
    nrYTiles: state.sequenceStats.nrYTiles,
    fullWidth: state.sequenceStats.fullWidth,
    fullHeight: state.sequenceStats.fullHeight,
  }
}
 
 
//const mapDispatchToProps = dispatch => {
  //return {
    //updatePosition: flow(updatePosition, dispatch),
  //}
//}
 
export default msaConnect(
  mapStateToProps,
  //mapDispatchToProps,
)(SequenceViewerComponent);