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

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

Issue 2450663003: MD History: hide tooltip promo when drawer is swiped open (Closed)
Patch Set: on-lonely="fixUpCode_" Created 4 years, 1 month 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 16 matching lines...) Expand all
27 // Use of this source code is governed by a BSD-style license that can be 27 // Use of this source code is governed by a BSD-style license that can be
28 // found in the LICENSE file. 28 // found in the LICENSE file.
29 var CrSearchFieldBehavior={properties:{label:{type:String,value:""},clearLabel:{ type:String,value:""},showingSearch:{type:Boolean,value:false,notify:true,observ er:"showingSearchChanged_",reflectToAttribute:true},lastValue_:{type:String,valu e:""}},getSearchInput:function(){},getValue:function(){return this.getSearchInpu t().value},setValue:function(value){this.getSearchInput().bindValue=value;this.o nValueChanged_(value)},showAndFocus:function(){this.showingSearch=true;this.focu s_()},focus_:function(){this.getSearchInput().focus()},onSearchTermSearch:functi on(){this.onValueChanged_(this.getValue())},onValueChanged_:function(newValue){i f(newValue==this.lastValue_)return;this.lastValue_=newValue;this.fire("search-ch anged",newValue)},onSearchTermKeydown:function(e){if(e.key=="Escape")this.showin gSearch=false},showingSearchChanged_:function(){if(this.showingSearch){this.focu s_();return}this.setValue("");this.getSearchInput().blur()}}; 29 var CrSearchFieldBehavior={properties:{label:{type:String,value:""},clearLabel:{ type:String,value:""},showingSearch:{type:Boolean,value:false,notify:true,observ er:"showingSearchChanged_",reflectToAttribute:true},lastValue_:{type:String,valu e:""}},getSearchInput:function(){},getValue:function(){return this.getSearchInpu t().value},setValue:function(value){this.getSearchInput().bindValue=value;this.o nValueChanged_(value)},showAndFocus:function(){this.showingSearch=true;this.focu s_()},focus_:function(){this.getSearchInput().focus()},onSearchTermSearch:functi on(){this.onValueChanged_(this.getValue())},onValueChanged_:function(newValue){i f(newValue==this.lastValue_)return;this.lastValue_=newValue;this.fire("search-ch anged",newValue)},onSearchTermKeydown:function(e){if(e.key=="Escape")this.showin gSearch=false},showingSearchChanged_:function(){if(this.showingSearch){this.focu s_();return}this.setValue("");this.getSearchInput().blur()}};
30 // Copyright 2016 The Chromium Authors. All rights reserved. 30 // Copyright 2016 The Chromium Authors. All rights reserved.
31 // Use of this source code is governed by a BSD-style license that can be 31 // Use of this source code is governed by a BSD-style license that can be
32 // found in the LICENSE file. 32 // found in the LICENSE file.
33 Polymer({is:"cr-toolbar-search-field",behaviors:[CrSearchFieldBehavior],properti es:{narrow:{type:Boolean,reflectToAttribute:true},label:String,clearLabel:String ,spinnerActive:{type:Boolean,reflectToAttribute:true},hasSearchText_:Boolean,isS pinnerShown_:{type:Boolean,computed:"computeIsSpinnerShown_(spinnerActive, showi ngSearch)"}},listeners:{tap:"showSearch_","searchInput.bind-value-changed":"onBi ndValueChanged_"},getSearchInput:function(){return this.$.searchInput},isSearchF ocused:function(){return this.$.searchTerm.focused},computeIconTabIndex_:functio n(narrow){return narrow?0:-1},computeIsSpinnerShown_:function(){return this.spin nerActive&&this.showingSearch},onInputBlur_:function(){if(!this.hasSearchText_)t his.showingSearch=false},onBindValueChanged_:function(){var newValue=this.$.sear chInput.bindValue;this.hasSearchText_=newValue!="";if(newValue!="")this.showingS earch=true},showSearch_:function(e){if(e.target!=this.$.clearSearch)this.showing Search=true},clearSearch_:function(e){this.setValue("");this.getSearchInput().fo cus()}}); 33 Polymer({is:"cr-toolbar-search-field",behaviors:[CrSearchFieldBehavior],properti es:{narrow:{type:Boolean,reflectToAttribute:true},label:String,clearLabel:String ,spinnerActive:{type:Boolean,reflectToAttribute:true},hasSearchText_:Boolean,isS pinnerShown_:{type:Boolean,computed:"computeIsSpinnerShown_(spinnerActive, showi ngSearch)"}},listeners:{tap:"showSearch_","searchInput.bind-value-changed":"onBi ndValueChanged_"},getSearchInput:function(){return this.$.searchInput},isSearchF ocused:function(){return this.$.searchTerm.focused},computeIconTabIndex_:functio n(narrow){return narrow?0:-1},computeIsSpinnerShown_:function(){return this.spin nerActive&&this.showingSearch},onInputBlur_:function(){if(!this.hasSearchText_)t his.showingSearch=false},onBindValueChanged_:function(){var newValue=this.$.sear chInput.bindValue;this.hasSearchText_=newValue!="";if(newValue!="")this.showingS earch=true},showSearch_:function(e){if(e.target!=this.$.clearSearch)this.showing Search=true},clearSearch_:function(e){this.setValue("");this.getSearchInput().fo cus()}});
34 // Copyright 2016 The Chromium Authors. All rights reserved. 34 // Copyright 2016 The Chromium Authors. All rights reserved.
35 // Use of this source code is governed by a BSD-style license that can be 35 // Use of this source code is governed by a BSD-style license that can be
36 // found in the LICENSE file. 36 // found in the LICENSE file.
37 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.showMenuPromo=false},onMenuTap_:function(){this.fire( "cr-menu-tap");this.onClosePromoTap_()},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-menu-promo-shown")}}.bind(this))},titleI fNotShowMenuPromo_:function(title,showMenuPromo){return showMenuPromo?"":title}} ); 37 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}});
38 // Copyright 2016 The Chromium Authors. All rights reserved. 38 // Copyright 2016 The Chromium Authors. All rights reserved.
39 // Use of this source code is governed by a BSD-style license that can be 39 // Use of this source code is governed by a BSD-style license that can be
40 // found in the LICENSE file. 40 // found in the LICENSE file.
41 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)} 41 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)}
42 // Copyright 2015 The Chromium Authors. All rights reserved. 42 // Copyright 2015 The Chromium Authors. All rights reserved.
43 // Use of this source code is governed by a BSD-style license that can be 43 // Use of this source code is governed by a BSD-style license that can be
44 // found in the LICENSE file. 44 // found in the LICENSE file.
45 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,observer:"hasDrawerCha nged_",reflectToAttribute:true},showSyncNotice:Boolean,isGroupedMode:{type:Boole an,reflectToAttribute:true},groupedRange:{type:Number,value:0,reflectToAttribute :true,notify:true},queryStartTime:String,queryEndTime:String,showMenuPromo_:{typ e:Boolean,value:function(){return loadTimeData.getBoolean("showMenuPromo")}}},ge t searchField(){return this.$["main-toolbar"].getSearchField()},showSearchField: function(){this.searchField.showAndFocus()},changeToolbarView_:function(){this.i temsSelected_=this.count>0},searchTermChanged_:function(){if(this.searchField.ge tValue()!=this.searchTerm){this.searchField.showAndFocus();this.searchField.setV alue(this.searchTerm)}},onMenuPromoShown_:function(){md_history.BrowserService.g etInstance().menuPromoShown()},onSearchChanged_:function(event){this.searchTerm= event.detail},onInfoButtonTap_:function(){var dropdown=this.$.syncNotice.get();d ropdown.positionTarget=this.$$("#info-button-icon");if(dropdown.style.display==" none")dropdown.open()},onClearSelectionTap_:function(){this.fire("unselect-all") },onDeleteTap_:function(){this.fire("delete-selected")},deletingAllowed_:functio n(){return loadTimeData.getBoolean("allowDeletingHistory")},numberOfItemsSelecte d_:function(count){return count>0?loadTimeData.getStringF("itemsSelected",count) :""},getHistoryInterval_:function(queryStartTime,queryEndTime){return loadTimeDa ta.getStringF("historyInterval",queryStartTime,queryEndTime)},hasDrawerChanged_: function(){this.updateStyles()}});(function(){var IOS=navigator.userAgent.match( /iP(?:hone|ad;(?: U;)? CPU) OS (\d+)/);var IOS_TOUCH_SCROLLING=IOS&&IOS[1]>=8;va r DEFAULT_PHYSICAL_COUNT=3;var HIDDEN_Y="-10000px";var ITEM_WIDTH=0;var ITEM_HEI GHT=1;var SECRET_TABINDEX=-100;Polymer({is:"iron-list",properties:{items:{type:A rray},maxPhysicalCount:{type:Number,value:500},as:{type:String,value:"item"},ind exAs:{type:String,value:"index"},selectedAs:{type:String,value:"selected"},grid: {type:Boolean,value:false,reflectToAttribute:true},selectionEnabled:{type:Boolea n,value:false},selectedItem:{type:Object,notify:true},selectedItems:{type:Object ,notify:true},multiSelection:{type:Boolean,value:false}},observers:["_itemsChang ed(items.*)","_selectionEnabledChanged(selectionEnabled)","_multiSelectionChange d(multiSelection)","_setOverflow(scrollTarget)"],behaviors:[Polymer.Templatizer, Polymer.IronResizableBehavior,Polymer.IronA11yKeysBehavior,Polymer.IronScrollTar getBehavior],keyBindings:{up:"_didMoveUp",down:"_didMoveDown",enter:"_didEnter"} ,_ratio:.5,_scrollerPaddingTop:0,_scrollPosition:0,_physicalSize:0,_physicalAver age:0,_physicalAverageCount:0,_physicalTop:0,_virtualCount:0,_physicalIndexForKe y:null,_estScrollHeight:0,_scrollHeight:0,_viewportHeight:0,_viewportWidth:0,_ph ysicalItems:null,_physicalSizes:null,_firstVisibleIndexVal:null,_lastVisibleInde xVal:null,_collection:null,_maxPages:2,_focusedItem:null,_focusedIndex:-1,_offsc reenFocusedItem:null,_focusBackfillItem:null,_itemsPerRow:1,_itemWidth:0,_rowHei ght:0,_templateCost:0,get _physicalBottom(){return this._physicalTop+this._physi calSize},get _scrollBottom(){return this._scrollPosition+this._viewportHeight},g et _virtualEnd(){return this._virtualStart+this._physicalCount-1},get _hiddenCon tentSize(){var size=this.grid?this._physicalRows*this._rowHeight:this._physicalS ize;return size-this._viewportHeight},get _maxScrollTop(){return this._estScroll Height-this._viewportHeight+this._scrollerPaddingTop},_minVirtualStart:0,get _ma xVirtualStart(){return Math.max(0,this._virtualCount-this._physicalCount)},_virt ualStartVal:0,set _virtualStart(val){this._virtualStartVal=Math.min(this._maxVir tualStart,Math.max(this._minVirtualStart,val))},get _virtualStart(){return this. _virtualStartVal||0},_physicalStartVal:0,set _physicalStart(val){this._physicalS tartVal=val%this._physicalCount;if(this._physicalStartVal<0){this._physicalStart Val=this._physicalCount+this._physicalStartVal}this._physicalEnd=(this._physical Start+this._physicalCount-1)%this._physicalCount},get _physicalStart(){return th is._physicalStartVal||0},_physicalCountVal:0,set _physicalCount(val){this._physi calCountVal=val;this._physicalEnd=(this._physicalStart+this._physicalCount-1)%th is._physicalCount},get _physicalCount(){return this._physicalCountVal},_physical End:0,get _optPhysicalSize(){if(this.grid){return this._estRowsInView*this._rowH eight*this._maxPages}return this._viewportHeight*this._maxPages},get _isVisible( ){return Boolean(this.offsetWidth||this.offsetHeight)},get firstVisibleIndex(){i f(this._firstVisibleIndexVal===null){var physicalOffset=Math.floor(this._physica lTop+this._scrollerPaddingTop);this._firstVisibleIndexVal=this._iterateItems(fun ction(pidx,vidx){physicalOffset+=this._getPhysicalSizeIncrement(pidx);if(physica lOffset>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},get lastVisibleIndex(){if(this._lastVisib leIndexVal===null){if(this.grid){var lastIndex=this.firstVisibleIndex+this._estR owsInView*this._itemsPerRow-1;this._lastVisibleIndexVal=Math.min(this._virtualCo unt,lastIndex)}else{var physicalOffset=this._physicalTop;this._iterateItems(func tion(pidx,vidx){if(physicalOffset<this._scrollBottom){this._lastVisibleIndexVal= vidx}else{return true}physicalOffset+=this._getPhysicalSizeIncrement(pidx)})}}re turn this._lastVisibleIndexVal},get _defaultScrollTarget(){return this},get _vir tualRowCount(){return Math.ceil(this._virtualCount/this._itemsPerRow)},get _estR owsInView(){return Math.ceil(this._viewportHeight/this._rowHeight)},get _physica lRows(){return Math.ceil(this._physicalCount/this._itemsPerRow)},ready:function( ){this.addEventListener("focus",this._didFocus.bind(this),true)},attached:functi on(){if(this._physicalCount===0){this._debounceTemplate(this._render)}this.liste n(this,"iron-resize","_resizeHandler")},detached:function(){this.unlisten(this," iron-resize","_resizeHandler")},_setOverflow:function(scrollTarget){this.style.w ebkitOverflowScrolling=scrollTarget===this?"touch":"";this.style.overflow=scroll Target===this?"auto":""},updateViewportBoundaries:function(){this._scrollerPaddi ngTop=this.scrollTarget===this?0:parseInt(window.getComputedStyle(this)["padding -top"],10);this._viewportWidth=this.$.items.offsetWidth;this._viewportHeight=thi s._scrollTargetHeight;this.grid&&this._updateGridMetrics()},_scrollHandler:funct ion(){var scrollTop=Math.max(0,Math.min(this._maxScrollTop,this._scrollTop));var delta=scrollTop-this._scrollPosition;var isScrollingDown=delta>=0;this._scrollP osition=scrollTop;this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null ;if(Math.abs(delta)>this._physicalSize){var idxAdjustment=Math.round(delta/this. _physicalAverage)*this._itemsPerRow;this._physicalTop=this._physicalTop+delta;th is._virtualStart=this._virtualStart+idxAdjustment;this._physicalStart=this._phys icalStart+idxAdjustment;this._update()}else{var reusables=this._getReusables(isS crollingDown);if(isScrollingDown){this._physicalTop=reusables.physicalTop;this._ virtualStart=this._virtualStart+reusables.indexes.length;this._physicalStart=thi s._physicalStart+reusables.indexes.length}else{this._virtualStart=this._virtualS tart-reusables.indexes.length;this._physicalStart=this._physicalStart-reusables. indexes.length}if(reusables.indexes.length===0){this._increasePoolIfNeeded()}els e{this._update(reusables.indexes,isScrollingDown?null:reusables.indexes)}}},_get Reusables:function(fromTop){var ith,lastIth,offsetContent,physicalItemHeight;var idxs=[];var protectedOffsetContent=this._hiddenContentSize*this._ratio;var virt ualStart=this._virtualStart;var virtualEnd=this._virtualEnd;var physicalCount=th is._physicalCount;var physicalTop=this._physicalTop;var scrollTop=this._scrollTo p;var scrollBottom=this._scrollBottom;if(fromTop){ith=this._physicalStart;lastIt h=this._physicalEnd;offsetContent=scrollTop-physicalTop}else{ith=this._physicalE nd;lastIth=this._physicalStart;offsetContent=this._physicalBottom-scrollBottom}w hile(true){physicalItemHeight=this._getPhysicalSizeIncrement(ith);offsetContent= offsetContent-physicalItemHeight;if(idxs.length>=physicalCount||offsetContent<=p rotectedOffsetContent){break}if(fromTop){if(virtualEnd+idxs.length+1>=this._virt ualCount){break}if(physicalTop+physicalItemHeight>=scrollTop){break}idxs.push(it h);physicalTop=physicalTop+physicalItemHeight;ith=(ith+1)%physicalCount}else{if( virtualStart-idxs.length<=0){break}if(physicalTop+this._physicalSize-physicalIte mHeight<=scrollBottom){break}idxs.push(ith);physicalTop=physicalTop-physicalItem Height;ith=ith===0?physicalCount-1:ith-1}}return{indexes:idxs,physicalTop:physic alTop}},_update:function(itemSet,movingUp){if(itemSet&&itemSet.length===0){retur n}this._manageFocus();this._assignModels(itemSet);this._updateMetrics(itemSet);i f(movingUp){while(movingUp.length){var idx=movingUp.pop();this._physicalTop-=thi s._getPhysicalSizeIncrement(idx)}}this._positionItems();this._updateScrollerSize ();this._increasePoolIfNeeded()},_createPool:function(size){var physicalItems=ne w Array(size);this._ensureTemplatized();for(var i=0;i<size;i++){var inst=this.st amp(null);physicalItems[i]=inst.root.querySelector("*");Polymer.dom(this).append Child(inst.root)}return physicalItems},_increasePoolIfNeeded:function(){if(this. _viewportHeight===0){return false}var self=this;var isClientFull=this._physicalB ottom>=this._scrollBottom&&this._physicalTop<=this._scrollPosition;if(this._phys icalSize>=this._optPhysicalSize&&isClientFull){return false}var maxPoolSize=Math .round(this._physicalCount*.5);if(!isClientFull){this._debounceTemplate(this._in creasePool.bind(this,maxPoolSize));return true}this._yield(function(){self._incr easePool(Math.min(maxPoolSize,Math.max(1,Math.round(50/self._templateCost))))}); return true},_yield:function(cb){var g=window;var handle=g.requestIdleCallback?g .requestIdleCallback(cb):g.setTimeout(cb,16);Polymer.dom.addDebouncer({complete: function(){g.cancelIdleCallback?g.cancelIdleCallback(handle):g.clearTimeout(hand le);cb()}})},_increasePool:function(missingItems){var nextPhysicalCount=Math.min (this._physicalCount+missingItems,this._virtualCount-this._virtualStart,Math.max (this.maxPhysicalCount,DEFAULT_PHYSICAL_COUNT));var prevPhysicalCount=this._phys icalCount;var delta=nextPhysicalCount-prevPhysicalCount;var ts=window.performanc e.now();if(delta<=0){return}[].push.apply(this._physicalItems,this._createPool(d elta));[].push.apply(this._physicalSizes,new Array(delta));this._physicalCount=p revPhysicalCount+delta;if(this._physicalStart>this._physicalEnd&&this._isIndexRe ndered(this._focusedIndex)&&this._getPhysicalIndex(this._focusedIndex)<this._phy sicalEnd){this._physicalStart=this._physicalStart+delta}this._update();this._tem plateCost=(window.performance.now()-ts)/delta},_render:function(){if(this.isAtta ched&&this._isVisible){if(this._physicalCount===0){this.updateViewportBoundaries ();this._increasePool(DEFAULT_PHYSICAL_COUNT)}else{var reusables=this._getReusab les(true);this._physicalTop=reusables.physicalTop;this._virtualStart=this._virtu alStart+reusables.indexes.length;this._physicalStart=this._physicalStart+reusabl es.indexes.length;this._update(reusables.indexes);this._update()}}},_ensureTempl atized:function(){if(!this.ctor){var props={};props.__key__=true;props[this.as]= true;props[this.indexAs]=true;props[this.selectedAs]=true;props.tabIndex=true;th is._instanceProps=props;this._userTemplate=Polymer.dom(this).querySelector("temp late");if(this._userTemplate){this.templatize(this._userTemplate)}else{console.w arn("iron-list requires a template to be provided in light-dom")}}},_getStampedC hildren:function(){return this._physicalItems},_forwardInstancePath:function(ins t,path,value){if(path.indexOf(this.as+".")===0){this.notifyPath("items."+inst.__ key__+"."+path.slice(this.as.length+1),value)}},_forwardParentProp:function(prop ,value){if(this._physicalItems){this._physicalItems.forEach(function(item){item. _templateInstance[prop]=value},this)}},_forwardParentPath:function(path,value){i f(this._physicalItems){this._physicalItems.forEach(function(item){item._template Instance.notifyPath(path,value,true)},this)}},_forwardItemPath:function(path,val ue){if(!this._physicalIndexForKey){return}var dot=path.indexOf(".");var key=path .substring(0,dot<0?path.length:dot);var idx=this._physicalIndexForKey[key];var o ffscreenItem=this._offscreenFocusedItem;var el=offscreenItem&&offscreenItem._tem plateInstance.__key__===key?offscreenItem:this._physicalItems[idx];if(!el||el._t emplateInstance.__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.isArray(this.selectedItems)){for(var i=0;i< this.selectedItems.length;i++){if(this.selectedItems[i]===currentItem){this.set( "selectedItems."+i,value);break}}}else if(this.selectedItem===currentItem){this. set("selectedItem",value)}el._templateInstance[this.as]=value}},_itemsChanged:fu nction(change){if(change.path==="items"){this._virtualStart=0;this._physicalTop= 0;this._virtualCount=this.items?this.items.length:0;this._collection=this.items? Polymer.Collection.get(this.items):null;this._physicalIndexForKey={};this._first VisibleIndexVal=null;this._lastVisibleIndexVal=null;this._physicalCount=this._ph ysicalCount||0;this._physicalItems=this._physicalItems||[];this._physicalSizes=t his._physicalSizes||[];this._physicalStart=0;this._resetScrollPosition(0);this._ removeFocusedItem();this._debounceTemplate(this._render)}else if(change.path===" items.splices"){this._adjustVirtualIndex(change.value.indexSplices);this._virtua lCount=this.items?this.items.length:0;this._debounceTemplate(this._render)}else{ this._forwardItemPath(change.path.split(".").slice(1).join("."),change.value)}}, _adjustVirtualIndex:function(splices){splices.forEach(function(splice){splice.re moved.forEach(this._removeItem,this);if(splice.index<this._virtualStart){var del ta=Math.max(splice.addedCount-splice.removed.length,splice.index-this._virtualSt art);this._virtualStart=this._virtualStart+delta;if(this._focusedIndex>=0){this. _focusedIndex=this._focusedIndex+delta}}},this)},_removeItem:function(item){this .$.selector.deselect(item);if(this._focusedItem&&this._focusedItem._templateInst ance[this.as]===item){this._removeFocusedItem()}},_iterateItems:function(fn,item Set){var pidx,vidx,rtn,i;if(arguments.length===2&&itemSet){for(i=0;i<itemSet.len gth;i++){pidx=itemSet[i];vidx=this._computeVidx(pidx);if((rtn=fn.call(this,pidx, vidx))!=null){return rtn}}}else{pidx=this._physicalStart;vidx=this._virtualStart ;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._physicalStart)}retur n this._virtualStart+(this._physicalCount-this._physicalStart)+pidx},_assignMode ls:function(itemSet){this._iterateItems(function(pidx,vidx){var el=this._physica lItems[pidx];var inst=el._templateInstance;var item=this.items&&this.items[vidx] ;if(item!=null){inst[this.as]=item;inst.__key__=this._collection.getKey(item);in st[this.selectedAs]=this.$.selector.isSelected(item);inst[this.indexAs]=vidx;ins t.tabIndex=this._focusedIndex===vidx?0:-1;this._physicalIndexForKey[inst.__key__ ]=pidx;el.removeAttribute("hidden")}else{inst.__key__=null;el.setAttribute("hidd en","")}},itemSet)},_updateMetrics:function(itemSet){Polymer.dom.flush();var new PhysicalSize=0;var oldPhysicalSize=0;var prevAvgCount=this._physicalAverageCount ;var prevPhysicalAvg=this._physicalAverage;this._iterateItems(function(pidx,vidx ){oldPhysicalSize+=this._physicalSizes[pidx]||0;this._physicalSizes[pidx]=this._ physicalItems[pidx].offsetHeight;newPhysicalSize+=this._physicalSizes[pidx];this ._physicalAverageCount+=this._physicalSizes[pidx]?1:0},itemSet);if(this.grid){th is._updateGridMetrics();this._physicalSize=Math.ceil(this._physicalCount/this._i temsPerRow)*this._rowHeight}else{this._physicalSize=this._physicalSize+newPhysic alSize-oldPhysicalSize}if(this._physicalAverageCount!==prevAvgCount){this._physi calAverage=Math.round((prevPhysicalAvg*prevAvgCount+newPhysicalSize)/this._physi calAverageCount)}},_updateGridMetrics:function(){this._itemWidth=this._physicalC ount>0?this._physicalItems[0].getBoundingClientRect().width:200;this._rowHeight= this._physicalCount>0?this._physicalItems[0].offsetHeight:200;this._itemsPerRow= this._itemWidth?Math.floor(this._viewportWidth/this._itemWidth):this._itemsPerRo w},_positionItems:function(){this._adjustScrollPosition();var y=this._physicalTo p;if(this.grid){var totalItemWidth=this._itemsPerRow*this._itemWidth;var rowOffs et=(this._viewportWidth-totalItemWidth)/2;this._iterateItems(function(pidx,vidx) {var modulus=vidx%this._itemsPerRow;var x=Math.floor(modulus*this._itemWidth+row Offset);this.translate3d(x+"px",y+"px",0,this._physicalItems[pidx]);if(this._sho uldRenderNextRow(vidx)){y+=this._rowHeight}})}else{this._iterateItems(function(p idx,vidx){this.translate3d(0,y+"px",0,this._physicalItems[pidx]);y+=this._physic alSizes[pidx]})}},_getPhysicalSizeIncrement:function(pidx){if(!this.grid){return this._physicalSizes[pidx]}if(this._computeVidx(pidx)%this._itemsPerRow!==this._ itemsPerRow-1){return 0}return this._rowHeight},_shouldRenderNextRow:function(vi dx){return vidx%this._itemsPerRow===this._itemsPerRow-1},_adjustScrollPosition:f unction(){var deltaHeight=this._virtualStart===0?this._physicalTop:Math.min(this ._scrollPosition+this._physicalTop,0);if(deltaHeight){this._physicalTop=this._ph ysicalTop-deltaHeight;if(!IOS_TOUCH_SCROLLING&&this._physicalTop!==0){this._rese tScrollPosition(this._scrollTop-deltaHeight)}}},_resetScrollPosition:function(po s){if(this.scrollTarget){this._scrollTop=pos;this._scrollPosition=this._scrollTo p}},_updateScrollerSize:function(forceUpdate){if(this.grid){this._estScrollHeigh t=this._virtualRowCount*this._rowHeight}else{this._estScrollHeight=this._physica lBottom+Math.max(this._virtualCount-this._physicalCount-this._virtualStart,0)*th is._physicalAverage}forceUpdate=forceUpdate||this._scrollHeight===0;forceUpdate= forceUpdate||this._scrollPosition>=this._estScrollHeight-this._physicalSize;forc eUpdate=forceUpdate||this.grid&&this.$.items.style.height<this._estScrollHeight; if(forceUpdate||Math.abs(this._estScrollHeight-this._scrollHeight)>=this._optPhy sicalSize){this.$.items.style.height=this._estScrollHeight+"px";this._scrollHeig ht=this._estScrollHeight}},scrollToItem:function(item){return this.scrollToIndex (this.items.indexOf(item))},scrollToIndex:function(idx){if(typeof idx!=="number" ||idx<0||idx>this.items.length-1){return}Polymer.dom.flush();if(this._physicalCo unt===0){return}idx=Math.min(Math.max(idx,0),this._virtualCount-1);if(!this._isI ndexRendered(idx)||idx>=this._maxVirtualStart){this._virtualStart=this.grid?idx- this._itemsPerRow*2:idx-1}this._manageFocus();this._assignModels();this._updateM etrics();this._physicalTop=Math.floor(this._virtualStart/this._itemsPerRow)*this ._physicalAverage;var currentTopItem=this._physicalStart;var currentVirtualItem= this._virtualStart;var targetOffsetTop=0;var hiddenContentSize=this._hiddenConte ntSize;while(currentVirtualItem<idx&&targetOffsetTop<=hiddenContentSize){targetO ffsetTop=targetOffsetTop+this._getPhysicalSizeIncrement(currentTopItem);currentT opItem=(currentTopItem+1)%this._physicalCount;currentVirtualItem++}this._updateS crollerSize(true);this._positionItems();this._resetScrollPosition(this._physical Top+this._scrollerPaddingTop+targetOffsetTop);this._increasePoolIfNeeded();this. _firstVisibleIndexVal=null;this._lastVisibleIndexVal=null},_resetAverage:functio n(){this._physicalAverage=0;this._physicalAverageCount=0},_resizeHandler:functio n(){if(IOS&&Math.abs(this._viewportHeight-this._scrollTargetHeight)<100){return} Polymer.dom.addDebouncer(this.debounce("_debounceTemplate",function(){this.updat eViewportBoundaries();this._render();if(this._isVisible){this.toggleScrollListen er(true);if(this._physicalCount>0){this._resetAverage();this.scrollToIndex(this. firstVisibleIndex)}}else{this.toggleScrollListener(false)}}.bind(this),1))},_get ModelFromItem:function(item){var key=this._collection.getKey(item);var pidx=this ._physicalIndexForKey[key];if(pidx!=null){return this._physicalItems[pidx]._temp lateInstance}return null},_getNormalizedItem:function(item){if(this._collection. getKey(item)===undefined){if(typeof item==="number"){item=this.items[item];if(!i tem){throw new RangeError("<item> not found")}return item}throw new TypeError("< item> should be a valid item")}return item},selectItem:function(item){item=this. _getNormalizedItem(item);var model=this._getModelFromItem(item);if(!this.multiSe lection&&this.selectedItem){this.deselectItem(this.selectedItem)}if(model){model [this.selectedAs]=true}this.$.selector.select(item);this.updateSizeForItem(item) },deselectItem:function(item){item=this._getNormalizedItem(item);var model=this. _getModelFromItem(item);if(model){model[this.selectedAs]=false}this.$.selector.d eselect(item);this.updateSizeForItem(item)},toggleSelectionForItem:function(item ){item=this._getNormalizedItem(item);if(this.$.selector.isSelected(item)){this.d eselectItem(item)}else{this.selectItem(item)}},clearSelection:function(){functio n unselect(item){var model=this._getModelFromItem(item);if(model){model[this.sel ectedAs]=false}}if(Array.isArray(this.selectedItems)){this.selectedItems.forEach (unselect,this)}else if(this.selectedItem){unselect.call(this,this.selectedItem) }this.$.selector.clearSelection()},_selectionEnabledChanged:function(selectionEn abled){var handler=selectionEnabled?this.listen:this.unlisten;handler.call(this, this,"tap","_selectionHandler")},_selectionHandler:function(e){var model=this.mo delForElement(e.target);if(!model){return}var modelTabIndex,activeElTabIndex;var target=Polymer.dom(e).path[0];var activeEl=Polymer.dom(this.domHost?this.domHos t.root:document).activeElement;var physicalItem=this._physicalItems[this._getPhy sicalIndex(model[this.indexAs])];if(target.localName==="input"||target.localName ==="button"||target.localName==="select"){return}modelTabIndex=model.tabIndex;mo del.tabIndex=SECRET_TABINDEX;activeElTabIndex=activeEl?activeEl.tabIndex:-1;mode l.tabIndex=modelTabIndex;if(activeEl&&physicalItem!==activeEl&&physicalItem.cont ains(activeEl)&&activeElTabIndex!==SECRET_TABINDEX){return}this.toggleSelectionF orItem(model[this.as])},_multiSelectionChanged:function(multiSelection){this.cle arSelection();this.$.selector.multi=multiSelection},updateSizeForItem:function(i tem){item=this._getNormalizedItem(item);var key=this._collection.getKey(item);va r 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._isIndexRendered(fidx)){this._restoreF ocusedItem()}else{this._createFocusBackfillItem()}}else if(this._virtualCount>0& &this._physicalCount>0){this._focusedIndex=this._virtualStart;this._focusedItem= this._physicalItems[this._physicalStart]}},_isIndexRendered:function(idx){return idx>=this._virtualStart&&idx<=this._virtualEnd},_isIndexVisible:function(idx){r eturn idx>=this.firstVisibleIndex&&idx<=this.lastVisibleIndex},_getPhysicalIndex :function(idx){return this._physicalIndexForKey[this._collection.getKey(this._ge tNormalizedItem(idx))]},_focusPhysicalItem:function(idx){if(idx<0||idx>=this._vi rtualCount){return}this._restoreFocusedItem();if(!this._isIndexRendered(idx)){th is.scrollToIndex(idx)}var physicalItem=this._physicalItems[this._getPhysicalInde x(idx)];var model=physicalItem._templateInstance;var focusable;model.tabIndex=SE CRET_TABINDEX;if(physicalItem.tabIndex===SECRET_TABINDEX){focusable=physicalItem }if(!focusable){focusable=Polymer.dom(physicalItem).querySelector('[tabindex="'+ SECRET_TABINDEX+'"]')}model.tabIndex=0;this._focusedIndex=idx;focusable&&focusab le.focus()},_removeFocusedItem:function(){if(this._offscreenFocusedItem){Polymer .dom(this).removeChild(this._offscreenFocusedItem)}this._offscreenFocusedItem=nu ll;this._focusBackfillItem=null;this._focusedItem=null;this._focusedIndex=-1},_c reateFocusBackfillItem:function(){var pidx,fidx=this._focusedIndex;if(this._offs creenFocusedItem||fidx<0){return}if(!this._focusBackfillItem){var stampedTemplat e=this.stamp(null);this._focusBackfillItem=stampedTemplate.root.querySelector("* ");Polymer.dom(this).appendChild(stampedTemplate.root)}pidx=this._getPhysicalInd ex(fidx);if(pidx!=null){this._offscreenFocusedItem=this._physicalItems[pidx];thi s._physicalItems[pidx]=this._focusBackfillItem;this.translate3d(0,HIDDEN_Y,0,thi s._offscreenFocusedItem)}},_restoreFocusedItem:function(){var pidx,fidx=this._fo cusedIndex;if(!this._offscreenFocusedItem||this._focusedIndex<0){return}this._as signModels();pidx=this._getPhysicalIndex(fidx);if(pidx!=null){this._focusBackfil lItem=this._physicalItems[pidx];this._physicalItems[pidx]=this._offscreenFocused Item;this._offscreenFocusedItem=null;this.translate3d(0,HIDDEN_Y,0,this._focusBa ckfillItem)}},_didFocus:function(e){var targetModel=this.modelForElement(e.targe t);var focusedModel=this._focusedItem?this._focusedItem._templateInstance:null;v ar hasOffscreenFocusedItem=this._offscreenFocusedItem!==null;var fidx=this._focu sedIndex;if(!targetModel||!focusedModel){return}if(focusedModel===targetModel){i f(!this._isIndexVisible(fidx)){this.scrollToIndex(fidx)}}else{this._restoreFocus edItem();focusedModel.tabIndex=-1;targetModel.tabIndex=0;fidx=targetModel[this.i ndexAs];this._focusedIndex=fidx;this._focusedItem=this._physicalItems[this._getP hysicalIndex(fidx)];if(hasOffscreenFocusedItem&&!this._offscreenFocusedItem){thi s._update()}}},_didMoveUp:function(){this._focusPhysicalItem(this._focusedIndex- 1)},_didMoveDown:function(e){e.detail.keyboardEvent.preventDefault();this._focus PhysicalItem(this._focusedIndex+1)},_didEnter:function(e){this._focusPhysicalIte m(this._focusedIndex);this._selectionHandler(e.detail.keyboardEvent)}})})();Poly mer({is:"iron-scroll-threshold",properties:{upperThreshold:{type:Number,value:10 0},lowerThreshold:{type:Number,value:100},upperTriggered:{type:Boolean,value:fal se,notify:true,readOnly:true},lowerTriggered:{type:Boolean,value:false,notify:tr ue,readOnly:true},horizontal:{type:Boolean,value:false}},behaviors:[Polymer.Iron ScrollTargetBehavior],observers:["_setOverflow(scrollTarget)","_initCheck(horizo ntal, isAttached)"],get _defaultScrollTarget(){return this},_setOverflow:functio n(scrollTarget){this.style.overflow=scrollTarget===this?"auto":""},_scrollHandle r:function(){var THROTTLE_THRESHOLD=200;if(!this.isDebouncerActive("_checkThesho ld")){this.debounce("_checkTheshold",function(){this.checkScrollThesholds()},THR OTTLE_THRESHOLD)}},_initCheck:function(horizontal,isAttached){if(isAttached){thi s.debounce("_init",function(){this.clearTriggers();this.checkScrollThesholds()}) }},checkScrollThesholds:function(){if(!this.scrollTarget||this.lowerTriggered&&t his.upperTriggered){return}var upperScrollValue=this.horizontal?this._scrollLeft :this._scrollTop;var lowerScrollValue=this.horizontal?this.scrollTarget.scrollWi dth-this._scrollTargetWidth-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._setLowerTr iggered(true);this.fire("lower-threshold")}},clearTriggers:function(){this._setU pperTriggered(false);this._setLowerTriggered(false)}}); 45 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,observer:"hasDrawerCha nged_",reflectToAttribute:true},showSyncNotice:Boolean,isGroupedMode:{type:Boole an,reflectToAttribute:true},groupedRange:{type:Number,value:0,reflectToAttribute :true,notify:true},queryStartTime:String,queryEndTime:String,showMenuPromo:Boole an},get searchField(){return this.$["main-toolbar"].getSearchField()},showSearch Field:function(){this.searchField.showAndFocus()},changeToolbarView_:function(){ this.itemsSelected_=this.count>0},searchTermChanged_:function(){if(this.searchFi eld.getValue()!=this.searchTerm){this.searchField.showAndFocus();this.searchFiel d.setValue(this.searchTerm)}},onSearchChanged_:function(event){this.searchTerm=e vent.detail},onInfoButtonTap_:function(){var dropdown=this.$.syncNotice.get();dr opdown.positionTarget=this.$$("#info-button-icon");if(dropdown.style.display=="n one")dropdown.open()},onClearSelectionTap_:function(){this.fire("unselect-all")} ,onDeleteTap_:function(){this.fire("delete-selected")},deletingAllowed_:function (){return loadTimeData.getBoolean("allowDeletingHistory")},numberOfItemsSelected _:function(count){return count>0?loadTimeData.getStringF("itemsSelected",count): ""},getHistoryInterval_:function(queryStartTime,queryEndTime){return loadTimeDat a.getStringF("historyInterval",queryStartTime,queryEndTime)},hasDrawerChanged_:f unction(){this.updateStyles()}});(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_HEIG HT=1;var SECRET_TABINDEX=-100;Polymer({is:"iron-list",properties:{items:{type:Ar ray},maxPhysicalCount:{type:Number,value:500},as:{type:String,value:"item"},inde xAs:{type:String,value:"index"},selectedAs:{type:String,value:"selected"},grid:{ type:Boolean,value:false,reflectToAttribute:true},selectionEnabled:{type:Boolean ,value:false},selectedItem:{type:Object,notify:true},selectedItems:{type:Object, notify:true},multiSelection:{type:Boolean,value:false}},observers:["_itemsChange d(items.*)","_selectionEnabledChanged(selectionEnabled)","_multiSelectionChanged (multiSelection)","_setOverflow(scrollTarget)"],behaviors:[Polymer.Templatizer,P olymer.IronResizableBehavior,Polymer.IronA11yKeysBehavior,Polymer.IronScrollTarg etBehavior],keyBindings:{up:"_didMoveUp",down:"_didMoveDown",enter:"_didEnter"}, _ratio:.5,_scrollerPaddingTop:0,_scrollPosition:0,_physicalSize:0,_physicalAvera ge:0,_physicalAverageCount:0,_physicalTop:0,_virtualCount:0,_physicalIndexForKey :null,_estScrollHeight:0,_scrollHeight:0,_viewportHeight:0,_viewportWidth:0,_phy sicalItems:null,_physicalSizes:null,_firstVisibleIndexVal:null,_lastVisibleIndex Val:null,_collection:null,_maxPages:2,_focusedItem:null,_focusedIndex:-1,_offscr eenFocusedItem:null,_focusBackfillItem:null,_itemsPerRow:1,_itemWidth:0,_rowHeig ht:0,_templateCost:0,get _physicalBottom(){return this._physicalTop+this._physic alSize},get _scrollBottom(){return this._scrollPosition+this._viewportHeight},ge t _virtualEnd(){return this._virtualStart+this._physicalCount-1},get _hiddenCont entSize(){var size=this.grid?this._physicalRows*this._rowHeight:this._physicalSi ze;return size-this._viewportHeight},get _maxScrollTop(){return this._estScrollH eight-this._viewportHeight+this._scrollerPaddingTop},_minVirtualStart:0,get _max VirtualStart(){return Math.max(0,this._virtualCount-this._physicalCount)},_virtu alStartVal:0,set _virtualStart(val){this._virtualStartVal=Math.min(this._maxVirt ualStart,Math.max(this._minVirtualStart,val))},get _virtualStart(){return this._ virtualStartVal||0},_physicalStartVal:0,set _physicalStart(val){this._physicalSt artVal=val%this._physicalCount;if(this._physicalStartVal<0){this._physicalStartV al=this._physicalCount+this._physicalStartVal}this._physicalEnd=(this._physicalS tart+this._physicalCount-1)%this._physicalCount},get _physicalStart(){return thi s._physicalStartVal||0},_physicalCountVal:0,set _physicalCount(val){this._physic alCountVal=val;this._physicalEnd=(this._physicalStart+this._physicalCount-1)%thi s._physicalCount},get _physicalCount(){return this._physicalCountVal},_physicalE nd:0,get _optPhysicalSize(){if(this.grid){return this._estRowsInView*this._rowHe ight*this._maxPages}return this._viewportHeight*this._maxPages},get _isVisible() {return Boolean(this.offsetWidth||this.offsetHeight)},get firstVisibleIndex(){if (this._firstVisibleIndexVal===null){var physicalOffset=Math.floor(this._physical Top+this._scrollerPaddingTop);this._firstVisibleIndexVal=this._iterateItems(func tion(pidx,vidx){physicalOffset+=this._getPhysicalSizeIncrement(pidx);if(physical Offset>this._scrollPosition){return this.grid?vidx-vidx%this._itemsPerRow:vidx}i f(this.grid&&this._virtualCount-1===vidx){return vidx-vidx%this._itemsPerRow}})| |0}return this._firstVisibleIndexVal},get lastVisibleIndex(){if(this._lastVisibl eIndexVal===null){if(this.grid){var lastIndex=this.firstVisibleIndex+this._estRo wsInView*this._itemsPerRow-1;this._lastVisibleIndexVal=Math.min(this._virtualCou nt,lastIndex)}else{var physicalOffset=this._physicalTop;this._iterateItems(funct ion(pidx,vidx){if(physicalOffset<this._scrollBottom){this._lastVisibleIndexVal=v idx}else{return true}physicalOffset+=this._getPhysicalSizeIncrement(pidx)})}}ret urn this._lastVisibleIndexVal},get _defaultScrollTarget(){return this},get _virt ualRowCount(){return Math.ceil(this._virtualCount/this._itemsPerRow)},get _estRo wsInView(){return Math.ceil(this._viewportHeight/this._rowHeight)},get _physical Rows(){return Math.ceil(this._physicalCount/this._itemsPerRow)},ready:function() {this.addEventListener("focus",this._didFocus.bind(this),true)},attached:functio n(){if(this._physicalCount===0){this._debounceTemplate(this._render)}this.listen (this,"iron-resize","_resizeHandler")},detached:function(){this.unlisten(this,"i ron-resize","_resizeHandler")},_setOverflow:function(scrollTarget){this.style.we bkitOverflowScrolling=scrollTarget===this?"touch":"";this.style.overflow=scrollT arget===this?"auto":""},updateViewportBoundaries:function(){this._scrollerPaddin gTop=this.scrollTarget===this?0:parseInt(window.getComputedStyle(this)["padding- top"],10);this._viewportWidth=this.$.items.offsetWidth;this._viewportHeight=this ._scrollTargetHeight;this.grid&&this._updateGridMetrics()},_scrollHandler:functi on(){var scrollTop=Math.max(0,Math.min(this._maxScrollTop,this._scrollTop));var delta=scrollTop-this._scrollPosition;var isScrollingDown=delta>=0;this._scrollPo sition=scrollTop;this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null; if(Math.abs(delta)>this._physicalSize){var idxAdjustment=Math.round(delta/this._ physicalAverage)*this._itemsPerRow;this._physicalTop=this._physicalTop+delta;thi s._virtualStart=this._virtualStart+idxAdjustment;this._physicalStart=this._physi calStart+idxAdjustment;this._update()}else{var reusables=this._getReusables(isSc rollingDown);if(isScrollingDown){this._physicalTop=reusables.physicalTop;this._v irtualStart=this._virtualStart+reusables.indexes.length;this._physicalStart=this ._physicalStart+reusables.indexes.length}else{this._virtualStart=this._virtualSt art-reusables.indexes.length;this._physicalStart=this._physicalStart-reusables.i ndexes.length}if(reusables.indexes.length===0){this._increasePoolIfNeeded()}else {this._update(reusables.indexes,isScrollingDown?null:reusables.indexes)}}},_getR eusables:function(fromTop){var ith,lastIth,offsetContent,physicalItemHeight;var idxs=[];var protectedOffsetContent=this._hiddenContentSize*this._ratio;var virtu alStart=this._virtualStart;var virtualEnd=this._virtualEnd;var physicalCount=thi s._physicalCount;var physicalTop=this._physicalTop;var scrollTop=this._scrollTop ;var scrollBottom=this._scrollBottom;if(fromTop){ith=this._physicalStart;lastIth =this._physicalEnd;offsetContent=scrollTop-physicalTop}else{ith=this._physicalEn d;lastIth=this._physicalStart;offsetContent=this._physicalBottom-scrollBottom}wh ile(true){physicalItemHeight=this._getPhysicalSizeIncrement(ith);offsetContent=o ffsetContent-physicalItemHeight;if(idxs.length>=physicalCount||offsetContent<=pr otectedOffsetContent){break}if(fromTop){if(virtualEnd+idxs.length+1>=this._virtu alCount){break}if(physicalTop+physicalItemHeight>=scrollTop){break}idxs.push(ith );physicalTop=physicalTop+physicalItemHeight;ith=(ith+1)%physicalCount}else{if(v irtualStart-idxs.length<=0){break}if(physicalTop+this._physicalSize-physicalItem Height<=scrollBottom){break}idxs.push(ith);physicalTop=physicalTop-physicalItemH eight;ith=ith===0?physicalCount-1:ith-1}}return{indexes:idxs,physicalTop:physica lTop}},_update:function(itemSet,movingUp){if(itemSet&&itemSet.length===0){return }this._manageFocus();this._assignModels(itemSet);this._updateMetrics(itemSet);if (movingUp){while(movingUp.length){var idx=movingUp.pop();this._physicalTop-=this ._getPhysicalSizeIncrement(idx)}}this._positionItems();this._updateScrollerSize( );this._increasePoolIfNeeded()},_createPool:function(size){var physicalItems=new Array(size);this._ensureTemplatized();for(var i=0;i<size;i++){var inst=this.sta mp(null);physicalItems[i]=inst.root.querySelector("*");Polymer.dom(this).appendC hild(inst.root)}return physicalItems},_increasePoolIfNeeded:function(){if(this._ viewportHeight===0){return false}var self=this;var isClientFull=this._physicalBo ttom>=this._scrollBottom&&this._physicalTop<=this._scrollPosition;if(this._physi calSize>=this._optPhysicalSize&&isClientFull){return false}var maxPoolSize=Math. round(this._physicalCount*.5);if(!isClientFull){this._debounceTemplate(this._inc reasePool.bind(this,maxPoolSize));return true}this._yield(function(){self._incre asePool(Math.min(maxPoolSize,Math.max(1,Math.round(50/self._templateCost))))});r eturn true},_yield:function(cb){var g=window;var handle=g.requestIdleCallback?g. requestIdleCallback(cb):g.setTimeout(cb,16);Polymer.dom.addDebouncer({complete:f unction(){g.cancelIdleCallback?g.cancelIdleCallback(handle):g.clearTimeout(handl e);cb()}})},_increasePool:function(missingItems){var nextPhysicalCount=Math.min( this._physicalCount+missingItems,this._virtualCount-this._virtualStart,Math.max( this.maxPhysicalCount,DEFAULT_PHYSICAL_COUNT));var prevPhysicalCount=this._physi calCount;var delta=nextPhysicalCount-prevPhysicalCount;var ts=window.performance .now();if(delta<=0){return}[].push.apply(this._physicalItems,this._createPool(de lta));[].push.apply(this._physicalSizes,new Array(delta));this._physicalCount=pr evPhysicalCount+delta;if(this._physicalStart>this._physicalEnd&&this._isIndexRen dered(this._focusedIndex)&&this._getPhysicalIndex(this._focusedIndex)<this._phys icalEnd){this._physicalStart=this._physicalStart+delta}this._update();this._temp lateCost=(window.performance.now()-ts)/delta},_render:function(){if(this.isAttac hed&&this._isVisible){if(this._physicalCount===0){this.updateViewportBoundaries( );this._increasePool(DEFAULT_PHYSICAL_COUNT)}else{var reusables=this._getReusabl es(true);this._physicalTop=reusables.physicalTop;this._virtualStart=this._virtua lStart+reusables.indexes.length;this._physicalStart=this._physicalStart+reusable s.indexes.length;this._update(reusables.indexes);this._update()}}},_ensureTempla tized:function(){if(!this.ctor){var props={};props.__key__=true;props[this.as]=t rue;props[this.indexAs]=true;props[this.selectedAs]=true;props.tabIndex=true;thi s._instanceProps=props;this._userTemplate=Polymer.dom(this).querySelector("templ ate");if(this._userTemplate){this.templatize(this._userTemplate)}else{console.wa rn("iron-list requires a template to be provided in light-dom")}}},_getStampedCh ildren:function(){return this._physicalItems},_forwardInstancePath:function(inst ,path,value){if(path.indexOf(this.as+".")===0){this.notifyPath("items."+inst.__k ey__+"."+path.slice(this.as.length+1),value)}},_forwardParentProp:function(prop, value){if(this._physicalItems){this._physicalItems.forEach(function(item){item._ templateInstance[prop]=value},this)}},_forwardParentPath:function(path,value){if (this._physicalItems){this._physicalItems.forEach(function(item){item._templateI nstance.notifyPath(path,value,true)},this)}},_forwardItemPath:function(path,valu e){if(!this._physicalIndexForKey){return}var dot=path.indexOf(".");var key=path. substring(0,dot<0?path.length:dot);var idx=this._physicalIndexForKey[key];var of fscreenItem=this._offscreenFocusedItem;var el=offscreenItem&&offscreenItem._temp lateInstance.__key__===key?offscreenItem:this._physicalItems[idx];if(!el||el._te mplateInstance.__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.isArray(this.selectedItems)){for(var i=0;i<t his.selectedItems.length;i++){if(this.selectedItems[i]===currentItem){this.set(" selectedItems."+i,value);break}}}else if(this.selectedItem===currentItem){this.s et("selectedItem",value)}el._templateInstance[this.as]=value}},_itemsChanged:fun ction(change){if(change.path==="items"){this._virtualStart=0;this._physicalTop=0 ;this._virtualCount=this.items?this.items.length:0;this._collection=this.items?P olymer.Collection.get(this.items):null;this._physicalIndexForKey={};this._firstV isibleIndexVal=null;this._lastVisibleIndexVal=null;this._physicalCount=this._phy sicalCount||0;this._physicalItems=this._physicalItems||[];this._physicalSizes=th is._physicalSizes||[];this._physicalStart=0;this._resetScrollPosition(0);this._r emoveFocusedItem();this._debounceTemplate(this._render)}else if(change.path==="i tems.splices"){this._adjustVirtualIndex(change.value.indexSplices);this._virtual Count=this.items?this.items.length:0;this._debounceTemplate(this._render)}else{t his._forwardItemPath(change.path.split(".").slice(1).join("."),change.value)}},_ adjustVirtualIndex:function(splices){splices.forEach(function(splice){splice.rem oved.forEach(this._removeItem,this);if(splice.index<this._virtualStart){var delt a=Math.max(splice.addedCount-splice.removed.length,splice.index-this._virtualSta rt);this._virtualStart=this._virtualStart+delta;if(this._focusedIndex>=0){this._ focusedIndex=this._focusedIndex+delta}}},this)},_removeItem:function(item){this. $.selector.deselect(item);if(this._focusedItem&&this._focusedItem._templateInsta nce[this.as]===item){this._removeFocusedItem()}},_iterateItems:function(fn,itemS et){var pidx,vidx,rtn,i;if(arguments.length===2&&itemSet){for(i=0;i<itemSet.leng th;i++){pidx=itemSet[i];vidx=this._computeVidx(pidx);if((rtn=fn.call(this,pidx,v idx))!=null){return rtn}}}else{pidx=this._physicalStart;vidx=this._virtualStart; for(;pidx<this._physicalCount;pidx++,vidx++){if((rtn=fn.call(this,pidx,vidx))!=n ull){return rtn}}for(pidx=0;pidx<this._physicalStart;pidx++,vidx++){if((rtn=fn.c all(this,pidx,vidx))!=null){return rtn}}}},_computeVidx:function(pidx){if(pidx>= this._physicalStart){return this._virtualStart+(pidx-this._physicalStart)}return this._virtualStart+(this._physicalCount-this._physicalStart)+pidx},_assignModel s:function(itemSet){this._iterateItems(function(pidx,vidx){var el=this._physical Items[pidx];var inst=el._templateInstance;var item=this.items&&this.items[vidx]; if(item!=null){inst[this.as]=item;inst.__key__=this._collection.getKey(item);ins t[this.selectedAs]=this.$.selector.isSelected(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("hidde n","")}},itemSet)},_updateMetrics:function(itemSet){Polymer.dom.flush();var newP hysicalSize=0;var oldPhysicalSize=0;var prevAvgCount=this._physicalAverageCount; var prevPhysicalAvg=this._physicalAverage;this._iterateItems(function(pidx,vidx) {oldPhysicalSize+=this._physicalSizes[pidx]||0;this._physicalSizes[pidx]=this._p hysicalItems[pidx].offsetHeight;newPhysicalSize+=this._physicalSizes[pidx];this. _physicalAverageCount+=this._physicalSizes[pidx]?1:0},itemSet);if(this.grid){thi s._updateGridMetrics();this._physicalSize=Math.ceil(this._physicalCount/this._it emsPerRow)*this._rowHeight}else{this._physicalSize=this._physicalSize+newPhysica lSize-oldPhysicalSize}if(this._physicalAverageCount!==prevAvgCount){this._physic alAverage=Math.round((prevPhysicalAvg*prevAvgCount+newPhysicalSize)/this._physic alAverageCount)}},_updateGridMetrics:function(){this._itemWidth=this._physicalCo unt>0?this._physicalItems[0].getBoundingClientRect().width:200;this._rowHeight=t his._physicalCount>0?this._physicalItems[0].offsetHeight:200;this._itemsPerRow=t his._itemWidth?Math.floor(this._viewportWidth/this._itemWidth):this._itemsPerRow },_positionItems:function(){this._adjustScrollPosition();var y=this._physicalTop ;if(this.grid){var totalItemWidth=this._itemsPerRow*this._itemWidth;var rowOffse t=(this._viewportWidth-totalItemWidth)/2;this._iterateItems(function(pidx,vidx){ var modulus=vidx%this._itemsPerRow;var x=Math.floor(modulus*this._itemWidth+rowO ffset);this.translate3d(x+"px",y+"px",0,this._physicalItems[pidx]);if(this._shou ldRenderNextRow(vidx)){y+=this._rowHeight}})}else{this._iterateItems(function(pi dx,vidx){this.translate3d(0,y+"px",0,this._physicalItems[pidx]);y+=this._physica lSizes[pidx]})}},_getPhysicalSizeIncrement:function(pidx){if(!this.grid){return this._physicalSizes[pidx]}if(this._computeVidx(pidx)%this._itemsPerRow!==this._i temsPerRow-1){return 0}return this._rowHeight},_shouldRenderNextRow:function(vid x){return vidx%this._itemsPerRow===this._itemsPerRow-1},_adjustScrollPosition:fu nction(){var deltaHeight=this._virtualStart===0?this._physicalTop:Math.min(this. _scrollPosition+this._physicalTop,0);if(deltaHeight){this._physicalTop=this._phy sicalTop-deltaHeight;if(!IOS_TOUCH_SCROLLING&&this._physicalTop!==0){this._reset ScrollPosition(this._scrollTop-deltaHeight)}}},_resetScrollPosition:function(pos ){if(this.scrollTarget){this._scrollTop=pos;this._scrollPosition=this._scrollTop }},_updateScrollerSize:function(forceUpdate){if(this.grid){this._estScrollHeight =this._virtualRowCount*this._rowHeight}else{this._estScrollHeight=this._physical Bottom+Math.max(this._virtualCount-this._physicalCount-this._virtualStart,0)*thi s._physicalAverage}forceUpdate=forceUpdate||this._scrollHeight===0;forceUpdate=f orceUpdate||this._scrollPosition>=this._estScrollHeight-this._physicalSize;force Update=forceUpdate||this.grid&&this.$.items.style.height<this._estScrollHeight;i f(forceUpdate||Math.abs(this._estScrollHeight-this._scrollHeight)>=this._optPhys icalSize){this.$.items.style.height=this._estScrollHeight+"px";this._scrollHeigh t=this._estScrollHeight}},scrollToItem:function(item){return this.scrollToIndex( this.items.indexOf(item))},scrollToIndex:function(idx){if(typeof idx!=="number"| |idx<0||idx>this.items.length-1){return}Polymer.dom.flush();if(this._physicalCou nt===0){return}idx=Math.min(Math.max(idx,0),this._virtualCount-1);if(!this._isIn dexRendered(idx)||idx>=this._maxVirtualStart){this._virtualStart=this.grid?idx-t his._itemsPerRow*2:idx-1}this._manageFocus();this._assignModels();this._updateMe trics();this._physicalTop=Math.floor(this._virtualStart/this._itemsPerRow)*this. _physicalAverage;var currentTopItem=this._physicalStart;var currentVirtualItem=t his._virtualStart;var targetOffsetTop=0;var hiddenContentSize=this._hiddenConten tSize;while(currentVirtualItem<idx&&targetOffsetTop<=hiddenContentSize){targetOf fsetTop=targetOffsetTop+this._getPhysicalSizeIncrement(currentTopItem);currentTo pItem=(currentTopItem+1)%this._physicalCount;currentVirtualItem++}this._updateSc rollerSize(true);this._positionItems();this._resetScrollPosition(this._physicalT op+this._scrollerPaddingTop+targetOffsetTop);this._increasePoolIfNeeded();this._ firstVisibleIndexVal=null;this._lastVisibleIndexVal=null},_resetAverage:function (){this._physicalAverage=0;this._physicalAverageCount=0},_resizeHandler:function (){if(IOS&&Math.abs(this._viewportHeight-this._scrollTargetHeight)<100){return}P olymer.dom.addDebouncer(this.debounce("_debounceTemplate",function(){this.update ViewportBoundaries();this._render();if(this._isVisible){this.toggleScrollListene r(true);if(this._physicalCount>0){this._resetAverage();this.scrollToIndex(this.f irstVisibleIndex)}}else{this.toggleScrollListener(false)}}.bind(this),1))},_getM odelFromItem:function(item){var key=this._collection.getKey(item);var pidx=this. _physicalIndexForKey[key];if(pidx!=null){return this._physicalItems[pidx]._templ ateInstance}return null},_getNormalizedItem:function(item){if(this._collection.g etKey(item)===undefined){if(typeof item==="number"){item=this.items[item];if(!it em){throw new RangeError("<item> not found")}return item}throw new TypeError("<i tem> should be a valid item")}return item},selectItem:function(item){item=this._ getNormalizedItem(item);var model=this._getModelFromItem(item);if(!this.multiSel ection&&this.selectedItem){this.deselectItem(this.selectedItem)}if(model){model[ this.selectedAs]=true}this.$.selector.select(item);this.updateSizeForItem(item)} ,deselectItem:function(item){item=this._getNormalizedItem(item);var model=this._ getModelFromItem(item);if(model){model[this.selectedAs]=false}this.$.selector.de select(item);this.updateSizeForItem(item)},toggleSelectionForItem:function(item) {item=this._getNormalizedItem(item);if(this.$.selector.isSelected(item)){this.de selectItem(item)}else{this.selectItem(item)}},clearSelection:function(){function unselect(item){var model=this._getModelFromItem(item);if(model){model[this.sele ctedAs]=false}}if(Array.isArray(this.selectedItems)){this.selectedItems.forEach( unselect,this)}else if(this.selectedItem){unselect.call(this,this.selectedItem)} this.$.selector.clearSelection()},_selectionEnabledChanged:function(selectionEna bled){var handler=selectionEnabled?this.listen:this.unlisten;handler.call(this,t his,"tap","_selectionHandler")},_selectionHandler:function(e){var model=this.mod elForElement(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._getPhys icalIndex(model[this.indexAs])];if(target.localName==="input"||target.localName= =="button"||target.localName==="select"){return}modelTabIndex=model.tabIndex;mod el.tabIndex=SECRET_TABINDEX;activeElTabIndex=activeEl?activeEl.tabIndex:-1;model .tabIndex=modelTabIndex;if(activeEl&&physicalItem!==activeEl&&physicalItem.conta ins(activeEl)&&activeElTabIndex!==SECRET_TABINDEX){return}this.toggleSelectionFo rItem(model[this.as])},_multiSelectionChanged:function(multiSelection){this.clea rSelection();this.$.selector.multi=multiSelection},updateSizeForItem:function(it em){item=this._getNormalizedItem(item);var key=this._collection.getKey(item);var pidx=this._physicalIndexForKey[key];if(pidx!=null){this._updateMetrics([pidx]); this._positionItems()}},_manageFocus:function(){var fidx=this._focusedIndex;if(f idx>=0&&fidx<this._virtualCount){if(this._isIndexRendered(fidx)){this._restoreFo cusedItem()}else{this._createFocusBackfillItem()}}else if(this._virtualCount>0&& this._physicalCount>0){this._focusedIndex=this._virtualStart;this._focusedItem=t his._physicalItems[this._physicalStart]}},_isIndexRendered:function(idx){return idx>=this._virtualStart&&idx<=this._virtualEnd},_isIndexVisible:function(idx){re turn idx>=this.firstVisibleIndex&&idx<=this.lastVisibleIndex},_getPhysicalIndex: function(idx){return this._physicalIndexForKey[this._collection.getKey(this._get NormalizedItem(idx))]},_focusPhysicalItem:function(idx){if(idx<0||idx>=this._vir tualCount){return}this._restoreFocusedItem();if(!this._isIndexRendered(idx)){thi s.scrollToIndex(idx)}var physicalItem=this._physicalItems[this._getPhysicalIndex (idx)];var model=physicalItem._templateInstance;var focusable;model.tabIndex=SEC RET_TABINDEX;if(physicalItem.tabIndex===SECRET_TABINDEX){focusable=physicalItem} if(!focusable){focusable=Polymer.dom(physicalItem).querySelector('[tabindex="'+S ECRET_TABINDEX+'"]')}model.tabIndex=0;this._focusedIndex=idx;focusable&&focusabl e.focus()},_removeFocusedItem:function(){if(this._offscreenFocusedItem){Polymer. dom(this).removeChild(this._offscreenFocusedItem)}this._offscreenFocusedItem=nul l;this._focusBackfillItem=null;this._focusedItem=null;this._focusedIndex=-1},_cr eateFocusBackfillItem:function(){var pidx,fidx=this._focusedIndex;if(this._offsc reenFocusedItem||fidx<0){return}if(!this._focusBackfillItem){var stampedTemplate =this.stamp(null);this._focusBackfillItem=stampedTemplate.root.querySelector("*" );Polymer.dom(this).appendChild(stampedTemplate.root)}pidx=this._getPhysicalInde x(fidx);if(pidx!=null){this._offscreenFocusedItem=this._physicalItems[pidx];this ._physicalItems[pidx]=this._focusBackfillItem;this.translate3d(0,HIDDEN_Y,0,this ._offscreenFocusedItem)}},_restoreFocusedItem:function(){var pidx,fidx=this._foc usedIndex;if(!this._offscreenFocusedItem||this._focusedIndex<0){return}this._ass ignModels();pidx=this._getPhysicalIndex(fidx);if(pidx!=null){this._focusBackfill Item=this._physicalItems[pidx];this._physicalItems[pidx]=this._offscreenFocusedI tem;this._offscreenFocusedItem=null;this.translate3d(0,HIDDEN_Y,0,this._focusBac kfillItem)}},_didFocus:function(e){var targetModel=this.modelForElement(e.target );var focusedModel=this._focusedItem?this._focusedItem._templateInstance:null;va r hasOffscreenFocusedItem=this._offscreenFocusedItem!==null;var fidx=this._focus edIndex;if(!targetModel||!focusedModel){return}if(focusedModel===targetModel){if (!this._isIndexVisible(fidx)){this.scrollToIndex(fidx)}}else{this._restoreFocuse dItem();focusedModel.tabIndex=-1;targetModel.tabIndex=0;fidx=targetModel[this.in dexAs];this._focusedIndex=fidx;this._focusedItem=this._physicalItems[this._getPh ysicalIndex(fidx)];if(hasOffscreenFocusedItem&&!this._offscreenFocusedItem){this ._update()}}},_didMoveUp:function(){this._focusPhysicalItem(this._focusedIndex-1 )},_didMoveDown:function(e){e.detail.keyboardEvent.preventDefault();this._focusP hysicalItem(this._focusedIndex+1)},_didEnter:function(e){this._focusPhysicalItem (this._focusedIndex);this._selectionHandler(e.detail.keyboardEvent)}})})();Polym er({is:"iron-scroll-threshold",properties:{upperThreshold:{type:Number,value:100 },lowerThreshold:{type:Number,value:100},upperTriggered:{type:Boolean,value:fals e,notify:true,readOnly:true},lowerTriggered:{type:Boolean,value:false,notify:tru e,readOnly:true},horizontal:{type:Boolean,value:false}},behaviors:[Polymer.IronS crollTargetBehavior],observers:["_setOverflow(scrollTarget)","_initCheck(horizon tal, isAttached)"],get _defaultScrollTarget(){return this},_setOverflow:function (scrollTarget){this.style.overflow=scrollTarget===this?"auto":""},_scrollHandler :function(){var THROTTLE_THRESHOLD=200;if(!this.isDebouncerActive("_checkTheshol d")){this.debounce("_checkTheshold",function(){this.checkScrollThesholds()},THRO TTLE_THRESHOLD)}},_initCheck:function(horizontal,isAttached){if(isAttached){this .debounce("_init",function(){this.clearTriggers();this.checkScrollThesholds()})} },checkScrollThesholds:function(){if(!this.scrollTarget||this.lowerTriggered&&th is.upperTriggered){return}var upperScrollValue=this.horizontal?this._scrollLeft: this._scrollTop;var lowerScrollValue=this.horizontal?this.scrollTarget.scrollWid th-this._scrollTargetWidth-this._scrollLeft:this.scrollTarget.scrollHeight-this. _scrollTargetHeight-this._scrollTop;if(upperScrollValue<=this.upperThreshold&&!t his.upperTriggered){this._setUpperTriggered(true);this.fire("upper-threshold")}i f(lowerScrollValue<=this.lowerThreshold&&!this.lowerTriggered){this._setLowerTri ggered(true);this.fire("lower-threshold")}},clearTriggers:function(){this._setUp perTriggered(false);this._setLowerTriggered(false)}});
46 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 46 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
47 // Use of this source code is governed by a BSD-style license that can be 47 // Use of this source code is governed by a BSD-style license that can be
48 // found in the LICENSE file. 48 // found in the LICENSE file.
49 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)}; 49 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)};
50 // Copyright 2014 The Chromium Authors. All rights reserved. 50 // Copyright 2014 The Chromium Authors. All rights reserved.
51 // Use of this source code is governed by a BSD-style license that can be 51 // Use of this source code is governed by a BSD-style license that can be
52 // found in the LICENSE file. 52 // found in the LICENSE file.
53 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(e.altKey||e.ctrlKey||e.metaKey| |e.shiftKey)return;var index=-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 elementToFo cus=elements[index];if(elementToFocus){this.getEquivalentElement(elementToFocus) .focus();e.preventDefault()}}};return{FocusRow:FocusRow}}); 53 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(e.altKey||e.ctrlKey||e.metaKey| |e.shiftKey)return;var index=-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 elementToFo cus=elements[index];if(elementToFocus){this.getEquivalentElement(elementToFocus) .focus();e.preventDefault()}}};return{FocusRow:FocusRow}});
54 // Copyright 2016 The Chromium Authors. All rights reserved. 54 // Copyright 2016 The Chromium Authors. All rights reserved.
55 // Use of this source code is governed by a BSD-style license that can be 55 // Use of this source code is governed by a BSD-style license that can be
(...skipping 23 matching lines...) Expand all
79 // Use of this source code is governed by a BSD-style license that can be 79 // Use of this source code is governed by a BSD-style license that can be
80 // found in the LICENSE file. 80 // found in the LICENSE file.
81 Polymer({is:"history-router",properties:{selectedPage:{type:String,observer:"ser ializePath_",notify:true},queryState:{type:Object,notify:true},path_:{type:Strin g,observer:"pathChanged_"},queryParams_:Object},observers:["queryParamsChanged_( queryParams_.*)","searchTermChanged_(queryState.searchTerm)"],attached:function( ){if(window.location.hash){window.location.href=window.location.href.split("#")[ 0]+"?"+window.location.hash.substr(1)}},serializePath_:function(){var page=this. selectedPage=="history"?"":this.selectedPage;this.path_="/"+page},pathChanged_:f unction(){var sections=this.path_.substr(1).split("/");this.selectedPage=section s[0]||"history"},queryParamsChanged_:function(){this.set("queryState.searchTerm" ,this.queryParams_.q||"")},searchTermChanged_:function(){this.set("queryParams_. q",this.queryState.searchTerm||null)}});Polymer.IronMultiSelectableBehaviorImpl= {properties:{multi:{type:Boolean,value:false,observer:"multiChanged"},selectedVa lues:{type:Array,notify:true},selectedItems:{type:Array,readOnly:true,notify:tru e}},observers:["_updateSelected(selectedValues.splices)"],select:function(value) {if(this.multi){if(this.selectedValues){this._toggleSelected(value)}else{this.se lectedValues=[value]}}else{this.selected=value}},multiChanged:function(multi){th is._selection.multi=multi},get _shouldUpdateSelection(){return this.selected!=nu ll||this.selectedValues!=null&&this.selectedValues.length},_updateAttrForSelecte d:function(){if(!this.multi){Polymer.IronSelectableBehavior._updateAttrForSelect ed.apply(this)}else if(this._shouldUpdateSelection){this.selectedValues=this.sel ectedItems.map(function(selectedItem){return this._indexToValue(this.indexOf(sel ectedItem))},this).filter(function(unfilteredValue){return unfilteredValue!=null },this)}},_updateSelected:function(){if(this.multi){this._selectMulti(this.selec tedValues)}else{this._selectSelected(this.selected)}},_selectMulti:function(valu es){if(values){var selectedItems=this._valuesToItems(values);this._selection.cle ar(selectedItems);for(var i=0;i<selectedItems.length;i++){this._selection.setIte mSelected(selectedItems[i],true)}if(this.fallbackSelection&&this.items.length&&! this._selection.get().length){var fallback=this._valueToItem(this.fallbackSelect ion);if(fallback){this.selectedValues=[this.fallbackSelection]}}}else{this._sele ction.clear()}},_selectionChange:function(){var s=this._selection.get();if(this. multi){this._setSelectedItems(s)}else{this._setSelectedItems([s]);this._setSelec tedItem(s)}},_toggleSelected:function(value){var i=this.selectedValues.indexOf(v alue);var unselected=i<0;if(unselected){this.push("selectedValues",value)}else{t his.splice("selectedValues",i,1)}},_valuesToItems:function(values){return values ==null?null:values.map(function(value){return this._valueToItem(value)},this)}}; Polymer.IronMultiSelectableBehavior=[Polymer.IronSelectableBehavior,Polymer.Iron MultiSelectableBehaviorImpl];Polymer({is:"iron-selector",behaviors:[Polymer.Iron MultiSelectableBehavior]}); 81 Polymer({is:"history-router",properties:{selectedPage:{type:String,observer:"ser ializePath_",notify:true},queryState:{type:Object,notify:true},path_:{type:Strin g,observer:"pathChanged_"},queryParams_:Object},observers:["queryParamsChanged_( queryParams_.*)","searchTermChanged_(queryState.searchTerm)"],attached:function( ){if(window.location.hash){window.location.href=window.location.href.split("#")[ 0]+"?"+window.location.hash.substr(1)}},serializePath_:function(){var page=this. selectedPage=="history"?"":this.selectedPage;this.path_="/"+page},pathChanged_:f unction(){var sections=this.path_.substr(1).split("/");this.selectedPage=section s[0]||"history"},queryParamsChanged_:function(){this.set("queryState.searchTerm" ,this.queryParams_.q||"")},searchTermChanged_:function(){this.set("queryParams_. q",this.queryState.searchTerm||null)}});Polymer.IronMultiSelectableBehaviorImpl= {properties:{multi:{type:Boolean,value:false,observer:"multiChanged"},selectedVa lues:{type:Array,notify:true},selectedItems:{type:Array,readOnly:true,notify:tru e}},observers:["_updateSelected(selectedValues.splices)"],select:function(value) {if(this.multi){if(this.selectedValues){this._toggleSelected(value)}else{this.se lectedValues=[value]}}else{this.selected=value}},multiChanged:function(multi){th is._selection.multi=multi},get _shouldUpdateSelection(){return this.selected!=nu ll||this.selectedValues!=null&&this.selectedValues.length},_updateAttrForSelecte d:function(){if(!this.multi){Polymer.IronSelectableBehavior._updateAttrForSelect ed.apply(this)}else if(this._shouldUpdateSelection){this.selectedValues=this.sel ectedItems.map(function(selectedItem){return this._indexToValue(this.indexOf(sel ectedItem))},this).filter(function(unfilteredValue){return unfilteredValue!=null },this)}},_updateSelected:function(){if(this.multi){this._selectMulti(this.selec tedValues)}else{this._selectSelected(this.selected)}},_selectMulti:function(valu es){if(values){var selectedItems=this._valuesToItems(values);this._selection.cle ar(selectedItems);for(var i=0;i<selectedItems.length;i++){this._selection.setIte mSelected(selectedItems[i],true)}if(this.fallbackSelection&&this.items.length&&! this._selection.get().length){var fallback=this._valueToItem(this.fallbackSelect ion);if(fallback){this.selectedValues=[this.fallbackSelection]}}}else{this._sele ction.clear()}},_selectionChange:function(){var s=this._selection.get();if(this. multi){this._setSelectedItems(s)}else{this._setSelectedItems([s]);this._setSelec tedItem(s)}},_toggleSelected:function(value){var i=this.selectedValues.indexOf(v alue);var unselected=i<0;if(unselected){this.push("selectedValues",value)}else{t his.splice("selectedValues",i,1)}},_valuesToItems:function(values){return values ==null?null:values.map(function(value){return this._valueToItem(value)},this)}}; Polymer.IronMultiSelectableBehavior=[Polymer.IronSelectableBehavior,Polymer.Iron MultiSelectableBehaviorImpl];Polymer({is:"iron-selector",behaviors:[Polymer.Iron MultiSelectableBehavior]});
82 // Copyright 2016 The Chromium Authors. All rights reserved. 82 // Copyright 2016 The Chromium Authors. All rights reserved.
83 // Use of this source code is governed by a BSD-style license that can be 83 // Use of this source code is governed by a BSD-style license that can be
84 // found in the LICENSE file. 84 // found in the LICENSE file.
85 Polymer({is:"history-side-bar",behaviors:[Polymer.IronA11yKeysBehavior],properti es:{selectedPage:{type:String,notify:true},showFooter:Boolean,drawer:{type:Boole an,reflectToAttribute:true}},keyBindings:{"space:keydown":"onSpacePressed_"},onS pacePressed_:function(e){e.detail.keyboardEvent.path[0].click()},onSelectorActiv ate_:function(){this.fire("history-close-drawer")},onClearBrowsingDataTap_:funct ion(e){var browserService=md_history.BrowserService.getInstance();browserService .recordAction("InitClearBrowsingData");browserService.openClearBrowsingData();th is.$["cbd-ripple"].upAction();e.preventDefault()},onItemClick_:function(e){e.pre ventDefault()}}); 85 Polymer({is:"history-side-bar",behaviors:[Polymer.IronA11yKeysBehavior],properti es:{selectedPage:{type:String,notify:true},showFooter:Boolean,drawer:{type:Boole an,reflectToAttribute:true}},keyBindings:{"space:keydown":"onSpacePressed_"},onS pacePressed_:function(e){e.detail.keyboardEvent.path[0].click()},onSelectorActiv ate_:function(){this.fire("history-close-drawer")},onClearBrowsingDataTap_:funct ion(e){var browserService=md_history.BrowserService.getInstance();browserService .recordAction("InitClearBrowsingData");browserService.openClearBrowsingData();th is.$["cbd-ripple"].upAction();e.preventDefault()},onItemClick_:function(e){e.pre ventDefault()}});
86 // Copyright 2016 The Chromium Authors. All rights reserved. 86 // Copyright 2016 The Chromium Authors. All rights reserved.
87 // Use of this source code is governed by a BSD-style license that can be 87 // Use of this source code is governed by a BSD-style license that can be
88 // found in the LICENSE file. 88 // found in the LICENSE file.
89 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,WebUIListenerBehavior ],properties:{showSidebarFooter:Boolean,hasSyncedResults:Boolean,selectedPage_:{ type:String,observer:"selectedPageChanged_"},grouped_:{type:Boolean,reflectToAtt ribute:true},queryState_:{type:Object,value:function(){return{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}}}},queryResult_:{type:Object,value:function(){return{info:null,results:n ull,sessionList:null}}},hasDrawer_:Boolean,isUserSignedIn_:{type:Boolean,value:l oadTimeData.getBoolean("isUserSignedIn")},toolbarShadow_:{type:Boolean,reflectTo Attribute:true,notify:true}},listeners:{"cr-menu-tap":"onMenuTap_","history-chec kbox-select":"checkboxSelected","unselect-all":"unselectAll","delete-selected":" deleteSelected","history-close-drawer":"closeDrawer_","history-view-changed":"hi storyViewChanged_"},ready:function(){this.grouped_=loadTimeData.getBoolean("grou pByDomain");cr.ui.decorate("command",cr.ui.Command);document.addEventListener("c anExecute",this.onCanExecute_.bind(this));document.addEventListener("command",th is.onCommand_.bind(this))},attached:function(){this.addWebUIListener("sign-in-st ate-updated",this.updateSignInState.bind(this))},onFirstRender:function(){setTim eout(function(){chrome.send("metricsHandler:recordTime",["History.ResultsRendere dTime",window.performance.now()])});var searchField=this.$.toolbar.searchField;i f(!searchField.narrow){searchField.getSearchInput().focus()}md_history.ensureLaz yLoaded()},_scrollHandler:function(){if(this.scrollTarget)this.toolbarShadow_=th is.scrollTarget.scrollTop!=0},onMenuTap_:function(){var drawer=this.$$("#drawer" );if(drawer)drawer.toggle()},checkboxSelected:function(e){var toolbar=this.$.too lbar;toolbar.count=this.$.history.getSelectedItemCount()},unselectAll:function() {var listContainer=this.$.history;var toolbar=this.$.toolbar;listContainer.unsel ectAllItems(toolbar.count);toolbar.count=0},deleteSelected:function(){this.$.his tory.deleteSelectedWithPrompt()},historyResult:function(info,results){this.set(" queryState_.querying",false);this.set("queryResult_.info",info);this.set("queryR esult_.results",results);var listContainer=this.$["history"];listContainer.histo ryResult(info,results)},focusToolbarSearchField:function(){this.$.toolbar.showSe archField()},onCanExecute_:function(e){e=e;switch(e.command.id){case"find-comman d":e.canExecute=true;break;case"slash-command":e.canExecute=!this.$.toolbar.sear chField.isSearchFocused();break;case"delete-command":e.canExecute=this.$.toolbar .count>0;break}},onCommand_:function(e){if(e.command.id=="find-command"||e.comma nd.id=="slash-command")this.focusToolbarSearchField();if(e.command.id=="delete-c ommand")this.deleteSelected()},setForeignSessions:function(sessionList,isTabSync Enabled){if(!isTabSyncEnabled){var syncedDeviceManagerElem=this.$$("history-sync ed-device-manager");if(syncedDeviceManagerElem)syncedDeviceManagerElem.tabSyncDi sabled();return}this.set("queryResult_.sessionList",sessionList)},historyDeleted :function(){this.$.history.historyDeleted()},updateSignInState:function(isUserSi gnedIn){this.isUserSignedIn_=isUserSignedIn},syncedTabsSelected_:function(select edPage){return selectedPage=="syncedTabs"},shouldShowSpinner_:function(querying, incremental,searchTerm){return querying&&!incremental&&searchTerm!=""},showSyncN otice_:function(hasSyncedResults,selectedPage){return hasSyncedResults&&selected Page!="syncedTabs"},selectedPageChanged_:function(){this.unselectAll();this.hist oryViewChanged_()},historyViewChanged_:function(){requestAnimationFrame(function (){if(!this.$.content.selectedItem)return;this.scrollTarget=this.$.content.selec tedItem.getContentScrollTarget();this._scrollHandler()}.bind(this));this.recordH istoryPageView_()},getSelectedPage_:function(selectedPage,items){return selected Page},closeDrawer_:function(){var drawer=this.$$("#drawer");if(drawer)drawer.clo se()},recordHistoryPageView_:function(){var histogramValue=HistoryPageViewHistog ram.END;switch(this.selectedPage_){case"syncedTabs":histogramValue=this.isUserSi gnedIn_?HistoryPageViewHistogram.SYNCED_TABS:HistoryPageViewHistogram.SIGNIN_PRO MO;break;default:switch(this.queryState_.range){case HistoryRange.ALL_TIME:histo gramValue=HistoryPageViewHistogram.HISTORY;break;case HistoryRange.WEEK:histogra mValue=HistoryPageViewHistogram.GROUPED_WEEK;break;case HistoryRange.MONTH:histo gramValue=HistoryPageViewHistogram.GROUPED_MONTH;break}break}md_history.BrowserS ervice.getInstance().recordHistogram("History.HistoryPageView",histogramValue,Hi storyPageViewHistogram.END)}}); 89 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,WebUIListenerBehavior ],properties:{showSidebarFooter:Boolean,hasSyncedResults:Boolean,selectedPage_:{ type:String,observer:"selectedPageChanged_"},grouped_:{type:Boolean,reflectToAtt ribute:true},queryState_:{type:Object,value:function(){return{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}}}},queryResult_:{type:Object,value:function(){return{info:null,results:n ull,sessionList:null}}},hasDrawer_:Boolean,isUserSignedIn_:{type:Boolean,value:l oadTimeData.getBoolean("isUserSignedIn")},toolbarShadow_:{type:Boolean,reflectTo Attribute:true,notify:true},showMenuPromo_:{type:Boolean,value:function(){return loadTimeData.getBoolean("showMenuPromo")}}},listeners:{"cr-toolbar-menu-promo-c lose":"onCrToolbarMenuPromoClose_","cr-toolbar-menu-promo-shown":"onCrToolbarMen uPromoShown_","cr-toolbar-menu-tap":"onCrToolbarMenuTap_","delete-selected":"del eteSelected","history-checkbox-select":"checkboxSelected","history-close-drawer" :"closeDrawer_","history-view-changed":"historyViewChanged_","opened-changed":"o nOpenedChanged_","unselect-all":"unselectAll"},ready:function(){this.grouped_=lo adTimeData.getBoolean("groupByDomain");cr.ui.decorate("command",cr.ui.Command);d ocument.addEventListener("canExecute",this.onCanExecute_.bind(this));document.ad dEventListener("command",this.onCommand_.bind(this))},attached:function(){this.a ddWebUIListener("sign-in-state-updated",this.updateSignInState.bind(this))},onFi rstRender:function(){setTimeout(function(){chrome.send("metricsHandler:recordTim e",["History.ResultsRenderedTime",window.performance.now()])});var searchField=t his.$.toolbar.searchField;if(!searchField.narrow){searchField.getSearchInput().f ocus()}md_history.ensureLazyLoaded()},_scrollHandler:function(){if(this.scrollTa rget)this.toolbarShadow_=this.scrollTarget.scrollTop!=0},onCrToolbarMenuPromoClo se_:function(){this.showMenuPromo_=false},onCrToolbarMenuPromoShown_:function(){ md_history.BrowserService.getInstance().menuPromoShown()},onCrToolbarMenuTap_:fu nction(){var drawer=this.$$("#drawer");if(drawer)drawer.toggle()},onOpenedChange d_:function(e){if(e.detail.value)this.showMenuPromo_=false},checkboxSelected:fun ction(e){var toolbar=this.$.toolbar;toolbar.count=this.$.history.getSelectedItem Count()},unselectAll:function(){var listContainer=this.$.history;var toolbar=thi s.$.toolbar;listContainer.unselectAllItems(toolbar.count);toolbar.count=0},delet eSelected:function(){this.$.history.deleteSelectedWithPrompt()},historyResult:fu nction(info,results){this.set("queryState_.querying",false);this.set("queryResul t_.info",info);this.set("queryResult_.results",results);var listContainer=this.$ ["history"];listContainer.historyResult(info,results)},focusToolbarSearchField:f unction(){this.$.toolbar.showSearchField()},onCanExecute_:function(e){e=e;switch (e.command.id){case"find-command":e.canExecute=true;break;case"slash-command":e. canExecute=!this.$.toolbar.searchField.isSearchFocused();break;case"delete-comma nd":e.canExecute=this.$.toolbar.count>0;break}},onCommand_:function(e){if(e.comm and.id=="find-command"||e.command.id=="slash-command")this.focusToolbarSearchFie ld();if(e.command.id=="delete-command")this.deleteSelected()},setForeignSessions :function(sessionList,isTabSyncEnabled){if(!isTabSyncEnabled){var syncedDeviceMa nagerElem=this.$$("history-synced-device-manager");if(syncedDeviceManagerElem)sy ncedDeviceManagerElem.tabSyncDisabled();return}this.set("queryResult_.sessionLis t",sessionList)},historyDeleted:function(){this.$.history.historyDeleted()},upda teSignInState:function(isUserSignedIn){this.isUserSignedIn_=isUserSignedIn},sync edTabsSelected_:function(selectedPage){return selectedPage=="syncedTabs"},should ShowSpinner_:function(querying,incremental,searchTerm){return querying&&!increme ntal&&searchTerm!=""},showSyncNotice_:function(hasSyncedResults,selectedPage){re turn hasSyncedResults&&selectedPage!="syncedTabs"},selectedPageChanged_:function (){this.unselectAll();this.historyViewChanged_()},historyViewChanged_:function() {requestAnimationFrame(function(){if(!this.$.content.selectedItem)return;this.sc rollTarget=this.$.content.selectedItem.getContentScrollTarget();this._scrollHand ler()}.bind(this));this.recordHistoryPageView_()},getSelectedPage_:function(sele ctedPage,items){return selectedPage},closeDrawer_:function(){var drawer=this.$$( "#drawer");if(drawer)drawer.close()},recordHistoryPageView_:function(){var histo gramValue=HistoryPageViewHistogram.END;switch(this.selectedPage_){case"syncedTab s":histogramValue=this.isUserSignedIn_?HistoryPageViewHistogram.SYNCED_TABS:Hist oryPageViewHistogram.SIGNIN_PROMO;break;default:switch(this.queryState_.range){c ase HistoryRange.ALL_TIME:histogramValue=HistoryPageViewHistogram.HISTORY;break; case HistoryRange.WEEK:histogramValue=HistoryPageViewHistogram.GROUPED_WEEK;brea k;case HistoryRange.MONTH:histogramValue=HistoryPageViewHistogram.GROUPED_MONTH; break}break}md_history.BrowserService.getInstance().recordHistogram("History.His toryPageView",histogramValue,HistoryPageViewHistogram.END)}});
OLDNEW
« no previous file with comments | « chrome/browser/resources/md_history/app.js ('k') | chrome/browser/resources/md_history/app.vulcanized.html » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698