forked from ampproject/amphtml
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpwa.js
521 lines (461 loc) · 13.5 KB
/
pwa.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
/**
* Copyright 2016 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.
*/
'use strict';
function log(args) {
var var_args = Array.prototype.slice.call(arguments, 0);
var_args.unshift('[SHELL]');
console/*OK*/.log.apply(console, var_args);
}
function startsWith(string, prefix) {
return string.lastIndexOf(prefix, 0) == 0;
}
class Shell {
constructor(win, useStreaming) {
/** @private @const {!Window} */
this.win = win;
/** @private @const {boolean} */
this.useStreaming_ = useStreaming;
/** @private @const {!AmpViewer} */
this.ampViewer_ = new AmpViewer(win,
win.document.getElementById('doc-container'));
/** @private {string} */
this.currentPage_ = win.location.pathname;
this.sidebarCloseButton_ = document.querySelector('#sidebarClose');
win.addEventListener('popstate', this.handlePopState_.bind(this));
win.document.documentElement.addEventListener('click',
this.handleNavigate_.bind(this));
log('Shell created');
if (this.currentPage_ && !isShellUrl(this.currentPage_)) {
this.navigateTo(this.currentPage_);
} else if (this.win.location.hash) {
const hashParams = parseQueryString(this.win.location.hash);
const href = hashParams['href'];
if (href) {
this.currentPage_ = href;
this.navigateTo(href);
}
}
// Install service worker
this.registerServiceWorker_();
}
registerServiceWorker_() {
if ('serviceWorker' in navigator) {
log('Register service worker');
navigator.serviceWorker.register('/pwa/pwa-sw.js').then(reg => {
log('Service worker registered: ', reg);
}).catch(err => {
log('Service worker registration failed: ', err);
});
}
}
unregisterServiceWorker_() {
if ('serviceWorker' in navigator) {
log('Register service worker');
navigator.serviceWorker.getRegistration('/pwa/pwa-sw.js').then(reg => {
log('Service worker found: ', reg);
reg.unregister();
log('Service worker unregistered');
});
}
}
/**
* @param {!Event} e
*/
handleNavigate_(e) {
if (e.defaultPrevented) {
return false;
}
if (e.button) {
return false;
}
let a = e.target;
while (a) {
if (a.tagName == 'A' && a.href) {
break;
}
a = a.parentElement;
}
if (a) {
const url = new URL(a.href);
const location = this.win.location;
if (url.origin == location.origin &&
startsWith(url.pathname, '/pwa/') &&
url.pathname.indexOf('amp.html') != -1) {
e.preventDefault();
const newPage = url.pathname + location.search;
log('Internal link to: ', newPage);
if (newPage != this.currentPage_) {
this.closeSidebar().then(() => this.navigateTo(newPage));
}
}
}
}
/**
*/
handlePopState_() {
const newPage = this.win.location.pathname;
log('Pop state: ', newPage, this.currentPage_);
if (newPage != this.currentPage_) {
this.navigateTo(newPage);
}
}
/**
* @param {string} path
* @return {!Promise}
*/
navigateTo(path) {
log('Navigate to: ', path);
const oldPage = this.currentPage_;
this.currentPage_ = path;
// Update URL.
const push = !isShellUrl(path) && isShellUrl(oldPage);
if (path != this.win.location.pathname) {
if (push) {
this.win.history.pushState(null, '', path);
} else {
this.win.history.replaceState(null, '', path);
}
}
if (isShellUrl(path)) {
log('Back to shell');
this.ampViewer_.clear();
return Promise.resolve();
}
// Fetch.
const url = this.resolveUrl_(path);
log('Fetch and render doc:', path, url);
// TODO(dvoytenko, #9490): Make `streamDocument` the only used API once
// streaming is graduated out of experimental.
if (this.useStreaming_) {
log('Streaming started: ', url);
return this.ampViewer_.showAsStream(url).then(
shadowDoc => streamDocument(url, shadowDoc.writer));
}
return fetchDocument(url).then(doc => {
log('Fetch complete: ', doc);
return this.ampViewer_.show(doc, url);
});
}
/**
* @param {string} url
* @return {string}
*/
resolveUrl_(url) {
if (!this.a_) {
this.a_ = this.win.document.createElement('a');
}
this.a_.href = url;
return this.a_.href;
}
closeSidebar() {
if (this.sidebarCloseButton_) {
return new Promise(resolve => {
this.sidebarCloseButton_.click();
// TODO implement a better method to detect when
// closing sidebar has finished
setTimeout(() => resolve(), 100);
});
} else {
return Promise.resolve();
}
}
}
class AmpViewer {
constructor(win, container) {
/** @private @const {!Window} */
this.win = win;
/** @private @const {!Element} */
this.container = container;
win.AMP_SHADOW = true;
const ampReadyPromise = new Promise(resolve => {
(window.AMP = window.AMP || []).push(resolve);
});
ampReadyPromise.then(AMP => {
log('AMP LOADED:', AMP);
});
const isShadowDomSupported = (
Element.prototype.attachShadow ||
Element.prototype.createShadowRoot
);
const shadowDomReadyPromise = new Promise((resolve, reject) => {
if (isShadowDomSupported) {
resolve();
} else if (this.win.document.querySelector('script[src*=webcomponents]')) {
this.win.addEventListener('WebComponentsReady', resolve);
} else {
// AMP polyfills small part of SD spec. It's functional, but some things
// (e.g. slots) are not available.
resolve();
}
});
this.readyPromise_ = Promise.all([
ampReadyPromise,
shadowDomReadyPromise,
]).then(results => results[0]);
/** @private @const {string} */
this.baseUrl_ = null;
/** @private @const {?Element} */
this.host_ = null;
/** @private @const {...} */
this.amp_ = null;
// Immediately install amp-shadow.js.
this.installScript_('/dist/shadow-v0.js', '/dist/amp-shadow.js');
}
/**
*/
clear() {
if (this.amp_) {
this.amp_.close();
this.amp_ = null;
}
this.container.textContent = '';
}
/**
* @param {!Document} doc
* @param {string} url
*/
show(doc, url) {
log('Show document:', doc, url);
// Cleanup the existing document if any.
this.clear();
this.baseUrl_ = url;
this.host_ = this.win.document.createElement('div');
this.host_.classList.add('amp-doc-host');
const hostTemplate = this.win.document.getElementById('amp-slot-template');
if (hostTemplate) {
this.host_.appendChild(hostTemplate.content.cloneNode(true));
}
this.container.appendChild(this.host_);
return this.readyPromise_.then(AMP => {
this.amp_ = AMP.attachShadowDoc(this.host_, doc, url, {});
this.win.document.title = this.amp_.title || '';
this.amp_.onMessage(this.onMessage_.bind(this));
this.amp_.setVisibilityState('visible');
});
}
/**
* @param {string} url
* @return {!Promise<!ShadowDoc>}
*/
showAsStream(url) {
log('Show stream document:', url);
// Cleanup the existing document if any.
this.clear();
this.baseUrl_ = url;
this.host_ = this.win.document.createElement('div');
this.host_.classList.add('amp-doc-host');
const hostTemplate = this.win.document.getElementById('amp-slot-template');
if (hostTemplate) {
this.host_.appendChild(hostTemplate.content.cloneNode(true));
}
this.container.appendChild(this.host_);
return this.readyPromise_.then(AMP => {
this.amp_ = AMP.attachShadowDocAsStream(this.host_, url, {});
this.win.document.title = this.amp_.title || '';
this.amp_.onMessage(this.onMessage_.bind(this));
this.amp_.setVisibilityState('visible');
return this.amp_;
});
}
/**
* @param {string} src
* @param {string=} fallbackSrc
* @param {string=} customElement
* @param {string=} customTemplate
*/
installScript_(src, fallbackSrc, customElement, customTemplate) {
const doc = this.win.document;
const el = doc.createElement('script');
el.setAttribute('src', src);
if (customElement) {
el.setAttribute('custom-element', customElement);
}
if (customTemplate) {
el.setAttribute('custom-template', customTemplate);
}
el.onload = () => {
log('- script added: ', src, el);
};
el.onerror = () => {
log('- script failed to load: ', src, el);
doc.head.removeChild(el);
if (fallbackSrc) {
this.installScript_(fallbackSrc, undefined, customElement, customTemplate);
}
};
doc.head.appendChild(el);
}
/**
* @param {string} url
* @return {string}
*/
resolveUrl_(relativeUrlString) {
return new URL(relativeUrlString, this.baseUrl_).toString();
}
/**
* @param {string} url
* @return {string}
*/
getOrigin_(relativeUrlString) {
return new URL(relativeUrlString, this.baseUrl_).origin;
}
/**
*/
onMessage_(type, data, rsvp) {
}
}
/**
* @param {string} url
* @return {boolean}
*/
function isShellUrl(url) {
return (url == '/pwa' || url == '/pwa/');
}
/**
* @param {string} url
* @return {!Promise<!Document>}
*/
function fetchDocument(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'document';
xhr.setRequestHeader('Accept', 'text/html');
xhr.onreadystatechange = () => {
if (xhr.readyState < /* STATUS_RECEIVED */ 2) {
return;
}
if (xhr.status < 100 || xhr.status > 599) {
xhr.onreadystatechange = null;
reject(new Error(`Unknown HTTP status ${xhr.status}`));
return;
}
if (xhr.readyState == /* COMPLETE */ 4) {
if (xhr.responseXML) {
resolve(xhr.responseXML);
} else {
reject(new Error(`No xhr.responseXML`));
}
}
};
xhr.onerror = () => {
reject(new Error('Network failure'));
};
xhr.onabort = () => {
reject(new Error('Request aborted'));
};
xhr.send();
});
}
/**
* @param {string} url
* @param {!WritableStreamDefaultWriter} writer
* @return {!Promise}
*/
function streamDocument(url, writer) {
// Try native first.
if (window.fetch && window.TextDecoder && window.ReadableStream) {
return fetch(url).then(response => {
// This should be a lot simpler with transforming streams and pipes,
// but, TMK, these are not supported anywhere yet.
const /** !ReadableStreamDefaultReader */ reader = response.body
.getReader();
const decoder = new TextDecoder();
function readChunk(chunk) {
const text = decoder.decode(
chunk.value || new Uint8Array(),
{stream: !chunk.done});
if (text) {
writer.write(text);
}
if (chunk.done) {
writer.close();
} else {
return reader.read().then(readChunk);
}
}
return reader.read().then(readChunk);
});
}
// Polyfill via XHR.
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader('Accept', 'text/html');
let pos = 0;
xhr.onreadystatechange = () => {
if (xhr.readyState < /* STATUS_RECEIVED */ 2) {
return;
}
if (xhr.status < 100 || xhr.status > 599) {
xhr.onreadystatechange = null;
reject(new Error(`Unknown HTTP status ${xhr.status}`));
return;
}
if (xhr.readyState == /* LOADING */ 3 ||
xhr.readyState == /* COMPLETE */ 4) {
const s = xhr.responseText;
const chunk = s.substring(pos);
pos = s.length;
writer.write(chunk);
if (xhr.readyState == /* COMPLETE */ 4) {
writer.close().then(resolve);
}
}
};
xhr.onerror = () => {
reject(new Error('Network failure'));
};
xhr.onabort = () => {
reject(new Error('Request aborted'));
};
xhr.send();
});
}
/**
* Parses the query string of an URL. This method returns a simple key/value
* map. If there are duplicate keys the latest value is returned.
* @param {string} queryString
* @return {!Object<string>}
*/
function parseQueryString(queryString) {
const params = Object.create(null);
if (!queryString) {
return params;
}
if (startsWith(queryString, '?') || startsWith(queryString, '#')) {
queryString = queryString.substr(1);
}
const pairs = queryString.split('&');
for (let i = 0; i < pairs.length; i++) {
const pair = pairs[i];
const eqIndex = pair.indexOf('=');
let name;
let value;
if (eqIndex != -1) {
name = decodeURIComponent(pair.substring(0, eqIndex)).trim();
value = decodeURIComponent(pair.substring(eqIndex + 1)).trim();
} else {
name = decodeURIComponent(pair).trim();
value = '';
}
if (name) {
params[name] = value;
}
}
return params;
}
var shell = new Shell(window, /* useStreaming */ true);