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

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

Issue 2643533003: MD History: Use one-way binding for history query state. (Closed)
Patch Set: Rebase Created 3 years, 11 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 // Copyright 2016 The Chromium Authors. All rights reserved. 1 // Copyright 2016 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 function PromiseResolver(){this.resolve_;this.reject_;this.promise_=new Promise( function(resolve,reject){this.resolve_=resolve;this.reject_=reject}.bind(this))} PromiseResolver.prototype={get promise(){return this.promise_},set promise(p){as sertNotReached()},get resolve(){return this.resolve_},set resolve(r){assertNotRe ached()},get reject(){return this.reject_},set reject(s){assertNotReached()}}; 4 function PromiseResolver(){this.resolve_;this.reject_;this.promise_=new Promise( function(resolve,reject){this.resolve_=resolve;this.reject_=reject}.bind(this))} PromiseResolver.prototype={get promise(){return this.promise_},set promise(p){as sertNotReached()},get resolve(){return this.resolve_},set resolve(r){assertNotRe ached()},get reject(){return this.reject_},set reject(s){assertNotReached()}};
5 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 5 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
6 // Use of this source code is governed by a BSD-style license that can be 6 // Use of this source code is governed by a BSD-style license that can be
7 // found in the LICENSE file. 7 // found in the LICENSE file.
8 var global=this;var WebUIListener;var cr=cr||function(){"use strict";function ex portPath(name,opt_object,opt_objectToExportTo){var parts=name.split(".");var cur =opt_objectToExportTo||global;for(var part;parts.length&&(part=parts.shift());){ if(!parts.length&&opt_object!==undefined){cur[part]=opt_object}else if(part in c ur){cur=cur[part]}else{cur=cur[part]={}}}return cur}function dispatchPropertyCha nge(target,propertyName,newValue,oldValue){var e=new Event(propertyName+"Change" );e.propertyName=propertyName;e.newValue=newValue;e.oldValue=oldValue;target.dis patchEvent(e)}function getAttributeName(jsName){return jsName.replace(/([A-Z])/g ,"-$1").toLowerCase()}var PropertyKind={JS:"js",ATTR:"attr",BOOL_ATTR:"boolAttr" };function getGetter(name,kind){switch(kind){case PropertyKind.JS:var privateNam e=name+"_";return function(){return this[privateName]};case PropertyKind.ATTR:va r attributeName=getAttributeName(name);return function(){return this.getAttribut e(attributeName)};case PropertyKind.BOOL_ATTR:var attributeName=getAttributeName (name);return function(){return this.hasAttribute(attributeName)}}throw"not reac hed"}function getSetter(name,kind,opt_setHook){switch(kind){case PropertyKind.JS :var privateName=name+"_";return function(value){var oldValue=this[name];if(valu e!==oldValue){this[privateName]=value;if(opt_setHook)opt_setHook.call(this,value ,oldValue);dispatchPropertyChange(this,name,value,oldValue)}};case PropertyKind. ATTR:var attributeName=getAttributeName(name);return function(value){var oldValu e=this[name];if(value!==oldValue){if(value==undefined)this.removeAttribute(attri buteName);else this.setAttribute(attributeName,value);if(opt_setHook)opt_setHook .call(this,value,oldValue);dispatchPropertyChange(this,name,value,oldValue)}};ca se PropertyKind.BOOL_ATTR:var attributeName=getAttributeName(name);return functi on(value){var oldValue=this[name];if(value!==oldValue){if(value)this.setAttribut e(attributeName,name);else this.removeAttribute(attributeName);if(opt_setHook)op t_setHook.call(this,value,oldValue);dispatchPropertyChange(this,name,value,oldVa lue)}}}throw"not reached"}function defineProperty(obj,name,opt_kind,opt_setHook) {if(typeof obj=="function")obj=obj.prototype;var kind=opt_kind||PropertyKind.JS; if(!obj.__lookupGetter__(name))obj.__defineGetter__(name,getGetter(name,kind));i f(!obj.__lookupSetter__(name))obj.__defineSetter__(name,getSetter(name,kind,opt_ setHook))}var uidCounter=1;function createUid(){return uidCounter++}function get Uid(item){if(item.hasOwnProperty("uid"))return item.uid;return item.uid=createUi d()}function dispatchSimpleEvent(target,type,opt_bubbles,opt_cancelable){var e=n ew Event(type,{bubbles:opt_bubbles,cancelable:opt_cancelable===undefined||opt_ca ncelable});return target.dispatchEvent(e)}function define(name,fun){var obj=expo rtPath(name);var exports=fun();for(var propertyName in exports){var propertyDesc riptor=Object.getOwnPropertyDescriptor(exports,propertyName);if(propertyDescript or)Object.defineProperty(obj,propertyName,propertyDescriptor)}}function addSingl etonGetter(ctor){ctor.getInstance=function(){return ctor.instance_||(ctor.instan ce_=new ctor)}}function makePublic(ctor,methods,opt_target){methods.forEach(func tion(method){ctor[method]=function(){var target=opt_target?document.getElementBy Id(opt_target):ctor.getInstance();return target[method+"_"].apply(target,argumen ts)}})}var chromeSendResolverMap={};function webUIResponse(id,isSuccess,response ){var resolver=chromeSendResolverMap[id];delete chromeSendResolverMap[id];if(isS uccess)resolver.resolve(response);else resolver.reject(response)}function sendWi thPromise(methodName,var_args){var args=Array.prototype.slice.call(arguments,1); var promiseResolver=new PromiseResolver;var id=methodName+"_"+createUid();chrome SendResolverMap[id]=promiseResolver;chrome.send(methodName,[id].concat(args));re turn promiseResolver.promise}var webUIListenerMap={};function webUIListenerCallb ack(event,var_args){var eventListenersMap=webUIListenerMap[event];if(!eventListe nersMap){return}var args=Array.prototype.slice.call(arguments,1);for(var listene rId in eventListenersMap){eventListenersMap[listenerId].apply(null,args)}}functi on addWebUIListener(eventName,callback){webUIListenerMap[eventName]=webUIListene rMap[eventName]||{};var uid=createUid();webUIListenerMap[eventName][uid]=callbac k;return{eventName:eventName,uid:uid}}function removeWebUIListener(listener){var listenerExists=webUIListenerMap[listener.eventName]&&webUIListenerMap[listener. eventName][listener.uid];if(listenerExists){delete webUIListenerMap[listener.eve ntName][listener.uid];return true}return false}return{addSingletonGetter:addSing letonGetter,createUid:createUid,define:define,defineProperty:defineProperty,disp atchPropertyChange:dispatchPropertyChange,dispatchSimpleEvent:dispatchSimpleEven t,exportPath:exportPath,getUid:getUid,makePublic:makePublic,PropertyKind:Propert yKind,addWebUIListener:addWebUIListener,removeWebUIListener:removeWebUIListener, sendWithPromise:sendWithPromise,webUIListenerCallback:webUIListenerCallback,webU IResponse:webUIResponse,get doc(){return document},get isMac(){return/Mac/.test( navigator.platform)},get isWindows(){return/Win/.test(navigator.platform)},get i sChromeOS(){return/CrOS/.test(navigator.userAgent)},get isLinux(){return/Linux/. test(navigator.userAgent)},get isAndroid(){return/Android/.test(navigator.userAg ent)},get isIOS(){return/iPad|iPhone|iPod/.test(navigator.platform)}}}(); 8 var global=this;var WebUIListener;var cr=cr||function(){"use strict";function ex portPath(name,opt_object,opt_objectToExportTo){var parts=name.split(".");var cur =opt_objectToExportTo||global;for(var part;parts.length&&(part=parts.shift());){ if(!parts.length&&opt_object!==undefined){cur[part]=opt_object}else if(part in c ur){cur=cur[part]}else{cur=cur[part]={}}}return cur}function dispatchPropertyCha nge(target,propertyName,newValue,oldValue){var e=new Event(propertyName+"Change" );e.propertyName=propertyName;e.newValue=newValue;e.oldValue=oldValue;target.dis patchEvent(e)}function getAttributeName(jsName){return jsName.replace(/([A-Z])/g ,"-$1").toLowerCase()}var PropertyKind={JS:"js",ATTR:"attr",BOOL_ATTR:"boolAttr" };function getGetter(name,kind){switch(kind){case PropertyKind.JS:var privateNam e=name+"_";return function(){return this[privateName]};case PropertyKind.ATTR:va r attributeName=getAttributeName(name);return function(){return this.getAttribut e(attributeName)};case PropertyKind.BOOL_ATTR:var attributeName=getAttributeName (name);return function(){return this.hasAttribute(attributeName)}}throw"not reac hed"}function getSetter(name,kind,opt_setHook){switch(kind){case PropertyKind.JS :var privateName=name+"_";return function(value){var oldValue=this[name];if(valu e!==oldValue){this[privateName]=value;if(opt_setHook)opt_setHook.call(this,value ,oldValue);dispatchPropertyChange(this,name,value,oldValue)}};case PropertyKind. ATTR:var attributeName=getAttributeName(name);return function(value){var oldValu e=this[name];if(value!==oldValue){if(value==undefined)this.removeAttribute(attri buteName);else this.setAttribute(attributeName,value);if(opt_setHook)opt_setHook .call(this,value,oldValue);dispatchPropertyChange(this,name,value,oldValue)}};ca se PropertyKind.BOOL_ATTR:var attributeName=getAttributeName(name);return functi on(value){var oldValue=this[name];if(value!==oldValue){if(value)this.setAttribut e(attributeName,name);else this.removeAttribute(attributeName);if(opt_setHook)op t_setHook.call(this,value,oldValue);dispatchPropertyChange(this,name,value,oldVa lue)}}}throw"not reached"}function defineProperty(obj,name,opt_kind,opt_setHook) {if(typeof obj=="function")obj=obj.prototype;var kind=opt_kind||PropertyKind.JS; if(!obj.__lookupGetter__(name))obj.__defineGetter__(name,getGetter(name,kind));i f(!obj.__lookupSetter__(name))obj.__defineSetter__(name,getSetter(name,kind,opt_ setHook))}var uidCounter=1;function createUid(){return uidCounter++}function get Uid(item){if(item.hasOwnProperty("uid"))return item.uid;return item.uid=createUi d()}function dispatchSimpleEvent(target,type,opt_bubbles,opt_cancelable){var e=n ew Event(type,{bubbles:opt_bubbles,cancelable:opt_cancelable===undefined||opt_ca ncelable});return target.dispatchEvent(e)}function define(name,fun){var obj=expo rtPath(name);var exports=fun();for(var propertyName in exports){var propertyDesc riptor=Object.getOwnPropertyDescriptor(exports,propertyName);if(propertyDescript or)Object.defineProperty(obj,propertyName,propertyDescriptor)}}function addSingl etonGetter(ctor){ctor.getInstance=function(){return ctor.instance_||(ctor.instan ce_=new ctor)}}function makePublic(ctor,methods,opt_target){methods.forEach(func tion(method){ctor[method]=function(){var target=opt_target?document.getElementBy Id(opt_target):ctor.getInstance();return target[method+"_"].apply(target,argumen ts)}})}var chromeSendResolverMap={};function webUIResponse(id,isSuccess,response ){var resolver=chromeSendResolverMap[id];delete chromeSendResolverMap[id];if(isS uccess)resolver.resolve(response);else resolver.reject(response)}function sendWi thPromise(methodName,var_args){var args=Array.prototype.slice.call(arguments,1); var promiseResolver=new PromiseResolver;var id=methodName+"_"+createUid();chrome SendResolverMap[id]=promiseResolver;chrome.send(methodName,[id].concat(args));re turn promiseResolver.promise}var webUIListenerMap={};function webUIListenerCallb ack(event,var_args){var eventListenersMap=webUIListenerMap[event];if(!eventListe nersMap){return}var args=Array.prototype.slice.call(arguments,1);for(var listene rId in eventListenersMap){eventListenersMap[listenerId].apply(null,args)}}functi on addWebUIListener(eventName,callback){webUIListenerMap[eventName]=webUIListene rMap[eventName]||{};var uid=createUid();webUIListenerMap[eventName][uid]=callbac k;return{eventName:eventName,uid:uid}}function removeWebUIListener(listener){var listenerExists=webUIListenerMap[listener.eventName]&&webUIListenerMap[listener. eventName][listener.uid];if(listenerExists){delete webUIListenerMap[listener.eve ntName][listener.uid];return true}return false}return{addSingletonGetter:addSing letonGetter,createUid:createUid,define:define,defineProperty:defineProperty,disp atchPropertyChange:dispatchPropertyChange,dispatchSimpleEvent:dispatchSimpleEven t,exportPath:exportPath,getUid:getUid,makePublic:makePublic,PropertyKind:Propert yKind,addWebUIListener:addWebUIListener,removeWebUIListener:removeWebUIListener, sendWithPromise:sendWithPromise,webUIListenerCallback:webUIListenerCallback,webU IResponse:webUIResponse,get doc(){return document},get isMac(){return/Mac/.test( navigator.platform)},get isWindows(){return/Win/.test(navigator.platform)},get i sChromeOS(){return/CrOS/.test(navigator.userAgent)},get isLinux(){return/Linux/. test(navigator.userAgent)},get isAndroid(){return/Android/.test(navigator.userAg ent)},get isIOS(){return/iPad|iPhone|iPod/.test(navigator.platform)}}}();
9 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 9 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
10 // Use of this source code is governed by a BSD-style license that can be 10 // Use of this source code is governed by a BSD-style license that can be
(...skipping 19 matching lines...) Expand all
30 // Use of this source code is governed by a BSD-style license that can be 30 // Use of this source code is governed by a BSD-style license that can be
31 // found in the LICENSE file. 31 // found in the LICENSE file.
32 Polymer({is:"cr-toolbar",properties:{pageName:String,searchPrompt:String,clearLa bel:String,menuLabel:String,menuPromo:String,spinnerActive:Boolean,showMenu:{typ e:Boolean,value:false},showMenuPromo:{type:Boolean,value:false},closeMenuPromo:S tring,narrow_:{type:Boolean,reflectToAttribute:true},showingSearch_:{type:Boolea n,reflectToAttribute:true}},observers:["possiblyShowMenuPromo_(showMenu, showMen uPromo, showingSearch_)"],getSearchField:function(){return this.$.search},onClos ePromoTap_:function(){this.fire("cr-toolbar-menu-promo-close")},onMenuTap_:funct ion(){this.fire("cr-toolbar-menu-tap")},possiblyShowMenuPromo_:function(){Polyme r.RenderStatus.afterNextRender(this,function(){if(this.showMenu&&this.showMenuPr omo&&!this.showingSearch_){this.$$("#menuPromo").animate({opacity:[0,.9]},{durat ion:500,fill:"forwards"});this.fire("cr-toolbar-menu-promo-shown")}}.bind(this)) },titleIfNotShowMenuPromo_:function(title,showMenuPromo){return showMenuPromo?"" :title}}); 32 Polymer({is:"cr-toolbar",properties:{pageName:String,searchPrompt:String,clearLa bel:String,menuLabel:String,menuPromo:String,spinnerActive:Boolean,showMenu:{typ e:Boolean,value:false},showMenuPromo:{type:Boolean,value:false},closeMenuPromo:S tring,narrow_:{type:Boolean,reflectToAttribute:true},showingSearch_:{type:Boolea n,reflectToAttribute:true}},observers:["possiblyShowMenuPromo_(showMenu, showMen uPromo, showingSearch_)"],getSearchField:function(){return this.$.search},onClos ePromoTap_:function(){this.fire("cr-toolbar-menu-promo-close")},onMenuTap_:funct ion(){this.fire("cr-toolbar-menu-tap")},possiblyShowMenuPromo_:function(){Polyme r.RenderStatus.afterNextRender(this,function(){if(this.showMenu&&this.showMenuPr omo&&!this.showingSearch_){this.$$("#menuPromo").animate({opacity:[0,.9]},{durat ion:500,fill:"forwards"});this.fire("cr-toolbar-menu-promo-shown")}}.bind(this)) },titleIfNotShowMenuPromo_:function(title,showMenuPromo){return showMenuPromo?"" :title}});
33 // Copyright 2016 The Chromium Authors. All rights reserved. 33 // Copyright 2016 The Chromium Authors. All rights reserved.
34 // Use of this source code is governed by a BSD-style license that can be 34 // Use of this source code is governed by a BSD-style license that can be
35 // found in the LICENSE file. 35 // found in the LICENSE file.
36 cr.define("md_history",function(){function BrowserService(){this.pendingDeleteIt ems_=null;this.pendingDeletePromise_=null}BrowserService.prototype={deleteItems: function(items){if(this.pendingDeleteItems_!=null){return new Promise(function(r esolve,reject){reject(items)})}var removalList=items.map(function(item){return{u rl:item.url,timestamps:item.allTimestamps}});this.pendingDeleteItems_=items;this .pendingDeletePromise_=new PromiseResolver;chrome.send("removeVisits",removalLis t);return this.pendingDeletePromise_.promise},removeBookmark:function(url){chrom e.send("removeBookmark",[url])},openForeignSessionAllTabs:function(sessionTag){c hrome.send("openForeignSession",[sessionTag])},openForeignSessionTab:function(se ssionTag,windowId,tabId,e){chrome.send("openForeignSession",[sessionTag,String(w indowId),String(tabId),e.button||0,e.altKey,e.ctrlKey,e.metaKey,e.shiftKey])},de leteForeignSession:function(sessionTag){chrome.send("deleteForeignSession",[sess ionTag])},openClearBrowsingData:function(){chrome.send("clearBrowsingData")},rec ordHistogram:function(histogram,value,max){chrome.send("metricsHandler:recordInH istogram",[histogram,value,max])},recordAction:function(action){if(action.indexO f("_")==-1)action="HistoryPage_"+action;chrome.send("metricsHandler:recordAction ",[action])},resolveDelete_:function(successful){if(this.pendingDeleteItems_==nu ll||this.pendingDeletePromise_==null){return}if(successful)this.pendingDeletePro mise_.resolve(this.pendingDeleteItems_);else this.pendingDeletePromise_.reject(t his.pendingDeleteItems_);this.pendingDeleteItems_=null;this.pendingDeletePromise _=null},menuPromoShown:function(){chrome.send("menuPromoShown")}};cr.addSingleto nGetter(BrowserService);return{BrowserService:BrowserService}});function deleteC omplete(){md_history.BrowserService.getInstance().resolveDelete_(true)}function deleteFailed(){md_history.BrowserService.getInstance().resolveDelete_(false)} 36 cr.define("md_history",function(){function BrowserService(){this.pendingDeleteIt ems_=null;this.pendingDeletePromise_=null}BrowserService.prototype={deleteItems: function(items){if(this.pendingDeleteItems_!=null){return new Promise(function(r esolve,reject){reject(items)})}var removalList=items.map(function(item){return{u rl:item.url,timestamps:item.allTimestamps}});this.pendingDeleteItems_=items;this .pendingDeletePromise_=new PromiseResolver;chrome.send("removeVisits",removalLis t);return this.pendingDeletePromise_.promise},removeBookmark:function(url){chrom e.send("removeBookmark",[url])},openForeignSessionAllTabs:function(sessionTag){c hrome.send("openForeignSession",[sessionTag])},openForeignSessionTab:function(se ssionTag,windowId,tabId,e){chrome.send("openForeignSession",[sessionTag,String(w indowId),String(tabId),e.button||0,e.altKey,e.ctrlKey,e.metaKey,e.shiftKey])},de leteForeignSession:function(sessionTag){chrome.send("deleteForeignSession",[sess ionTag])},openClearBrowsingData:function(){chrome.send("clearBrowsingData")},rec ordHistogram:function(histogram,value,max){chrome.send("metricsHandler:recordInH istogram",[histogram,value,max])},recordAction:function(action){if(action.indexO f("_")==-1)action="HistoryPage_"+action;chrome.send("metricsHandler:recordAction ",[action])},resolveDelete_:function(successful){if(this.pendingDeleteItems_==nu ll||this.pendingDeletePromise_==null){return}if(successful)this.pendingDeletePro mise_.resolve(this.pendingDeleteItems_);else this.pendingDeletePromise_.reject(t his.pendingDeleteItems_);this.pendingDeleteItems_=null;this.pendingDeletePromise _=null},menuPromoShown:function(){chrome.send("menuPromoShown")}};cr.addSingleto nGetter(BrowserService);return{BrowserService:BrowserService}});function deleteC omplete(){md_history.BrowserService.getInstance().resolveDelete_(true)}function deleteFailed(){md_history.BrowserService.getInstance().resolveDelete_(false)}
37 // Copyright 2015 The Chromium Authors. All rights reserved. 37 // Copyright 2015 The Chromium Authors. All rights reserved.
38 // Use of this source code is governed by a BSD-style license that can be 38 // Use of this source code is governed by a BSD-style license that can be
39 // found in the LICENSE file. 39 // found in the LICENSE file.
40 Polymer({is:"history-toolbar",properties:{count:{type:Number,value:0,observer:"c hangeToolbarView_"},itemsSelected_:{type:Boolean,value:false,reflectToAttribute: true},searchTerm:{type:String,observer:"searchTermChanged_",notify:true},spinner Active:{type:Boolean,value:false},hasDrawer:{type:Boolean,reflectToAttribute:tru e},isGroupedMode:{type:Boolean,reflectToAttribute:true},groupedRange:{type:Numbe r,reflectToAttribute:true,notify:true},groupedOffset:{type:Number,notify:true},h asMoreResults:Boolean,querying:Boolean,queryInfo:Object,showMenuPromo:Boolean,sh owSyncNotice:Boolean},get searchField(){return this.$["main-toolbar"].getSearchF ield()},showSearchField:function(){this.searchField.showAndFocus()},changeToolba rView_:function(){this.itemsSelected_=this.count>0},searchTermChanged_:function( ){if(this.searchField.getValue()!=this.searchTerm){this.searchField.showAndFocus ();this.searchField.setValue(this.searchTerm)}},onSearchChanged_:function(event) {this.searchTerm=event.detail},onInfoButtonTap_:function(){var dropdown=this.$.s yncNotice.get();dropdown.positionTarget=this.$$("#info-button-icon");if(dropdown .style.display=="none")dropdown.open()},onClearSelectionTap_:function(){this.fir e("unselect-all")},onDeleteTap_:function(){this.fire("delete-selected")},deletin gAllowed_:function(){return loadTimeData.getBoolean("allowDeletingHistory")},num berOfItemsSelected_:function(count){return count>0?loadTimeData.getStringF("item sSelected",count):""},getHistoryInterval_:function(){var info=this.queryInfo;if( this.groupedRange==HistoryRange.WEEK)return info.queryInterval;if(this.groupedRa nge==HistoryRange.MONTH)return info.queryStartMonth},onTodayTap_:function(){if(! this.querying)this.groupedOffset=0},onPrevTap_:function(){if(!this.querying)this .groupedOffset=this.groupedOffset+1},onNextTap_:function(){if(!this.querying)thi s.groupedOffset=this.groupedOffset-1},isToday_:function(){return this.groupedOff set==0}});(function(){"use strict";Polymer.IronA11yAnnouncer=Polymer({is:"iron-a 11y-announcer",properties:{mode:{type:String,value:"polite"},_text:{type:String, value:""}},created:function(){if(!Polymer.IronA11yAnnouncer.instance){Polymer.Ir onA11yAnnouncer.instance=this}document.body.addEventListener("iron-announce",thi s._onIronAnnounce.bind(this))},announce:function(text){this._text="";this.async( function(){this._text=text},100)},_onIronAnnounce:function(event){if(event.detai l&&event.detail.text){this.announce(event.detail.text)}}});Polymer.IronA11yAnnou ncer.instance=null;Polymer.IronA11yAnnouncer.requestAvailability=function(){if(! Polymer.IronA11yAnnouncer.instance){Polymer.IronA11yAnnouncer.instance=document. createElement("iron-a11y-announcer")}document.body.appendChild(Polymer.IronA11yA nnouncer.instance)}})();(function(){var IOS=navigator.userAgent.match(/iP(?:hone |ad;(?: U;)? CPU) OS (\d+)/);var IOS_TOUCH_SCROLLING=IOS&&IOS[1]>=8;var DEFAULT_ PHYSICAL_COUNT=3;var HIDDEN_Y="-10000px";var ITEM_WIDTH=0;var ITEM_HEIGHT=1;var SECRET_TABINDEX=-100;Polymer({is:"iron-list",properties:{items:{type:Array},maxP hysicalCount:{type:Number,value:500},as:{type:String,value:"item"},indexAs:{type :String,value:"index"},selectedAs:{type:String,value:"selected"},grid:{type:Bool ean,value:false,reflectToAttribute:true},selectionEnabled:{type:Boolean,value:fa lse},selectedItem:{type:Object,notify:true},selectedItems:{type:Object,notify:tr ue},multiSelection:{type:Boolean,value:false}},observers:["_itemsChanged(items.* )","_selectionEnabledChanged(selectionEnabled)","_multiSelectionChanged(multiSel ection)","_setOverflow(scrollTarget)"],behaviors:[Polymer.Templatizer,Polymer.Ir onResizableBehavior,Polymer.IronA11yKeysBehavior,Polymer.IronScrollTargetBehavio r],keyBindings:{up:"_didMoveUp",down:"_didMoveDown",enter:"_didEnter"},_ratio:.5 ,_scrollerPaddingTop:0,_scrollPosition:0,_physicalSize:0,_physicalAverage:0,_phy sicalAverageCount:0,_physicalTop:0,_virtualCount:0,_physicalIndexForKey:null,_es tScrollHeight:0,_scrollHeight:0,_viewportHeight:0,_viewportWidth:0,_physicalItem s:null,_physicalSizes:null,_firstVisibleIndexVal:null,_lastVisibleIndexVal:null, _collection:null,_maxPages:2,_focusedItem:null,_focusedIndex:-1,_offscreenFocuse dItem:null,_focusBackfillItem:null,_itemsPerRow:1,_itemWidth:0,_rowHeight:0,_tem plateCost:0,get _physicalBottom(){return this._physicalTop+this._physicalSize},g et _scrollBottom(){return this._scrollPosition+this._viewportHeight},get _virtua lEnd(){return this._virtualStart+this._physicalCount-1},get _hiddenContentSize() {var size=this.grid?this._physicalRows*this._rowHeight:this._physicalSize;return size-this._viewportHeight},get _maxScrollTop(){return this._estScrollHeight-thi s._viewportHeight+this._scrollerPaddingTop},_minVirtualStart:0,get _maxVirtualSt art(){return Math.max(0,this._virtualCount-this._physicalCount)},_virtualStartVa l:0,set _virtualStart(val){this._virtualStartVal=Math.min(this._maxVirtualStart, Math.max(this._minVirtualStart,val))},get _virtualStart(){return this._virtualSt artVal||0},_physicalStartVal:0,set _physicalStart(val){this._physicalStartVal=va l%this._physicalCount;if(this._physicalStartVal<0){this._physicalStartVal=this._ physicalCount+this._physicalStartVal}this._physicalEnd=(this._physicalStart+this ._physicalCount-1)%this._physicalCount},get _physicalStart(){return this._physic alStartVal||0},_physicalCountVal:0,set _physicalCount(val){this._physicalCountVa l=val;this._physicalEnd=(this._physicalStart+this._physicalCount-1)%this._physic alCount},get _physicalCount(){return this._physicalCountVal},_physicalEnd:0,get _optPhysicalSize(){if(this.grid){return this._estRowsInView*this._rowHeight*this ._maxPages}return this._viewportHeight*this._maxPages},get _isVisible(){return B oolean(this.offsetWidth||this.offsetHeight)},get firstVisibleIndex(){if(this._fi rstVisibleIndexVal===null){var physicalOffset=Math.floor(this._physicalTop+this. _scrollerPaddingTop);this._firstVisibleIndexVal=this._iterateItems(function(pidx ,vidx){physicalOffset+=this._getPhysicalSizeIncrement(pidx);if(physicalOffset>th is._scrollPosition){return this.grid?vidx-vidx%this._itemsPerRow:vidx}if(this.gr id&&this._virtualCount-1===vidx){return vidx-vidx%this._itemsPerRow}})||0}return this._firstVisibleIndexVal},get lastVisibleIndex(){if(this._lastVisibleIndexVal ===null){if(this.grid){var lastIndex=this.firstVisibleIndex+this._estRowsInView* this._itemsPerRow-1;this._lastVisibleIndexVal=Math.min(this._virtualCount,lastIn dex)}else{var physicalOffset=this._physicalTop;this._iterateItems(function(pidx, vidx){if(physicalOffset<this._scrollBottom){this._lastVisibleIndexVal=vidx}else{ return true}physicalOffset+=this._getPhysicalSizeIncrement(pidx)})}}return this. _lastVisibleIndexVal},get _defaultScrollTarget(){return this},get _virtualRowCou nt(){return Math.ceil(this._virtualCount/this._itemsPerRow)},get _estRowsInView( ){return Math.ceil(this._viewportHeight/this._rowHeight)},get _physicalRows(){re turn Math.ceil(this._physicalCount/this._itemsPerRow)},ready:function(){this.add EventListener("focus",this._didFocus.bind(this),true)},attached:function(){if(th is._physicalCount===0){this._debounceTemplate(this._render)}this.listen(this,"ir on-resize","_resizeHandler")},detached:function(){this.unlisten(this,"iron-resiz e","_resizeHandler")},_setOverflow:function(scrollTarget){this.style.webkitOverf lowScrolling=scrollTarget===this?"touch":"";this.style.overflow=scrollTarget===t his?"auto":""},updateViewportBoundaries:function(){this._scrollerPaddingTop=this .scrollTarget===this?0:parseInt(window.getComputedStyle(this)["padding-top"],10) ;this._viewportWidth=this.$.items.offsetWidth;this._viewportHeight=this._scrollT argetHeight;this.grid&&this._updateGridMetrics()},_scrollHandler:function(){var scrollTop=Math.max(0,Math.min(this._maxScrollTop,this._scrollTop));var delta=scr ollTop-this._scrollPosition;var isScrollingDown=delta>=0;this._scrollPosition=sc rollTop;this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null;if(Math.a bs(delta)>this._physicalSize){var idxAdjustment=Math.round(delta/this._physicalA verage)*this._itemsPerRow;this._physicalTop=this._physicalTop+delta;this._virtua lStart=this._virtualStart+idxAdjustment;this._physicalStart=this._physicalStart+ idxAdjustment;this._update()}else{var reusables=this._getReusables(isScrollingDo wn);if(isScrollingDown){this._physicalTop=reusables.physicalTop;this._virtualSta rt=this._virtualStart+reusables.indexes.length;this._physicalStart=this._physica lStart+reusables.indexes.length}else{this._virtualStart=this._virtualStart-reusa bles.indexes.length;this._physicalStart=this._physicalStart-reusables.indexes.le ngth}if(reusables.indexes.length===0){this._increasePoolIfNeeded()}else{this._up date(reusables.indexes,isScrollingDown?null:reusables.indexes)}}},_getReusables: function(fromTop){var ith,lastIth,offsetContent,physicalItemHeight;var idxs=[];v ar protectedOffsetContent=this._hiddenContentSize*this._ratio;var virtualStart=t his._virtualStart;var virtualEnd=this._virtualEnd;var physicalCount=this._physic alCount;var physicalTop=this._physicalTop+this._scrollerPaddingTop;var scrollTop =this._scrollTop;var scrollBottom=this._scrollBottom;if(fromTop){ith=this._physi calStart;lastIth=this._physicalEnd;offsetContent=scrollTop-physicalTop}else{ith= this._physicalEnd;lastIth=this._physicalStart;offsetContent=this._physicalBottom -scrollBottom}while(true){physicalItemHeight=this._getPhysicalSizeIncrement(ith) ;offsetContent=offsetContent-physicalItemHeight;if(idxs.length>=physicalCount||o ffsetContent<=protectedOffsetContent){break}if(fromTop){if(virtualEnd+idxs.lengt h+1>=this._virtualCount){break}if(physicalTop+physicalItemHeight>=scrollTop){bre ak}idxs.push(ith);physicalTop=physicalTop+physicalItemHeight;ith=(ith+1)%physica lCount}else{if(virtualStart-idxs.length<=0){break}if(physicalTop+this._physicalS ize-physicalItemHeight<=scrollBottom){break}idxs.push(ith);physicalTop=physicalT op-physicalItemHeight;ith=ith===0?physicalCount-1:ith-1}}return{indexes:idxs,phy sicalTop:physicalTop-this._scrollerPaddingTop}},_update:function(itemSet,movingU p){if(itemSet&&itemSet.length===0){return}this._manageFocus();this._assignModels (itemSet);this._updateMetrics(itemSet);if(movingUp){while(movingUp.length){var i dx=movingUp.pop();this._physicalTop-=this._getPhysicalSizeIncrement(idx)}}this._ positionItems();this._updateScrollerSize();this._increasePoolIfNeeded()},_create Pool:function(size){var physicalItems=new Array(size);this._ensureTemplatized(); for(var i=0;i<size;i++){var inst=this.stamp(null);physicalItems[i]=inst.root.que rySelector("*");Polymer.dom(this).appendChild(inst.root)}return physicalItems},_ increasePoolIfNeeded:function(){if(this._viewportHeight===0){return false}var se lf=this;var isClientFull=this._physicalBottom>=this._scrollBottom&&this._physica lTop<=this._scrollPosition;if(this._physicalSize>=this._optPhysicalSize&&isClien tFull){return false}var maxPoolSize=Math.round(this._physicalCount*.5);if(!isCli entFull){this._debounceTemplate(this._increasePool.bind(this,maxPoolSize));retur n true}this._yield(function(){self._increasePool(Math.min(maxPoolSize,Math.max(1 ,Math.round(50/self._templateCost))))});return true},_yield:function(cb){var g=w indow;var handle=g.requestIdleCallback?g.requestIdleCallback(cb):g.setTimeout(cb ,16);Polymer.dom.addDebouncer({complete:function(){g.cancelIdleCallback?g.cancel IdleCallback(handle):g.clearTimeout(handle);cb()}})},_increasePool:function(miss ingItems){var nextPhysicalCount=Math.min(this._physicalCount+missingItems,this._ virtualCount-this._virtualStart,Math.max(this.maxPhysicalCount,DEFAULT_PHYSICAL_ COUNT));var prevPhysicalCount=this._physicalCount;var delta=nextPhysicalCount-pr evPhysicalCount;var ts=window.performance.now();if(delta<=0){return}[].push.appl y(this._physicalItems,this._createPool(delta));[].push.apply(this._physicalSizes ,new Array(delta));this._physicalCount=prevPhysicalCount+delta;if(this._physical Start>this._physicalEnd&&this._isIndexRendered(this._focusedIndex)&&this._getPhy sicalIndex(this._focusedIndex)<this._physicalEnd){this._physicalStart=this._phys icalStart+delta}this._update();this._templateCost=(window.performance.now()-ts)/ delta},_render:function(){if(this.isAttached&&this._isVisible){if(this._physical Count===0){this.updateViewportBoundaries();this._increasePool(DEFAULT_PHYSICAL_C OUNT)}else{var reusables=this._getReusables(true);this._physicalTop=reusables.ph ysicalTop;this._virtualStart=this._virtualStart+reusables.indexes.length;this._p hysicalStart=this._physicalStart+reusables.indexes.length;this._update(reusables .indexes);this._update()}}},_ensureTemplatized:function(){if(!this.ctor){var pro ps={};props.__key__=true;props[this.as]=true;props[this.indexAs]=true;props[this .selectedAs]=true;props.tabIndex=true;this._instanceProps=props;this._userTempla te=Polymer.dom(this).querySelector("template");if(this._userTemplate){this.templ atize(this._userTemplate)}else{console.warn("iron-list requires a template to be provided in light-dom")}}},_getStampedChildren:function(){return this._physical Items},_forwardInstancePath:function(inst,path,value){if(path.indexOf(this.as+". ")===0){this.notifyPath("items."+inst.__key__+"."+path.slice(this.as.length+1),v alue)}},_forwardParentProp:function(prop,value){if(this._physicalItems){this._ph ysicalItems.forEach(function(item){item._templateInstance[prop]=value},this)}},_ forwardParentPath:function(path,value){if(this._physicalItems){this._physicalIte ms.forEach(function(item){item._templateInstance.notifyPath(path,value,true)},th is)}},_forwardItemPath:function(path,value){if(!this._physicalIndexForKey){retur n}var dot=path.indexOf(".");var key=path.substring(0,dot<0?path.length:dot);var idx=this._physicalIndexForKey[key];var offscreenItem=this._offscreenFocusedItem; var el=offscreenItem&&offscreenItem._templateInstance.__key__===key?offscreenIte m:this._physicalItems[idx];if(!el||el._templateInstance.__key__!==key){return}if (dot>=0){path=this.as+"."+path.substring(dot+1);el._templateInstance.notifyPath( path,value,true)}else{var currentItem=el._templateInstance[this.as];if(Array.isA rray(this.selectedItems)){for(var i=0;i<this.selectedItems.length;i++){if(this.s electedItems[i]===currentItem){this.set("selectedItems."+i,value);break}}}else i f(this.selectedItem===currentItem){this.set("selectedItem",value)}el._templateIn stance[this.as]=value}},_itemsChanged:function(change){if(change.path==="items") {this._virtualStart=0;this._physicalTop=0;this._virtualCount=this.items?this.ite ms.length:0;this._collection=this.items?Polymer.Collection.get(this.items):null; this._physicalIndexForKey={};this._firstVisibleIndexVal=null;this._lastVisibleIn dexVal=null;this._physicalCount=this._physicalCount||0;this._physicalItems=this. _physicalItems||[];this._physicalSizes=this._physicalSizes||[];this._physicalSta rt=0;this._resetScrollPosition(0);this._removeFocusedItem();this._debounceTempla te(this._render)}else if(change.path==="items.splices"){this._adjustVirtualIndex (change.value.indexSplices);this._virtualCount=this.items?this.items.length:0;th is._debounceTemplate(this._render)}else{this._forwardItemPath(change.path.split( ".").slice(1).join("."),change.value)}},_adjustVirtualIndex:function(splices){sp lices.forEach(function(splice){splice.removed.forEach(this._removeItem,this);if( splice.index<this._virtualStart){var delta=Math.max(splice.addedCount-splice.rem oved.length,splice.index-this._virtualStart);this._virtualStart=this._virtualSta rt+delta;if(this._focusedIndex>=0){this._focusedIndex=this._focusedIndex+delta}} },this)},_removeItem:function(item){this.$.selector.deselect(item);if(this._focu sedItem&&this._focusedItem._templateInstance[this.as]===item){this._removeFocuse dItem()}},_iterateItems:function(fn,itemSet){var pidx,vidx,rtn,i;if(arguments.le ngth===2&&itemSet){for(i=0;i<itemSet.length;i++){pidx=itemSet[i];vidx=this._comp uteVidx(pidx);if((rtn=fn.call(this,pidx,vidx))!=null){return rtn}}}else{pidx=thi s._physicalStart;vidx=this._virtualStart;for(;pidx<this._physicalCount;pidx++,vi dx++){if((rtn=fn.call(this,pidx,vidx))!=null){return rtn}}for(pidx=0;pidx<this._ physicalStart;pidx++,vidx++){if((rtn=fn.call(this,pidx,vidx))!=null){return rtn} }}},_computeVidx:function(pidx){if(pidx>=this._physicalStart){return this._virtu alStart+(pidx-this._physicalStart)}return this._virtualStart+(this._physicalCoun t-this._physicalStart)+pidx},_assignModels:function(itemSet){this._iterateItems( function(pidx,vidx){var el=this._physicalItems[pidx];var inst=el._templateInstan ce;var item=this.items&&this.items[vidx];if(item!=null){inst[this.as]=item;inst. __key__=this._collection.getKey(item);inst[this.selectedAs]=this.$.selector.isSe lected(item);inst[this.indexAs]=vidx;inst.tabIndex=this._focusedIndex===vidx?0:- 1;this._physicalIndexForKey[inst.__key__]=pidx;el.removeAttribute("hidden")}else {inst.__key__=null;el.setAttribute("hidden","")}},itemSet)},_updateMetrics:funct ion(itemSet){Polymer.dom.flush();var newPhysicalSize=0;var oldPhysicalSize=0;var prevAvgCount=this._physicalAverageCount;var prevPhysicalAvg=this._physicalAvera ge;this._iterateItems(function(pidx,vidx){oldPhysicalSize+=this._physicalSizes[p idx]||0;this._physicalSizes[pidx]=this._physicalItems[pidx].offsetHeight;newPhys icalSize+=this._physicalSizes[pidx];this._physicalAverageCount+=this._physicalSi zes[pidx]?1:0},itemSet);if(this.grid){this._updateGridMetrics();this._physicalSi ze=Math.ceil(this._physicalCount/this._itemsPerRow)*this._rowHeight}else{this._p hysicalSize=this._physicalSize+newPhysicalSize-oldPhysicalSize}if(this._physical AverageCount!==prevAvgCount){this._physicalAverage=Math.round((prevPhysicalAvg*p revAvgCount+newPhysicalSize)/this._physicalAverageCount)}},_updateGridMetrics:fu nction(){this._itemWidth=this._physicalCount>0?this._physicalItems[0].getBoundin gClientRect().width:200;this._rowHeight=this._physicalCount>0?this._physicalItem s[0].offsetHeight:200;this._itemsPerRow=this._itemWidth?Math.floor(this._viewpor tWidth/this._itemWidth):this._itemsPerRow},_positionItems:function(){this._adjus tScrollPosition();var y=this._physicalTop;if(this.grid){var totalItemWidth=this. _itemsPerRow*this._itemWidth;var rowOffset=(this._viewportWidth-totalItemWidth)/ 2;this._iterateItems(function(pidx,vidx){var modulus=vidx%this._itemsPerRow;var x=Math.floor(modulus*this._itemWidth+rowOffset);this.translate3d(x+"px",y+"px",0 ,this._physicalItems[pidx]);if(this._shouldRenderNextRow(vidx)){y+=this._rowHeig ht}})}else{this._iterateItems(function(pidx,vidx){this.translate3d(0,y+"px",0,th is._physicalItems[pidx]);y+=this._physicalSizes[pidx]})}},_getPhysicalSizeIncrem ent:function(pidx){if(!this.grid){return this._physicalSizes[pidx]}if(this._comp uteVidx(pidx)%this._itemsPerRow!==this._itemsPerRow-1){return 0}return this._row Height},_shouldRenderNextRow:function(vidx){return vidx%this._itemsPerRow===this ._itemsPerRow-1},_adjustScrollPosition:function(){var deltaHeight=this._virtualS tart===0?this._physicalTop:Math.min(this._scrollPosition+this._physicalTop,0);if (deltaHeight){this._physicalTop=this._physicalTop-deltaHeight;if(!IOS_TOUCH_SCRO LLING&&this._physicalTop!==0){this._resetScrollPosition(this._scrollTop-deltaHei ght)}}},_resetScrollPosition:function(pos){if(this.scrollTarget){this._scrollTop =pos;this._scrollPosition=this._scrollTop}},_updateScrollerSize:function(forceUp date){if(this.grid){this._estScrollHeight=this._virtualRowCount*this._rowHeight} else{this._estScrollHeight=this._physicalBottom+Math.max(this._virtualCount-this ._physicalCount-this._virtualStart,0)*this._physicalAverage}forceUpdate=forceUpd ate||this._scrollHeight===0;forceUpdate=forceUpdate||this._scrollPosition>=this. _estScrollHeight-this._physicalSize;forceUpdate=forceUpdate||this.grid&&this.$.i tems.style.height<this._estScrollHeight;if(forceUpdate||Math.abs(this._estScroll Height-this._scrollHeight)>=this._optPhysicalSize){this.$.items.style.height=thi s._estScrollHeight+"px";this._scrollHeight=this._estScrollHeight}},scrollToItem: function(item){return this.scrollToIndex(this.items.indexOf(item))},scrollToInde x:function(idx){if(typeof idx!=="number"||idx<0||idx>this.items.length-1){return }Polymer.dom.flush();if(this._physicalCount===0){return}idx=Math.min(Math.max(id x,0),this._virtualCount-1);if(!this._isIndexRendered(idx)||idx>=this._maxVirtual Start){this._virtualStart=this.grid?idx-this._itemsPerRow*2:idx-1}this._manageFo cus();this._assignModels();this._updateMetrics();this._physicalTop=Math.floor(th is._virtualStart/this._itemsPerRow)*this._physicalAverage;var currentTopItem=thi s._physicalStart;var currentVirtualItem=this._virtualStart;var targetOffsetTop=0 ;var hiddenContentSize=this._hiddenContentSize;while(currentVirtualItem<idx&&tar getOffsetTop<=hiddenContentSize){targetOffsetTop=targetOffsetTop+this._getPhysic alSizeIncrement(currentTopItem);currentTopItem=(currentTopItem+1)%this._physical Count;currentVirtualItem++}this._updateScrollerSize(true);this._positionItems(); this._resetScrollPosition(this._physicalTop+this._scrollerPaddingTop+targetOffse tTop);this._increasePoolIfNeeded();this._firstVisibleIndexVal=null;this._lastVis ibleIndexVal=null},_resetAverage:function(){this._physicalAverage=0;this._physic alAverageCount=0},_resizeHandler:function(){var delta=Math.abs(this._viewportHei ght-this._scrollTargetHeight);if(IOS&&delta>0&&delta<100){return}Polymer.dom.add Debouncer(this.debounce("_debounceTemplate",function(){this.updateViewportBounda ries();this._render();if(this._isVisible){this.toggleScrollListener(true);if(thi s._physicalCount>0){this._resetAverage();this.scrollToIndex(this.firstVisibleInd ex)}}else{this.toggleScrollListener(false)}}.bind(this),1))},_getModelFromItem:f unction(item){var key=this._collection.getKey(item);var pidx=this._physicalIndex ForKey[key];if(pidx!=null){return this._physicalItems[pidx]._templateInstance}re turn null},_getNormalizedItem:function(item){if(this._collection.getKey(item)=== undefined){if(typeof item==="number"){item=this.items[item];if(!item){throw new RangeError("<item> not found")}return item}throw new TypeError("<item> should be a valid item")}return item},selectItem:function(item){item=this._getNormalizedI tem(item);var model=this._getModelFromItem(item);if(!this.multiSelection&&this.s electedItem){this.deselectItem(this.selectedItem)}if(model){model[this.selectedA s]=true}this.$.selector.select(item);this.updateSizeForItem(item)},deselectItem: function(item){item=this._getNormalizedItem(item);var model=this._getModelFromIt em(item);if(model){model[this.selectedAs]=false}this.$.selector.deselect(item);t his.updateSizeForItem(item)},toggleSelectionForItem:function(item){item=this._ge tNormalizedItem(item);if(this.$.selector.isSelected(item)){this.deselectItem(ite m)}else{this.selectItem(item)}},clearSelection:function(){function unselect(item ){var model=this._getModelFromItem(item);if(model){model[this.selectedAs]=false} }if(Array.isArray(this.selectedItems)){this.selectedItems.forEach(unselect,this) }else if(this.selectedItem){unselect.call(this,this.selectedItem)}this.$.selecto r.clearSelection()},_selectionEnabledChanged:function(selectionEnabled){var hand ler=selectionEnabled?this.listen:this.unlisten;handler.call(this,this,"tap","_se lectionHandler")},_selectionHandler:function(e){var model=this.modelForElement(e .target);if(!model){return}var modelTabIndex,activeElTabIndex;var target=Polymer .dom(e).path[0];var activeEl=Polymer.dom(this.domHost?this.domHost.root:document ).activeElement;var physicalItem=this._physicalItems[this._getPhysicalIndex(mode l[this.indexAs])];if(target.localName==="input"||target.localName==="button"||ta rget.localName==="select"){return}modelTabIndex=model.tabIndex;model.tabIndex=SE CRET_TABINDEX;activeElTabIndex=activeEl?activeEl.tabIndex:-1;model.tabIndex=mode lTabIndex;if(activeEl&&physicalItem!==activeEl&&physicalItem.contains(activeEl)& &activeElTabIndex!==SECRET_TABINDEX){return}this.toggleSelectionForItem(model[th is.as])},_multiSelectionChanged:function(multiSelection){this.clearSelection();t his.$.selector.multi=multiSelection},updateSizeForItem:function(item){item=this. _getNormalizedItem(item);var key=this._collection.getKey(item);var pidx=this._ph ysicalIndexForKey[key];if(pidx!=null){this._updateMetrics([pidx]);this._position Items()}},_manageFocus:function(){var fidx=this._focusedIndex;if(fidx>=0&&fidx<t his._virtualCount){if(this._isIndexRendered(fidx)){this._restoreFocusedItem()}el se{this._createFocusBackfillItem()}}else if(this._virtualCount>0&&this._physical Count>0){this._focusedIndex=this._virtualStart;this._focusedItem=this._physicalI tems[this._physicalStart]}},_isIndexRendered:function(idx){return idx>=this._vir tualStart&&idx<=this._virtualEnd},_isIndexVisible:function(idx){return idx>=this .firstVisibleIndex&&idx<=this.lastVisibleIndex},_getPhysicalIndex:function(idx){ return this._physicalIndexForKey[this._collection.getKey(this._getNormalizedItem (idx))]},_focusPhysicalItem:function(idx){if(idx<0||idx>=this._virtualCount){ret urn}this._restoreFocusedItem();if(!this._isIndexRendered(idx)){this.scrollToInde x(idx)}var physicalItem=this._physicalItems[this._getPhysicalIndex(idx)];var mod el=physicalItem._templateInstance;var focusable;model.tabIndex=SECRET_TABINDEX;i f(physicalItem.tabIndex===SECRET_TABINDEX){focusable=physicalItem}if(!focusable) {focusable=Polymer.dom(physicalItem).querySelector('[tabindex="'+SECRET_TABINDEX +'"]')}model.tabIndex=0;this._focusedIndex=idx;focusable&&focusable.focus()},_re moveFocusedItem:function(){if(this._offscreenFocusedItem){Polymer.dom(this).remo veChild(this._offscreenFocusedItem)}this._offscreenFocusedItem=null;this._focusB ackfillItem=null;this._focusedItem=null;this._focusedIndex=-1},_createFocusBackf illItem:function(){var fidx=this._focusedIndex;var pidx=this._getPhysicalIndex(f idx);if(this._offscreenFocusedItem||pidx==null||fidx<0){return}if(!this._focusBa ckfillItem){var stampedTemplate=this.stamp(null);this._focusBackfillItem=stamped Template.root.querySelector("*");Polymer.dom(this).appendChild(stampedTemplate.r oot)}this._offscreenFocusedItem=this._physicalItems[pidx];this._offscreenFocused Item._templateInstance.tabIndex=0;this._physicalItems[pidx]=this._focusBackfillI tem;this.translate3d(0,HIDDEN_Y,0,this._offscreenFocusedItem)},_restoreFocusedIt em:function(){var pidx,fidx=this._focusedIndex;if(!this._offscreenFocusedItem||t his._focusedIndex<0){return}this._assignModels();pidx=this._getPhysicalIndex(fid x);if(pidx!=null){this._focusBackfillItem=this._physicalItems[pidx];this._focusB ackfillItem._templateInstance.tabIndex=-1;this._physicalItems[pidx]=this._offscr eenFocusedItem;this._offscreenFocusedItem=null;this.translate3d(0,HIDDEN_Y,0,thi s._focusBackfillItem)}},_didFocus:function(e){var targetModel=this.modelForEleme nt(e.target);var focusedModel=this._focusedItem?this._focusedItem._templateInsta nce:null;var hasOffscreenFocusedItem=this._offscreenFocusedItem!==null;var fidx= this._focusedIndex;if(!targetModel||!focusedModel){return}if(focusedModel===targ etModel){if(!this._isIndexVisible(fidx)){this.scrollToIndex(fidx)}}else{this._re storeFocusedItem();focusedModel.tabIndex=-1;targetModel.tabIndex=0;fidx=targetMo del[this.indexAs];this._focusedIndex=fidx;this._focusedItem=this._physicalItems[ this._getPhysicalIndex(fidx)];if(hasOffscreenFocusedItem&&!this._offscreenFocuse dItem){this._update()}}},_didMoveUp:function(){this._focusPhysicalItem(this._foc usedIndex-1)},_didMoveDown:function(e){e.detail.keyboardEvent.preventDefault();t his._focusPhysicalItem(this._focusedIndex+1)},_didEnter:function(e){this._focusP hysicalItem(this._focusedIndex);this._selectionHandler(e.detail.keyboardEvent)}} )})();Polymer({is:"iron-scroll-threshold",properties:{upperThreshold:{type:Numbe r,value:100},lowerThreshold:{type:Number,value:100},upperTriggered:{type:Boolean ,value:false,notify:true,readOnly:true},lowerTriggered:{type:Boolean,value:false ,notify:true,readOnly:true},horizontal:{type:Boolean,value:false}},behaviors:[Po lymer.IronScrollTargetBehavior],observers:["_setOverflow(scrollTarget)","_initCh eck(horizontal, isAttached)"],get _defaultScrollTarget(){return this},_setOverfl ow:function(scrollTarget){this.style.overflow=scrollTarget===this?"auto":""},_sc rollHandler:function(){var THROTTLE_THRESHOLD=200;if(!this.isDebouncerActive("_c heckTheshold")){this.debounce("_checkTheshold",function(){this.checkScrollThesho lds()},THROTTLE_THRESHOLD)}},_initCheck:function(horizontal,isAttached){if(isAtt ached){this.debounce("_init",function(){this.clearTriggers();this.checkScrollThe sholds()})}},checkScrollThesholds:function(){if(!this.scrollTarget||this.lowerTr iggered&&this.upperTriggered){return}var upperScrollValue=this.horizontal?this._ scrollLeft:this._scrollTop;var lowerScrollValue=this.horizontal?this.scrollTarge t.scrollWidth-this._scrollTargetWidth-this._scrollLeft:this.scrollTarget.scrollH eight-this._scrollTargetHeight-this._scrollTop;if(upperScrollValue<=this.upperTh reshold&&!this.upperTriggered){this._setUpperTriggered(true);this.fire("upper-th reshold")}if(lowerScrollValue<=this.lowerThreshold&&!this.lowerTriggered){this._ setLowerTriggered(true);this.fire("lower-threshold")}},clearTriggers:function(){ this._setUpperTriggered(false);this._setLowerTriggered(false)}}); 40 Polymer({is:"history-toolbar",properties:{count:{type:Number,value:0,observer:"c hangeToolbarView_"},itemsSelected_:{type:Boolean,value:false,reflectToAttribute: true},searchTerm:{type:String,observer:"searchTermChanged_"},spinnerActive:{type :Boolean,value:false},hasDrawer:{type:Boolean,reflectToAttribute:true},isGrouped Mode:{type:Boolean,reflectToAttribute:true},groupedRange:{type:Number,reflectToA ttribute:true},groupedOffset:Number,hasMoreResults:Boolean,querying:Boolean,quer yInfo:Object,showMenuPromo:Boolean,showSyncNotice:Boolean},get searchField(){ret urn this.$["main-toolbar"].getSearchField()},showSearchField:function(){this.sea rchField.showAndFocus()},changeToolbarView_:function(){this.itemsSelected_=this. count>0},searchTermChanged_:function(){if(this.searchField.getValue()!=this.sear chTerm){this.searchField.showAndFocus();this.searchField.setValue(this.searchTer m)}},onSearchChanged_:function(event){this.fire("change-query",{search:event.det ail})},onInfoButtonTap_:function(){var dropdown=this.$.syncNotice.get();dropdown .positionTarget=this.$$("#info-button-icon");if(dropdown.style.display=="none")d ropdown.open()},onClearSelectionTap_:function(){this.fire("unselect-all")},onDel eteTap_:function(){this.fire("delete-selected")},deletingAllowed_:function(){ret urn loadTimeData.getBoolean("allowDeletingHistory")},numberOfItemsSelected_:func tion(count){return count>0?loadTimeData.getStringF("itemsSelected",count):""},ge tHistoryInterval_:function(){var info=this.queryInfo;if(this.groupedRange==Histo ryRange.WEEK)return info.queryInterval;if(this.groupedRange==HistoryRange.MONTH) return info.queryStartMonth},onTabSelected_:function(e){this.fire("change-query" ,{range:Number(e.detail.item.getAttribute("value"))})},changeOffset_:function(ne wOffset){if(!this.querying)this.fire("change-query",{offset:newOffset})},onToday Tap_:function(){this.changeOffset_(0)},onPrevTap_:function(){this.changeOffset_( this.groupedOffset+1)},onNextTap_:function(){this.changeOffset_(this.groupedOffs et-1)},isToday_:function(){return this.groupedOffset==0}});(function(){"use stri ct";Polymer.IronA11yAnnouncer=Polymer({is:"iron-a11y-announcer",properties:{mode :{type:String,value:"polite"},_text:{type:String,value:""}},created:function(){i f(!Polymer.IronA11yAnnouncer.instance){Polymer.IronA11yAnnouncer.instance=this}d ocument.body.addEventListener("iron-announce",this._onIronAnnounce.bind(this))}, announce:function(text){this._text="";this.async(function(){this._text=text},100 )},_onIronAnnounce:function(event){if(event.detail&&event.detail.text){this.anno unce(event.detail.text)}}});Polymer.IronA11yAnnouncer.instance=null;Polymer.Iron A11yAnnouncer.requestAvailability=function(){if(!Polymer.IronA11yAnnouncer.insta nce){Polymer.IronA11yAnnouncer.instance=document.createElement("iron-a11y-announ cer")}document.body.appendChild(Polymer.IronA11yAnnouncer.instance)}})();(functi on(){var IOS=navigator.userAgent.match(/iP(?:hone|ad;(?: U;)? CPU) OS (\d+)/);va r IOS_TOUCH_SCROLLING=IOS&&IOS[1]>=8;var DEFAULT_PHYSICAL_COUNT=3;var HIDDEN_Y=" -10000px";var ITEM_WIDTH=0;var ITEM_HEIGHT=1;var SECRET_TABINDEX=-100;Polymer({i s:"iron-list",properties:{items:{type:Array},maxPhysicalCount:{type:Number,value :500},as:{type:String,value:"item"},indexAs:{type:String,value:"index"},selected As:{type:String,value:"selected"},grid:{type:Boolean,value:false,reflectToAttrib ute:true},selectionEnabled:{type:Boolean,value:false},selectedItem:{type:Object, notify:true},selectedItems:{type:Object,notify:true},multiSelection:{type:Boolea n,value:false}},observers:["_itemsChanged(items.*)","_selectionEnabledChanged(se lectionEnabled)","_multiSelectionChanged(multiSelection)","_setOverflow(scrollTa rget)"],behaviors:[Polymer.Templatizer,Polymer.IronResizableBehavior,Polymer.Iro nA11yKeysBehavior,Polymer.IronScrollTargetBehavior],keyBindings:{up:"_didMoveUp" ,down:"_didMoveDown",enter:"_didEnter"},_ratio:.5,_scrollerPaddingTop:0,_scrollP osition:0,_physicalSize:0,_physicalAverage:0,_physicalAverageCount:0,_physicalTo p:0,_virtualCount:0,_physicalIndexForKey:null,_estScrollHeight:0,_scrollHeight:0 ,_viewportHeight:0,_viewportWidth:0,_physicalItems:null,_physicalSizes:null,_fir stVisibleIndexVal:null,_lastVisibleIndexVal:null,_collection:null,_maxPages:2,_f ocusedItem:null,_focusedIndex:-1,_offscreenFocusedItem:null,_focusBackfillItem:n ull,_itemsPerRow:1,_itemWidth:0,_rowHeight:0,_templateCost:0,get _physicalBottom (){return this._physicalTop+this._physicalSize},get _scrollBottom(){return this. _scrollPosition+this._viewportHeight},get _virtualEnd(){return this._virtualStar t+this._physicalCount-1},get _hiddenContentSize(){var size=this.grid?this._physi calRows*this._rowHeight:this._physicalSize;return size-this._viewportHeight},get _maxScrollTop(){return this._estScrollHeight-this._viewportHeight+this._scrolle rPaddingTop},_minVirtualStart:0,get _maxVirtualStart(){return Math.max(0,this._v irtualCount-this._physicalCount)},_virtualStartVal:0,set _virtualStart(val){this ._virtualStartVal=Math.min(this._maxVirtualStart,Math.max(this._minVirtualStart, val))},get _virtualStart(){return this._virtualStartVal||0},_physicalStartVal:0, set _physicalStart(val){this._physicalStartVal=val%this._physicalCount;if(this._ physicalStartVal<0){this._physicalStartVal=this._physicalCount+this._physicalSta rtVal}this._physicalEnd=(this._physicalStart+this._physicalCount-1)%this._physic alCount},get _physicalStart(){return this._physicalStartVal||0},_physicalCountVa l:0,set _physicalCount(val){this._physicalCountVal=val;this._physicalEnd=(this._ physicalStart+this._physicalCount-1)%this._physicalCount},get _physicalCount(){r eturn this._physicalCountVal},_physicalEnd:0,get _optPhysicalSize(){if(this.grid ){return this._estRowsInView*this._rowHeight*this._maxPages}return this._viewpor tHeight*this._maxPages},get _isVisible(){return Boolean(this.offsetWidth||this.o ffsetHeight)},get firstVisibleIndex(){if(this._firstVisibleIndexVal===null){var physicalOffset=Math.floor(this._physicalTop+this._scrollerPaddingTop);this._firs tVisibleIndexVal=this._iterateItems(function(pidx,vidx){physicalOffset+=this._ge tPhysicalSizeIncrement(pidx);if(physicalOffset>this._scrollPosition){return this .grid?vidx-vidx%this._itemsPerRow:vidx}if(this.grid&&this._virtualCount-1===vidx ){return vidx-vidx%this._itemsPerRow}})||0}return this._firstVisibleIndexVal},ge t lastVisibleIndex(){if(this._lastVisibleIndexVal===null){if(this.grid){var last Index=this.firstVisibleIndex+this._estRowsInView*this._itemsPerRow-1;this._lastV isibleIndexVal=Math.min(this._virtualCount,lastIndex)}else{var physicalOffset=th is._physicalTop;this._iterateItems(function(pidx,vidx){if(physicalOffset<this._s crollBottom){this._lastVisibleIndexVal=vidx}else{return true}physicalOffset+=thi s._getPhysicalSizeIncrement(pidx)})}}return this._lastVisibleIndexVal},get _defa ultScrollTarget(){return this},get _virtualRowCount(){return Math.ceil(this._vir tualCount/this._itemsPerRow)},get _estRowsInView(){return Math.ceil(this._viewpo rtHeight/this._rowHeight)},get _physicalRows(){return Math.ceil(this._physicalCo unt/this._itemsPerRow)},ready:function(){this.addEventListener("focus",this._did Focus.bind(this),true)},attached:function(){if(this._physicalCount===0){this._de bounceTemplate(this._render)}this.listen(this,"iron-resize","_resizeHandler")},d etached:function(){this.unlisten(this,"iron-resize","_resizeHandler")},_setOverf low:function(scrollTarget){this.style.webkitOverflowScrolling=scrollTarget===thi s?"touch":"";this.style.overflow=scrollTarget===this?"auto":""},updateViewportBo undaries:function(){this._scrollerPaddingTop=this.scrollTarget===this?0:parseInt (window.getComputedStyle(this)["padding-top"],10);this._viewportWidth=this.$.ite ms.offsetWidth;this._viewportHeight=this._scrollTargetHeight;this.grid&&this._up dateGridMetrics()},_scrollHandler:function(){var scrollTop=Math.max(0,Math.min(t his._maxScrollTop,this._scrollTop));var delta=scrollTop-this._scrollPosition;var isScrollingDown=delta>=0;this._scrollPosition=scrollTop;this._firstVisibleIndex Val=null;this._lastVisibleIndexVal=null;if(Math.abs(delta)>this._physicalSize){v ar idxAdjustment=Math.round(delta/this._physicalAverage)*this._itemsPerRow;this. _physicalTop=this._physicalTop+delta;this._virtualStart=this._virtualStart+idxAd justment;this._physicalStart=this._physicalStart+idxAdjustment;this._update()}el se{var reusables=this._getReusables(isScrollingDown);if(isScrollingDown){this._p hysicalTop=reusables.physicalTop;this._virtualStart=this._virtualStart+reusables .indexes.length;this._physicalStart=this._physicalStart+reusables.indexes.length }else{this._virtualStart=this._virtualStart-reusables.indexes.length;this._physi calStart=this._physicalStart-reusables.indexes.length}if(reusables.indexes.lengt h===0){this._increasePoolIfNeeded()}else{this._update(reusables.indexes,isScroll ingDown?null:reusables.indexes)}}},_getReusables:function(fromTop){var ith,lastI th,offsetContent,physicalItemHeight;var idxs=[];var protectedOffsetContent=this. _hiddenContentSize*this._ratio;var virtualStart=this._virtualStart;var virtualEn d=this._virtualEnd;var physicalCount=this._physicalCount;var physicalTop=this._p hysicalTop+this._scrollerPaddingTop;var scrollTop=this._scrollTop;var scrollBott om=this._scrollBottom;if(fromTop){ith=this._physicalStart;lastIth=this._physical End;offsetContent=scrollTop-physicalTop}else{ith=this._physicalEnd;lastIth=this. _physicalStart;offsetContent=this._physicalBottom-scrollBottom}while(true){physi calItemHeight=this._getPhysicalSizeIncrement(ith);offsetContent=offsetContent-ph ysicalItemHeight;if(idxs.length>=physicalCount||offsetContent<=protectedOffsetCo ntent){break}if(fromTop){if(virtualEnd+idxs.length+1>=this._virtualCount){break} if(physicalTop+physicalItemHeight>=scrollTop){break}idxs.push(ith);physicalTop=p hysicalTop+physicalItemHeight;ith=(ith+1)%physicalCount}else{if(virtualStart-idx s.length<=0){break}if(physicalTop+this._physicalSize-physicalItemHeight<=scrollB ottom){break}idxs.push(ith);physicalTop=physicalTop-physicalItemHeight;ith=ith== =0?physicalCount-1:ith-1}}return{indexes:idxs,physicalTop:physicalTop-this._scro llerPaddingTop}},_update:function(itemSet,movingUp){if(itemSet&&itemSet.length== =0){return}this._manageFocus();this._assignModels(itemSet);this._updateMetrics(i temSet);if(movingUp){while(movingUp.length){var idx=movingUp.pop();this._physica lTop-=this._getPhysicalSizeIncrement(idx)}}this._positionItems();this._updateScr ollerSize();this._increasePoolIfNeeded()},_createPool:function(size){var physica lItems=new Array(size);this._ensureTemplatized();for(var i=0;i<size;i++){var ins t=this.stamp(null);physicalItems[i]=inst.root.querySelector("*");Polymer.dom(thi s).appendChild(inst.root)}return physicalItems},_increasePoolIfNeeded:function() {if(this._viewportHeight===0){return false}var self=this;var isClientFull=this._ physicalBottom>=this._scrollBottom&&this._physicalTop<=this._scrollPosition;if(t his._physicalSize>=this._optPhysicalSize&&isClientFull){return false}var maxPool Size=Math.round(this._physicalCount*.5);if(!isClientFull){this._debounceTemplate (this._increasePool.bind(this,maxPoolSize));return true}this._yield(function(){s elf._increasePool(Math.min(maxPoolSize,Math.max(1,Math.round(50/self._templateCo st))))});return true},_yield:function(cb){var g=window;var handle=g.requestIdleC allback?g.requestIdleCallback(cb):g.setTimeout(cb,16);Polymer.dom.addDebouncer({ complete:function(){g.cancelIdleCallback?g.cancelIdleCallback(handle):g.clearTim eout(handle);cb()}})},_increasePool:function(missingItems){var nextPhysicalCount =Math.min(this._physicalCount+missingItems,this._virtualCount-this._virtualStart ,Math.max(this.maxPhysicalCount,DEFAULT_PHYSICAL_COUNT));var prevPhysicalCount=t his._physicalCount;var delta=nextPhysicalCount-prevPhysicalCount;var ts=window.p erformance.now();if(delta<=0){return}[].push.apply(this._physicalItems,this._cre atePool(delta));[].push.apply(this._physicalSizes,new Array(delta));this._physic alCount=prevPhysicalCount+delta;if(this._physicalStart>this._physicalEnd&&this._ isIndexRendered(this._focusedIndex)&&this._getPhysicalIndex(this._focusedIndex)< this._physicalEnd){this._physicalStart=this._physicalStart+delta}this._update(); this._templateCost=(window.performance.now()-ts)/delta},_render:function(){if(th is.isAttached&&this._isVisible){if(this._physicalCount===0){this.updateViewportB oundaries();this._increasePool(DEFAULT_PHYSICAL_COUNT)}else{var reusables=this._ getReusables(true);this._physicalTop=reusables.physicalTop;this._virtualStart=th is._virtualStart+reusables.indexes.length;this._physicalStart=this._physicalStar t+reusables.indexes.length;this._update(reusables.indexes);this._update()}}},_en sureTemplatized:function(){if(!this.ctor){var props={};props.__key__=true;props[ this.as]=true;props[this.indexAs]=true;props[this.selectedAs]=true;props.tabInde x=true;this._instanceProps=props;this._userTemplate=Polymer.dom(this).querySelec tor("template");if(this._userTemplate){this.templatize(this._userTemplate)}else{ console.warn("iron-list requires a template to be provided in light-dom")}}},_ge tStampedChildren:function(){return this._physicalItems},_forwardInstancePath:fun ction(inst,path,value){if(path.indexOf(this.as+".")===0){this.notifyPath("items. "+inst.__key__+"."+path.slice(this.as.length+1),value)}},_forwardParentProp:func tion(prop,value){if(this._physicalItems){this._physicalItems.forEach(function(it em){item._templateInstance[prop]=value},this)}},_forwardParentPath:function(path ,value){if(this._physicalItems){this._physicalItems.forEach(function(item){item. _templateInstance.notifyPath(path,value,true)},this)}},_forwardItemPath:function (path,value){if(!this._physicalIndexForKey){return}var dot=path.indexOf(".");var key=path.substring(0,dot<0?path.length:dot);var idx=this._physicalIndexForKey[k ey];var offscreenItem=this._offscreenFocusedItem;var el=offscreenItem&&offscreen Item._templateInstance.__key__===key?offscreenItem:this._physicalItems[idx];if(! el||el._templateInstance.__key__!==key){return}if(dot>=0){path=this.as+"."+path. substring(dot+1);el._templateInstance.notifyPath(path,value,true)}else{var curre ntItem=el._templateInstance[this.as];if(Array.isArray(this.selectedItems)){for(v ar i=0;i<this.selectedItems.length;i++){if(this.selectedItems[i]===currentItem){ this.set("selectedItems."+i,value);break}}}else if(this.selectedItem===currentIt em){this.set("selectedItem",value)}el._templateInstance[this.as]=value}},_itemsC hanged:function(change){if(change.path==="items"){this._virtualStart=0;this._phy sicalTop=0;this._virtualCount=this.items?this.items.length:0;this._collection=th is.items?Polymer.Collection.get(this.items):null;this._physicalIndexForKey={};th is._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null;this._physicalCount =this._physicalCount||0;this._physicalItems=this._physicalItems||[];this._physic alSizes=this._physicalSizes||[];this._physicalStart=0;this._resetScrollPosition( 0);this._removeFocusedItem();this._debounceTemplate(this._render)}else if(change .path==="items.splices"){this._adjustVirtualIndex(change.value.indexSplices);thi s._virtualCount=this.items?this.items.length:0;this._debounceTemplate(this._rend er)}else{this._forwardItemPath(change.path.split(".").slice(1).join("."),change. value)}},_adjustVirtualIndex:function(splices){splices.forEach(function(splice){ splice.removed.forEach(this._removeItem,this);if(splice.index<this._virtualStart ){var delta=Math.max(splice.addedCount-splice.removed.length,splice.index-this._ virtualStart);this._virtualStart=this._virtualStart+delta;if(this._focusedIndex> =0){this._focusedIndex=this._focusedIndex+delta}}},this)},_removeItem:function(i tem){this.$.selector.deselect(item);if(this._focusedItem&&this._focusedItem._tem plateInstance[this.as]===item){this._removeFocusedItem()}},_iterateItems:functio n(fn,itemSet){var pidx,vidx,rtn,i;if(arguments.length===2&&itemSet){for(i=0;i<it emSet.length;i++){pidx=itemSet[i];vidx=this._computeVidx(pidx);if((rtn=fn.call(t his,pidx,vidx))!=null){return rtn}}}else{pidx=this._physicalStart;vidx=this._vir tualStart;for(;pidx<this._physicalCount;pidx++,vidx++){if((rtn=fn.call(this,pidx ,vidx))!=null){return rtn}}for(pidx=0;pidx<this._physicalStart;pidx++,vidx++){if ((rtn=fn.call(this,pidx,vidx))!=null){return rtn}}}},_computeVidx:function(pidx) {if(pidx>=this._physicalStart){return this._virtualStart+(pidx-this._physicalSta rt)}return this._virtualStart+(this._physicalCount-this._physicalStart)+pidx},_a ssignModels:function(itemSet){this._iterateItems(function(pidx,vidx){var el=this ._physicalItems[pidx];var inst=el._templateInstance;var item=this.items&&this.it ems[vidx];if(item!=null){inst[this.as]=item;inst.__key__=this._collection.getKey (item);inst[this.selectedAs]=this.$.selector.isSelected(item);inst[this.indexAs] =vidx;inst.tabIndex=this._focusedIndex===vidx?0:-1;this._physicalIndexForKey[ins t.__key__]=pidx;el.removeAttribute("hidden")}else{inst.__key__=null;el.setAttrib ute("hidden","")}},itemSet)},_updateMetrics:function(itemSet){Polymer.dom.flush( );var newPhysicalSize=0;var oldPhysicalSize=0;var prevAvgCount=this._physicalAve rageCount;var prevPhysicalAvg=this._physicalAverage;this._iterateItems(function( pidx,vidx){oldPhysicalSize+=this._physicalSizes[pidx]||0;this._physicalSizes[pid x]=this._physicalItems[pidx].offsetHeight;newPhysicalSize+=this._physicalSizes[p idx];this._physicalAverageCount+=this._physicalSizes[pidx]?1:0},itemSet);if(this .grid){this._updateGridMetrics();this._physicalSize=Math.ceil(this._physicalCoun t/this._itemsPerRow)*this._rowHeight}else{this._physicalSize=this._physicalSize+ newPhysicalSize-oldPhysicalSize}if(this._physicalAverageCount!==prevAvgCount){th is._physicalAverage=Math.round((prevPhysicalAvg*prevAvgCount+newPhysicalSize)/th is._physicalAverageCount)}},_updateGridMetrics:function(){this._itemWidth=this._ physicalCount>0?this._physicalItems[0].getBoundingClientRect().width:200;this._r owHeight=this._physicalCount>0?this._physicalItems[0].offsetHeight:200;this._ite msPerRow=this._itemWidth?Math.floor(this._viewportWidth/this._itemWidth):this._i temsPerRow},_positionItems:function(){this._adjustScrollPosition();var y=this._p hysicalTop;if(this.grid){var totalItemWidth=this._itemsPerRow*this._itemWidth;va r rowOffset=(this._viewportWidth-totalItemWidth)/2;this._iterateItems(function(p idx,vidx){var modulus=vidx%this._itemsPerRow;var x=Math.floor(modulus*this._item Width+rowOffset);this.translate3d(x+"px",y+"px",0,this._physicalItems[pidx]);if( this._shouldRenderNextRow(vidx)){y+=this._rowHeight}})}else{this._iterateItems(f unction(pidx,vidx){this.translate3d(0,y+"px",0,this._physicalItems[pidx]);y+=thi s._physicalSizes[pidx]})}},_getPhysicalSizeIncrement:function(pidx){if(!this.gri d){return this._physicalSizes[pidx]}if(this._computeVidx(pidx)%this._itemsPerRow !==this._itemsPerRow-1){return 0}return this._rowHeight},_shouldRenderNextRow:fu nction(vidx){return vidx%this._itemsPerRow===this._itemsPerRow-1},_adjustScrollP osition:function(){var deltaHeight=this._virtualStart===0?this._physicalTop:Math .min(this._scrollPosition+this._physicalTop,0);if(deltaHeight){this._physicalTop =this._physicalTop-deltaHeight;if(!IOS_TOUCH_SCROLLING&&this._physicalTop!==0){t his._resetScrollPosition(this._scrollTop-deltaHeight)}}},_resetScrollPosition:fu nction(pos){if(this.scrollTarget){this._scrollTop=pos;this._scrollPosition=this. _scrollTop}},_updateScrollerSize:function(forceUpdate){if(this.grid){this._estSc rollHeight=this._virtualRowCount*this._rowHeight}else{this._estScrollHeight=this ._physicalBottom+Math.max(this._virtualCount-this._physicalCount-this._virtualSt art,0)*this._physicalAverage}forceUpdate=forceUpdate||this._scrollHeight===0;for ceUpdate=forceUpdate||this._scrollPosition>=this._estScrollHeight-this._physical Size;forceUpdate=forceUpdate||this.grid&&this.$.items.style.height<this._estScro llHeight;if(forceUpdate||Math.abs(this._estScrollHeight-this._scrollHeight)>=thi s._optPhysicalSize){this.$.items.style.height=this._estScrollHeight+"px";this._s crollHeight=this._estScrollHeight}},scrollToItem:function(item){return this.scro llToIndex(this.items.indexOf(item))},scrollToIndex:function(idx){if(typeof idx!= ="number"||idx<0||idx>this.items.length-1){return}Polymer.dom.flush();if(this._p hysicalCount===0){return}idx=Math.min(Math.max(idx,0),this._virtualCount-1);if(! this._isIndexRendered(idx)||idx>=this._maxVirtualStart){this._virtualStart=this. grid?idx-this._itemsPerRow*2:idx-1}this._manageFocus();this._assignModels();this ._updateMetrics();this._physicalTop=Math.floor(this._virtualStart/this._itemsPer Row)*this._physicalAverage;var currentTopItem=this._physicalStart;var currentVir tualItem=this._virtualStart;var targetOffsetTop=0;var hiddenContentSize=this._hi ddenContentSize;while(currentVirtualItem<idx&&targetOffsetTop<=hiddenContentSize ){targetOffsetTop=targetOffsetTop+this._getPhysicalSizeIncrement(currentTopItem) ;currentTopItem=(currentTopItem+1)%this._physicalCount;currentVirtualItem++}this ._updateScrollerSize(true);this._positionItems();this._resetScrollPosition(this. _physicalTop+this._scrollerPaddingTop+targetOffsetTop);this._increasePoolIfNeede d();this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null},_resetAverag e:function(){this._physicalAverage=0;this._physicalAverageCount=0},_resizeHandle r:function(){var delta=Math.abs(this._viewportHeight-this._scrollTargetHeight);i f(IOS&&delta>0&&delta<100){return}Polymer.dom.addDebouncer(this.debounce("_debou nceTemplate",function(){this.updateViewportBoundaries();this._render();if(this._ isVisible){this.toggleScrollListener(true);if(this._physicalCount>0){this._reset Average();this.scrollToIndex(this.firstVisibleIndex)}}else{this.toggleScrollList ener(false)}}.bind(this),1))},_getModelFromItem:function(item){var key=this._col lection.getKey(item);var pidx=this._physicalIndexForKey[key];if(pidx!=null){retu rn this._physicalItems[pidx]._templateInstance}return null},_getNormalizedItem:f unction(item){if(this._collection.getKey(item)===undefined){if(typeof item==="nu mber"){item=this.items[item];if(!item){throw new RangeError("<item> not found")} return item}throw new TypeError("<item> should be a valid item")}return item},se lectItem:function(item){item=this._getNormalizedItem(item);var model=this._getMo delFromItem(item);if(!this.multiSelection&&this.selectedItem){this.deselectItem( this.selectedItem)}if(model){model[this.selectedAs]=true}this.$.selector.select( item);this.updateSizeForItem(item)},deselectItem:function(item){item=this._getNo rmalizedItem(item);var model=this._getModelFromItem(item);if(model){model[this.s electedAs]=false}this.$.selector.deselect(item);this.updateSizeForItem(item)},to ggleSelectionForItem:function(item){item=this._getNormalizedItem(item);if(this.$ .selector.isSelected(item)){this.deselectItem(item)}else{this.selectItem(item)}} ,clearSelection:function(){function unselect(item){var model=this._getModelFromI tem(item);if(model){model[this.selectedAs]=false}}if(Array.isArray(this.selected Items)){this.selectedItems.forEach(unselect,this)}else if(this.selectedItem){uns elect.call(this,this.selectedItem)}this.$.selector.clearSelection()},_selectionE nabledChanged:function(selectionEnabled){var handler=selectionEnabled?this.liste n:this.unlisten;handler.call(this,this,"tap","_selectionHandler")},_selectionHan dler:function(e){var model=this.modelForElement(e.target);if(!model){return}var modelTabIndex,activeElTabIndex;var target=Polymer.dom(e).path[0];var activeEl=Po lymer.dom(this.domHost?this.domHost.root:document).activeElement;var physicalIte m=this._physicalItems[this._getPhysicalIndex(model[this.indexAs])];if(target.loc alName==="input"||target.localName==="button"||target.localName==="select"){retu rn}modelTabIndex=model.tabIndex;model.tabIndex=SECRET_TABINDEX;activeElTabIndex= activeEl?activeEl.tabIndex:-1;model.tabIndex=modelTabIndex;if(activeEl&&physical Item!==activeEl&&physicalItem.contains(activeEl)&&activeElTabIndex!==SECRET_TABI NDEX){return}this.toggleSelectionForItem(model[this.as])},_multiSelectionChanged :function(multiSelection){this.clearSelection();this.$.selector.multi=multiSelec tion},updateSizeForItem:function(item){item=this._getNormalizedItem(item);var ke y=this._collection.getKey(item);var pidx=this._physicalIndexForKey[key];if(pidx! =null){this._updateMetrics([pidx]);this._positionItems()}},_manageFocus:function (){var fidx=this._focusedIndex;if(fidx>=0&&fidx<this._virtualCount){if(this._isI ndexRendered(fidx)){this._restoreFocusedItem()}else{this._createFocusBackfillIte m()}}else if(this._virtualCount>0&&this._physicalCount>0){this._focusedIndex=thi s._virtualStart;this._focusedItem=this._physicalItems[this._physicalStart]}},_is IndexRendered:function(idx){return idx>=this._virtualStart&&idx<=this._virtualEn d},_isIndexVisible:function(idx){return idx>=this.firstVisibleIndex&&idx<=this.l astVisibleIndex},_getPhysicalIndex:function(idx){return this._physicalIndexForKe y[this._collection.getKey(this._getNormalizedItem(idx))]},_focusPhysicalItem:fun ction(idx){if(idx<0||idx>=this._virtualCount){return}this._restoreFocusedItem(); if(!this._isIndexRendered(idx)){this.scrollToIndex(idx)}var physicalItem=this._p hysicalItems[this._getPhysicalIndex(idx)];var model=physicalItem._templateInstan ce;var focusable;model.tabIndex=SECRET_TABINDEX;if(physicalItem.tabIndex===SECRE T_TABINDEX){focusable=physicalItem}if(!focusable){focusable=Polymer.dom(physical Item).querySelector('[tabindex="'+SECRET_TABINDEX+'"]')}model.tabIndex=0;this._f ocusedIndex=idx;focusable&&focusable.focus()},_removeFocusedItem:function(){if(t his._offscreenFocusedItem){Polymer.dom(this).removeChild(this._offscreenFocusedI tem)}this._offscreenFocusedItem=null;this._focusBackfillItem=null;this._focusedI tem=null;this._focusedIndex=-1},_createFocusBackfillItem:function(){var fidx=thi s._focusedIndex;var pidx=this._getPhysicalIndex(fidx);if(this._offscreenFocusedI tem||pidx==null||fidx<0){return}if(!this._focusBackfillItem){var stampedTemplate =this.stamp(null);this._focusBackfillItem=stampedTemplate.root.querySelector("*" );Polymer.dom(this).appendChild(stampedTemplate.root)}this._offscreenFocusedItem =this._physicalItems[pidx];this._offscreenFocusedItem._templateInstance.tabIndex =0;this._physicalItems[pidx]=this._focusBackfillItem;this.translate3d(0,HIDDEN_Y ,0,this._offscreenFocusedItem)},_restoreFocusedItem:function(){var pidx,fidx=thi s._focusedIndex;if(!this._offscreenFocusedItem||this._focusedIndex<0){return}thi s._assignModels();pidx=this._getPhysicalIndex(fidx);if(pidx!=null){this._focusBa ckfillItem=this._physicalItems[pidx];this._focusBackfillItem._templateInstance.t abIndex=-1;this._physicalItems[pidx]=this._offscreenFocusedItem;this._offscreenF ocusedItem=null;this.translate3d(0,HIDDEN_Y,0,this._focusBackfillItem)}},_didFoc us:function(e){var targetModel=this.modelForElement(e.target);var focusedModel=t his._focusedItem?this._focusedItem._templateInstance:null;var hasOffscreenFocuse dItem=this._offscreenFocusedItem!==null;var fidx=this._focusedIndex;if(!targetMo del||!focusedModel){return}if(focusedModel===targetModel){if(!this._isIndexVisib le(fidx)){this.scrollToIndex(fidx)}}else{this._restoreFocusedItem();focusedModel .tabIndex=-1;targetModel.tabIndex=0;fidx=targetModel[this.indexAs];this._focused Index=fidx;this._focusedItem=this._physicalItems[this._getPhysicalIndex(fidx)];i f(hasOffscreenFocusedItem&&!this._offscreenFocusedItem){this._update()}}},_didMo veUp:function(){this._focusPhysicalItem(this._focusedIndex-1)},_didMoveDown:func tion(e){e.detail.keyboardEvent.preventDefault();this._focusPhysicalItem(this._fo cusedIndex+1)},_didEnter:function(e){this._focusPhysicalItem(this._focusedIndex) ;this._selectionHandler(e.detail.keyboardEvent)}})})();Polymer({is:"iron-scroll- threshold",properties:{upperThreshold:{type:Number,value:100},lowerThreshold:{ty pe:Number,value:100},upperTriggered:{type:Boolean,value:false,notify:true,readOn ly:true},lowerTriggered:{type:Boolean,value:false,notify:true,readOnly:true},hor izontal:{type:Boolean,value:false}},behaviors:[Polymer.IronScrollTargetBehavior] ,observers:["_setOverflow(scrollTarget)","_initCheck(horizontal, isAttached)"],g et _defaultScrollTarget(){return this},_setOverflow:function(scrollTarget){this. style.overflow=scrollTarget===this?"auto":""},_scrollHandler:function(){var THRO TTLE_THRESHOLD=200;if(!this.isDebouncerActive("_checkTheshold")){this.debounce(" _checkTheshold",function(){this.checkScrollThesholds()},THROTTLE_THRESHOLD)}},_i nitCheck:function(horizontal,isAttached){if(isAttached){this.debounce("_init",fu nction(){this.clearTriggers();this.checkScrollThesholds()})}},checkScrollTheshol ds:function(){if(!this.scrollTarget||this.lowerTriggered&&this.upperTriggered){r eturn}var upperScrollValue=this.horizontal?this._scrollLeft:this._scrollTop;var lowerScrollValue=this.horizontal?this.scrollTarget.scrollWidth-this._scrollTarge tWidth-this._scrollLeft:this.scrollTarget.scrollHeight-this._scrollTargetHeight- this._scrollTop;if(upperScrollValue<=this.upperThreshold&&!this.upperTriggered){ this._setUpperTriggered(true);this.fire("upper-threshold")}if(lowerScrollValue<= this.lowerThreshold&&!this.lowerTriggered){this._setLowerTriggered(true);this.fi re("lower-threshold")}},clearTriggers:function(){this._setUpperTriggered(false); this._setLowerTriggered(false)}});
41 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 41 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
42 // Use of this source code is governed by a BSD-style license that can be 42 // Use of this source code is governed by a BSD-style license that can be
43 // found in the LICENSE file. 43 // found in the LICENSE file.
44 var EventTrackerEntry;function EventTracker(){this.listeners_=[]}EventTracker.pr ototype={add:function(target,eventType,listener,opt_capture){var capture=!!opt_c apture;var h={target:target,eventType:eventType,listener:listener,capture:captur e};this.listeners_.push(h);target.addEventListener(eventType,listener,capture)}, remove:function(target,eventType){this.listeners_=this.listeners_.filter(functio n(h){if(h.target==target&&(!eventType||h.eventType==eventType)){EventTracker.rem oveEventListener_(h);return false}return true})},removeAll:function(){this.liste ners_.forEach(EventTracker.removeEventListener_);this.listeners_=[]}};EventTrack er.removeEventListener_=function(h){h.target.removeEventListener(h.eventType,h.l istener,h.capture)}; 44 var EventTrackerEntry;function EventTracker(){this.listeners_=[]}EventTracker.pr ototype={add:function(target,eventType,listener,opt_capture){var capture=!!opt_c apture;var h={target:target,eventType:eventType,listener:listener,capture:captur e};this.listeners_.push(h);target.addEventListener(eventType,listener,capture)}, remove:function(target,eventType){this.listeners_=this.listeners_.filter(functio n(h){if(h.target==target&&(!eventType||h.eventType==eventType)){EventTracker.rem oveEventListener_(h);return false}return true})},removeAll:function(){this.liste ners_.forEach(EventTracker.removeEventListener_);this.listeners_=[]}};EventTrack er.removeEventListener_=function(h){h.target.removeEventListener(h.eventType,h.l istener,h.capture)};
45 // Copyright 2014 The Chromium Authors. All rights reserved. 45 // Copyright 2014 The Chromium Authors. All rights reserved.
46 // Use of this source code is governed by a BSD-style license that can be 46 // Use of this source code is governed by a BSD-style license that can be
47 // found in the LICENSE file. 47 // found in the LICENSE file.
48 cr.define("cr.ui",function(){function FocusRow(root,boundary,opt_delegate){this. root=root;this.boundary_=boundary||document.documentElement;this.delegate=opt_de legate;this.eventTracker=new EventTracker}FocusRow.Delegate=function(){};FocusRo w.Delegate.prototype={onKeydown:assertNotReached,onFocus:assertNotReached};Focus Row.ACTIVE_CLASS="focus-row-active";FocusRow.isFocusable=function(element){if(!e lement||element.disabled)return false;function isVisible(element){assertInstance of(element,Element);var style=window.getComputedStyle(element);if(style.visibili ty=="hidden"||style.display=="none")return false;var parent=element.parentNode;i f(!parent)return false;if(parent==element.ownerDocument||parent instanceof Docum entFragment)return true;return isVisible(parent)}return isVisible(element)};Focu sRow.prototype={addItem:function(type,query){assert(type);var element=this.root. querySelector(query);if(!element)return false;element.setAttribute("focus-type", type);element.tabIndex=this.isActive()?0:-1;this.eventTracker.add(element,"blur" ,this.onBlur_.bind(this));this.eventTracker.add(element,"focus",this.onFocus_.bi nd(this));this.eventTracker.add(element,"keydown",this.onKeydown_.bind(this));th is.eventTracker.add(element,"mousedown",this.onMousedown_.bind(this));return tru e},destroy:function(){this.eventTracker.removeAll()},getCustomEquivalent:functio n(sampleElement){return assert(this.getFirstFocusable())},getElements:function() {var elements=this.root.querySelectorAll("[focus-type]");return Array.prototype. slice.call(elements)},getEquivalentElement:function(sampleElement){if(this.getFo cusableElements().indexOf(sampleElement)>=0)return sampleElement;var sampleFocus Type=this.getTypeForElement(sampleElement);if(sampleFocusType){var sameType=this .getFirstFocusable(sampleFocusType);if(sameType)return sameType}return this.getC ustomEquivalent(sampleElement)},getFirstFocusable:function(opt_type){var filter= opt_type?'="'+opt_type+'"':"";var elements=this.root.querySelectorAll("[focus-ty pe"+filter+"]");for(var i=0;i<elements.length;++i){if(cr.ui.FocusRow.isFocusable (elements[i]))return elements[i]}return null},getFocusableElements:function(){re turn this.getElements().filter(cr.ui.FocusRow.isFocusable)},getTypeForElement:fu nction(element){return element.getAttribute("focus-type")||""},isActive:function (){return this.root.classList.contains(FocusRow.ACTIVE_CLASS)},makeActive:functi on(active){if(active==this.isActive())return;this.getElements().forEach(function (element){element.tabIndex=active?0:-1});this.root.classList.toggle(FocusRow.ACT IVE_CLASS,active)},onBlur_:function(e){if(!this.boundary_.contains(e.relatedTarg et))return;var currentTarget=e.currentTarget;if(this.getFocusableElements().inde xOf(currentTarget)>=0)this.makeActive(false)},onFocus_:function(e){if(this.deleg ate)this.delegate.onFocus(this,e)},onMousedown_:function(e){if(e.button)return;i f(!e.currentTarget.disabled)e.currentTarget.tabIndex=0},onKeydown_:function(e){v ar elements=this.getFocusableElements();var currentElement=e.currentTarget;var e lementIndex=elements.indexOf(currentElement);assert(elementIndex>=0);if(this.del egate&&this.delegate.onKeydown(this,e))return;if(hasKeyModifiers(e))return;var i ndex=-1;if(e.key=="ArrowLeft")index=elementIndex+(isRTL()?1:-1);else if(e.key==" ArrowRight")index=elementIndex+(isRTL()?-1:1);else if(e.key=="Home")index=0;else if(e.key=="End")index=elements.length-1;var elementToFocus=elements[index];if(e lementToFocus){this.getEquivalentElement(elementToFocus).focus();e.preventDefaul t()}}};return{FocusRow:FocusRow}}); 48 cr.define("cr.ui",function(){function FocusRow(root,boundary,opt_delegate){this. root=root;this.boundary_=boundary||document.documentElement;this.delegate=opt_de legate;this.eventTracker=new EventTracker}FocusRow.Delegate=function(){};FocusRo w.Delegate.prototype={onKeydown:assertNotReached,onFocus:assertNotReached};Focus Row.ACTIVE_CLASS="focus-row-active";FocusRow.isFocusable=function(element){if(!e lement||element.disabled)return false;function isVisible(element){assertInstance of(element,Element);var style=window.getComputedStyle(element);if(style.visibili ty=="hidden"||style.display=="none")return false;var parent=element.parentNode;i f(!parent)return false;if(parent==element.ownerDocument||parent instanceof Docum entFragment)return true;return isVisible(parent)}return isVisible(element)};Focu sRow.prototype={addItem:function(type,query){assert(type);var element=this.root. querySelector(query);if(!element)return false;element.setAttribute("focus-type", type);element.tabIndex=this.isActive()?0:-1;this.eventTracker.add(element,"blur" ,this.onBlur_.bind(this));this.eventTracker.add(element,"focus",this.onFocus_.bi nd(this));this.eventTracker.add(element,"keydown",this.onKeydown_.bind(this));th is.eventTracker.add(element,"mousedown",this.onMousedown_.bind(this));return tru e},destroy:function(){this.eventTracker.removeAll()},getCustomEquivalent:functio n(sampleElement){return assert(this.getFirstFocusable())},getElements:function() {var elements=this.root.querySelectorAll("[focus-type]");return Array.prototype. slice.call(elements)},getEquivalentElement:function(sampleElement){if(this.getFo cusableElements().indexOf(sampleElement)>=0)return sampleElement;var sampleFocus Type=this.getTypeForElement(sampleElement);if(sampleFocusType){var sameType=this .getFirstFocusable(sampleFocusType);if(sameType)return sameType}return this.getC ustomEquivalent(sampleElement)},getFirstFocusable:function(opt_type){var filter= opt_type?'="'+opt_type+'"':"";var elements=this.root.querySelectorAll("[focus-ty pe"+filter+"]");for(var i=0;i<elements.length;++i){if(cr.ui.FocusRow.isFocusable (elements[i]))return elements[i]}return null},getFocusableElements:function(){re turn this.getElements().filter(cr.ui.FocusRow.isFocusable)},getTypeForElement:fu nction(element){return element.getAttribute("focus-type")||""},isActive:function (){return this.root.classList.contains(FocusRow.ACTIVE_CLASS)},makeActive:functi on(active){if(active==this.isActive())return;this.getElements().forEach(function (element){element.tabIndex=active?0:-1});this.root.classList.toggle(FocusRow.ACT IVE_CLASS,active)},onBlur_:function(e){if(!this.boundary_.contains(e.relatedTarg et))return;var currentTarget=e.currentTarget;if(this.getFocusableElements().inde xOf(currentTarget)>=0)this.makeActive(false)},onFocus_:function(e){if(this.deleg ate)this.delegate.onFocus(this,e)},onMousedown_:function(e){if(e.button)return;i f(!e.currentTarget.disabled)e.currentTarget.tabIndex=0},onKeydown_:function(e){v ar elements=this.getFocusableElements();var currentElement=e.currentTarget;var e lementIndex=elements.indexOf(currentElement);assert(elementIndex>=0);if(this.del egate&&this.delegate.onKeydown(this,e))return;if(hasKeyModifiers(e))return;var i ndex=-1;if(e.key=="ArrowLeft")index=elementIndex+(isRTL()?1:-1);else if(e.key==" ArrowRight")index=elementIndex+(isRTL()?-1:1);else if(e.key=="Home")index=0;else if(e.key=="End")index=elements.length-1;var elementToFocus=elements[index];if(e lementToFocus){this.getEquivalentElement(elementToFocus).focus();e.preventDefaul t()}}};return{FocusRow:FocusRow}});
49 // Copyright 2016 The Chromium Authors. All rights reserved. 49 // Copyright 2016 The Chromium Authors. All rights reserved.
50 // Use of this source code is governed by a BSD-style license that can be 50 // Use of this source code is governed by a BSD-style license that can be
(...skipping 11 matching lines...) Expand all
62 // Use of this source code is governed by a BSD-style license that can be 62 // Use of this source code is governed by a BSD-style license that can be
63 // found in the LICENSE file. 63 // found in the LICENSE file.
64 var SelectionTreeNode=function(currentPath){this.currentPath=currentPath;this.le af=false;this.indexes=[];this.children=[]};SelectionTreeNode.prototype.addChild= function(index,path){this.indexes.push(index);this.children[index]=new Selection TreeNode(path)};var HistoryListBehavior={properties:{selectedPaths:{type:Object, value:function(){return new Set}},lastSelectedPath:String},listeners:{"history-c heckbox-select":"itemSelected_"},addNewResults:function(results,incremental,fini shed){},hasResults:function(historyDataLength){return historyDataLength>0},noRes ultsMessage:function(searchedTerm,isLoading){if(isLoading)return"";var messageId =searchedTerm!==""?"noSearchResults":"noResults";return loadTimeData.getString(m essageId)},unselectAllItems:function(){this.selectedPaths.forEach(function(path) {this.set(path+".selected",false)}.bind(this));this.selectedPaths.clear()},delet eSelected:function(){var toBeRemoved=Array.from(this.selectedPaths.values()).map (function(path){return this.get(path)}.bind(this));md_history.BrowserService.get Instance().deleteItems(toBeRemoved).then(function(){this.removeItemsByPath(Array .from(this.selectedPaths));this.fire("unselect-all")}.bind(this))},removeItemsBy Path:function(paths){if(paths.length==0)return;this.removeItemsBeneathNode_(this .buildRemovalTree_(paths))},buildRemovalTree_:function(paths){var rootNode=new S electionTreeNode(paths[0].split(".")[0]);paths.forEach(function(path){var compon ents=path.split(".");var node=rootNode;components.shift();while(components.lengt h>1){var index=Number(components.shift());var arrayName=components.shift();if(!n ode.children[index])node.addChild(index,[node.currentPath,index,arrayName].join( "."));node=node.children[index]}node.leaf=true;node.indexes.push(Number(componen ts.shift()))});return rootNode},removeItemsBeneathNode_:function(node){var array =this.get(node.currentPath);var splices=[];node.indexes.sort(function(a,b){retur n b-a});node.indexes.forEach(function(index){if(node.leaf||this.removeItemsBenea thNode_(node.children[index])){var item=array.splice(index,1)[0];splices.push({i ndex:index,removed:[item],addedCount:0,object:array,type:"splice"})}}.bind(this) );if(array.length==0&&node.currentPath.indexOf(".")!=-1)return true;this.notifyS plices(node.currentPath,splices);return false},itemSelected_:function(e){var ite m=e.detail.element;var paths=[];var itemPath=item.path;if(e.detail.shiftKey&&thi s.lastSelectedPath){var itemPathComponents=itemPath.split(".");var itemIndex=Num ber(itemPathComponents.pop());var itemArrayPath=itemPathComponents.join(".");var lastItemPathComponents=this.lastSelectedPath.split(".");var lastItemIndex=Numbe r(lastItemPathComponents.pop());if(itemArrayPath==lastItemPathComponents.join(". ")){for(var i=Math.min(itemIndex,lastItemIndex);i<=Math.max(itemIndex,lastItemIn dex);i++){paths.push(itemArrayPath+"."+i)}}}if(paths.length==0)paths.push(item.p ath);var selected=!this.selectedPaths.has(item.path);paths.forEach(function(path ){this.set(path+".selected",selected);if(selected){this.selectedPaths.add(path); return}this.selectedPaths.delete(path)}.bind(this));this.lastSelectedPath=itemPa th}}; 64 var SelectionTreeNode=function(currentPath){this.currentPath=currentPath;this.le af=false;this.indexes=[];this.children=[]};SelectionTreeNode.prototype.addChild= function(index,path){this.indexes.push(index);this.children[index]=new Selection TreeNode(path)};var HistoryListBehavior={properties:{selectedPaths:{type:Object, value:function(){return new Set}},lastSelectedPath:String},listeners:{"history-c heckbox-select":"itemSelected_"},addNewResults:function(results,incremental,fini shed){},hasResults:function(historyDataLength){return historyDataLength>0},noRes ultsMessage:function(searchedTerm,isLoading){if(isLoading)return"";var messageId =searchedTerm!==""?"noSearchResults":"noResults";return loadTimeData.getString(m essageId)},unselectAllItems:function(){this.selectedPaths.forEach(function(path) {this.set(path+".selected",false)}.bind(this));this.selectedPaths.clear()},delet eSelected:function(){var toBeRemoved=Array.from(this.selectedPaths.values()).map (function(path){return this.get(path)}.bind(this));md_history.BrowserService.get Instance().deleteItems(toBeRemoved).then(function(){this.removeItemsByPath(Array .from(this.selectedPaths));this.fire("unselect-all")}.bind(this))},removeItemsBy Path:function(paths){if(paths.length==0)return;this.removeItemsBeneathNode_(this .buildRemovalTree_(paths))},buildRemovalTree_:function(paths){var rootNode=new S electionTreeNode(paths[0].split(".")[0]);paths.forEach(function(path){var compon ents=path.split(".");var node=rootNode;components.shift();while(components.lengt h>1){var index=Number(components.shift());var arrayName=components.shift();if(!n ode.children[index])node.addChild(index,[node.currentPath,index,arrayName].join( "."));node=node.children[index]}node.leaf=true;node.indexes.push(Number(componen ts.shift()))});return rootNode},removeItemsBeneathNode_:function(node){var array =this.get(node.currentPath);var splices=[];node.indexes.sort(function(a,b){retur n b-a});node.indexes.forEach(function(index){if(node.leaf||this.removeItemsBenea thNode_(node.children[index])){var item=array.splice(index,1)[0];splices.push({i ndex:index,removed:[item],addedCount:0,object:array,type:"splice"})}}.bind(this) );if(array.length==0&&node.currentPath.indexOf(".")!=-1)return true;this.notifyS plices(node.currentPath,splices);return false},itemSelected_:function(e){var ite m=e.detail.element;var paths=[];var itemPath=item.path;if(e.detail.shiftKey&&thi s.lastSelectedPath){var itemPathComponents=itemPath.split(".");var itemIndex=Num ber(itemPathComponents.pop());var itemArrayPath=itemPathComponents.join(".");var lastItemPathComponents=this.lastSelectedPath.split(".");var lastItemIndex=Numbe r(lastItemPathComponents.pop());if(itemArrayPath==lastItemPathComponents.join(". ")){for(var i=Math.min(itemIndex,lastItemIndex);i<=Math.max(itemIndex,lastItemIn dex);i++){paths.push(itemArrayPath+"."+i)}}}if(paths.length==0)paths.push(item.p ath);var selected=!this.selectedPaths.has(item.path);paths.forEach(function(path ){this.set(path+".selected",selected);if(selected){this.selectedPaths.add(path); return}this.selectedPaths.delete(path)}.bind(this));this.lastSelectedPath=itemPa th}};
65 // Copyright 2015 The Chromium Authors. All rights reserved. 65 // Copyright 2015 The Chromium Authors. All rights reserved.
66 // Use of this source code is governed by a BSD-style license that can be 66 // Use of this source code is governed by a BSD-style license that can be
67 // found in the LICENSE file. 67 // found in the LICENSE file.
68 Polymer({is:"history-list",behaviors:[HistoryListBehavior],properties:{searchedT erm:{type:String,value:""},resultLoadingDisabled_:{type:Boolean,value:false},his toryData_:Array,lastFocused_:Object,querying:Boolean},listeners:{"remove-bookmar k-stars":"removeBookmarkStars_","open-menu":"onOpenMenu_"},attached:function(){t his.$["infinite-list"].notifyResize();this.$["infinite-list"].scrollTarget=this; this.$["scroll-threshold"].scrollTarget=this},removeBookmarkStars_:function(e){v ar url=e.detail;if(this.historyData_===undefined)return;for(var i=0;i<this.histo ryData_.length;i++){if(this.historyData_[i].url==url)this.set("historyData_."+i+ ".starred",false)}},addNewResults:function(historyResults,incremental,finished){ var results=historyResults.slice();this.$["scroll-threshold"].clearTriggers();if (!incremental){this.resultLoadingDisabled_=false;if(this.historyData_)this.splic e("historyData_",0,this.historyData_.length);this.fire("unselect-all")}if(this.h istoryData_){results.unshift("historyData_");this.push.apply(this,results)}else{ this.set("historyData_",results)}this.resultLoadingDisabled_=finished},loadMoreD ata_:function(){if(this.resultLoadingDisabled_||this.querying)return;this.fire(" query-history",true)},onOpenMenu_:function(e){var index=e.detail.index;var list= this.$["infinite-list"];if(index<list.firstVisibleIndex||index>list.lastVisibleI ndex)list.scrollToIndex(index)},needsTimeGap_:function(item,index,length){return md_history.HistoryItem.needsTimeGap(this.historyData_,index,this.searchedTerm)} ,isCardStart_:function(item,i,length){if(length==0||i>length-1)return false;retu rn i==0||this.historyData_[i].dateRelativeDay!=this.historyData_[i-1].dateRelati veDay},isCardEnd_:function(item,i,length){if(length==0||i>length-1)return false; return i==length-1||this.historyData_[i].dateRelativeDay!=this.historyData_[i+1] .dateRelativeDay},pathForItem_:function(index){return"historyData_."+index}}); 68 Polymer({is:"history-list",behaviors:[HistoryListBehavior],properties:{searchedT erm:{type:String,value:""},resultLoadingDisabled_:{type:Boolean,value:false},his toryData_:Array,lastFocused_:Object,querying:Boolean},listeners:{"remove-bookmar k-stars":"removeBookmarkStars_","open-menu":"onOpenMenu_"},attached:function(){t his.$["infinite-list"].notifyResize();this.$["infinite-list"].scrollTarget=this; this.$["scroll-threshold"].scrollTarget=this},removeBookmarkStars_:function(e){v ar url=e.detail;if(this.historyData_===undefined)return;for(var i=0;i<this.histo ryData_.length;i++){if(this.historyData_[i].url==url)this.set("historyData_."+i+ ".starred",false)}},addNewResults:function(historyResults,incremental,finished){ var results=historyResults.slice();this.$["scroll-threshold"].clearTriggers();if (!incremental){this.resultLoadingDisabled_=false;if(this.historyData_)this.splic e("historyData_",0,this.historyData_.length);this.fire("unselect-all")}if(this.h istoryData_){results.unshift("historyData_");this.push.apply(this,results)}else{ this.set("historyData_",results)}this.resultLoadingDisabled_=finished},loadMoreD ata_:function(){if(this.resultLoadingDisabled_||this.querying)return;this.fire(" query-history",true)},onOpenMenu_:function(e){var index=e.detail.index;var list= this.$["infinite-list"];if(index<list.firstVisibleIndex||index>list.lastVisibleI ndex)list.scrollToIndex(index)},needsTimeGap_:function(item,index,length){return md_history.HistoryItem.needsTimeGap(this.historyData_,index,this.searchedTerm)} ,isCardStart_:function(item,i,length){if(length==0||i>length-1)return false;retu rn i==0||this.historyData_[i].dateRelativeDay!=this.historyData_[i-1].dateRelati veDay},isCardEnd_:function(item,i,length){if(length==0||i>length-1)return false; return i==length-1||this.historyData_[i].dateRelativeDay!=this.historyData_[i+1] .dateRelativeDay},pathForItem_:function(index){return"historyData_."+index}});
69 // Copyright 2016 The Chromium Authors. All rights reserved. 69 // Copyright 2016 The Chromium Authors. All rights reserved.
70 // Use of this source code is governed by a BSD-style license that can be 70 // Use of this source code is governed by a BSD-style license that can be
71 // found in the LICENSE file. 71 // found in the LICENSE file.
72 Polymer({is:"history-list-container",properties:{groupedRange:{type:Number,obser ver:"groupedRangeChanged_"},selectedPage_:{type:String,computed:"computeSelected Page_(groupedRange)"},grouped:Boolean,queryState:Object,queryResult:Object,actio nMenuModel_:Object},observers:["groupedRangeChanged_(queryState.range)"],listene rs:{"open-menu":"openMenu_"},historyResult:function(info,results){this.initializ eResults_(info,results);this.closeMenu_();if(info.term&&!this.queryState.increme ntal){Polymer.IronA11yAnnouncer.requestAvailability();this.fire("iron-announce", {text:md_history.HistoryItem.searchResultsTitle(results.length,info.term)})}var list=this.getSelectedList_();list.addNewResults(results,this.queryState.incremen tal,info.finished)},historyDeleted:function(){if(this.getSelectedItemCount()>0)r eturn;this.fire("query-history",false)},getContentScrollTarget:function(){return this.getSelectedList_()},getSelectedItemCount:function(){return this.getSelecte dList_().selectedPaths.size},unselectAllItems:function(count){var selectedList=t his.getSelectedList_();if(selectedList)selectedList.unselectAllItems(count)},del eteSelectedWithPrompt:function(){if(!loadTimeData.getBoolean("allowDeletingHisto ry"))return;var browserService=md_history.BrowserService.getInstance();browserSe rvice.recordAction("RemoveSelected");if(this.queryState.searchTerm!="")browserSe rvice.recordAction("SearchResultRemove");this.$.dialog.get().showModal();this.$$ (".action-button").focus()},computeSelectedPage_:function(range){return range==H istoryRange.ALL_TIME?"infinite-list":"grouped-list"},groupedRangeChanged_:functi on(range){if(range!=HistoryRange.ALL_TIME&&this.queryResult.info){this.set("quer yResult.results",[]);this.historyResult(this.queryResult.info,[])}},initializeRe sults_:function(info,results){if(results.length==0)return;var currentDate=result s[0].dateRelativeDay;for(var i=0;i<results.length;i++){results[i].selected=false ;results[i].readableTimestamp=info.term==""?results[i].dateTimeOfDay:results[i]. dateShort;if(results[i].dateRelativeDay!=currentDate){currentDate=results[i].dat eRelativeDay}}},onDialogConfirmTap_:function(){md_history.BrowserService.getInst ance().recordAction("ConfirmRemoveSelected");this.getSelectedList_().deleteSelec ted();var dialog=assert(this.$.dialog.getIfExists());dialog.close()},onDialogCan celTap_:function(){md_history.BrowserService.getInstance().recordAction("CancelR emoveSelected");var dialog=assert(this.$.dialog.getIfExists());dialog.close()},c loseMenu_:function(){var menu=this.$.sharedMenu.getIfExists();if(menu&&menu.open ){this.actionMenuModel_=null;menu.close()}},openMenu_:function(e){var target=e.d etail.target;this.actionMenuModel_=e.detail;var menu=this.$.sharedMenu.get();men u.showAt(target)},onMoreFromSiteTap_:function(){md_history.BrowserService.getIns tance().recordAction("EntryMenuShowMoreFromSite");var menu=assert(this.$.sharedM enu.getIfExists());this.set("queryState.searchTerm",this.actionMenuModel_.item.d omain);this.actionMenuModel_=null;this.closeMenu_()},onRemoveFromHistoryTap_:fun ction(){var browserService=md_history.BrowserService.getInstance();browserServic e.recordAction("EntryMenuRemoveFromHistory");var menu=assert(this.$.sharedMenu.g etIfExists());var itemData=this.actionMenuModel_;browserService.deleteItems([ite mData.item]).then(function(items){this.fire("unselect-all");this.getSelectedList _().removeItemsByPath([itemData.path]);var index=itemData.index;if(index==undefi ned)return;var browserService=md_history.BrowserService.getInstance();browserSer vice.recordHistogram("HistoryPage.RemoveEntryPosition",Math.min(index,UMA_MAX_BU CKET_VALUE),UMA_MAX_BUCKET_VALUE);if(index<=UMA_MAX_SUBSET_BUCKET_VALUE){browser Service.recordHistogram("HistoryPage.RemoveEntryPositionSubset",index,UMA_MAX_SU BSET_BUCKET_VALUE)}}.bind(this));this.closeMenu_()},getSelectedList_:function(){ return this.$$("#"+this.selectedPage_)},canDeleteHistory_:function(){return load TimeData.getBoolean("allowDeletingHistory")}}); 72 Polymer({is:"history-list-container",properties:{selectedPage_:{type:String,comp uted:"computeSelectedPage_(queryState.range)"},grouped:Boolean,queryState:Object ,queryResult:Object,actionMenuModel_:Object},observers:["groupedRangeChanged_(qu eryState.range)"],listeners:{"open-menu":"openMenu_"},historyResult:function(inf o,results){this.initializeResults_(info,results);this.closeMenu_();if(info.term& &!this.queryState.incremental){Polymer.IronA11yAnnouncer.requestAvailability();t his.fire("iron-announce",{text:md_history.HistoryItem.searchResultsTitle(results .length,info.term)})}var list=this.getSelectedList_();list.addNewResults(results ,this.queryState.incremental,info.finished)},historyDeleted:function(){if(this.g etSelectedItemCount()>0)return;this.fire("query-history",false)},getContentScrol lTarget:function(){return this.getSelectedList_()},getSelectedItemCount:function (){return this.getSelectedList_().selectedPaths.size},unselectAllItems:function( count){var selectedList=this.getSelectedList_();if(selectedList)selectedList.uns electAllItems(count)},deleteSelectedWithPrompt:function(){if(!loadTimeData.getBo olean("allowDeletingHistory"))return;var browserService=md_history.BrowserServic e.getInstance();browserService.recordAction("RemoveSelected");if(this.queryState .searchTerm!="")browserService.recordAction("SearchResultRemove");this.$.dialog. get().showModal();this.$$(".action-button").focus()},computeSelectedPage_:functi on(range){return range==HistoryRange.ALL_TIME?"infinite-list":"grouped-list"},gr oupedRangeChanged_:function(range){if(range!=HistoryRange.ALL_TIME&&this.queryRe sult.info){this.set("queryResult.results",[]);this.historyResult(this.queryResul t.info,[])}},initializeResults_:function(info,results){if(results.length==0)retu rn;var currentDate=results[0].dateRelativeDay;for(var i=0;i<results.length;i++){ results[i].selected=false;results[i].readableTimestamp=info.term==""?results[i]. dateTimeOfDay:results[i].dateShort;if(results[i].dateRelativeDay!=currentDate){c urrentDate=results[i].dateRelativeDay}}},onDialogConfirmTap_:function(){md_histo ry.BrowserService.getInstance().recordAction("ConfirmRemoveSelected");this.getSe lectedList_().deleteSelected();var dialog=assert(this.$.dialog.getIfExists());di alog.close()},onDialogCancelTap_:function(){md_history.BrowserService.getInstanc e().recordAction("CancelRemoveSelected");var dialog=assert(this.$.dialog.getIfEx ists());dialog.close()},closeMenu_:function(){var menu=this.$.sharedMenu.getIfEx ists();if(menu&&menu.open){this.actionMenuModel_=null;menu.close()}},openMenu_:f unction(e){var target=e.detail.target;this.actionMenuModel_=e.detail;var menu=th is.$.sharedMenu.get();menu.showAt(target)},onMoreFromSiteTap_:function(){md_hist ory.BrowserService.getInstance().recordAction("EntryMenuShowMoreFromSite");var m enu=assert(this.$.sharedMenu.getIfExists());this.fire("change-query",{search:thi s.actionMenuModel_.item.domain});this.actionMenuModel_=null;this.closeMenu_()},o nRemoveFromHistoryTap_:function(){var browserService=md_history.BrowserService.g etInstance();browserService.recordAction("EntryMenuRemoveFromHistory");var menu= assert(this.$.sharedMenu.getIfExists());var itemData=this.actionMenuModel_;brows erService.deleteItems([itemData.item]).then(function(items){this.fire("unselect- all");this.getSelectedList_().removeItemsByPath([itemData.path]);var index=itemD ata.index;if(index==undefined)return;var browserService=md_history.BrowserServic e.getInstance();browserService.recordHistogram("HistoryPage.RemoveEntryPosition" ,Math.min(index,UMA_MAX_BUCKET_VALUE),UMA_MAX_BUCKET_VALUE);if(index<=UMA_MAX_SU BSET_BUCKET_VALUE){browserService.recordHistogram("HistoryPage.RemoveEntryPositi onSubset",index,UMA_MAX_SUBSET_BUCKET_VALUE)}}.bind(this));this.closeMenu_()},ge tSelectedList_:function(){return this.$$("#"+this.selectedPage_)},canDeleteHisto ry_:function(){return loadTimeData.getBoolean("allowDeletingHistory")}});
73 // Copyright 2017 The Chromium Authors. All rights reserved. 73 // Copyright 2017 The Chromium Authors. All rights reserved.
74 // Use of this source code is governed by a BSD-style license that can be 74 // Use of this source code is governed by a BSD-style license that can be
75 // found in the LICENSE file. 75 // found in the LICENSE file.
76 Polymer({is:"history-query-manager",properties:{queryState:{type:Object,notify:t rue},groupedRange_:{type:Number,computed:"computeGroupedRange_(queryState.range) "},queryResult:Object},observers:["searchTermChanged_(queryState.searchTerm)","g roupedOffsetChanged_(queryState.groupedOffset)"],boundOnQueryHistory_:null,attac hed:function(){this.boundOnQueryHistory_=this.onQueryHistory_.bind(this);documen t.addEventListener("query-history",this.boundOnQueryHistory_)},detached:function (){document.removeEventListener("query-history",this.boundOnQueryHistory_)},quer yHistory_:function(incremental){var queryState=this.queryState;var noResults=!th is.queryResult||this.queryResult.results==null;if(queryState.queryingDisabled||! this.queryState.searchTerm&&noResults){return}this.set("queryState.querying",tru e);this.set("queryState.incremental",incremental);var lastVisitTime=0;if(increme ntal){var lastVisit=this.queryResult.results.slice(-1)[0];lastVisitTime=lastVisi t?Math.floor(lastVisit.time):0}var maxResults=this.queryState.range==HistoryRang e.ALL_TIME?RESULTS_PER_PAGE:0;chrome.send("queryHistory",[queryState.searchTerm, queryState.groupedOffset,queryState.range,lastVisitTime,maxResults])},onQueryHis tory_:function(e){this.queryHistory_(e.detail);return false},groupedOffsetChange d_:function(){this.queryHistory_(false)},computeGroupedRange_:function(range){if (this.groupedRange_!=undefined){this.set("queryState.groupedOffset",0);this.quer yHistory_(false);this.fire("history-view-changed")}return range},searchTermChang ed_:function(){this.queryHistory_(false);if(this.queryState.searchTerm)md_histor y.BrowserService.getInstance().recordAction("Search")}});(function(){"use strict ";Polymer({is:"iron-location",properties:{path:{type:String,notify:true,value:fu nction(){return window.decodeURIComponent(window.location.pathname)}},query:{typ e:String,notify:true,value:function(){return window.decodeURIComponent(window.lo cation.search.slice(1))}},hash:{type:String,notify:true,value:function(){return window.decodeURIComponent(window.location.hash.slice(1))}},dwellTime:{type:Numbe r,value:2e3},urlSpaceRegex:{type:String,value:""},_urlSpaceRegExp:{computed:"_ma keRegExp(urlSpaceRegex)"},_lastChangedAt:{type:Number},_initialized:{type:Boolea n,value:false}},hostAttributes:{hidden:true},observers:["_updateUrl(path, query, hash)"],attached:function(){this.listen(window,"hashchange","_hashChanged");thi s.listen(window,"location-changed","_urlChanged");this.listen(window,"popstate", "_urlChanged");this.listen(document.body,"click","_globalOnClick");this._lastCha ngedAt=window.performance.now()-(this.dwellTime-200);this._initialized=true;this ._urlChanged()},detached:function(){this.unlisten(window,"hashchange","_hashChan ged");this.unlisten(window,"location-changed","_urlChanged");this.unlisten(windo w,"popstate","_urlChanged");this.unlisten(document.body,"click","_globalOnClick" );this._initialized=false},_hashChanged:function(){this.hash=window.decodeURICom ponent(window.location.hash.substring(1))},_urlChanged:function(){this._dontUpda teUrl=true;this._hashChanged();this.path=window.decodeURIComponent(window.locati on.pathname);this.query=window.decodeURIComponent(window.location.search.substri ng(1));this._dontUpdateUrl=false;this._updateUrl()},_getUrl:function(){var parti allyEncodedPath=window.encodeURI(this.path).replace(/\#/g,"%23").replace(/\?/g," %3F");var partiallyEncodedQuery="";if(this.query){partiallyEncodedQuery="?"+wind ow.encodeURI(this.query).replace(/\#/g,"%23")}var partiallyEncodedHash="";if(thi s.hash){partiallyEncodedHash="#"+window.encodeURI(this.hash)}return partiallyEnc odedPath+partiallyEncodedQuery+partiallyEncodedHash},_updateUrl:function(){if(th is._dontUpdateUrl||!this._initialized){return}if(this.path===window.decodeURICom ponent(window.location.pathname)&&this.query===window.decodeURIComponent(window. location.search.substring(1))&&this.hash===window.decodeURIComponent(window.loca tion.hash.substring(1))){return}var newUrl=this._getUrl();var fullNewUrl=new URL (newUrl,window.location.protocol+"//"+window.location.host).href;var now=window. performance.now();var shouldReplace=this._lastChangedAt+this.dwellTime>now;this. _lastChangedAt=now;if(shouldReplace){window.history.replaceState({},"",fullNewUr l)}else{window.history.pushState({},"",fullNewUrl)}this.fire("location-changed", {},{node:window})},_globalOnClick:function(event){if(event.defaultPrevented){ret urn}var href=this._getSameOriginLinkHref(event);if(!href){return}event.preventDe fault();if(href===window.location.href){return}window.history.pushState({},"",hr ef);this.fire("location-changed",{},{node:window})},_getSameOriginLinkHref:funct ion(event){if(event.button!==0){return null}if(event.metaKey||event.ctrlKey){ret urn null}var eventPath=Polymer.dom(event).path;var anchor=null;for(var i=0;i<eve ntPath.length;i++){var element=eventPath[i];if(element.tagName==="A"&&element.hr ef){anchor=element;break}}if(!anchor){return null}if(anchor.target==="_blank"){r eturn null}if((anchor.target==="_top"||anchor.target==="_parent")&&window.top!== window){return null}var href=anchor.href;var url;if(document.baseURI!=null){url= new URL(href,document.baseURI)}else{url=new URL(href)}var origin;if(window.locat ion.origin){origin=window.location.origin}else{origin=window.location.protocol+" //"+window.location.hostname;if(window.location.port){origin+=":"+window.locatio n.port}}if(url.origin!==origin){return null}var normalizedHref=url.pathname+url. search+url.hash;if(this._urlSpaceRegExp&&!this._urlSpaceRegExp.test(normalizedHr ef)){return null}var fullNormalizedHref=new URL(normalizedHref,window.location.h ref).href;return fullNormalizedHref},_makeRegExp:function(urlSpaceRegex){return RegExp(urlSpaceRegex)}})})();"use strict";Polymer({is:"iron-query-params",proper ties:{paramsString:{type:String,notify:true,observer:"paramsStringChanged"},para msObject:{type:Object,notify:true,value:function(){return{}}},_dontReact:{type:B oolean,value:false}},hostAttributes:{hidden:true},observers:["paramsObjectChange d(paramsObject.*)"],paramsStringChanged:function(){this._dontReact=true;this.par amsObject=this._decodeParams(this.paramsString);this._dontReact=false},paramsObj ectChanged:function(){if(this._dontReact){return}this.paramsString=this._encodeP arams(this.paramsObject)},_encodeParams:function(params){var encodedParams=[];fo r(var key in params){var value=params[key];if(value===""){encodedParams.push(enc odeURIComponent(key))}else if(value){encodedParams.push(encodeURIComponent(key)+ "="+encodeURIComponent(value.toString()))}}return encodedParams.join("&")},_deco deParams:function(paramString){var params={};paramString=(paramString||"").repla ce(/\+/g,"%20");var paramList=paramString.split("&");for(var i=0;i<paramList.len gth;i++){var param=paramList[i].split("=");if(param[0]){params[decodeURIComponen t(param[0])]=decodeURIComponent(param[1]||"")}}return params}}); 76 Polymer({is:"history-query-manager",properties:{queryState:{type:Object,notify:t rue,value:function(){return{incremental:false,querying:true,queryingDisabled:fal se,_range:HistoryRange.ALL_TIME,searchTerm:"",groupedOffset:0,set range(val){thi s._range=Number(val)},get range(){return this._range}}}},queryResult:Object},obs ervers:["searchTermChanged_(queryState.searchTerm)"],documentListeners_:{},attac hed:function(){this.documentListeners_["change-query"]=this.onChangeQuery_.bind( this);this.documentListeners_["query-history"]=this.onQueryHistory_.bind(this);f or(var e in this.documentListeners_)document.addEventListener(e,this.documentLis teners_[e])},detached:function(){for(var e in this.documentListeners_)document.r emoveEventListener(e,this.documentListeners_[e])},queryHistory_:function(increme ntal){var queryState=this.queryState;var noResults=!this.queryResult||this.query Result.results==null;if(queryState.queryingDisabled||!this.queryState.searchTerm &&noResults){return}this.set("queryState.querying",true);this.set("queryState.in cremental",incremental);var lastVisitTime=0;if(incremental){var lastVisit=this.q ueryResult.results.slice(-1)[0];lastVisitTime=lastVisit?Math.floor(lastVisit.tim e):0}var maxResults=this.queryState.range==HistoryRange.ALL_TIME?RESULTS_PER_PAG E:0;chrome.send("queryHistory",[queryState.searchTerm,queryState.groupedOffset,q ueryState.range,lastVisitTime,maxResults])},changeQuery_:function(changes){var n eedsUpdate=false;if(changes.range!=null&&changes.range!=this.queryState.range){t his.set("queryState.range",changes.range);needsUpdate=true;if(!changes.offset)th is.set("queryState.groupedOffset",0);this.fire("history-view-changed")}if(change s.offset!=null&&changes.offset!=this.queryState.groupedOffset){this.set("querySt ate.groupedOffset",changes.offset);needsUpdate=true}if(changes.search!=null&&cha nges.search!=this.queryState.searchTerm){this.set("queryState.searchTerm",change s.search);needsUpdate=true}if(needsUpdate)this.queryHistory_(false)},onChangeQue ry_:function(e){this.changeQuery_(e.detail)},onQueryHistory_:function(e){this.qu eryHistory_(e.detail);return false},searchTermChanged_:function(){if(this.queryS tate.searchTerm)md_history.BrowserService.getInstance().recordAction("Search")}} );(function(){"use strict";Polymer({is:"iron-location",properties:{path:{type:St ring,notify:true,value:function(){return window.decodeURIComponent(window.locati on.pathname)}},query:{type:String,notify:true,value:function(){return window.dec odeURIComponent(window.location.search.slice(1))}},hash:{type:String,notify:true ,value:function(){return window.decodeURIComponent(window.location.hash.slice(1) )}},dwellTime:{type:Number,value:2e3},urlSpaceRegex:{type:String,value:""},_urlS paceRegExp:{computed:"_makeRegExp(urlSpaceRegex)"},_lastChangedAt:{type:Number}, _initialized:{type:Boolean,value:false}},hostAttributes:{hidden:true},observers: ["_updateUrl(path, query, hash)"],attached:function(){this.listen(window,"hashch ange","_hashChanged");this.listen(window,"location-changed","_urlChanged");this. listen(window,"popstate","_urlChanged");this.listen(document.body,"click","_glob alOnClick");this._lastChangedAt=window.performance.now()-(this.dwellTime-200);th is._initialized=true;this._urlChanged()},detached:function(){this.unlisten(windo w,"hashchange","_hashChanged");this.unlisten(window,"location-changed","_urlChan ged");this.unlisten(window,"popstate","_urlChanged");this.unlisten(document.body ,"click","_globalOnClick");this._initialized=false},_hashChanged:function(){this .hash=window.decodeURIComponent(window.location.hash.substring(1))},_urlChanged: function(){this._dontUpdateUrl=true;this._hashChanged();this.path=window.decodeU RIComponent(window.location.pathname);this.query=window.decodeURIComponent(windo w.location.search.substring(1));this._dontUpdateUrl=false;this._updateUrl()},_ge tUrl:function(){var partiallyEncodedPath=window.encodeURI(this.path).replace(/\# /g,"%23").replace(/\?/g,"%3F");var partiallyEncodedQuery="";if(this.query){parti allyEncodedQuery="?"+window.encodeURI(this.query).replace(/\#/g,"%23")}var parti allyEncodedHash="";if(this.hash){partiallyEncodedHash="#"+window.encodeURI(this. hash)}return partiallyEncodedPath+partiallyEncodedQuery+partiallyEncodedHash},_u pdateUrl:function(){if(this._dontUpdateUrl||!this._initialized){return}if(this.p ath===window.decodeURIComponent(window.location.pathname)&&this.query===window.d ecodeURIComponent(window.location.search.substring(1))&&this.hash===window.decod eURIComponent(window.location.hash.substring(1))){return}var newUrl=this._getUrl ();var fullNewUrl=new URL(newUrl,window.location.protocol+"//"+window.location.h ost).href;var now=window.performance.now();var shouldReplace=this._lastChangedAt +this.dwellTime>now;this._lastChangedAt=now;if(shouldReplace){window.history.rep laceState({},"",fullNewUrl)}else{window.history.pushState({},"",fullNewUrl)}this .fire("location-changed",{},{node:window})},_globalOnClick:function(event){if(ev ent.defaultPrevented){return}var href=this._getSameOriginLinkHref(event);if(!hre f){return}event.preventDefault();if(href===window.location.href){return}window.h istory.pushState({},"",href);this.fire("location-changed",{},{node:window})},_ge tSameOriginLinkHref:function(event){if(event.button!==0){return null}if(event.me taKey||event.ctrlKey){return null}var eventPath=Polymer.dom(event).path;var anch or=null;for(var i=0;i<eventPath.length;i++){var element=eventPath[i];if(element. tagName==="A"&&element.href){anchor=element;break}}if(!anchor){return null}if(an chor.target==="_blank"){return null}if((anchor.target==="_top"||anchor.target=== "_parent")&&window.top!==window){return null}var href=anchor.href;var url;if(doc ument.baseURI!=null){url=new URL(href,document.baseURI)}else{url=new URL(href)}v ar origin;if(window.location.origin){origin=window.location.origin}else{origin=w indow.location.protocol+"//"+window.location.hostname;if(window.location.port){o rigin+=":"+window.location.port}}if(url.origin!==origin){return null}var normali zedHref=url.pathname+url.search+url.hash;if(this._urlSpaceRegExp&&!this._urlSpac eRegExp.test(normalizedHref)){return null}var fullNormalizedHref=new URL(normali zedHref,window.location.href).href;return fullNormalizedHref},_makeRegExp:functi on(urlSpaceRegex){return RegExp(urlSpaceRegex)}})})();"use strict";Polymer({is:" iron-query-params",properties:{paramsString:{type:String,notify:true,observer:"p aramsStringChanged"},paramsObject:{type:Object,notify:true,value:function(){retu rn{}}},_dontReact:{type:Boolean,value:false}},hostAttributes:{hidden:true},obser vers:["paramsObjectChanged(paramsObject.*)"],paramsStringChanged:function(){this ._dontReact=true;this.paramsObject=this._decodeParams(this.paramsString);this._d ontReact=false},paramsObjectChanged:function(){if(this._dontReact){return}this.p aramsString=this._encodeParams(this.paramsObject)},_encodeParams:function(params ){var encodedParams=[];for(var key in params){var value=params[key];if(value===" "){encodedParams.push(encodeURIComponent(key))}else if(value){encodedParams.push (encodeURIComponent(key)+"="+encodeURIComponent(value.toString()))}}return encod edParams.join("&")},_decodeParams:function(paramString){var params={};paramStrin g=(paramString||"").replace(/\+/g,"%20");var paramList=paramString.split("&");fo r(var i=0;i<paramList.length;i++){var param=paramList[i].split("=");if(param[0]) {params[decodeURIComponent(param[0])]=decodeURIComponent(param[1]||"")}}return p arams}});
77 // Copyright 2016 The Chromium Authors. All rights reserved. 77 // Copyright 2016 The Chromium Authors. All rights reserved.
78 // Use of this source code is governed by a BSD-style license that can be 78 // Use of this source code is governed by a BSD-style license that can be
79 // found in the LICENSE file. 79 // found in the LICENSE file.
80 Polymer({is:"history-router",properties:{selectedPage:{type:String,observer:"ser ializePath_",notify:true},queryState:{type:Object,notify:true,value:function(){r eturn{incremental:false,querying:true,queryingDisabled:false,_range:HistoryRange .ALL_TIME,searchTerm:"",groupedOffset:0,set range(val){this._range=Number(val)}, get range(){return this._range}}}},path_:{type:String,observer:"pathChanged_"},q ueryParams_:Object},observers:["queryParamsChanged_(queryParams_.*)","searchTerm Changed_(queryState.searchTerm)"],attached:function(){if(window.location.hash){w indow.location.href=window.location.href.split("#")[0]+"?"+window.location.hash. substr(1)}},serializePath_:function(){var page=this.selectedPage=="history"?"":t his.selectedPage;this.path_="/"+page},pathChanged_:function(){var sections=this. path_.substr(1).split("/");this.selectedPage=sections[0]||"history"},queryParams Changed_:function(){this.set("queryState.searchTerm",this.queryParams_.q||"")},s earchTermChanged_:function(){this.set("queryParams_.q",this.queryState.searchTer m||null)}});Polymer.IronMultiSelectableBehaviorImpl={properties:{multi:{type:Boo lean,value:false,observer:"multiChanged"},selectedValues:{type:Array,notify:true },selectedItems:{type:Array,readOnly:true,notify:true}},observers:["_updateSelec ted(selectedValues.splices)"],select:function(value){if(this.multi){if(this.sele ctedValues){this._toggleSelected(value)}else{this.selectedValues=[value]}}else{t his.selected=value}},multiChanged:function(multi){this._selection.multi=multi},g et _shouldUpdateSelection(){return this.selected!=null||this.selectedValues!=nul l&&this.selectedValues.length},_updateAttrForSelected:function(){if(!this.multi) {Polymer.IronSelectableBehavior._updateAttrForSelected.apply(this)}else if(this. _shouldUpdateSelection){this.selectedValues=this.selectedItems.map(function(sele ctedItem){return this._indexToValue(this.indexOf(selectedItem))},this).filter(fu nction(unfilteredValue){return unfilteredValue!=null},this)}},_updateSelected:fu nction(){if(this.multi){this._selectMulti(this.selectedValues)}else{this._select Selected(this.selected)}},_selectMulti:function(values){if(values){var selectedI tems=this._valuesToItems(values);this._selection.clear(selectedItems);for(var i= 0;i<selectedItems.length;i++){this._selection.setItemSelected(selectedItems[i],t rue)}if(this.fallbackSelection&&this.items.length&&!this._selection.get().length ){var fallback=this._valueToItem(this.fallbackSelection);if(fallback){this.selec tedValues=[this.fallbackSelection]}}}else{this._selection.clear()}},_selectionCh ange:function(){var s=this._selection.get();if(this.multi){this._setSelectedItem s(s)}else{this._setSelectedItems([s]);this._setSelectedItem(s)}},_toggleSelected :function(value){var i=this.selectedValues.indexOf(value);var unselected=i<0;if( unselected){this.push("selectedValues",value)}else{this.splice("selectedValues", i,1)}},_valuesToItems:function(values){return values==null?null:values.map(funct ion(value){return this._valueToItem(value)},this)}};Polymer.IronMultiSelectableB ehavior=[Polymer.IronSelectableBehavior,Polymer.IronMultiSelectableBehaviorImpl] ;Polymer({is:"iron-selector",behaviors:[Polymer.IronMultiSelectableBehavior]}); 80 Polymer({is:"history-router",properties:{selectedPage:{type:String,observer:"ser ializePath_",notify:true},path_:{type:String,observer:"pathChanged_"},queryState :Object,queryParams_:Object},observers:["queryParamsChanged_(queryParams_.*)","s earchTermChanged_(queryState.searchTerm)"],attached:function(){if(window.locatio n.hash){window.location.href=window.location.href.split("#")[0]+"?"+window.locat ion.hash.substr(1)}},serializePath_:function(){var page=this.selectedPage=="hist ory"?"":this.selectedPage;this.path_="/"+page},pathChanged_:function(){var secti ons=this.path_.substr(1).split("/");this.selectedPage=sections[0]||"history"},qu eryParamsChanged_:function(){this.fire("change-query",{search:this.queryParams_. q||""})},searchTermChanged_:function(){this.set("queryParams_.q",this.queryState .searchTerm||null)}});Polymer.IronMultiSelectableBehaviorImpl={properties:{multi :{type:Boolean,value:false,observer:"multiChanged"},selectedValues:{type:Array,n otify:true},selectedItems:{type:Array,readOnly:true,notify:true}},observers:["_u pdateSelected(selectedValues.splices)"],select:function(value){if(this.multi){if (this.selectedValues){this._toggleSelected(value)}else{this.selectedValues=[valu e]}}else{this.selected=value}},multiChanged:function(multi){this._selection.mult i=multi},get _shouldUpdateSelection(){return this.selected!=null||this.selectedV alues!=null&&this.selectedValues.length},_updateAttrForSelected:function(){if(!t his.multi){Polymer.IronSelectableBehavior._updateAttrForSelected.apply(this)}els e if(this._shouldUpdateSelection){this.selectedValues=this.selectedItems.map(fun ction(selectedItem){return this._indexToValue(this.indexOf(selectedItem))},this) .filter(function(unfilteredValue){return unfilteredValue!=null},this)}},_updateS elected:function(){if(this.multi){this._selectMulti(this.selectedValues)}else{th is._selectSelected(this.selected)}},_selectMulti:function(values){if(values){var selectedItems=this._valuesToItems(values);this._selection.clear(selectedItems); for(var i=0;i<selectedItems.length;i++){this._selection.setItemSelected(selected Items[i],true)}if(this.fallbackSelection&&this.items.length&&!this._selection.ge t().length){var fallback=this._valueToItem(this.fallbackSelection);if(fallback){ this.selectedValues=[this.fallbackSelection]}}}else{this._selection.clear()}},_s electionChange:function(){var s=this._selection.get();if(this.multi){this._setSe lectedItems(s)}else{this._setSelectedItems([s]);this._setSelectedItem(s)}},_togg leSelected:function(value){var i=this.selectedValues.indexOf(value);var unselect ed=i<0;if(unselected){this.push("selectedValues",value)}else{this.splice("select edValues",i,1)}},_valuesToItems:function(values){return values==null?null:values .map(function(value){return this._valueToItem(value)},this)}};Polymer.IronMultiS electableBehavior=[Polymer.IronSelectableBehavior,Polymer.IronMultiSelectableBeh aviorImpl];Polymer({is:"iron-selector",behaviors:[Polymer.IronMultiSelectableBeh avior]});
81 // Copyright 2016 The Chromium Authors. All rights reserved. 81 // Copyright 2016 The Chromium Authors. All rights reserved.
82 // Use of this source code is governed by a BSD-style license that can be 82 // Use of this source code is governed by a BSD-style license that can be
83 // found in the LICENSE file. 83 // found in the LICENSE file.
84 Polymer({is:"history-side-bar",behaviors:[Polymer.IronA11yKeysBehavior],properti es:{selectedPage:{type:String,notify:true},showFooter:Boolean},keyBindings:{"spa ce:keydown":"onSpacePressed_"},onSpacePressed_:function(e){e.detail.keyboardEven t.path[0].click()},onSelectorActivate_:function(){this.fire("history-close-drawe r")},onClearBrowsingDataTap_:function(e){var browserService=md_history.BrowserSe rvice.getInstance();browserService.recordAction("InitClearBrowsingData");browser Service.openClearBrowsingData();this.$["cbd-ripple"].upAction();e.preventDefault ()},onItemClick_:function(e){e.preventDefault()}}); 84 Polymer({is:"history-side-bar",behaviors:[Polymer.IronA11yKeysBehavior],properti es:{selectedPage:{type:String,notify:true},showFooter:Boolean},keyBindings:{"spa ce:keydown":"onSpacePressed_"},onSpacePressed_:function(e){e.detail.keyboardEven t.path[0].click()},onSelectorActivate_:function(){this.fire("history-close-drawe r")},onClearBrowsingDataTap_:function(e){var browserService=md_history.BrowserSe rvice.getInstance();browserService.recordAction("InitClearBrowsingData");browser Service.openClearBrowsingData();this.$["cbd-ripple"].upAction();e.preventDefault ()},onItemClick_:function(e){e.preventDefault()}});
85 // Copyright 2016 The Chromium Authors. All rights reserved. 85 // Copyright 2016 The Chromium Authors. All rights reserved.
86 // Use of this source code is governed by a BSD-style license that can be 86 // Use of this source code is governed by a BSD-style license that can be
87 // found in the LICENSE file. 87 // found in the LICENSE file.
88 cr.define("md_history",function(){var lazyLoadPromise=null;function ensureLazyLo aded(){if(!lazyLoadPromise){lazyLoadPromise=new Promise(function(resolve,reject) {Polymer.Base.importHref("chrome://history/lazy_load.html",resolve,reject,true)} )}return lazyLoadPromise}return{ensureLazyLoaded:ensureLazyLoaded}});Polymer({is :"history-app",behaviors:[Polymer.IronScrollTargetBehavior],properties:{selected Page_:{type:String,observer:"selectedPageChanged_"},grouped_:{type:Boolean,refle ctToAttribute:true},queryResult_:{type:Object,value:function(){return{info:null, results:null,sessionList:null}}},isUserSignedIn_:{type:Boolean,value:loadTimeDat a.getBoolean("isUserSignedIn")},toolbarShadow_:{type:Boolean,reflectToAttribute: true,notify:true},showMenuPromo_:{type:Boolean,value:function(){return loadTimeD ata.getBoolean("showMenuPromo")}},queryState_:Object,hasDrawer_:{type:Boolean,ob server:"hasDrawerChanged_"},showSidebarFooter:Boolean,hasSyncedResults:Boolean}, listeners:{"cr-toolbar-menu-promo-close":"onCrToolbarMenuPromoClose_","cr-toolba r-menu-promo-shown":"onCrToolbarMenuPromoShown_","cr-toolbar-menu-tap":"onCrTool barMenuTap_","delete-selected":"deleteSelected","history-checkbox-select":"check boxSelected","history-close-drawer":"closeDrawer_","history-view-changed":"histo ryViewChanged_","opened-changed":"onOpenedChanged_","unselect-all":"unselectAll" },boundOnCanExecute_:null,boundOnCommand_:null,attached:function(){this.grouped_ =loadTimeData.getBoolean("groupByDomain");cr.ui.decorate("command",cr.ui.Command );this.boundOnCanExecute_=this.onCanExecute_.bind(this);this.boundOnCommand_=thi s.onCommand_.bind(this);document.addEventListener("canExecute",this.boundOnCanEx ecute_);document.addEventListener("command",this.boundOnCommand_)},detached:func tion(){document.removeEventListener("canExecute",this.boundOnCanExecute_);docume nt.removeEventListener("command",this.boundOnCommand_)},onFirstRender:function() {setTimeout(function(){chrome.send("metricsHandler:recordTime",["History.Results RenderedTime",window.performance.now()])});var searchField=this.$.toolbar.search Field;if(!searchField.narrow){searchField.getSearchInput().focus()}md_history.en sureLazyLoaded().then(function(){window.requestIdleCallback(function(){document. fonts.load("bold 12px Roboto")})})},_scrollHandler:function(){if(this.scrollTarg et)this.toolbarShadow_=this.scrollTarget.scrollTop!=0},onCrToolbarMenuPromoClose _:function(){this.showMenuPromo_=false},onCrToolbarMenuPromoShown_:function(){md _history.BrowserService.getInstance().menuPromoShown()},onCrToolbarMenuTap_:func tion(){var drawer=this.$.drawer.get();drawer.align=document.documentElement.dir= ="ltr"?"left":"right";drawer.toggle()},onOpenedChanged_:function(e){if(e.detail. value)this.showMenuPromo_=false},checkboxSelected:function(e){var toolbar=this.$ .toolbar;toolbar.count=this.$.history.getSelectedItemCount()},unselectAll:functi on(){var listContainer=this.$.history;var toolbar=this.$.toolbar;listContainer.u nselectAllItems(toolbar.count);toolbar.count=0},deleteSelected:function(){this.$ .history.deleteSelectedWithPrompt()},historyResult:function(info,results){this.s et("queryState_.querying",false);this.set("queryResult_.info",info);this.set("qu eryResult_.results",results);var listContainer=this.$["history"];listContainer.h istoryResult(info,results)},focusToolbarSearchField:function(){this.$.toolbar.sh owSearchField()},onCanExecute_:function(e){e=e;switch(e.command.id){case"find-co mmand":case"toggle-grouped":e.canExecute=true;break;case"slash-command":e.canExe cute=!this.$.toolbar.searchField.isSearchFocused();break;case"delete-command":e. canExecute=this.$.toolbar.count>0;break}},onCommand_:function(e){if(e.command.id =="find-command"||e.command.id=="slash-command")this.focusToolbarSearchField();i f(e.command.id=="delete-command")this.deleteSelected();if(e.command.id=="toggle- grouped")this.grouped_=!this.grouped_},setForeignSessions:function(sessionList){ this.set("queryResult_.sessionList",sessionList)},historyDeleted:function(){this .$.history.historyDeleted()},updateSignInState:function(isUserSignedIn){this.isU serSignedIn_=isUserSignedIn},syncedTabsSelected_:function(selectedPage){return s electedPage=="syncedTabs"},shouldShowSpinner_:function(querying,incremental,sear chTerm){return querying&&!incremental&&searchTerm!=""},showSyncNotice_:function( hasSyncedResults,selectedPage){return hasSyncedResults&&selectedPage!="syncedTab s"},selectedPageChanged_:function(){this.unselectAll();this.historyViewChanged_( )},historyViewChanged_:function(){requestAnimationFrame(function(){md_history.en sureLazyLoaded().then(function(){if(!this.$.content.selectedItem)return;this.scr ollTarget=this.$.content.selectedItem.getContentScrollTarget();this._scrollHandl er()}.bind(this))}.bind(this));this.recordHistoryPageView_()},hasDrawerChanged_: function(){var drawer=this.$.drawer.getIfExists();if(!this.hasDrawer_&&drawer&&d rawer.open)drawer.closeDrawer()},getSelectedPage_:function(selectedPage,items){r eturn selectedPage},closeDrawer_:function(){var drawer=this.$.drawer.get();if(dr awer&&drawer.open)drawer.closeDrawer()},recordHistoryPageView_:function(){var hi stogramValue=HistoryPageViewHistogram.END;switch(this.selectedPage_){case"synced Tabs":histogramValue=this.isUserSignedIn_?HistoryPageViewHistogram.SYNCED_TABS:H istoryPageViewHistogram.SIGNIN_PROMO;break;default:switch(this.queryState_.range ){case HistoryRange.ALL_TIME:histogramValue=HistoryPageViewHistogram.HISTORY;bre ak;case HistoryRange.WEEK:histogramValue=HistoryPageViewHistogram.GROUPED_WEEK;b reak;case HistoryRange.MONTH:histogramValue=HistoryPageViewHistogram.GROUPED_MON TH;break}break}md_history.BrowserService.getInstance().recordHistogram("History. HistoryPageView",histogramValue,HistoryPageViewHistogram.END)}}); 88 cr.define("md_history",function(){var lazyLoadPromise=null;function ensureLazyLo aded(){if(!lazyLoadPromise){lazyLoadPromise=new Promise(function(resolve,reject) {Polymer.Base.importHref("chrome://history/lazy_load.html",resolve,reject,true)} )}return lazyLoadPromise}return{ensureLazyLoaded:ensureLazyLoaded}});Polymer({is :"history-app",behaviors:[Polymer.IronScrollTargetBehavior],properties:{selected Page_:{type:String,observer:"selectedPageChanged_"},grouped_:{type:Boolean,refle ctToAttribute:true},queryResult_:{type:Object,value:function(){return{info:null, results:null,sessionList:null}}},isUserSignedIn_:{type:Boolean,value:loadTimeDat a.getBoolean("isUserSignedIn")},toolbarShadow_:{type:Boolean,reflectToAttribute: true,notify:true},showMenuPromo_:{type:Boolean,value:function(){return loadTimeD ata.getBoolean("showMenuPromo")}},queryState_:Object,hasDrawer_:{type:Boolean,ob server:"hasDrawerChanged_"},showSidebarFooter:Boolean,hasSyncedResults:Boolean}, listeners:{"cr-toolbar-menu-promo-close":"onCrToolbarMenuPromoClose_","cr-toolba r-menu-promo-shown":"onCrToolbarMenuPromoShown_","cr-toolbar-menu-tap":"onCrTool barMenuTap_","delete-selected":"deleteSelected","history-checkbox-select":"check boxSelected","history-close-drawer":"closeDrawer_","history-view-changed":"histo ryViewChanged_","opened-changed":"onOpenedChanged_","unselect-all":"unselectAll" },boundOnCanExecute_:null,boundOnCommand_:null,attached:function(){this.grouped_ =loadTimeData.getBoolean("groupByDomain");cr.ui.decorate("command",cr.ui.Command );this.boundOnCanExecute_=this.onCanExecute_.bind(this);this.boundOnCommand_=thi s.onCommand_.bind(this);document.addEventListener("canExecute",this.boundOnCanEx ecute_);document.addEventListener("command",this.boundOnCommand_)},detached:func tion(){document.removeEventListener("canExecute",this.boundOnCanExecute_);docume nt.removeEventListener("command",this.boundOnCommand_)},onFirstRender:function() {setTimeout(function(){chrome.send("metricsHandler:recordTime",["History.Results RenderedTime",window.performance.now()])});var searchField=this.$.toolbar.search Field;if(!searchField.narrow){searchField.getSearchInput().focus()}md_history.en sureLazyLoaded().then(function(){window.requestIdleCallback(function(){document. fonts.load("bold 12px Roboto")})})},_scrollHandler:function(){if(this.scrollTarg et)this.toolbarShadow_=this.scrollTarget.scrollTop!=0},onCrToolbarMenuPromoClose _:function(){this.showMenuPromo_=false},onCrToolbarMenuPromoShown_:function(){md _history.BrowserService.getInstance().menuPromoShown()},onCrToolbarMenuTap_:func tion(){var drawer=this.$.drawer.get();drawer.align=document.documentElement.dir= ="ltr"?"left":"right";drawer.toggle()},onOpenedChanged_:function(e){if(e.detail. value)this.showMenuPromo_=false},checkboxSelected:function(e){var toolbar=this.$ .toolbar;toolbar.count=this.$.history.getSelectedItemCount()},unselectAll:functi on(){var listContainer=this.$.history;var toolbar=this.$.toolbar;listContainer.u nselectAllItems(toolbar.count);toolbar.count=0},deleteSelected:function(){this.$ .history.deleteSelectedWithPrompt()},historyResult:function(info,results){this.s et("queryState_.querying",false);this.set("queryResult_.info",info);this.set("qu eryResult_.results",results);var listContainer=this.$["history"];listContainer.h istoryResult(info,results)},focusToolbarSearchField:function(){this.$.toolbar.sh owSearchField()},onCanExecute_:function(e){e=e;switch(e.command.id){case"find-co mmand":case"toggle-grouped":e.canExecute=true;break;case"slash-command":e.canExe cute=!this.$.toolbar.searchField.isSearchFocused();break;case"delete-command":e. canExecute=this.$.toolbar.count>0;break}},onCommand_:function(e){if(e.command.id =="find-command"||e.command.id=="slash-command")this.focusToolbarSearchField();i f(e.command.id=="delete-command")this.deleteSelected();if(e.command.id=="toggle- grouped")this.grouped_=!this.grouped_},setForeignSessions:function(sessionList){ this.set("queryResult_.sessionList",sessionList)},historyDeleted:function(){this .$.history.historyDeleted()},updateSignInState:function(isUserSignedIn){this.isU serSignedIn_=isUserSignedIn},syncedTabsSelected_:function(selectedPage){return s electedPage=="syncedTabs"},shouldShowSpinner_:function(querying,incremental,sear chTerm){return querying&&!incremental&&searchTerm!=""},showSyncNotice_:function( hasSyncedResults,selectedPage){return hasSyncedResults&&selectedPage!="syncedTab s"},selectedPageChanged_:function(){this.unselectAll();this.historyViewChanged_( )},historyViewChanged_:function(){requestAnimationFrame(function(){md_history.en sureLazyLoaded().then(function(){if(!this.$.content.selectedItem)return;this.scr ollTarget=this.$.content.selectedItem.getContentScrollTarget();this._scrollHandl er()}.bind(this))}.bind(this));this.recordHistoryPageView_()},hasDrawerChanged_: function(){var drawer=this.$.drawer.getIfExists();if(!this.hasDrawer_&&drawer&&d rawer.open)drawer.closeDrawer()},getSelectedPage_:function(selectedPage,items){r eturn selectedPage},closeDrawer_:function(){var drawer=this.$.drawer.get();if(dr awer&&drawer.open)drawer.closeDrawer()},recordHistoryPageView_:function(){var hi stogramValue=HistoryPageViewHistogram.END;switch(this.selectedPage_){case"synced Tabs":histogramValue=this.isUserSignedIn_?HistoryPageViewHistogram.SYNCED_TABS:H istoryPageViewHistogram.SIGNIN_PROMO;break;default:switch(this.queryState_.range ){case HistoryRange.ALL_TIME:histogramValue=HistoryPageViewHistogram.HISTORY;bre ak;case HistoryRange.WEEK:histogramValue=HistoryPageViewHistogram.GROUPED_WEEK;b reak;case HistoryRange.MONTH:histogramValue=HistoryPageViewHistogram.GROUPED_MON TH;break}break}md_history.BrowserService.getInstance().recordHistogram("History. HistoryPageView",histogramValue,HistoryPageViewHistogram.END)}});
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698