forked from google/material-design-lite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmdlComponentHandler.js
276 lines (252 loc) · 9.1 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
/**
* @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';
var registeredComponents_ = [];
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 {object} optReplace Optional object to replace match with.
* @return {object | false}
* @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;
}
/**
* Searches existing DOM for elements of our component type and upgrades them
* if they have not already been upgraded.
* @param {string} jsClass the programatic name of the element class we need
* to create a new instance of.
* @param {string} cssClass the name of the CSS class elements of this type
* will have.
*/
function upgradeDomInternal(jsClass, cssClass) {
if (jsClass === undefined && cssClass === undefined) {
for (var i = 0; i < registeredComponents_.length; i++) {
upgradeDomInternal(registeredComponents_[i].className,
registeredComponents_[i].cssClass);
}
} else {
if (cssClass === undefined) {
var registeredClass = findRegisteredClass_(jsClass);
if (registeredClass) {
cssClass = registeredClass.cssClass;
}
}
var elements = document.querySelectorAll('.' + cssClass);
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} jsClass The name of the class we want to upgrade
* the element to.
*/
function upgradeElementInternal(element, jsClass) {
// Only upgrade elements that have not already been upgraded.
var dataUpgraded = element.getAttribute('data-upgraded');
if (dataUpgraded === null || dataUpgraded.indexOf(jsClass) === -1) {
// Upgrade element.
if (dataUpgraded === null) {
dataUpgraded = '';
}
element.setAttribute('data-upgraded', dataUpgraded + ',' + jsClass);
var registeredClass = findRegisteredClass_(jsClass);
if (registeredClass) {
// new
var instance = new registeredClass.classConstructor(element);
instance[componentConfigProperty_] = registeredClass;
createdComponents_.push(instance);
// Call any callbacks the user has registered with this component type.
registeredClass.callbacks.forEach(function(callback) {
callback(element);
});
if (registeredClass.widget) {
// Assign per element instance for control over API
element[jsClass] = instance;
}
} else {
throw 'Unable to find a registered component for the given class.';
}
var ev = document.createEvent('Events');
ev.initEvent('mdl-componentupgraded', true, true);
element.dispatchEvent(ev);
}
}
/**
* Registers a class for future use and attempts to upgrade existing DOM.
* @param {object} config An object containing:
* {constructor: Constructor, classAsString: string, cssClass: string}
*/
function registerInternal(config) {
var newConfig = {
'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 'The provided cssClass has already been registered.';
}
if (item.className === newConfig.className) {
throw 'The provided className has already been registered';
}
});
if (config.constructor.prototype
.hasOwnProperty(componentConfigProperty_)) {
throw '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} 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 {!Element} 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_.dataset.upgraded.split(',');
var componentPlace = upgrades.indexOf(
component[componentConfigProperty_].classAsString);
upgrades.splice(componentPlace, 1);
component.element_.dataset.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 {*} 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 '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,
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() {};
}
});