-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjodaresponsive.ts
executable file
·117 lines (95 loc) · 2.84 KB
/
jodaresponsive.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import {Logger} from "../helper/logger";
export const breakpoints = {
"xsm": 0,
"sm": 576,
"md": 768,
"lg": 992,
"xl": 1200,
"xxl": 1400
}
export function getCurrentBreakpoint() : string {
let ret = "";
Object.keys(breakpoints).forEach((key) => {
if (window.innerWidth >= breakpoints[key]) {
ret = key;
}
});
return ret;
}
class ResponsiveClass {
always: string[] = [];
default: string[] = null;
xsm: null = null;
xs: string[] = null;
sm: string[] = null;
md: string[] = null;
lg: string[] = null;
xl: string[] = null;
xxl: string[] = null;
breakpoints = ["xsm", "xs", "sm", "md", "lg", "xl", "xxl"];
getClassesForBreakpoint(breakpoint : string = null) : string[] {
if (breakpoint === null) {
breakpoint = getCurrentBreakpoint();
}
let ret = [];
ret.push(...this.always);
let isDefault = true;
for (let bp of this.breakpoints) {
//console.log("Breakpoint", bp, this[bp], breakpoint);
if (this[bp] !== null) {
ret = this[bp];
isDefault = false;
}
if (bp === breakpoint) {
break;
}
}
if (isDefault && this.default !== null) {
ret.push(...this.default);
}
ret = ret.filter((item) => item !== "");
return ret;
};
}
export function parseClassStr(input : string) : ResponsiveClass {
let ret = new ResponsiveClass();
let pointer = "always";
input.split(" ").map((item) => {
let matches = item.match(/\:([a-zA-Z]*)\:/);
if (matches === null) {
ret[pointer].push(item);
return;
}
pointer = matches[1];
if (pointer === "") {
pointer = "default";
}
if (ret[pointer] === null) {
ret[pointer] = [];
}
});
return ret;
}
export class Jodaresponsive {
constructor(public logger : Logger) {
}
private processNode(node : HTMLElement) {
const origAttr = "data-class-orig";
if ( ! node.hasAttribute(origAttr)) {
let classes = node.getAttribute("class") ?? "";
if (classes.indexOf(":") === -1)
return;
node.setAttribute(origAttr, classes);
}
let classes = node.getAttribute(origAttr);
let responsiveClasses = parseClassStr(classes);
node.setAttribute("class", "");
node.classList.add(...responsiveClasses.always.filter((item) => item !== ""));
node.classList.add(...responsiveClasses.getClassesForBreakpoint());
}
process(node : HTMLElement) {
Array.from([node, ...Array.from(node.querySelectorAll<HTMLElement>("*"))]).forEach((child) => {
this.processNode(child);
});
}
}