-
Notifications
You must be signed in to change notification settings - Fork 19
/
ConstructedStyleSheet.ts
241 lines (201 loc) · 6.62 KB
/
ConstructedStyleSheet.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import type Location from './Location';
import {fixBrokenRules, hasBrokenRules} from './safari';
import {_DOMException, bootstrapper, defineProperty} from './shared';
import {clearRules, insertAllRules, rejectImports} from './utils';
const cssStyleSheetMethods = [
'addRule',
'deleteRule',
'insertRule',
'removeRule',
];
const NonConstructedStyleSheet = CSSStyleSheet;
const nonConstructedProto = NonConstructedStyleSheet.prototype;
nonConstructedProto.replace = function () {
// document.styleSheets[0].replace('body {}');
return Promise.reject(
new _DOMException("Can't call replace on non-constructed CSSStyleSheets."),
);
};
nonConstructedProto.replaceSync = function () {
// document.styleSheets[0].replaceSync('body {}');
throw new _DOMException(
"Failed to execute 'replaceSync' on 'CSSStyleSheet': Can't call replaceSync on non-constructed CSSStyleSheets.",
);
};
export function isCSSStyleSheetInstance(instance: object): boolean {
return typeof instance === 'object'
? proto.isPrototypeOf(instance) ||
nonConstructedProto.isPrototypeOf(instance)
: false;
}
export function isNonConstructedStyleSheetInstance(instance: object): boolean {
return typeof instance === 'object'
? nonConstructedProto.isPrototypeOf(instance)
: false;
}
/*
* Private properties
*/
/**
* Basic stylesheet is an sample stylesheet that contains all the CSS rules of
* the current constructable stylesheet. The document or custom elements can
* adopt constructable stylesheet; in this case, basic stylesheet's CSS rules
* are reflected in document/custom element internal <style> elements.
*/
const $basicStyleSheet = new WeakMap<ConstructedStyleSheet, CSSStyleSheet>();
/**
* Contains all locations associated with the current ConstructedStyleSheet.
*/
const $locations = new WeakMap<ConstructedStyleSheet, Location[]>();
/**
* Adopter is a `<style>` element that belongs to the document or a custom
* element and contains the content of the basic stylesheet.
*
* This property contains a map of `<style>` adopter associated with locations.
*/
const $adoptersByLocation = new WeakMap<
ConstructedStyleSheet,
WeakMap<Location, HTMLStyleElement>
>();
/*
* Package-level control functions
*/
export function addAdopterLocation(
sheet: ConstructedStyleSheet,
location: Location,
): HTMLStyleElement {
const adopter = document.createElement('style');
$adoptersByLocation.get(sheet)!.set(location, adopter);
$locations.get(sheet)!.push(location);
return adopter;
}
export function getAdopterByLocation(
sheet: ConstructedStyleSheet,
location: Location,
): HTMLStyleElement | undefined {
return $adoptersByLocation.get(sheet)!.get(location);
}
export function removeAdopterLocation(
sheet: ConstructedStyleSheet,
location: Location,
): void {
$adoptersByLocation.get(sheet)!.delete(location);
$locations.set(
sheet,
$locations.get(sheet)!.filter((_location) => _location !== location),
);
}
/**
* Re-styles a single `<style>` adopter according to the basic style sheet.
*
* NOTE: don't use it for disconnected adopters. It will throw an error.
*/
export function restyleAdopter(
sheet: ConstructedStyleSheet,
adopter: HTMLStyleElement,
): void {
requestAnimationFrame(() => {
clearRules(adopter.sheet!);
insertAllRules($basicStyleSheet.get(sheet)!, adopter.sheet!);
});
}
/*
* Private methods
*/
/**
* This method checks if the method of the class is called correctly using the
* CSSStyleSheet instance. It is necessary to be sure that all private
* properties are initialized.
*/
function checkInvocationCorrectness(self: ConstructedStyleSheet) {
if (!$basicStyleSheet.has(self)) {
throw new TypeError('Illegal invocation');
}
}
/**
* A replacement for CSSStyleSheet class which is not actually constructable in
* any browser that does not support Constructable Style Sheet proposal. To
* fulfil the Constructable Style Sheet specification, it preserves a separate
* HTMLStyleElement that behaves as a backup for all the `<style>` adopters.
*/
declare class ConstructedStyleSheet extends CSSStyleSheet {
replace(text: string): Promise<ConstructedStyleSheet>;
replaceSync(text: string): void;
}
function ConstructedStyleSheet(this: ConstructedStyleSheet) {
const self = this;
const style = document.createElement('style');
bootstrapper.body.appendChild(style);
// Init private properties
$basicStyleSheet.set(self, style.sheet!);
$locations.set(self, []);
$adoptersByLocation.set(self, new WeakMap());
}
const proto = ConstructedStyleSheet.prototype;
proto.replace = function replace(
contents: string,
): Promise<ConstructedStyleSheet> {
try {
this.replaceSync(contents);
return Promise.resolve(this);
} catch (e) {
return Promise.reject(e);
}
};
proto.replaceSync = function replaceSync(contents) {
// CSSStyleSheet.prototype.replaceSync('body {}')
checkInvocationCorrectness(this);
if (typeof contents === 'string') {
const self = this;
const style = $basicStyleSheet.get(self)!.ownerNode as HTMLStyleElement;
style.textContent = hasBrokenRules
? fixBrokenRules(rejectImports(contents))
: rejectImports(contents);
$basicStyleSheet.set(self, style.sheet!);
$locations.get(self)!.forEach((location) => {
if (location.isConnected()) {
// Type Note: if location is connected, adopter is already created.
restyleAdopter(self, getAdopterByLocation(self, location)!);
}
});
}
};
defineProperty(proto, 'cssRules', {
configurable: true,
enumerable: true,
get: function cssRules() {
// CSSStyleSheet.prototype.cssRules;
checkInvocationCorrectness(this);
return $basicStyleSheet.get(this)!.cssRules;
},
});
cssStyleSheetMethods.forEach((method) => {
proto[method] = function () {
const self = this;
checkInvocationCorrectness(self);
const args = arguments;
$locations.get(self)!.forEach((location) => {
if (location.isConnected()) {
// Type Note: If location is connected, adopter is already created; and
// since it is connected to DOM, the sheet cannot be null.
const sheet = getAdopterByLocation(self, location)!.sheet!;
sheet[method].apply(sheet, args);
}
});
if (hasBrokenRules) {
if (method === 'insertRule') {
args[0] = fixBrokenRules(args[0]);
}
if (method === 'addRule') {
args[1] = fixBrokenRules(args[1]);
}
}
const basic = $basicStyleSheet.get(self)!;
return basic[method].apply(basic, args);
};
});
defineProperty(ConstructedStyleSheet, Symbol.hasInstance, {
configurable: true,
value: isCSSStyleSheetInstance,
});
export default ConstructedStyleSheet;