-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathcss.ts
219 lines (178 loc) · 6.11 KB
/
css.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
/**
* @author Saviio
* @since 2020-4-19
*/
// https://developer.mozilla.org/en-US/docs/Web/API/CSSRule
enum RuleType {
// type: rule will be rewrote
STYLE = 1,
MEDIA = 4,
SUPPORTS = 12,
// type: value will be kept
IMPORT = 3,
FONT_FACE = 5,
PAGE = 6,
KEYFRAMES = 7,
KEYFRAME = 8,
}
const arrayify = <T>(list: CSSRuleList | any[]) => {
return [].slice.call(list, 0) as T[];
};
const rawDocumentBodyAppend = HTMLBodyElement.prototype.appendChild;
export class ScopedCSS {
private static ModifiedTag = 'Symbol(style-modified-qiankun)';
private sheet: StyleSheet;
private swapNode: HTMLStyleElement;
constructor() {
const styleNode = document.createElement('style');
rawDocumentBodyAppend.call(document.body, styleNode);
this.swapNode = styleNode;
this.sheet = styleNode.sheet!;
this.sheet.disabled = true;
}
process(styleNode: HTMLStyleElement, prefix: string = '') {
if (ScopedCSS.ModifiedTag in styleNode) {
return;
}
if (styleNode.textContent !== '') {
const textNode = document.createTextNode(styleNode.textContent || '');
this.swapNode.appendChild(textNode);
const sheet = this.swapNode.sheet as any; // type is missing
const rules = arrayify<CSSRule>(sheet?.cssRules ?? []);
const css = this.rewrite(rules, prefix);
// eslint-disable-next-line no-param-reassign
styleNode.textContent = css;
// cleanup
this.swapNode.removeChild(textNode);
(styleNode as any)[ScopedCSS.ModifiedTag] = true;
return;
}
const mutator = new MutationObserver((mutations) => {
for (let i = 0; i < mutations.length; i += 1) {
const mutation = mutations[i];
if (ScopedCSS.ModifiedTag in styleNode) {
return;
}
if (mutation.type === 'childList') {
const sheet = styleNode.sheet as any;
const rules = arrayify<CSSRule>(sheet?.cssRules ?? []);
const css = this.rewrite(rules, prefix);
// eslint-disable-next-line no-param-reassign
styleNode.textContent = css;
// eslint-disable-next-line no-param-reassign
(styleNode as any)[ScopedCSS.ModifiedTag] = true;
}
}
});
// since observer will be deleted when node be removed
// we dont need create a cleanup function manually
// see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/disconnect
mutator.observe(styleNode, { childList: true });
}
private rewrite(rules: CSSRule[], prefix: string = '') {
let css = '';
rules.forEach((rule) => {
switch (rule.type) {
case RuleType.STYLE:
css += this.ruleStyle(rule as CSSStyleRule, prefix);
break;
case RuleType.MEDIA:
css += this.ruleMedia(rule as CSSMediaRule, prefix);
break;
case RuleType.SUPPORTS:
css += this.ruleSupport(rule as CSSSupportsRule, prefix);
break;
default:
if (typeof rule.cssText === 'string') {
css += `${rule.cssText}`;
}
break;
}
});
return css;
}
// handle case:
// .app-main {}
// html, body {}
// eslint-disable-next-line class-methods-use-this
private ruleStyle(rule: CSSStyleRule, prefix: string) {
const rootSelectorRE = /((?:[^\w\-.#]|^)(body|html|:root))/gm;
const rootCombinationRE = /(html[^\w{[]+)/gm;
const selector = rule.selectorText.trim();
let cssText = '';
if (typeof rule.cssText === 'string') {
cssText = rule.cssText;
}
// handle html { ... }
// handle body { ... }
// handle :root { ... }
if (selector === 'html' || selector === 'body' || selector === ':root') {
return cssText.replace(rootSelectorRE, prefix);
}
// handle html body { ... }
// handle html > body { ... }
if (rootCombinationRE.test(rule.selectorText)) {
const siblingSelectorRE = /(html[^\w{]+)(\+|~)/gm;
// since html + body is a non-standard rule for html
// transformer will ignore it
if (!siblingSelectorRE.test(rule.selectorText)) {
cssText = cssText.replace(rootCombinationRE, '');
}
}
// handle grouping selector, a,span,p,div { ... }
cssText = cssText.replace(/^[\s\S]+{/, (selectors) =>
selectors.replace(/(^|,\n?)([^,]+)/g, (item, p, s) => {
// handle div,body,span { ... }
if (rootSelectorRE.test(item)) {
return item.replace(rootSelectorRE, (m) => {
// do not discard valid previous character, such as body,html or *:not(:root)
const whitePrevChars = [',', '('];
if (m && whitePrevChars.includes(m[0])) {
return `${m[0]}${prefix}`;
}
// replace root selector with prefix
return prefix;
});
}
return `${p}${prefix} ${s.replace(/^ */, '')}`;
}),
);
return cssText;
}
// handle case:
// @media screen and (max-width: 300px) {}
private ruleMedia(rule: CSSMediaRule, prefix: string) {
const css = this.rewrite(arrayify(rule.cssRules), prefix);
return `@media ${rule.conditionText || rule.media.mediaText} {${css}}`;
}
// handle case:
// @supports (display: grid) {}
private ruleSupport(rule: CSSSupportsRule, prefix: string) {
const css = this.rewrite(arrayify(rule.cssRules), prefix);
return `@supports ${rule.conditionText || rule.cssText.split('{')[0]} {${css}}`;
}
}
let processor: ScopedCSS;
export const QiankunCSSRewriteAttr = 'data-qiankun';
export const process = (
appWrapper: HTMLElement,
stylesheetElement: HTMLStyleElement | HTMLLinkElement,
appName: string,
): void => {
// lazy singleton pattern
if (!processor) {
processor = new ScopedCSS();
}
if (stylesheetElement.tagName === 'LINK') {
console.warn('Feature: sandbox.experimentalStyleIsolation is not support for link element yet.');
}
const mountDOM = appWrapper;
if (!mountDOM) {
return;
}
const tag = (mountDOM.tagName || '').toLowerCase();
if (tag && stylesheetElement.tagName === 'STYLE') {
const prefix = `${tag}[${QiankunCSSRewriteAttr}="${appName}"]`;
processor.process(stylesheetElement, prefix);
}
};