element.js 1.7 KB
Newer Older
K
Kamran Ahmed 已提交
1 2 3
import Position from './position';

export default class Element {
K
Kamran Ahmed 已提交
4 5 6 7
  /**
   * DOM element object
   * @param node
   */
K
Kamran Ahmed 已提交
8 9 10 11 12
  constructor(node) {
    this.element = node;
    this.document = document;
  }

K
Kamran Ahmed 已提交
13 14 15 16
  /**
   * Gets the screen co-ordinates (x,y) for the current dom element
   * @returns {{x: number, y: number}}
   */
K
Kamran Ahmed 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
  getScreenCoordinates() {
    let tempNode = this.element;

    let x = this.document.documentElement.offsetLeft;
    let y = this.document.documentElement.offsetTop;

    if (tempNode.offsetParent) {
      do {
        x += tempNode.offsetLeft;
        y += tempNode.offsetTop;
      } while (tempNode = tempNode.offsetParent);
    }

    return { x, y };
  }

K
Kamran Ahmed 已提交
33 34 35 36 37
  /**
   * Gets the calculated position on screen, around which
   * we need to draw
   */
  getCalculatedPosition() {
K
Kamran Ahmed 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
    const coordinates = this.getScreenCoordinates();
    const position = new Position({
      left: Number.MAX_VALUE,
      top: Number.MAX_VALUE,
      right: 0,
      bottom: 0,
    });

    // If we have the position for this element
    // and the element is visible on screen (has some height)
    if (typeof coordinates.x === 'number' && typeof coordinates.y === 'number' && (this.element.offsetWidth > 0 || this.element.offsetHeight > 0)) {
      position.left = Math.min(position.left, coordinates.x);
      position.top = Math.min(position.top, coordinates.y);
      position.right = Math.max(position.right, coordinates.x + this.element.offsetWidth);
      position.bottom = Math.max(position.bottom, coordinates.y + this.element.offsetHeight);
    }

    return position;
  }
57 58 59 60 61

  onHighlighted() {
    console.log('on highlighted');
    console.log(this.getScreenCoordinates());
  }
K
Kamran Ahmed 已提交
62
}