forked from material-components/material-components-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
interactivity.js
328 lines (280 loc) · 9.13 KB
/
interactivity.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
/**
* @license
* Copyright 2017 Google Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import * as dom from './dom.js';
import * as pony from './ponyfill.js';
import * as util from './util.js';
const classes = {
TOOLBAR_PROGRESS_BAR_ACTIVE: 'demo-toolbar-progress-bar--active',
};
const attrs = {
HOT_SWAP: 'data-hot',
IS_LOADING: 'data-is-loading',
};
const ids = {
TOOLBAR_PROGRESS_BAR: 'demo-toolbar-progress-bar',
};
/** @abstract */
export class InteractivityProvider {
constructor(root) {
/** @protected {!Document|!Element} */
this.root_ = root;
/** @protected {!Document} */
this.document_ = dom.getDocument(this.root_);
/** @protected {!Window} */
this.window_ = dom.getWindow(this.root_);
}
lazyInit() {}
/**
* @param {string} selector
* @param {!Document|!Element=} root
* @return {!Array<!Element>}
* @protected
*/
querySelectorAll_(selector, root = this.root_) {
return dom.getAll(selector, root);
}
}
export class ToolbarProvider extends InteractivityProvider {
/** @param {!Document|!Element} root */
static attachTo(root) {
const instance = new ToolbarProvider(root);
instance.lazyInit();
return instance;
}
/** @override */
lazyInit() {
/** @type {?Element} */
this.progressBarEl_ = this.root_.getElementById(ids.TOOLBAR_PROGRESS_BAR);
}
/** @param {boolean} isLoading */
setIsLoading(isLoading) {
if (!this.progressBarEl_) {
return;
}
if (isLoading) {
this.progressBarEl_.classList.add(classes.TOOLBAR_PROGRESS_BAR_ACTIVE);
} else {
this.progressBarEl_.classList.remove(classes.TOOLBAR_PROGRESS_BAR_ACTIVE);
}
}
}
/** @type {?HotSwapper} */
let hotSwapperInstance = null;
export class HotSwapper extends InteractivityProvider {
/**
* @param {!Document|!Element} root
* @param {!ToolbarProvider} toolbarProvider
*/
static attachTo(root, toolbarProvider) {
const instance = new HotSwapper(root);
instance.lazyInit(toolbarProvider);
return instance;
}
/** @private {number} */
static get hotUpdateWaitPeriodMs_() {
return 250;
}
/**
* @param {!ToolbarProvider} toolbarProvider
* @override
*/
lazyInit(toolbarProvider) {
/** @type {!ToolbarProvider} */
this.toolbarProvider_ = toolbarProvider;
/** @type {!Array<string>} */
this.pendingRequests_ = [];
this.registerHotUpdateHandler_();
}
/** @private */
registerHotUpdateHandler_() {
const hotSwapAllStylesheets = util.debounce(() => {
this.hotSwapAllStylesheets_();
}, HotSwapper.hotUpdateWaitPeriodMs_);
this.window_.addEventListener('message', (evt) => {
if (this.isWebpackRecompileStart_(evt)) {
this.toolbarProvider_.setIsLoading(true);
} else if (this.isWebpackRecompileEnd_(evt)) {
hotSwapAllStylesheets();
}
});
}
/**
* @param {!Event} evt
* @return {boolean}
* @private
*/
isWebpackRecompileStart_(evt) {
return Boolean(evt.data) && evt.data.type === 'webpackInvalid';
}
/**
* @param {!Event} evt
* @return {boolean}
* @private
*/
isWebpackRecompileEnd_(evt) {
return typeof evt.data === 'string' && evt.data.indexOf('webpackHotUpdate') === 0;
}
/** @private */
hotSwapAllStylesheets_() {
this.querySelectorAll_(`link[${attrs.HOT_SWAP}]:not([${attrs.IS_LOADING}])`).forEach((link) => {
this.hotSwapStylesheet(link);
});
}
/**
* @param {!Element} oldLink
* @param {string=} newUri
*/
hotSwapStylesheet(oldLink, newUri) {
const oldUri = oldLink.getAttribute('href');
// Reload existing stylesheet
if (!newUri) {
newUri = oldUri;
}
// Force IE 11 and Edge to bypass the cache and request a fresh copy of the CSS.
newUri = this.bustCache_(newUri);
this.swapItLikeItsHot_(oldLink, oldUri, newUri);
}
/**
* @param {!Element} oldLink
* @param {string} oldUri
* @param {string} newUri
* @private
*/
swapItLikeItsHot_(oldLink, oldUri, newUri) {
this.logHotSwap_('swapping', oldUri, newUri, '...');
// Ensure that oldLink has a unique ID so we can remove all stale stylesheets from the DOM after newLink loads.
// This is a more robust approach than holding a reference to oldLink and removing it directly, because a user might
// quickly switch themes several times before the first stylesheet finishes loading (especially over a slow network)
// and each new stylesheet would try to remove the first one, leaving multiple conflicting stylesheets in the DOM.
if (!oldLink.id) {
oldLink.id = `stylesheet-${Math.floor(Math.random() * Date.now())}`;
}
const newLink = /** @type {!Element} */ (oldLink.cloneNode(false));
newLink.setAttribute('href', newUri);
newLink.setAttribute(attrs.IS_LOADING, 'true');
// IE 11 and Edge fire the `load` event twice for `<link>` elements.
newLink.addEventListener('load', util.debounce(() => {
this.handleStylesheetLoad_(newLink, newUri, oldUri);
}, 50));
oldLink.parentNode.insertBefore(newLink, oldLink);
this.pendingRequests_.push(newUri);
this.toolbarProvider_.setIsLoading(true);
}
/**
* @param {!Element} newLink
* @param {string} newUri
* @param {string} oldUri
* @private
*/
handleStylesheetLoad_(newLink, newUri, oldUri) {
this.pendingRequests_.splice(this.pendingRequests_.indexOf(newUri), 1);
if (this.pendingRequests_.length === 0) {
this.toolbarProvider_.setIsLoading(false);
}
setTimeout(() => {
this.purgeOldStylesheets_(newLink);
// Remove the 'loading' attribute *after* purging old stylesheets to avoid purging this one.
newLink.removeAttribute(attrs.IS_LOADING);
this.logHotSwap_('swapped', oldUri, newUri, '!');
});
}
/**
* @param {!Element} newLink
* @private
*/
purgeOldStylesheets_(newLink) {
let oldLinks;
const getOldLinks = () => this.querySelectorAll_(`link[id="${newLink.id}"]:not([${attrs.IS_LOADING}])`);
while ((oldLinks = getOldLinks()).length > 0) {
oldLinks.forEach((oldLink) => {
// Link has already been detached from the DOM. I'm not sure what causes this to happen; I've only seen it in
// IE 11 and/or Edge so far, and only occasionally.
if (!oldLink.parentNode) {
return;
}
oldLink.parentNode.removeChild(oldLink);
});
}
}
/**
* Adds a timestamp to the given URI to force IE 11 and Edge to bypass the cache and request a fresh copy of the CSS.
* @param oldUri
* @return {string}
* @private
*/
bustCache_(oldUri) {
const newUri = oldUri
// Remove previous timestamp param (if present)
.replace(/[?&]timestamp=\d+(&|$)/, '')
// Remove trailing '?' or '&' char (if present)
.replace(/[?&]$/, '');
const separator = newUri.indexOf('?') === -1 ? '?' : '&';
return `${newUri}${separator}timestamp=${Date.now()}`;
}
/**
* @param {string} verb
* @param {string} oldUri
* @param {string} newUri
* @param {string} trailingPunctuation
* @private
*/
logHotSwap_(verb, oldUri, newUri, trailingPunctuation) {
const swapMessage = `"${oldUri}"${newUri ? ` with "${newUri}"` : ''}`;
console.log(`Hot ${verb} stylesheet ${swapMessage}${trailingPunctuation}`);
}
/**
* @param {!Document|!Element} root
* @return {!HotSwapper}
*/
static getInstance(root) {
if (!hotSwapperInstance) {
hotSwapperInstance = HotSwapper.attachTo(root, ToolbarProvider.attachTo(root));
}
return hotSwapperInstance;
}
}
class HashLinker extends InteractivityProvider {
/** @param {!Document|!Element} root */
static attachTo(root) {
const instance = new HashLinker(root);
instance.lazyInit();
return instance;
}
/** @override */
lazyInit() {
this.root_.addEventListener('click', (evt) => {
if (this.shouldPreventDefault_(evt)) {
evt.preventDefault();
}
});
}
/** @private */
shouldPreventDefault_(evt) {
return pony.closest(evt.target, 'a[href="#"], [data-demo-disable-hash-link-navigation] a[href^="#"]');
}
}
/** @param {!Document|!Element} root */
export function init(root) {
HotSwapper.getInstance(root);
HashLinker.attachTo(root);
}