-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
style-installer.js
288 lines (270 loc) · 8.35 KB
/
style-installer.js
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {CommonSignals} from './core/constants/common-signals';
import {Services} from './services';
import {TickLabel} from './core/constants/enums';
import {dev, devAssert} from './log';
import {getAmpdoc} from './service';
import {insertAfterOrAtStart, waitForBodyOpenPromise} from './dom';
import {map} from './core/types/object';
import {rethrowAsync} from './core/error';
import {setStyles} from './style';
import {waitForServices} from './render-delaying-services';
const TRANSFORMER_PROP = '__AMP_CSS_TR';
const STYLE_MAP_PROP = '__AMP_CSS_SM';
/**
* Adds the given css text to the given ampdoc.
*
* The style tags will be at the beginning of the head before all author
* styles. One element can be the main runtime CSS. This is guaranteed
* to always be the first stylesheet in the doc.
*
* @param {!./service/ampdoc-impl.AmpDoc} ampdoc The ampdoc that should get the new styles.
* @param {string} cssText
* @param {?function(!Element)|undefined} cb Called when the new styles are available.
* Not using a promise, because this is synchronous when possible.
* for better performance.
* @param {boolean=} opt_isRuntimeCss If true, this style tag will be inserted
* as the first element in head and all style elements will be positioned
* after.
* @param {string=} opt_ext
* @return {!Element}
*/
export function installStylesForDoc(
ampdoc,
cssText,
cb,
opt_isRuntimeCss,
opt_ext
) {
const cssRoot = ampdoc.getHeadNode();
const style = insertStyleElement(
cssRoot,
maybeTransform(cssRoot, cssText),
opt_isRuntimeCss || false,
opt_ext || null
);
if (cb) {
const rootNode = ampdoc.getRootNode();
// Styles aren't always available synchronously. E.g. if there is a
// pending style download, it will have to finish before the new
// style is visible.
// For this reason we poll until the style becomes available.
// Sync case.
if (styleLoaded(rootNode, style)) {
cb(style);
return style;
}
// Poll until styles are available.
const interval = setInterval(() => {
if (styleLoaded(rootNode, style)) {
clearInterval(interval);
cb(style);
}
}, 4);
}
return style;
}
/**
* Creates the properly configured style element.
* @param {!Element|!ShadowRoot} cssRoot
* @param {string} cssText
* @param {boolean} isRuntimeCss
* @param {?string} ext
* @return {!Element}
*/
function insertStyleElement(cssRoot, cssText, isRuntimeCss, ext) {
let styleMap = cssRoot[STYLE_MAP_PROP];
if (!styleMap) {
styleMap = cssRoot[STYLE_MAP_PROP] = map();
}
const isExtCss =
!isRuntimeCss && ext && ext != 'amp-custom' && ext != 'amp-keyframes';
const key = isRuntimeCss
? 'amp-runtime'
: isExtCss
? `amp-extension=${ext}`
: null;
// Check if it has already been created or discovered.
if (key) {
const existing = getExistingStyleElement(cssRoot, styleMap, key);
if (existing) {
if (existing.textContent !== cssText) {
existing.textContent = cssText;
}
return existing;
}
}
// Create the new style element and append to cssRoot.
const doc = cssRoot.ownerDocument || cssRoot;
const style = doc.createElement('style');
style./*OK*/ textContent = cssText;
let afterElement = null;
// Make sure that we place style tags after the main runtime CSS. Otherwise
// the order is random.
if (isRuntimeCss) {
style.setAttribute('amp-runtime', '');
} else if (isExtCss) {
style.setAttribute('amp-extension', ext || '');
afterElement = dev().assertElement(
getExistingStyleElement(cssRoot, styleMap, 'amp-runtime')
);
} else {
if (ext) {
style.setAttribute(ext, '');
}
afterElement = cssRoot.lastChild;
}
insertAfterOrAtStart(cssRoot, style, afterElement);
if (key) {
styleMap[key] = style;
}
return style;
}
/**
* @param {!Element|!ShadowRoot} cssRoot
* @param {!Object<string, !Element>} styleMap
* @param {string} key
* @return {?Element}
*/
function getExistingStyleElement(cssRoot, styleMap, key) {
// Already cached.
if (styleMap[key]) {
return styleMap[key];
}
// Check if the style has already been added by the server layout.
const existing = cssRoot./*OK*/ querySelector(`style[${key}]`);
if (existing) {
styleMap[key] = existing;
return existing;
}
// Nothing found.
return null;
}
/**
* Applies a transformer to the CSS text if it has been registered.
* @param {!Element|!ShadowRoot} cssRoot
* @param {function(string):string} transformer
*/
export function installCssTransformer(cssRoot, transformer) {
cssRoot[TRANSFORMER_PROP] = transformer;
}
/**
* Applies a transformer to the CSS text if it has been registered.
* @param {!Element|!ShadowRoot} cssRoot
* @param {string} cssText
* @return {string}
*/
function maybeTransform(cssRoot, cssText) {
const transformer = cssRoot[TRANSFORMER_PROP];
return transformer ? transformer(cssText) : cssText;
}
/** @private {boolean} */
let bodyMadeVisible = false;
/**
* @param {boolean} value
* @visibleForTesting
*/
export function setBodyMadeVisibleForTesting(value) {
bodyMadeVisible = value;
}
/**
* Sets the document's body opacity to 1.
* If the body is not yet available (because our script was loaded
* synchronously), polls until it is.
* @param {!Document} doc The document who's body we should make visible.
*/
export function makeBodyVisible(doc) {
devAssert(doc.defaultView, 'Passed in document must have a defaultView');
const win = /** @type {!Window} */ (doc.defaultView);
waitForBodyOpenPromise(doc)
.then(() => {
return waitForServices(win);
})
.catch((reason) => {
rethrowAsync(reason);
return [];
})
.then((services) => {
bodyMadeVisible = true;
if (INI_LOAD_INOB) {
// Force sync measurement to ensure that style recalc is complete
// before showing body, which would trigger FCP. This should reduce
// make it less likely that a CLS would be triggered after FCP.
doc.body./*OK*/ getBoundingClientRect();
}
setBodyVisibleStyles(doc);
const ampdoc = getAmpdoc(doc);
ampdoc.signals().signal(CommonSignals.RENDER_START);
if (services.length > 0) {
const resources = Services.resourcesForDoc(doc.documentElement);
resources./*OK*/ schedulePass(1, /* relayoutAll */ true);
}
try {
const perf = Services.performanceFor(win);
perf.tick(TickLabel.MAKE_BODY_VISIBLE);
perf.flush();
} catch (e) {}
});
}
/**
* Set the document's body opacity to 1. Called in error cases.
* @param {!Document} doc The document who's body we should make visible.
*/
export function makeBodyVisibleRecovery(doc) {
devAssert(doc.defaultView, 'Passed in document must have a defaultView');
if (bodyMadeVisible) {
return;
}
bodyMadeVisible = true;
setBodyVisibleStyles(doc);
}
/**
* Make sure that body exists, and make it visible.
* @param {!Document} doc
*/
function setBodyVisibleStyles(doc) {
setStyles(dev().assertElement(doc.body), {
opacity: 1,
visibility: 'visible',
'animation': 'none',
});
}
/**
* Indicates that the body is always visible. For instance, in case of PWA.
* This check is on a module level variable, and could be problematic if you are
* relying on this function across different binaries.
* @param {!Window} unusedWin
*/
export function bodyAlwaysVisible(unusedWin) {
bodyMadeVisible = true;
}
/**
* Checks whether a style element was registered in the DOM.
* @param {!Document|!ShadowRoot} doc
* @param {!Element} style
* @return {boolean}
*/
function styleLoaded(doc, style) {
const sheets = doc.styleSheets;
for (let i = 0; i < sheets.length; i++) {
const sheet = sheets[i];
if (sheet.ownerNode == style) {
return true;
}
}
return false;
}