-
Notifications
You must be signed in to change notification settings - Fork 5k
/
mdlComponentHandler.js
376 lines (345 loc) · 12.7 KB
/
mdlComponentHandler.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
/**
* @license
* Copyright 2015 Google Inc. 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.
*/
/**
* A component handler interface using the revealing module design pattern.
* More details on this design pattern here:
* https://github.com/jasonmayes/mdl-component-design-pattern
* @author Jason Mayes.
*/
/* exported componentHandler */
var componentHandler = (function() {
'use strict';
/** @type {!Array<componentHandler.ComponentConfig>} */
var registeredComponents_ = [];
/** @type {!Array<componentHandler.Component>} */
var createdComponents_ = [];
var downgradeMethod_ = 'mdlDowngrade_';
var componentConfigProperty_ = 'mdlComponentConfigInternal_';
/**
* Searches registered components for a class we are interested in using.
* Optionally replaces a match with passed object if specified.
* @param {string} name The name of a class we want to use.
* @param {componentHandler.ComponentConfig=} optReplace Optional object to replace match with.
* @return {!Object|boolean}
* @private
*/
function findRegisteredClass_(name, optReplace) {
for (var i = 0; i < registeredComponents_.length; i++) {
if (registeredComponents_[i].className === name) {
if (optReplace !== undefined) {
registeredComponents_[i] = optReplace;
}
return registeredComponents_[i];
}
}
return false;
}
/**
* Returns an array of the classNames of the upgraded classes on the element.
* @param {!HTMLElement} element The element to fetch data from.
* @return {!Array<string>}
* @private
*/
function getUpgradedListOfElement_(element) {
var dataUpgraded = element.getAttribute('data-upgraded');
// Use `['']` as default value to conform the `,name,name...` style.
return dataUpgraded === null ? [''] : dataUpgraded.split(',');
}
/**
* Returns true if the given element has already been upgraded for the given
* class.
* @param {!HTMLElement} element The element we want to check.
* @param {string} jsClass The class to check for.
* @return boolean
* @private
*/
function isElementUpgraded_(element, jsClass) {
var upgradedList = getUpgradedListOfElement_(element);
return upgradedList.indexOf(jsClass) !== -1;
}
/**
* Searches existing DOM for elements of our component type and upgrades them
* if they have not already been upgraded.
* @param {string=} optJsClass the programatic name of the element class we
* need to create a new instance of.
* @param {string=} optCssClass the name of the CSS class elements of this
* type will have.
*/
function upgradeDomInternal(optJsClass, optCssClass) {
if (optJsClass === undefined && optCssClass === undefined) {
for (var i = 0; i < registeredComponents_.length; i++) {
upgradeDomInternal(registeredComponents_[i].className,
registeredComponents_[i].cssClass);
}
} else {
var jsClass = /** @type {string} */ (optJsClass);
if (optCssClass === undefined) {
var registeredClass = findRegisteredClass_(jsClass);
if (registeredClass) {
optCssClass = registeredClass.cssClass;
}
}
var elements = document.querySelectorAll('.' + optCssClass);
for (var n = 0; n < elements.length; n++) {
upgradeElementInternal(elements[n], jsClass);
}
}
}
/**
* Upgrades a specific element rather than all in the DOM.
* @param {!HTMLElement} element The element we wish to upgrade.
* @param {string=} optJsClass Optional name of the class we want to upgrade
* the element to.
*/
function upgradeElementInternal(element, optJsClass) {
// Verify argument type.
if (!(typeof element === 'object' && element instanceof Element)) {
throw new Error('Invalid argument provided to upgrade MDL element.');
}
var upgradedList = getUpgradedListOfElement_(element);
var classesToUpgrade = [];
// If jsClass is not provided scan the registered components to find the
// ones matching the element's CSS classList.
if (!optJsClass) {
var classList = element.classList;
registeredComponents_.forEach(function(component) {
// Match CSS & Not to be upgraded & Not upgraded.
if (classList.contains(component.cssClass) &&
classesToUpgrade.indexOf(component) === -1 &&
!isElementUpgraded_(element, component.className)) {
classesToUpgrade.push(component);
}
});
} else if (!isElementUpgraded_(element, optJsClass)) {
classesToUpgrade.push(findRegisteredClass_(optJsClass));
}
// Upgrade the element for each classes.
for (var i = 0, n = classesToUpgrade.length, registeredClass; i < n; i++) {
registeredClass = classesToUpgrade[i];
if (registeredClass) {
// Mark element as upgraded.
upgradedList.push(registeredClass.className);
element.setAttribute('data-upgraded', upgradedList.join(','));
var instance = new registeredClass.classConstructor(element);
instance[componentConfigProperty_] = registeredClass;
createdComponents_.push(instance);
// Call any callbacks the user has registered with this component type.
for (var j = 0, m = registeredClass.callbacks.length; j < m; j++) {
registeredClass.callbacks[j](element);
}
if (registeredClass.widget) {
// Assign per element instance for control over API
element[registeredClass.className] = instance;
}
} else {
throw new Error(
'Unable to find a registered component for the given class.');
}
var ev = document.createEvent('Events');
ev.initEvent('mdl-componentupgraded', true, true);
element.dispatchEvent(ev);
}
}
/**
* Upgrades a specific list of elements rather than all in the DOM.
* @param {!HTMLElement|!Array<!HTMLElement>|!NodeList|!HTMLCollection} elements
* The elements we wish to upgrade.
*/
function upgradeElementsInternal(elements) {
if (!Array.isArray(elements)) {
if (typeof elements.item === 'function') {
elements = Array.prototype.slice.call(/** @type {Array} */ (elements));
} else {
elements = [elements];
}
}
for (var i = 0, n = elements.length, element; i < n; i++) {
element = elements[i];
if (element instanceof HTMLElement) {
if (element.children.length > 0) {
upgradeElementsInternal(element.children);
}
upgradeElementInternal(element);
}
}
}
/**
* Registers a class for future use and attempts to upgrade existing DOM.
* @param {{constructor: !Function, classAsString: string, cssClass: string, widget: string}} config
*/
function registerInternal(config) {
var newConfig = /** @type {componentHandler.ComponentConfig} */ ({
'classConstructor': config.constructor,
'className': config.classAsString,
'cssClass': config.cssClass,
'widget': config.widget === undefined ? true : config.widget,
'callbacks': []
});
registeredComponents_.forEach(function(item) {
if (item.cssClass === newConfig.cssClass) {
throw new Error('The provided cssClass has already been registered.');
}
if (item.className === newConfig.className) {
throw new Error('The provided className has already been registered');
}
});
if (config.constructor.prototype
.hasOwnProperty(componentConfigProperty_)) {
throw new Error(
'MDL component classes must not have ' + componentConfigProperty_ +
' defined as a property.');
}
var found = findRegisteredClass_(config.classAsString, newConfig);
if (!found) {
registeredComponents_.push(newConfig);
}
}
/**
* Allows user to be alerted to any upgrades that are performed for a given
* component type
* @param {string} jsClass The class name of the MDL component we wish
* to hook into for any upgrades performed.
* @param {function(!HTMLElement)} callback The function to call upon an
* upgrade. This function should expect 1 parameter - the HTMLElement which
* got upgraded.
*/
function registerUpgradedCallbackInternal(jsClass, callback) {
var regClass = findRegisteredClass_(jsClass);
if (regClass) {
regClass.callbacks.push(callback);
}
}
/**
* Upgrades all registered components found in the current DOM. This is
* automatically called on window load.
*/
function upgradeAllRegisteredInternal() {
for (var n = 0; n < registeredComponents_.length; n++) {
upgradeDomInternal(registeredComponents_[n].className);
}
}
/**
* Finds a created component by a given DOM node.
*
* @param {!Node} node
* @return {*}
*/
function findCreatedComponentByNodeInternal(node) {
for (var n = 0; n < createdComponents_.length; n++) {
var component = createdComponents_[n];
if (component.element_ === node) {
return component;
}
}
}
/**
* Check the component for the downgrade method.
* Execute if found.
* Remove component from createdComponents list.
*
* @param {*} component
*/
function deconstructComponentInternal(component) {
if (component &&
component[componentConfigProperty_]
.classConstructor.prototype
.hasOwnProperty(downgradeMethod_)) {
component[downgradeMethod_]();
var componentIndex = createdComponents_.indexOf(component);
createdComponents_.splice(componentIndex, 1);
var upgrades = component.element_.getAttribute('data-upgraded').split(',');
var componentPlace = upgrades.indexOf(
component[componentConfigProperty_].classAsString);
upgrades.splice(componentPlace, 1);
component.element_.setAttribute('data-upgraded', upgrades.join(','));
var ev = document.createEvent('Events');
ev.initEvent('mdl-componentdowngraded', true, true);
component.element_.dispatchEvent(ev);
}
}
/**
* Downgrade either a given node, an array of nodes, or a NodeList.
*
* @param {!Node|!Array<!Node>|!NodeList} nodes
*/
function downgradeNodesInternal(nodes) {
var downgradeNode = function(node) {
deconstructComponentInternal(findCreatedComponentByNodeInternal(node));
};
if (nodes instanceof Array || nodes instanceof NodeList) {
for (var n = 0; n < nodes.length; n++) {
downgradeNode(nodes[n]);
}
} else if (nodes instanceof Node) {
downgradeNode(nodes);
} else {
throw new Error('Invalid argument provided to downgrade MDL nodes.');
}
}
// Now return the functions that should be made public with their publicly
// facing names...
return {
upgradeDom: upgradeDomInternal,
upgradeElement: upgradeElementInternal,
upgradeElements: upgradeElementsInternal,
upgradeAllRegistered: upgradeAllRegisteredInternal,
registerUpgradedCallback: registerUpgradedCallbackInternal,
register: registerInternal,
downgradeElements: downgradeNodesInternal
};
})();
window.addEventListener('load', function() {
'use strict';
/**
* Performs a "Cutting the mustard" test. If the browser supports the features
* tested, adds a mdl-js class to the <html> element. It then upgrades all MDL
* components requiring JavaScript.
*/
if ('classList' in document.createElement('div') &&
'querySelector' in document &&
'addEventListener' in window && Array.prototype.forEach) {
document.documentElement.classList.add('mdl-js');
componentHandler.upgradeAllRegistered();
} else {
componentHandler.upgradeElement =
componentHandler.register = function() {};
}
});
/**
* Describes the type of a registered component type managed by
* componentHandler. Provided for benefit of the Closure compiler.
* @typedef {{
* constructor: !Function,
* className: string,
* cssClass: string,
* widget: string,
* callbacks: !Array<function(!HTMLElement)>
* }}
*/
componentHandler.ComponentConfig; // jshint ignore:line
/**
* Created component (i.e., upgraded element) type as managed by
* componentHandler. Provided for benefit of the Closure compiler.
* @typedef {{
* element_: !HTMLElement,
* className: string,
* classAsString: string,
* cssClass: string,
* widget: string
* }}
*/
componentHandler.Component; // jshint ignore:line