-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathDataFormsJS.js
More file actions
3409 lines (3168 loc) · 155 KB
/
DataFormsJS.js
File metadata and controls
3409 lines (3168 loc) · 155 KB
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* DataFormsJS Framework Application Object
*
* This script creates a global [DataFormJS] object which can also be
* referenced as [app]. One or more optional template rending engines are the
* only dependencies. In most apps the core [jsonData] page object from file
* [pages/jsonData.js] will also be included. DataFormsJS Framework uses
* ES5 syntax so that it can work with all browsers including older
* Mobile Devices and supported versions of IE. For older browsers and
* devices functions [fetch, Promise, etc] will be loaded as polyfill
* functions when the page is loaded. While the Framework is developed
* using ES5 custom code for apps that use it can use modern JS classes.
*
* View Engine Options:
* https://handlebarsjs.com
* https://vuejs.org
* # Both Vue 2 and Vue 3 are supported
* https://mozilla.github.io/nunjucks/
* https://underscorejs.org
*
* Common API Functions for creating Single Page Apps (SPA):
* # Pages `app.addPage()` and Plugins `app.addPlugin()` are the recommended
* # method for creating most custom app logic. JavaScript Controls
* # `app.addControl()` are similar in concept to Web Components and
* # recommended for complex page component/control logic that needs to render
* # custom HTML and call plugins or use other features from within the control.
* app.addPage()
* app.addPlugin()
* app.addControl()
* app.refreshAllHtmlControls(callback, model)
* app.refreshHtmlControl(element, callback, model)
* app.escapeHtml(value)
* app.showErrorAlert('message')
* app.showError(document.querySelector('h1'), 'Error Text')
* app.isUsingVue()
*
* Common API Properties for working with app data and for debugging with
* Browser DevTools:
* app.activeController
* app.activeModel
* app.activeJsControls
* app.activeVueModel
* app.activeParameterList
* app.controllers
* app.models
*
* Many more API functions exist and the demos provide many examples of how
* apps can be built with DataFormsJS. DataFormsJS is built to run directly
* in a browser without a build process; this allows for fast prototyping,
* development, and a clearly defined structure for apps built with DataFormsJS.
*
* In addition to the standard DataFormsJS Framework standalone classes for
* React and Web Components are available which provide similar functionality.
*
* Copyright Conrad Sollitt and Authors. For full details of copyright
* and license, view the LICENSE file that is distributed with DataFormsJS.
*
* @link https://www.dataformsjs.com
* @author Conrad Sollitt (https://conradsollitt.com)
* @license MIT
*/
/* Validates with both [jshint] and [eslint] */
/* global Handlebars, nunjucks, _, Vue, Promise */
/* jshint strict: true */
/* eslint-env browser */
/* eslint quotes: ["error", "single", { "avoidEscape": true }] */
/* eslint strict: ["error", "function"] */
/* eslint spaced-comment: ["error", "always"] */
/* eslint no-console: ["error", { allow: ["log", "warn", "error"] }] */
/* eslint no-prototype-builtins: "off" */
(function () {
'use strict'; // Invoke strict mode
// Object for Enum
var ViewEngines = {
NotSet: 'Not Set',
Unknown: 'Unknown',
Mixed: 'Mixed',
Handlebars: 'Handlebars',
Vue: 'Vue',
Nunjucks: 'Nunjucks',
Underscore: 'Underscore',
Text: 'Text',
};
// Private variables available to this function scope only
var viewEngine = ViewEngines.NotSet;
var validViewEngines = [
ViewEngines.Handlebars,
ViewEngines.Vue,
ViewEngines.Nunjucks,
ViewEngines.Underscore,
ViewEngines.Text,
];
var isUpdatingView = false;
var isUpdatingAllControls = false;
var isLoadingRoute = false;
var previousUrl = null;
var routeLoadingCount = 0;
var renderInterval = null;
var vueUpdateView = false;
var vueWatcherDepPrevLen = 0;
var isIE = (navigator.userAgent.indexOf('Trident/') !== -1);
var routingMode = null;
var checkedForCssVarPolyfill = false;
function validateTypeOf(value, typeName, propName, callingFunction) {
if (typeof value !== typeName) {
console.log(value);
throw new TypeError('[' + propName + '] was not defined as a ' + typeName + ' when the function ' + callingFunction + ' was called');
}
}
function validateObjectExists(value, propName, callingFunction) {
if (value === undefined) {
throw new TypeError('[' + propName + '] must first be defined before the function ' + callingFunction + ' is called');
} else if (typeof value !== 'object') {
console.log(value);
throw new TypeError('[' + propName + '] was not defined as an object when the function ' + callingFunction + ' was called');
}
}
function validateStringWithValue(value, propName, callingFunction) {
if (value === '') {
throw new TypeError('[' + propName + '] must have a value when defined when the function ' + callingFunction + ' is called');
}
}
function requireUndefinedProperty(object, objName, property) {
if (object[property] !== undefined) {
console.log(object);
throw new TypeError('[' + objName + '.' + property + '] is already defined');
}
}
function validateOptionalFunctions(obj, objName, objType, func) {
for (var n = 0, m = func.length; n < m; n++) {
if (obj[func[n]] !== undefined) {
if (typeof obj[func[n]] !== 'function') {
console.log(obj);
throw new TypeError(objType + '[' + objName + '].' + func[n] + ' is not defined as a function.');
}
}
}
}
function requireOneNamedProperty(obj, objName, objType, props) {
for (var n = 0, m = props.length; n < m; n++) {
if (obj[props[n]] !== undefined && obj[props[n]] !== null) {
return;
}
}
// If code execution makes it here the object is not valid
console.log(obj);
throw new TypeError(objType + '[' + objName + '] must have one of the following properties defined: ' + props.join(', '));
}
function validateElementExists(id, propName, callingFunction) {
if (document.getElementById(id) === null) {
throw new TypeError('An element was not found on the page with [' + propName + '][id=' + id + '] when the function ' + callingFunction + ' was called');
}
}
/**
* Private function used when rendering template errors. It creates a prefix
* for the error message that is relevant to the control had the error.
*
* @param {HTMLElement|null} element If the source of the error was from an HTML element
* @param {object|null} controller If the source of the error was from a controller
*/
function getTemplateErrorPrefix(element, controller) {
var errorMessage = '';
try {
// Where was the error from? A Control or an HTML Element?
if (controller !== null && controller.path) {
errorMessage = 'Error with [Controller.path = "' + controller.path + '"] - ';
} else if (element !== null && element instanceof HTMLElement) {
// If a HTML Element then get the attributes [data-template-id]
// and [data-template-url]
var attrId = element.getAttribute('data-template-id');
var attrUrl = element.getAttribute('data-template-url');
attrId = (attrId === null ? '' : ' data-template-id="' + attrId + '"');
attrUrl = (attrUrl === null ? '' : ' data-template-url="' + attrUrl + '"');
// Include [id] and [class] attributes along with the relevant data attributes.
errorMessage = 'Error with Element <' + element.tagName.toLowerCase();
errorMessage += ' id="' + element.id + '"';
errorMessage += ' class="' + element.className + '"';
errorMessage += attrId + attrUrl + '> - ';
}
return errorMessage;
} catch (e) {
console.error(e);
return errorMessage;
}
}
// Used by [app.showError] and [app.showErrorAlert]
function createElement(type, textContent, className) {
var el = document.createElement(type);
el.textContent = textContent;
if (className) {
el.className = className;
}
return el;
}
// Use to handle Vue Errors and Warnings. If a rendering error
// occurs the main View Element can end up being removed from the
// screen so this function handles it.
function showVueError(err, viewEl) {
// Wait half a second, this is not ideal but documented Vue functions
// do not appear to provide a callback to handle this.
console.error(err);
window.setTimeout(function () {
// Attach view element back to DOM if if was removed.
if (viewEl) {
if (viewEl.parentNode === null) {
var docEl = document.querySelector('body');
if (!docEl) {
docEl = document.documentElement;
}
docEl.appendChild(viewEl);
// Update active template so error shows again otherwise the
// view will disappear if a rendering error is view again for
// the same controller.
if (app.activeTemplate) {
app.activeTemplate.error = true;
app.activeTemplate.errorMessage = err.toString();
}
}
}
// Show Error
app.showError(viewEl, err);
}, 500);
}
/**
* Read or download and then compiles a template. This function is optimized so
* if an existing template is already compiled then it will not be compiled twice.
*
* @param {HTMLElement|null} element Element where the template was called from
* @param {object|null} controller Controller object
* @param {function} callback Callback function(template) that gets called once the template is compiled
*/
function compileTemplate(element, controller, callback) {
var script = null,
scriptUrl = null,
n,
m,
errorMessage = null,
templateId = null,
templateUrl = null,
templateEngine = null;
// Use Template ID if loading template embedded on the page or Template URL to download a new template
if (controller === null) {
templateId = element.getAttribute('data-template-id');
templateUrl = element.getAttribute('data-template-url');
if (app.activeController !== null) {
templateEngine = app.activeController.viewEngine;
}
} else {
// Get Controller Settings
templateId = controller.viewId;
templateUrl = controller.viewUrl;
if (controller.viewEngine !== undefined) {
templateEngine = controller.viewEngine;
}
// Make sure they are null. This would only happen if calling code
// redefines controller properties after they have been added.
if (templateId === undefined) {
templateId = null;
}
if (templateUrl === undefined) {
templateUrl = null;
}
// Validate Properties. The only way that these error can happen is if the controller is
// modified manually after calling addController() so these error would not be common.
if (templateId !== null && templateUrl !== null) {
errorMessage = 'A controller must have either [viewId] or [viewUrl] defined but not both properties. This error is not possible when calling the [addController()] so one or more of the properties were modified by JavaScript code after the controller was already added.';
callback(addTemplate(null, templateId, templateUrl, templateEngine, true, errorMessage));
return;
} else if (templateId === null && templateUrl === null) {
// Check if the controller being rendered only uses functions
// and not a template engine. If so then pass null to the callback.
if (typeof controller.onRouteLoad === 'function' ||
typeof controller.onBeforeRender === 'function' ||
typeof controller.onRendered === 'function') {
callback(null);
return;
}
// Missing required properties or functions
errorMessage = 'A controller must have either [viewId] or [viewUrl] defined but neither property is defined. This error is not possible when calling the [addController()] so one or more of the properties were modified by JavaScript code after the controller was already added.';
callback(addTemplate(null, templateId, templateUrl, templateEngine, true, errorMessage));
return;
}
}
// First check the template cache in case it has already been compiled
for (n = 0, m = app.compiledTemplates.length; n < m; n++) {
if (templateId !== null && app.compiledTemplates[n].id === templateId) {
callback(app.compiledTemplates[n]);
return;
} else if (templateUrl !== null && app.compiledTemplates[n].url === templateUrl) {
callback(app.compiledTemplates[n]);
return;
}
}
// If the template was not found from cached array, compile it and add it to the compiledTemplates Array.
// Determine download settings or read from <script> on screen
if (templateUrl !== null) {
scriptUrl = templateUrl;
// Unless defined from the controller property [viewEngine] the current
// View Engine will be used for the downloaded template.
if (templateEngine === null) {
templateEngine = viewEngine;
}
} else {
// Get the <script> element that contains either a template
// or a reference of a template to download from the [src] URL.
script = document.getElementById(templateId);
// Make sure the element exists
if (script === null) {
errorMessage = 'Script Tag for Template ID [' + templateId + '] does not exist.';
callback(addTemplate(element, templateId, templateUrl, templateEngine, true, errorMessage));
return;
}
// Check if it has [src] or [data-src] attributes
scriptUrl = (script.src ? script.src : script.getAttribute('data-src'));
templateEngine = app.getTemplateType(script);
}
// Is the the view engine of the current template different than the default view engine?
// Is so then change the current to match the view being compiled so that any downloaded
// controls from the view engine will use the same template engine.
if (templateEngine !== viewEngine && validViewEngines.indexOf(templateEngine) !== -1) {
viewEngine = templateEngine;
}
if (scriptUrl !== null && scriptUrl !== '') {
// Make the Request to get the Template then compile
app
.fetch(scriptUrl, null, 'text/plain')
.then(function(text) {
callback(addTemplate(null, templateId, templateUrl, templateEngine, false, text));
})
.catch(function(error) {
console.error(error);
var errorMessage = 'Error Downloading Template: [' + scriptUrl + '], Error: ' + error;
callback(addTemplate(null, templateId, templateUrl, templateEngine, true, errorMessage));
});
} else {
// This source of this template is inline in the HTML of the page
callback(addTemplate(script, templateId, templateUrl, templateEngine, false, script.innerHTML));
}
}
/**
* Adds a template to the compiledTemplates Array. This function
* only gets called from [compileTemplate()].
*
* @param {HTMLElement|null} script
* @param {string|null} templateId
* @param {string|null} templateUrl
* @param {string} engineType
* @param {bool} isError
* @param {string} sourceCode
* @return {object} Compiled Template
*/
function addTemplate(script, templateId, templateUrl, engineType, isError, sourceCode) {
var fn = null,
html = null,
compileError = false,
errorMessage = null;
if (!isError) {
try {
// Use the specified Template Engine to Compile the
// Text Source Code into a JavaScript Function
switch (engineType) {
case ViewEngines.Handlebars:
fn = Handlebars.compile(sourceCode);
break;
case ViewEngines.Nunjucks:
if (app.nunjucksEnvironment) {
fn = nunjucks.compile(sourceCode, app.nunjucksEnvironment);
} else {
fn = nunjucks.compile(sourceCode);
}
break;
case ViewEngines.Underscore:
fn = _.template(sourceCode);
break;
case ViewEngines.Text:
case ViewEngines.Vue:
html = sourceCode;
break;
default:
if (script === null) {
throw new TypeError('Unsupported or Unknown Template View Engine when the Template was downloaded. Template type at the time of downloading = ' + engineType);
} else {
throw new TypeError('Unsupported or Unknown Template View Engine specified in <script id="' + script.id + '" type="' + script.type + '" data-engine="' + script.getAttribute('data-engine') + '">');
}
}
} catch (e) {
fn = null;
html = null;
compileError = true;
errorMessage = e;
}
}
// Create a Template Object and add it to the compiledTemplates Source
var template = {
id: templateId,
url: templateUrl,
type: engineType,
engine: fn,
html: html,
error: isError || compileError,
errorMessage: (isError ? sourceCode : errorMessage)
};
app.compiledTemplates.push(template);
return template;
}
/**
* Render a compiled template to an HTML Element
*
* @param {HTMLElement} element Element that the template gets rendered to
* @param {object} controller Controller Object, this is used for debug text in the event of a rendering error
* @param {Object} template Template object from the compiledTemplates Array
* @param {object} model Data Context for the template
*/
function renderTemplate(element, controller, template, model) {
// Declare Variables
var html = '';
// Catch Exceptions
try {
// Show error if the Template had a compile or download error
if (template.error) {
app.showError(element, getTemplateErrorPrefix(element, controller) + template.errorMessage);
return;
}
// No error, render the template based on the specified template engine
switch (template.type) {
case ViewEngines.Handlebars:
case ViewEngines.Underscore:
html = template.engine(model);
break;
case ViewEngines.Nunjucks:
html = template.engine.render(model);
break;
case ViewEngines.Text:
case ViewEngines.Vue:
html = template.html;
break;
default:
// In most cases code execution will likely never reach here as these
// type of errors would be handled before they make it this far.
// This error can happen if an already compiled template is modified
// after being defined. This is confirmed with a unit test.
throw new TypeError('Unsupported or Unknown Template View Engine: ' + template.type);
}
// Set HTML of the Element (View or Control)
var setTextContent = element.getAttribute('data-set-text-content');
if (setTextContent === null) {
element.innerHTML = html;
} else {
element.textContent = html;
}
app.updateTemplatesForIE(element);
} catch (e) {
// If there was an error (for example a parsing error from Handlebars or Nunjucks) then
// get template error info that is helpful for the developer and show it along with the
// error text in the element.
app.showError(element, getTemplateErrorPrefix(element, controller) + e);
}
}
/**
* Render the view or call functions based on the URL hash.
* Called from [app.setup()] and the window [hashchange] event.
*/
function handleRouteChange() {
var path = (routingMode === 'hash' ? window.location.hash : window.location.pathname),
controller = null,
n,
m,
prop,
defaultIndex = -1,
routeResult,
error,
plugin;
// Handle race conditions where this function is called while the previous page
// is still loading or rendering. Typically this only causes errors on routes
// that use a lot of custom JavaScript and the route’s web services (or resources)
// are loading slowly and the user is clicking from page to page very fast.
// This is not unit tested, rather uncomment the [console.log] statements
// and for slow resources. For example, modify code in 'website\app\app.php'
// [$app->get('/*' ...] adding a timer and test with a local build of the main site.
if (routeLoadingCount > 200) {
app.showErrorAlert(app.settings.errors.pageLoading);
routeLoadingCount = 0;
isLoadingRoute = false;
return;
}
if (isLoadingRoute) {
if (previousUrl === path) {
return; // Still loading same route
}
// console.log('***** isLoadingRoute=true *****');
window.setTimeout(handleRouteChange, 200);
routeLoadingCount++;
return;
}
if (isUpdatingView) {
if (previousUrl === path) {
return; // Still rendering same route
}
// console.log('***** isUpdatingView=true *****');
window.setTimeout(handleRouteChange, 200);
routeLoadingCount++;
return;
}
isLoadingRoute = true;
routeLoadingCount = 0;
previousUrl = path;
// Is # the first character? If yes remove it
if (path.indexOf('#') === 0) {
path = path.substring(1);
}
// Define as root url ('/') if blank
if (path === '') {
path = '/';
}
// Allow plugins to cancel the route change. This is not a common
// event and was created so that DataFormsJS can be used with one page sites
// rather than Single Page Apps (SPA).
for (plugin in app.plugins) {
if (app.plugins.hasOwnProperty(plugin) && app.plugins[plugin].onAllowRouteChange !== undefined) {
try {
var changeRoute = app.plugins[plugin].onAllowRouteChange(path);
if (changeRoute === false) {
isLoadingRoute = false;
return;
}
} catch (e) {
app.showErrorAlert('Error from Plugin [' + plugin + '] on [onAllowRouteChange()]: ' + e.toString());
console.error(e);
}
}
}
// Make sure all loaded JS Controls are unloaded
app.unloadAllJsControls();
// Handle [onRouteUnload] functions for the previous route
if (app.activeController !== null) {
// Unload Plugins
for (plugin in app.plugins) {
if (app.plugins.hasOwnProperty(plugin) && app.plugins[plugin].onRouteUnload !== undefined) {
try {
app.plugins[plugin].onRouteUnload();
} catch (e) {
app.showErrorAlert('Error from Plugin [' + plugin + '] on [onRouteUnload()]: ' + e.toString());
console.error(e);
}
}
}
// Unload Controller
// When using Vue [onRouteUnload()] is called on the Vue instance [beforeDestroy()]
if (app.activeController.onRouteUnload !== undefined && app.activeVueModel === null && app.viewEngine() !== 'Vue') {
try {
app.activeController.onRouteUnload.apply(app.activeModel, app.activeParameters);
} catch (e) {
app.showErrorAlert('Error from Controller [path=' + app.activeController.path + '] on [onRouteUnload()]: ' + e.toString());
console.error(e);
}
}
}
// Destroy the Vue View Model
if (app.activeVueModel !== null) {
if (app.activeVueApp === null) {
// Vue 2
app.activeVueModel.$destroy();
// Optionally (default: false) convert data from the Vue Instance to a
// plain JavaScript Object and save it back to the models object.
// For info on usage and example see [CHANGELOG.md] release `4.2.1`.
if (app.settings.clearVue2WatchersOnRouteUnload &&
app.activeController &&
app.activeController.modelName &&
app.models[app.activeController.modelName] &&
app.activeVueModel.$data
) {
app.models[app.activeController.modelName] = JSON.parse(JSON.stringify(app.activeVueModel.$data));
}
} else {
// Vue 3 uses a JavaScript Proxy object so the model is automatically
// updated by the proxy and does not have to be reset when the route changes.
app.activeVueApp.unmount();
}
}
// Clear the Current Route
app.activeController = null;
app.activeTemplate = null;
app.activeModel = null;
app.activeVueModel = null;
app.activeVueApp = null;
app.activeParameters = [];
app.activeParameterList = {};
vueWatcherDepPrevLen = 0;
vueUpdateView = false;
// Find matching controller for the hash or get default if not match
for (n = 0, m = app.controllers.length; n < m; n++) {
routeResult = app.routeMatches(path, app.controllers[n].path);
if (routeResult.isMatch) {
controller = app.controllers[n];
app.activeParameters = routeResult.args;
app.activeParameterList = routeResult.namedArgs;
break;
} else if (app.controllers[n].path === app.settings.defaultRoute) {
defaultIndex = n;
}
}
// Route not found, redirect to the default
if (controller === null && defaultIndex !== -1) {
// If the default path is a page for a specific language and the
// i18n plugin is being used then redirect to the default language.
var newPath = app.settings.defaultRoute;
if (app.settings.defaultRoute === '/:lang/' &&
app.plugins.i18n !== undefined &&
typeof app.plugins.i18n.readSettings === 'function' &&
typeof app.plugins.i18n.getUserDefaultLang === 'function'
) {
app.plugins.i18n.readSettings();
var selectedLang = app.plugins.i18n.getUserDefaultLang();
if (selectedLang !== null) {
newPath = '/' + selectedLang + '/';
}
}
app.changeRoute(newPath);
isLoadingRoute = false;
return;
}
// Route found or No Controllers or No Default Route
if (controller === null) {
// No controllers so SPA is not being used, render/load Controls and call Plugins
if (app.controllers.length === 0) {
app.updateView();
isLoadingRoute = false;
return;
}
// Show error that happens only if there is an invalid default route.
if (path !== app.settings.defaultRoute) {
error = 'Error - The route [' + path + '] does not have a <script data-route> element or [Controller] defined. Check to make sure that a controller or script for default route [' + app.settings.defaultRoute + '] exists.';
app.showError(document.querySelector(app.settings.viewSelector), error);
}
isLoadingRoute = false;
} else {
// Set active controller/route and load both controller and model
app.activeController = controller;
loadController(controller, function () {
loadModel(controller);
// Assign named parameters to the active model
for (prop in app.activeParameterList) {
if (app.activeParameterList.hasOwnProperty(prop)) {
app.activeModel[prop] = app.activeParameterList[prop];
}
}
// Compile and set the active Template then load the view
compileTemplate(null, controller, function(template) {
var fn = [],
fnName = [],
fnIndex = 0,
fnCount = 0;
// Private function to load the route/controller after plugins run
function routeLoad() {
// Set active template and call controller route load method
app.activeTemplate = template;
if (controller.onRouteLoad !== undefined && app.activeController && app.activeController.viewEngine !== ViewEngines.Vue) {
try {
controller.onRouteLoad.apply(app.activeModel, app.activeParameters);
} catch (e) {
app.showErrorAlert('Error from Controller [path=' + controller.path + '] on [onRouteLoad()]: ' + e.toString());
console.error(e);
}
}
// Reset scroll position and render the view
window.scrollTo(0, 0);
app.updateView();
isLoadingRoute = false;
}
// Recursive function that gets called if using plugins with
// [onRouteLoad]. Only one function runs at a time and must finish
// before the next one is called. Each plugin must handle the
// [next()] callback otherwise the view will never be rendered.
// If a plugin calls [next(false)] then the route will not be loaded;
// this would be used for cases where the route sets [window.location].
function nextPlugin() {
try {
var plugin = fnName[fnIndex];
plugin = app.plugins[plugin];
fn[fnIndex].call(plugin, (function(loadRoute) {
if (loadRoute === false) {
isLoadingRoute = false;
return;
}
fnIndex++;
if (fnIndex === fnCount) {
routeLoad();
} else {
nextPlugin();
}
}));
} catch (e) {
app.showErrorAlert('Error from Plugin [' + fnName[fnIndex] + '] on [onRouteLoad()]: ' + e.toString());
console.error(e);
app.updateView();
isLoadingRoute = false;
}
}
// Build a list of Plugin [onRouteLoad] functions and call the first one,
// or if no plugins have an [onRouteLoad] then render the view.
for (var plugin in app.plugins) {
if (app.plugins.hasOwnProperty(plugin) && app.plugins[plugin].onRouteLoad !== undefined) {
fn.push(app.plugins[plugin].onRouteLoad);
fnName.push(plugin);
}
}
fnCount = fn.length;
if (fnCount === 0) {
routeLoad();
} else {
nextPlugin();
}
});
});
}
}
/**
* Load the controller after the route changes. This function handles
* [data-lazy-load] (controller.settings.lazyLoad) to download any
* needed JS and CSS scripts before the controller is used.
*
* @param {object} controller
* @param {function} callback
*/
function loadController(controller, callback) {
// Controller does not use lazy loading so finish loading it immediately.
if (controller.settings === undefined || controller.settings.lazyLoad === undefined) {
setControllerFromPage(controller);
callback();
return;
}
// Show loading screen while the scripts are being loaded. Scripts should load
// quick but on mobile devices a delay of 1 second makes the page looks like it
// is not being loaded. This code displays the loading view, however only
// simple templates embedded on the page can be used with it.
if (app.settings.lazyTemplateSelector !== null) {
var view = document.querySelector(app.settings.viewSelector);
var tmpl = document.querySelector(app.settings.lazyTemplateSelector);
if (view && tmpl) {
if (tmpl.tagName === 'TEMPLATE' || (tmpl.tagName === 'SCRIPT' && tmpl.getAttribute('data-engine') === 'text')) {
view.innerHTML = tmpl.innerHTML;
} else {
console.warn('Unable to show loading screen from [app.settings.lazyTemplateSelector]. Only <template> tags are allowed.');
}
}
}
// Items to load are comma delimited, for each item add a promise
// to load the related scripts defined from [app.lazyLoad].
var lazyLoad = controller.settings.lazyLoad;
var routeScripts = lazyLoad.split(',').map(function(s) { return s.trim(); });
var promises = [];
routeScripts.forEach(function(script) {
if (app.lazyLoad[script] === undefined) {
console.error('Missing [app.LazyLoad] scripts for: ' + script);
} else {
promises.push(app.loadScripts(app.lazyLoad[script]));
}
});
// Once all scripts are downloaded then finish loading the controller.
Promise.all(promises).finally(function () {
setControllerFromPage(controller);
callback();
});
}
/**
* Setup Controller functions from the page object the first time
* that the controller is used.
*
* @param {object} controller
*/
function setControllerFromPage(controller) {
if (controller.pageType !== null && controller.pageType !== undefined && controller._pageCopied === undefined) {
// Validate
var error = null;
if (app.pages[controller.pageType] === undefined) {
error = 'The page [' + controller.pageType + '] has not been loaded for Controller[path=' + controller.path + '].';
} else if (typeof app.pages[controller.pageType] === 'object' && typeof app.pages[controller.pageType].model !== 'object') {
error = 'Error - The [model] property for page object [' + controller.pageType + '] must be a valid JavaScript Object.';
}
if (error !== null) {
controller.settings = controller.settings || {};
controller.settings.errorMessage = error;
controller.settings.hasError = true;
app.showErrorAlert(error);
return;
}
// Update controller with all functions from the page object or class
var page = app.pages[controller.pageType];
if (typeof page === 'function') {
// JavaScript class
var functions = app.getClassFunctionNames(page);
var includeFn = ['onRouteLoad', 'onBeforeRender', 'onRendered', 'onRouteUnload'];
for (var n = 0; n < functions.length; n++) {
var fn = functions[n];
if (includeFn.includes(fn)) {
controller[fn] = page.prototype[fn];
}
}
} else {
// Copy from Object
for (var prop in page) {
if (page.hasOwnProperty(prop) && typeof page[prop] === 'function') {
controller[prop] = page[prop];
}
}
}
// If using Vue and the page objects defines [computed] functions then
// assign them to the controller. [methods] are assigned for Vue from the
// model when `loadModel(controller)` is called. See example usage in [examples\template-files-vue.htm]
if (controller.viewEngine === ViewEngines.Vue && typeof page.computed === 'object' && controller.computed === undefined) {
controller.computed = page.computed;
}
// Define variable so this runs only once per controller
controller._pageCopied = true;
}
}
/**
* Load the [app.activeModel] based on the controller
* @param {object} controller
*/
function loadModel(controller) {
var model,
modelName,
page,
prop;
// Set active model and exit if it already exists
if (controller.modelName) {
app.activeModel = app.models[controller.modelName];
return;
}
// If Page Type is defined then create a dynamic model from the Page Object
if (controller.pageType) {
page = app.pages[controller.pageType];
if (page !== undefined) {
// Create the model and assign the new model name to the controller.
// For Vue, properties are assigned to the model and functions are
// assigned to a controller [methods] object.
if (controller.viewEngine === ViewEngines.Vue) {
model = {};
controller.methods = (controller.methods === undefined ? {} : controller.methods);
if (typeof page === 'function') {
// Page defined as a `class`
model = new page();
var fn = app.getClassFunctionNames(page);
var excludeFn = ['constructor', 'onRouteLoad', 'onBeforeRender', 'onRendered', 'onRouteUnload'];
for (var n = 0; n < fn.length; n++) {
prop = fn[n];
if (!excludeFn.includes(prop)) {
controller.methods[prop] = page.prototype[prop];
}
}
} else {
// Page defined as an object `{}`
for (prop in page.model) {
if (page.model.hasOwnProperty(prop)) {
var propType = Object.prototype.toString.call(page.model[prop]);
if (propType === '[object Function]') {
controller.methods[prop] = page.model[prop];
} else if (propType === '[object Object]') {
model[prop] = app.deepClone({}, page.model[prop]);
} else if (propType === '[object Array]') {
model[prop] = app.deepClone([], page.model[prop]);
} else {
model[prop] = page.model[prop];
}
}
}
}
} else {
if (typeof page === 'function') {
model = new page(); // JS class
} else {
model = app.deepClone({}, page.model);
}
}
}
}
// Copy Controller Settings to the Model Object
if (controller.settings !== undefined && Object.keys(controller.settings).length > 0) {
if (model === undefined) {
model = {};
}
app.deepClone(model, controller.settings);
}
// Save Model to App unless [model.loadOnlyOnce] is defined and set to false
if (model && model.loadOnlyOnce !== false) {
// Create a dynamic model name (e.g.: 'model_0_JsonData')
if (controller.pageType === null || controller.pageType === undefined) {
modelName = 'Dynamic';
} else {
modelName = controller.pageType;
modelName = modelName.substring(0, 1).toUpperCase() + modelName.substring(1);
}
modelName = 'model_' + String(Object.keys(app.models).length) + '_' + modelName;
// Add Model
app.addModel(modelName, model);
controller.modelName = modelName;
}
// Set the active model or create a temporary one for the page
if (controller.modelName) {
app.activeModel = app.models[controller.modelName];
} else {
app.activeModel = (model === undefined ? {} : model);
}
}
/**
* Private function used to handle global errors when [app.handleGlobalErrors(true)]
* is called or if attribute <html data-show-errors> is defined.
*
* Code modified from:
* https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror
*
* @param {ErrorEvent} errorEvent
*/
function errorHandler(errorEvent) {
// Current Time
var now = (new Date());
var time = ('toLocaleString' in now ? now.toLocaleString() : now.toString());
// Build and Show Message
var message;
if (errorEvent.message.toLowerCase().indexOf('script error') > -1){
message = 'Script Error at ' + time + ': See Browser Console for Detail';
} else {
message = [
'Message: [' + errorEvent.message + ']',
'Time: [' + time + ']',
'URL: [' + errorEvent.filename + ']',
'Line: ' + errorEvent.lineno,
'Column: ' + errorEvent.colno,
'Error Object: ' + JSON.stringify(errorEvent.error)
].join(' - ');
}