-
-
Notifications
You must be signed in to change notification settings - Fork 610
/
getRect.ts
97 lines (84 loc) · 2.03 KB
/
getRect.ts
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
import type {Coordinates, ClientRect, LayoutRect, ViewRect} from '../../types';
import {getScrollableAncestors, getScrollOffsets} from '../scroll';
import {defaultCoordinates} from '../coordinates';
function getEdgeOffset(
node: HTMLElement | null,
parent: (Node & ParentNode) | null,
offset = defaultCoordinates
): Coordinates {
if (!node || !(node instanceof HTMLElement)) {
return offset;
}
const nodeOffset = {
x: offset.x + node.offsetLeft,
y: offset.y + node.offsetTop,
};
if (node.offsetParent === parent) {
return nodeOffset;
}
return getEdgeOffset(node.offsetParent as HTMLElement, parent, nodeOffset);
}
export function getElementLayout(element: HTMLElement): LayoutRect {
const {offsetWidth: width, offsetHeight: height} = element;
const {x: offsetLeft, y: offsetTop} = getEdgeOffset(element, null);
return {
width,
height,
offsetTop,
offsetLeft,
};
}
export function getBoundingClientRect(
element: HTMLElement | Window
): ClientRect {
if (element instanceof Window) {
const width = window.innerWidth;
const height = window.innerHeight;
return {
top: 0,
left: 0,
right: width,
bottom: height,
width,
height,
offsetTop: 0,
offsetLeft: 0,
};
}
const {offsetTop, offsetLeft} = getElementLayout(element);
const {
width,
height,
top,
bottom,
left,
right,
} = element.getBoundingClientRect();
return {
width,
height,
top,
bottom,
right,
left,
offsetTop,
offsetLeft,
};
}
export function getViewRect(element: HTMLElement): ViewRect {
const {width, height, offsetTop, offsetLeft} = getElementLayout(element);
const scrollableAncestors = getScrollableAncestors(element);
const scrollOffsets = getScrollOffsets(scrollableAncestors);
const top = offsetTop - scrollOffsets.y;
const left = offsetLeft - scrollOffsets.x;
return {
width,
height,
top,
bottom: top + height,
right: left + width,
left,
offsetTop,
offsetLeft,
};
}