-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstyling.ts
More file actions
60 lines (54 loc) · 1.55 KB
/
styling.ts
File metadata and controls
60 lines (54 loc) · 1.55 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
import { notEmpty } from "./arrays";
/**
* Applies styles to a given HTML element
* @param element HTML element
* @param styles object of CSS styles
* @example applyStyles(document.body, {overflowY: "hidden"});
*/
export const applyStyles = (
element: HTMLElement,
styles: Partial<CSSStyleDeclaration>
): void => {
Object.entries(styles).forEach(([property, value]) => {
element.style[property] = value;
});
};
type TransformAttribute =
| "perspective"
| "rotate"
| "rotateX"
| "rotateY"
| "rotateZ"
| "scale"
| "scaleX"
| "scaleY"
| "skewX"
| "skewY"
| "translateX"
| "translateY"
| "transformX"
| "transformY"
| "transformZ";
/**
* Gets pixel values for each of the given element's transform attributes
* @param element HTML element
* @returns map of transform attributes to their values
* @example "transformX(10px) transformY(20px)" -> {transformX: 10, transformY: 20}
*/
export const parseTransformAttributeValue = (
element: HTMLElement
): Record<TransformAttribute, number> => {
const value = element.style.transform;
const transformFunctions = value.split(" ");
const entries = transformFunctions
.map((transformFunction: string) => {
if (!transformFunction) {
return undefined;
}
const name = transformFunction.split("(")[0];
const value = parseFloat(transformFunction.split("(")[1].split("px")[0]);
return isNaN(value) ? undefined : ([name, value] as const);
})
.filter(notEmpty);
return Object.fromEntries(entries) as Record<TransformAttribute, number>;
};