Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(542)

Side by Side Diff: chrome/browser/resources/md_history/lazy_load.crisper.js

Issue 2371383003: MD Downloads/History: make javascript uglier and more compact (Closed)
Patch Set: merge Created 4 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 Polymer({ 1 Polymer({is:"iron-collapse",behaviors:[Polymer.IronResizableBehavior],properties :{horizontal:{type:Boolean,value:false,observer:"_horizontalChanged"},opened:{ty pe:Boolean,value:false,notify:true,observer:"_openedChanged"},noAnimation:{type: Boolean},_desiredSize:{type:String,value:""}},get dimension(){return this.horizo ntal?"width":"height"},get _dimensionMax(){return this.horizontal?"maxWidth":"ma xHeight"},get _dimensionMaxCss(){return this.horizontal?"max-width":"max-height" },hostAttributes:{role:"group","aria-hidden":"true","aria-expanded":"false"},lis teners:{transitionend:"_transitionEnd"},attached:function(){this._transitionEnd( )},toggle:function(){this.opened=!this.opened},show:function(){this.opened=true} ,hide:function(){this.opened=false},updateSize:function(size,animated){size=size ==="auto"?"":size;if(this._desiredSize===size){return}this._desiredSize=size;thi s._updateTransition(false);var willAnimate=animated&&!this.noAnimation&&this._is Displayed;if(willAnimate){var startSize=this._calcSize();if(size===""){this.styl e[this._dimensionMax]="";size=this._calcSize()}this.style[this._dimensionMax]=st artSize;this.scrollTop=this.scrollTop;this._updateTransition(true);willAnimate=s ize!==startSize}this.style[this._dimensionMax]=size;if(!willAnimate){this._trans itionEnd()}},enableTransition:function(enabled){Polymer.Base._warn("`enableTrans ition()` is deprecated, use `noAnimation` instead.");this.noAnimation=!enabled}, _updateTransition:function(enabled){this.style.transitionDuration=enabled&&!this .noAnimation?"":"0s"},_horizontalChanged:function(){this.style.transitionPropert y=this._dimensionMaxCss;var otherDimension=this._dimensionMax==="maxWidth"?"maxH eight":"maxWidth";this.style[otherDimension]="";this.updateSize(this.opened?"aut o":"0px",false)},_openedChanged:function(){this.setAttribute("aria-expanded",thi s.opened);this.setAttribute("aria-hidden",!this.opened);this.toggleClass("iron-c ollapse-closed",false);this.toggleClass("iron-collapse-opened",false);this.updat eSize(this.opened?"auto":"0px",true);if(this.opened){this.focus()}},_transitionE nd:function(){this.style[this._dimensionMax]=this._desiredSize;this.toggleClass( "iron-collapse-closed",!this.opened);this.toggleClass("iron-collapse-opened",thi s.opened);this._updateTransition(false);this.notifyResize()},get _isDisplayed(){ var rect=this.getBoundingClientRect();for(var prop in rect){if(rect[prop]!==0)re turn true}return false},_calcSize:function(){return this.getBoundingClientRect() [this.dimension]+"px"}});
2 is: 'iron-collapse',
3 behaviors: [ Polymer.IronResizableBehavior ],
4 properties: {
5 horizontal: {
6 type: Boolean,
7 value: false,
8 observer: '_horizontalChanged'
9 },
10 opened: {
11 type: Boolean,
12 value: false,
13 notify: true,
14 observer: '_openedChanged'
15 },
16 noAnimation: {
17 type: Boolean
18 },
19 _desiredSize: {
20 type: String,
21 value: ''
22 }
23 },
24 get dimension() {
25 return this.horizontal ? 'width' : 'height';
26 },
27 get _dimensionMax() {
28 return this.horizontal ? 'maxWidth' : 'maxHeight';
29 },
30 get _dimensionMaxCss() {
31 return this.horizontal ? 'max-width' : 'max-height';
32 },
33 hostAttributes: {
34 role: 'group',
35 'aria-hidden': 'true',
36 'aria-expanded': 'false'
37 },
38 listeners: {
39 transitionend: '_transitionEnd'
40 },
41 attached: function() {
42 this._transitionEnd();
43 },
44 toggle: function() {
45 this.opened = !this.opened;
46 },
47 show: function() {
48 this.opened = true;
49 },
50 hide: function() {
51 this.opened = false;
52 },
53 updateSize: function(size, animated) {
54 size = size === 'auto' ? '' : size;
55 if (this._desiredSize === size) {
56 return;
57 }
58 this._desiredSize = size;
59 this._updateTransition(false);
60 var willAnimate = animated && !this.noAnimation && this._isDisplayed;
61 if (willAnimate) {
62 var startSize = this._calcSize();
63 if (size === '') {
64 this.style[this._dimensionMax] = '';
65 size = this._calcSize();
66 }
67 this.style[this._dimensionMax] = startSize;
68 this.scrollTop = this.scrollTop;
69 this._updateTransition(true);
70 willAnimate = size !== startSize;
71 }
72 this.style[this._dimensionMax] = size;
73 if (!willAnimate) {
74 this._transitionEnd();
75 }
76 },
77 enableTransition: function(enabled) {
78 Polymer.Base._warn('`enableTransition()` is deprecated, use `noAnimation` in stead.');
79 this.noAnimation = !enabled;
80 },
81 _updateTransition: function(enabled) {
82 this.style.transitionDuration = enabled && !this.noAnimation ? '' : '0s';
83 },
84 _horizontalChanged: function() {
85 this.style.transitionProperty = this._dimensionMaxCss;
86 var otherDimension = this._dimensionMax === 'maxWidth' ? 'maxHeight' : 'maxW idth';
87 this.style[otherDimension] = '';
88 this.updateSize(this.opened ? 'auto' : '0px', false);
89 },
90 _openedChanged: function() {
91 this.setAttribute('aria-expanded', this.opened);
92 this.setAttribute('aria-hidden', !this.opened);
93 this.toggleClass('iron-collapse-closed', false);
94 this.toggleClass('iron-collapse-opened', false);
95 this.updateSize(this.opened ? 'auto' : '0px', true);
96 if (this.opened) {
97 this.focus();
98 }
99 },
100 _transitionEnd: function() {
101 this.style[this._dimensionMax] = this._desiredSize;
102 this.toggleClass('iron-collapse-closed', !this.opened);
103 this.toggleClass('iron-collapse-opened', this.opened);
104 this._updateTransition(false);
105 this.notifyResize();
106 },
107 get _isDisplayed() {
108 var rect = this.getBoundingClientRect();
109 for (var prop in rect) {
110 if (rect[prop] !== 0) return true;
111 }
112 return false;
113 },
114 _calcSize: function() {
115 return this.getBoundingClientRect()[this.dimension] + 'px';
116 }
117 });
118
119 // Copyright 2016 The Chromium Authors. All rights reserved. 2 // Copyright 2016 The Chromium Authors. All rights reserved.
120 // Use of this source code is governed by a BSD-style license that can be 3 // Use of this source code is governed by a BSD-style license that can be
121 // found in the LICENSE file. 4 // found in the LICENSE file.
122 var HistoryDomain; 5 var HistoryDomain;var HistoryGroup;Polymer({is:"history-grouped-list",behaviors: [HistoryListBehavior],properties:{historyData:{type:Array},groupedHistoryData_:{ type:Array},searchedTerm:{type:String,value:""},range:{type:Number},queryStartTi me:String,queryEndTime:String},observers:["updateGroupedHistoryData_(range, hist oryData)"],createHistoryDomains_:function(visits){var domainIndexes={};var domai ns=[];for(var i=0,visit;visit=visits[i];i++){var domain=visit.domain;if(domainIn dexes[domain]==undefined){domainIndexes[domain]=domains.length;domains.push({dom ain:domain,visits:[],expanded:false,rendered:false})}domains[domainIndexes[domai n]].visits.push(visit)}var sortByVisits=function(a,b){return b.visits.length-a.v isits.length};domains.sort(sortByVisits);return domains},updateGroupedHistoryDat a_:function(){if(this.historyData.length==0){this.groupedHistoryData_=[];return} if(this.range==HistoryRange.WEEK){var days=[];var currentDayVisits=[this.history Data[0]];var pushCurrentDay=function(){days.push({title:this.searchedTerm?curren tDayVisits[0].dateShort:currentDayVisits[0].dateRelativeDay,domains:this.createH istoryDomains_(currentDayVisits)})}.bind(this);var visitsSameDay=function(a,b){i f(this.searchedTerm)return a.dateShort==b.dateShort;return a.dateRelativeDay==b. dateRelativeDay}.bind(this);for(var i=1;i<this.historyData.length;i++){var visit =this.historyData[i];if(!visitsSameDay(visit,currentDayVisits[0])){pushCurrentDa y();currentDayVisits=[]}currentDayVisits.push(visit)}pushCurrentDay();this.group edHistoryData_=days}else if(this.range==HistoryRange.MONTH){this.groupedHistoryD ata_=[{title:this.queryStartTime+" – "+this.queryEndTime,domains:this.createHist oryDomains_(this.historyData)}]}},toggleDomainExpanded_:function(e){var collapse =e.currentTarget.parentNode.querySelector("iron-collapse");e.model.set("domain.r endered",true);setTimeout(function(){collapse.toggle()},0)},needsTimeGap_:functi on(groupIndex,domainIndex,itemIndex){var visits=this.groupedHistoryData_[groupIn dex].domains[domainIndex].visits;return md_history.HistoryItem.needsTimeGap(visi ts,itemIndex,this.searchedTerm)},pathForItem_:function(groupIndex,domainIndex,it emIndex){return["groupedHistoryData_",groupIndex,"domains",domainIndex,"visits", itemIndex].join(".")},getWebsiteIconStyle_:function(domain){return"background-im age: "+cr.icon.getFavicon(domain.visits[0].url)},getDropdownIcon_:function(expan ded){return expanded?"cr:expand-less":"cr:expand-more"}});Polymer.PaperButtonBeh aviorImpl={properties:{elevation:{type:Number,reflectToAttribute:true,readOnly:t rue}},observers:["_calculateElevation(focused, disabled, active, pressed, receiv edFocusFromKeyboard)","_computeKeyboardClass(receivedFocusFromKeyboard)"],hostAt tributes:{role:"button",tabindex:"0",animated:true},_calculateElevation:function (){var e=1;if(this.disabled){e=0}else if(this.active||this.pressed){e=4}else if( this.receivedFocusFromKeyboard){e=3}this._setElevation(e)},_computeKeyboardClass :function(receivedFocusFromKeyboard){this.toggleClass("keyboard-focus",receivedF ocusFromKeyboard)},_spaceKeyDownHandler:function(event){Polymer.IronButtonStateI mpl._spaceKeyDownHandler.call(this,event);if(this.hasRipple()&&this.getRipple(). ripples.length<1){this._ripple.uiDownAction()}},_spaceKeyUpHandler:function(even t){Polymer.IronButtonStateImpl._spaceKeyUpHandler.call(this,event);if(this.hasRi pple()){this._ripple.uiUpAction()}}};Polymer.PaperButtonBehavior=[Polymer.IronBu ttonState,Polymer.IronControlState,Polymer.PaperRippleBehavior,Polymer.PaperButt onBehaviorImpl];Polymer({is:"paper-button",behaviors:[Polymer.PaperButtonBehavio r],properties:{raised:{type:Boolean,reflectToAttribute:true,value:false,observer :"_calculateElevation"}},_calculateElevation:function(){if(!this.raised){this._s etElevation(0)}else{Polymer.PaperButtonBehaviorImpl._calculateElevation.apply(th is)}}});Polymer.PaperItemBehaviorImpl={hostAttributes:{role:"option",tabindex:"0 "}};Polymer.PaperItemBehavior=[Polymer.IronButtonState,Polymer.IronControlState, Polymer.PaperItemBehaviorImpl];Polymer({is:"paper-item",behaviors:[Polymer.Paper ItemBehavior]});Polymer.IronFitBehavior={properties:{sizingTarget:{type:Object,v alue:function(){return this}},fitInto:{type:Object,value:window},noOverlap:{type :Boolean},positionTarget:{type:Element},horizontalAlign:{type:String},verticalAl ign:{type:String},dynamicAlign:{type:Boolean},horizontalOffset:{type:Number,valu e:0,notify:true},verticalOffset:{type:Number,value:0,notify:true},autoFitOnAttac h:{type:Boolean,value:false},_fitInfo:{type:Object}},get _fitWidth(){var fitWidt h;if(this.fitInto===window){fitWidth=this.fitInto.innerWidth}else{fitWidth=this. fitInto.getBoundingClientRect().width}return fitWidth},get _fitHeight(){var fitH eight;if(this.fitInto===window){fitHeight=this.fitInto.innerHeight}else{fitHeigh t=this.fitInto.getBoundingClientRect().height}return fitHeight},get _fitLeft(){v ar fitLeft;if(this.fitInto===window){fitLeft=0}else{fitLeft=this.fitInto.getBoun dingClientRect().left}return fitLeft},get _fitTop(){var fitTop;if(this.fitInto== =window){fitTop=0}else{fitTop=this.fitInto.getBoundingClientRect().top}return fi tTop},get _defaultPositionTarget(){var parent=Polymer.dom(this).parentNode;if(pa rent&&parent.nodeType===Node.DOCUMENT_FRAGMENT_NODE){parent=parent.host}return p arent},get _localeHorizontalAlign(){if(this._isRTL){if(this.horizontalAlign==="r ight"){return"left"}if(this.horizontalAlign==="left"){return"right"}}return this .horizontalAlign},attached:function(){this._isRTL=window.getComputedStyle(this). direction=="rtl";this.positionTarget=this.positionTarget||this._defaultPositionT arget;if(this.autoFitOnAttach){if(window.getComputedStyle(this).display==="none" ){setTimeout(function(){this.fit()}.bind(this))}else{this.fit()}}},fit:function( ){this.position();this.constrain();this.center()},_discoverInfo:function(){if(th is._fitInfo){return}var target=window.getComputedStyle(this);var sizer=window.ge tComputedStyle(this.sizingTarget);this._fitInfo={inlineStyle:{top:this.style.top ||"",left:this.style.left||"",position:this.style.position||""},sizerInlineStyle :{maxWidth:this.sizingTarget.style.maxWidth||"",maxHeight:this.sizingTarget.styl e.maxHeight||"",boxSizing:this.sizingTarget.style.boxSizing||""},positionedBy:{v ertically:target.top!=="auto"?"top":target.bottom!=="auto"?"bottom":null,horizon tally:target.left!=="auto"?"left":target.right!=="auto"?"right":null},sizedBy:{h eight:sizer.maxHeight!=="none",width:sizer.maxWidth!=="none",minWidth:parseInt(s izer.minWidth,10)||0,minHeight:parseInt(sizer.minHeight,10)||0},margin:{top:pars eInt(target.marginTop,10)||0,right:parseInt(target.marginRight,10)||0,bottom:par seInt(target.marginBottom,10)||0,left:parseInt(target.marginLeft,10)||0}};if(thi s.verticalOffset){this._fitInfo.margin.top=this._fitInfo.margin.bottom=this.vert icalOffset;this._fitInfo.inlineStyle.marginTop=this.style.marginTop||"";this._fi tInfo.inlineStyle.marginBottom=this.style.marginBottom||"";this.style.marginTop= this.style.marginBottom=this.verticalOffset+"px"}if(this.horizontalOffset){this. _fitInfo.margin.left=this._fitInfo.margin.right=this.horizontalOffset;this._fitI nfo.inlineStyle.marginLeft=this.style.marginLeft||"";this._fitInfo.inlineStyle.m arginRight=this.style.marginRight||"";this.style.marginLeft=this.style.marginRig ht=this.horizontalOffset+"px"}},resetFit:function(){var info=this._fitInfo||{};f or(var property in info.sizerInlineStyle){this.sizingTarget.style[property]=info .sizerInlineStyle[property]}for(var property in info.inlineStyle){this.style[pro perty]=info.inlineStyle[property]}this._fitInfo=null},refit:function(){var scrol lLeft=this.sizingTarget.scrollLeft;var scrollTop=this.sizingTarget.scrollTop;thi s.resetFit();this.fit();this.sizingTarget.scrollLeft=scrollLeft;this.sizingTarge t.scrollTop=scrollTop},position:function(){if(!this.horizontalAlign&&!this.verti calAlign){return}this._discoverInfo();this.style.position="fixed";this.sizingTar get.style.boxSizing="border-box";this.style.left="0px";this.style.top="0px";var rect=this.getBoundingClientRect();var positionRect=this.__getNormalizedRect(this .positionTarget);var fitRect=this.__getNormalizedRect(this.fitInto);var margin=t his._fitInfo.margin;var size={width:rect.width+margin.left+margin.right,height:r ect.height+margin.top+margin.bottom};var position=this.__getPosition(this._local eHorizontalAlign,this.verticalAlign,size,positionRect,fitRect);var left=position .left+margin.left;var top=position.top+margin.top;var right=Math.min(fitRect.rig ht-margin.right,left+rect.width);var bottom=Math.min(fitRect.bottom-margin.botto m,top+rect.height);var minWidth=this._fitInfo.sizedBy.minWidth;var minHeight=thi s._fitInfo.sizedBy.minHeight;if(left<margin.left){left=margin.left;if(right-left <minWidth){left=right-minWidth}}if(top<margin.top){top=margin.top;if(bottom-top< minHeight){top=bottom-minHeight}}this.sizingTarget.style.maxWidth=right-left+"px ";this.sizingTarget.style.maxHeight=bottom-top+"px";this.style.left=left-rect.le ft+"px";this.style.top=top-rect.top+"px"},constrain:function(){if(this.horizonta lAlign||this.verticalAlign){return}this._discoverInfo();var info=this._fitInfo;i f(!info.positionedBy.vertically){this.style.position="fixed";this.style.top="0px "}if(!info.positionedBy.horizontally){this.style.position="fixed";this.style.lef t="0px"}this.sizingTarget.style.boxSizing="border-box";var rect=this.getBounding ClientRect();if(!info.sizedBy.height){this.__sizeDimension(rect,info.positionedB y.vertically,"top","bottom","Height")}if(!info.sizedBy.width){this.__sizeDimensi on(rect,info.positionedBy.horizontally,"left","right","Width")}},_sizeDimension: function(rect,positionedBy,start,end,extent){this.__sizeDimension(rect,positione dBy,start,end,extent)},__sizeDimension:function(rect,positionedBy,start,end,exte nt){var info=this._fitInfo;var fitRect=this.__getNormalizedRect(this.fitInto);va r max=extent==="Width"?fitRect.width:fitRect.height;var flip=positionedBy===end; var offset=flip?max-rect[end]:rect[start];var margin=info.margin[flip?start:end] ;var offsetExtent="offset"+extent;var sizingOffset=this[offsetExtent]-this.sizin gTarget[offsetExtent];this.sizingTarget.style["max"+extent]=max-margin-offset-si zingOffset+"px"},center:function(){if(this.horizontalAlign||this.verticalAlign){ return}this._discoverInfo();var positionedBy=this._fitInfo.positionedBy;if(posit ionedBy.vertically&&positionedBy.horizontally){return}this.style.position="fixed ";if(!positionedBy.vertically){this.style.top="0px"}if(!positionedBy.horizontall y){this.style.left="0px"}var rect=this.getBoundingClientRect();var fitRect=this. __getNormalizedRect(this.fitInto);if(!positionedBy.vertically){var top=fitRect.t op-rect.top+(fitRect.height-rect.height)/2;this.style.top=top+"px"}if(!positione dBy.horizontally){var left=fitRect.left-rect.left+(fitRect.width-rect.width)/2;t his.style.left=left+"px"}},__getNormalizedRect:function(target){if(target===docu ment.documentElement||target===window){return{top:0,left:0,width:window.innerWid th,height:window.innerHeight,right:window.innerWidth,bottom:window.innerHeight}} return target.getBoundingClientRect()},__getCroppedArea:function(position,size,f itRect){var verticalCrop=Math.min(0,position.top)+Math.min(0,fitRect.bottom-(pos ition.top+size.height));var horizontalCrop=Math.min(0,position.left)+Math.min(0, fitRect.right-(position.left+size.width));return Math.abs(verticalCrop)*size.wid th+Math.abs(horizontalCrop)*size.height},__getPosition:function(hAlign,vAlign,si ze,positionRect,fitRect){var positions=[{verticalAlign:"top",horizontalAlign:"le ft",top:positionRect.top,left:positionRect.left},{verticalAlign:"top",horizontal Align:"right",top:positionRect.top,left:positionRect.right-size.width},{vertical Align:"bottom",horizontalAlign:"left",top:positionRect.bottom-size.height,left:p ositionRect.left},{verticalAlign:"bottom",horizontalAlign:"right",top:positionRe ct.bottom-size.height,left:positionRect.right-size.width}];if(this.noOverlap){fo r(var i=0,l=positions.length;i<l;i++){var copy={};for(var key in positions[i]){c opy[key]=positions[i][key]}positions.push(copy)}positions[0].top=positions[1].to p+=positionRect.height;positions[2].top=positions[3].top-=positionRect.height;po sitions[4].left=positions[6].left+=positionRect.width;positions[5].left=position s[7].left-=positionRect.width}vAlign=vAlign==="auto"?null:vAlign;hAlign=hAlign== ="auto"?null:hAlign;var position;for(var i=0;i<positions.length;i++){var pos=pos itions[i];if(!this.dynamicAlign&&!this.noOverlap&&pos.verticalAlign===vAlign&&po s.horizontalAlign===hAlign){position=pos;break}var alignOk=(!vAlign||pos.vertica lAlign===vAlign)&&(!hAlign||pos.horizontalAlign===hAlign);if(!this.dynamicAlign& &!alignOk){continue}position=position||pos;pos.croppedArea=this.__getCroppedArea (pos,size,fitRect);var diff=pos.croppedArea-position.croppedArea;if(diff<0||diff ===0&&alignOk){position=pos}if(position.croppedArea===0&&alignOk){break}}return position}};(function(){"use strict";Polymer({is:"iron-overlay-backdrop",properti es:{opened:{reflectToAttribute:true,type:Boolean,value:false,observer:"_openedCh anged"}},listeners:{transitionend:"_onTransitionend"},created:function(){this.__ openedRaf=null},attached:function(){this.opened&&this._openedChanged(this.opened )},prepare:function(){if(this.opened&&!this.parentNode){Polymer.dom(document.bod y).appendChild(this)}},open:function(){this.opened=true},close:function(){this.o pened=false},complete:function(){if(!this.opened&&this.parentNode===document.bod y){Polymer.dom(this.parentNode).removeChild(this)}},_onTransitionend:function(ev ent){if(event&&event.target===this){this.complete()}},_openedChanged:function(op ened){if(opened){this.prepare()}else{var cs=window.getComputedStyle(this);if(cs. transitionDuration==="0s"||cs.opacity==0){this.complete()}}if(!this.isAttached){ return}if(this.__openedRaf){window.cancelAnimationFrame(this.__openedRaf);this._ _openedRaf=null}this.scrollTop=this.scrollTop;this.__openedRaf=window.requestAni mationFrame(function(){this.__openedRaf=null;this.toggleClass("opened",this.open ed)}.bind(this))}})})();Polymer.IronOverlayManagerClass=function(){this._overlay s=[];this._minimumZ=101;this._backdropElement=null;Polymer.Gestures.add(document ,"tap",this._onCaptureClick.bind(this));document.addEventListener("focus",this._ onCaptureFocus.bind(this),true);document.addEventListener("keydown",this._onCapt ureKeyDown.bind(this),true)};Polymer.IronOverlayManagerClass.prototype={construc tor:Polymer.IronOverlayManagerClass,get backdropElement(){if(!this._backdropElem ent){this._backdropElement=document.createElement("iron-overlay-backdrop")}retur n this._backdropElement},get deepActiveElement(){var active=document.activeEleme nt||document.body;while(active.root&&Polymer.dom(active.root).activeElement){act ive=Polymer.dom(active.root).activeElement}return active},_bringOverlayAtIndexTo Front:function(i){var overlay=this._overlays[i];if(!overlay){return}var lastI=th is._overlays.length-1;var currentOverlay=this._overlays[lastI];if(currentOverlay &&this._shouldBeBehindOverlay(overlay,currentOverlay)){lastI--}if(i>=lastI){retu rn}var minimumZ=Math.max(this.currentOverlayZ(),this._minimumZ);if(this._getZ(ov erlay)<=minimumZ){this._applyOverlayZ(overlay,minimumZ)}while(i<lastI){this._ove rlays[i]=this._overlays[i+1];i++}this._overlays[lastI]=overlay},addOrRemoveOverl ay:function(overlay){if(overlay.opened){this.addOverlay(overlay)}else{this.remov eOverlay(overlay)}},addOverlay:function(overlay){var i=this._overlays.indexOf(ov erlay);if(i>=0){this._bringOverlayAtIndexToFront(i);this.trackBackdrop();return} var insertionIndex=this._overlays.length;var currentOverlay=this._overlays[inser tionIndex-1];var minimumZ=Math.max(this._getZ(currentOverlay),this._minimumZ);va r newZ=this._getZ(overlay);if(currentOverlay&&this._shouldBeBehindOverlay(overla y,currentOverlay)){this._applyOverlayZ(currentOverlay,minimumZ);insertionIndex-- ;var previousOverlay=this._overlays[insertionIndex-1];minimumZ=Math.max(this._ge tZ(previousOverlay),this._minimumZ)}if(newZ<=minimumZ){this._applyOverlayZ(overl ay,minimumZ)}this._overlays.splice(insertionIndex,0,overlay);this.trackBackdrop( )},removeOverlay:function(overlay){var i=this._overlays.indexOf(overlay);if(i=== -1){return}this._overlays.splice(i,1);this.trackBackdrop()},currentOverlay:funct ion(){var i=this._overlays.length-1;return this._overlays[i]},currentOverlayZ:fu nction(){return this._getZ(this.currentOverlay())},ensureMinimumZ:function(minim umZ){this._minimumZ=Math.max(this._minimumZ,minimumZ)},focusOverlay:function(){v ar current=this.currentOverlay();if(current){current._applyFocus()}},trackBackdr op:function(){var overlay=this._overlayWithBackdrop();if(!overlay&&!this._backdr opElement){return}this.backdropElement.style.zIndex=this._getZ(overlay)-1;this.b ackdropElement.opened=!!overlay},getBackdrops:function(){var backdrops=[];for(va r i=0;i<this._overlays.length;i++){if(this._overlays[i].withBackdrop){backdrops. push(this._overlays[i])}}return backdrops},backdropZ:function(){return this._get Z(this._overlayWithBackdrop())-1},_overlayWithBackdrop:function(){for(var i=0;i< this._overlays.length;i++){if(this._overlays[i].withBackdrop){return this._overl ays[i]}}},_getZ:function(overlay){var z=this._minimumZ;if(overlay){var z1=Number (overlay.style.zIndex||window.getComputedStyle(overlay).zIndex);if(z1===z1){z=z1 }}return z},_setZ:function(element,z){element.style.zIndex=z},_applyOverlayZ:fun ction(overlay,aboveZ){this._setZ(overlay,aboveZ+2)},_overlayInPath:function(path ){path=path||[];for(var i=0;i<path.length;i++){if(path[i]._manager===this){retur n path[i]}}},_onCaptureClick:function(event){var overlay=this.currentOverlay();i f(overlay&&this._overlayInPath(Polymer.dom(event).path)!==overlay){overlay._onCa ptureClick(event)}},_onCaptureFocus:function(event){var overlay=this.currentOver lay();if(overlay){overlay._onCaptureFocus(event)}},_onCaptureKeyDown:function(ev ent){var overlay=this.currentOverlay();if(overlay){if(Polymer.IronA11yKeysBehavi or.keyboardEventMatchesKeys(event,"esc")){overlay._onCaptureEsc(event)}else if(P olymer.IronA11yKeysBehavior.keyboardEventMatchesKeys(event,"tab")){overlay._onCa ptureTab(event)}}},_shouldBeBehindOverlay:function(overlay1,overlay2){return!ove rlay1.alwaysOnTop&&overlay2.alwaysOnTop}};Polymer.IronOverlayManager=new Polymer .IronOverlayManagerClass;(function(){"use strict";Polymer.IronOverlayBehaviorImp l={properties:{opened:{observer:"_openedChanged",type:Boolean,value:false,notify :true},canceled:{observer:"_canceledChanged",readOnly:true,type:Boolean,value:fa lse},withBackdrop:{observer:"_withBackdropChanged",type:Boolean},noAutoFocus:{ty pe:Boolean,value:false},noCancelOnEscKey:{type:Boolean,value:false},noCancelOnOu tsideClick:{type:Boolean,value:false},closingReason:{type:Object},restoreFocusOn Close:{type:Boolean,value:false},alwaysOnTop:{type:Boolean},_manager:{type:Objec t,value:Polymer.IronOverlayManager},_focusedChild:{type:Object}},listeners:{"iro n-resize":"_onIronResize"},get backdropElement(){return this._manager.backdropEl ement},get _focusNode(){return this._focusedChild||Polymer.dom(this).querySelect or("[autofocus]")||this},get _focusableNodes(){var FOCUSABLE_WITH_DISABLED=["a[h ref]","area[href]","iframe","[tabindex]","[contentEditable=true]"];var FOCUSABLE _WITHOUT_DISABLED=["input","select","textarea","button"];var selector=FOCUSABLE_ WITH_DISABLED.join(':not([tabindex="-1"]),')+':not([tabindex="-1"]),'+FOCUSABLE_ WITHOUT_DISABLED.join(':not([disabled]):not([tabindex="-1"]),')+':not([disabled] ):not([tabindex="-1"])';var focusables=Polymer.dom(this).querySelectorAll(select or);if(this.tabIndex>=0){focusables.splice(0,0,this)}return focusables.sort(func tion(a,b){if(a.tabIndex===b.tabIndex){return 0}if(a.tabIndex===0||a.tabIndex>b.t abIndex){return 1}return-1})},ready:function(){this.__isAnimating=false;this.__s houldRemoveTabIndex=false;this.__firstFocusableNode=this.__lastFocusableNode=nul l;this.__raf=null;this.__restoreFocusNode=null;this._ensureSetup()},attached:fun ction(){if(this.opened){this._openedChanged(this.opened)}this._observer=Polymer. dom(this).observeNodes(this._onNodesChange)},detached:function(){Polymer.dom(thi s).unobserveNodes(this._observer);this._observer=null;if(this.__raf){window.canc elAnimationFrame(this.__raf);this.__raf=null}this._manager.removeOverlay(this)}, toggle:function(){this._setCanceled(false);this.opened=!this.opened},open:functi on(){this._setCanceled(false);this.opened=true},close:function(){this._setCancel ed(false);this.opened=false},cancel:function(event){var cancelEvent=this.fire("i ron-overlay-canceled",event,{cancelable:true});if(cancelEvent.defaultPrevented){ return}this._setCanceled(true);this.opened=false},_ensureSetup:function(){if(thi s._overlaySetup){return}this._overlaySetup=true;this.style.outline="none";this.s tyle.display="none"},_openedChanged:function(opened){if(opened){this.removeAttri bute("aria-hidden")}else{this.setAttribute("aria-hidden","true")}if(!this.isAtta ched){return}this.__isAnimating=true;this.__onNextAnimationFrame(this.__openedCh anged)},_canceledChanged:function(){this.closingReason=this.closingReason||{};th is.closingReason.canceled=this.canceled},_withBackdropChanged:function(){if(this .withBackdrop&&!this.hasAttribute("tabindex")){this.setAttribute("tabindex","-1" );this.__shouldRemoveTabIndex=true}else if(this.__shouldRemoveTabIndex){this.rem oveAttribute("tabindex");this.__shouldRemoveTabIndex=false}if(this.opened&&this. isAttached){this._manager.trackBackdrop()}},_prepareRenderOpened:function(){this .__restoreFocusNode=this._manager.deepActiveElement;this._preparePositioning();t his.refit();this._finishPositioning();if(this.noAutoFocus&&document.activeElemen t===this._focusNode){this._focusNode.blur();this.__restoreFocusNode.focus()}},_r enderOpened:function(){this._finishRenderOpened()},_renderClosed:function(){this ._finishRenderClosed()},_finishRenderOpened:function(){this.notifyResize();this. __isAnimating=false;var focusableNodes=this._focusableNodes;this.__firstFocusabl eNode=focusableNodes[0];this.__lastFocusableNode=focusableNodes[focusableNodes.l ength-1];this.fire("iron-overlay-opened")},_finishRenderClosed:function(){this.s tyle.display="none";this.style.zIndex="";this.notifyResize();this.__isAnimating= false;this.fire("iron-overlay-closed",this.closingReason)},_preparePositioning:f unction(){this.style.transition=this.style.webkitTransition="none";this.style.tr ansform=this.style.webkitTransform="none";this.style.display=""},_finishPosition ing:function(){this.style.display="none";this.scrollTop=this.scrollTop;this.styl e.transition=this.style.webkitTransition="";this.style.transform=this.style.webk itTransform="";this.style.display="";this.scrollTop=this.scrollTop},_applyFocus: function(){if(this.opened){if(!this.noAutoFocus){this._focusNode.focus()}}else{t his._focusNode.blur();this._focusedChild=null;if(this.restoreFocusOnClose&&this. __restoreFocusNode){this.__restoreFocusNode.focus()}this.__restoreFocusNode=null ;var currentOverlay=this._manager.currentOverlay();if(currentOverlay&&this!==cur rentOverlay){currentOverlay._applyFocus()}}},_onCaptureClick:function(event){if( !this.noCancelOnOutsideClick){this.cancel(event)}},_onCaptureFocus:function(even t){if(!this.withBackdrop){return}var path=Polymer.dom(event).path;if(path.indexO f(this)===-1){event.stopPropagation();this._applyFocus()}else{this._focusedChild =path[0]}},_onCaptureEsc:function(event){if(!this.noCancelOnEscKey){this.cancel( event)}},_onCaptureTab:function(event){if(!this.withBackdrop){return}var shift=e vent.shiftKey;var nodeToCheck=shift?this.__firstFocusableNode:this.__lastFocusab leNode;var nodeToSet=shift?this.__lastFocusableNode:this.__firstFocusableNode;va r shouldWrap=false;if(nodeToCheck===nodeToSet){shouldWrap=true}else{var focusedN ode=this._manager.deepActiveElement;shouldWrap=focusedNode===nodeToCheck||focuse dNode===this}if(shouldWrap){event.preventDefault();this._focusedChild=nodeToSet; this._applyFocus()}},_onIronResize:function(){if(this.opened&&!this.__isAnimatin g){this.__onNextAnimationFrame(this.refit)}},_onNodesChange:function(){if(this.o pened&&!this.__isAnimating){this.notifyResize()}},__openedChanged:function(){if( this.opened){this._prepareRenderOpened();this._manager.addOverlay(this);this._ap plyFocus();this._renderOpened()}else{this._manager.removeOverlay(this);this._app lyFocus();this._renderClosed()}},__onNextAnimationFrame:function(callback){if(th is.__raf){window.cancelAnimationFrame(this.__raf)}var self=this;this.__raf=windo w.requestAnimationFrame(function nextAnimationFrame(){self.__raf=null;callback.c all(self)})}};Polymer.IronOverlayBehavior=[Polymer.IronFitBehavior,Polymer.IronR esizableBehavior,Polymer.IronOverlayBehaviorImpl]})();Polymer.NeonAnimatableBeha vior={properties:{animationConfig:{type:Object},entryAnimation:{observer:"_entry AnimationChanged",type:String},exitAnimation:{observer:"_exitAnimationChanged",t ype:String}},_entryAnimationChanged:function(){this.animationConfig=this.animati onConfig||{};this.animationConfig["entry"]=[{name:this.entryAnimation,node:this} ]},_exitAnimationChanged:function(){this.animationConfig=this.animationConfig||{ };this.animationConfig["exit"]=[{name:this.exitAnimation,node:this}]},_copyPrope rties:function(config1,config2){for(var property in config2){config1[property]=c onfig2[property]}},_cloneConfig:function(config){var clone={isClone:true};this._ copyProperties(clone,config);return clone},_getAnimationConfigRecursive:function (type,map,allConfigs){if(!this.animationConfig){return}if(this.animationConfig.v alue&&typeof this.animationConfig.value==="function"){this._warn(this._logf("pla yAnimation","Please put 'animationConfig' inside of your components 'properties' object instead of outside of it."));return}var thisConfig;if(type){thisConfig=t his.animationConfig[type]}else{thisConfig=this.animationConfig}if(!Array.isArray (thisConfig)){thisConfig=[thisConfig]}if(thisConfig){for(var config,index=0;conf ig=thisConfig[index];index++){if(config.animatable){config.animatable._getAnimat ionConfigRecursive(config.type||type,map,allConfigs)}else{if(config.id){var cach edConfig=map[config.id];if(cachedConfig){if(!cachedConfig.isClone){map[config.id ]=this._cloneConfig(cachedConfig);cachedConfig=map[config.id]}this._copyProperti es(cachedConfig,config)}else{map[config.id]=config}}else{allConfigs.push(config) }}}}},getAnimationConfig:function(type){var map={};var allConfigs=[];this._getAn imationConfigRecursive(type,map,allConfigs);for(var key in map){allConfigs.push( map[key])}return allConfigs}};Polymer.NeonAnimationRunnerBehaviorImpl={_configur eAnimations:function(configs){var results=[];if(configs.length>0){for(var config ,index=0;config=configs[index];index++){var neonAnimation=document.createElement (config.name);if(neonAnimation.isNeonAnimation){var result=null;try{result=neonA nimation.configure(config);if(typeof result.cancel!="function"){result=document. timeline.play(result)}}catch(e){result=null;console.warn("Couldnt play","(",conf ig.name,").",e)}if(result){results.push({neonAnimation:neonAnimation,config:conf ig,animation:result})}}else{console.warn(this.is+":",config.name,"not found!")}} }return results},_shouldComplete:function(activeEntries){var finished=true;for(v ar i=0;i<activeEntries.length;i++){if(activeEntries[i].animation.playState!="fin ished"){finished=false;break}}return finished},_complete:function(activeEntries) {for(var i=0;i<activeEntries.length;i++){activeEntries[i].neonAnimation.complete (activeEntries[i].config)}for(var i=0;i<activeEntries.length;i++){activeEntries[ i].animation.cancel()}},playAnimation:function(type,cookie){var configs=this.get AnimationConfig(type);if(!configs){return}this._active=this._active||{};if(this. _active[type]){this._complete(this._active[type]);delete this._active[type]}var activeEntries=this._configureAnimations(configs);if(activeEntries.length==0){thi s.fire("neon-animation-finish",cookie,{bubbles:false});return}this._active[type] =activeEntries;for(var i=0;i<activeEntries.length;i++){activeEntries[i].animatio n.onfinish=function(){if(this._shouldComplete(activeEntries)){this._complete(act iveEntries);delete this._active[type];this.fire("neon-animation-finish",cookie,{ bubbles:false})}}.bind(this)}},cancelAnimation:function(){for(var k in this._ani mations){this._animations[k].cancel()}this._animations={}}};Polymer.NeonAnimatio nRunnerBehavior=[Polymer.NeonAnimatableBehavior,Polymer.NeonAnimationRunnerBehav iorImpl];Polymer.NeonAnimationBehavior={properties:{animationTiming:{type:Object ,value:function(){return{duration:500,easing:"cubic-bezier(0.4, 0, 0.2, 1)",fill :"both"}}}},isNeonAnimation:true,timingFromConfig:function(config){if(config.tim ing){for(var property in config.timing){this.animationTiming[property]=config.ti ming[property]}}return this.animationTiming},setPrefixedProperty:function(node,p roperty,value){var map={transform:["webkitTransform"],transformOrigin:["mozTrans formOrigin","webkitTransformOrigin"]};var prefixes=map[property];for(var prefix, index=0;prefix=prefixes[index];index++){node.style[prefix]=value}node.style[prop erty]=value},complete:function(){}};Polymer({is:"opaque-animation",behaviors:[Po lymer.NeonAnimationBehavior],configure:function(config){var node=config.node;thi s._effect=new KeyframeEffect(node,[{opacity:"1"},{opacity:"1"}],this.timingFromC onfig(config));node.style.opacity="0";return this._effect},complete:function(con fig){config.node.style.opacity=""}});(function(){"use strict";var LAST_TOUCH_POS ITION={pageX:0,pageY:0};var ROOT_TARGET=null;var SCROLLABLE_NODES=[];Polymer.Iro nDropdownScrollManager={get currentLockingElement(){return this._lockingElements [this._lockingElements.length-1]},elementIsScrollLocked:function(element){var cu rrentLockingElement=this.currentLockingElement;if(currentLockingElement===undefi ned)return false;var scrollLocked;if(this._hasCachedLockedElement(element)){retu rn true}if(this._hasCachedUnlockedElement(element)){return false}scrollLocked=!! currentLockingElement&&currentLockingElement!==element&&!this._composedTreeConta ins(currentLockingElement,element);if(scrollLocked){this._lockedElementCache.pus h(element)}else{this._unlockedElementCache.push(element)}return scrollLocked},pu shScrollLock:function(element){if(this._lockingElements.indexOf(element)>=0){ret urn}if(this._lockingElements.length===0){this._lockScrollInteractions()}this._lo ckingElements.push(element);this._lockedElementCache=[];this._unlockedElementCac he=[]},removeScrollLock:function(element){var index=this._lockingElements.indexO f(element);if(index===-1){return}this._lockingElements.splice(index,1);this._loc kedElementCache=[];this._unlockedElementCache=[];if(this._lockingElements.length ===0){this._unlockScrollInteractions()}},_lockingElements:[],_lockedElementCache :null,_unlockedElementCache:null,_hasCachedLockedElement:function(element){retur n this._lockedElementCache.indexOf(element)>-1},_hasCachedUnlockedElement:functi on(element){return this._unlockedElementCache.indexOf(element)>-1},_composedTree Contains:function(element,child){var contentElements;var distributedNodes;var co ntentIndex;var nodeIndex;if(element.contains(child)){return true}contentElements =Polymer.dom(element).querySelectorAll("content");for(contentIndex=0;contentInde x<contentElements.length;++contentIndex){distributedNodes=Polymer.dom(contentEle ments[contentIndex]).getDistributedNodes();for(nodeIndex=0;nodeIndex<distributed Nodes.length;++nodeIndex){if(this._composedTreeContains(distributedNodes[nodeInd ex],child)){return true}}}return false},_scrollInteractionHandler:function(event ){if(event.cancelable&&this._shouldPreventScrolling(event)){event.preventDefault ()}if(event.targetTouches){var touch=event.targetTouches[0];LAST_TOUCH_POSITION. pageX=touch.pageX;LAST_TOUCH_POSITION.pageY=touch.pageY}},_lockScrollInteraction s:function(){this._boundScrollHandler=this._boundScrollHandler||this._scrollInte ractionHandler.bind(this);document.addEventListener("wheel",this._boundScrollHan dler,true);document.addEventListener("mousewheel",this._boundScrollHandler,true) ;document.addEventListener("DOMMouseScroll",this._boundScrollHandler,true);docum ent.addEventListener("touchstart",this._boundScrollHandler,true);
123 6
124 var HistoryGroup; 7 document.addEventListener("touchmove",this._boundScrollHandler,true)},_unlockScr ollInteractions:function(){document.removeEventListener("wheel",this._boundScrol lHandler,true);document.removeEventListener("mousewheel",this._boundScrollHandle r,true);document.removeEventListener("DOMMouseScroll",this._boundScrollHandler,t rue);document.removeEventListener("touchstart",this._boundScrollHandler,true);do cument.removeEventListener("touchmove",this._boundScrollHandler,true)},_shouldPr eventScrolling:function(event){var target=Polymer.dom(event).rootTarget;if(event .type!=="touchmove"&&ROOT_TARGET!==target){ROOT_TARGET=target;SCROLLABLE_NODES=t his._getScrollableNodes(Polymer.dom(event).path)}if(!SCROLLABLE_NODES.length){re turn true}if(event.type==="touchstart"){return false}var info=this._getScrollInf o(event);return!this._getScrollingNode(SCROLLABLE_NODES,info.deltaX,info.deltaY) },_getScrollableNodes:function(nodes){var scrollables=[];var lockingIndex=nodes. indexOf(this.currentLockingElement);for(var i=0;i<=lockingIndex;i++){var node=no des[i];if(node.nodeType===11){continue}var style=node.style;if(style.overflow!== "scroll"&&style.overflow!=="auto"){style=window.getComputedStyle(node)}if(style. overflow==="scroll"||style.overflow==="auto"){scrollables.push(node)}}return scr ollables},_getScrollingNode:function(nodes,deltaX,deltaY){if(!deltaX&&!deltaY){r eturn}var verticalScroll=Math.abs(deltaY)>=Math.abs(deltaX);for(var i=0;i<nodes. length;i++){var node=nodes[i];var canScroll=false;if(verticalScroll){canScroll=d eltaY<0?node.scrollTop>0:node.scrollTop<node.scrollHeight-node.clientHeight}else {canScroll=deltaX<0?node.scrollLeft>0:node.scrollLeft<node.scrollWidth-node.clie ntWidth}if(canScroll){return node}}},_getScrollInfo:function(event){var info={de ltaX:event.deltaX,deltaY:event.deltaY};if("deltaX"in event){}else if("wheelDelta X"in event){info.deltaX=-event.wheelDeltaX;info.deltaY=-event.wheelDeltaY}else i f("axis"in event){info.deltaX=event.axis===1?event.detail:0;info.deltaY=event.ax is===2?event.detail:0}else if(event.targetTouches){var touch=event.targetTouches [0];info.deltaX=LAST_TOUCH_POSITION.pageX-touch.pageX;info.deltaY=LAST_TOUCH_POS ITION.pageY-touch.pageY}return info}}})();(function(){"use strict";Polymer({is:" iron-dropdown",behaviors:[Polymer.IronControlState,Polymer.IronA11yKeysBehavior, Polymer.IronOverlayBehavior,Polymer.NeonAnimationRunnerBehavior],properties:{hor izontalAlign:{type:String,value:"left",reflectToAttribute:true},verticalAlign:{t ype:String,value:"top",reflectToAttribute:true},openAnimationConfig:{type:Object },closeAnimationConfig:{type:Object},focusTarget:{type:Object},noAnimations:{typ e:Boolean,value:false},allowOutsideScroll:{type:Boolean,value:false},_boundOnCap tureScroll:{type:Function,value:function(){return this._onCaptureScroll.bind(thi s)}}},listeners:{"neon-animation-finish":"_onNeonAnimationFinish"},observers:["_ updateOverlayPosition(positionTarget, verticalAlign, horizontalAlign, verticalOf fset, horizontalOffset)"],get containedElement(){return Polymer.dom(this.$.conte nt).getDistributedNodes()[0]},get _focusTarget(){return this.focusTarget||this.c ontainedElement},ready:function(){this._scrollTop=0;this._scrollLeft=0;this._ref itOnScrollRAF=null},attached:function(){if(!this.sizingTarget||this.sizingTarget ===this){this.sizingTarget=this.containedElement}},detached:function(){this.canc elAnimation();document.removeEventListener("scroll",this._boundOnCaptureScroll); Polymer.IronDropdownScrollManager.removeScrollLock(this)},_openedChanged:functio n(){if(this.opened&&this.disabled){this.cancel()}else{this.cancelAnimation();thi s._updateAnimationConfig();this._saveScrollPosition();if(this.opened){document.a ddEventListener("scroll",this._boundOnCaptureScroll);!this.allowOutsideScroll&&P olymer.IronDropdownScrollManager.pushScrollLock(this)}else{document.removeEventL istener("scroll",this._boundOnCaptureScroll);Polymer.IronDropdownScrollManager.r emoveScrollLock(this)}Polymer.IronOverlayBehaviorImpl._openedChanged.apply(this, arguments)}},_renderOpened:function(){if(!this.noAnimations&&this.animationConfi g.open){this.$.contentWrapper.classList.add("animating");this.playAnimation("ope n")}else{Polymer.IronOverlayBehaviorImpl._renderOpened.apply(this,arguments)}},_ renderClosed:function(){if(!this.noAnimations&&this.animationConfig.close){this. $.contentWrapper.classList.add("animating");this.playAnimation("close")}else{Pol ymer.IronOverlayBehaviorImpl._renderClosed.apply(this,arguments)}},_onNeonAnimat ionFinish:function(){this.$.contentWrapper.classList.remove("animating");if(this .opened){this._finishRenderOpened()}else{this._finishRenderClosed()}},_onCapture Scroll:function(){if(!this.allowOutsideScroll){this._restoreScrollPosition()}els e{this._refitOnScrollRAF&&window.cancelAnimationFrame(this._refitOnScrollRAF);th is._refitOnScrollRAF=window.requestAnimationFrame(this.refit.bind(this))}},_save ScrollPosition:function(){if(document.scrollingElement){this._scrollTop=document .scrollingElement.scrollTop;this._scrollLeft=document.scrollingElement.scrollLef t}else{this._scrollTop=Math.max(document.documentElement.scrollTop,document.body .scrollTop);this._scrollLeft=Math.max(document.documentElement.scrollLeft,docume nt.body.scrollLeft)}},_restoreScrollPosition:function(){if(document.scrollingEle ment){document.scrollingElement.scrollTop=this._scrollTop;document.scrollingElem ent.scrollLeft=this._scrollLeft}else{document.documentElement.scrollTop=this._sc rollTop;document.documentElement.scrollLeft=this._scrollLeft;document.body.scrol lTop=this._scrollTop;document.body.scrollLeft=this._scrollLeft}},_updateAnimatio nConfig:function(){var animations=(this.openAnimationConfig||[]).concat(this.clo seAnimationConfig||[]);for(var i=0;i<animations.length;i++){animations[i].node=t his.containedElement}this.animationConfig={open:this.openAnimationConfig,close:t his.closeAnimationConfig}},_updateOverlayPosition:function(){if(this.isAttached) {this.notifyResize()}},_applyFocus:function(){var focusTarget=this.focusTarget|| this.containedElement;if(focusTarget&&this.opened&&!this.noAutoFocus){focusTarge t.focus()}else{Polymer.IronOverlayBehaviorImpl._applyFocus.apply(this,arguments) }}})})();Polymer({is:"fade-in-animation",behaviors:[Polymer.NeonAnimationBehavio r],configure:function(config){var node=config.node;this._effect=new KeyframeEffe ct(node,[{opacity:"0"},{opacity:"1"}],this.timingFromConfig(config));return this ._effect}});Polymer({is:"fade-out-animation",behaviors:[Polymer.NeonAnimationBeh avior],configure:function(config){var node=config.node;this._effect=new Keyframe Effect(node,[{opacity:"1"},{opacity:"0"}],this.timingFromConfig(config));return this._effect}});Polymer({is:"paper-menu-grow-height-animation",behaviors:[Polyme r.NeonAnimationBehavior],configure:function(config){var node=config.node;var rec t=node.getBoundingClientRect();var height=rect.height;this._effect=new KeyframeE ffect(node,[{height:height/2+"px"},{height:height+"px"}],this.timingFromConfig(c onfig));return this._effect}});Polymer({is:"paper-menu-grow-width-animation",beh aviors:[Polymer.NeonAnimationBehavior],configure:function(config){var node=confi g.node;var rect=node.getBoundingClientRect();var width=rect.width;this._effect=n ew KeyframeEffect(node,[{width:width/2+"px"},{width:width+"px"}],this.timingFrom Config(config));return this._effect}});Polymer({is:"paper-menu-shrink-width-anim ation",behaviors:[Polymer.NeonAnimationBehavior],configure:function(config){var node=config.node;var rect=node.getBoundingClientRect();var width=rect.width;this ._effect=new KeyframeEffect(node,[{width:width+"px"},{width:width-width/20+"px"} ],this.timingFromConfig(config));return this._effect}});Polymer({is:"paper-menu- shrink-height-animation",behaviors:[Polymer.NeonAnimationBehavior],configure:fun ction(config){var node=config.node;var rect=node.getBoundingClientRect();var hei ght=rect.height;var top=rect.top;this.setPrefixedProperty(node,"transformOrigin" ,"0 0");this._effect=new KeyframeEffect(node,[{height:height+"px",transform:"tra nslateY(0)"},{height:height/2+"px",transform:"translateY(-20px)"}],this.timingFr omConfig(config));return this._effect}});
125
126 Polymer({
127 is: 'history-grouped-list',
128 behaviors: [ HistoryListBehavior ],
129 properties: {
130 historyData: {
131 type: Array
132 },
133 groupedHistoryData_: {
134 type: Array
135 },
136 searchedTerm: {
137 type: String,
138 value: ''
139 },
140 range: {
141 type: Number
142 },
143 queryStartTime: String,
144 queryEndTime: String
145 },
146 observers: [ 'updateGroupedHistoryData_(range, historyData)' ],
147 createHistoryDomains_: function(visits) {
148 var domainIndexes = {};
149 var domains = [];
150 for (var i = 0, visit; visit = visits[i]; i++) {
151 var domain = visit.domain;
152 if (domainIndexes[domain] == undefined) {
153 domainIndexes[domain] = domains.length;
154 domains.push({
155 domain: domain,
156 visits: [],
157 expanded: false,
158 rendered: false
159 });
160 }
161 domains[domainIndexes[domain]].visits.push(visit);
162 }
163 var sortByVisits = function(a, b) {
164 return b.visits.length - a.visits.length;
165 };
166 domains.sort(sortByVisits);
167 return domains;
168 },
169 updateGroupedHistoryData_: function() {
170 if (this.historyData.length == 0) {
171 this.groupedHistoryData_ = [];
172 return;
173 }
174 if (this.range == HistoryRange.WEEK) {
175 var days = [];
176 var currentDayVisits = [ this.historyData[0] ];
177 var pushCurrentDay = function() {
178 days.push({
179 title: this.searchedTerm ? currentDayVisits[0].dateShort : currentDayV isits[0].dateRelativeDay,
180 domains: this.createHistoryDomains_(currentDayVisits)
181 });
182 }.bind(this);
183 var visitsSameDay = function(a, b) {
184 if (this.searchedTerm) return a.dateShort == b.dateShort;
185 return a.dateRelativeDay == b.dateRelativeDay;
186 }.bind(this);
187 for (var i = 1; i < this.historyData.length; i++) {
188 var visit = this.historyData[i];
189 if (!visitsSameDay(visit, currentDayVisits[0])) {
190 pushCurrentDay();
191 currentDayVisits = [];
192 }
193 currentDayVisits.push(visit);
194 }
195 pushCurrentDay();
196 this.groupedHistoryData_ = days;
197 } else if (this.range == HistoryRange.MONTH) {
198 this.groupedHistoryData_ = [ {
199 title: this.queryStartTime + ' – ' + this.queryEndTime,
200 domains: this.createHistoryDomains_(this.historyData)
201 } ];
202 }
203 },
204 toggleDomainExpanded_: function(e) {
205 var collapse = e.currentTarget.parentNode.querySelector('iron-collapse');
206 e.model.set('domain.rendered', true);
207 setTimeout(function() {
208 collapse.toggle();
209 }, 0);
210 },
211 needsTimeGap_: function(groupIndex, domainIndex, itemIndex) {
212 var visits = this.groupedHistoryData_[groupIndex].domains[domainIndex].visit s;
213 return md_history.HistoryItem.needsTimeGap(visits, itemIndex, this.searchedT erm);
214 },
215 pathForItem_: function(groupIndex, domainIndex, itemIndex) {
216 return [ 'groupedHistoryData_', groupIndex, 'domains', domainIndex, 'visits' , itemIndex ].join('.');
217 },
218 getWebsiteIconStyle_: function(domain) {
219 return 'background-image: ' + cr.icon.getFavicon(domain.visits[0].url);
220 },
221 getDropdownIcon_: function(expanded) {
222 return expanded ? 'cr:expand-less' : 'cr:expand-more';
223 }
224 });
225
226 Polymer.PaperButtonBehaviorImpl = {
227 properties: {
228 elevation: {
229 type: Number,
230 reflectToAttribute: true,
231 readOnly: true
232 }
233 },
234 observers: [ '_calculateElevation(focused, disabled, active, pressed, received FocusFromKeyboard)', '_computeKeyboardClass(receivedFocusFromKeyboard)' ],
235 hostAttributes: {
236 role: 'button',
237 tabindex: '0',
238 animated: true
239 },
240 _calculateElevation: function() {
241 var e = 1;
242 if (this.disabled) {
243 e = 0;
244 } else if (this.active || this.pressed) {
245 e = 4;
246 } else if (this.receivedFocusFromKeyboard) {
247 e = 3;
248 }
249 this._setElevation(e);
250 },
251 _computeKeyboardClass: function(receivedFocusFromKeyboard) {
252 this.toggleClass('keyboard-focus', receivedFocusFromKeyboard);
253 },
254 _spaceKeyDownHandler: function(event) {
255 Polymer.IronButtonStateImpl._spaceKeyDownHandler.call(this, event);
256 if (this.hasRipple() && this.getRipple().ripples.length < 1) {
257 this._ripple.uiDownAction();
258 }
259 },
260 _spaceKeyUpHandler: function(event) {
261 Polymer.IronButtonStateImpl._spaceKeyUpHandler.call(this, event);
262 if (this.hasRipple()) {
263 this._ripple.uiUpAction();
264 }
265 }
266 };
267
268 Polymer.PaperButtonBehavior = [ Polymer.IronButtonState, Polymer.IronControlStat e, Polymer.PaperRippleBehavior, Polymer.PaperButtonBehaviorImpl ];
269
270 Polymer({
271 is: 'paper-button',
272 behaviors: [ Polymer.PaperButtonBehavior ],
273 properties: {
274 raised: {
275 type: Boolean,
276 reflectToAttribute: true,
277 value: false,
278 observer: '_calculateElevation'
279 }
280 },
281 _calculateElevation: function() {
282 if (!this.raised) {
283 this._setElevation(0);
284 } else {
285 Polymer.PaperButtonBehaviorImpl._calculateElevation.apply(this);
286 }
287 }
288 });
289
290 Polymer.PaperItemBehaviorImpl = {
291 hostAttributes: {
292 role: 'option',
293 tabindex: '0'
294 }
295 };
296
297 Polymer.PaperItemBehavior = [ Polymer.IronButtonState, Polymer.IronControlState, Polymer.PaperItemBehaviorImpl ];
298
299 Polymer({
300 is: 'paper-item',
301 behaviors: [ Polymer.PaperItemBehavior ]
302 });
303
304 Polymer.IronFitBehavior = {
305 properties: {
306 sizingTarget: {
307 type: Object,
308 value: function() {
309 return this;
310 }
311 },
312 fitInto: {
313 type: Object,
314 value: window
315 },
316 noOverlap: {
317 type: Boolean
318 },
319 positionTarget: {
320 type: Element
321 },
322 horizontalAlign: {
323 type: String
324 },
325 verticalAlign: {
326 type: String
327 },
328 dynamicAlign: {
329 type: Boolean
330 },
331 horizontalOffset: {
332 type: Number,
333 value: 0,
334 notify: true
335 },
336 verticalOffset: {
337 type: Number,
338 value: 0,
339 notify: true
340 },
341 autoFitOnAttach: {
342 type: Boolean,
343 value: false
344 },
345 _fitInfo: {
346 type: Object
347 }
348 },
349 get _fitWidth() {
350 var fitWidth;
351 if (this.fitInto === window) {
352 fitWidth = this.fitInto.innerWidth;
353 } else {
354 fitWidth = this.fitInto.getBoundingClientRect().width;
355 }
356 return fitWidth;
357 },
358 get _fitHeight() {
359 var fitHeight;
360 if (this.fitInto === window) {
361 fitHeight = this.fitInto.innerHeight;
362 } else {
363 fitHeight = this.fitInto.getBoundingClientRect().height;
364 }
365 return fitHeight;
366 },
367 get _fitLeft() {
368 var fitLeft;
369 if (this.fitInto === window) {
370 fitLeft = 0;
371 } else {
372 fitLeft = this.fitInto.getBoundingClientRect().left;
373 }
374 return fitLeft;
375 },
376 get _fitTop() {
377 var fitTop;
378 if (this.fitInto === window) {
379 fitTop = 0;
380 } else {
381 fitTop = this.fitInto.getBoundingClientRect().top;
382 }
383 return fitTop;
384 },
385 get _defaultPositionTarget() {
386 var parent = Polymer.dom(this).parentNode;
387 if (parent && parent.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
388 parent = parent.host;
389 }
390 return parent;
391 },
392 get _localeHorizontalAlign() {
393 if (this._isRTL) {
394 if (this.horizontalAlign === 'right') {
395 return 'left';
396 }
397 if (this.horizontalAlign === 'left') {
398 return 'right';
399 }
400 }
401 return this.horizontalAlign;
402 },
403 attached: function() {
404 this._isRTL = window.getComputedStyle(this).direction == 'rtl';
405 this.positionTarget = this.positionTarget || this._defaultPositionTarget;
406 if (this.autoFitOnAttach) {
407 if (window.getComputedStyle(this).display === 'none') {
408 setTimeout(function() {
409 this.fit();
410 }.bind(this));
411 } else {
412 this.fit();
413 }
414 }
415 },
416 fit: function() {
417 this.position();
418 this.constrain();
419 this.center();
420 },
421 _discoverInfo: function() {
422 if (this._fitInfo) {
423 return;
424 }
425 var target = window.getComputedStyle(this);
426 var sizer = window.getComputedStyle(this.sizingTarget);
427 this._fitInfo = {
428 inlineStyle: {
429 top: this.style.top || '',
430 left: this.style.left || '',
431 position: this.style.position || ''
432 },
433 sizerInlineStyle: {
434 maxWidth: this.sizingTarget.style.maxWidth || '',
435 maxHeight: this.sizingTarget.style.maxHeight || '',
436 boxSizing: this.sizingTarget.style.boxSizing || ''
437 },
438 positionedBy: {
439 vertically: target.top !== 'auto' ? 'top' : target.bottom !== 'auto' ? ' bottom' : null,
440 horizontally: target.left !== 'auto' ? 'left' : target.right !== 'auto' ? 'right' : null
441 },
442 sizedBy: {
443 height: sizer.maxHeight !== 'none',
444 width: sizer.maxWidth !== 'none',
445 minWidth: parseInt(sizer.minWidth, 10) || 0,
446 minHeight: parseInt(sizer.minHeight, 10) || 0
447 },
448 margin: {
449 top: parseInt(target.marginTop, 10) || 0,
450 right: parseInt(target.marginRight, 10) || 0,
451 bottom: parseInt(target.marginBottom, 10) || 0,
452 left: parseInt(target.marginLeft, 10) || 0
453 }
454 };
455 if (this.verticalOffset) {
456 this._fitInfo.margin.top = this._fitInfo.margin.bottom = this.verticalOffs et;
457 this._fitInfo.inlineStyle.marginTop = this.style.marginTop || '';
458 this._fitInfo.inlineStyle.marginBottom = this.style.marginBottom || '';
459 this.style.marginTop = this.style.marginBottom = this.verticalOffset + 'px ';
460 }
461 if (this.horizontalOffset) {
462 this._fitInfo.margin.left = this._fitInfo.margin.right = this.horizontalOf fset;
463 this._fitInfo.inlineStyle.marginLeft = this.style.marginLeft || '';
464 this._fitInfo.inlineStyle.marginRight = this.style.marginRight || '';
465 this.style.marginLeft = this.style.marginRight = this.horizontalOffset + ' px';
466 }
467 },
468 resetFit: function() {
469 var info = this._fitInfo || {};
470 for (var property in info.sizerInlineStyle) {
471 this.sizingTarget.style[property] = info.sizerInlineStyle[property];
472 }
473 for (var property in info.inlineStyle) {
474 this.style[property] = info.inlineStyle[property];
475 }
476 this._fitInfo = null;
477 },
478 refit: function() {
479 var scrollLeft = this.sizingTarget.scrollLeft;
480 var scrollTop = this.sizingTarget.scrollTop;
481 this.resetFit();
482 this.fit();
483 this.sizingTarget.scrollLeft = scrollLeft;
484 this.sizingTarget.scrollTop = scrollTop;
485 },
486 position: function() {
487 if (!this.horizontalAlign && !this.verticalAlign) {
488 return;
489 }
490 this._discoverInfo();
491 this.style.position = 'fixed';
492 this.sizingTarget.style.boxSizing = 'border-box';
493 this.style.left = '0px';
494 this.style.top = '0px';
495 var rect = this.getBoundingClientRect();
496 var positionRect = this.__getNormalizedRect(this.positionTarget);
497 var fitRect = this.__getNormalizedRect(this.fitInto);
498 var margin = this._fitInfo.margin;
499 var size = {
500 width: rect.width + margin.left + margin.right,
501 height: rect.height + margin.top + margin.bottom
502 };
503 var position = this.__getPosition(this._localeHorizontalAlign, this.vertical Align, size, positionRect, fitRect);
504 var left = position.left + margin.left;
505 var top = position.top + margin.top;
506 var right = Math.min(fitRect.right - margin.right, left + rect.width);
507 var bottom = Math.min(fitRect.bottom - margin.bottom, top + rect.height);
508 var minWidth = this._fitInfo.sizedBy.minWidth;
509 var minHeight = this._fitInfo.sizedBy.minHeight;
510 if (left < margin.left) {
511 left = margin.left;
512 if (right - left < minWidth) {
513 left = right - minWidth;
514 }
515 }
516 if (top < margin.top) {
517 top = margin.top;
518 if (bottom - top < minHeight) {
519 top = bottom - minHeight;
520 }
521 }
522 this.sizingTarget.style.maxWidth = right - left + 'px';
523 this.sizingTarget.style.maxHeight = bottom - top + 'px';
524 this.style.left = left - rect.left + 'px';
525 this.style.top = top - rect.top + 'px';
526 },
527 constrain: function() {
528 if (this.horizontalAlign || this.verticalAlign) {
529 return;
530 }
531 this._discoverInfo();
532 var info = this._fitInfo;
533 if (!info.positionedBy.vertically) {
534 this.style.position = 'fixed';
535 this.style.top = '0px';
536 }
537 if (!info.positionedBy.horizontally) {
538 this.style.position = 'fixed';
539 this.style.left = '0px';
540 }
541 this.sizingTarget.style.boxSizing = 'border-box';
542 var rect = this.getBoundingClientRect();
543 if (!info.sizedBy.height) {
544 this.__sizeDimension(rect, info.positionedBy.vertically, 'top', 'bottom', 'Height');
545 }
546 if (!info.sizedBy.width) {
547 this.__sizeDimension(rect, info.positionedBy.horizontally, 'left', 'right' , 'Width');
548 }
549 },
550 _sizeDimension: function(rect, positionedBy, start, end, extent) {
551 this.__sizeDimension(rect, positionedBy, start, end, extent);
552 },
553 __sizeDimension: function(rect, positionedBy, start, end, extent) {
554 var info = this._fitInfo;
555 var fitRect = this.__getNormalizedRect(this.fitInto);
556 var max = extent === 'Width' ? fitRect.width : fitRect.height;
557 var flip = positionedBy === end;
558 var offset = flip ? max - rect[end] : rect[start];
559 var margin = info.margin[flip ? start : end];
560 var offsetExtent = 'offset' + extent;
561 var sizingOffset = this[offsetExtent] - this.sizingTarget[offsetExtent];
562 this.sizingTarget.style['max' + extent] = max - margin - offset - sizingOffs et + 'px';
563 },
564 center: function() {
565 if (this.horizontalAlign || this.verticalAlign) {
566 return;
567 }
568 this._discoverInfo();
569 var positionedBy = this._fitInfo.positionedBy;
570 if (positionedBy.vertically && positionedBy.horizontally) {
571 return;
572 }
573 this.style.position = 'fixed';
574 if (!positionedBy.vertically) {
575 this.style.top = '0px';
576 }
577 if (!positionedBy.horizontally) {
578 this.style.left = '0px';
579 }
580 var rect = this.getBoundingClientRect();
581 var fitRect = this.__getNormalizedRect(this.fitInto);
582 if (!positionedBy.vertically) {
583 var top = fitRect.top - rect.top + (fitRect.height - rect.height) / 2;
584 this.style.top = top + 'px';
585 }
586 if (!positionedBy.horizontally) {
587 var left = fitRect.left - rect.left + (fitRect.width - rect.width) / 2;
588 this.style.left = left + 'px';
589 }
590 },
591 __getNormalizedRect: function(target) {
592 if (target === document.documentElement || target === window) {
593 return {
594 top: 0,
595 left: 0,
596 width: window.innerWidth,
597 height: window.innerHeight,
598 right: window.innerWidth,
599 bottom: window.innerHeight
600 };
601 }
602 return target.getBoundingClientRect();
603 },
604 __getCroppedArea: function(position, size, fitRect) {
605 var verticalCrop = Math.min(0, position.top) + Math.min(0, fitRect.bottom - (position.top + size.height));
606 var horizontalCrop = Math.min(0, position.left) + Math.min(0, fitRect.right - (position.left + size.width));
607 return Math.abs(verticalCrop) * size.width + Math.abs(horizontalCrop) * size .height;
608 },
609 __getPosition: function(hAlign, vAlign, size, positionRect, fitRect) {
610 var positions = [ {
611 verticalAlign: 'top',
612 horizontalAlign: 'left',
613 top: positionRect.top,
614 left: positionRect.left
615 }, {
616 verticalAlign: 'top',
617 horizontalAlign: 'right',
618 top: positionRect.top,
619 left: positionRect.right - size.width
620 }, {
621 verticalAlign: 'bottom',
622 horizontalAlign: 'left',
623 top: positionRect.bottom - size.height,
624 left: positionRect.left
625 }, {
626 verticalAlign: 'bottom',
627 horizontalAlign: 'right',
628 top: positionRect.bottom - size.height,
629 left: positionRect.right - size.width
630 } ];
631 if (this.noOverlap) {
632 for (var i = 0, l = positions.length; i < l; i++) {
633 var copy = {};
634 for (var key in positions[i]) {
635 copy[key] = positions[i][key];
636 }
637 positions.push(copy);
638 }
639 positions[0].top = positions[1].top += positionRect.height;
640 positions[2].top = positions[3].top -= positionRect.height;
641 positions[4].left = positions[6].left += positionRect.width;
642 positions[5].left = positions[7].left -= positionRect.width;
643 }
644 vAlign = vAlign === 'auto' ? null : vAlign;
645 hAlign = hAlign === 'auto' ? null : hAlign;
646 var position;
647 for (var i = 0; i < positions.length; i++) {
648 var pos = positions[i];
649 if (!this.dynamicAlign && !this.noOverlap && pos.verticalAlign === vAlign && pos.horizontalAlign === hAlign) {
650 position = pos;
651 break;
652 }
653 var alignOk = (!vAlign || pos.verticalAlign === vAlign) && (!hAlign || pos .horizontalAlign === hAlign);
654 if (!this.dynamicAlign && !alignOk) {
655 continue;
656 }
657 position = position || pos;
658 pos.croppedArea = this.__getCroppedArea(pos, size, fitRect);
659 var diff = pos.croppedArea - position.croppedArea;
660 if (diff < 0 || diff === 0 && alignOk) {
661 position = pos;
662 }
663 if (position.croppedArea === 0 && alignOk) {
664 break;
665 }
666 }
667 return position;
668 }
669 };
670
671 (function() {
672 'use strict';
673 Polymer({
674 is: 'iron-overlay-backdrop',
675 properties: {
676 opened: {
677 reflectToAttribute: true,
678 type: Boolean,
679 value: false,
680 observer: '_openedChanged'
681 }
682 },
683 listeners: {
684 transitionend: '_onTransitionend'
685 },
686 created: function() {
687 this.__openedRaf = null;
688 },
689 attached: function() {
690 this.opened && this._openedChanged(this.opened);
691 },
692 prepare: function() {
693 if (this.opened && !this.parentNode) {
694 Polymer.dom(document.body).appendChild(this);
695 }
696 },
697 open: function() {
698 this.opened = true;
699 },
700 close: function() {
701 this.opened = false;
702 },
703 complete: function() {
704 if (!this.opened && this.parentNode === document.body) {
705 Polymer.dom(this.parentNode).removeChild(this);
706 }
707 },
708 _onTransitionend: function(event) {
709 if (event && event.target === this) {
710 this.complete();
711 }
712 },
713 _openedChanged: function(opened) {
714 if (opened) {
715 this.prepare();
716 } else {
717 var cs = window.getComputedStyle(this);
718 if (cs.transitionDuration === '0s' || cs.opacity == 0) {
719 this.complete();
720 }
721 }
722 if (!this.isAttached) {
723 return;
724 }
725 if (this.__openedRaf) {
726 window.cancelAnimationFrame(this.__openedRaf);
727 this.__openedRaf = null;
728 }
729 this.scrollTop = this.scrollTop;
730 this.__openedRaf = window.requestAnimationFrame(function() {
731 this.__openedRaf = null;
732 this.toggleClass('opened', this.opened);
733 }.bind(this));
734 }
735 });
736 })();
737
738 Polymer.IronOverlayManagerClass = function() {
739 this._overlays = [];
740 this._minimumZ = 101;
741 this._backdropElement = null;
742 Polymer.Gestures.add(document, 'tap', this._onCaptureClick.bind(this));
743 document.addEventListener('focus', this._onCaptureFocus.bind(this), true);
744 document.addEventListener('keydown', this._onCaptureKeyDown.bind(this), true);
745 };
746
747 Polymer.IronOverlayManagerClass.prototype = {
748 constructor: Polymer.IronOverlayManagerClass,
749 get backdropElement() {
750 if (!this._backdropElement) {
751 this._backdropElement = document.createElement('iron-overlay-backdrop');
752 }
753 return this._backdropElement;
754 },
755 get deepActiveElement() {
756 var active = document.activeElement || document.body;
757 while (active.root && Polymer.dom(active.root).activeElement) {
758 active = Polymer.dom(active.root).activeElement;
759 }
760 return active;
761 },
762 _bringOverlayAtIndexToFront: function(i) {
763 var overlay = this._overlays[i];
764 if (!overlay) {
765 return;
766 }
767 var lastI = this._overlays.length - 1;
768 var currentOverlay = this._overlays[lastI];
769 if (currentOverlay && this._shouldBeBehindOverlay(overlay, currentOverlay)) {
770 lastI--;
771 }
772 if (i >= lastI) {
773 return;
774 }
775 var minimumZ = Math.max(this.currentOverlayZ(), this._minimumZ);
776 if (this._getZ(overlay) <= minimumZ) {
777 this._applyOverlayZ(overlay, minimumZ);
778 }
779 while (i < lastI) {
780 this._overlays[i] = this._overlays[i + 1];
781 i++;
782 }
783 this._overlays[lastI] = overlay;
784 },
785 addOrRemoveOverlay: function(overlay) {
786 if (overlay.opened) {
787 this.addOverlay(overlay);
788 } else {
789 this.removeOverlay(overlay);
790 }
791 },
792 addOverlay: function(overlay) {
793 var i = this._overlays.indexOf(overlay);
794 if (i >= 0) {
795 this._bringOverlayAtIndexToFront(i);
796 this.trackBackdrop();
797 return;
798 }
799 var insertionIndex = this._overlays.length;
800 var currentOverlay = this._overlays[insertionIndex - 1];
801 var minimumZ = Math.max(this._getZ(currentOverlay), this._minimumZ);
802 var newZ = this._getZ(overlay);
803 if (currentOverlay && this._shouldBeBehindOverlay(overlay, currentOverlay)) {
804 this._applyOverlayZ(currentOverlay, minimumZ);
805 insertionIndex--;
806 var previousOverlay = this._overlays[insertionIndex - 1];
807 minimumZ = Math.max(this._getZ(previousOverlay), this._minimumZ);
808 }
809 if (newZ <= minimumZ) {
810 this._applyOverlayZ(overlay, minimumZ);
811 }
812 this._overlays.splice(insertionIndex, 0, overlay);
813 this.trackBackdrop();
814 },
815 removeOverlay: function(overlay) {
816 var i = this._overlays.indexOf(overlay);
817 if (i === -1) {
818 return;
819 }
820 this._overlays.splice(i, 1);
821 this.trackBackdrop();
822 },
823 currentOverlay: function() {
824 var i = this._overlays.length - 1;
825 return this._overlays[i];
826 },
827 currentOverlayZ: function() {
828 return this._getZ(this.currentOverlay());
829 },
830 ensureMinimumZ: function(minimumZ) {
831 this._minimumZ = Math.max(this._minimumZ, minimumZ);
832 },
833 focusOverlay: function() {
834 var current = this.currentOverlay();
835 if (current) {
836 current._applyFocus();
837 }
838 },
839 trackBackdrop: function() {
840 var overlay = this._overlayWithBackdrop();
841 if (!overlay && !this._backdropElement) {
842 return;
843 }
844 this.backdropElement.style.zIndex = this._getZ(overlay) - 1;
845 this.backdropElement.opened = !!overlay;
846 },
847 getBackdrops: function() {
848 var backdrops = [];
849 for (var i = 0; i < this._overlays.length; i++) {
850 if (this._overlays[i].withBackdrop) {
851 backdrops.push(this._overlays[i]);
852 }
853 }
854 return backdrops;
855 },
856 backdropZ: function() {
857 return this._getZ(this._overlayWithBackdrop()) - 1;
858 },
859 _overlayWithBackdrop: function() {
860 for (var i = 0; i < this._overlays.length; i++) {
861 if (this._overlays[i].withBackdrop) {
862 return this._overlays[i];
863 }
864 }
865 },
866 _getZ: function(overlay) {
867 var z = this._minimumZ;
868 if (overlay) {
869 var z1 = Number(overlay.style.zIndex || window.getComputedStyle(overlay).z Index);
870 if (z1 === z1) {
871 z = z1;
872 }
873 }
874 return z;
875 },
876 _setZ: function(element, z) {
877 element.style.zIndex = z;
878 },
879 _applyOverlayZ: function(overlay, aboveZ) {
880 this._setZ(overlay, aboveZ + 2);
881 },
882 _overlayInPath: function(path) {
883 path = path || [];
884 for (var i = 0; i < path.length; i++) {
885 if (path[i]._manager === this) {
886 return path[i];
887 }
888 }
889 },
890 _onCaptureClick: function(event) {
891 var overlay = this.currentOverlay();
892 if (overlay && this._overlayInPath(Polymer.dom(event).path) !== overlay) {
893 overlay._onCaptureClick(event);
894 }
895 },
896 _onCaptureFocus: function(event) {
897 var overlay = this.currentOverlay();
898 if (overlay) {
899 overlay._onCaptureFocus(event);
900 }
901 },
902 _onCaptureKeyDown: function(event) {
903 var overlay = this.currentOverlay();
904 if (overlay) {
905 if (Polymer.IronA11yKeysBehavior.keyboardEventMatchesKeys(event, 'esc')) {
906 overlay._onCaptureEsc(event);
907 } else if (Polymer.IronA11yKeysBehavior.keyboardEventMatchesKeys(event, 't ab')) {
908 overlay._onCaptureTab(event);
909 }
910 }
911 },
912 _shouldBeBehindOverlay: function(overlay1, overlay2) {
913 return !overlay1.alwaysOnTop && overlay2.alwaysOnTop;
914 }
915 };
916
917 Polymer.IronOverlayManager = new Polymer.IronOverlayManagerClass();
918
919 (function() {
920 'use strict';
921 Polymer.IronOverlayBehaviorImpl = {
922 properties: {
923 opened: {
924 observer: '_openedChanged',
925 type: Boolean,
926 value: false,
927 notify: true
928 },
929 canceled: {
930 observer: '_canceledChanged',
931 readOnly: true,
932 type: Boolean,
933 value: false
934 },
935 withBackdrop: {
936 observer: '_withBackdropChanged',
937 type: Boolean
938 },
939 noAutoFocus: {
940 type: Boolean,
941 value: false
942 },
943 noCancelOnEscKey: {
944 type: Boolean,
945 value: false
946 },
947 noCancelOnOutsideClick: {
948 type: Boolean,
949 value: false
950 },
951 closingReason: {
952 type: Object
953 },
954 restoreFocusOnClose: {
955 type: Boolean,
956 value: false
957 },
958 alwaysOnTop: {
959 type: Boolean
960 },
961 _manager: {
962 type: Object,
963 value: Polymer.IronOverlayManager
964 },
965 _focusedChild: {
966 type: Object
967 }
968 },
969 listeners: {
970 'iron-resize': '_onIronResize'
971 },
972 get backdropElement() {
973 return this._manager.backdropElement;
974 },
975 get _focusNode() {
976 return this._focusedChild || Polymer.dom(this).querySelector('[autofocus]' ) || this;
977 },
978 get _focusableNodes() {
979 var FOCUSABLE_WITH_DISABLED = [ 'a[href]', 'area[href]', 'iframe', '[tabin dex]', '[contentEditable=true]' ];
980 var FOCUSABLE_WITHOUT_DISABLED = [ 'input', 'select', 'textarea', 'button' ];
981 var selector = FOCUSABLE_WITH_DISABLED.join(':not([tabindex="-1"]),') + ': not([tabindex="-1"]),' + FOCUSABLE_WITHOUT_DISABLED.join(':not([disabled]):not([ tabindex="-1"]),') + ':not([disabled]):not([tabindex="-1"])';
982 var focusables = Polymer.dom(this).querySelectorAll(selector);
983 if (this.tabIndex >= 0) {
984 focusables.splice(0, 0, this);
985 }
986 return focusables.sort(function(a, b) {
987 if (a.tabIndex === b.tabIndex) {
988 return 0;
989 }
990 if (a.tabIndex === 0 || a.tabIndex > b.tabIndex) {
991 return 1;
992 }
993 return -1;
994 });
995 },
996 ready: function() {
997 this.__isAnimating = false;
998 this.__shouldRemoveTabIndex = false;
999 this.__firstFocusableNode = this.__lastFocusableNode = null;
1000 this.__raf = null;
1001 this.__restoreFocusNode = null;
1002 this._ensureSetup();
1003 },
1004 attached: function() {
1005 if (this.opened) {
1006 this._openedChanged(this.opened);
1007 }
1008 this._observer = Polymer.dom(this).observeNodes(this._onNodesChange);
1009 },
1010 detached: function() {
1011 Polymer.dom(this).unobserveNodes(this._observer);
1012 this._observer = null;
1013 if (this.__raf) {
1014 window.cancelAnimationFrame(this.__raf);
1015 this.__raf = null;
1016 }
1017 this._manager.removeOverlay(this);
1018 },
1019 toggle: function() {
1020 this._setCanceled(false);
1021 this.opened = !this.opened;
1022 },
1023 open: function() {
1024 this._setCanceled(false);
1025 this.opened = true;
1026 },
1027 close: function() {
1028 this._setCanceled(false);
1029 this.opened = false;
1030 },
1031 cancel: function(event) {
1032 var cancelEvent = this.fire('iron-overlay-canceled', event, {
1033 cancelable: true
1034 });
1035 if (cancelEvent.defaultPrevented) {
1036 return;
1037 }
1038 this._setCanceled(true);
1039 this.opened = false;
1040 },
1041 _ensureSetup: function() {
1042 if (this._overlaySetup) {
1043 return;
1044 }
1045 this._overlaySetup = true;
1046 this.style.outline = 'none';
1047 this.style.display = 'none';
1048 },
1049 _openedChanged: function(opened) {
1050 if (opened) {
1051 this.removeAttribute('aria-hidden');
1052 } else {
1053 this.setAttribute('aria-hidden', 'true');
1054 }
1055 if (!this.isAttached) {
1056 return;
1057 }
1058 this.__isAnimating = true;
1059 this.__onNextAnimationFrame(this.__openedChanged);
1060 },
1061 _canceledChanged: function() {
1062 this.closingReason = this.closingReason || {};
1063 this.closingReason.canceled = this.canceled;
1064 },
1065 _withBackdropChanged: function() {
1066 if (this.withBackdrop && !this.hasAttribute('tabindex')) {
1067 this.setAttribute('tabindex', '-1');
1068 this.__shouldRemoveTabIndex = true;
1069 } else if (this.__shouldRemoveTabIndex) {
1070 this.removeAttribute('tabindex');
1071 this.__shouldRemoveTabIndex = false;
1072 }
1073 if (this.opened && this.isAttached) {
1074 this._manager.trackBackdrop();
1075 }
1076 },
1077 _prepareRenderOpened: function() {
1078 this.__restoreFocusNode = this._manager.deepActiveElement;
1079 this._preparePositioning();
1080 this.refit();
1081 this._finishPositioning();
1082 if (this.noAutoFocus && document.activeElement === this._focusNode) {
1083 this._focusNode.blur();
1084 this.__restoreFocusNode.focus();
1085 }
1086 },
1087 _renderOpened: function() {
1088 this._finishRenderOpened();
1089 },
1090 _renderClosed: function() {
1091 this._finishRenderClosed();
1092 },
1093 _finishRenderOpened: function() {
1094 this.notifyResize();
1095 this.__isAnimating = false;
1096 var focusableNodes = this._focusableNodes;
1097 this.__firstFocusableNode = focusableNodes[0];
1098 this.__lastFocusableNode = focusableNodes[focusableNodes.length - 1];
1099 this.fire('iron-overlay-opened');
1100 },
1101 _finishRenderClosed: function() {
1102 this.style.display = 'none';
1103 this.style.zIndex = '';
1104 this.notifyResize();
1105 this.__isAnimating = false;
1106 this.fire('iron-overlay-closed', this.closingReason);
1107 },
1108 _preparePositioning: function() {
1109 this.style.transition = this.style.webkitTransition = 'none';
1110 this.style.transform = this.style.webkitTransform = 'none';
1111 this.style.display = '';
1112 },
1113 _finishPositioning: function() {
1114 this.style.display = 'none';
1115 this.scrollTop = this.scrollTop;
1116 this.style.transition = this.style.webkitTransition = '';
1117 this.style.transform = this.style.webkitTransform = '';
1118 this.style.display = '';
1119 this.scrollTop = this.scrollTop;
1120 },
1121 _applyFocus: function() {
1122 if (this.opened) {
1123 if (!this.noAutoFocus) {
1124 this._focusNode.focus();
1125 }
1126 } else {
1127 this._focusNode.blur();
1128 this._focusedChild = null;
1129 if (this.restoreFocusOnClose && this.__restoreFocusNode) {
1130 this.__restoreFocusNode.focus();
1131 }
1132 this.__restoreFocusNode = null;
1133 var currentOverlay = this._manager.currentOverlay();
1134 if (currentOverlay && this !== currentOverlay) {
1135 currentOverlay._applyFocus();
1136 }
1137 }
1138 },
1139 _onCaptureClick: function(event) {
1140 if (!this.noCancelOnOutsideClick) {
1141 this.cancel(event);
1142 }
1143 },
1144 _onCaptureFocus: function(event) {
1145 if (!this.withBackdrop) {
1146 return;
1147 }
1148 var path = Polymer.dom(event).path;
1149 if (path.indexOf(this) === -1) {
1150 event.stopPropagation();
1151 this._applyFocus();
1152 } else {
1153 this._focusedChild = path[0];
1154 }
1155 },
1156 _onCaptureEsc: function(event) {
1157 if (!this.noCancelOnEscKey) {
1158 this.cancel(event);
1159 }
1160 },
1161 _onCaptureTab: function(event) {
1162 if (!this.withBackdrop) {
1163 return;
1164 }
1165 var shift = event.shiftKey;
1166 var nodeToCheck = shift ? this.__firstFocusableNode : this.__lastFocusable Node;
1167 var nodeToSet = shift ? this.__lastFocusableNode : this.__firstFocusableNo de;
1168 var shouldWrap = false;
1169 if (nodeToCheck === nodeToSet) {
1170 shouldWrap = true;
1171 } else {
1172 var focusedNode = this._manager.deepActiveElement;
1173 shouldWrap = focusedNode === nodeToCheck || focusedNode === this;
1174 }
1175 if (shouldWrap) {
1176 event.preventDefault();
1177 this._focusedChild = nodeToSet;
1178 this._applyFocus();
1179 }
1180 },
1181 _onIronResize: function() {
1182 if (this.opened && !this.__isAnimating) {
1183 this.__onNextAnimationFrame(this.refit);
1184 }
1185 },
1186 _onNodesChange: function() {
1187 if (this.opened && !this.__isAnimating) {
1188 this.notifyResize();
1189 }
1190 },
1191 __openedChanged: function() {
1192 if (this.opened) {
1193 this._prepareRenderOpened();
1194 this._manager.addOverlay(this);
1195 this._applyFocus();
1196 this._renderOpened();
1197 } else {
1198 this._manager.removeOverlay(this);
1199 this._applyFocus();
1200 this._renderClosed();
1201 }
1202 },
1203 __onNextAnimationFrame: function(callback) {
1204 if (this.__raf) {
1205 window.cancelAnimationFrame(this.__raf);
1206 }
1207 var self = this;
1208 this.__raf = window.requestAnimationFrame(function nextAnimationFrame() {
1209 self.__raf = null;
1210 callback.call(self);
1211 });
1212 }
1213 };
1214 Polymer.IronOverlayBehavior = [ Polymer.IronFitBehavior, Polymer.IronResizable Behavior, Polymer.IronOverlayBehaviorImpl ];
1215 })();
1216
1217 Polymer.NeonAnimatableBehavior = {
1218 properties: {
1219 animationConfig: {
1220 type: Object
1221 },
1222 entryAnimation: {
1223 observer: '_entryAnimationChanged',
1224 type: String
1225 },
1226 exitAnimation: {
1227 observer: '_exitAnimationChanged',
1228 type: String
1229 }
1230 },
1231 _entryAnimationChanged: function() {
1232 this.animationConfig = this.animationConfig || {};
1233 this.animationConfig['entry'] = [ {
1234 name: this.entryAnimation,
1235 node: this
1236 } ];
1237 },
1238 _exitAnimationChanged: function() {
1239 this.animationConfig = this.animationConfig || {};
1240 this.animationConfig['exit'] = [ {
1241 name: this.exitAnimation,
1242 node: this
1243 } ];
1244 },
1245 _copyProperties: function(config1, config2) {
1246 for (var property in config2) {
1247 config1[property] = config2[property];
1248 }
1249 },
1250 _cloneConfig: function(config) {
1251 var clone = {
1252 isClone: true
1253 };
1254 this._copyProperties(clone, config);
1255 return clone;
1256 },
1257 _getAnimationConfigRecursive: function(type, map, allConfigs) {
1258 if (!this.animationConfig) {
1259 return;
1260 }
1261 if (this.animationConfig.value && typeof this.animationConfig.value === 'fun ction') {
1262 this._warn(this._logf('playAnimation', "Please put 'animationConfig' insid e of your components 'properties' object instead of outside of it."));
1263 return;
1264 }
1265 var thisConfig;
1266 if (type) {
1267 thisConfig = this.animationConfig[type];
1268 } else {
1269 thisConfig = this.animationConfig;
1270 }
1271 if (!Array.isArray(thisConfig)) {
1272 thisConfig = [ thisConfig ];
1273 }
1274 if (thisConfig) {
1275 for (var config, index = 0; config = thisConfig[index]; index++) {
1276 if (config.animatable) {
1277 config.animatable._getAnimationConfigRecursive(config.type || type, ma p, allConfigs);
1278 } else {
1279 if (config.id) {
1280 var cachedConfig = map[config.id];
1281 if (cachedConfig) {
1282 if (!cachedConfig.isClone) {
1283 map[config.id] = this._cloneConfig(cachedConfig);
1284 cachedConfig = map[config.id];
1285 }
1286 this._copyProperties(cachedConfig, config);
1287 } else {
1288 map[config.id] = config;
1289 }
1290 } else {
1291 allConfigs.push(config);
1292 }
1293 }
1294 }
1295 }
1296 },
1297 getAnimationConfig: function(type) {
1298 var map = {};
1299 var allConfigs = [];
1300 this._getAnimationConfigRecursive(type, map, allConfigs);
1301 for (var key in map) {
1302 allConfigs.push(map[key]);
1303 }
1304 return allConfigs;
1305 }
1306 };
1307
1308 Polymer.NeonAnimationRunnerBehaviorImpl = {
1309 _configureAnimations: function(configs) {
1310 var results = [];
1311 if (configs.length > 0) {
1312 for (var config, index = 0; config = configs[index]; index++) {
1313 var neonAnimation = document.createElement(config.name);
1314 if (neonAnimation.isNeonAnimation) {
1315 var result = null;
1316 try {
1317 result = neonAnimation.configure(config);
1318 if (typeof result.cancel != 'function') {
1319 result = document.timeline.play(result);
1320 }
1321 } catch (e) {
1322 result = null;
1323 console.warn('Couldnt play', '(', config.name, ').', e);
1324 }
1325 if (result) {
1326 results.push({
1327 neonAnimation: neonAnimation,
1328 config: config,
1329 animation: result
1330 });
1331 }
1332 } else {
1333 console.warn(this.is + ':', config.name, 'not found!');
1334 }
1335 }
1336 }
1337 return results;
1338 },
1339 _shouldComplete: function(activeEntries) {
1340 var finished = true;
1341 for (var i = 0; i < activeEntries.length; i++) {
1342 if (activeEntries[i].animation.playState != 'finished') {
1343 finished = false;
1344 break;
1345 }
1346 }
1347 return finished;
1348 },
1349 _complete: function(activeEntries) {
1350 for (var i = 0; i < activeEntries.length; i++) {
1351 activeEntries[i].neonAnimation.complete(activeEntries[i].config);
1352 }
1353 for (var i = 0; i < activeEntries.length; i++) {
1354 activeEntries[i].animation.cancel();
1355 }
1356 },
1357 playAnimation: function(type, cookie) {
1358 var configs = this.getAnimationConfig(type);
1359 if (!configs) {
1360 return;
1361 }
1362 this._active = this._active || {};
1363 if (this._active[type]) {
1364 this._complete(this._active[type]);
1365 delete this._active[type];
1366 }
1367 var activeEntries = this._configureAnimations(configs);
1368 if (activeEntries.length == 0) {
1369 this.fire('neon-animation-finish', cookie, {
1370 bubbles: false
1371 });
1372 return;
1373 }
1374 this._active[type] = activeEntries;
1375 for (var i = 0; i < activeEntries.length; i++) {
1376 activeEntries[i].animation.onfinish = function() {
1377 if (this._shouldComplete(activeEntries)) {
1378 this._complete(activeEntries);
1379 delete this._active[type];
1380 this.fire('neon-animation-finish', cookie, {
1381 bubbles: false
1382 });
1383 }
1384 }.bind(this);
1385 }
1386 },
1387 cancelAnimation: function() {
1388 for (var k in this._animations) {
1389 this._animations[k].cancel();
1390 }
1391 this._animations = {};
1392 }
1393 };
1394
1395 Polymer.NeonAnimationRunnerBehavior = [ Polymer.NeonAnimatableBehavior, Polymer. NeonAnimationRunnerBehaviorImpl ];
1396
1397 Polymer.NeonAnimationBehavior = {
1398 properties: {
1399 animationTiming: {
1400 type: Object,
1401 value: function() {
1402 return {
1403 duration: 500,
1404 easing: 'cubic-bezier(0.4, 0, 0.2, 1)',
1405 fill: 'both'
1406 };
1407 }
1408 }
1409 },
1410 isNeonAnimation: true,
1411 timingFromConfig: function(config) {
1412 if (config.timing) {
1413 for (var property in config.timing) {
1414 this.animationTiming[property] = config.timing[property];
1415 }
1416 }
1417 return this.animationTiming;
1418 },
1419 setPrefixedProperty: function(node, property, value) {
1420 var map = {
1421 transform: [ 'webkitTransform' ],
1422 transformOrigin: [ 'mozTransformOrigin', 'webkitTransformOrigin' ]
1423 };
1424 var prefixes = map[property];
1425 for (var prefix, index = 0; prefix = prefixes[index]; index++) {
1426 node.style[prefix] = value;
1427 }
1428 node.style[property] = value;
1429 },
1430 complete: function() {}
1431 };
1432
1433 Polymer({
1434 is: 'opaque-animation',
1435 behaviors: [ Polymer.NeonAnimationBehavior ],
1436 configure: function(config) {
1437 var node = config.node;
1438 this._effect = new KeyframeEffect(node, [ {
1439 opacity: '1'
1440 }, {
1441 opacity: '1'
1442 } ], this.timingFromConfig(config));
1443 node.style.opacity = '0';
1444 return this._effect;
1445 },
1446 complete: function(config) {
1447 config.node.style.opacity = '';
1448 }
1449 });
1450
1451 (function() {
1452 'use strict';
1453 var LAST_TOUCH_POSITION = {
1454 pageX: 0,
1455 pageY: 0
1456 };
1457 var ROOT_TARGET = null;
1458 var SCROLLABLE_NODES = [];
1459 Polymer.IronDropdownScrollManager = {
1460 get currentLockingElement() {
1461 return this._lockingElements[this._lockingElements.length - 1];
1462 },
1463 elementIsScrollLocked: function(element) {
1464 var currentLockingElement = this.currentLockingElement;
1465 if (currentLockingElement === undefined) return false;
1466 var scrollLocked;
1467 if (this._hasCachedLockedElement(element)) {
1468 return true;
1469 }
1470 if (this._hasCachedUnlockedElement(element)) {
1471 return false;
1472 }
1473 scrollLocked = !!currentLockingElement && currentLockingElement !== elemen t && !this._composedTreeContains(currentLockingElement, element);
1474 if (scrollLocked) {
1475 this._lockedElementCache.push(element);
1476 } else {
1477 this._unlockedElementCache.push(element);
1478 }
1479 return scrollLocked;
1480 },
1481 pushScrollLock: function(element) {
1482 if (this._lockingElements.indexOf(element) >= 0) {
1483 return;
1484 }
1485 if (this._lockingElements.length === 0) {
1486 this._lockScrollInteractions();
1487 }
1488 this._lockingElements.push(element);
1489 this._lockedElementCache = [];
1490 this._unlockedElementCache = [];
1491 },
1492 removeScrollLock: function(element) {
1493 var index = this._lockingElements.indexOf(element);
1494 if (index === -1) {
1495 return;
1496 }
1497 this._lockingElements.splice(index, 1);
1498 this._lockedElementCache = [];
1499 this._unlockedElementCache = [];
1500 if (this._lockingElements.length === 0) {
1501 this._unlockScrollInteractions();
1502 }
1503 },
1504 _lockingElements: [],
1505 _lockedElementCache: null,
1506 _unlockedElementCache: null,
1507 _hasCachedLockedElement: function(element) {
1508 return this._lockedElementCache.indexOf(element) > -1;
1509 },
1510 _hasCachedUnlockedElement: function(element) {
1511 return this._unlockedElementCache.indexOf(element) > -1;
1512 },
1513 _composedTreeContains: function(element, child) {
1514 var contentElements;
1515 var distributedNodes;
1516 var contentIndex;
1517 var nodeIndex;
1518 if (element.contains(child)) {
1519 return true;
1520 }
1521 contentElements = Polymer.dom(element).querySelectorAll('content');
1522 for (contentIndex = 0; contentIndex < contentElements.length; ++contentInd ex) {
1523 distributedNodes = Polymer.dom(contentElements[contentIndex]).getDistrib utedNodes();
1524 for (nodeIndex = 0; nodeIndex < distributedNodes.length; ++nodeIndex) {
1525 if (this._composedTreeContains(distributedNodes[nodeIndex], child)) {
1526 return true;
1527 }
1528 }
1529 }
1530 return false;
1531 },
1532 _scrollInteractionHandler: function(event) {
1533 if (event.cancelable && this._shouldPreventScrolling(event)) {
1534 event.preventDefault();
1535 }
1536 if (event.targetTouches) {
1537 var touch = event.targetTouches[0];
1538 LAST_TOUCH_POSITION.pageX = touch.pageX;
1539 LAST_TOUCH_POSITION.pageY = touch.pageY;
1540 }
1541 },
1542 _lockScrollInteractions: function() {
1543 this._boundScrollHandler = this._boundScrollHandler || this._scrollInterac tionHandler.bind(this);
1544 document.addEventListener('wheel', this._boundScrollHandler, true);
1545 document.addEventListener('mousewheel', this._boundScrollHandler, true);
1546 document.addEventListener('DOMMouseScroll', this._boundScrollHandler, true );
1547 document.addEventListener('touchstart', this._boundScrollHandler, true);
1548 document.addEventListener('touchmove', this._boundScrollHandler, true);
1549 },
1550 _unlockScrollInteractions: function() {
1551 document.removeEventListener('wheel', this._boundScrollHandler, true);
1552 document.removeEventListener('mousewheel', this._boundScrollHandler, true) ;
1553 document.removeEventListener('DOMMouseScroll', this._boundScrollHandler, t rue);
1554 document.removeEventListener('touchstart', this._boundScrollHandler, true) ;
1555 document.removeEventListener('touchmove', this._boundScrollHandler, true);
1556 },
1557 _shouldPreventScrolling: function(event) {
1558 var target = Polymer.dom(event).rootTarget;
1559 if (event.type !== 'touchmove' && ROOT_TARGET !== target) {
1560 ROOT_TARGET = target;
1561 SCROLLABLE_NODES = this._getScrollableNodes(Polymer.dom(event).path);
1562 }
1563 if (!SCROLLABLE_NODES.length) {
1564 return true;
1565 }
1566 if (event.type === 'touchstart') {
1567 return false;
1568 }
1569 var info = this._getScrollInfo(event);
1570 return !this._getScrollingNode(SCROLLABLE_NODES, info.deltaX, info.deltaY) ;
1571 },
1572 _getScrollableNodes: function(nodes) {
1573 var scrollables = [];
1574 var lockingIndex = nodes.indexOf(this.currentLockingElement);
1575 for (var i = 0; i <= lockingIndex; i++) {
1576 var node = nodes[i];
1577 if (node.nodeType === 11) {
1578 continue;
1579 }
1580 var style = node.style;
1581 if (style.overflow !== 'scroll' && style.overflow !== 'auto') {
1582 style = window.getComputedStyle(node);
1583 }
1584 if (style.overflow === 'scroll' || style.overflow === 'auto') {
1585 scrollables.push(node);
1586 }
1587 }
1588 return scrollables;
1589 },
1590 _getScrollingNode: function(nodes, deltaX, deltaY) {
1591 if (!deltaX && !deltaY) {
1592 return;
1593 }
1594 var verticalScroll = Math.abs(deltaY) >= Math.abs(deltaX);
1595 for (var i = 0; i < nodes.length; i++) {
1596 var node = nodes[i];
1597 var canScroll = false;
1598 if (verticalScroll) {
1599 canScroll = deltaY < 0 ? node.scrollTop > 0 : node.scrollTop < node.sc rollHeight - node.clientHeight;
1600 } else {
1601 canScroll = deltaX < 0 ? node.scrollLeft > 0 : node.scrollLeft < node. scrollWidth - node.clientWidth;
1602 }
1603 if (canScroll) {
1604 return node;
1605 }
1606 }
1607 },
1608 _getScrollInfo: function(event) {
1609 var info = {
1610 deltaX: event.deltaX,
1611 deltaY: event.deltaY
1612 };
1613 if ('deltaX' in event) {} else if ('wheelDeltaX' in event) {
1614 info.deltaX = -event.wheelDeltaX;
1615 info.deltaY = -event.wheelDeltaY;
1616 } else if ('axis' in event) {
1617 info.deltaX = event.axis === 1 ? event.detail : 0;
1618 info.deltaY = event.axis === 2 ? event.detail : 0;
1619 } else if (event.targetTouches) {
1620 var touch = event.targetTouches[0];
1621 info.deltaX = LAST_TOUCH_POSITION.pageX - touch.pageX;
1622 info.deltaY = LAST_TOUCH_POSITION.pageY - touch.pageY;
1623 }
1624 return info;
1625 }
1626 };
1627 })();
1628
1629 (function() {
1630 'use strict';
1631 Polymer({
1632 is: 'iron-dropdown',
1633 behaviors: [ Polymer.IronControlState, Polymer.IronA11yKeysBehavior, Polymer .IronOverlayBehavior, Polymer.NeonAnimationRunnerBehavior ],
1634 properties: {
1635 horizontalAlign: {
1636 type: String,
1637 value: 'left',
1638 reflectToAttribute: true
1639 },
1640 verticalAlign: {
1641 type: String,
1642 value: 'top',
1643 reflectToAttribute: true
1644 },
1645 openAnimationConfig: {
1646 type: Object
1647 },
1648 closeAnimationConfig: {
1649 type: Object
1650 },
1651 focusTarget: {
1652 type: Object
1653 },
1654 noAnimations: {
1655 type: Boolean,
1656 value: false
1657 },
1658 allowOutsideScroll: {
1659 type: Boolean,
1660 value: false
1661 },
1662 _boundOnCaptureScroll: {
1663 type: Function,
1664 value: function() {
1665 return this._onCaptureScroll.bind(this);
1666 }
1667 }
1668 },
1669 listeners: {
1670 'neon-animation-finish': '_onNeonAnimationFinish'
1671 },
1672 observers: [ '_updateOverlayPosition(positionTarget, verticalAlign, horizont alAlign, verticalOffset, horizontalOffset)' ],
1673 get containedElement() {
1674 return Polymer.dom(this.$.content).getDistributedNodes()[0];
1675 },
1676 get _focusTarget() {
1677 return this.focusTarget || this.containedElement;
1678 },
1679 ready: function() {
1680 this._scrollTop = 0;
1681 this._scrollLeft = 0;
1682 this._refitOnScrollRAF = null;
1683 },
1684 attached: function() {
1685 if (!this.sizingTarget || this.sizingTarget === this) {
1686 this.sizingTarget = this.containedElement;
1687 }
1688 },
1689 detached: function() {
1690 this.cancelAnimation();
1691 document.removeEventListener('scroll', this._boundOnCaptureScroll);
1692 Polymer.IronDropdownScrollManager.removeScrollLock(this);
1693 },
1694 _openedChanged: function() {
1695 if (this.opened && this.disabled) {
1696 this.cancel();
1697 } else {
1698 this.cancelAnimation();
1699 this._updateAnimationConfig();
1700 this._saveScrollPosition();
1701 if (this.opened) {
1702 document.addEventListener('scroll', this._boundOnCaptureScroll);
1703 !this.allowOutsideScroll && Polymer.IronDropdownScrollManager.pushScro llLock(this);
1704 } else {
1705 document.removeEventListener('scroll', this._boundOnCaptureScroll);
1706 Polymer.IronDropdownScrollManager.removeScrollLock(this);
1707 }
1708 Polymer.IronOverlayBehaviorImpl._openedChanged.apply(this, arguments);
1709 }
1710 },
1711 _renderOpened: function() {
1712 if (!this.noAnimations && this.animationConfig.open) {
1713 this.$.contentWrapper.classList.add('animating');
1714 this.playAnimation('open');
1715 } else {
1716 Polymer.IronOverlayBehaviorImpl._renderOpened.apply(this, arguments);
1717 }
1718 },
1719 _renderClosed: function() {
1720 if (!this.noAnimations && this.animationConfig.close) {
1721 this.$.contentWrapper.classList.add('animating');
1722 this.playAnimation('close');
1723 } else {
1724 Polymer.IronOverlayBehaviorImpl._renderClosed.apply(this, arguments);
1725 }
1726 },
1727 _onNeonAnimationFinish: function() {
1728 this.$.contentWrapper.classList.remove('animating');
1729 if (this.opened) {
1730 this._finishRenderOpened();
1731 } else {
1732 this._finishRenderClosed();
1733 }
1734 },
1735 _onCaptureScroll: function() {
1736 if (!this.allowOutsideScroll) {
1737 this._restoreScrollPosition();
1738 } else {
1739 this._refitOnScrollRAF && window.cancelAnimationFrame(this._refitOnScrol lRAF);
1740 this._refitOnScrollRAF = window.requestAnimationFrame(this.refit.bind(th is));
1741 }
1742 },
1743 _saveScrollPosition: function() {
1744 if (document.scrollingElement) {
1745 this._scrollTop = document.scrollingElement.scrollTop;
1746 this._scrollLeft = document.scrollingElement.scrollLeft;
1747 } else {
1748 this._scrollTop = Math.max(document.documentElement.scrollTop, document. body.scrollTop);
1749 this._scrollLeft = Math.max(document.documentElement.scrollLeft, documen t.body.scrollLeft);
1750 }
1751 },
1752 _restoreScrollPosition: function() {
1753 if (document.scrollingElement) {
1754 document.scrollingElement.scrollTop = this._scrollTop;
1755 document.scrollingElement.scrollLeft = this._scrollLeft;
1756 } else {
1757 document.documentElement.scrollTop = this._scrollTop;
1758 document.documentElement.scrollLeft = this._scrollLeft;
1759 document.body.scrollTop = this._scrollTop;
1760 document.body.scrollLeft = this._scrollLeft;
1761 }
1762 },
1763 _updateAnimationConfig: function() {
1764 var animations = (this.openAnimationConfig || []).concat(this.closeAnimati onConfig || []);
1765 for (var i = 0; i < animations.length; i++) {
1766 animations[i].node = this.containedElement;
1767 }
1768 this.animationConfig = {
1769 open: this.openAnimationConfig,
1770 close: this.closeAnimationConfig
1771 };
1772 },
1773 _updateOverlayPosition: function() {
1774 if (this.isAttached) {
1775 this.notifyResize();
1776 }
1777 },
1778 _applyFocus: function() {
1779 var focusTarget = this.focusTarget || this.containedElement;
1780 if (focusTarget && this.opened && !this.noAutoFocus) {
1781 focusTarget.focus();
1782 } else {
1783 Polymer.IronOverlayBehaviorImpl._applyFocus.apply(this, arguments);
1784 }
1785 }
1786 });
1787 })();
1788
1789 Polymer({
1790 is: 'fade-in-animation',
1791 behaviors: [ Polymer.NeonAnimationBehavior ],
1792 configure: function(config) {
1793 var node = config.node;
1794 this._effect = new KeyframeEffect(node, [ {
1795 opacity: '0'
1796 }, {
1797 opacity: '1'
1798 } ], this.timingFromConfig(config));
1799 return this._effect;
1800 }
1801 });
1802
1803 Polymer({
1804 is: 'fade-out-animation',
1805 behaviors: [ Polymer.NeonAnimationBehavior ],
1806 configure: function(config) {
1807 var node = config.node;
1808 this._effect = new KeyframeEffect(node, [ {
1809 opacity: '1'
1810 }, {
1811 opacity: '0'
1812 } ], this.timingFromConfig(config));
1813 return this._effect;
1814 }
1815 });
1816
1817 Polymer({
1818 is: 'paper-menu-grow-height-animation',
1819 behaviors: [ Polymer.NeonAnimationBehavior ],
1820 configure: function(config) {
1821 var node = config.node;
1822 var rect = node.getBoundingClientRect();
1823 var height = rect.height;
1824 this._effect = new KeyframeEffect(node, [ {
1825 height: height / 2 + 'px'
1826 }, {
1827 height: height + 'px'
1828 } ], this.timingFromConfig(config));
1829 return this._effect;
1830 }
1831 });
1832
1833 Polymer({
1834 is: 'paper-menu-grow-width-animation',
1835 behaviors: [ Polymer.NeonAnimationBehavior ],
1836 configure: function(config) {
1837 var node = config.node;
1838 var rect = node.getBoundingClientRect();
1839 var width = rect.width;
1840 this._effect = new KeyframeEffect(node, [ {
1841 width: width / 2 + 'px'
1842 }, {
1843 width: width + 'px'
1844 } ], this.timingFromConfig(config));
1845 return this._effect;
1846 }
1847 });
1848
1849 Polymer({
1850 is: 'paper-menu-shrink-width-animation',
1851 behaviors: [ Polymer.NeonAnimationBehavior ],
1852 configure: function(config) {
1853 var node = config.node;
1854 var rect = node.getBoundingClientRect();
1855 var width = rect.width;
1856 this._effect = new KeyframeEffect(node, [ {
1857 width: width + 'px'
1858 }, {
1859 width: width - width / 20 + 'px'
1860 } ], this.timingFromConfig(config));
1861 return this._effect;
1862 }
1863 });
1864
1865 Polymer({
1866 is: 'paper-menu-shrink-height-animation',
1867 behaviors: [ Polymer.NeonAnimationBehavior ],
1868 configure: function(config) {
1869 var node = config.node;
1870 var rect = node.getBoundingClientRect();
1871 var height = rect.height;
1872 var top = rect.top;
1873 this.setPrefixedProperty(node, 'transformOrigin', '0 0');
1874 this._effect = new KeyframeEffect(node, [ {
1875 height: height + 'px',
1876 transform: 'translateY(0)'
1877 }, {
1878 height: height / 2 + 'px',
1879 transform: 'translateY(-20px)'
1880 } ], this.timingFromConfig(config));
1881 return this._effect;
1882 }
1883 });
1884
1885 // Copyright 2016 The Chromium Authors. All rights reserved. 8 // Copyright 2016 The Chromium Authors. All rights reserved.
1886 // Use of this source code is governed by a BSD-style license that can be 9 // Use of this source code is governed by a BSD-style license that can be
1887 // found in the LICENSE file. 10 // found in the LICENSE file.
1888 var SLIDE_CUBIC_BEZIER = 'cubic-bezier(0.3, 0.95, 0.5, 1)'; 11 var SLIDE_CUBIC_BEZIER="cubic-bezier(0.3, 0.95, 0.5, 1)";Polymer({is:"cr-shared- menu",behaviors:[Polymer.IronA11yKeysBehavior],properties:{menuOpen:{type:Boolea n,observer:"menuOpenChanged_",value:false,notify:true},itemData:{type:Object,val ue:null},keyEventTarget:{type:Object,value:function(){return this.$.menu}},openA nimationConfig:{type:Object,value:function(){return[{name:"fade-in-animation",ti ming:{delay:50,duration:200}},{name:"paper-menu-grow-width-animation",timing:{de lay:50,duration:150,easing:SLIDE_CUBIC_BEZIER}},{name:"paper-menu-grow-height-an imation",timing:{delay:100,duration:275,easing:SLIDE_CUBIC_BEZIER}}]}},closeAnim ationConfig:{type:Object,value:function(){return[{name:"fade-out-animation",timi ng:{duration:150}}]}}},keyBindings:{tab:"onTabPressed_"},listeners:{"dropdown.ir on-overlay-canceled":"onOverlayCanceled_"},lastAnchor_:null,firstFocus_:null,las tFocus_:null,attached:function(){window.addEventListener("resize",this.closeMenu .bind(this))},closeMenu:function(){if(this.root.activeElement==null){this.$.drop down.restoreFocusOnClose=false}this.menuOpen=false},openMenu:function(anchor,opt _itemData){if(this.lastAnchor_==anchor&&this.menuOpen)return;if(this.menuOpen)th is.closeMenu();this.itemData=opt_itemData||null;this.lastAnchor_=anchor;this.$.d ropdown.restoreFocusOnClose=true;var focusableChildren=Polymer.dom(this).querySe lectorAll("[tabindex]:not([disabled]):not([hidden]),"+"button:not([disabled]):no t([hidden])");if(focusableChildren.length>0){this.$.dropdown.focusTarget=focusab leChildren[0];this.firstFocus_=focusableChildren[0];this.lastFocus_=focusableChi ldren[focusableChildren.length-1]}this.$.dropdown.positionTarget=anchor;this.men uOpen=true},toggleMenu:function(anchor,opt_itemData){if(anchor==this.lastAnchor_ &&this.menuOpen)this.closeMenu();else this.openMenu(anchor,opt_itemData)},onTabP ressed_:function(e){if(!this.firstFocus_||!this.lastFocus_)return;var toFocus;va r keyEvent=e.detail.keyboardEvent;if(keyEvent.shiftKey&&keyEvent.target==this.fi rstFocus_)toFocus=this.lastFocus_;else if(!keyEvent.shiftKey&&keyEvent.target==t his.lastFocus_)toFocus=this.firstFocus_;if(!toFocus)return;e.preventDefault();to Focus.focus()},menuOpenChanged_:function(){if(!this.menuOpen){this.itemData=null ;this.lastAnchor_=null}},onOverlayCanceled_:function(e){if(e.detail.type=="tap") this.$.dropdown.restoreFocusOnClose=false}});Polymer({is:"paper-icon-button-ligh t","extends":"button",behaviors:[Polymer.PaperRippleBehavior],listeners:{down:"_ rippleDown",up:"_rippleUp",focus:"_rippleDown",blur:"_rippleUp"},_rippleDown:fun ction(){this.getRipple().downAction()},_rippleUp:function(){this.getRipple().upA ction()},ensureRipple:function(var_args){var lastRipple=this._ripple;Polymer.Pap erRippleBehavior.ensureRipple.apply(this,arguments);if(this._ripple&&this._rippl e!==lastRipple){this._ripple.center=true;this._ripple.classList.add("circle")}}} );
1889
1890 Polymer({
1891 is: 'cr-shared-menu',
1892 behaviors: [ Polymer.IronA11yKeysBehavior ],
1893 properties: {
1894 menuOpen: {
1895 type: Boolean,
1896 observer: 'menuOpenChanged_',
1897 value: false,
1898 notify: true
1899 },
1900 itemData: {
1901 type: Object,
1902 value: null
1903 },
1904 keyEventTarget: {
1905 type: Object,
1906 value: function() {
1907 return this.$.menu;
1908 }
1909 },
1910 openAnimationConfig: {
1911 type: Object,
1912 value: function() {
1913 return [ {
1914 name: 'fade-in-animation',
1915 timing: {
1916 delay: 50,
1917 duration: 200
1918 }
1919 }, {
1920 name: 'paper-menu-grow-width-animation',
1921 timing: {
1922 delay: 50,
1923 duration: 150,
1924 easing: SLIDE_CUBIC_BEZIER
1925 }
1926 }, {
1927 name: 'paper-menu-grow-height-animation',
1928 timing: {
1929 delay: 100,
1930 duration: 275,
1931 easing: SLIDE_CUBIC_BEZIER
1932 }
1933 } ];
1934 }
1935 },
1936 closeAnimationConfig: {
1937 type: Object,
1938 value: function() {
1939 return [ {
1940 name: 'fade-out-animation',
1941 timing: {
1942 duration: 150
1943 }
1944 } ];
1945 }
1946 }
1947 },
1948 keyBindings: {
1949 tab: 'onTabPressed_'
1950 },
1951 listeners: {
1952 'dropdown.iron-overlay-canceled': 'onOverlayCanceled_'
1953 },
1954 lastAnchor_: null,
1955 firstFocus_: null,
1956 lastFocus_: null,
1957 attached: function() {
1958 window.addEventListener('resize', this.closeMenu.bind(this));
1959 },
1960 closeMenu: function() {
1961 if (this.root.activeElement == null) {
1962 this.$.dropdown.restoreFocusOnClose = false;
1963 }
1964 this.menuOpen = false;
1965 },
1966 openMenu: function(anchor, opt_itemData) {
1967 if (this.lastAnchor_ == anchor && this.menuOpen) return;
1968 if (this.menuOpen) this.closeMenu();
1969 this.itemData = opt_itemData || null;
1970 this.lastAnchor_ = anchor;
1971 this.$.dropdown.restoreFocusOnClose = true;
1972 var focusableChildren = Polymer.dom(this).querySelectorAll('[tabindex]:not([ disabled]):not([hidden]),' + 'button:not([disabled]):not([hidden])');
1973 if (focusableChildren.length > 0) {
1974 this.$.dropdown.focusTarget = focusableChildren[0];
1975 this.firstFocus_ = focusableChildren[0];
1976 this.lastFocus_ = focusableChildren[focusableChildren.length - 1];
1977 }
1978 this.$.dropdown.positionTarget = anchor;
1979 this.menuOpen = true;
1980 },
1981 toggleMenu: function(anchor, opt_itemData) {
1982 if (anchor == this.lastAnchor_ && this.menuOpen) this.closeMenu(); else this .openMenu(anchor, opt_itemData);
1983 },
1984 onTabPressed_: function(e) {
1985 if (!this.firstFocus_ || !this.lastFocus_) return;
1986 var toFocus;
1987 var keyEvent = e.detail.keyboardEvent;
1988 if (keyEvent.shiftKey && keyEvent.target == this.firstFocus_) toFocus = this .lastFocus_; else if (!keyEvent.shiftKey && keyEvent.target == this.lastFocus_) toFocus = this.firstFocus_;
1989 if (!toFocus) return;
1990 e.preventDefault();
1991 toFocus.focus();
1992 },
1993 menuOpenChanged_: function() {
1994 if (!this.menuOpen) {
1995 this.itemData = null;
1996 this.lastAnchor_ = null;
1997 }
1998 },
1999 onOverlayCanceled_: function(e) {
2000 if (e.detail.type == 'tap') this.$.dropdown.restoreFocusOnClose = false;
2001 }
2002 });
2003
2004 Polymer({
2005 is: 'paper-icon-button-light',
2006 "extends": 'button',
2007 behaviors: [ Polymer.PaperRippleBehavior ],
2008 listeners: {
2009 down: '_rippleDown',
2010 up: '_rippleUp',
2011 focus: '_rippleDown',
2012 blur: '_rippleUp'
2013 },
2014 _rippleDown: function() {
2015 this.getRipple().downAction();
2016 },
2017 _rippleUp: function() {
2018 this.getRipple().upAction();
2019 },
2020 ensureRipple: function(var_args) {
2021 var lastRipple = this._ripple;
2022 Polymer.PaperRippleBehavior.ensureRipple.apply(this, arguments);
2023 if (this._ripple && this._ripple !== lastRipple) {
2024 this._ripple.center = true;
2025 this._ripple.classList.add('circle');
2026 }
2027 }
2028 });
2029
2030 // Copyright 2016 The Chromium Authors. All rights reserved. 12 // Copyright 2016 The Chromium Authors. All rights reserved.
2031 // Use of this source code is governed by a BSD-style license that can be 13 // Use of this source code is governed by a BSD-style license that can be
2032 // found in the LICENSE file. 14 // found in the LICENSE file.
2033 Polymer({ 15 Polymer({is:"history-synced-device-card",properties:{device:String,lastUpdateTim e:String,tabs:{type:Array,value:function(){return[]},observer:"updateIcons_"},se paratorIndexes:Array,opened:Boolean,searchTerm:String,sessionTag:String},openTab _:function(e){var tab=e.model.tab;var browserService=md_history.BrowserService.g etInstance();browserService.recordHistogram(SYNCED_TABS_HISTOGRAM_NAME,SyncedTab sHistogram.LINK_CLICKED,SyncedTabsHistogram.LIMIT);browserService.openForeignSes sionTab(this.sessionTag,tab.windowId,tab.sessionId,e);e.preventDefault()},toggle TabCard:function(){var histogramValue=this.$.collapse.opened?SyncedTabsHistogram .COLLAPSE_SESSION:SyncedTabsHistogram.EXPAND_SESSION;md_history.BrowserService.g etInstance().recordHistogram(SYNCED_TABS_HISTOGRAM_NAME,histogramValue,SyncedTab sHistogram.LIMIT);this.$.collapse.toggle();this.$["dropdown-indicator"].icon=thi s.$.collapse.opened?"cr:expand-less":"cr:expand-more"},updateIcons_:function(){t his.async(function(){var icons=Polymer.dom(this.root).querySelectorAll(".website -icon");for(var i=0;i<this.tabs.length;i++){icons[i].style.backgroundImage=cr.ic on.getFavicon(this.tabs[i].url)}})},isWindowSeparatorIndex_:function(index,separ atorIndexes){return this.separatorIndexes.indexOf(index)!=-1},getCollapseIcon_:f unction(opened){return opened?"cr:expand-less":"cr:expand-more"},getCollapseTitl e_:function(opened){return opened?loadTimeData.getString("collapseSessionButton" ):loadTimeData.getString("expandSessionButton")},onMenuButtonTap_:function(e){th is.fire("toggle-menu",{target:Polymer.dom(e).localTarget,tag:this.sessionTag});e .stopPropagation()},onLinkRightClick_:function(){md_history.BrowserService.getIn stance().recordHistogram(SYNCED_TABS_HISTOGRAM_NAME,SyncedTabsHistogram.LINK_RIG HT_CLICKED,SyncedTabsHistogram.LIMIT)}});
2034 is: 'history-synced-device-card',
2035 properties: {
2036 device: String,
2037 lastUpdateTime: String,
2038 tabs: {
2039 type: Array,
2040 value: function() {
2041 return [];
2042 },
2043 observer: 'updateIcons_'
2044 },
2045 separatorIndexes: Array,
2046 opened: Boolean,
2047 searchTerm: String,
2048 sessionTag: String
2049 },
2050 openTab_: function(e) {
2051 var tab = e.model.tab;
2052 var browserService = md_history.BrowserService.getInstance();
2053 browserService.recordHistogram(SYNCED_TABS_HISTOGRAM_NAME, SyncedTabsHistogr am.LINK_CLICKED, SyncedTabsHistogram.LIMIT);
2054 browserService.openForeignSessionTab(this.sessionTag, tab.windowId, tab.sess ionId, e);
2055 e.preventDefault();
2056 },
2057 toggleTabCard: function() {
2058 var histogramValue = this.$.collapse.opened ? SyncedTabsHistogram.COLLAPSE_S ESSION : SyncedTabsHistogram.EXPAND_SESSION;
2059 md_history.BrowserService.getInstance().recordHistogram(SYNCED_TABS_HISTOGRA M_NAME, histogramValue, SyncedTabsHistogram.LIMIT);
2060 this.$.collapse.toggle();
2061 this.$['dropdown-indicator'].icon = this.$.collapse.opened ? 'cr:expand-less ' : 'cr:expand-more';
2062 },
2063 updateIcons_: function() {
2064 this.async(function() {
2065 var icons = Polymer.dom(this.root).querySelectorAll('.website-icon');
2066 for (var i = 0; i < this.tabs.length; i++) {
2067 icons[i].style.backgroundImage = cr.icon.getFavicon(this.tabs[i].url);
2068 }
2069 });
2070 },
2071 isWindowSeparatorIndex_: function(index, separatorIndexes) {
2072 return this.separatorIndexes.indexOf(index) != -1;
2073 },
2074 getCollapseIcon_: function(opened) {
2075 return opened ? 'cr:expand-less' : 'cr:expand-more';
2076 },
2077 getCollapseTitle_: function(opened) {
2078 return opened ? loadTimeData.getString('collapseSessionButton') : loadTimeDa ta.getString('expandSessionButton');
2079 },
2080 onMenuButtonTap_: function(e) {
2081 this.fire('toggle-menu', {
2082 target: Polymer.dom(e).localTarget,
2083 tag: this.sessionTag
2084 });
2085 e.stopPropagation();
2086 },
2087 onLinkRightClick_: function() {
2088 md_history.BrowserService.getInstance().recordHistogram(SYNCED_TABS_HISTOGRA M_NAME, SyncedTabsHistogram.LINK_RIGHT_CLICKED, SyncedTabsHistogram.LIMIT);
2089 }
2090 });
2091
2092 // Copyright 2016 The Chromium Authors. All rights reserved. 16 // Copyright 2016 The Chromium Authors. All rights reserved.
2093 // Use of this source code is governed by a BSD-style license that can be 17 // Use of this source code is governed by a BSD-style license that can be
2094 // found in the LICENSE file. 18 // found in the LICENSE file.
2095 var ForeignDeviceInternal; 19 var ForeignDeviceInternal;Polymer({is:"history-synced-device-manager",properties :{sessionList:{type:Array,observer:"updateSyncedDevices"},searchTerm:{type:Strin g,observer:"searchTermChanged"},syncedDevices_:{type:Array,value:function(){retu rn[]}},signInState:{type:Boolean,observer:"signInStateChanged_"},guestSession_:{ type:Boolean,value:loadTimeData.getBoolean("isGuestSession")},fetchingSyncedTabs _:{type:Boolean,value:false},hasSeenForeignData_:Boolean},listeners:{"toggle-men u":"onToggleMenu_",scroll:"onListScroll_"},attached:function(){chrome.send("othe rDevicesInitialized");md_history.BrowserService.getInstance().recordHistogram(SY NCED_TABS_HISTOGRAM_NAME,SyncedTabsHistogram.INITIALIZED,SyncedTabsHistogram.LIM IT)},getContentScrollTarget:function(){return this},createInternalDevice_:functi on(session){var tabs=[];var separatorIndexes=[];for(var i=0;i<session.windows.le ngth;i++){var windowId=session.windows[i].sessionId;var newTabs=session.windows[ i].tabs;if(newTabs.length==0)continue;newTabs.forEach(function(tab){tab.windowId =windowId});var windowAdded=false;if(!this.searchTerm){tabs=tabs.concat(newTabs) ;windowAdded=true}else{var searchText=this.searchTerm.toLowerCase();for(var j=0; j<newTabs.length;j++){var tab=newTabs[j];if(tab.title.toLowerCase().indexOf(sear chText)!=-1){tabs.push(tab);windowAdded=true}}}if(windowAdded&&i!=session.window s.length-1)separatorIndexes.push(tabs.length-1)}return{device:session.name,lastU pdateTime:"– "+session.modifiedTime,opened:true,separatorIndexes:separatorIndexe s,timestamp:session.timestamp,tabs:tabs,tag:session.tag}},onSignInTap_:function( ){chrome.send("startSignInFlow")},onListScroll_:function(){var menu=this.$.menu. getIfExists();if(menu)menu.closeMenu()},onToggleMenu_:function(e){var menu=this. $.menu.get();menu.toggleMenu(e.detail.target,e.detail.tag);if(menu.menuOpen){md_ history.BrowserService.getInstance().recordHistogram(SYNCED_TABS_HISTOGRAM_NAME, SyncedTabsHistogram.SHOW_SESSION_MENU,SyncedTabsHistogram.LIMIT)}},onOpenAllTap_ :function(){var menu=assert(this.$.menu.getIfExists());var browserService=md_his tory.BrowserService.getInstance();browserService.recordHistogram(SYNCED_TABS_HIS TOGRAM_NAME,SyncedTabsHistogram.OPEN_ALL,SyncedTabsHistogram.LIMIT);browserServi ce.openForeignSessionAllTabs(menu.itemData);menu.closeMenu()},onDeleteSessionTap _:function(){var menu=assert(this.$.menu.getIfExists());var browserService=md_hi story.BrowserService.getInstance();browserService.recordHistogram(SYNCED_TABS_HI STOGRAM_NAME,SyncedTabsHistogram.HIDE_FOR_NOW,SyncedTabsHistogram.LIMIT);browser Service.deleteForeignSession(menu.itemData);menu.closeMenu()},clearDisplayedSync edDevices_:function(){this.syncedDevices_=[]},showNoSyncedMessage:function(signI nState,syncedDevicesLength,guestSession){if(guestSession)return true;return sign InState&&syncedDevicesLength==0},showSignInGuide:function(signInState,guestSessi on){var show=!signInState&&!guestSession;if(show){md_history.BrowserService.getI nstance().recordAction("Signin_Impression_FromRecentTabs")}return show},noSynced TabsMessage:function(){var stringName=this.fetchingSyncedTabs_?"loading":"noSync edResults";if(this.searchTerm!=="")stringName="noSearchResults";return loadTimeD ata.getString(stringName)},updateSyncedDevices:function(sessionList){this.fetchi ngSyncedTabs_=false;if(!sessionList)return;if(sessionList.length>0&&!this.hasSee nForeignData_){this.hasSeenForeignData_=true;md_history.BrowserService.getInstan ce().recordHistogram(SYNCED_TABS_HISTOGRAM_NAME,SyncedTabsHistogram.HAS_FOREIGN_ DATA,SyncedTabsHistogram.LIMIT)}var updateCount=Math.min(sessionList.length,this .syncedDevices_.length);for(var i=0;i<updateCount;i++){var oldDevice=this.synced Devices_[i];if(oldDevice.tag!=sessionList[i].tag||oldDevice.timestamp!=sessionLi st[i].timestamp){var device=this.createInternalDevice_(sessionList[i]);if(device .tabs.length!=0)this.splice("syncedDevices_",i,1,device)}}if(sessionList.length> =this.syncedDevices_.length){for(var i=updateCount;i<sessionList.length;i++){var device=this.createInternalDevice_(sessionList[i]);if(device.tabs.length!=0)this .push("syncedDevices_",device)}}else{this.splice("syncedDevices_",updateCount,th is.syncedDevices_.length-updateCount)}},tabSyncDisabled:function(){this.fetching SyncedTabs_=false;this.clearDisplayedSyncedDevices_()},signInStateChanged_:funct ion(){this.fire("history-view-changed");if(!this.signInState){this.clearDisplaye dSyncedDevices_();return}this.fetchingSyncedTabs_=true},searchTermChanged:functi on(searchTerm){this.clearDisplayedSyncedDevices_();this.updateSyncedDevices(this .sessionList)}});
2096
2097 Polymer({
2098 is: 'history-synced-device-manager',
2099 properties: {
2100 sessionList: {
2101 type: Array,
2102 observer: 'updateSyncedDevices'
2103 },
2104 searchTerm: {
2105 type: String,
2106 observer: 'searchTermChanged'
2107 },
2108 syncedDevices_: {
2109 type: Array,
2110 value: function() {
2111 return [];
2112 }
2113 },
2114 signInState: {
2115 type: Boolean,
2116 observer: 'signInStateChanged_'
2117 },
2118 guestSession_: {
2119 type: Boolean,
2120 value: loadTimeData.getBoolean('isGuestSession')
2121 },
2122 fetchingSyncedTabs_: {
2123 type: Boolean,
2124 value: false
2125 },
2126 hasSeenForeignData_: Boolean
2127 },
2128 listeners: {
2129 'toggle-menu': 'onToggleMenu_',
2130 scroll: 'onListScroll_'
2131 },
2132 attached: function() {
2133 chrome.send('otherDevicesInitialized');
2134 md_history.BrowserService.getInstance().recordHistogram(SYNCED_TABS_HISTOGRA M_NAME, SyncedTabsHistogram.INITIALIZED, SyncedTabsHistogram.LIMIT);
2135 },
2136 getContentScrollTarget: function() {
2137 return this;
2138 },
2139 createInternalDevice_: function(session) {
2140 var tabs = [];
2141 var separatorIndexes = [];
2142 for (var i = 0; i < session.windows.length; i++) {
2143 var windowId = session.windows[i].sessionId;
2144 var newTabs = session.windows[i].tabs;
2145 if (newTabs.length == 0) continue;
2146 newTabs.forEach(function(tab) {
2147 tab.windowId = windowId;
2148 });
2149 var windowAdded = false;
2150 if (!this.searchTerm) {
2151 tabs = tabs.concat(newTabs);
2152 windowAdded = true;
2153 } else {
2154 var searchText = this.searchTerm.toLowerCase();
2155 for (var j = 0; j < newTabs.length; j++) {
2156 var tab = newTabs[j];
2157 if (tab.title.toLowerCase().indexOf(searchText) != -1) {
2158 tabs.push(tab);
2159 windowAdded = true;
2160 }
2161 }
2162 }
2163 if (windowAdded && i != session.windows.length - 1) separatorIndexes.push( tabs.length - 1);
2164 }
2165 return {
2166 device: session.name,
2167 lastUpdateTime: '– ' + session.modifiedTime,
2168 opened: true,
2169 separatorIndexes: separatorIndexes,
2170 timestamp: session.timestamp,
2171 tabs: tabs,
2172 tag: session.tag
2173 };
2174 },
2175 onSignInTap_: function() {
2176 chrome.send('startSignInFlow');
2177 },
2178 onListScroll_: function() {
2179 var menu = this.$.menu.getIfExists();
2180 if (menu) menu.closeMenu();
2181 },
2182 onToggleMenu_: function(e) {
2183 var menu = this.$.menu.get();
2184 menu.toggleMenu(e.detail.target, e.detail.tag);
2185 if (menu.menuOpen) {
2186 md_history.BrowserService.getInstance().recordHistogram(SYNCED_TABS_HISTOG RAM_NAME, SyncedTabsHistogram.SHOW_SESSION_MENU, SyncedTabsHistogram.LIMIT);
2187 }
2188 },
2189 onOpenAllTap_: function() {
2190 var menu = assert(this.$.menu.getIfExists());
2191 var browserService = md_history.BrowserService.getInstance();
2192 browserService.recordHistogram(SYNCED_TABS_HISTOGRAM_NAME, SyncedTabsHistogr am.OPEN_ALL, SyncedTabsHistogram.LIMIT);
2193 browserService.openForeignSessionAllTabs(menu.itemData);
2194 menu.closeMenu();
2195 },
2196 onDeleteSessionTap_: function() {
2197 var menu = assert(this.$.menu.getIfExists());
2198 var browserService = md_history.BrowserService.getInstance();
2199 browserService.recordHistogram(SYNCED_TABS_HISTOGRAM_NAME, SyncedTabsHistogr am.HIDE_FOR_NOW, SyncedTabsHistogram.LIMIT);
2200 browserService.deleteForeignSession(menu.itemData);
2201 menu.closeMenu();
2202 },
2203 clearDisplayedSyncedDevices_: function() {
2204 this.syncedDevices_ = [];
2205 },
2206 showNoSyncedMessage: function(signInState, syncedDevicesLength, guestSession) {
2207 if (guestSession) return true;
2208 return signInState && syncedDevicesLength == 0;
2209 },
2210 showSignInGuide: function(signInState, guestSession) {
2211 var show = !signInState && !guestSession;
2212 if (show) {
2213 md_history.BrowserService.getInstance().recordAction('Signin_Impression_Fr omRecentTabs');
2214 }
2215 return show;
2216 },
2217 noSyncedTabsMessage: function() {
2218 var stringName = this.fetchingSyncedTabs_ ? 'loading' : 'noSyncedResults';
2219 if (this.searchTerm !== '') stringName = 'noSearchResults';
2220 return loadTimeData.getString(stringName);
2221 },
2222 updateSyncedDevices: function(sessionList) {
2223 this.fetchingSyncedTabs_ = false;
2224 if (!sessionList) return;
2225 if (sessionList.length > 0 && !this.hasSeenForeignData_) {
2226 this.hasSeenForeignData_ = true;
2227 md_history.BrowserService.getInstance().recordHistogram(SYNCED_TABS_HISTOG RAM_NAME, SyncedTabsHistogram.HAS_FOREIGN_DATA, SyncedTabsHistogram.LIMIT);
2228 }
2229 var updateCount = Math.min(sessionList.length, this.syncedDevices_.length);
2230 for (var i = 0; i < updateCount; i++) {
2231 var oldDevice = this.syncedDevices_[i];
2232 if (oldDevice.tag != sessionList[i].tag || oldDevice.timestamp != sessionL ist[i].timestamp) {
2233 var device = this.createInternalDevice_(sessionList[i]);
2234 if (device.tabs.length != 0) this.splice('syncedDevices_', i, 1, device) ;
2235 }
2236 }
2237 if (sessionList.length >= this.syncedDevices_.length) {
2238 for (var i = updateCount; i < sessionList.length; i++) {
2239 var device = this.createInternalDevice_(sessionList[i]);
2240 if (device.tabs.length != 0) this.push('syncedDevices_', device);
2241 }
2242 } else {
2243 this.splice('syncedDevices_', updateCount, this.syncedDevices_.length - up dateCount);
2244 }
2245 },
2246 tabSyncDisabled: function() {
2247 this.fetchingSyncedTabs_ = false;
2248 this.clearDisplayedSyncedDevices_();
2249 },
2250 signInStateChanged_: function() {
2251 this.fire('history-view-changed');
2252 if (!this.signInState) {
2253 this.clearDisplayedSyncedDevices_();
2254 return;
2255 }
2256 this.fetchingSyncedTabs_ = true;
2257 },
2258 searchTermChanged: function(searchTerm) {
2259 this.clearDisplayedSyncedDevices_();
2260 this.updateSyncedDevices(this.sessionList);
2261 }
2262 });
2263
2264 // Copyright 2016 The Chromium Authors. All rights reserved. 20 // Copyright 2016 The Chromium Authors. All rights reserved.
2265 // Use of this source code is governed by a BSD-style license that can be 21 // Use of this source code is governed by a BSD-style license that can be
2266 // found in the LICENSE file. 22 // found in the LICENSE file.
2267 Polymer({ 23 Polymer({is:"cr-dialog","extends":"dialog",created:function(){window.addEventLis tener("popstate",function(){if(this.open)this.cancel()}.bind(this))},cancel:func tion(){this.fire("cancel");HTMLDialogElement.prototype.close.call(this,"")},clos e:function(opt_returnValue){HTMLDialogElement.prototype.close.call(this,"success ")},getCloseButton:function(){return this.$.close}});Polymer({is:"app-drawer",pr operties:{opened:{type:Boolean,value:false,notify:true,reflectToAttribute:true}, persistent:{type:Boolean,value:false,reflectToAttribute:true},align:{type:String ,value:"left"},position:{type:String,readOnly:true,value:"left",reflectToAttribu te:true},swipeOpen:{type:Boolean,value:false,reflectToAttribute:true},noFocusTra p:{type:Boolean,value:false}},observers:["resetLayout(position)","_resetPosition (align, isAttached)"],_translateOffset:0,_trackDetails:null,_drawerState:0,_boun dEscKeydownHandler:null,_firstTabStop:null,_lastTabStop:null,ready:function(){th is.setScrollDirection("y");this._setTransitionDuration("0s")},attached:function( ){Polymer.RenderStatus.afterNextRender(this,function(){this._setTransitionDurati on("");this._boundEscKeydownHandler=this._escKeydownHandler.bind(this);this._res etDrawerState();this.listen(this,"track","_track");this.addEventListener("transi tionend",this._transitionend.bind(this));this.addEventListener("keydown",this._t abKeydownHandler.bind(this))})},detached:function(){document.removeEventListener ("keydown",this._boundEscKeydownHandler)},open:function(){this.opened=true},clos e:function(){this.opened=false},toggle:function(){this.opened=!this.opened},getW idth:function(){return this.$.contentContainer.offsetWidth},resetLayout:function (){this.debounce("_resetLayout",function(){this.fire("app-drawer-reset-layout")} ,1)},_isRTL:function(){return window.getComputedStyle(this).direction==="rtl"},_ resetPosition:function(){switch(this.align){case"start":this._setPosition(this._ isRTL()?"right":"left");return;case"end":this._setPosition(this._isRTL()?"left": "right");return}this._setPosition(this.align)},_escKeydownHandler:function(event ){var ESC_KEYCODE=27;if(event.keyCode===ESC_KEYCODE){event.preventDefault();this .close()}},_track:function(event){if(this.persistent){return}event.preventDefaul t();switch(event.detail.state){case"start":this._trackStart(event);break;case"tr ack":this._trackMove(event);break;case"end":this._trackEnd(event);break}},_track Start:function(event){this._drawerState=this._DRAWER_STATE.TRACKING;this._setTra nsitionDuration("0s");this.style.visibility="visible";var rect=this.$.contentCon tainer.getBoundingClientRect();if(this.position==="left"){this._translateOffset= rect.left}else{this._translateOffset=rect.right-window.innerWidth}this._trackDet ails=[]},_trackMove:function(event){this._translateDrawer(event.detail.dx+this._ translateOffset);this._trackDetails.push({dx:event.detail.dx,timeStamp:Date.now( )})},_trackEnd:function(event){var x=event.detail.dx+this._translateOffset;var d rawerWidth=this.getWidth();var isPositionLeft=this.position==="left";var isInEnd State=isPositionLeft?x>=0||x<=-drawerWidth:x<=0||x>=drawerWidth;if(!isInEndState ){var trackDetails=this._trackDetails;this._trackDetails=null;this._flingDrawer( event,trackDetails);if(this._drawerState===this._DRAWER_STATE.FLINGING){return}} var halfWidth=drawerWidth/2;if(event.detail.dx<-halfWidth){this.opened=this.posi tion==="right"}else if(event.detail.dx>halfWidth){this.opened=this.position==="l eft"}if(isInEndState){this._resetDrawerState()}this._setTransitionDuration("");t his._resetDrawerTranslate();this.style.visibility=""},_calculateVelocity:functio n(event,trackDetails){var now=Date.now();var timeLowerBound=now-100;var trackDet ail;var min=0;var max=trackDetails.length-1;while(min<=max){var mid=min+max>>1;v ar d=trackDetails[mid];if(d.timeStamp>=timeLowerBound){trackDetail=d;max=mid-1}e lse{min=mid+1}}if(trackDetail){var dx=event.detail.dx-trackDetail.dx;var dt=now- trackDetail.timeStamp||1;return dx/dt}return 0},_flingDrawer:function(event,trac kDetails){var velocity=this._calculateVelocity(event,trackDetails);if(Math.abs(v elocity)<this._MIN_FLING_THRESHOLD){return}this._drawerState=this._DRAWER_STATE. FLINGING;var x=event.detail.dx+this._translateOffset;var drawerWidth=this.getWid th();var isPositionLeft=this.position==="left";var isVelocityPositive=velocity>0 ;var isClosingLeft=!isVelocityPositive&&isPositionLeft;var isClosingRight=isVelo cityPositive&&!isPositionLeft;var dx;if(isClosingLeft){dx=-(x+drawerWidth)}else if(isClosingRight){dx=drawerWidth-x}else{dx=-x}if(isVelocityPositive){velocity=M ath.max(velocity,this._MIN_TRANSITION_VELOCITY);this.opened=this.position==="lef t"}else{velocity=Math.min(velocity,-this._MIN_TRANSITION_VELOCITY);this.opened=t his.position==="right"}this._setTransitionDuration(this._FLING_INITIAL_SLOPE*dx/ velocity+"ms");this._setTransitionTimingFunction(this._FLING_TIMING_FUNCTION);th is._resetDrawerTranslate()},_transitionend:function(event){var target=Polymer.do m(event).rootTarget;if(target===this.$.contentContainer||target===this.$.scrim){ if(this._drawerState===this._DRAWER_STATE.FLINGING){this._setTransitionDuration( "");this._setTransitionTimingFunction("");this.style.visibility=""}this._resetDr awerState()}},_setTransitionDuration:function(duration){this.$.contentContainer. style.transitionDuration=duration;this.$.scrim.style.transitionDuration=duration },_setTransitionTimingFunction:function(timingFunction){this.$.contentContainer. style.transitionTimingFunction=timingFunction;this.$.scrim.style.transitionTimin gFunction=timingFunction},_translateDrawer:function(x){var drawerWidth=this.getW idth();if(this.position==="left"){x=Math.max(-drawerWidth,Math.min(x,0));this.$. scrim.style.opacity=1+x/drawerWidth}else{x=Math.max(0,Math.min(x,drawerWidth));t his.$.scrim.style.opacity=1-x/drawerWidth}this.translate3d(x+"px","0","0",this.$ .contentContainer)},_resetDrawerTranslate:function(){this.$.scrim.style.opacity= "";this.transform("",this.$.contentContainer)},_resetDrawerState:function(){var oldState=this._drawerState;if(this.opened){this._drawerState=this.persistent?thi s._DRAWER_STATE.OPENED_PERSISTENT:this._DRAWER_STATE.OPENED}else{this._drawerSta te=this._DRAWER_STATE.CLOSED}if(oldState!==this._drawerState){if(this._drawerSta te===this._DRAWER_STATE.OPENED){this._setKeyboardFocusTrap();document.addEventLi stener("keydown",this._boundEscKeydownHandler);document.body.style.overflow="hid den"}else{document.removeEventListener("keydown",this._boundEscKeydownHandler);d ocument.body.style.overflow=""}if(oldState!==this._DRAWER_STATE.INIT){this.fire( "app-drawer-transitioned")}}},_setKeyboardFocusTrap:function(){if(this.noFocusTr ap){return}var focusableElementsSelector=['a[href]:not([tabindex="-1"])','area[h ref]:not([tabindex="-1"])','input:not([disabled]):not([tabindex="-1"])','select: not([disabled]):not([tabindex="-1"])','textarea:not([disabled]):not([tabindex="- 1"])','button:not([disabled]):not([tabindex="-1"])','iframe:not([tabindex="-1"]) ','[tabindex]:not([tabindex="-1"])','[contentEditable=true]:not([tabindex="-1"]) '].join(",");var focusableElements=Polymer.dom(this).querySelectorAll(focusableE lementsSelector);if(focusableElements.length>0){this._firstTabStop=focusableElem ents[0];this._lastTabStop=focusableElements[focusableElements.length-1]}else{thi s._firstTabStop=null;this._lastTabStop=null}var tabindex=this.getAttribute("tabi ndex");if(tabindex&&parseInt(tabindex,10)>-1){this.focus()}else if(this._firstTa bStop){this._firstTabStop.focus()}},_tabKeydownHandler:function(event){if(this.n oFocusTrap){return}var TAB_KEYCODE=9;if(this._drawerState===this._DRAWER_STATE.O PENED&&event.keyCode===TAB_KEYCODE){if(event.shiftKey){if(this._firstTabStop&&Po lymer.dom(event).localTarget===this._firstTabStop){event.preventDefault();this._ lastTabStop.focus()}}else{if(this._lastTabStop&&Polymer.dom(event).localTarget== =this._lastTabStop){event.preventDefault();this._firstTabStop.focus()}}}},_MIN_F LING_THRESHOLD:.2,_MIN_TRANSITION_VELOCITY:1.2,_FLING_TIMING_FUNCTION:"cubic-bez ier(0.667, 1, 0.667, 1)",_FLING_INITIAL_SLOPE:1.5,_DRAWER_STATE:{INIT:0,OPENED:1 ,OPENED_PERSISTENT:2,CLOSED:3,TRACKING:4,FLINGING:5}});Polymer.IronFormElementBe havior={properties:{name:{type:String},value:{notify:true,type:String},required: {type:Boolean,value:false},_parentForm:{type:Object}},attached:function(){this.f ire("iron-form-element-register")},detached:function(){if(this._parentForm){this ._parentForm.fire("iron-form-element-unregister",{target:this})}}};Polymer.IronC heckedElementBehaviorImpl={properties:{checked:{type:Boolean,value:false,reflect ToAttribute:true,notify:true,observer:"_checkedChanged"},toggles:{type:Boolean,v alue:true,reflectToAttribute:true},value:{type:String,value:"on",observer:"_valu eChanged"}},observers:["_requiredChanged(required)"],created:function(){this._ha sIronCheckedElementBehavior=true},_getValidity:function(_value){return this.disa bled||!this.required||this.checked},_requiredChanged:function(){if(this.required ){this.setAttribute("aria-required","true")}else{this.removeAttribute("aria-requ ired")}},_checkedChanged:function(){this.active=this.checked;this.fire("iron-cha nge")},_valueChanged:function(){if(this.value===undefined||this.value===null){th is.value="on"}}};Polymer.IronCheckedElementBehavior=[Polymer.IronFormElementBeha vior,Polymer.IronValidatableBehavior,Polymer.IronCheckedElementBehaviorImpl];Pol ymer.PaperCheckedElementBehaviorImpl={_checkedChanged:function(){Polymer.IronChe ckedElementBehaviorImpl._checkedChanged.call(this);if(this.hasRipple()){if(this. checked){this._ripple.setAttribute("checked","")}else{this._ripple.removeAttribu te("checked")}}},_buttonStateChanged:function(){Polymer.PaperRippleBehavior._but tonStateChanged.call(this);if(this.disabled){return}if(this.isAttached){this.che cked=this.active}}};Polymer.PaperCheckedElementBehavior=[Polymer.PaperInkyFocusB ehavior,Polymer.IronCheckedElementBehavior,Polymer.PaperCheckedElementBehaviorIm pl];Polymer({is:"paper-checkbox",behaviors:[Polymer.PaperCheckedElementBehavior] ,hostAttributes:{role:"checkbox","aria-checked":false,tabindex:0},properties:{ar iaActiveAttribute:{type:String,value:"aria-checked"}},attached:function(){var in kSize=this.getComputedStyleValue("--calculated-paper-checkbox-ink-size");if(inkS ize==="-1px"){var checkboxSize=parseFloat(this.getComputedStyleValue("--calculat ed-paper-checkbox-size"));var defaultInkSize=Math.floor(8/3*checkboxSize);if(def aultInkSize%2!==checkboxSize%2){defaultInkSize++}this.customStyle["--paper-check box-ink-size"]=defaultInkSize+"px";this.updateStyles()}},_computeCheckboxClass:f unction(checked,invalid){var className="";if(checked){className+="checked "}if(i nvalid){className+="invalid"}return className},_computeCheckmarkClass:function(c hecked){return checked?"":"hidden"},_createRipple:function(){this._rippleContain er=this.$.checkboxContainer;return Polymer.PaperInkyFocusBehaviorImpl._createRip ple.call(this)}});Polymer({is:"paper-tab",behaviors:[Polymer.IronControlState,Po lymer.IronButtonState,Polymer.PaperRippleBehavior],properties:{link:{type:Boolea n,value:false,reflectToAttribute:true}},hostAttributes:{role:"tab"},listeners:{d own:"_updateNoink",tap:"_onTap"},attached:function(){this._updateNoink()},get _p arentNoink(){var parent=Polymer.dom(this).parentNode;return!!parent&&!!parent.no ink},_updateNoink:function(){this.noink=!!this.noink||!!this._parentNoink},_onTa p:function(event){if(this.link){var anchor=this.queryEffectiveChildren("a");if(! anchor){return}if(event.target===anchor){return}anchor.click()}}});Polymer.IronM enuBehaviorImpl={properties:{focusedItem:{observer:"_focusedItemChanged",readOnl y:true,type:Object},attrForItemTitle:{type:String}},hostAttributes:{role:"menu", tabindex:"0"},observers:["_updateMultiselectable(multi)"],listeners:{focus:"_onF ocus",keydown:"_onKeydown","iron-items-changed":"_onIronItemsChanged"},keyBindin gs:{up:"_onUpKey",down:"_onDownKey",esc:"_onEscKey","shift+tab:keydown":"_onShif tTabDown"},attached:function(){this._resetTabindices()},select:function(value){i f(this._defaultFocusAsync){this.cancelAsync(this._defaultFocusAsync);this._defau ltFocusAsync=null}var item=this._valueToItem(value);if(item&&item.hasAttribute(" disabled"))return;this._setFocusedItem(item);Polymer.IronMultiSelectableBehavior Impl.select.apply(this,arguments)},_resetTabindices:function(){var selectedItem= this.multi?this.selectedItems&&this.selectedItems[0]:this.selectedItem;this.item s.forEach(function(item){item.setAttribute("tabindex",item===selectedItem?"0":"- 1")},this)},_updateMultiselectable:function(multi){if(multi){this.setAttribute(" aria-multiselectable","true")}else{this.removeAttribute("aria-multiselectable")} },_focusWithKeyboardEvent:function(event){for(var i=0,item;item=this.items[i];i+ +){var attr=this.attrForItemTitle||"textContent";var title=item[attr]||item.getA ttribute(attr);if(!item.hasAttribute("disabled")&&title&&title.trim().charAt(0). toLowerCase()===String.fromCharCode(event.keyCode).toLowerCase()){this._setFocus edItem(item);break}}},_focusPrevious:function(){var length=this.items.length;var curFocusIndex=Number(this.indexOf(this.focusedItem));for(var i=1;i<length+1;i++ ){var item=this.items[(curFocusIndex-i+length)%length];if(!item.hasAttribute("di sabled")){var owner=Polymer.dom(item).getOwnerRoot()||document;this._setFocusedI tem(item);if(Polymer.dom(owner).activeElement==item){return}}}},_focusNext:funct ion(){var length=this.items.length;var curFocusIndex=Number(this.indexOf(this.fo cusedItem));for(var i=1;i<length+1;i++){var item=this.items[(curFocusIndex+i)%le ngth];if(!item.hasAttribute("disabled")){var owner=Polymer.dom(item).getOwnerRoo t()||document;this._setFocusedItem(item);if(Polymer.dom(owner).activeElement==it em){return}}}},_applySelection:function(item,isSelected){if(isSelected){item.set Attribute("aria-selected","true")}else{item.removeAttribute("aria-selected")}Pol ymer.IronSelectableBehavior._applySelection.apply(this,arguments)},_focusedItemC hanged:function(focusedItem,old){old&&old.setAttribute("tabindex","-1");if(focus edItem){focusedItem.setAttribute("tabindex","0");focusedItem.focus()}},_onIronIt emsChanged:function(event){if(event.detail.addedNodes.length){this._resetTabindi ces()}},_onShiftTabDown:function(event){var oldTabIndex=this.getAttribute("tabin dex");Polymer.IronMenuBehaviorImpl._shiftTabPressed=true;this._setFocusedItem(nu ll);this.setAttribute("tabindex","-1");this.async(function(){this.setAttribute(" tabindex",oldTabIndex);Polymer.IronMenuBehaviorImpl._shiftTabPressed=false},1)}, _onFocus:function(event){if(Polymer.IronMenuBehaviorImpl._shiftTabPressed){retur n}var rootTarget=Polymer.dom(event).rootTarget;if(rootTarget!==this&&typeof root Target.tabIndex!=="undefined"&&!this.isLightDescendant(rootTarget)){return}this. _defaultFocusAsync=this.async(function(){var selectedItem=this.multi?this.select edItems&&this.selectedItems[0]:this.selectedItem;this._setFocusedItem(null);if(s electedItem){this._setFocusedItem(selectedItem)}else if(this.items[0]){this._foc usNext()}})},_onUpKey:function(event){this._focusPrevious();event.detail.keyboar dEvent.preventDefault()},_onDownKey:function(event){this._focusNext();event.deta il.keyboardEvent.preventDefault()},_onEscKey:function(event){this.focusedItem.bl ur()},_onKeydown:function(event){if(!this.keyboardEventMatchesKeys(event,"up dow n esc")){this._focusWithKeyboardEvent(event)}event.stopPropagation()},_activateH andler:function(event){Polymer.IronSelectableBehavior._activateHandler.call(this ,event);event.stopPropagation()}};Polymer.IronMenuBehaviorImpl._shiftTabPressed= false;Polymer.IronMenuBehavior=[Polymer.IronMultiSelectableBehavior,Polymer.Iron A11yKeysBehavior,Polymer.IronMenuBehaviorImpl];Polymer.IronMenubarBehaviorImpl={ hostAttributes:{role:"menubar"},keyBindings:{left:"_onLeftKey",right:"_onRightKe y"},_onUpKey:function(event){this.focusedItem.click();event.detail.keyboardEvent .preventDefault()},_onDownKey:function(event){this.focusedItem.click();event.det ail.keyboardEvent.preventDefault()},get _isRTL(){return window.getComputedStyle( this)["direction"]==="rtl"},_onLeftKey:function(event){if(this._isRTL){this._foc usNext()}else{this._focusPrevious()}event.detail.keyboardEvent.preventDefault()} ,_onRightKey:function(event){if(this._isRTL){this._focusPrevious()}else{this._fo cusNext()}event.detail.keyboardEvent.preventDefault()},_onKeydown:function(event ){if(this.keyboardEventMatchesKeys(event,"up down left right esc")){return}this. _focusWithKeyboardEvent(event)}};Polymer.IronMenubarBehavior=[Polymer.IronMenuBe havior,Polymer.IronMenubarBehaviorImpl];Polymer({is:"paper-tabs",behaviors:[Poly mer.IronResizableBehavior,Polymer.IronMenubarBehavior],properties:{noink:{type:B oolean,value:false,observer:"_noinkChanged"},noBar:{type:Boolean,value:false},no Slide:{type:Boolean,value:false},scrollable:{type:Boolean,value:false},fitContai ner:{type:Boolean,value:false},disableDrag:{type:Boolean,value:false},hideScroll Buttons:{type:Boolean,value:false},alignBottom:{type:Boolean,value:false},select able:{type:String,value:"paper-tab"},autoselect:{type:Boolean,value:false},autos electDelay:{type:Number,value:0},_step:{type:Number,value:10},_holdDelay:{type:N umber,value:1},_leftHidden:{type:Boolean,value:false},_rightHidden:{type:Boolean ,value:false},_previousTab:{type:Object}},hostAttributes:{role:"tablist"},listen ers:{"iron-resize":"_onTabSizingChanged","iron-items-changed":"_onTabSizingChang ed","iron-select":"_onIronSelect","iron-deselect":"_onIronDeselect"},keyBindings :{"left:keyup right:keyup":"_onArrowKeyup"},created:function(){this._holdJob=nul l;this._pendingActivationItem=undefined;this._pendingActivationTimeout=undefined ;this._bindDelayedActivationHandler=this._delayedActivationHandler.bind(this);th is.addEventListener("blur",this._onBlurCapture.bind(this),true)},ready:function( ){this.setScrollDirection("y",this.$.tabsContainer)},detached:function(){this._c ancelPendingActivation()},_noinkChanged:function(noink){var childTabs=Polymer.do m(this).querySelectorAll("paper-tab");childTabs.forEach(noink?this._setNoinkAttr ibute:this._removeNoinkAttribute)},_setNoinkAttribute:function(element){element. setAttribute("noink","")},_removeNoinkAttribute:function(element){element.remove Attribute("noink")},_computeScrollButtonClass:function(hideThisButton,scrollable ,hideScrollButtons){if(!scrollable||hideScrollButtons){return"hidden"}if(hideThi sButton){return"not-visible"}return""},_computeTabsContentClass:function(scrolla ble,fitContainer){return scrollable?"scrollable"+(fitContainer?" fit-container": ""):" fit-container"},_computeSelectionBarClass:function(noBar,alignBottom){if(n oBar){return"hidden"}else if(alignBottom){return"align-bottom"}return""},_onTabS izingChanged:function(){this.debounce("_onTabSizingChanged",function(){this._scr oll();this._tabChanged(this.selectedItem)},10)},_onIronSelect:function(event){th is._tabChanged(event.detail.item,this._previousTab);this._previousTab=event.deta il.item;this.cancelDebouncer("tab-changed")},_onIronDeselect:function(event){thi s.debounce("tab-changed",function(){this._tabChanged(null,this._previousTab);thi s._previousTab=null},1)},_activateHandler:function(){this._cancelPendingActivati on();Polymer.IronMenuBehaviorImpl._activateHandler.apply(this,arguments)},_sched uleActivation:function(item,delay){this._pendingActivationItem=item;this._pendin gActivationTimeout=this.async(this._bindDelayedActivationHandler,delay)},_delaye dActivationHandler:function(){var item=this._pendingActivationItem;this._pending ActivationItem=undefined;this._pendingActivationTimeout=undefined;item.fire(this .activateEvent,null,{bubbles:true,cancelable:true})},_cancelPendingActivation:fu nction(){if(this._pendingActivationTimeout!==undefined){this.cancelAsync(this._p endingActivationTimeout);this._pendingActivationItem=undefined;this._pendingActi vationTimeout=undefined}},_onArrowKeyup:function(event){if(this.autoselect){this ._scheduleActivation(this.focusedItem,this.autoselectDelay)}},_onBlurCapture:fun ction(event){if(event.target===this._pendingActivationItem){this._cancelPendingA ctivation()}},get _tabContainerScrollSize(){return Math.max(0,this.$.tabsContain er.scrollWidth-this.$.tabsContainer.offsetWidth)},_scroll:function(e,detail){if( !this.scrollable){return}var ddx=detail&&-detail.ddx||0;this._affectScroll(ddx)} ,_down:function(e){this.async(function(){if(this._defaultFocusAsync){this.cancel Async(this._defaultFocusAsync);this._defaultFocusAsync=null}},1)},_affectScroll: function(dx){this.$.tabsContainer.scrollLeft+=dx;var scrollLeft=this.$.tabsConta iner.scrollLeft;this._leftHidden=scrollLeft===0;this._rightHidden=scrollLeft===t his._tabContainerScrollSize},_onLeftScrollButtonDown:function(){this._scrollToLe ft();this._holdJob=setInterval(this._scrollToLeft.bind(this),this._holdDelay)},_ onRightScrollButtonDown:function(){this._scrollToRight();this._holdJob=setInterv al(this._scrollToRight.bind(this),this._holdDelay)},_onScrollButtonUp:function() {clearInterval(this._holdJob);this._holdJob=null},_scrollToLeft:function(){this. _affectScroll(-this._step)},_scrollToRight:function(){this._affectScroll(this._s tep)},_tabChanged:function(tab,old){if(!tab){this.$.selectionBar.classList.remov e("expand");this.$.selectionBar.classList.remove("contract");this._positionBar(0 ,0);return}var r=this.$.tabsContent.getBoundingClientRect();var w=r.width;var ta bRect=tab.getBoundingClientRect();var tabOffsetLeft=tabRect.left-r.left;this._po s={width:this._calcPercent(tabRect.width,w),left:this._calcPercent(tabOffsetLeft ,w)};if(this.noSlide||old==null){this.$.selectionBar.classList.remove("expand"); this.$.selectionBar.classList.remove("contract");this._positionBar(this._pos.wid th,this._pos.left);return}var oldRect=old.getBoundingClientRect();var oldIndex=t his.items.indexOf(old);var index=this.items.indexOf(tab);var m=5;this.$.selectio nBar.classList.add("expand");var moveRight=oldIndex<index;var isRTL=this._isRTL; if(isRTL){moveRight=!moveRight}if(moveRight){this._positionBar(this._calcPercent (tabRect.left+tabRect.width-oldRect.left,w)-m,this._left)}else{this._positionBar (this._calcPercent(oldRect.left+oldRect.width-tabRect.left,w)-m,this._calcPercen t(tabOffsetLeft,w)+m)}if(this.scrollable){this._scrollToSelectedIfNeeded(tabRect .width,tabOffsetLeft)}},_scrollToSelectedIfNeeded:function(tabWidth,tabOffsetLef t){var l=tabOffsetLeft-this.$.tabsContainer.scrollLeft;if(l<0){this.$.tabsContai ner.scrollLeft+=l}else{l+=tabWidth-this.$.tabsContainer.offsetWidth;if(l>0){this .$.tabsContainer.scrollLeft+=l}}},_calcPercent:function(w,w0){return 100*w/w0},_ positionBar:function(width,left){width=width||0;left=left||0;this._width=width;t his._left=left;this.transform("translateX("+left+"%) scaleX("+width/100+")",this .$.selectionBar)},_onBarTransitionEnd:function(e){var cl=this.$.selectionBar.cla ssList;if(cl.contains("expand")){cl.remove("expand");cl.add("contract");this._po sitionBar(this._pos.width,this._pos.left)}else if(cl.contains("contract")){cl.re move("contract")}}});
2268 is: 'cr-dialog',
2269 "extends": 'dialog',
2270 created: function() {
2271 window.addEventListener('popstate', function() {
2272 if (this.open) this.cancel();
2273 }.bind(this));
2274 },
2275 cancel: function() {
2276 this.fire('cancel');
2277 HTMLDialogElement.prototype.close.call(this, '');
2278 },
2279 close: function(opt_returnValue) {
2280 HTMLDialogElement.prototype.close.call(this, 'success');
2281 },
2282 getCloseButton: function() {
2283 return this.$.close;
2284 }
2285 });
2286
2287 Polymer({
2288 is: 'app-drawer',
2289 properties: {
2290 opened: {
2291 type: Boolean,
2292 value: false,
2293 notify: true,
2294 reflectToAttribute: true
2295 },
2296 persistent: {
2297 type: Boolean,
2298 value: false,
2299 reflectToAttribute: true
2300 },
2301 align: {
2302 type: String,
2303 value: 'left'
2304 },
2305 position: {
2306 type: String,
2307 readOnly: true,
2308 value: 'left',
2309 reflectToAttribute: true
2310 },
2311 swipeOpen: {
2312 type: Boolean,
2313 value: false,
2314 reflectToAttribute: true
2315 },
2316 noFocusTrap: {
2317 type: Boolean,
2318 value: false
2319 }
2320 },
2321 observers: [ 'resetLayout(position)', '_resetPosition(align, isAttached)' ],
2322 _translateOffset: 0,
2323 _trackDetails: null,
2324 _drawerState: 0,
2325 _boundEscKeydownHandler: null,
2326 _firstTabStop: null,
2327 _lastTabStop: null,
2328 ready: function() {
2329 this.setScrollDirection('y');
2330 this._setTransitionDuration('0s');
2331 },
2332 attached: function() {
2333 Polymer.RenderStatus.afterNextRender(this, function() {
2334 this._setTransitionDuration('');
2335 this._boundEscKeydownHandler = this._escKeydownHandler.bind(this);
2336 this._resetDrawerState();
2337 this.listen(this, 'track', '_track');
2338 this.addEventListener('transitionend', this._transitionend.bind(this));
2339 this.addEventListener('keydown', this._tabKeydownHandler.bind(this));
2340 });
2341 },
2342 detached: function() {
2343 document.removeEventListener('keydown', this._boundEscKeydownHandler);
2344 },
2345 open: function() {
2346 this.opened = true;
2347 },
2348 close: function() {
2349 this.opened = false;
2350 },
2351 toggle: function() {
2352 this.opened = !this.opened;
2353 },
2354 getWidth: function() {
2355 return this.$.contentContainer.offsetWidth;
2356 },
2357 resetLayout: function() {
2358 this.debounce('_resetLayout', function() {
2359 this.fire('app-drawer-reset-layout');
2360 }, 1);
2361 },
2362 _isRTL: function() {
2363 return window.getComputedStyle(this).direction === 'rtl';
2364 },
2365 _resetPosition: function() {
2366 switch (this.align) {
2367 case 'start':
2368 this._setPosition(this._isRTL() ? 'right' : 'left');
2369 return;
2370
2371 case 'end':
2372 this._setPosition(this._isRTL() ? 'left' : 'right');
2373 return;
2374 }
2375 this._setPosition(this.align);
2376 },
2377 _escKeydownHandler: function(event) {
2378 var ESC_KEYCODE = 27;
2379 if (event.keyCode === ESC_KEYCODE) {
2380 event.preventDefault();
2381 this.close();
2382 }
2383 },
2384 _track: function(event) {
2385 if (this.persistent) {
2386 return;
2387 }
2388 event.preventDefault();
2389 switch (event.detail.state) {
2390 case 'start':
2391 this._trackStart(event);
2392 break;
2393
2394 case 'track':
2395 this._trackMove(event);
2396 break;
2397
2398 case 'end':
2399 this._trackEnd(event);
2400 break;
2401 }
2402 },
2403 _trackStart: function(event) {
2404 this._drawerState = this._DRAWER_STATE.TRACKING;
2405 this._setTransitionDuration('0s');
2406 this.style.visibility = 'visible';
2407 var rect = this.$.contentContainer.getBoundingClientRect();
2408 if (this.position === 'left') {
2409 this._translateOffset = rect.left;
2410 } else {
2411 this._translateOffset = rect.right - window.innerWidth;
2412 }
2413 this._trackDetails = [];
2414 },
2415 _trackMove: function(event) {
2416 this._translateDrawer(event.detail.dx + this._translateOffset);
2417 this._trackDetails.push({
2418 dx: event.detail.dx,
2419 timeStamp: Date.now()
2420 });
2421 },
2422 _trackEnd: function(event) {
2423 var x = event.detail.dx + this._translateOffset;
2424 var drawerWidth = this.getWidth();
2425 var isPositionLeft = this.position === 'left';
2426 var isInEndState = isPositionLeft ? x >= 0 || x <= -drawerWidth : x <= 0 || x >= drawerWidth;
2427 if (!isInEndState) {
2428 var trackDetails = this._trackDetails;
2429 this._trackDetails = null;
2430 this._flingDrawer(event, trackDetails);
2431 if (this._drawerState === this._DRAWER_STATE.FLINGING) {
2432 return;
2433 }
2434 }
2435 var halfWidth = drawerWidth / 2;
2436 if (event.detail.dx < -halfWidth) {
2437 this.opened = this.position === 'right';
2438 } else if (event.detail.dx > halfWidth) {
2439 this.opened = this.position === 'left';
2440 }
2441 if (isInEndState) {
2442 this._resetDrawerState();
2443 }
2444 this._setTransitionDuration('');
2445 this._resetDrawerTranslate();
2446 this.style.visibility = '';
2447 },
2448 _calculateVelocity: function(event, trackDetails) {
2449 var now = Date.now();
2450 var timeLowerBound = now - 100;
2451 var trackDetail;
2452 var min = 0;
2453 var max = trackDetails.length - 1;
2454 while (min <= max) {
2455 var mid = min + max >> 1;
2456 var d = trackDetails[mid];
2457 if (d.timeStamp >= timeLowerBound) {
2458 trackDetail = d;
2459 max = mid - 1;
2460 } else {
2461 min = mid + 1;
2462 }
2463 }
2464 if (trackDetail) {
2465 var dx = event.detail.dx - trackDetail.dx;
2466 var dt = now - trackDetail.timeStamp || 1;
2467 return dx / dt;
2468 }
2469 return 0;
2470 },
2471 _flingDrawer: function(event, trackDetails) {
2472 var velocity = this._calculateVelocity(event, trackDetails);
2473 if (Math.abs(velocity) < this._MIN_FLING_THRESHOLD) {
2474 return;
2475 }
2476 this._drawerState = this._DRAWER_STATE.FLINGING;
2477 var x = event.detail.dx + this._translateOffset;
2478 var drawerWidth = this.getWidth();
2479 var isPositionLeft = this.position === 'left';
2480 var isVelocityPositive = velocity > 0;
2481 var isClosingLeft = !isVelocityPositive && isPositionLeft;
2482 var isClosingRight = isVelocityPositive && !isPositionLeft;
2483 var dx;
2484 if (isClosingLeft) {
2485 dx = -(x + drawerWidth);
2486 } else if (isClosingRight) {
2487 dx = drawerWidth - x;
2488 } else {
2489 dx = -x;
2490 }
2491 if (isVelocityPositive) {
2492 velocity = Math.max(velocity, this._MIN_TRANSITION_VELOCITY);
2493 this.opened = this.position === 'left';
2494 } else {
2495 velocity = Math.min(velocity, -this._MIN_TRANSITION_VELOCITY);
2496 this.opened = this.position === 'right';
2497 }
2498 this._setTransitionDuration(this._FLING_INITIAL_SLOPE * dx / velocity + 'ms' );
2499 this._setTransitionTimingFunction(this._FLING_TIMING_FUNCTION);
2500 this._resetDrawerTranslate();
2501 },
2502 _transitionend: function(event) {
2503 var target = Polymer.dom(event).rootTarget;
2504 if (target === this.$.contentContainer || target === this.$.scrim) {
2505 if (this._drawerState === this._DRAWER_STATE.FLINGING) {
2506 this._setTransitionDuration('');
2507 this._setTransitionTimingFunction('');
2508 this.style.visibility = '';
2509 }
2510 this._resetDrawerState();
2511 }
2512 },
2513 _setTransitionDuration: function(duration) {
2514 this.$.contentContainer.style.transitionDuration = duration;
2515 this.$.scrim.style.transitionDuration = duration;
2516 },
2517 _setTransitionTimingFunction: function(timingFunction) {
2518 this.$.contentContainer.style.transitionTimingFunction = timingFunction;
2519 this.$.scrim.style.transitionTimingFunction = timingFunction;
2520 },
2521 _translateDrawer: function(x) {
2522 var drawerWidth = this.getWidth();
2523 if (this.position === 'left') {
2524 x = Math.max(-drawerWidth, Math.min(x, 0));
2525 this.$.scrim.style.opacity = 1 + x / drawerWidth;
2526 } else {
2527 x = Math.max(0, Math.min(x, drawerWidth));
2528 this.$.scrim.style.opacity = 1 - x / drawerWidth;
2529 }
2530 this.translate3d(x + 'px', '0', '0', this.$.contentContainer);
2531 },
2532 _resetDrawerTranslate: function() {
2533 this.$.scrim.style.opacity = '';
2534 this.transform('', this.$.contentContainer);
2535 },
2536 _resetDrawerState: function() {
2537 var oldState = this._drawerState;
2538 if (this.opened) {
2539 this._drawerState = this.persistent ? this._DRAWER_STATE.OPENED_PERSISTENT : this._DRAWER_STATE.OPENED;
2540 } else {
2541 this._drawerState = this._DRAWER_STATE.CLOSED;
2542 }
2543 if (oldState !== this._drawerState) {
2544 if (this._drawerState === this._DRAWER_STATE.OPENED) {
2545 this._setKeyboardFocusTrap();
2546 document.addEventListener('keydown', this._boundEscKeydownHandler);
2547 document.body.style.overflow = 'hidden';
2548 } else {
2549 document.removeEventListener('keydown', this._boundEscKeydownHandler);
2550 document.body.style.overflow = '';
2551 }
2552 if (oldState !== this._DRAWER_STATE.INIT) {
2553 this.fire('app-drawer-transitioned');
2554 }
2555 }
2556 },
2557 _setKeyboardFocusTrap: function() {
2558 if (this.noFocusTrap) {
2559 return;
2560 }
2561 var focusableElementsSelector = [ 'a[href]:not([tabindex="-1"])', 'area[href ]:not([tabindex="-1"])', 'input:not([disabled]):not([tabindex="-1"])', 'select:n ot([disabled]):not([tabindex="-1"])', 'textarea:not([disabled]):not([tabindex="- 1"])', 'button:not([disabled]):not([tabindex="-1"])', 'iframe:not([tabindex="-1" ])', '[tabindex]:not([tabindex="-1"])', '[contentEditable=true]:not([tabindex="- 1"])' ].join(',');
2562 var focusableElements = Polymer.dom(this).querySelectorAll(focusableElements Selector);
2563 if (focusableElements.length > 0) {
2564 this._firstTabStop = focusableElements[0];
2565 this._lastTabStop = focusableElements[focusableElements.length - 1];
2566 } else {
2567 this._firstTabStop = null;
2568 this._lastTabStop = null;
2569 }
2570 var tabindex = this.getAttribute('tabindex');
2571 if (tabindex && parseInt(tabindex, 10) > -1) {
2572 this.focus();
2573 } else if (this._firstTabStop) {
2574 this._firstTabStop.focus();
2575 }
2576 },
2577 _tabKeydownHandler: function(event) {
2578 if (this.noFocusTrap) {
2579 return;
2580 }
2581 var TAB_KEYCODE = 9;
2582 if (this._drawerState === this._DRAWER_STATE.OPENED && event.keyCode === TAB _KEYCODE) {
2583 if (event.shiftKey) {
2584 if (this._firstTabStop && Polymer.dom(event).localTarget === this._first TabStop) {
2585 event.preventDefault();
2586 this._lastTabStop.focus();
2587 }
2588 } else {
2589 if (this._lastTabStop && Polymer.dom(event).localTarget === this._lastTa bStop) {
2590 event.preventDefault();
2591 this._firstTabStop.focus();
2592 }
2593 }
2594 }
2595 },
2596 _MIN_FLING_THRESHOLD: .2,
2597 _MIN_TRANSITION_VELOCITY: 1.2,
2598 _FLING_TIMING_FUNCTION: 'cubic-bezier(0.667, 1, 0.667, 1)',
2599 _FLING_INITIAL_SLOPE: 1.5,
2600 _DRAWER_STATE: {
2601 INIT: 0,
2602 OPENED: 1,
2603 OPENED_PERSISTENT: 2,
2604 CLOSED: 3,
2605 TRACKING: 4,
2606 FLINGING: 5
2607 }
2608 });
2609
2610 Polymer.IronFormElementBehavior = {
2611 properties: {
2612 name: {
2613 type: String
2614 },
2615 value: {
2616 notify: true,
2617 type: String
2618 },
2619 required: {
2620 type: Boolean,
2621 value: false
2622 },
2623 _parentForm: {
2624 type: Object
2625 }
2626 },
2627 attached: function() {
2628 this.fire('iron-form-element-register');
2629 },
2630 detached: function() {
2631 if (this._parentForm) {
2632 this._parentForm.fire('iron-form-element-unregister', {
2633 target: this
2634 });
2635 }
2636 }
2637 };
2638
2639 Polymer.IronCheckedElementBehaviorImpl = {
2640 properties: {
2641 checked: {
2642 type: Boolean,
2643 value: false,
2644 reflectToAttribute: true,
2645 notify: true,
2646 observer: '_checkedChanged'
2647 },
2648 toggles: {
2649 type: Boolean,
2650 value: true,
2651 reflectToAttribute: true
2652 },
2653 value: {
2654 type: String,
2655 value: 'on',
2656 observer: '_valueChanged'
2657 }
2658 },
2659 observers: [ '_requiredChanged(required)' ],
2660 created: function() {
2661 this._hasIronCheckedElementBehavior = true;
2662 },
2663 _getValidity: function(_value) {
2664 return this.disabled || !this.required || this.checked;
2665 },
2666 _requiredChanged: function() {
2667 if (this.required) {
2668 this.setAttribute('aria-required', 'true');
2669 } else {
2670 this.removeAttribute('aria-required');
2671 }
2672 },
2673 _checkedChanged: function() {
2674 this.active = this.checked;
2675 this.fire('iron-change');
2676 },
2677 _valueChanged: function() {
2678 if (this.value === undefined || this.value === null) {
2679 this.value = 'on';
2680 }
2681 }
2682 };
2683
2684 Polymer.IronCheckedElementBehavior = [ Polymer.IronFormElementBehavior, Polymer. IronValidatableBehavior, Polymer.IronCheckedElementBehaviorImpl ];
2685
2686 Polymer.PaperCheckedElementBehaviorImpl = {
2687 _checkedChanged: function() {
2688 Polymer.IronCheckedElementBehaviorImpl._checkedChanged.call(this);
2689 if (this.hasRipple()) {
2690 if (this.checked) {
2691 this._ripple.setAttribute('checked', '');
2692 } else {
2693 this._ripple.removeAttribute('checked');
2694 }
2695 }
2696 },
2697 _buttonStateChanged: function() {
2698 Polymer.PaperRippleBehavior._buttonStateChanged.call(this);
2699 if (this.disabled) {
2700 return;
2701 }
2702 if (this.isAttached) {
2703 this.checked = this.active;
2704 }
2705 }
2706 };
2707
2708 Polymer.PaperCheckedElementBehavior = [ Polymer.PaperInkyFocusBehavior, Polymer. IronCheckedElementBehavior, Polymer.PaperCheckedElementBehaviorImpl ];
2709
2710 Polymer({
2711 is: 'paper-checkbox',
2712 behaviors: [ Polymer.PaperCheckedElementBehavior ],
2713 hostAttributes: {
2714 role: 'checkbox',
2715 'aria-checked': false,
2716 tabindex: 0
2717 },
2718 properties: {
2719 ariaActiveAttribute: {
2720 type: String,
2721 value: 'aria-checked'
2722 }
2723 },
2724 attached: function() {
2725 var inkSize = this.getComputedStyleValue('--calculated-paper-checkbox-ink-si ze');
2726 if (inkSize === '-1px') {
2727 var checkboxSize = parseFloat(this.getComputedStyleValue('--calculated-pap er-checkbox-size'));
2728 var defaultInkSize = Math.floor(8 / 3 * checkboxSize);
2729 if (defaultInkSize % 2 !== checkboxSize % 2) {
2730 defaultInkSize++;
2731 }
2732 this.customStyle['--paper-checkbox-ink-size'] = defaultInkSize + 'px';
2733 this.updateStyles();
2734 }
2735 },
2736 _computeCheckboxClass: function(checked, invalid) {
2737 var className = '';
2738 if (checked) {
2739 className += 'checked ';
2740 }
2741 if (invalid) {
2742 className += 'invalid';
2743 }
2744 return className;
2745 },
2746 _computeCheckmarkClass: function(checked) {
2747 return checked ? '' : 'hidden';
2748 },
2749 _createRipple: function() {
2750 this._rippleContainer = this.$.checkboxContainer;
2751 return Polymer.PaperInkyFocusBehaviorImpl._createRipple.call(this);
2752 }
2753 });
2754
2755 Polymer({
2756 is: 'paper-tab',
2757 behaviors: [ Polymer.IronControlState, Polymer.IronButtonState, Polymer.PaperR ippleBehavior ],
2758 properties: {
2759 link: {
2760 type: Boolean,
2761 value: false,
2762 reflectToAttribute: true
2763 }
2764 },
2765 hostAttributes: {
2766 role: 'tab'
2767 },
2768 listeners: {
2769 down: '_updateNoink',
2770 tap: '_onTap'
2771 },
2772 attached: function() {
2773 this._updateNoink();
2774 },
2775 get _parentNoink() {
2776 var parent = Polymer.dom(this).parentNode;
2777 return !!parent && !!parent.noink;
2778 },
2779 _updateNoink: function() {
2780 this.noink = !!this.noink || !!this._parentNoink;
2781 },
2782 _onTap: function(event) {
2783 if (this.link) {
2784 var anchor = this.queryEffectiveChildren('a');
2785 if (!anchor) {
2786 return;
2787 }
2788 if (event.target === anchor) {
2789 return;
2790 }
2791 anchor.click();
2792 }
2793 }
2794 });
2795
2796 Polymer.IronMenuBehaviorImpl = {
2797 properties: {
2798 focusedItem: {
2799 observer: '_focusedItemChanged',
2800 readOnly: true,
2801 type: Object
2802 },
2803 attrForItemTitle: {
2804 type: String
2805 }
2806 },
2807 hostAttributes: {
2808 role: 'menu',
2809 tabindex: '0'
2810 },
2811 observers: [ '_updateMultiselectable(multi)' ],
2812 listeners: {
2813 focus: '_onFocus',
2814 keydown: '_onKeydown',
2815 'iron-items-changed': '_onIronItemsChanged'
2816 },
2817 keyBindings: {
2818 up: '_onUpKey',
2819 down: '_onDownKey',
2820 esc: '_onEscKey',
2821 'shift+tab:keydown': '_onShiftTabDown'
2822 },
2823 attached: function() {
2824 this._resetTabindices();
2825 },
2826 select: function(value) {
2827 if (this._defaultFocusAsync) {
2828 this.cancelAsync(this._defaultFocusAsync);
2829 this._defaultFocusAsync = null;
2830 }
2831 var item = this._valueToItem(value);
2832 if (item && item.hasAttribute('disabled')) return;
2833 this._setFocusedItem(item);
2834 Polymer.IronMultiSelectableBehaviorImpl.select.apply(this, arguments);
2835 },
2836 _resetTabindices: function() {
2837 var selectedItem = this.multi ? this.selectedItems && this.selectedItems[0] : this.selectedItem;
2838 this.items.forEach(function(item) {
2839 item.setAttribute('tabindex', item === selectedItem ? '0' : '-1');
2840 }, this);
2841 },
2842 _updateMultiselectable: function(multi) {
2843 if (multi) {
2844 this.setAttribute('aria-multiselectable', 'true');
2845 } else {
2846 this.removeAttribute('aria-multiselectable');
2847 }
2848 },
2849 _focusWithKeyboardEvent: function(event) {
2850 for (var i = 0, item; item = this.items[i]; i++) {
2851 var attr = this.attrForItemTitle || 'textContent';
2852 var title = item[attr] || item.getAttribute(attr);
2853 if (!item.hasAttribute('disabled') && title && title.trim().charAt(0).toLo werCase() === String.fromCharCode(event.keyCode).toLowerCase()) {
2854 this._setFocusedItem(item);
2855 break;
2856 }
2857 }
2858 },
2859 _focusPrevious: function() {
2860 var length = this.items.length;
2861 var curFocusIndex = Number(this.indexOf(this.focusedItem));
2862 for (var i = 1; i < length + 1; i++) {
2863 var item = this.items[(curFocusIndex - i + length) % length];
2864 if (!item.hasAttribute('disabled')) {
2865 var owner = Polymer.dom(item).getOwnerRoot() || document;
2866 this._setFocusedItem(item);
2867 if (Polymer.dom(owner).activeElement == item) {
2868 return;
2869 }
2870 }
2871 }
2872 },
2873 _focusNext: function() {
2874 var length = this.items.length;
2875 var curFocusIndex = Number(this.indexOf(this.focusedItem));
2876 for (var i = 1; i < length + 1; i++) {
2877 var item = this.items[(curFocusIndex + i) % length];
2878 if (!item.hasAttribute('disabled')) {
2879 var owner = Polymer.dom(item).getOwnerRoot() || document;
2880 this._setFocusedItem(item);
2881 if (Polymer.dom(owner).activeElement == item) {
2882 return;
2883 }
2884 }
2885 }
2886 },
2887 _applySelection: function(item, isSelected) {
2888 if (isSelected) {
2889 item.setAttribute('aria-selected', 'true');
2890 } else {
2891 item.removeAttribute('aria-selected');
2892 }
2893 Polymer.IronSelectableBehavior._applySelection.apply(this, arguments);
2894 },
2895 _focusedItemChanged: function(focusedItem, old) {
2896 old && old.setAttribute('tabindex', '-1');
2897 if (focusedItem) {
2898 focusedItem.setAttribute('tabindex', '0');
2899 focusedItem.focus();
2900 }
2901 },
2902 _onIronItemsChanged: function(event) {
2903 if (event.detail.addedNodes.length) {
2904 this._resetTabindices();
2905 }
2906 },
2907 _onShiftTabDown: function(event) {
2908 var oldTabIndex = this.getAttribute('tabindex');
2909 Polymer.IronMenuBehaviorImpl._shiftTabPressed = true;
2910 this._setFocusedItem(null);
2911 this.setAttribute('tabindex', '-1');
2912 this.async(function() {
2913 this.setAttribute('tabindex', oldTabIndex);
2914 Polymer.IronMenuBehaviorImpl._shiftTabPressed = false;
2915 }, 1);
2916 },
2917 _onFocus: function(event) {
2918 if (Polymer.IronMenuBehaviorImpl._shiftTabPressed) {
2919 return;
2920 }
2921 var rootTarget = Polymer.dom(event).rootTarget;
2922 if (rootTarget !== this && typeof rootTarget.tabIndex !== "undefined" && !th is.isLightDescendant(rootTarget)) {
2923 return;
2924 }
2925 this._defaultFocusAsync = this.async(function() {
2926 var selectedItem = this.multi ? this.selectedItems && this.selectedItems[0 ] : this.selectedItem;
2927 this._setFocusedItem(null);
2928 if (selectedItem) {
2929 this._setFocusedItem(selectedItem);
2930 } else if (this.items[0]) {
2931 this._focusNext();
2932 }
2933 });
2934 },
2935 _onUpKey: function(event) {
2936 this._focusPrevious();
2937 event.detail.keyboardEvent.preventDefault();
2938 },
2939 _onDownKey: function(event) {
2940 this._focusNext();
2941 event.detail.keyboardEvent.preventDefault();
2942 },
2943 _onEscKey: function(event) {
2944 this.focusedItem.blur();
2945 },
2946 _onKeydown: function(event) {
2947 if (!this.keyboardEventMatchesKeys(event, 'up down esc')) {
2948 this._focusWithKeyboardEvent(event);
2949 }
2950 event.stopPropagation();
2951 },
2952 _activateHandler: function(event) {
2953 Polymer.IronSelectableBehavior._activateHandler.call(this, event);
2954 event.stopPropagation();
2955 }
2956 };
2957
2958 Polymer.IronMenuBehaviorImpl._shiftTabPressed = false;
2959
2960 Polymer.IronMenuBehavior = [ Polymer.IronMultiSelectableBehavior, Polymer.IronA1 1yKeysBehavior, Polymer.IronMenuBehaviorImpl ];
2961
2962 Polymer.IronMenubarBehaviorImpl = {
2963 hostAttributes: {
2964 role: 'menubar'
2965 },
2966 keyBindings: {
2967 left: '_onLeftKey',
2968 right: '_onRightKey'
2969 },
2970 _onUpKey: function(event) {
2971 this.focusedItem.click();
2972 event.detail.keyboardEvent.preventDefault();
2973 },
2974 _onDownKey: function(event) {
2975 this.focusedItem.click();
2976 event.detail.keyboardEvent.preventDefault();
2977 },
2978 get _isRTL() {
2979 return window.getComputedStyle(this)['direction'] === 'rtl';
2980 },
2981 _onLeftKey: function(event) {
2982 if (this._isRTL) {
2983 this._focusNext();
2984 } else {
2985 this._focusPrevious();
2986 }
2987 event.detail.keyboardEvent.preventDefault();
2988 },
2989 _onRightKey: function(event) {
2990 if (this._isRTL) {
2991 this._focusPrevious();
2992 } else {
2993 this._focusNext();
2994 }
2995 event.detail.keyboardEvent.preventDefault();
2996 },
2997 _onKeydown: function(event) {
2998 if (this.keyboardEventMatchesKeys(event, 'up down left right esc')) {
2999 return;
3000 }
3001 this._focusWithKeyboardEvent(event);
3002 }
3003 };
3004
3005 Polymer.IronMenubarBehavior = [ Polymer.IronMenuBehavior, Polymer.IronMenubarBeh aviorImpl ];
3006
3007 Polymer({
3008 is: 'paper-tabs',
3009 behaviors: [ Polymer.IronResizableBehavior, Polymer.IronMenubarBehavior ],
3010 properties: {
3011 noink: {
3012 type: Boolean,
3013 value: false,
3014 observer: '_noinkChanged'
3015 },
3016 noBar: {
3017 type: Boolean,
3018 value: false
3019 },
3020 noSlide: {
3021 type: Boolean,
3022 value: false
3023 },
3024 scrollable: {
3025 type: Boolean,
3026 value: false
3027 },
3028 fitContainer: {
3029 type: Boolean,
3030 value: false
3031 },
3032 disableDrag: {
3033 type: Boolean,
3034 value: false
3035 },
3036 hideScrollButtons: {
3037 type: Boolean,
3038 value: false
3039 },
3040 alignBottom: {
3041 type: Boolean,
3042 value: false
3043 },
3044 selectable: {
3045 type: String,
3046 value: 'paper-tab'
3047 },
3048 autoselect: {
3049 type: Boolean,
3050 value: false
3051 },
3052 autoselectDelay: {
3053 type: Number,
3054 value: 0
3055 },
3056 _step: {
3057 type: Number,
3058 value: 10
3059 },
3060 _holdDelay: {
3061 type: Number,
3062 value: 1
3063 },
3064 _leftHidden: {
3065 type: Boolean,
3066 value: false
3067 },
3068 _rightHidden: {
3069 type: Boolean,
3070 value: false
3071 },
3072 _previousTab: {
3073 type: Object
3074 }
3075 },
3076 hostAttributes: {
3077 role: 'tablist'
3078 },
3079 listeners: {
3080 'iron-resize': '_onTabSizingChanged',
3081 'iron-items-changed': '_onTabSizingChanged',
3082 'iron-select': '_onIronSelect',
3083 'iron-deselect': '_onIronDeselect'
3084 },
3085 keyBindings: {
3086 'left:keyup right:keyup': '_onArrowKeyup'
3087 },
3088 created: function() {
3089 this._holdJob = null;
3090 this._pendingActivationItem = undefined;
3091 this._pendingActivationTimeout = undefined;
3092 this._bindDelayedActivationHandler = this._delayedActivationHandler.bind(thi s);
3093 this.addEventListener('blur', this._onBlurCapture.bind(this), true);
3094 },
3095 ready: function() {
3096 this.setScrollDirection('y', this.$.tabsContainer);
3097 },
3098 detached: function() {
3099 this._cancelPendingActivation();
3100 },
3101 _noinkChanged: function(noink) {
3102 var childTabs = Polymer.dom(this).querySelectorAll('paper-tab');
3103 childTabs.forEach(noink ? this._setNoinkAttribute : this._removeNoinkAttribu te);
3104 },
3105 _setNoinkAttribute: function(element) {
3106 element.setAttribute('noink', '');
3107 },
3108 _removeNoinkAttribute: function(element) {
3109 element.removeAttribute('noink');
3110 },
3111 _computeScrollButtonClass: function(hideThisButton, scrollable, hideScrollButt ons) {
3112 if (!scrollable || hideScrollButtons) {
3113 return 'hidden';
3114 }
3115 if (hideThisButton) {
3116 return 'not-visible';
3117 }
3118 return '';
3119 },
3120 _computeTabsContentClass: function(scrollable, fitContainer) {
3121 return scrollable ? 'scrollable' + (fitContainer ? ' fit-container' : '') : ' fit-container';
3122 },
3123 _computeSelectionBarClass: function(noBar, alignBottom) {
3124 if (noBar) {
3125 return 'hidden';
3126 } else if (alignBottom) {
3127 return 'align-bottom';
3128 }
3129 return '';
3130 },
3131 _onTabSizingChanged: function() {
3132 this.debounce('_onTabSizingChanged', function() {
3133 this._scroll();
3134 this._tabChanged(this.selectedItem);
3135 }, 10);
3136 },
3137 _onIronSelect: function(event) {
3138 this._tabChanged(event.detail.item, this._previousTab);
3139 this._previousTab = event.detail.item;
3140 this.cancelDebouncer('tab-changed');
3141 },
3142 _onIronDeselect: function(event) {
3143 this.debounce('tab-changed', function() {
3144 this._tabChanged(null, this._previousTab);
3145 this._previousTab = null;
3146 }, 1);
3147 },
3148 _activateHandler: function() {
3149 this._cancelPendingActivation();
3150 Polymer.IronMenuBehaviorImpl._activateHandler.apply(this, arguments);
3151 },
3152 _scheduleActivation: function(item, delay) {
3153 this._pendingActivationItem = item;
3154 this._pendingActivationTimeout = this.async(this._bindDelayedActivationHandl er, delay);
3155 },
3156 _delayedActivationHandler: function() {
3157 var item = this._pendingActivationItem;
3158 this._pendingActivationItem = undefined;
3159 this._pendingActivationTimeout = undefined;
3160 item.fire(this.activateEvent, null, {
3161 bubbles: true,
3162 cancelable: true
3163 });
3164 },
3165 _cancelPendingActivation: function() {
3166 if (this._pendingActivationTimeout !== undefined) {
3167 this.cancelAsync(this._pendingActivationTimeout);
3168 this._pendingActivationItem = undefined;
3169 this._pendingActivationTimeout = undefined;
3170 }
3171 },
3172 _onArrowKeyup: function(event) {
3173 if (this.autoselect) {
3174 this._scheduleActivation(this.focusedItem, this.autoselectDelay);
3175 }
3176 },
3177 _onBlurCapture: function(event) {
3178 if (event.target === this._pendingActivationItem) {
3179 this._cancelPendingActivation();
3180 }
3181 },
3182 get _tabContainerScrollSize() {
3183 return Math.max(0, this.$.tabsContainer.scrollWidth - this.$.tabsContainer.o ffsetWidth);
3184 },
3185 _scroll: function(e, detail) {
3186 if (!this.scrollable) {
3187 return;
3188 }
3189 var ddx = detail && -detail.ddx || 0;
3190 this._affectScroll(ddx);
3191 },
3192 _down: function(e) {
3193 this.async(function() {
3194 if (this._defaultFocusAsync) {
3195 this.cancelAsync(this._defaultFocusAsync);
3196 this._defaultFocusAsync = null;
3197 }
3198 }, 1);
3199 },
3200 _affectScroll: function(dx) {
3201 this.$.tabsContainer.scrollLeft += dx;
3202 var scrollLeft = this.$.tabsContainer.scrollLeft;
3203 this._leftHidden = scrollLeft === 0;
3204 this._rightHidden = scrollLeft === this._tabContainerScrollSize;
3205 },
3206 _onLeftScrollButtonDown: function() {
3207 this._scrollToLeft();
3208 this._holdJob = setInterval(this._scrollToLeft.bind(this), this._holdDelay);
3209 },
3210 _onRightScrollButtonDown: function() {
3211 this._scrollToRight();
3212 this._holdJob = setInterval(this._scrollToRight.bind(this), this._holdDelay) ;
3213 },
3214 _onScrollButtonUp: function() {
3215 clearInterval(this._holdJob);
3216 this._holdJob = null;
3217 },
3218 _scrollToLeft: function() {
3219 this._affectScroll(-this._step);
3220 },
3221 _scrollToRight: function() {
3222 this._affectScroll(this._step);
3223 },
3224 _tabChanged: function(tab, old) {
3225 if (!tab) {
3226 this.$.selectionBar.classList.remove('expand');
3227 this.$.selectionBar.classList.remove('contract');
3228 this._positionBar(0, 0);
3229 return;
3230 }
3231 var r = this.$.tabsContent.getBoundingClientRect();
3232 var w = r.width;
3233 var tabRect = tab.getBoundingClientRect();
3234 var tabOffsetLeft = tabRect.left - r.left;
3235 this._pos = {
3236 width: this._calcPercent(tabRect.width, w),
3237 left: this._calcPercent(tabOffsetLeft, w)
3238 };
3239 if (this.noSlide || old == null) {
3240 this.$.selectionBar.classList.remove('expand');
3241 this.$.selectionBar.classList.remove('contract');
3242 this._positionBar(this._pos.width, this._pos.left);
3243 return;
3244 }
3245 var oldRect = old.getBoundingClientRect();
3246 var oldIndex = this.items.indexOf(old);
3247 var index = this.items.indexOf(tab);
3248 var m = 5;
3249 this.$.selectionBar.classList.add('expand');
3250 var moveRight = oldIndex < index;
3251 var isRTL = this._isRTL;
3252 if (isRTL) {
3253 moveRight = !moveRight;
3254 }
3255 if (moveRight) {
3256 this._positionBar(this._calcPercent(tabRect.left + tabRect.width - oldRect .left, w) - m, this._left);
3257 } else {
3258 this._positionBar(this._calcPercent(oldRect.left + oldRect.width - tabRect .left, w) - m, this._calcPercent(tabOffsetLeft, w) + m);
3259 }
3260 if (this.scrollable) {
3261 this._scrollToSelectedIfNeeded(tabRect.width, tabOffsetLeft);
3262 }
3263 },
3264 _scrollToSelectedIfNeeded: function(tabWidth, tabOffsetLeft) {
3265 var l = tabOffsetLeft - this.$.tabsContainer.scrollLeft;
3266 if (l < 0) {
3267 this.$.tabsContainer.scrollLeft += l;
3268 } else {
3269 l += tabWidth - this.$.tabsContainer.offsetWidth;
3270 if (l > 0) {
3271 this.$.tabsContainer.scrollLeft += l;
3272 }
3273 }
3274 },
3275 _calcPercent: function(w, w0) {
3276 return 100 * w / w0;
3277 },
3278 _positionBar: function(width, left) {
3279 width = width || 0;
3280 left = left || 0;
3281 this._width = width;
3282 this._left = left;
3283 this.transform('translateX(' + left + '%) scaleX(' + width / 100 + ')', this .$.selectionBar);
3284 },
3285 _onBarTransitionEnd: function(e) {
3286 var cl = this.$.selectionBar.classList;
3287 if (cl.contains('expand')) {
3288 cl.remove('expand');
3289 cl.add('contract');
3290 this._positionBar(this._pos.width, this._pos.left);
3291 } else if (cl.contains('contract')) {
3292 cl.remove('contract');
3293 }
3294 }
3295 });
OLDNEW
« no previous file with comments | « chrome/browser/resources/md_history/app.vulcanized.html ('k') | chrome/browser/resources/md_history/lazy_load.vulcanized.html » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698