-
Notifications
You must be signed in to change notification settings - Fork 142
Expand file tree
/
Copy pathhandleElementHighlights.js
More file actions
65 lines (56 loc) · 1.81 KB
/
handleElementHighlights.js
File metadata and controls
65 lines (56 loc) · 1.81 KB
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
import throttle from 'lodash-es/throttle';
import channel from './channel';
const RESIZE_THROTTLE = 250;
let highlightSelector = null;
const handleWindowResize = throttle(() => {
updateCovers(highlightSelector);
}, RESIZE_THROTTLE);
window.addEventListener('resize', handleWindowResize);
function getOffsetFromBody(element) {
if (element === document.body) {
return {top: 0, left: 0};
}
const {top, left} = getOffsetFromBody(element.offsetParent);
return {top: top + element.offsetTop, left: left + element.offsetLeft};
}
function removeCovers() {
const highlighterElements =
document.querySelectorAll('.__popcode-highlighter');
for (const highlighterElement of highlighterElements) {
highlighterElement.remove();
}
}
function addCovers(selector) {
const elements = document.querySelectorAll(selector);
for (const element of elements) {
const cover = document.createElement('div');
const rect = element.getBoundingClientRect();
let offset = {top: rect.top, left: rect.left};
if (element.offsetParent === null) {
cover.style.position = 'fixed';
} else if (element !== document.body ||
element !== document.documentElement) {
offset = getOffsetFromBody(element);
}
document.body.appendChild(cover);
cover.classList = '__popcode-highlighter';
cover.style.left = `${offset.left}px`;
cover.style.top = `${offset.top}px`;
cover.style.width = `${element.offsetWidth}px`;
cover.style.height = `${element.offsetHeight}px`;
cover.classList.add('fade');
}
}
function updateCovers(selector) {
removeCovers();
if (selector !== null) {
highlightSelector = selector;
addCovers(selector);
}
}
export default function handleElementHighlights() {
channel.bind(
'highlightElement',
(_trans, selector) => updateCovers(selector),
);
}