aboutsummaryrefslogtreecommitdiff
path: root/src/content/components/common/hint.js
blob: 14725872623a60ad7de49cb01029f481d256e261 (plain) (blame)
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
import * as dom from 'shared/utils/dom';

const hintPosition = (element) => {
  let { left, top, right, bottom } = dom.viewportRect(element);

  if (element.tagName !== 'AREA') {
    return { x: left, y: top };
  }

  return {
    x: (left + right) / 2,
    y: (top + bottom) / 2,
  };
};

export default class Hint {
  constructor(target, tag) {
    if (!(document.body instanceof HTMLElement)) {
      throw new TypeError('target is not an HTMLElement');
    }

    this.target = target;

    let doc = target.ownerDocument;
    let { x, y } = hintPosition(target);
    let { scrollX, scrollY } = window;

    this.element = doc.createElement('span');
    this.element.className = 'vimvixen-hint';
    this.element.textContent = tag;
    this.element.style.left = x + scrollX + 'px';
    this.element.style.top = y + scrollY + 'px';

    this.show();
    doc.body.append(this.element);
  }

  show() {
    this.element.style.display = 'inline';
  }

  hide() {
    this.element.style.display = 'none';
  }

  remove() {
    this.element.remove();
  }
}