forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmultidoc-manager.js
572 lines (534 loc) · 18.8 KB
/
multidoc-manager.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
/**
* Copyright 2019 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 './common-signals';
import {Services} from './services';
import {VisibilityState} from './visibility-state';
import {childElementsByTag, isConnectedNode} from './dom';
import {
createShadowDomWriter,
createShadowRoot,
importShadowBody,
} from './shadow-embed';
import {dev, user} from './log';
import {disposeServicesForDoc, getServicePromiseOrNullForDoc} from './service';
import {getMode} from './mode';
import {installStylesForDoc} from './style-installer';
import {isArray, isObject} from './types';
import {parseUrlDeprecated} from './url';
import {setStyle} from './style';
/** @const @private {string} */
const TAG = 'multidoc-manager';
/**
* A manager for documents in the multi-doc environment.
*/
export class MultidocManager {
/**
* @param {!Window} win
* @param {!./service/ampdoc-impl.AmpDocService} ampdocService
* @param {!./service/extensions-impl.Extensions} extensions
* @param {!./service/timer-impl.Timer} timer
*/
constructor(win, ampdocService, extensions, timer) {
/** @const */
this.win = win;
/** @private @const */
this.ampdocService_ = ampdocService;
/** @private @const */
this.extensions_ = extensions;
/** @private @const */
this.timer_ = timer;
/** @private @const {!Array<!ShadowRoot>} */
this.shadowRoots_ = [];
}
/**
* Attaches the shadow root and calls the supplied DOM builder.
* @param {!Element} hostElement
* @param {string} url
* @param {!Object<string, string>|undefined} params
* @param {function(!Object, !ShadowRoot,
* !./service/ampdoc-impl.AmpDocShadow):!Promise} builder
* @return {!./runtime.ShadowDoc}
* @private
*/
attachShadowDoc_(hostElement, url, params, builder) {
params = params || Object.create(null);
this.purgeShadowRoots_();
setStyle(hostElement, 'visibility', 'hidden');
const shadowRoot = createShadowRoot(hostElement);
// TODO: closeShadowRoot_ is asynchronous. While this safety check is well
// intentioned, it leads to a race between unlayout and layout of custom
// elements.
if (shadowRoot.AMP) {
user().warn(TAG, "Shadow doc wasn't previously closed");
this.closeShadowRoot_(shadowRoot);
}
const amp = {};
shadowRoot.AMP = amp;
amp.url = url;
const {origin} = parseUrlDeprecated(url);
const ampdoc = this.ampdocService_.installShadowDoc(url, shadowRoot, {
params,
});
/** @const {!./service/ampdoc-impl.AmpDocShadow} */
amp.ampdoc = ampdoc;
dev().fine(TAG, 'Attach to shadow root:', shadowRoot, ampdoc);
// Install runtime CSS.
installStylesForDoc(
ampdoc,
AMP.combinedCss,
/* callback */ null,
/* opt_isRuntimeCss */ true
);
// Instal doc services.
AMP.installAmpdocServices(ampdoc);
const viewer = Services.viewerForDoc(ampdoc);
/**
* Sets the document's visibility state.
* @param {!VisibilityState} state
*/
amp['setVisibilityState'] = function(state) {
ampdoc.overrideVisibilityState(state);
};
// Messaging pipe.
/**
* Posts message to the ampdoc.
* @param {string} eventType
* @param {!JsonObject} data
* @param {boolean} unusedAwaitResponse
* @return {(!Promise<*>|undefined)}
*/
amp['postMessage'] = viewer.receiveMessage.bind(viewer);
/** @type {function(string, *, boolean):(!Promise<*>|undefined)} */
let onMessage;
/**
* Provides a message delivery mechanism by which AMP document can send
* messages to the viewer.
* @param {function(string, *, boolean):(!Promise<*>|undefined)} callback
*/
amp['onMessage'] = function(callback) {
onMessage = callback;
};
viewer.setMessageDeliverer((eventType, data, awaitResponse) => {
// Special messages.
if (eventType == 'broadcast') {
this.broadcast_(data, shadowRoot);
return awaitResponse ? Promise.resolve() : undefined;
}
// All other messages.
if (onMessage) {
return onMessage(eventType, data, awaitResponse);
}
}, origin);
/**
* Closes the document, resolving when visibility changes and services have
* been cleand up. The document can no longer be activated again.
* @return {Promise}
*/
amp['close'] = () => {
return this.closeShadowRoot_(shadowRoot);
};
if (getMode().development) {
amp.toggleRuntime = viewer.toggleRuntime.bind(viewer);
amp.resources = Services.resourcesForDoc(ampdoc);
}
/**
* Expose amp-bind getState
* @param {string} name - Name of state or deep state
* @return {Promise<*>} - Resolves to a copy of the value of a state
*/
amp['getState'] = name => {
return Services.bindForDocOrNull(shadowRoot).then(bind => {
if (!bind) {
return Promise.reject('amp-bind is not available in this document');
}
return bind.getState(name);
});
};
/**
* Expose amp-bind setState
* @param {(!JsonObject|string)} state - State to be set
* @return {Promise} - Resolves after state and history have been updated
*/
amp['setState'] = state => {
return Services.bindForDocOrNull(shadowRoot).then(bind => {
if (!bind) {
return Promise.reject('amp-bind is not available in this document');
}
if (typeof state === 'string') {
return bind.setStateWithExpression(
/** @type {string} */ (state),
/** @type {!JsonObject} */ ({})
);
} else if (isObject(state) || isArray(state)) {
return bind.setStateWithObject(/** @type {!JsonObject} */ (state));
}
return Promise.reject('Invalid state');
});
};
// Start building the shadow doc DOM.
builder(amp, shadowRoot, ampdoc).then(() => {
// Document is ready.
ampdoc.setReady();
ampdoc.signals().signal(CommonSignals.RENDER_START);
setStyle(hostElement, 'visibility', 'visible');
});
// Store reference.
if (!this.shadowRoots_.includes(shadowRoot)) {
this.shadowRoots_.push(shadowRoot);
}
dev().fine(TAG, 'Shadow root initialization is done:', shadowRoot, ampdoc);
return amp;
}
/**
* Implementation for `attachShadowDoc` function. Attaches the shadow doc and
* configures ampdoc for it.
* @param {!Element} hostElement
* @param {!Document} doc
* @param {string} url
* @param {!Object<string, string>=} opt_initParams
* @return {!./runtime.ShadowDoc}
*/
attachShadowDoc(hostElement, doc, url, opt_initParams) {
user().assertString(url);
dev().fine(TAG, 'Attach shadow doc:', doc);
// TODO(dvoytenko, #9490): once stable, port full document case to emulated
// stream.
return this.attachShadowDoc_(
hostElement,
url,
opt_initParams,
(amp, shadowRoot, ampdoc) => {
// Install extensions.
const extensionIds = this.mergeShadowHead_(ampdoc, shadowRoot, doc);
this.extensions_.installExtensionsInDoc(ampdoc, extensionIds);
// Append body.
if (doc.body) {
const body = importShadowBody(shadowRoot, doc.body, /* deep */ true);
body.classList.add('amp-shadow');
ampdoc.setBody(body);
}
// TODO(dvoytenko): find a better and more stable way to make content
// visible. E.g. integrate with dynamic classes. In shadow case
// specifically, we have to wait for stubbing to complete, which may
// take awhile due to importNode.
setTimeout(() => {
ampdoc.signals().signal(CommonSignals.RENDER_START);
setStyle(hostElement, 'visibility', 'visible');
}, 50);
return Promise.resolve();
}
);
}
/**
* Implementation for `attachShadowDocAsStream` function. Attaches the shadow
* doc and configures ampdoc for it.
* @param {!Element} hostElement
* @param {string} url
* @param {!Object<string, string>=} opt_initParams
* @return {!Object}
*/
attachShadowDocAsStream(hostElement, url, opt_initParams) {
user().assertString(url);
dev().fine(TAG, 'Attach shadow doc as stream');
return this.attachShadowDoc_(
hostElement,
url,
opt_initParams,
(amp, shadowRoot, ampdoc) => {
// Start streaming.
let renderStarted = false;
const writer = createShadowDomWriter(this.win);
amp['writer'] = writer;
writer.onBody(doc => {
// Install extensions.
const extensionIds = this.mergeShadowHead_(ampdoc, shadowRoot, doc);
// Apply all doc extensions.
this.extensions_.installExtensionsInDoc(ampdoc, extensionIds);
// Append shallow body.
const body = importShadowBody(
shadowRoot,
dev().assertElement(doc.body),
/* deep */ false
);
body.classList.add('amp-shadow');
ampdoc.setBody(body);
return body;
});
writer.onBodyChunk(() => {
// TODO(dvoytenko): find a better and more stable way to make
// content visible. E.g. integrate with dynamic classes. In shadow
// case specifically, we have to wait for stubbing to complete,
// which may take awhile due to node importing.
if (!renderStarted) {
renderStarted = true;
setTimeout(() => {
ampdoc.signals().signal(CommonSignals.RENDER_START);
setStyle(hostElement, 'visibility', 'visible');
}, 50);
}
});
return new Promise(resolve => {
writer.onEnd(() => {
resolve();
amp.writer = null;
});
});
}
);
}
/**
* Processes the contents of the shadow document's head.
* @param {!./service/ampdoc-impl.AmpDoc} ampdoc
* @param {!ShadowRoot} shadowRoot
* @param {!Document} doc
* @return {!Array<string>}
* @private
*/
mergeShadowHead_(ampdoc, shadowRoot, doc) {
const extensionIds = [];
if (doc.head) {
shadowRoot.AMP.head = doc.head;
const parentLinks = {};
const links = childElementsByTag(
dev().assertElement(this.win.document.head),
'link'
);
for (let i = 0; i < links.length; i++) {
const href = links[i].getAttribute('href');
if (href) {
parentLinks[href] = true;
}
}
for (let n = doc.head.firstElementChild; n; n = n.nextElementSibling) {
const {tagName} = n;
const name = n.getAttribute('name');
const rel = n.getAttribute('rel');
switch (tagName) {
case 'TITLE':
shadowRoot.AMP.title = n.textContent;
dev().fine(TAG, '- set title: ', shadowRoot.AMP.title);
break;
case 'META':
if (n.hasAttribute('charset')) {
// Ignore.
} else if (name == 'viewport') {
// Ignore.
} else if (name) {
// Store meta name/content pairs.
ampdoc.setMetaByName(name, n.getAttribute('content') || '');
} else {
// TODO(dvoytenko): copy other meta tags.
dev().warn(TAG, 'meta ignored: ', n);
}
break;
case 'LINK':
/** @const {string} */
const href = n.getAttribute('href');
if (rel == 'canonical') {
shadowRoot.AMP.canonicalUrl = href;
dev().fine(TAG, '- set canonical: ', shadowRoot.AMP.canonicalUrl);
} else if (rel == 'stylesheet') {
// Must be a font definition: no other stylesheets are allowed.
if (parentLinks[href]) {
dev().fine(TAG, '- stylesheet already included: ', href);
} else {
parentLinks[href] = true;
const el = this.win.document.createElement('link');
el.setAttribute('rel', 'stylesheet');
el.setAttribute('type', 'text/css');
el.setAttribute('href', href);
this.win.document.head.appendChild(el);
dev().fine(TAG, '- import font to parent: ', href, el);
}
} else {
dev().fine(TAG, '- ignore link rel=', rel);
}
break;
case 'STYLE':
if (n.hasAttribute('amp-boilerplate')) {
// Ignore.
dev().fine(TAG, '- ignore boilerplate style: ', n);
} else if (n.hasAttribute('amp-custom')) {
installStylesForDoc(
ampdoc,
n.textContent,
/* callback */ null,
/* isRuntimeCss */ false,
'amp-custom'
);
dev().fine(TAG, '- import style: ', n);
} else if (n.hasAttribute('amp-keyframes')) {
installStylesForDoc(
ampdoc,
n.textContent,
/* callback */ null,
/* isRuntimeCss */ false,
'amp-keyframes'
);
dev().fine(TAG, '- import style: ', n);
}
break;
case 'SCRIPT':
if (n.hasAttribute('src')) {
dev().fine(TAG, '- src script: ', n);
const src = n.getAttribute('src');
const isRuntime =
src.indexOf('/amp.js') != -1 || src.indexOf('/v0.js') != -1;
// Note: Some extensions don't have [custom-element] or
// [custom-template] e.g. amp-viewer-integration.
const customElement = n.getAttribute('custom-element');
const customTemplate = n.getAttribute('custom-template');
const versionRe = /-(\d+.\d+)(.max)?\.js$/;
const match = versionRe.exec(src);
const version = match ? match[1] : '0.1';
if (isRuntime) {
dev().fine(TAG, '- ignore runtime script: ', src);
} else if (customElement || customTemplate) {
// This is an extension.
this.extensions_.installExtensionForDoc(
ampdoc,
customElement || customTemplate,
version
);
dev().fine(
TAG,
'- load extension: ',
customElement || customTemplate,
' ',
version
);
if (customElement) {
extensionIds.push(customElement);
}
} else if (!n.hasAttribute('data-amp-report-test')) {
user().error(TAG, '- unknown script: ', n, src);
}
} else {
// Non-src version of script.
const type = n.getAttribute('type') || 'application/javascript';
if (type.indexOf('javascript') == -1) {
shadowRoot.appendChild(this.win.document.importNode(n, true));
dev().fine(TAG, '- non-src script: ', n);
} else {
user().error(TAG, '- unallowed inline javascript: ', n);
}
}
break;
case 'NOSCRIPT':
// Ignore.
break;
default:
user().error(TAG, '- UNKNOWN head element:', n);
break;
}
}
}
return extensionIds;
}
/**
* @param {*} data
* @param {!ShadowRoot} sender
* @private
*/
broadcast_(data, sender) {
this.purgeShadowRoots_();
this.shadowRoots_.forEach(shadowRoot => {
if (shadowRoot == sender) {
// Don't broadcast to the sender.
return;
}
// Broadcast message asynchronously.
const viewer = Services.viewerForDoc(shadowRoot.AMP.ampdoc);
this.timer_.delay(() => {
viewer.receiveMessage(
'broadcast',
/** @type {!JsonObject} */ (data),
/* awaitResponse */ false
);
}, 0);
});
}
/**
* @param {!ShadowRoot} shadowRoot
* @return {Promise}
* @private
*/
closeShadowRoot_(shadowRoot) {
this.removeShadowRoot_(shadowRoot);
const amp = shadowRoot.AMP;
delete shadowRoot.AMP;
const {ampdoc} = amp;
ampdoc.overrideVisibilityState(VisibilityState.INACTIVE);
disposeServicesForDoc(ampdoc);
// There is a race between the visibility state change finishing and
// resources.onNextPass firing, but this is intentional. closeShadowRoot_
// was traditionally introduced as a synchronous method, so PWAs in the wild
// do not expect to have to wait for a promise to resolve before the shadow
// is deemed 'closed'. Moving .overrideVisibilityState() and
// disposeServicesForDoc inside a promise could adversely affect sites that
// depend on at least the synchronous portions of those methods completing
// before proceeding. The promise race is designed to be very quick so that
// even if the pass callback completes before resources.onNextPass is called
// below, we only delay promise resolution by a few ms.
return this.timer_
.timeoutPromise(
15, // Delay for queued pass after visibility change is 10ms
new this.win.Promise(resolve => {
getServicePromiseOrNullForDoc(ampdoc, 'resources').then(resources => {
if (resources) {
resources.onNextPass(resolve);
} else {
resolve();
}
});
}),
'Timeout reached waiting for visibility state change callback'
)
.catch(error => {
user().info(TAG, error);
});
}
/**
* @param {!ShadowRoot} shadowRoot
* @private
*/
removeShadowRoot_(shadowRoot) {
const index = this.shadowRoots_.indexOf(shadowRoot);
if (index != -1) {
this.shadowRoots_.splice(index, 1);
}
}
/**
* @param {!ShadowRoot} shadowRoot
* @private
*/
closeShadowRootAsync_(shadowRoot) {
this.timer_.delay(() => {
this.closeShadowRoot_(shadowRoot);
}, 0);
}
/** @private */
purgeShadowRoots_() {
this.shadowRoots_.forEach(shadowRoot => {
// The shadow root has been disconnected. Force it closed.
if (!shadowRoot.host || !isConnectedNode(shadowRoot.host)) {
user().warn(TAG, "Shadow doc wasn't previously closed");
this.removeShadowRoot_(shadowRoot);
this.closeShadowRootAsync_(shadowRoot);
}
});
}
}