-
Notifications
You must be signed in to change notification settings - Fork 56
/
responsiveStyle.ts
172 lines (147 loc) · 6.45 KB
/
responsiveStyle.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import { pxToNumber } from "../../../common/css";
import { PageModifier, trackModifierExecution } from "../_interface";
import CSSOMProvider, { isMediaRule, isStyleRule, isSupportsRule } from "./_provider";
@trackModifierExecution
export default class ResponsiveStyleModifier implements PageModifier {
private cssomProvider: CSSOMProvider;
private oldWidth = window.innerWidth;
private newWidth = 750;
private rootFontSizePx: number;
private fixedPositionRules: CSSStyleRule[] = [];
private expiredRules: CSSStyleRule[] = [];
private newRules: CSSStyleRule[] = [];
constructor(cssomProvider: CSSOMProvider) {
this.cssomProvider = cssomProvider;
// font size used to convert 'em' breakpoints to px
const rootFontSize = window
.getComputedStyle(document.documentElement)
.getPropertyValue("font-size");
this.rootFontSizePx = parseFloat(rootFontSize.match(/\d+/)[0]);
}
async iterateCSSOM() {
this.cssomProvider.stylesheets.map((sheet) => {
this.mapAggregatedRule(sheet);
});
}
private mapAggregatedRule(aggregationNode: CSSGroupingRule) {
for (let rule of aggregationNode.cssRules) {
if (isStyleRule(rule)) {
const position = rule.style.position;
if (position && (position === "fixed" || position === "sticky")) {
// allow full-page containers, e.g. https://developer.android.com/codelabs/basic-android-kotlin-training-shared-viewmodel?continue=https%3A%2F%2Fdeveloper.android.com%2Fcourses%2Fpathways%2Fandroid-basics-kotlin-unit-3-pathway-4%23codelab-https%3A%2F%2Fdeveloper.android.com%2Fcodelabs%2Fbasic-android-kotlin-training-shared-viewmodel#5
if (pxToNumber(rule.style.top) === 0 && pxToNumber(rule.style.bottom) === 0) {
continue;
}
this.fixedPositionRules.push(rule);
}
} else if (isSupportsRule(rule)) {
// recurse
this.mapAggregatedRule(rule);
} else if (isMediaRule(rule)) {
// recurse
this.mapAggregatedRule(rule);
const [appliedBefore, appliesNow] = this.parseMediaCondition(
rule,
this.oldWidth,
this.newWidth
);
if (appliedBefore && !appliesNow) {
this.expiredRules.push(
...[...rule.cssRules].filter((rule) => isStyleRule(rule) && !!rule.style)
);
}
if (!appliedBefore && appliesNow) {
this.newRules.push(
...[...rule.cssRules].filter((rule) => isStyleRule(rule) && !!rule.style)
);
}
}
}
}
private expiredRulesOriginalStyles: { [key: string]: [string, boolean] }[] = [];
private addedRules: CSSStyleRule[] = [];
enableResponsiveStyles() {
// disable desktop-only styles
this.expiredRules.map((rule, index) => {
// actually deleting & reinserting rule is hard -- need to keep track of mutating rule index
// so simply remove style properties from rule
// save properties for restoration later
// TODO measure performance of this
const obj = {};
for (const key of rule.style) {
obj[key] = [
rule.style.getPropertyValue(key),
rule.style.getPropertyPriority(key) === "important",
];
}
this.expiredRulesOriginalStyles.push(obj);
// @ts-ignore this works, even if it should be read-only in theory
rule.style = {};
});
// enable mobile styles
this.newRules.map((rule) => {
const newIndex = rule.parentStyleSheet.insertRule(
rule.cssText,
rule.parentStyleSheet.cssRules.length
);
const newRule = rule.parentStyleSheet.cssRules[newIndex] as CSSStyleRule;
this.addedRules.push(newRule);
});
}
disableResponsiveStyles() {
this.expiredRules.map((rule, index) => {
for (const [key, [value, isImportant]] of Object.entries(
this.expiredRulesOriginalStyles[index]
)) {
rule.style.setProperty(key, value, isImportant ? "important" : "");
}
});
this.addedRules.map((rule) => {
// @ts-ignore this works, even if it should be read-only in theory
rule.style = {};
});
}
private fixedElementsOriginalDisplay: string[] = [];
blockFixedElements() {
// completely remove fade-out elements (shifts layout)
this.fixedElementsOriginalDisplay = this.fixedPositionRules.map((rule) => {
const originalValue = rule.style.getPropertyValue("display");
rule.style.setProperty("display", "none", "important");
return originalValue;
});
}
unblockFixedElements() {
this.fixedPositionRules.map((rule, index) => {
const originalValue = this.fixedElementsOriginalDisplay[index];
rule.style.setProperty("display", originalValue);
});
}
private parseMediaCondition(rule: CSSMediaRule, oldWidth: number, newWidth: number) {
// TODO ideally, iterate the media list
const condition = rule.media[0];
// get viewport range where condition applies
let min = 0;
let max = Infinity;
let minMatch = /\(min-width:\s*([0-9]+)([a-z]+)/g.exec(condition);
let maxMatch = /\(max-width:\s*([0-9]+)([a-z]+)/g.exec(condition);
if (minMatch) {
min = this.unitToPx(minMatch[2], parseFloat(minMatch[1]));
}
if (maxMatch) {
max = this.unitToPx(maxMatch[2], parseFloat(maxMatch[1]));
}
const appliedBefore = min <= oldWidth && oldWidth <= max;
const appliesNow = min <= newWidth && newWidth <= max;
return [appliedBefore, appliesNow];
}
private unitToPx(unit: string, value: number) {
if (unit === "px") {
return value;
} else if (unit === "em" || unit === "rem") {
return value * this.rootFontSizePx;
} else {
console.error(`Unexpected media query breakpoint unit ${unit}:`, value);
return 1000000;
}
}
}