This repository has been archived by the owner on Jul 11, 2019. It is now read-only.
/
MdlComponentHandler.dart
470 lines (371 loc) · 16.2 KB
/
MdlComponentHandler.dart
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
/**
* Copyright (c) 2015, Michael Mitterer (office@mikemitterer.at),
* IT-Consulting and Development Limited.
*
* 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.
*/
part of mdlcore;
class _RootContext { const _RootContext(); }
/// Store strings for class names defined by this component that are used in Dart.
class _MdlComponentHandlerCssClasses {
final String UPGRADING = "mdl-upgrading";
final String UPGRADED = "mdl-upgraded";
final String HTML_JS = "mdl-js";
final String HTML_DART = "mdl-dart";
final String DOWNGRADED = "mdl-downgraded";
final String RIPPLE_EFFECT = "mdl-js-ripple-effect";
const _MdlComponentHandlerCssClasses();
}
class _MdlComponentHandlerCssAttributes {
final String REPEAT_TEMPLATE = "template";
const _MdlComponentHandlerCssAttributes();
}
/**
* A component handler interface using the revealing module design pattern.
* More details on this pattern design here:
* https://github.com/jasonmayes/mdl-component-design-pattern
* (JS-Version: Jason Mayes.)
*
* @author Mike Mitterer
*/
class MdlComponentHandler {
final Logger _logger = new Logger('mdlcore.ComponentHandler');
final String _DATA_KEY = "data-upgraded";
static const _MdlComponentHandlerCssClasses _cssClasses = const _MdlComponentHandlerCssClasses();
static const _MdlComponentHandlerCssAttributes _cssAttributes = const _MdlComponentHandlerCssAttributes();
final Map<String, MdlConfig> _registeredComponents = new HashMap<String, MdlConfig>();
final List<di.Module> _modules = new List<di.Module>();
/// If set to true it
bool _enableVisualDebugging = false;
/// The injector for this module.
di.Injector _injector;
/**
* Registers a class for future use and attempts to upgrade existing DOM.
* Sample:
* final ComponentHandler componenthandler = new ComponentHandler();
* componenthandler.register(new MdlConfig<MaterialButton>("mdl-button"));
*/
void register(final MdlConfig config) {
Validate.notNull(config);
if(!_isValidClassName(config.classAsString)) {
_logger.severe("(${config.classAsString}) is not a valid component for ${config.selector}");
return;
}
if (!_isRegistered(config)) {
_registeredComponents.putIfAbsent(config.classAsString, () => config);
}
}
/**
* Allows user to be alerted to any upgrades that are performed for a given
* component type
* [config] The class-config of the MDL component we wish
* to hook into for any upgrades performed.
* The [callback]-function to call upon an upgrade. This
* function should expect 1 parameter - the HTMLElement which got upgraded.
*/
void registerUpgradedCallback(final MdlConfig config,final MdlCallback callback) {
if(_isValidClassName(config.classAsString) && _isRegistered(config)) {
_registeredComponents[config.classAsString].callbacks.add(callback);
}
}
@deprecated
Future upgradeAllRegistered() => run();
/// Upgrades all children for {element} and returns the current Injector
Future<di.Injector> upgradeElement(final dom.HtmlElement element) {
Validate.notNull(_injector,"Injector must not be null - did you call run?");
Validate.notNull(element,"Component must not be null!");
dom.querySelector("html")
..classes.add(_cssClasses.HTML_JS)
..classes.add(_cssClasses.HTML_DART)
..classes.remove(_cssClasses.UPGRADED);
final Future<di.Injector> future = new Future<di.Injector>( () {
element.classes.add(_cssClasses.UPGRADING);
_configs.forEach((final MdlConfig config) {
_upgradeDom(element,config);
_logger.finer("${config.selector} upgraded with ${config.classAsString}...");
});
element.classes.remove(_cssClasses.UPGRADING);
element.classes.add(_cssClasses.UPGRADED);
dom.querySelector("body").classes.remove(_cssClasses.UPGRADING);
dom.querySelector("html").classes.add(_cssClasses.UPGRADED);
_logger.fine("All components are upgraded...");
return _injector;
});
return future;
}
/// downgrade() will be called for the given Component and it's children
Future downgradeElement(final dom.HtmlElement element) {
Validate.notNull(element,"Element to downgrade must not be null!");
final Completer completer = new Completer();
new Future(() {
if(element is dom.HtmlElement) {
final List<dom.Element> children = element.querySelectorAll('[class*="mdl-"]');
// Children first
children.forEach((final dom.Element element) => _deconstructComponent(element));
_deconstructComponent(element);
}
completer.complete();
});
return completer.future;
}
//- DI ----------------------------------------------------------------------------------------
/**
* Upgrades all registered components found in the current DOM. This
* should be called in your main-function.
* At the beginning of the upgrade-process it adds the css-classes
* mdl-js, mdl-dart and mdl-upgrading to the <html>-element.
* If all components are ready it removes mdl-upgrading.
*
* Sample:
* main() {
* registerMdl();
*
* componentFactory().run().then( (_) {
*
* });
* }
*/
Future<MaterialApplication> run( { final enableVisualDebugging: false } ) {
final dom.Element body = dom.querySelector("body");
_enableVisualDebugging = enableVisualDebugging;
//_modules.add(new di.Module()..bind(DomRenderer));
_injector = _createInjector();
return upgradeElement(body).then((_) => new Future<MaterialApplication>(() {
return _injector.get(MaterialApplication) as MaterialApplication;
}));
}
/**
* In most cases this is your AppController
*
* Sample:
* @MdlComponentModel @di.Injectable()
* class AppController {
*
* }
*
* main() {
* registerMdl();
*
* componentFactory().rootContext(AppController).run().then( (final di.Injector injector) {
* new AppController();
* });
* }
*/
MdlComponentHandler rootContext(final Type rootContext) {
_modules.add(new di.Module()..bind(MaterialApplication, toImplementation: rootContext));
return this;
}
/// Add your App-specific modules
MdlComponentHandler addModule(final di.Module module) {
if(_modules.indexOf(module) == -1) {
_modules.add(module);
}
return this;
}
/// Returns the injector for this module.
di.Injector get injector {
if(_injector == null) {
_injector = _createInjector();
}
return _injector;
}
/**
* Returns your Application-Object.
*
* Define it like this:
*
* @MdlComponentModel @di.Injectable()
* class Application extends MaterialApplication {
* Application() { }
*
* @override
* void run() {
* // App logic
* }
* }
*
* main() {
* registerMdl();
*
* componentFactory().rootContext(Application).run()
* .then((final MaterialApplication application) {
* application.run();
* });
* }
*
*/
MaterialApplication get application {
return injector.get(MaterialApplication);
}
//- private -----------------------------------------------------------------------------------
bool _isRegistered(final MdlConfig config) => _registeredComponents.containsKey(config.classAsString);
bool _isValidClassName(final String classname) => (classname != "dynamic");
/// The component with the highest priority comes last
List<MdlConfig> get _configs {
final List<MdlConfig> configs = new List<MdlConfig>.from(_registeredComponents.values);
configs.sort((final MdlConfig a, final MdlConfig b) {
return a.priority.compareTo(b.priority);
});
return configs;
}
/// Returns true if the given element has already been upgraded for the given
/// class / Config.
bool _isElementUpgraded(final dom.Element element,final MdlConfig config) {
final bool upgraded = element.dataset.containsKey('upgraded');
if(!upgraded) {
return false;
}
return element.dataset['upgraded'].contains(config.classAsString);
}
/**
* Searches existing DOM for elements of our component type and upgrades them
* if they have not already been upgraded!
* {queryBaseElement} defines where the querySelector starts to search - can be any element.
* upgradeAllRegistered uses "body" as {queryBaseElement}
*/
void _upgradeDom(final dom.Element queryBaseElement, final MdlConfig config) {
Validate.notNull(queryBaseElement);
Validate.notNull(config);
// final List<Future> futureUpgrade = new List<Future>();
// final Future future = new Future(() {
/// Check if {config.selector} is either the class-name or the tag name of {baseElement}
/// If so - upgrade
void _upgradeBaseElementIfSelectorFits(final dom.Element baseElement) {
bool upgrade = false;
switch(config.selectorType) {
case SelectorType.TAG:
upgrade = baseElement.tagName.toLowerCase() == config.selector;
break;
case SelectorType.ATTRIBUTE:
upgrade = baseElement.attributes.containsKey(config.selector.replaceAll(new RegExp(r"\[|\]"),""));
break;
case SelectorType.CLASS:
default:
upgrade = baseElement.classes.contains(config.selector.replaceFirst(".",""));
}
if(upgrade) {
_upgradeElement(baseElement, config);
}
}
_upgradeBaseElementIfSelectorFits(queryBaseElement);
final dom.ElementList<dom.HtmlElement> elements = queryBaseElement.querySelectorAll(config.selector);
elements.forEach((final dom.HtmlElement element) {
_upgradeElement(element, config);
// futureUpgrade.add(_upgradeElement(element, config));
});
// });
// futureUpgrade.add(future);
// Future.wait(futureUpgrade);
}
/**
* Upgrades a specific element rather than all in the DOM.
* [element] is the element we wish to upgrade.
* [config] the Dart-Class/Css-Class configuration of the class we want to upgrade
* the element to.
*/
void _upgradeElement(final dom.HtmlElement element, final MdlConfig config) {
Validate.notNull(element);
Validate.notNull(config);
/// If there is a tag with template attribute - ignore this element!
bool _hasRepeatTemplate(final dom.HtmlElement element) {
if(element == null) {
return false;
}
if(element.attributes.containsKey(_cssAttributes.REPEAT_TEMPLATE)) {
return true;
}
return _hasRepeatTemplate(element.parent);
}
if (( !element.attributes.containsKey(_DATA_KEY) ||
element.attributes[_DATA_KEY].contains(config.classAsString) == false) && !_hasRepeatTemplate(element)) {
void _markAsUpgraded() {
final List<String> registeredClasses = element.attributes.containsKey(_DATA_KEY)
? element.attributes[_DATA_KEY].split(",") : new List<String>();
registeredClasses.add(config.classAsString);
element.attributes[_DATA_KEY] = registeredClasses.join(",");
}
try {
final MdlComponent component = config.newComponent(element,_injector);
component.visualDebugging = _enableVisualDebugging;
config.callbacks.forEach((final MdlCallback callback) => callback(element));
_markAsUpgraded();
_logger.finer("${config.classAsString} -> ${component}");
// Makes it possible to query for the main element in this component.
var jsElement = new JsObject.fromBrowserObject(component.hub);
if(config.isWidget) {
// remember all the registered components in MDL_WIDGET_PROPERTY
if(jsElement.hasProperty(MDL_WIDGET_PROPERTY)) {
final List<String> componentsForElement = (jsElement[MDL_WIDGET_PROPERTY] as String).split(",");
if(!componentsForElement.contains(config.classAsString)) {
componentsForElement.add(config.classAsString);
jsElement[MDL_WIDGET_PROPERTY] = componentsForElement.join(",");
}
// MDL/JS wants to go this route - not sure if it makes sense!!!!
if(componentsForElement.length > 1) {
_logger.warning("$element has more than one components. ($componentsForElement)\n"
"This can lead into problems with 'MdlComponent.parent'...");
}
} else {
jsElement[MDL_WIDGET_PROPERTY] = config.classAsString;
}
// register the component
jsElement[config.classAsString] = component;
} else {
jsElement[MDL_RIPPLE_PROPERTY] = component;
}
}
catch (exception, stacktrace) {
_logger.severe("Registration for: ${config.selector} not possible. Check if ${config.classAsString} is correctly imported");
_logger.severe(exception, stacktrace);
}
}
}
/**
* Creates an injector function that can be used for retrieving services as well as for
* dependency injection.
*/
di.Injector _createInjector() {
return new di.ModuleInjector(_modules);
}
/// Downgrades the given {element} with all it's components
void _deconstructComponent(final dom.HtmlElement element) {
try {
// Also remove the Widget-Property
var jsElement = new JsObject.fromBrowserObject(element);
MdlComponent component;
if(jsElement.hasProperty(MDL_RIPPLE_PROPERTY)) {
component = jsElement[MDL_RIPPLE_PROPERTY] as MdlComponent;
component.downgrade();
jsElement.deleteProperty(MDL_RIPPLE_PROPERTY);
}
if(jsElement.hasProperty(MDL_WIDGET_PROPERTY)) {
final List<String> componentsForElement = (jsElement[MDL_WIDGET_PROPERTY] as String).split(",");
componentsForElement.forEach((final String componentName) {
component = jsElement[componentName] as MdlComponent;
component.downgrade();
jsElement.deleteProperty(componentName);
});
jsElement.deleteProperty(MDL_WIDGET_PROPERTY);
}
// doesn't mater if it is a widget or a ripple...
if(component != null) {
component.attributes.remove(_DATA_KEY);
component.classes.add(_cssClasses.DOWNGRADED);
}
} on String catch (e) {
_logger.severe(e);
}
}
}