Skip to content

Commit bb728c4

Browse files
committed
feat: add dom helper module
1 parent c628e16 commit bb728c4

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/common/dom.ts

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
export type HTMLElementType = HTMLElement | null;
2+
export const select = document.querySelector.bind(document);
3+
export const selectAll = document.querySelectorAll.bind(document);
4+
5+
export interface IPosition {
6+
x: number;
7+
y: number;
8+
}
9+
10+
/**
11+
* Get Document Rectangle info
12+
*/
13+
export function getDocumentRect() {
14+
const body = document.body;
15+
const html = document.documentElement;
16+
17+
const height = Math.max( body.scrollHeight, body.offsetHeight,
18+
html.clientHeight, html.scrollHeight, html.offsetHeight );
19+
20+
const width = Math.max( body.scrollWidth, body.offsetWidth,
21+
html.clientWidth, html.scrollWidth, html.offsetWidth );
22+
23+
return {
24+
height,
25+
width,
26+
};
27+
}
28+
29+
/**
30+
* Returns the position of element relative anchor's position
31+
* @param element target element
32+
* @param anchorPos anchor's position
33+
*/
34+
export function getRelativePosition(element: HTMLElement, anchorPos: IPosition) {
35+
const page = getDocumentRect();
36+
const anchorX = anchorPos.x;
37+
const anchorY = anchorPos.y;
38+
39+
const marginRight = page.width - anchorX;
40+
const marginBottom = page.height - anchorY;
41+
42+
const viewHeight = element.offsetHeight;
43+
const viewWidth = element.offsetWidth;
44+
45+
const x = marginRight < viewWidth ? anchorX - viewWidth : anchorX;
46+
const y = marginBottom < viewHeight ? anchorY - viewHeight : anchorY;
47+
48+
return {
49+
x,
50+
y,
51+
};
52+
}

0 commit comments

Comments
 (0)