This repository has been archived by the owner on May 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 187
/
ionic-angular.js
14399 lines (12737 loc) · 450 KB
/
ionic-angular.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
/*!
* Copyright 2015 Drifty Co.
* http://drifty.com/
*
* Ionic, v1.3.3
* A powerful HTML5 mobile app framework.
* http://ionicframework.com/
*
* By @maxlynch, @benjsperry, @adamdbradley <3
*
* Licensed under the MIT license. Please see LICENSE for more information.
*
*/
(function() {
/* eslint no-unused-vars:0 */
var IonicModule = angular.module('ionic', ['ngAnimate', 'ngSanitize', 'ui.router', 'ngIOS9UIWebViewPatch']),
extend = angular.extend,
forEach = angular.forEach,
isDefined = angular.isDefined,
isNumber = angular.isNumber,
isString = angular.isString,
jqLite = angular.element,
noop = angular.noop;
/**
* @ngdoc service
* @name $ionicActionSheet
* @module ionic
* @description
* The Action Sheet is a slide-up pane that lets the user choose from a set of options.
* Dangerous options are highlighted in red and made obvious.
*
* There are easy ways to cancel out of the action sheet, such as tapping the backdrop or even
* hitting escape on the keyboard for desktop testing.
*
* ![Action Sheet](http://ionicframework.com.s3.amazonaws.com/docs/controllers/actionSheet.gif)
*
* @usage
* To trigger an Action Sheet in your code, use the $ionicActionSheet service in your angular controllers:
*
* ```js
* angular.module('mySuperApp', ['ionic'])
* .controller(function($scope, $ionicActionSheet, $timeout) {
*
* // Triggered on a button click, or some other target
* $scope.show = function() {
*
* // Show the action sheet
* var hideSheet = $ionicActionSheet.show({
* buttons: [
* { text: '<b>Share</b> This' },
* { text: 'Move' }
* ],
* destructiveText: 'Delete',
* titleText: 'Modify your album',
* cancelText: 'Cancel',
* cancel: function() {
// add cancel code..
},
* buttonClicked: function(index) {
* return true;
* }
* });
*
* // For example's sake, hide the sheet after two seconds
* $timeout(function() {
* hideSheet();
* }, 2000);
*
* };
* });
* ```
*
*/
IonicModule
.factory('$ionicActionSheet', [
'$rootScope',
'$compile',
'$animate',
'$timeout',
'$ionicTemplateLoader',
'$ionicPlatform',
'$ionicBody',
'IONIC_BACK_PRIORITY',
function($rootScope, $compile, $animate, $timeout, $ionicTemplateLoader, $ionicPlatform, $ionicBody, IONIC_BACK_PRIORITY) {
return {
show: actionSheet
};
/**
* @ngdoc method
* @name $ionicActionSheet#show
* @description
* Load and return a new action sheet.
*
* A new isolated scope will be created for the
* action sheet and the new element will be appended into the body.
*
* @param {object} options The options for this ActionSheet. Properties:
*
* - `[Object]` `buttons` Which buttons to show. Each button is an object with a `text` field.
* - `{string}` `titleText` The title to show on the action sheet.
* - `{string=}` `cancelText` the text for a 'cancel' button on the action sheet.
* - `{string=}` `destructiveText` The text for a 'danger' on the action sheet.
* - `{function=}` `cancel` Called if the cancel button is pressed, the backdrop is tapped or
* the hardware back button is pressed.
* - `{function=}` `buttonClicked` Called when one of the non-destructive buttons is clicked,
* with the index of the button that was clicked and the button object. Return true to close
* the action sheet, or false to keep it opened.
* - `{function=}` `destructiveButtonClicked` Called when the destructive button is clicked.
* Return true to close the action sheet, or false to keep it opened.
* - `{boolean=}` `cancelOnStateChange` Whether to cancel the actionSheet when navigating
* to a new state. Default true.
* - `{string}` `cssClass` The custom CSS class name.
*
* @returns {function} `hideSheet` A function which, when called, hides & cancels the action sheet.
*/
function actionSheet(opts) {
var scope = $rootScope.$new(true);
extend(scope, {
cancel: noop,
destructiveButtonClicked: noop,
buttonClicked: noop,
$deregisterBackButton: noop,
buttons: [],
cancelOnStateChange: true
}, opts || {});
function textForIcon(text) {
if (text && /icon/.test(text)) {
scope.$actionSheetHasIcon = true;
}
}
for (var x = 0; x < scope.buttons.length; x++) {
textForIcon(scope.buttons[x].text);
}
textForIcon(scope.cancelText);
textForIcon(scope.destructiveText);
// Compile the template
var element = scope.element = $compile('<ion-action-sheet ng-class="cssClass" buttons="buttons"></ion-action-sheet>')(scope);
// Grab the sheet element for animation
var sheetEl = jqLite(element[0].querySelector('.action-sheet-wrapper'));
var stateChangeListenDone = scope.cancelOnStateChange ?
$rootScope.$on('$stateChangeSuccess', function() { scope.cancel(); }) :
noop;
// removes the actionSheet from the screen
scope.removeSheet = function(done) {
if (scope.removed) return;
scope.removed = true;
sheetEl.removeClass('action-sheet-up');
$timeout(function() {
// wait to remove this due to a 300ms delay native
// click which would trigging whatever was underneath this
$ionicBody.removeClass('action-sheet-open');
}, 400);
scope.$deregisterBackButton();
stateChangeListenDone();
$animate.removeClass(element, 'active').then(function() {
scope.$destroy();
element.remove();
// scope.cancel.$scope is defined near the bottom
scope.cancel.$scope = sheetEl = null;
(done || noop)(opts.buttons);
});
};
scope.showSheet = function(done) {
if (scope.removed) return;
$ionicBody.append(element)
.addClass('action-sheet-open');
$animate.addClass(element, 'active').then(function() {
if (scope.removed) return;
(done || noop)();
});
$timeout(function() {
if (scope.removed) return;
sheetEl.addClass('action-sheet-up');
}, 20, false);
};
// registerBackButtonAction returns a callback to deregister the action
scope.$deregisterBackButton = $ionicPlatform.registerBackButtonAction(
function() {
$timeout(scope.cancel);
},
IONIC_BACK_PRIORITY.actionSheet
);
// called when the user presses the cancel button
scope.cancel = function() {
// after the animation is out, call the cancel callback
scope.removeSheet(opts.cancel);
};
scope.buttonClicked = function(index) {
// Check if the button click event returned true, which means
// we can close the action sheet
if (opts.buttonClicked(index, opts.buttons[index]) === true) {
scope.removeSheet();
}
};
scope.destructiveButtonClicked = function() {
// Check if the destructive button click event returned true, which means
// we can close the action sheet
if (opts.destructiveButtonClicked() === true) {
scope.removeSheet();
}
};
scope.showSheet();
// Expose the scope on $ionicActionSheet's return value for the sake
// of testing it.
scope.cancel.$scope = scope;
return scope.cancel;
}
}]);
jqLite.prototype.addClass = function(cssClasses) {
var x, y, cssClass, el, splitClasses, existingClasses;
if (cssClasses && cssClasses != 'ng-scope' && cssClasses != 'ng-isolate-scope') {
for (x = 0; x < this.length; x++) {
el = this[x];
if (el.setAttribute) {
if (cssClasses.indexOf(' ') < 0 && el.classList.add) {
el.classList.add(cssClasses);
} else {
existingClasses = (' ' + (el.getAttribute('class') || '') + ' ')
.replace(/[\n\t]/g, " ");
splitClasses = cssClasses.split(' ');
for (y = 0; y < splitClasses.length; y++) {
cssClass = splitClasses[y].trim();
if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
existingClasses += cssClass + ' ';
}
}
el.setAttribute('class', existingClasses.trim());
}
}
}
}
return this;
};
jqLite.prototype.removeClass = function(cssClasses) {
var x, y, splitClasses, cssClass, el;
if (cssClasses) {
for (x = 0; x < this.length; x++) {
el = this[x];
if (el.getAttribute) {
if (cssClasses.indexOf(' ') < 0 && el.classList.remove) {
el.classList.remove(cssClasses);
} else {
splitClasses = cssClasses.split(' ');
for (y = 0; y < splitClasses.length; y++) {
cssClass = splitClasses[y];
el.setAttribute('class', (
(" " + (el.getAttribute('class') || '') + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + cssClass.trim() + " ", " ")).trim()
);
}
}
}
}
}
return this;
};
/**
* @ngdoc service
* @name $ionicBackdrop
* @module ionic
* @description
* Shows and hides a backdrop over the UI. Appears behind popups, loading,
* and other overlays.
*
* Often, multiple UI components require a backdrop, but only one backdrop is
* ever needed in the DOM at a time.
*
* Therefore, each component that requires the backdrop to be shown calls
* `$ionicBackdrop.retain()` when it wants the backdrop, then `$ionicBackdrop.release()`
* when it is done with the backdrop.
*
* For each time `retain` is called, the backdrop will be shown until `release` is called.
*
* For example, if `retain` is called three times, the backdrop will be shown until `release`
* is called three times.
*
* **Notes:**
* - The backdrop service will broadcast 'backdrop.shown' and 'backdrop.hidden' events from the root scope,
* this is useful for alerting native components not in html.
*
* @usage
*
* ```js
* function MyController($scope, $ionicBackdrop, $timeout, $rootScope) {
* //Show a backdrop for one second
* $scope.action = function() {
* $ionicBackdrop.retain();
* $timeout(function() {
* $ionicBackdrop.release();
* }, 1000);
* };
*
* // Execute action on backdrop disappearing
* $scope.$on('backdrop.hidden', function() {
* // Execute action
* });
*
* // Execute action on backdrop appearing
* $scope.$on('backdrop.shown', function() {
* // Execute action
* });
*
* }
* ```
*/
IonicModule
.factory('$ionicBackdrop', [
'$document', '$timeout', '$$rAF', '$rootScope',
function($document, $timeout, $$rAF, $rootScope) {
var el = jqLite('<div class="backdrop">');
var backdropHolds = 0;
$document[0].body.appendChild(el[0]);
return {
/**
* @ngdoc method
* @name $ionicBackdrop#retain
* @description Retains the backdrop.
*/
retain: retain,
/**
* @ngdoc method
* @name $ionicBackdrop#release
* @description
* Releases the backdrop.
*/
release: release,
getElement: getElement,
// exposed for testing
_element: el
};
function retain() {
backdropHolds++;
if (backdropHolds === 1) {
el.addClass('visible');
$rootScope.$broadcast('backdrop.shown');
$$rAF(function() {
// If we're still at >0 backdropHolds after async...
if (backdropHolds >= 1) el.addClass('active');
});
}
}
function release() {
if (backdropHolds === 1) {
el.removeClass('active');
$rootScope.$broadcast('backdrop.hidden');
$timeout(function() {
// If we're still at 0 backdropHolds after async...
if (backdropHolds === 0) el.removeClass('visible');
}, 400, false);
}
backdropHolds = Math.max(0, backdropHolds - 1);
}
function getElement() {
return el;
}
}]);
/**
* @private
*/
IonicModule
.factory('$ionicBind', ['$parse', '$interpolate', function($parse, $interpolate) {
var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
return function(scope, attrs, bindDefinition) {
forEach(bindDefinition || {}, function(definition, scopeName) {
//Adapted from angular.js $compile
var match = definition.match(LOCAL_REGEXP) || [],
attrName = match[3] || scopeName,
mode = match[1], // @, =, or &
parentGet,
unwatch;
switch (mode) {
case '@':
if (!attrs[attrName]) {
return;
}
attrs.$observe(attrName, function(value) {
scope[scopeName] = value;
});
// we trigger an interpolation to ensure
// the value is there for use immediately
if (attrs[attrName]) {
scope[scopeName] = $interpolate(attrs[attrName])(scope);
}
break;
case '=':
if (!attrs[attrName]) {
return;
}
unwatch = scope.$watch(attrs[attrName], function(value) {
scope[scopeName] = value;
});
//Destroy parent scope watcher when this scope is destroyed
scope.$on('$destroy', unwatch);
break;
case '&':
/* jshint -W044 */
if (attrs[attrName] && attrs[attrName].match(RegExp(scopeName + '\(.*?\)'))) {
throw new Error('& expression binding "' + scopeName + '" looks like it will recursively call "' +
attrs[attrName] + '" and cause a stack overflow! Please choose a different scopeName.');
}
parentGet = $parse(attrs[attrName]);
scope[scopeName] = function(locals) {
return parentGet(scope, locals);
};
break;
}
});
};
}]);
/**
* @ngdoc service
* @name $ionicBody
* @module ionic
* @description An angular utility service to easily and efficiently
* add and remove CSS classes from the document's body element.
*/
IonicModule
.factory('$ionicBody', ['$document', function($document) {
return {
/**
* @ngdoc method
* @name $ionicBody#addClass
* @description Add a class to the document's body element.
* @param {string} class Each argument will be added to the body element.
* @returns {$ionicBody} The $ionicBody service so methods can be chained.
*/
addClass: function() {
for (var x = 0; x < arguments.length; x++) {
$document[0].body.classList.add(arguments[x]);
}
return this;
},
/**
* @ngdoc method
* @name $ionicBody#removeClass
* @description Remove a class from the document's body element.
* @param {string} class Each argument will be removed from the body element.
* @returns {$ionicBody} The $ionicBody service so methods can be chained.
*/
removeClass: function() {
for (var x = 0; x < arguments.length; x++) {
$document[0].body.classList.remove(arguments[x]);
}
return this;
},
/**
* @ngdoc method
* @name $ionicBody#enableClass
* @description Similar to the `add` method, except the first parameter accepts a boolean
* value determining if the class should be added or removed. Rather than writing user code,
* such as "if true then add the class, else then remove the class", this method can be
* given a true or false value which reduces redundant code.
* @param {boolean} shouldEnableClass A true/false value if the class should be added or removed.
* @param {string} class Each remaining argument would be added or removed depending on
* the first argument.
* @returns {$ionicBody} The $ionicBody service so methods can be chained.
*/
enableClass: function(shouldEnableClass) {
var args = Array.prototype.slice.call(arguments).slice(1);
if (shouldEnableClass) {
this.addClass.apply(this, args);
} else {
this.removeClass.apply(this, args);
}
return this;
},
/**
* @ngdoc method
* @name $ionicBody#append
* @description Append a child to the document's body.
* @param {element} element The element to be appended to the body. The passed in element
* can be either a jqLite element, or a DOM element.
* @returns {$ionicBody} The $ionicBody service so methods can be chained.
*/
append: function(ele) {
$document[0].body.appendChild(ele.length ? ele[0] : ele);
return this;
},
/**
* @ngdoc method
* @name $ionicBody#get
* @description Get the document's body element.
* @returns {element} Returns the document's body element.
*/
get: function() {
return $document[0].body;
}
};
}]);
IonicModule
.factory('$ionicClickBlock', [
'$document',
'$ionicBody',
'$timeout',
function($document, $ionicBody, $timeout) {
var CSS_HIDE = 'click-block-hide';
var cbEle, fallbackTimer, pendingShow;
function preventClick(ev) {
ev.preventDefault();
ev.stopPropagation();
}
function addClickBlock() {
if (pendingShow) {
if (cbEle) {
cbEle.classList.remove(CSS_HIDE);
} else {
cbEle = $document[0].createElement('div');
cbEle.className = 'click-block';
$ionicBody.append(cbEle);
cbEle.addEventListener('touchstart', preventClick);
cbEle.addEventListener('mousedown', preventClick);
}
pendingShow = false;
}
}
function removeClickBlock() {
cbEle && cbEle.classList.add(CSS_HIDE);
}
return {
show: function(autoExpire) {
pendingShow = true;
$timeout.cancel(fallbackTimer);
fallbackTimer = $timeout(this.hide, autoExpire || 310, false);
addClickBlock();
},
hide: function() {
pendingShow = false;
$timeout.cancel(fallbackTimer);
removeClickBlock();
}
};
}]);
/**
* @ngdoc service
* @name $ionicGesture
* @module ionic
* @description An angular service exposing ionic
* {@link ionic.utility:ionic.EventController}'s gestures.
*/
IonicModule
.factory('$ionicGesture', [function() {
return {
/**
* @ngdoc method
* @name $ionicGesture#on
* @description Add an event listener for a gesture on an element. See {@link ionic.utility:ionic.EventController#onGesture}.
* @param {string} eventType The gesture event to listen for.
* @param {function(e)} callback The function to call when the gesture
* happens.
* @param {element} $element The angular element to listen for the event on.
* @param {object} options object.
* @returns {ionic.Gesture} The gesture object (use this to remove the gesture later on).
*/
on: function(eventType, cb, $element, options) {
return window.ionic.onGesture(eventType, cb, $element[0], options);
},
/**
* @ngdoc method
* @name $ionicGesture#off
* @description Remove an event listener for a gesture on an element. See {@link ionic.utility:ionic.EventController#offGesture}.
* @param {ionic.Gesture} gesture The gesture that should be removed.
* @param {string} eventType The gesture event to remove the listener for.
* @param {function(e)} callback The listener to remove.
*/
off: function(gesture, eventType, cb) {
return window.ionic.offGesture(gesture, eventType, cb);
}
};
}]);
/**
* @ngdoc service
* @name $ionicHistory
* @module ionic
* @description
* $ionicHistory keeps track of views as the user navigates through an app. Similar to the way a
* browser behaves, an Ionic app is able to keep track of the previous view, the current view, and
* the forward view (if there is one). However, a typical web browser only keeps track of one
* history stack in a linear fashion.
*
* Unlike a traditional browser environment, apps and webapps have parallel independent histories,
* such as with tabs. Should a user navigate few pages deep on one tab, and then switch to a new
* tab and back, the back button relates not to the previous tab, but to the previous pages
* visited within _that_ tab.
*
* `$ionicHistory` facilitates this parallel history architecture.
*/
IonicModule
.factory('$ionicHistory', [
'$rootScope',
'$state',
'$location',
'$window',
'$timeout',
'$ionicViewSwitcher',
'$ionicNavViewDelegate',
function($rootScope, $state, $location, $window, $timeout, $ionicViewSwitcher, $ionicNavViewDelegate) {
// history actions while navigating views
var ACTION_INITIAL_VIEW = 'initialView';
var ACTION_NEW_VIEW = 'newView';
var ACTION_MOVE_BACK = 'moveBack';
var ACTION_MOVE_FORWARD = 'moveForward';
// direction of navigation
var DIRECTION_BACK = 'back';
var DIRECTION_FORWARD = 'forward';
var DIRECTION_ENTER = 'enter';
var DIRECTION_EXIT = 'exit';
var DIRECTION_SWAP = 'swap';
var DIRECTION_NONE = 'none';
var stateChangeCounter = 0;
var lastStateId, nextViewOptions, deregisterStateChangeListener, nextViewExpireTimer, forcedNav;
var viewHistory = {
histories: { root: { historyId: 'root', parentHistoryId: null, stack: [], cursor: -1 } },
views: {},
backView: null,
forwardView: null,
currentView: null
};
var View = function() {};
View.prototype.initialize = function(data) {
if (data) {
for (var name in data) this[name] = data[name];
return this;
}
return null;
};
View.prototype.go = function() {
if (this.stateName) {
return $state.go(this.stateName, this.stateParams);
}
if (this.url && this.url !== $location.url()) {
if (viewHistory.backView === this) {
return $window.history.go(-1);
} else if (viewHistory.forwardView === this) {
return $window.history.go(1);
}
$location.url(this.url);
}
return null;
};
View.prototype.destroy = function() {
if (this.scope) {
this.scope.$destroy && this.scope.$destroy();
this.scope = null;
}
};
function getViewById(viewId) {
return (viewId ? viewHistory.views[ viewId ] : null);
}
function getBackView(view) {
return (view ? getViewById(view.backViewId) : null);
}
function getForwardView(view) {
return (view ? getViewById(view.forwardViewId) : null);
}
function getHistoryById(historyId) {
return (historyId ? viewHistory.histories[ historyId ] : null);
}
function getHistory(scope) {
var histObj = getParentHistoryObj(scope);
if (!viewHistory.histories[ histObj.historyId ]) {
// this history object exists in parent scope, but doesn't
// exist in the history data yet
viewHistory.histories[ histObj.historyId ] = {
historyId: histObj.historyId,
parentHistoryId: getParentHistoryObj(histObj.scope.$parent).historyId,
stack: [],
cursor: -1
};
}
return getHistoryById(histObj.historyId);
}
function getParentHistoryObj(scope) {
var parentScope = scope;
while (parentScope) {
if (parentScope.hasOwnProperty('$historyId')) {
// this parent scope has a historyId
return { historyId: parentScope.$historyId, scope: parentScope };
}
// nothing found keep climbing up
parentScope = parentScope.$parent;
}
// no history for the parent, use the root
return { historyId: 'root', scope: $rootScope };
}
function setNavViews(viewId) {
viewHistory.currentView = getViewById(viewId);
viewHistory.backView = getBackView(viewHistory.currentView);
viewHistory.forwardView = getForwardView(viewHistory.currentView);
}
function getCurrentStateId() {
var id;
if ($state && $state.current && $state.current.name) {
id = $state.current.name;
if ($state.params) {
for (var key in $state.params) {
if ($state.params.hasOwnProperty(key) && $state.params[key]) {
id += "_" + key + "=" + $state.params[key];
}
}
}
return id;
}
// if something goes wrong make sure its got a unique stateId
return ionic.Utils.nextUid();
}
function getCurrentStateParams() {
var rtn;
if ($state && $state.params) {
for (var key in $state.params) {
if ($state.params.hasOwnProperty(key)) {
rtn = rtn || {};
rtn[key] = $state.params[key];
}
}
}
return rtn;
}
return {
register: function(parentScope, viewLocals) {
var currentStateId = getCurrentStateId(),
hist = getHistory(parentScope),
currentView = viewHistory.currentView,
backView = viewHistory.backView,
forwardView = viewHistory.forwardView,
viewId = null,
action = null,
direction = DIRECTION_NONE,
historyId = hist.historyId,
url = $location.url(),
tmp, x, ele;
if (lastStateId !== currentStateId) {
lastStateId = currentStateId;
stateChangeCounter++;
}
if (forcedNav) {
// we've previously set exactly what to do
viewId = forcedNav.viewId;
action = forcedNav.action;
direction = forcedNav.direction;
forcedNav = null;
} else if (backView && backView.stateId === currentStateId) {
// they went back one, set the old current view as a forward view
viewId = backView.viewId;
historyId = backView.historyId;
action = ACTION_MOVE_BACK;
if (backView.historyId === currentView.historyId) {
// went back in the same history
direction = DIRECTION_BACK;
} else if (currentView) {
direction = DIRECTION_EXIT;
tmp = getHistoryById(backView.historyId);
if (tmp && tmp.parentHistoryId === currentView.historyId) {
direction = DIRECTION_ENTER;
} else {
tmp = getHistoryById(currentView.historyId);
if (tmp && tmp.parentHistoryId === hist.parentHistoryId) {
direction = DIRECTION_SWAP;
}
}
}
} else if (forwardView && forwardView.stateId === currentStateId) {
// they went to the forward one, set the forward view to no longer a forward view
viewId = forwardView.viewId;
historyId = forwardView.historyId;
action = ACTION_MOVE_FORWARD;
if (forwardView.historyId === currentView.historyId) {
direction = DIRECTION_FORWARD;
} else if (currentView) {
direction = DIRECTION_EXIT;
if (currentView.historyId === hist.parentHistoryId) {
direction = DIRECTION_ENTER;
} else {
tmp = getHistoryById(currentView.historyId);
if (tmp && tmp.parentHistoryId === hist.parentHistoryId) {
direction = DIRECTION_SWAP;
}
}
}
tmp = getParentHistoryObj(parentScope);
if (forwardView.historyId && tmp.scope) {
// if a history has already been created by the forward view then make sure it stays the same
tmp.scope.$historyId = forwardView.historyId;
historyId = forwardView.historyId;
}
} else if (currentView && currentView.historyId !== historyId &&
hist.cursor > -1 && hist.stack.length > 0 && hist.cursor < hist.stack.length &&
hist.stack[hist.cursor].stateId === currentStateId) {
// they just changed to a different history and the history already has views in it
var switchToView = hist.stack[hist.cursor];
viewId = switchToView.viewId;
historyId = switchToView.historyId;
action = ACTION_MOVE_BACK;
direction = DIRECTION_SWAP;
tmp = getHistoryById(currentView.historyId);
if (tmp && tmp.parentHistoryId === historyId) {
direction = DIRECTION_EXIT;
} else {
tmp = getHistoryById(historyId);
if (tmp && tmp.parentHistoryId === currentView.historyId) {
direction = DIRECTION_ENTER;
}
}
// if switching to a different history, and the history of the view we're switching
// to has an existing back view from a different history than itself, then
// it's back view would be better represented using the current view as its back view
tmp = getViewById(switchToView.backViewId);
if (tmp && switchToView.historyId !== tmp.historyId) {
// the new view is being removed from it's old position in the history and being placed at the top,
// so we need to update any views that reference it as a backview, otherwise there will be infinitely loops
var viewIds = Object.keys(viewHistory.views);
viewIds.forEach(function(viewId) {
var view = viewHistory.views[viewId];
if ((view.backViewId === switchToView.viewId) && (view.historyId !== switchToView.historyId)) {
view.backViewId = null;
}
});
hist.stack[hist.cursor].backViewId = currentView.viewId;
}
} else {
// create an element from the viewLocals template
ele = $ionicViewSwitcher.createViewEle(viewLocals);
if (this.isAbstractEle(ele, viewLocals)) {
return {
action: 'abstractView',
direction: DIRECTION_NONE,
ele: ele
};
}
// set a new unique viewId
viewId = ionic.Utils.nextUid();
if (currentView) {
// set the forward view if there is a current view (ie: if its not the first view)
currentView.forwardViewId = viewId;
action = ACTION_NEW_VIEW;
// check if there is a new forward view within the same history
if (forwardView && currentView.stateId !== forwardView.stateId &&
currentView.historyId === forwardView.historyId) {
// they navigated to a new view but the stack already has a forward view
// since its a new view remove any forwards that existed
tmp = getHistoryById(forwardView.historyId);
if (tmp) {
// the forward has a history
for (x = tmp.stack.length - 1; x >= forwardView.index; x--) {
// starting from the end destroy all forwards in this history from this point
var stackItem = tmp.stack[x];
stackItem && stackItem.destroy && stackItem.destroy();
tmp.stack.splice(x);
}
historyId = forwardView.historyId;
}
}
// its only moving forward if its in the same history
if (hist.historyId === currentView.historyId) {
direction = DIRECTION_FORWARD;
} else if (currentView.historyId !== hist.historyId) {
// DB: this is a new view in a different tab
direction = DIRECTION_ENTER;
tmp = getHistoryById(currentView.historyId);
if (tmp && tmp.parentHistoryId === hist.parentHistoryId) {
direction = DIRECTION_SWAP;
} else {
tmp = getHistoryById(tmp.parentHistoryId);
if (tmp && tmp.historyId === hist.historyId) {
direction = DIRECTION_EXIT;
}
}
}
} else {
// there's no current view, so this must be the initial view
action = ACTION_INITIAL_VIEW;
}
if (stateChangeCounter < 2) {
// views that were spun up on the first load should not animate
direction = DIRECTION_NONE;
}
// add the new view
viewHistory.views[viewId] = this.createView({
viewId: viewId,
index: hist.stack.length,
historyId: hist.historyId,
backViewId: (currentView && currentView.viewId ? currentView.viewId : null),
forwardViewId: null,
stateId: currentStateId,
stateName: this.currentStateName(),
stateParams: getCurrentStateParams(),
url: url,
canSwipeBack: canSwipeBack(ele, viewLocals)
});
// add the new view to this history's stack
hist.stack.push(viewHistory.views[viewId]);
}
deregisterStateChangeListener && deregisterStateChangeListener();