-
Notifications
You must be signed in to change notification settings - Fork 0
/
qairoe-app-router-behavior.html
445 lines (374 loc) · 15.8 KB
/
qairoe-app-router-behavior.html
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
<!-- Polymer dependencies -->
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../lazy-imports/lazy-imports.html">
<script>
(function(){
'use strict';
/** @polymerBehavior Polymer.QairoeAppRouterBehavior */
Polymer.QairoeAppRouterBehaviorImpl = {
observers: [
'_setQueryParams(_route.__queryParams)',
'_setPath(_route.path)'
],
properties: {
/**
* Comes from app-location. The current most important parts here
* are `path` and `__queryParams` which sets the `path` and `queryParams`
* of this element respectively.
* @type {{prefix: string, path: string, __queryParams: object }}
*/
_route: {
type: Object
},
/**
* The current path of the app. Changes depending on the URL put at the top
* or pushed in the state of the browser
*/
path: {
type: String,
notify: true,
observer: '_pathChanged'
},
/**
* This is an object that holds the values of the parameters in the route
* pattern set in the current page element being viewed.
*/
params: {
type: Object,
// value: function() { return {}; },
notify: true
},
/**
* This is an object that holds the values of the query parameters in the url
*/
queryParams: {
type: Object,
// value: function() { return {}; },
notify: true
},
/**
* This is required. This is the tag-name of the element that holds
* the list of page elements that will need to be lazy-loaded.
*/
parentTagName: {
type: String
},
/**
* This is for iron-selected navigation lists
*/
currentRoute: {
type: String,
notify: true
}
},
/**
* This will be the registered element that holds all the source files of the
* elements that needed to be lazy-loaded.
*/
_fromElement: null,
/**
* This is a dictionary of routes linked to its corresponding elements.
*/
_routes: {},
/**
* This holds the current route that is being viewed
*/
_currentView: '',
/**
* This holds the next route to be viewed after the url has been changed.
*/
_newView: '',
attached: function() {
// https://github.com/Polymer/polymer/blob/master/src/lib/dom-module.html#L69
// Using DomModule API import to get the element with links
this._fromElement = Polymer.DomModule && Polymer.DomModule.import && this.parentTagName ?
Polymer.DomModule.import(this.parentTagName) : null;
if (!this._fromElement || !this.parentTagName) {
return console.error(new Error('Please put existing element name with link tags with rel="lazy-import"'));
}
this._observer = Polymer.dom(this).observeNodes(function(info) {
this._contentAdded(info.addedNodes.filter(function(node) {
return (node.nodeType === Node.ELEMENT_NODE);
}));
}.bind(this));
},
detached: function() {
Polymer.dom(this).unobserveNodes(this._observer);
},
/**
* Sets the queryParams property and updates the element's params and queryParams
* properties. It also calls the page element's updateView method if it exists
*/
_setQueryParams: function(queryParams) {
this.queryParams = queryParams || {};
this._updateCurrentViewData();
},
/**
* updates the currentView using the updateView method and
* and also updates the currentView's params and queryParams attributes
*/
_updateCurrentViewData: function() {
if (this._routes[this._currentView] &&
this._routes[this._currentView].element &&
this._routes[this._currentView].element.updateView) {
this._routes[this._currentView].element.updateView({
params: this.params,
queryParams: this.queryParams
});
}
if (this._currentView) {
this._routes[this._currentView].element.params = this.params || {};
this._routes[this._currentView].element.queryParams = this.queryParams || {};
}
},
/**
* Sets the path property
*/
_setPath: function(path) {
this.path = path || '/';
},
/**
* Called in the attached lifecycle method to put the children to the dictionary
* for easy referencing
*/
_contentAdded: function(pages) {
for (var i in pages) {
var el = pages[i];
if (el && el.hasAttribute && el.hasAttribute('route')) {
var route = el.getAttribute('route');
var title = el.getAttribute('title');
if (!this._routes[route]) {
this.set('_routes.' + route, {
element: el,
title: title
});
} else {
console.log(new Error(el.tagName.toLowerCase() + ' uses the same route: ' +
route + ' with ' + this._routes[route].element.tagName.toLocaleLowerCase()));
}
}
}
this._pathChanged(this.path);
},
/**
* This is called when the path changes. It tries to look for a the pattern
* that matches the path, then calls the _changeView method to change the view
*/
_pathChanged: function(path, authFlag) {
var routes = this._routes;
var patternMatched = null;
this.params = {};
// TODO: TEST IF THIS IS THE RIGHT WAY
this.currentRoute = path;
// goes checks each and every route
for (var pattern in routes) {
// Because 404 and 403 are not url patterns
if (pattern === 'not-authorized' || pattern === 'not-found') {
continue;
}
var remainingPieces = path.split('/');
var patternPieces = pattern.split('/');
var pathLength = remainingPieces[remainingPieces.length - 1] === '' ? remainingPieces.length - 1 : remainingPieces.length;
var patternLength = patternPieces[patternPieces.length - 1] === '' ? patternPieces.length - 1 : patternPieces.length;
var routeMatched = [];
var namedMatches = {};
// does the match making if the path length and pattern lenght is the same
// or if the last part of the pattern is a *
if ((pathLength === patternLength) || patternPieces[patternPieces.length - 1] === '*') {
// evaluate and match the path to pattern
for (var i=0; i < patternPieces.length; i++) {
var patternPiece = patternPieces[i];
// stops if the pattern piece is not existing
if (!patternPiece && patternPiece !== '') {
break;
}
// get the left side of the path.
var pathPiece = remainingPieces.shift();
// stops if the left side doesn't exist
if (!pathPiece && pathPiece !== '') {
break;
}
// push the current pattern to the route matched
routeMatched.push(patternPiece);
// if it has a ':', it means that the value in the current path fragment
// should be put in the variable that has the name after the ':'
if (patternPiece.charAt(0) == ':') {
namedMatches[patternPiece.slice(1)] = pathPiece;
// if it is a '*', it means that it should accept all paths that has
// a prefix of the route matched
} else if (patternPiece === '*') {
patternMatched = routeMatched.join('/');
// the pattern piece and the path piece doesn't match, go to next route pattern
} else if (patternPiece !== pathPiece) {
break;
}
// create the pattern matched
patternMatched = routeMatched.join('/');
}
// if pattern matched is created, stop searching and change views
if (patternMatched) {
break;
}
}
}
// if pattern matched is created, change the view, if exausted all
// route patterns, make view a not-found
if (patternMatched) {
this._newView = patternMatched;
this.params = namedMatches || {};
} else {
this._newView = 'not-found';
}
this._changeView(authFlag);
},
/**
* Changes the viewport
*/
_changeView: function(authFlag) {
var outViewPromise = null;
var newView = this._routes[this._newView];
var currentView = this._routes[this._currentView];
var promises = [];
var data = {
params: this.params,
queryParams: this.queryParams
};
// if there's no element that exists given a route pattern
if (!newView || !newView.element) {
// check if adding a * would do the trick
var array = this._newView.split('/');
// even if adding a * at the end doesn't work, it will not do anything
if (array[array.length - 1] === '*') {
return;
// if the the last of the pattern is '', just change it to * and then check again
} else if (array[array.length - 1] === '') {
array[array.length - 1] = '*'
} else {
array.push('*')
}
this._newView = array.join('/');
return this._changeView(authFlag);
}
// check if the page element has an auth attribute and if it is set to true or false
if (newView.element.auth !== null && newView.element.auth !== undefined && !!!newView.element.auth) {
// if it is being checked for the first time (like first load and authentication checking hasn't kicked in)
// wait for 2 seconds before checking the view again.
// TODO: might need to add a loader of some sort
if (!authFlag) {
return this.async(this._changeView.bind(this, true), 1500);
} else {
this._newView = 'not-authorized';
newView = this._routes[this._newView];
}
}
// if the next view is just equal to the same view, just update the data.
if (this._newView === this._currentView) {
return this._updateCurrentViewData();
}
// calls exitView method of the currentView element
if (currentView && currentView.element && currentView.element.exitView) {
outViewPromise = currentView.element.exitView(data);
}
// checks if the output of currentView is a promise and if it is not, just create
// a resolved promise to continue
if (!(outViewPromise instanceof Promise)) {
outViewPromise = Promise.resolve();
}
// add the promise to the list of promises
promises.push(outViewPromise);
// if the view has not been loaded, call the importLazyGroup method from LazyGroupBehaviors
// to load the element and push the result to the promise
if (!this._routes[this._newView].resolved) {
if (this._routes[this._newView].element.constructor === HTMLElement || this._routes[this._newView].element.constructor === HTMLUnknownElement) {
var lazyGroupPromise = this.importLazyGroup(newView.element.tagName.toLocaleLowerCase(), this._fromElement);
if (!(lazyGroupPromise instanceof Promise)) {
lazyGroupPromise = Promise.resolve();
}
promises.push(lazyGroupPromise);
} else {
this._routes[this._newView].resolved = {
loaded: [true]
};
}
}
// execute all promises and outputs the result
Promise.all(promises).then(function(result) {
// if there's a result from the lazy group promise
// set the routes resolved to the result of the promise
if (result[1]) {
this._routes[this._newView].resolved = result[1];
}
// if the element has been called by the lazy group, but it is not loaded,
// or the constructor is set to HTMLElement or HTMLUnknownElement (for IE users)
// which means the definition wasn't loaded, then set the view to not-found
if (this._routes[this._newView].resolved.loaded.length === 0 ||
newView.element.constructor === HTMLElement ||
newView.element.constructor === HTMLUnknownElement) {
this._newView = 'not-found';
return this._changeView();
}
// if the element has been loaded, but still the constructor is not set
// then tell the dev that the lazy-group definition loaded the wrong file
// for the html tag that it should define
if (this._routes[this._newView].resolved.loaded.length > 0 &&
(newView.element.constructor === HTMLElement ||
newView.element.constructor === HTMLUnknownElement)) {
console.error(new Error('You have loaded a different file that didn\'t define the element: ' +
newView.element.tagName.toLocaleLowerCase()));
}
// set the viewport to the newView and set the currentView to the newView
this.$$('#viewport').select(this._newView);
this._currentView = this._newView;
// call the enterView method if it exits
if (newView && newView.element && newView.element.enterView) {
newView.element.enterView(data);
}
if (newView && newView.element) {
newView.element.params = this.params || {};
newView.element.queryParams = this.queryParams || {};
}
// change the title in the browser
if (newView && newView.title) {
document.title = newView.title;
}
this.fire('view-loaded');
// using google tag manager
if (window.dataLayer) {
dataLayer.push({
'event':'virtualPageView',
'page':{
'title': document.title,
'url': window.location.href
}
});
// or if using google analytics
} else if (window.ga) {
ga('set', 'page', this.path);
ga('send', 'pageview');
}
}.bind(this)).catch(function(error) {
console.error(error);
/**
* Fired when there's an error in changing the views.
*
* @event change-view-error
* @param {object} the error object.
*/
this.fire('change-view-error', error);
}.bind(this));
},
/**
* This should be called if the auth value of the current page element changes
* so as to "hot" reload the page.
*/
renderForAuth: function() {
this._pathChanged(this.path, true);
}
};
/** @polymerBehavior */
Polymer.QairoeAppRouterBehavior = [
Polymer.LazyImportsBehavior,
Polymer.QairoeAppRouterBehaviorImpl
];
})();
</script>