Repository navigation
Expand file tree
/
Copy pathmail_common.js
More file actions
1436 lines (1279 loc) · 44.9 KB
/
Copy pathmail_common.js
File metadata and controls
1436 lines (1279 loc) · 44.9 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
/**
* UI infrastructure code and utility code for the gaia email app.
**/
/*jshint browser: true */
/*global define, console, hookupInputAreaResetButtons */
define(function(require, exports) {
var Cards, Toaster,
mozL10n = require('l10n!'),
toasterNode = require('tmpl!./cards/toaster.html'),
confirmDialogTemplateNode = require('tmpl!./cards/confirm_dialog.html'),
ValueSelector = require('value_selector');
var hookupInputAreaResetButtons = require('input_areas');
function addClass(domNode, name) {
if (domNode) {
domNode.classList.add(name);
}
}
function removeClass(domNode, name) {
if (domNode) {
domNode.classList.remove(name);
}
}
function batchAddClass(domNode, searchClass, classToAdd) {
var nodes = domNode.getElementsByClassName(searchClass);
for (var i = 0; i < nodes.length; i++) {
nodes[i].classList.add(classToAdd);
}
}
function batchRemoveClass(domNode, searchClass, classToRemove) {
var nodes = domNode.getElementsByClassName(searchClass);
for (var i = 0; i < nodes.length; i++) {
nodes[i].classList.remove(classToRemove);
}
}
var MATCHED_TEXT_CLASS = 'highlight';
function appendMatchItemTo(matchItem, node) {
var text = matchItem.text;
var idx = 0;
for (var iRun = 0; iRun <= matchItem.matchRuns.length; iRun++) {
var run;
if (iRun === matchItem.matchRuns.length)
run = { start: text.length, length: 0 };
else
run = matchItem.matchRuns[iRun];
// generate the un-highlighted span
if (run.start > idx) {
var tnode = document.createTextNode(text.substring(idx, run.start));
node.appendChild(tnode);
}
if (!run.length)
continue;
var hspan = document.createElement('span');
hspan.classList.add(MATCHED_TEXT_CLASS);
hspan.textContent = text.substr(run.start, run.length);
node.appendChild(hspan);
idx = run.start + run.length;
}
}
/**
* Add an event listener on a container that, when an event is encounted on
* a descendant, walks up the tree to find the immediate child of the container
* and tells us what the click was on.
*/
function bindContainerHandler(containerNode, eventName, func) {
containerNode.addEventListener(eventName, function(event) {
var node = event.target;
// bail if they clicked on the container and not a child...
if (node === containerNode)
return;
while (node && node.parentNode !== containerNode) {
node = node.parentNode;
}
func(node, event);
}, false);
}
/**
* Bind both 'click' and 'contextmenu' (synthetically created by b2g), plus
* handling click suppression that is currently required because we still
* see the click event. We also suppress contextmenu's default event so that
* we don't trigger the browser's right-click menu when operating in firefox.
*/
function bindContainerClickAndHold(containerNode, clickFunc, holdFunc) {
// Rather than tracking suppressClick ourselves in here, we maintain the
// state globally in Cards. The rationale is that popup menus will be
// triggered on contextmenu, which transfers responsibility of the click
// event to the popup handling logic. There is also no chance for multiple
// contextmenu events overlapping (that we would consider reasonable).
bindContainerHandler(
containerNode, 'click',
function(node, event) {
if (Cards._suppressClick) {
Cards._suppressClick = false;
return;
}
clickFunc(node, event);
});
bindContainerHandler(
containerNode, 'contextmenu',
function(node, event) {
// Always preventDefault, as this terminates processing of the click as a
// drag event.
event.preventDefault();
// suppress the subsequent click if this was actually a left click
if (event.button === 0) {
Cards._suppressClick = true;
}
return holdFunc(node, event);
});
}
/**
* Fairly simple card abstraction with support for simple horizontal animated
* transitions. We are cribbing from deuxdrop's mobile UI's cards.js
* implementation created jrburke.
*/
Cards = {
/* @dictof[
* @key[name String]
* @value[@dict[
* @key[name String]{
* The name of the card, which should also be the name of the css class
* used for the card when 'card-' is prepended.
* }
* @key[modes @dictof[
* @key[modeName String]
* @value[modeDef @dict[
* @key[tray Boolean]{
* Should this card be displayed as a tray that leaves the edge of
* the adjacent card visible? (The width of the edge being a
* value consistent across all cards.)
* }
* ]
* ]]
* @key[constructor Function]{
* The constructor to use to create an instance of the card.
* }
* ]]
* ]
*/
_cardDefs: {},
/* @listof[@typedef[CardInstance @dict[
* @key[domNode]{
* }
* @key[cardDef]
* @key[modeDef]
* @key[left Number]{
* Left offset of the card in #cards.
* }
* @key[cardImpl]{
* The result of calling the card's constructor.
* }
* ]]]{
* Existing cards, left-to-right, new cards getting pushed onto the right.
* }
*/
_cardStack: [],
activeCardIndex: -1,
/*
* @oneof[null @listof[cardName modeName]]{
* If a lazy load is causing us to have to wait before we push a card, this
* is the type of card we are planning to push. This is used by hasCard
* to avoid returning misleading answers while an async push is happening.
* }
*/
_pendingPush: null,
/**
* Cards can stack on top of each other, make sure the stacked set is
* visible over the lower sets.
*/
_zIndex: 0,
/**
* The DOM node that contains the _containerNode ("#cardContainer") and which
* we inject popup and masking layers into. The choice of doing the popup
* stuff at this layer is arbitrary.
*/
_rootNode: null,
/**
* The "#cardContainer" node which serves as the scroll container for the
* contained _cardsNode ("#cards"). It is as wide as the viewport.
*/
_containerNode: null,
/**
* The "#cards" node that holds the cards; it is as wide as all of the cards
* it contains and has its left offset changed in order to change what card
* is visible.
*/
_cardsNode: null,
/**
* The DOM nodes that should be removed from their parent when our current
* transition ends.
*/
_animatingDeadDomNodes: [],
/**
* Tracks the number of transition events per card animation. Since each
* animation ends up with two transitionend events since two cards are
* moving, need to wait for the last one to be finished before doing
* cleanup, like DOM removal.
*/
_transitionCount: 0,
/**
* Annoying logic related to contextmenu event handling; search for the uses
* for more info.
*/
_suppressClick: false,
/**
* Is a tray card visible, suggesting that we need to intercept clicks in the
* tray region so that we can transition back to the thing visible because of
* the tray and avoid the click triggering that card's logic.
*/
_trayActive: false,
/**
* Is a popup visible, suggesting that any click that is not on the popup
* should be taken as a desire to close the popup? This is not a boolean,
* but rather info on the active popup.
*/
_popupActive: null,
/**
* Are we eating all click events we see until we transition to the next
* card (possibly due to a call to pushCard that has not yet occurred?).
* Set by calling `eatEventsUntilNextCard`.
*/
_eatingEventsUntilNextCard: false,
/**
* Initialize and bind ourselves to the DOM which should now be fully loaded.
*/
_init: function() {
this._rootNode = document.body;
this._containerNode = document.getElementById('cardContainer');
this._cardsNode = document.getElementById('cards');
this._containerNode.appendChild(toasterNode);
this._containerNode.addEventListener('click',
this._onMaybeIntercept.bind(this),
true);
this._containerNode.addEventListener('contextmenu',
this._onMaybeIntercept.bind(this),
true);
// XXX be more platform detecty. or just add more events. unless the
// prefixes are already gone with webkit and opera?
this._cardsNode.addEventListener('transitionend',
this._onTransitionEnd.bind(this),
false);
},
/**
* If the tray is active and a click happens in the tray area, transition
* back to the visible thing (which must be to our right currently.)
*/
_onMaybeIntercept: function(event) {
// Contextmenu-derived click suppression wants to gobble an explicitly
// expected event, and so takes priority over other types of suppression.
if (event.type === 'click' && this._suppressClick) {
this._suppressClick = false;
event.stopPropagation();
return;
}
if (this._eatingEventsUntilNextCard) {
event.stopPropagation();
return;
}
if (this._popupActive) {
event.stopPropagation();
this._popupActive.close();
return;
}
// Find the card containing the event target.
var cardNode = event.target;
for (cardNode = event.target; cardNode; cardNode = cardNode.parentNode) {
if (cardNode.classList.contains('card'))
break;
}
// If tray is active and the click is in the card that is after
// current card (in the gutter), then just transition back to
// that card.
if (this._trayActive && cardNode && cardNode.classList.contains('after')) {
event.stopPropagation();
// Look for a card with a data-tray-target attribute
var targetIndex = -1;
this._cardStack.some(function(card, i) {
if (card.domNode.hasAttribute('data-tray-target')) {
targetIndex = i;
return true;
}
});
// Choose a default of one card ahead
if (targetIndex === -1)
targetIndex = this.activeCardIndex + 1;
var indexDiff = targetIndex - (this.activeCardIndex + 1);
if (indexDiff > 0) {
this._afterTransitionAction = (function() {
this.removeCardAndSuccessors(this._cardStack[0].domNode,
'none', indexDiff);
this.moveToCard(targetIndex, 'animate', 'forward');
}.bind(this));
}
this.moveToCard(this.activeCardIndex + 1, 'animate', 'forward');
}
},
/**
* Called whenever the default card for the app should be inserted.
* Override this method in the app. The app should call Card.pushCard
* with the card of its choosing, and call the onPushed function passed
* in to pushDefaultCard once the default card has been pushed. The
* default card should be pushed with showMethod of 'none' so that
* whatever the onPushed function does will work well with card nav.
* @param {Function} onPushed pass as the onPushed arg to pushCard.
*/
pushDefaultCard: function(onPushed) {},
defineCard: function(cardDef) {
if (!cardDef.name)
throw new Error('The card type needs a name');
if (this._cardDefs.hasOwnProperty(cardDef.name))
throw new Error('Duplicate card name: ' + cardDef.name);
this._cardDefs[cardDef.name] = cardDef;
// normalize the modes
for (var modeName in cardDef.modes) {
var mode = cardDef.modes[modeName];
if (!mode.hasOwnProperty('tray'))
mode.tray = false;
mode.name = modeName;
}
},
defineCardWithDefaultMode: function(name, defaultMode, constructor,
templateNode) {
var cardDef = {
name: name,
modes: {},
constructor: constructor,
templateNode: templateNode
};
cardDef.modes['default'] = defaultMode;
this.defineCard(cardDef);
},
/**
* Push a card onto the card-stack.
*/
/* @args[
* @param[type]
* @param[mode String]{
* }
* @param[showMethod @oneof[
* @case['animate']{
* Perform an animated scrolling transition.
* }
* @case['immediate']{
* Immediately warp to the card without animation.
* }
* @case['none']{
* Don't touch the view at all.
* }
* ]]
* @param[args Object]{
* An arguments object to provide to the card's constructor when
* instantiating.
* }
* @param[placement #:optional @oneof[
* @case[undefined]{
* The card gets pushed onto the end of the stack.
* }
* @case['left']{
* The card gets inserted to the left of the current card.
* }
* @case['right']{
* The card gets inserted to the right of the current card.
* }
* }
* ]
*/
pushCard: function(type, mode, showMethod, args, placement) {
var cardDef = this._cardDefs[type];
var typePrefix = type.split('-')[0];
args = args || {};
if (!cardDef) {
var cbArgs = Array.slice(arguments);
this._pendingPush = [type, mode];
// Only eat clicks if the card will be visibly displayed.
if (showMethod !== 'none')
this.eatEventsUntilNextCard();
require(['cards/' + type], function() {
this.pushCard.apply(this, cbArgs);
}.bind(this));
return;
}
this._pendingPush = null;
var modeDef = cardDef.modes[mode];
if (!modeDef)
throw new Error('No such card mode: ' + mode);
console.log('pushCard for type: ' + type);
var domNode = args.cachedNode ?
args.cachedNode : cardDef.templateNode.cloneNode(true);
domNode.setAttribute('data-type', type);
domNode.setAttribute('data-mode', mode);
var cardImpl = new cardDef.constructor(domNode, mode, args);
var cardInst = {
domNode: domNode,
cardDef: cardDef,
modeDef: modeDef,
cardImpl: cardImpl
};
var cardIndex, insertBuddy;
if (!placement) {
cardIndex = this._cardStack.length;
insertBuddy = null;
domNode.classList.add(cardIndex === 0 ? 'before' : 'after');
}
else if (placement === 'left') {
cardIndex = this.activeCardIndex++;
insertBuddy = this._cardsNode.children[cardIndex];
domNode.classList.add('before');
}
else if (placement === 'right') {
cardIndex = this.activeCardIndex + 1;
if (cardIndex >= this._cardStack.length)
insertBuddy = null;
else
insertBuddy = this._cardsNode.children[cardIndex];
domNode.classList.add('after');
}
this._cardStack.splice(cardIndex, 0, cardInst);
if (!args.cachedNode)
this._cardsNode.insertBefore(domNode, insertBuddy);
// If the card has any <button type="reset"> buttons,
// make them clear the field they're next to and not the entire form.
// See input_areas.js and shared/style/input_areas.css.
hookupInputAreaResetButtons(domNode);
if ('postInsert' in cardImpl)
cardImpl.postInsert();
if (showMethod !== 'none') {
// make sure the reflow sees the new node so that the animation
// later is smooth.
if (!args.cachedNode)
domNode.clientWidth;
this._showCard(cardIndex, showMethod, 'forward');
}
if (args.onPushed)
args.onPushed(cardImpl);
},
/**
* Pushes a new card if none exists, otherwise, uses existing
* card and passes args to that card via tellCard. Arguments
* are the same as pushCard.
* @return {Boolean} true if card was pushed.
*/
pushOrTellCard: function(type, mode, showMethod, args, placement) {
var query = [type, mode];
if (this.hasCard(query)) {
this.tellCard(query, args);
return false;
} else {
this.pushCard.apply(this, Array.slice(arguments));
return true;
}
},
_findCardUsingTypeAndMode: function(type, mode) {
for (var i = 0; i < this._cardStack.length; i++) {
var cardInst = this._cardStack[i];
if (cardInst.cardDef.name === type &&
cardInst.modeDef.name === mode) {
return i;
}
}
},
_findCardUsingImpl: function(impl) {
for (var i = 0; i < this._cardStack.length; i++) {
var cardInst = this._cardStack[i];
if (cardInst.cardImpl === impl)
return i;
}
},
_findCard: function(query, skipFail) {
var result;
if (Array.isArray(query))
result = this._findCardUsingTypeAndMode(query[0], query[1], skipFail);
else if (typeof(query) === 'number') // index number
result = query;
else
result = this._findCardUsingImpl(query);
if (result > -1)
return result;
else if (!skipFail)
throw new Error('Unable to find card with query:', query);
else
// Returning undefined explicitly so that index comparisons, like
// the one in hasCard, are correct.
return undefined;
},
hasCard: function(query) {
if (this._pendingPush && Array.isArray(query) && query.length === 2 &&
this._pendingPush[0] === query[0] &&
this._pendingPush[1] === query[1])
return true;
return this._findCard(query, true) > -1;
},
isVisible: function(cardImpl) {
return !!(cardImpl.domNode &&
cardImpl.domNode.classList.contains('center'));
},
findCardObject: function(query) {
return this._cardStack[this._findCard(query)];
},
getCurrentCardType: function() {
var result = null,
card = this._cardStack[this.activeCardIndex];
// Favor any _pendingPush value as it is about to
// become current, just waiting on an async cycle
// to finish. Otherwise use current card value.
if (this._pendingPush) {
result = this._pendingPush;
} else if (card) {
result = [card.cardDef.name, card.cardImpl.mode];
}
return result;
},
folderSelector: function(callback) {
var self = this;
require(['model', 'value_selector'], function(model) {
// XXX: Unified folders will require us to make sure we get the folder
// list for the account the message originates from.
if (!self.folderPrompt) {
var selectorTitle = mozL10n.get('messages-folder-select');
self.folderPrompt = new ValueSelector(selectorTitle);
}
model.latestOnce('foldersSlice', function(foldersSlice) {
var folders = foldersSlice.items;
for (var i = 0; i < folders.length; i++) {
var folder = folders[i];
self.folderPrompt.addToList(folder.name, folder.depth,
folder.selectable,
function(folder) {
return function() {
self.folderPrompt.hide();
callback(folder);
};
}(folder));
}
self.folderPrompt.show();
});
});
},
moveToCard: function(query, showMethod) {
this._showCard(this._findCard(query), showMethod || 'animate');
},
tellCard: function(query, what) {
var cardIndex = this._findCard(query),
cardInst = this._cardStack[cardIndex];
if (!('told' in cardInst.cardImpl))
console.warn("Tried to tell a card that's not listening!", query, what);
else
cardInst.cardImpl.told(what);
},
/**
* Create a mask that shows only the given node by creating 2 or 4 div's,
* returning the container that holds those divs. It's not clear if a single
* div with some type of fancy clipping would be better.
*/
_createMaskForNode: function(domNode, bounds) {
var anchorIn = this._rootNode, cleanupDivs = [];
var uiWidth = this._containerNode.offsetWidth,
uiHeight = this._containerNode.offsetHeight;
// inclusive pixel coverage
function addMask(left, top, right, bottom) {
var node = document.createElement('div');
node.classList.add('popup-mask');
node.style.left = left + 'px';
node.style.top = top + 'px';
node.style.width = (right - left + 1) + 'px';
node.style.height = (bottom - top + 1) + 'px';
cleanupDivs.push(node);
anchorIn.appendChild(node);
}
if (bounds.left > 1)
addMask(0, bounds.top, bounds.left - 1, bounds.bottom);
if (bounds.top > 0)
addMask(0, 0, uiWidth - 1, bounds.top - 1);
if (bounds.right < uiWidth - 1)
addMask(bounds.right + 1, bounds.top, uiWidth - 1, bounds.bottom);
if (bounds.bottom < uiHeight - 1)
addMask(0, bounds.bottom + 1, uiWidth - 1, uiHeight - 1);
return function() {
for (var i = 0; i < cleanupDivs.length; i++) {
anchorIn.removeChild(cleanupDivs[i]);
}
};
},
/**
* Remove the card identified by its DOM node and all the cards to its right.
* Pass null to remove all of the cards! If cardDomNode passed, but there
* are no cards before it, Cards.getDefaultCard is called to set up a before
* card.
*/
/* @args[
* @param[cardDomNode]{
* The DOM node that is the first card to remove; all of the cards to its
* right will also be removed. If null is passed it is understood you
* want to remove all cards.
* }
* @param[showMethod @oneof[
* @case['animate']{
* Perform an animated scrolling transition.
* }
* @case['immediate']{
* Immediately warp to the card without animation.
* }
* @case['none']{
* Remove the nodes immediately, don't do anything about the view
* position. You only want to do this if you are going to push one
* or more cards and the last card will use a transition of 'immediate'.
* }
* ]]
* @param[numCards #:optional Number]{
* The number of cards to remove. If omitted, all the cards to the right
* of this card are removed as well.
* }
* @param[nextCardSpec #:optional]{
* If a showMethod is not 'none', the card to show after removal.
* }
* @param[skipDefault #:optional Boolean]{
* Skips the default pushCard if the removal ends up with no more
* cards in the stack.
* }
* ]
*/
removeCardAndSuccessors: function(cardDomNode, showMethod, numCards,
nextCardSpec, skipDefault) {
if (!this._cardStack.length)
return;
if (cardDomNode && this._cardStack.length === 1 && !skipDefault) {
// No card to go to when done, so ask for a default
// card and continue work once it exists.
return Cards.pushDefaultCard(function() {
this.removeCardAndSuccessors(cardDomNode, showMethod, numCards,
nextCardSpec);
}.bind(this));
}
var firstIndex, iCard, cardInst;
if (cardDomNode === undefined) {
throw new Error('undefined is not a valid card spec!');
}
else if (cardDomNode === null) {
firstIndex = 0;
// reset the z-index to 0 since we may have cards in the stack that
// adjusted the z-index (and we are definitively clearing all cards).
this._zIndex = 0;
}
else {
for (iCard = this._cardStack.length - 1; iCard >= 0; iCard--) {
cardInst = this._cardStack[iCard];
if (cardInst.domNode === cardDomNode) {
firstIndex = iCard;
break;
}
}
if (firstIndex === undefined)
throw new Error('No card represented by that DOM node');
}
if (!numCards)
numCards = this._cardStack.length - firstIndex;
if (showMethod !== 'none') {
var nextCardIndex = -1;
if (nextCardSpec) {
nextCardIndex = this._findCard(nextCardSpec);
} else if (this._cardStack.length) {
nextCardIndex = Math.min(firstIndex - 1, this._cardStack.length - 1);
}
if (nextCardIndex > -1) {
this._showCard(nextCardIndex, showMethod, 'back');
}
}
// Update activeCardIndex if nodes were removed that would affect its
// value.
if (firstIndex <= this.activeCardIndex) {
this.activeCardIndex -= numCards;
if (this.activeCardIndex < -1) {
this.activeCardIndex = -1;
}
}
var deadCardInsts = this._cardStack.splice(
firstIndex, numCards);
for (iCard = 0; iCard < deadCardInsts.length; iCard++) {
cardInst = deadCardInsts[iCard];
try {
cardInst.cardImpl.die();
}
catch (ex) {
console.warn('Problem cleaning up card:', ex, '\n', ex.stack);
}
switch (showMethod) {
case 'animate':
case 'immediate': // XXX handle properly
this._animatingDeadDomNodes.push(cardInst.domNode);
break;
case 'none':
cardInst.domNode.parentNode.removeChild(cardInst.domNode);
break;
}
}
},
/**
* Shortcut for removing all the cards
*/
removeAllCards: function() {
return this.removeCardAndSuccessors(null, 'none');
},
_showCard: function(cardIndex, showMethod, navDirection) {
// Do not do anything if this is a show card for the current card.
if (cardIndex === this.activeCardIndex) {
return;
}
if (cardIndex > this._cardStack.length - 1) {
// Some cards were removed, adjust.
cardIndex = this._cardStack.length - 1;
}
if (this.activeCardIndex > this._cardStack.length - 1) {
this.activeCardIndex = -1;
}
if (this.activeCardIndex === -1) {
this.activeCardIndex = cardIndex === 0 ? cardIndex : cardIndex - 1;
}
var cardInst = (cardIndex !== null) ? this._cardStack[cardIndex] : null;
var beginNode = this._cardStack[this.activeCardIndex].domNode;
var endNode = this._cardStack[cardIndex].domNode;
var isForward = navDirection === 'forward';
if (this._cardStack.length === 1) {
// Reset zIndex so that it does not grow ever higher when all but
// one card are removed
this._zIndex = 0;
}
// If going forward and it is an overlay node, then do not animate the
// beginning node, it will just sit under the overlay.
if (isForward && endNode.classList.contains('anim-overlay')) {
beginNode = null;
// anim-overlays are the transitions to new layers in the stack. If
// starting a new one, it is forward movement and needs a new zIndex.
// Otherwise, going back to
this._zIndex += 10;
}
// If going back and the beginning node was an overlay, do not animate
// the end node, since it should just be hidden under the overlay.
if (beginNode && beginNode.classList.contains('anim-overlay')) {
if (isForward) {
// If a forward animation and overlay had a vertical transition,
// disable it, use normal horizontal transition.
if (showMethod !== 'immediate' &&
beginNode.classList.contains('anim-vertical')) {
removeClass(beginNode, 'anim-vertical');
addClass(beginNode, 'disabled-anim-vertical');
}
} else {
endNode = null;
this._zIndex -= 10;
}
}
// If the zindex is not zero, then in an overlay stack, adjust zindex
// accordingly.
if (endNode && isForward && this._zIndex) {
endNode.style.zIndex = this._zIndex;
}
var cardsNode = this._cardsNode;
if (showMethod === 'immediate') {
addClass(beginNode, 'no-anim');
addClass(endNode, 'no-anim');
// make sure the reflow sees the transition is turned off.
cardsNode.clientWidth;
// explicitly clear since there will be no animation
this._eatingEventsUntilNextCard = false;
}
else if (showMethod === 'none') {
// do not set _eatingEventsUntilNextCard, but don't clear it either.
}
else {
this._transitionCount = (beginNode && endNode) ? 2 : 1;
this._eatingEventsUntilNextCard = true;
}
if (this.activeCardIndex === cardIndex) {
// same node, no transition, just bootstrapping UI.
removeClass(beginNode, 'before');
removeClass(beginNode, 'after');
addClass(beginNode, 'center');
} else if (this.activeCardIndex > cardIndex) {
// back
removeClass(beginNode, 'center');
addClass(beginNode, 'after');
removeClass(endNode, 'before');
addClass(endNode, 'center');
} else {
// forward
removeClass(beginNode, 'center');
addClass(beginNode, 'before');
removeClass(endNode, 'after');
addClass(endNode, 'center');
}
if (showMethod === 'immediate') {
// make sure the instantaneous transition is seen before we turn
// transitions back on.
cardsNode.clientWidth;
removeClass(beginNode, 'no-anim');
removeClass(endNode, 'no-anim');
if (cardInst && cardInst.onCardVisible)
cardInst.onCardVisible();
}
// Hide toaster while active card index changed:
Toaster.hide();
this.activeCardIndex = cardIndex;
if (cardInst)
this._trayActive = cardInst.modeDef.tray;
},
_onTransitionEnd: function(event) {
var activeCard = this._cardStack[this.activeCardIndex];
// If no current card, this could be initial setup from cache, no valid
// cards yet, so bail.
if (!activeCard)
return;
// Multiple cards can animate, so there can be multiple transitionend
// events. Only do the end work when all have finished animating.
if (this._transitionCount > 0)
this._transitionCount -= 1;
if (this._transitionCount === 0) {
if (this._eatingEventsUntilNextCard) {
this._eatingEventsUntilNextCard = false;
}
if (this._animatingDeadDomNodes.length) {
// Use a setTimeout to give the animation some space to settle.
setTimeout(function() {
this._animatingDeadDomNodes.forEach(function(domNode) {
if (domNode.parentNode)
domNode.parentNode.removeChild(domNode);
});
this._animatingDeadDomNodes = [];
}.bind(this), 100);
}
// If an vertical overlay transition was was disabled, if
// current node index is an overlay, enable it again.
var endNode = activeCard.domNode;
if (endNode.classList.contains('disabled-anim-vertical')) {
removeClass(endNode, 'disabled-anim-vertical');
addClass(endNode, 'anim-vertical');
}
// Popup toaster that pended for previous card view.
var pendingToaster = Toaster.pendingStack.slice(-1)[0];
if (pendingToaster) {
pendingToaster();
Toaster.pendingStack.pop();
}
// If any action to do at the end of transition trigger now.
if (this._afterTransitionAction) {
var afterTransitionAction = this._afterTransitionAction;
this._afterTransitionAction = null;
afterTransitionAction();
}
if (activeCard.cardImpl.onCardVisible)
activeCard.cardImpl.onCardVisible();
// If the card has next cards that can be preloaded, load them now.
// Use of nextCards should be balanced with startup performance.
// nextCards can result in smoother transitions to new cards on first
// navigation to that new card type, but loading the extra module may
// also compete with current card and data model performance.
var nextCards = activeCard.cardImpl.nextCards;
if (nextCards) {
console.log('Preloading cards: ' + nextCards);
require(nextCards.map(function(id) {
return 'cards/' + id;
}));
}
}
},
/**
* Helper that causes (some) events targeted at our cards to be eaten until
* we get to the next card. The idea is to avoid bugs caused by the user
* still being able to click things while our cards are transitioning or
* while we are performing a (reliable) async wait before we actually initiate
* a pushCard in response to user stimulus.
*
* This is automatically triggered when performing an animated transition;
* other code should only call this in the async wait case mentioned above.
*
* For example, we don't want the user to have 2 message readers happening
* at the same time because they managed to click on a second message before
* the first reader got displayed.
*/
eatEventsUntilNextCard: function() {
this._eatingEventsUntilNextCard = true;
},
/**
* Stop eating events, presumably because eatEventsUntilNextCard was used
* as a hack for a known-fast async operation to avoid bugs (where we knew
* full well that we weren't going to show a card).
*/
stopEatingEvents: function() {
this._eatingEventsUntilNextCard = false;
},
/**
* If there are any cards on the deck right now, log an error and clear them
* all out. Our caller is strongly asserting that there should be no cards