-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathnavigator-js.js
2532 lines (2084 loc) · 76.1 KB
/
navigator-js.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
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
/*
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:</p>
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
this.navigatorjs = this.navigatorjs || {};
(function() {
var AsynchResponders = function() {
this._responders = [];
};
//PUBLIC API
AsynchResponders.prototype = {
getLength: function() {
return this._responders.length;
},
isBusy: function() {
return this.getLength() > 0;
},
hasResponder: function(responder) {
return this._responders.indexOf(responder) != -1;
},
addResponder: function(responder) {
this._responders.push(responder);
},
addResponders: function(additionalRespondersArray) {
if (additionalRespondersArray && additionalRespondersArray instanceof Array && additionalRespondersArray.length) {
this._responders = this._responders.concat(additionalRespondersArray);
}
},
takeOutResponder: function(responder) {
var index = this._responders.indexOf(responder);
if (index != -1) {
this._responders.splice(index, 1);
return true;
}
return false;
},
reset: function() {
if (this._responders.length > 0) {
console.warn("Resetting too early? Still have responders marked for asynchronous tasks");
}
this._responders = [];
}
};
navigatorjs.AsynchResponders = AsynchResponders;
}());;this.navigatorjs = this.navigatorjs || {};
(function() {
/**
* History manager for the navigatorjs.Navigator
*
* @example
* <code>
*
* // Create the normal navigator
* var navigator = new navigatorjs.Navigator();
*
* // Create the history and supply the navigator it should manage
* var history = new navigatorjs.History(navigator);
*
* // Navigate to states as you normally would
* navigator.request('/my/state');
*
* // Go back in time
* history.back();
*
* </code>
*
* @author Laurent van Dommelen
* @created 11 oct 2013
*
* @param {navigatorjs.Navigator} navigator
*/
var History = function(navigator) {
// Bind the methods to this scope
navigatorjs.utils.AutoBind(this, this);
// Initialize the instance
this._initialize(navigator);
};
// Default max history length, don't change this,
// change the maxLength instance property
History.MAX_HISTORY_LENGTH = 100;
// Navigation direction types
History.DIRECTION_BACK = -1;
History.DIRECTION_NORMAL = 0;
History.DIRECTION_FORWARD = 1;
/**
* Instance properties
*/
History.prototype = {
// The navigator it is controlling
_navigator: null,
// The history, last state is at start of Array
_history: null,
// The current position in history
_historyPosition: 0,
// The navigator doesn't know anything about going forward or back.
// Therefore, we need to keep track of the direction.
// This is changed when the forward or back methods are called.
_navigationDirection: History.DIRECTION_NORMAL,
// The max number of history states
maxLength: History.MAX_HISTORY_LENGTH,
/**
* Create the history manager. When navigating back and forword, the history is maintained.
* It is truncated when navigating to a state naturally
*
* @param {navigatorjs.Navigator} navigator
* @param {Object} [options]
*/
_initialize: function(navigator, options) {
// Setup the options
if (options) {
this.maxLength = options.maxLength || this.maxLength;
}
// Create the history array containing the NavigationState objects
this._history = [];
// Listen to changes on the navigator
this._navigator = navigator;
this._navigator.on(navigatorjs.NavigatorEvent.STATE_CHANGED, this._handleStateChange);
},
/**
* Go back in the history
*
* @param {Number} [steps=1] The number of steps to go back in history
* @return {Boolean} Returns false if there was no previous state
*/
back: function(steps) {
// Check if we know history
if (this._historyPosition == this._history.length - 1) {
return false;
}
// Set to 1 by default
steps = steps || 1;
// Set the history position and navigate to it
this._historyPosition = Math.min(this._history.length - 1, this._historyPosition + steps);
this._navigationDirection = History.DIRECTION_BACK;
this._navigateToCurrentHistoryPosition();
return true;
},
/**
* Go forward in the history
*
* @param {Number} [steps=1] The number of steps to go forward in history
* @return {Boolean} Returns false if there was no next state
*/
forward: function(steps) {
if (this._historyPosition === 0) {
return false;
}
// Set to 1 by default
steps = steps || 1;
// Set the history position and navigate to it
this._historyPosition = Math.max(0, this._historyPosition - steps);
this._navigationDirection = History.DIRECTION_FORWARD;
this._navigateToCurrentHistoryPosition();
return true;
},
/**
* Go back in the history and return that NavigationState
*
* @param {Number} [steps=1] The number of steps to go back in history
* @return {navigatorjs.NavigationState} The found state or null if no state was found
*/
getPreviousState: function(steps) {
// Cannot go beyond the first entry in history
if (this._history.length === 0 || this._historyPosition == Math.max(0, this._history.length - 1)) {
return null;
}
// Set to 1 by default
steps = steps || 1;
// Fetch the requested state in history
var position = Math.min(this._history.length - 1, Math.max(0, this._historyPosition + steps));
return this._history[position];
},
/**
* Go forward in the history and return that NavigationState
*
* @param {Number} [steps=1] The number of steps to go back in history
* @return {navigatorjs.NavigationState} The found state or null if no state was found
*/
getNextState: function(steps) {
// Cannot look into the future
if (this._history.length === 0 || this._historyPosition === 0) {
return null;
}
// Set to 1 by default
steps = steps || 1;
// Fetch the requested state in history
var position = Math.max(0, this._historyPosition - steps);
return this._history[position];
},
/**
* Fetch the current NavigationState
*
* @return {navigatorjs.NavigationState}
*/
getCurrentState: function() {
return this._history[this._historyPosition] || null;
},
/**
* Clear the navigation history
*/
clearHistory: function() {
this._history = [];
this._historyPosition = 1;
},
/**
* Get the full history
*
* @return {Array} List of navigatorjs.NavigationStates
*/
all: function() {
return this._history;
},
/**
* Get the state by historyposition
*
* @param {Number} position The position in history
* @return {navigatorjs.NavigationState} The found state or null if no state was found
*/
getStateByPosition: function (position) {
if (position < 0 || position > this._history.length - 1) {
return null;
}
return this._history[position];
},
/**
* Get the first occurence of a state in the history
*
* @param {navigatorjs.NavigationState} state The NavigationState in history
* @return {Number} The found position or false if not found
*/
getPositionByState: function(state) {
return this.getPositionByPath(state.getPath());
},
/**
* Find the first occurence of the path in the history
*
* @param {String} path
* @return {Number} The index or false if not found
*/
getPositionByPath: function(path) {
var count = this.getLength();
for (var i = 0; i < count; i++) {
if (this._history[i].getPath() == path) {
return i;
}
}
return false;
},
/**
* Get the number of items in the history
*
* @return {Number}
*/
getLength: function() {
return this._history.length;
},
/**
* Tell the navigator to go the current historyPosition
*/
_navigateToCurrentHistoryPosition: function() {
var newState = this._history[this._historyPosition];
this._navigator.request(newState);
},
/**
* Check what to do with the new state
*
* @param {Object} event
* @param {Object} update
*/
_handleStateChange: function(event, update) {
var state = update.state;
switch (this._navigationDirection) {
case History.DIRECTION_BACK:
this._navigationDirection = History.DIRECTION_NORMAL;
break;
case History.DIRECTION_NORMAL:
// Strip every history state before current
this._history.splice(0, this._historyPosition);
// Add the state at the beginning of the history array
this._history.unshift(state);
this._historyPosition = 0;
// Truncate the history to the max allowed items
this._history.length = Math.min(this._history.length, this.maxLength);
break;
case History.DIRECTION_FORWARD:
this._navigationDirection = History.DIRECTION_NORMAL;
break;
}
}
};
// Copy the History object to the navigatorjs namespace
navigatorjs.History = History;
}());;this.navigatorjs = this.navigatorjs || {};
this.navigatorjs.NavigationBehaviors = {};
/**
* Will show when the state matches, will hide when it doesn't
*/
this.navigatorjs.NavigationBehaviors.SHOW = "show";
/**
* Will hide when the state matches, even if it has a show on a higher level
*/
this.navigatorjs.NavigationBehaviors.HIDE = "hide";
/**
* Will update before any show method gets called
*/
this.navigatorjs.NavigationBehaviors.UPDATE = "update";
/**
* Will swap out and in, when the state is changed
*/
this.navigatorjs.NavigationBehaviors.SWAP = "swap";
/**
* Will ask for validation of the state, if a state can't be validated, it is denied
*/
this.navigatorjs.NavigationBehaviors.VALIDATE = "validate";
/**
* Will try to add all behaviors, based on the class properties of the responder
*/
this.navigatorjs.NavigationBehaviors.AUTO = "auto";
/**
* Used for looping through when the AUTO behavior is used.
*/
this.navigatorjs.NavigationBehaviors.ALL_AUTO = ["show", "update", "swap", "validate"];;this.navigatorjs = this.navigatorjs || {};
this.navigatorjs.NavigationResponderBehaviors = {};
this.navigatorjs.NavigationResponderBehaviors.IHasStateInitialization = {name: "IHasStateInitialization", methods: ["initializeByNavigator"]};
this.navigatorjs.NavigationResponderBehaviors.IHasStateValidation = {name: "IHasStateValidation", methods: ["validate"]};
this.navigatorjs.NavigationResponderBehaviors.IHasStateValidationAsync = {name: "IHasStateValidationAsync", "extends": ["IHasStateValidation"], methods: ["prepareValidation"]};
this.navigatorjs.NavigationResponderBehaviors.IHasStateValidationOptional = {name: "IHasStateValidationOptional", "extends": ["IHasStateValidation"], methods: ["willValidate"]};
this.navigatorjs.NavigationResponderBehaviors.IHasStateValidationOptionalAsync = {name: "IHasStateValidationOptionalAsync", "extends": ["IHasStateValidationAsync", "IHasStateValidationOptional"], methods: []};
this.navigatorjs.NavigationResponderBehaviors.IHasStateRedirection = {name: "IHasStateRedirection", "extends": ["IHasStateValidation"], methods: ["redirect"]};
this.navigatorjs.NavigationResponderBehaviors.IHasStateSwap = {name: "IHasStateSwap", methods: ["willSwapToState", "swapOut", "swapIn"]};
this.navigatorjs.NavigationResponderBehaviors.IHasStateTransition = {name: "IHasStateTransition", methods: ["transitionIn", "transitionOut"]};
this.navigatorjs.NavigationResponderBehaviors.IHasStateUpdate = {name: "IHasStateUpdate", methods: ["updateState"]};
this.navigatorjs.NavigationResponderBehaviors.implementsBehaviorInterface = function(object, interface) {
if (object.navigatorBehaviors == undefined || !object.navigatorBehaviors instanceof Array) {
//The input interface is not set on object's navigatorBehaviors.
return false;
}
var inheritanceChain = navigatorjs.NavigationResponderBehaviors.getInterfaceInheritanceChain(interface),
methodsToBeImplemented = navigatorjs.NavigationResponderBehaviors.getInterfaceMethods(inheritanceChain),
i, method,
length = methodsToBeImplemented.length;
for (i = 0; i < length; i++) {
method = methodsToBeImplemented[i];
if (object[method] == undefined || typeof object[method] !== 'function') {
return false;
}
}
return true;
};
this.navigatorjs.NavigationResponderBehaviors.getInterfaceInheritanceChain = function(interface, existingChain) {
var chain = existingChain || [],
extendsArray,
extendingInterface,
i, length,
interfaceObject = navigatorjs.NavigationResponderBehaviors[interface];
if (interfaceObject == undefined || typeof interfaceObject !== 'object') {
// console.log('behaviorObject for interface is undefined ', interface );
return chain;
}
chain.push(interface);
extendsArray = interfaceObject["extends"];
if (extendsArray == undefined) {
// console.log('extendsArray for interface is undefined, the chain ends here ', interface, chain);
return chain;
}
length = extendsArray.length;
for (i = 0; i < length; i++) {
extendingInterface = extendsArray[i];
if (chain.indexOf(extendingInterface) == -1) {
//We did not yet extend this interface, so continue to follow the chain
navigatorjs.NavigationResponderBehaviors.getInterfaceInheritanceChain(extendingInterface, chain);
}
}
return chain;
};
this.navigatorjs.NavigationResponderBehaviors.getInterfaceMethods = function(interfaces) {
if (interfaces == undefined || !interfaces instanceof Array) {
//No valid input
return [];
}
var combinedInterfacesChain = [],
interface, i,
length = interfaces.length,
interfaceObject,
interfaceMethods,
j, methodsLength, method,
methods = [];
for (i = 0; i < length; i++) {
interface = interfaces[i];
navigatorjs.NavigationResponderBehaviors.getInterfaceInheritanceChain(interface, combinedInterfacesChain);
}
length = combinedInterfacesChain.length;
for (i = 0; i < length; i++) {
interface = combinedInterfacesChain[i];
interfaceObject = navigatorjs.NavigationResponderBehaviors[interface];
interfaceMethods = interfaceObject.methods;
if (interfaceObject != undefined && typeof interfaceObject === 'object' && interfaceMethods != undefined && interfaceMethods instanceof Array) {
methodsLength = interfaceMethods.length;
for (j = 0; j < methodsLength; j++) {
method = interfaceMethods[j];
if (methods.indexOf(method) == -1) {
methods.push(method);
}
}
}
}
return methods;
};;this.navigatorjs = this.navigatorjs || {};
(function() {
var NavigationState = function(pathStringOrArray) {
this._path = '';
if (pathStringOrArray instanceof Array) {
this.setSegments(pathStringOrArray);
} else {
this.setPath(pathStringOrArray || "");
}
};
NavigationState.make = function(stateOrPath) {
return stateOrPath instanceof navigatorjs.NavigationState ? stateOrPath : new navigatorjs.NavigationState(stateOrPath);
};
NavigationState.prototype = {
setPath: function(path) {
this._path = '/' + path.toLowerCase() + '/';
this._path = this._path.replace(new RegExp("[^-_/A-Za-z0-9* ]", "g"), "");
this._path = this._path.replace(new RegExp("\/+", "g"), "/");
this._path = this._path.replace(/\s+/g, "-");
return this;
},
getPath: function() {
return this._path;
},
getPathRegex: function() {
var segments = this.getSegments(),
regexPath = "\/",
segment,
i, length = segments.length;
for(i=0; i<length; i++) {
segment = segments[i];
if(segment == "**") {
// match any character, including slashes (multiple segments)
// eg: bla or bla/bla or bla/bla/bla
regexPath = regexPath + "(.*)";
} else if(segment == "*") {
// match anything expect slashes and end with a slash (1 segment only).
// eg: bla/ but not /bla/ or bla/bla/
regexPath = regexPath + "([^/]*)\/";
} else {
// Either the segment, a wildcard or double wildcard and ends with a forward slash (1 segment only).
// eg: segment/ or */ or **/
regexPath = regexPath + "("+segment+"|\\*|\\*\\*)\/";
}
}
return new RegExp(regexPath);
},
setSegments: function(segments) {
this.setPath(segments.join("/"));
},
getSegments: function() {
var segments = this._path.split("/");
segments.pop();
segments.shift();
return segments;
},
getSegment: function(index) {
return this.getSegments()[index];
},
getFirstSegment: function() {
return this.getSegment(0);
},
getLastSegment: function() {
var segments = this.getSegments();
return this.getSegment(segments.length - 1);
},
contains: function(foreignStateOrPathOrArray) {
if(foreignStateOrPathOrArray instanceof Array) {
return this._containsStateInArray(foreignStateOrPathOrArray);
}
var foreignStateOrPath = foreignStateOrPathOrArray, //if we get this far, it is a state or path
foreignState = NavigationState.make(foreignStateOrPath),
foreignSegments = foreignState.getSegments(),
nativeSegments = this.getSegments(),
foreignMatch = this.getPath().match(foreignState.getPathRegex()),
nativeMatch = foreignState.getPath().match(this.getPathRegex()),
isForeignMatch = foreignMatch && foreignMatch.index == 0 ? true : false,
isNativeMatch = nativeMatch && nativeMatch.index == 0 ? true : false,
foreignSegmentDoubleWildcardsMatch = foreignState.getPath().match(/\*\*/g),
doubleWildcardsLength = foreignSegmentDoubleWildcardsMatch ? foreignSegmentDoubleWildcardsMatch.length : 0,
tooManyForeignSegments = foreignSegments.length > (nativeSegments.length + doubleWildcardsLength),
enoughNativeSegments = nativeSegments.length > foreignSegments.length;
return (isForeignMatch || (isNativeMatch && enoughNativeSegments)) && !tooManyForeignSegments;
},
_containsStateInArray: function(foreignStatesOrPaths) {
var i, length = foreignStatesOrPaths.length,
foreignStateOrPath;
for(i=0; i<length; i++){
foreignStateOrPath = foreignStatesOrPaths[i];
if(this.contains(foreignStateOrPath)) {
return true;
}
}
return false;
},
equals: function(stateOrPathOrArray) {
if(stateOrPathOrArray instanceof Array) {
return this._equalsStateInArray(stateOrPathOrArray);
}
var stateOrPath = stateOrPathOrArray, //if we get this far, it is a state or path
state = NavigationState.make(stateOrPath),
subtractedState = this.subtract(state) || state.subtract(this); //Or the other way around for double wildcard states
if (subtractedState === null) {
return false;
}
return subtractedState.getSegments().length === 0;
},
_equalsStateInArray: function(statesOrPaths) {
var i, length = statesOrPaths.length,
stateOrPath;
for(i=0; i<length; i++){
stateOrPath = statesOrPaths[i];
if(this.equals(stateOrPath)) {
return true;
}
}
return false;
},
subtract: function(operandStateOrPath) {
var operand = NavigationState.make(operandStateOrPath),
subtractedPath;
if (!this.contains(operand)) {
return null;
}
subtractedPath = this.getPath().replace(operand.getPathRegex(), "");
return new navigatorjs.NavigationState(subtractedPath);
},
append: function(stringOrState) {
var path = stringOrState;
if (stringOrState instanceof NavigationState) {
path = stringOrState.getPath();
}
return this.setPath(this._path + path);
},
prepend: function(stringOrState) {
var path = stringOrState;
if (stringOrState instanceof NavigationState) {
path = stringOrState.getPath();
}
return this.setPath(path + this._path);
},
hasWildcard: function() {
return this.getPath().indexOf("/*/") != -1;
},
mask: function(sourceStateOrPath) {
var sourceState = NavigationState.make(sourceStateOrPath),
unmaskedSegments = this.getSegments(),
sourceSegments = sourceState.getSegments(),
length = Math.min(unmaskedSegments.length, sourceSegments.length),
i;
for (i = 0; i < length; i++) {
if (unmaskedSegments[i] === "*") {
unmaskedSegments[i] = sourceSegments[i];
}
}
return new navigatorjs.NavigationState(unmaskedSegments);
},
clone: function() {
return new navigatorjs.NavigationState(this._path);
}
};
navigatorjs.NavigationState = NavigationState;
}());;this.navigatorjs = this.navigatorjs || {};
(function() {
//
var _$eventDispatcher = null;
//internal namespaces
var _flow = {};
var _transition = {};
var _validation = {};
var _hidden = {};
//
var _currentState = null;
var _previousState = null;
var _defaultState = null;
var _isTransitioning = false;
//
var _responders = null; //new navigatorjs.ResponderLists();
var _respondersByID = null; //{};
var _statusByResponderID = null; //{};
var _redirects = null;
var _disappearingAsynchResponders = null;
var _appearingAsynchResponders = null;
var _swappingAsynchResponders = null;
var _validatingAsynchResponders = null;
var _preparedValidatingAsynchRespondersStack = null;
var _inlineRedirectionState = null;
//
var _asyncInvalidated = false;
var _asyncValidated = false;
var _asyncValidationOccurred = false;
var _responderIDCount = 0;
var _modify = function(addition, responder, pathsOrStates, behaviorString) {
if (_relayModification(addition, responder, pathsOrStates, behaviorString)) {
return;
}
// Using the path variable as dictionary key to break instance referencing.
var path = navigatorjs.NavigationState.make(pathsOrStates).getPath(),
list, matchingInterface;
// Create, store and retrieve the list that matches the desired behavior.
switch (behaviorString) {
case navigatorjs.NavigationBehaviors.SHOW:
matchingInterface = "IHasStateTransition";
list = _responders.showByPath[path] = _responders.showByPath[path] || [];
break;
case navigatorjs.NavigationBehaviors.HIDE:
matchingInterface = "IHasStateTransition";
list = _responders.hideByPath[path] = _responders.hideByPath[path] || [];
break;
case navigatorjs.NavigationBehaviors.VALIDATE:
matchingInterface = "IHasStateValidation";
list = _responders.validateByPath[path] = _responders.validateByPath[path] || [];
break;
case navigatorjs.NavigationBehaviors.UPDATE:
matchingInterface = "IHasStateUpdate";
list = _responders.updateByPath[path] = _responders.updateByPath[path] || [];
break;
case navigatorjs.NavigationBehaviors.SWAP:
matchingInterface = "IHasStateSwap";
list = _responders.swapByPath[path] = _responders.swapByPath[path] || [];
break;
default:
throw new Error("Unknown behavior: " + behaviorString);
}
//TODO: Build in more strict validation?
if (!navigatorjs.NavigationResponderBehaviors.implementsBehaviorInterface(responder, matchingInterface)) {
throw new Error("Responder " + responder + " should implement " + matchingInterface + " to respond to " + behaviorString);
}
if (addition) {
// add
if (list.indexOf(responder) < 0) {
list.push(responder);
if (responder.__navigatorjs == undefined) {
//Create new hidden navigatorjs data
_responderIDCount++;
responder.__navigatorjs = {id: _responderIDCount};
_respondersByID[responder.__navigatorjs.id] = responder;
}
// If the responder has no status yet, initialize it to UNINITIALIZED:
_statusByResponderID[responder.__navigatorjs.id] = _statusByResponderID[responder.__navigatorjs.id] || navigatorjs.transition.TransitionStatus.UNINITIALIZED;
} else {
return;
}
} else {
// remove
var index = list.indexOf(responder);
if (index >= 0) {
list.splice(index, 1);
delete _statusByResponderID[responder.__navigatorjs.id];
delete _respondersByID[responder.__navigatorjs.id];
} else {
return;
}
if (matchingInterface == "IHasStateSwap" && _responders.swappedBefore[responder]) {
// cleanup after the special swap case
delete _responders.swappedBefore[responder];
}
}
_$eventDispatcher.trigger(navigatorjs.NavigatorEvent.TRANSITION_STATUS_UPDATED, {statusByResponderID: _statusByResponderID, respondersByID: _respondersByID});
};
var _relayModification = function(addition, responder, pathsOrStates, behaviorString) {
if (!responder) {
throw new Error("add: responder is null");
}
var i, length;
if (pathsOrStates instanceof Array) {
length = pathsOrStates.length;
for (i = 0; i < length; i++) {
_modify(addition, responder, pathsOrStates[i], behaviorString);
}
return true;
}
behaviorString = behaviorString || navigatorjs.NavigationBehaviors.AUTO;
if (behaviorString == navigatorjs.NavigationBehaviors.AUTO) {
length = navigatorjs.NavigationBehaviors.ALL_AUTO.length;
for (i = 0; i < length; i++) {
try {
_modify(addition, responder, pathsOrStates, navigatorjs.NavigationBehaviors.ALL_AUTO[i]);
} catch (e) {
// ignore 'should implement xyz' errors
}
}
return true;
}
return false;
};
/**
* Check if there is a responder registered for a given state. Optionally check for implementation of a given
* interface. This allows you to check if there was something mapped to a state which implements
* "IHasStateValidationAsync" for example.
*/
var _hasRegisteredResponder = function(state, optionalInterface) {
var i, length = _responders.all.length,
j, respondersLength, responder,
responders, respondersForPath, path;
for(i=0; i<length; i++) {
responders = _responders.all[i];
for(path in responders) {
if(state.equals(path)) {
if(optionalInterface) {
//Loop through all responders and check if it implements the given interface
respondersForPath = responders[path];
respondersLength = respondersForPath.length;
for(j=0; j<respondersLength; j++) {
responder = respondersForPath[j];
if(navigatorjs.NavigationResponderBehaviors.implementsBehaviorInterface(responder, optionalInterface)) {
return true;
}
}
} else {
return true;
}
return true;
}
}
}
return false;
};
var _request = function(pathOrState) {
if (pathOrState == null) {
// logger.error("Requested a null state. Aborting request.");
return;
}
var requestedState,
path,
fromState,
toState;
// Store and possibly mask the requested state
requestedState = navigatorjs.NavigationState.make(pathOrState);
if (requestedState.hasWildcard()) {
requestedState = requestedState.mask(_currentState || _defaultState);
}
// Check for exact match of the requested and the current state
if (_currentState && _currentState.getPath() == requestedState.getPath()) {
//logger.info("Already at the requested state: " + requested);
return;
}
if (_redirects) {
for (path in _redirects) {
fromState = new navigatorjs.NavigationState(path);
if (fromState.equals(requestedState)) {
toState = navigatorjs.NavigationState.make(_redirects[path]);
//logger.info("Redirecting " + from + " to " + to);
_request(toState);
return;
}
}
}
// this event makes it possible to add responders just in time to participate in the validation process.
_$eventDispatcher.trigger(navigatorjs.NavigatorEvent.STATE_REQUESTED, {state: requestedState});
// Inline redirection is reset with every request call.
// It can be changed by a responder implementing the IHasStateRedirection interface.
_inlineRedirectionState = null;
_performRequestCascade(requestedState);
};
var _performRequestCascade = function(requestedState, startAsyncValidation) {
if (!_defaultState) { throw new Error("No default state set. Call start() before the first request!"); }
// Request cascade starts here.
//
// console.groupEnd();
// console.group('_performRequestCascade', requestedState.getPath(), startAsyncValidation);
if (requestedState.getPath() == _defaultState.getPath() && !_defaultState.hasWildcard()) {
// console.log('exact match');
// Exact match on default state bypasses validation.
_grantRequest(_defaultState);
} else if (_asyncValidationOccurred && (_asyncValidated && !_asyncInvalidated)) {
// console.log('Async operation completed');
// Async operation completed
_grantRequest(requestedState);
} else if (_validate(requestedState, true, startAsyncValidation)) {
// console.log('Any other state needs to be validated.');
// Any other state needs to be validated.
_grantRequest(requestedState);
} else if (_validatingAsynchResponders && _validatingAsynchResponders.isBusy()) {
// console.log('Waiting for async validation.');
// Waiting for async validation.
// FIXME: What do we do in the mean time, dispatch an event or sth?
//logger.notice("waiting for async validation to complete");
} else if (startAsyncValidation && _asyncValidationOccurred) {
// console.log('any async prepration happened instantaneuously');
// any async prepration happened instantaneuously
} else if (_inlineRedirectionState) {
// console.log('_inlineRedirectionState');
_request(_inlineRedirectionState);
} else if (_currentState) {
// console.log('_inlineRedirectionState');
// If validation fails, the notifyStateChange() is called with the current state as a parameter,
// mainly for subclasses to respond to the blocked navigation (e.g. SWFAddress).
_notifyStateChange(_currentState);
} else if (requestedState.hasWildcard()) {
// console.log('wildcard error');
// If we get here, after validateWithWildcards has failed, this means there are still
// wildcards in the requested state that didn't match the previous state. This,
// unfortunately means your application has a logic error. Go fix it!
throw new Error("Check wildcard masking: " + requestedState.getPath());
} else if (_defaultState) {
// console.log('everything failed, use default state');
// If all else fails, we'll put up the default state.
_grantRequest(_defaultState);
} else {
// console.log('everything failed without default state');
// If you don't provide a default state, at least make sure your first request makes sense!
throw new Error("First request is invalid: " + requestedState.getPath());
}
};
var _grantRequest = function(state) {
_asyncInvalidated = false;
_asyncValidated = false;
_previousState = _currentState;
_currentState = state;
_notifyStateChange(_currentState);
_flow.startTransition();
};
var _notifyStateChange = function(state) {
//logger.notice(state);
// Do call the super.notifyStateChange() when overriding.
if (state != _previousState) {
_$eventDispatcher.trigger(navigatorjs.NavigatorEvent.STATE_CHANGED, {statusByResponderID: _statusByResponderID, respondersByID: _respondersByID, state: _currentState});
}
};
// FLOW NAMESPACE START
_flow.startTransition = function() {