-
Notifications
You must be signed in to change notification settings - Fork 790
/
Copy pathcss-style-declaration.ts
111 lines (94 loc) · 2.48 KB
/
css-style-declaration.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
export class MockCSSStyleDeclaration {
private _styles = new Map<string, string>();
setProperty(prop: string, value: string) {
prop = jsCaseToCssCase(prop);
if (value == null || value === '') {
this._styles.delete(prop);
} else {
this._styles.set(prop, String(value));
}
}
getPropertyValue(prop: string) {
prop = jsCaseToCssCase(prop);
return String(this._styles.get(prop) || '');
}
removeProperty(prop: string) {
prop = jsCaseToCssCase(prop);
this._styles.delete(prop);
}
get length() {
return this._styles.size;
}
get cssText() {
const cssText: string[] = [];
this._styles.forEach((value, prop) => {
cssText.push(`${prop}: ${value};`);
});
return cssText.join(' ').trim();
}
set cssText(cssText: string) {
if (cssText == null || cssText === '') {
this._styles.clear();
return;
}
cssText.split(';').forEach(rule => {
rule = rule.trim();
if (rule.length > 0) {
const splt = rule.split(':');
if (splt.length > 1) {
const prop = splt[0].trim();
const value = splt[1].trim();
if (prop !== '' && value !== '') {
this._styles.set(jsCaseToCssCase(prop), value);
}
}
}
});
}
hasAttribute() {
return false;
}
}
export function createCSSStyleDeclaration() {
return new Proxy(new MockCSSStyleDeclaration(), cssProxyHandler);
}
const cssProxyHandler: ProxyHandler<MockCSSStyleDeclaration> = {
get(cssStyle, prop: string) {
if (prop in cssStyle) {
return (cssStyle as any)[prop];
}
prop = cssCaseToJsCase(prop);
return cssStyle.getPropertyValue(prop);
},
set(cssStyle, prop: string, value) {
if (prop in cssStyle) {
(cssStyle as any)[prop] = value;
} else {
cssStyle.setProperty(prop, value);
}
return true;
},
};
function cssCaseToJsCase(str: string) {
// font-size to fontSize
if (str.length > 1 && str.includes('-') === true) {
str = str
.toLowerCase()
.split('-')
.map(segment => segment.charAt(0).toUpperCase() + segment.slice(1))
.join('');
str = str.substr(0, 1).toLowerCase() + str.substr(1);
}
return str;
}
function jsCaseToCssCase(str: string) {
// fontSize to font-size
if (str.length > 1 && str.includes('-') === false && /[A-Z]/.test(str) === true) {
str = str
.replace(/([A-Z])/g, g => ' ' + g[0])
.trim()
.replace(/ /g, '-')
.toLowerCase();
}
return str;
}