Skip to content

Commit 7121416

Browse files
committed
feat: add findParentByClassName, getEventPosition, triggerEvent, TriggerEvent
1 parent c9e291e commit 7121416

File tree

1 file changed

+42
-5
lines changed

1 file changed

+42
-5
lines changed

src/common/dom.ts

+42-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export type HTMLElementType = HTMLElement | null;
2+
export type TriggerEvent = 'click' | 'contextmenu' | 'hover';
23
export const select = document.querySelector.bind(document);
34
export const selectAll = document.querySelectorAll.bind(document);
45

@@ -37,17 +38,17 @@ export function getDocumentRect() {
3738
}
3839

3940
/**
40-
* Returns the position of element relative anchor's position
41+
* Returns the position of element relative to element position
4142
* @param element target element
42-
* @param anchorPos anchor's position
43+
* @param relatedPos the relative element position
4344
*/
4445
export function getRelativePosition(
4546
element: HTMLElement,
46-
anchorPos: IPosition
47+
relativePos: IPosition
4748
) {
4849
const page = getDocumentRect();
49-
const anchorX = anchorPos.x;
50-
const anchorY = anchorPos.y;
50+
const anchorX = relativePos.x;
51+
const anchorY = relativePos.y;
5152

5253
const marginRight = page.width - anchorX;
5354
const marginBottom = page.height - anchorY;
@@ -63,3 +64,39 @@ export function getRelativePosition(
6364
y,
6465
};
6566
}
67+
68+
export function getEventPosition(e: React.MouseEvent) {
69+
return {
70+
x: e.clientX,
71+
y: e.clientY
72+
}
73+
}
74+
75+
export function findParentByClassName<T>(element, className): T | null {
76+
try {
77+
while (element && element) {
78+
const classes = element.getAttribute('class');
79+
if (classes && classes.indexOf(className) > -1) {
80+
return element;
81+
}
82+
element = element.parentElement;
83+
}
84+
} catch (e) {
85+
throw new Error(e);
86+
}
87+
return null;
88+
}
89+
90+
export function triggerEvent(trigger: TriggerEvent) {
91+
switch (trigger) {
92+
case 'click': {
93+
return 'onClick';
94+
}
95+
case 'hover': {
96+
return 'onMouseOver';
97+
}
98+
default: {
99+
return trigger;
100+
}
101+
}
102+
}

0 commit comments

Comments
 (0)