| OLD | NEW |
| 1 // Copyright 2016 The Chromium Authors. All rights reserved. | 1 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
| 4 function PromiseResolver(){this.resolve_;this.reject_;this.promise_=new Promise(
function(resolve,reject){this.resolve_=resolve;this.reject_=reject}.bind(this))}
PromiseResolver.prototype={get promise(){return this.promise_},set promise(p){as
sertNotReached()},get resolve(){return this.resolve_},set resolve(r){assertNotRe
ached()},get reject(){return this.reject_},set reject(s){assertNotReached()}}; | 4 function PromiseResolver(){this.resolve_;this.reject_;this.promise_=new Promise(
function(resolve,reject){this.resolve_=resolve;this.reject_=reject}.bind(this))}
PromiseResolver.prototype={get promise(){return this.promise_},set promise(p){as
sertNotReached()},get resolve(){return this.resolve_},set resolve(r){assertNotRe
ached()},get reject(){return this.reject_},set reject(s){assertNotReached()}}; |
| 5 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | 5 // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| 6 // Use of this source code is governed by a BSD-style license that can be | 6 // Use of this source code is governed by a BSD-style license that can be |
| 7 // found in the LICENSE file. | 7 // found in the LICENSE file. |
| 8 var global=this;var WebUIListener;var cr=cr||function(){"use strict";function ex
portPath(name,opt_object,opt_objectToExportTo){var parts=name.split(".");var cur
=opt_objectToExportTo||global;for(var part;parts.length&&(part=parts.shift());){
if(!parts.length&&opt_object!==undefined){cur[part]=opt_object}else if(part in c
ur){cur=cur[part]}else{cur=cur[part]={}}}return cur}function dispatchPropertyCha
nge(target,propertyName,newValue,oldValue){var e=new Event(propertyName+"Change"
);e.propertyName=propertyName;e.newValue=newValue;e.oldValue=oldValue;target.dis
patchEvent(e)}function getAttributeName(jsName){return jsName.replace(/([A-Z])/g
,"-$1").toLowerCase()}var PropertyKind={JS:"js",ATTR:"attr",BOOL_ATTR:"boolAttr"
};function getGetter(name,kind){switch(kind){case PropertyKind.JS:var privateNam
e=name+"_";return function(){return this[privateName]};case PropertyKind.ATTR:va
r attributeName=getAttributeName(name);return function(){return this.getAttribut
e(attributeName)};case PropertyKind.BOOL_ATTR:var attributeName=getAttributeName
(name);return function(){return this.hasAttribute(attributeName)}}throw"not reac
hed"}function getSetter(name,kind,opt_setHook){switch(kind){case PropertyKind.JS
:var privateName=name+"_";return function(value){var oldValue=this[name];if(valu
e!==oldValue){this[privateName]=value;if(opt_setHook)opt_setHook.call(this,value
,oldValue);dispatchPropertyChange(this,name,value,oldValue)}};case PropertyKind.
ATTR:var attributeName=getAttributeName(name);return function(value){var oldValu
e=this[name];if(value!==oldValue){if(value==undefined)this.removeAttribute(attri
buteName);else this.setAttribute(attributeName,value);if(opt_setHook)opt_setHook
.call(this,value,oldValue);dispatchPropertyChange(this,name,value,oldValue)}};ca
se PropertyKind.BOOL_ATTR:var attributeName=getAttributeName(name);return functi
on(value){var oldValue=this[name];if(value!==oldValue){if(value)this.setAttribut
e(attributeName,name);else this.removeAttribute(attributeName);if(opt_setHook)op
t_setHook.call(this,value,oldValue);dispatchPropertyChange(this,name,value,oldVa
lue)}}}throw"not reached"}function defineProperty(obj,name,opt_kind,opt_setHook)
{if(typeof obj=="function")obj=obj.prototype;var kind=opt_kind||PropertyKind.JS;
if(!obj.__lookupGetter__(name))obj.__defineGetter__(name,getGetter(name,kind));i
f(!obj.__lookupSetter__(name))obj.__defineSetter__(name,getSetter(name,kind,opt_
setHook))}var uidCounter=1;function createUid(){return uidCounter++}function get
Uid(item){if(item.hasOwnProperty("uid"))return item.uid;return item.uid=createUi
d()}function dispatchSimpleEvent(target,type,opt_bubbles,opt_cancelable){var e=n
ew Event(type,{bubbles:opt_bubbles,cancelable:opt_cancelable===undefined||opt_ca
ncelable});return target.dispatchEvent(e)}function define(name,fun){var obj=expo
rtPath(name);var exports=fun();for(var propertyName in exports){var propertyDesc
riptor=Object.getOwnPropertyDescriptor(exports,propertyName);if(propertyDescript
or)Object.defineProperty(obj,propertyName,propertyDescriptor)}}function addSingl
etonGetter(ctor){ctor.getInstance=function(){return ctor.instance_||(ctor.instan
ce_=new ctor)}}function makePublic(ctor,methods,opt_target){methods.forEach(func
tion(method){ctor[method]=function(){var target=opt_target?document.getElementBy
Id(opt_target):ctor.getInstance();return target[method+"_"].apply(target,argumen
ts)}})}var chromeSendResolverMap={};function webUIResponse(id,isSuccess,response
){var resolver=chromeSendResolverMap[id];delete chromeSendResolverMap[id];if(isS
uccess)resolver.resolve(response);else resolver.reject(response)}function sendWi
thPromise(methodName,var_args){var args=Array.prototype.slice.call(arguments,1);
var promiseResolver=new PromiseResolver;var id=methodName+"_"+createUid();chrome
SendResolverMap[id]=promiseResolver;chrome.send(methodName,[id].concat(args));re
turn promiseResolver.promise}var webUIListenerMap={};function webUIListenerCallb
ack(event,var_args){var eventListenersMap=webUIListenerMap[event];if(!eventListe
nersMap){return}var args=Array.prototype.slice.call(arguments,1);for(var listene
rId in eventListenersMap){eventListenersMap[listenerId].apply(null,args)}}functi
on addWebUIListener(eventName,callback){webUIListenerMap[eventName]=webUIListene
rMap[eventName]||{};var uid=createUid();webUIListenerMap[eventName][uid]=callbac
k;return{eventName:eventName,uid:uid}}function removeWebUIListener(listener){var
listenerExists=webUIListenerMap[listener.eventName]&&webUIListenerMap[listener.
eventName][listener.uid];if(listenerExists){delete webUIListenerMap[listener.eve
ntName][listener.uid];return true}return false}return{addSingletonGetter:addSing
letonGetter,createUid:createUid,define:define,defineProperty:defineProperty,disp
atchPropertyChange:dispatchPropertyChange,dispatchSimpleEvent:dispatchSimpleEven
t,exportPath:exportPath,getUid:getUid,makePublic:makePublic,PropertyKind:Propert
yKind,addWebUIListener:addWebUIListener,removeWebUIListener:removeWebUIListener,
sendWithPromise:sendWithPromise,webUIListenerCallback:webUIListenerCallback,webU
IResponse:webUIResponse,get doc(){return document},get isMac(){return/Mac/.test(
navigator.platform)},get isWindows(){return/Win/.test(navigator.platform)},get i
sChromeOS(){return/CrOS/.test(navigator.userAgent)},get isLinux(){return/Linux/.
test(navigator.userAgent)},get isAndroid(){return/Android/.test(navigator.userAg
ent)},get isIOS(){return/iPad|iPhone|iPod/.test(navigator.platform)}}}(); | 8 var global=this;var WebUIListener;var cr=cr||function(){"use strict";function ex
portPath(name,opt_object,opt_objectToExportTo){var parts=name.split(".");var cur
=opt_objectToExportTo||global;for(var part;parts.length&&(part=parts.shift());){
if(!parts.length&&opt_object!==undefined){cur[part]=opt_object}else if(part in c
ur){cur=cur[part]}else{cur=cur[part]={}}}return cur}function dispatchPropertyCha
nge(target,propertyName,newValue,oldValue){var e=new Event(propertyName+"Change"
);e.propertyName=propertyName;e.newValue=newValue;e.oldValue=oldValue;target.dis
patchEvent(e)}function getAttributeName(jsName){return jsName.replace(/([A-Z])/g
,"-$1").toLowerCase()}var PropertyKind={JS:"js",ATTR:"attr",BOOL_ATTR:"boolAttr"
};function getGetter(name,kind){switch(kind){case PropertyKind.JS:var privateNam
e=name+"_";return function(){return this[privateName]};case PropertyKind.ATTR:va
r attributeName=getAttributeName(name);return function(){return this.getAttribut
e(attributeName)};case PropertyKind.BOOL_ATTR:var attributeName=getAttributeName
(name);return function(){return this.hasAttribute(attributeName)}}throw"not reac
hed"}function getSetter(name,kind,opt_setHook){switch(kind){case PropertyKind.JS
:var privateName=name+"_";return function(value){var oldValue=this[name];if(valu
e!==oldValue){this[privateName]=value;if(opt_setHook)opt_setHook.call(this,value
,oldValue);dispatchPropertyChange(this,name,value,oldValue)}};case PropertyKind.
ATTR:var attributeName=getAttributeName(name);return function(value){var oldValu
e=this[name];if(value!==oldValue){if(value==undefined)this.removeAttribute(attri
buteName);else this.setAttribute(attributeName,value);if(opt_setHook)opt_setHook
.call(this,value,oldValue);dispatchPropertyChange(this,name,value,oldValue)}};ca
se PropertyKind.BOOL_ATTR:var attributeName=getAttributeName(name);return functi
on(value){var oldValue=this[name];if(value!==oldValue){if(value)this.setAttribut
e(attributeName,name);else this.removeAttribute(attributeName);if(opt_setHook)op
t_setHook.call(this,value,oldValue);dispatchPropertyChange(this,name,value,oldVa
lue)}}}throw"not reached"}function defineProperty(obj,name,opt_kind,opt_setHook)
{if(typeof obj=="function")obj=obj.prototype;var kind=opt_kind||PropertyKind.JS;
if(!obj.__lookupGetter__(name))obj.__defineGetter__(name,getGetter(name,kind));i
f(!obj.__lookupSetter__(name))obj.__defineSetter__(name,getSetter(name,kind,opt_
setHook))}var uidCounter=1;function createUid(){return uidCounter++}function get
Uid(item){if(item.hasOwnProperty("uid"))return item.uid;return item.uid=createUi
d()}function dispatchSimpleEvent(target,type,opt_bubbles,opt_cancelable){var e=n
ew Event(type,{bubbles:opt_bubbles,cancelable:opt_cancelable===undefined||opt_ca
ncelable});return target.dispatchEvent(e)}function define(name,fun){var obj=expo
rtPath(name);var exports=fun();for(var propertyName in exports){var propertyDesc
riptor=Object.getOwnPropertyDescriptor(exports,propertyName);if(propertyDescript
or)Object.defineProperty(obj,propertyName,propertyDescriptor)}}function addSingl
etonGetter(ctor){ctor.getInstance=function(){return ctor.instance_||(ctor.instan
ce_=new ctor)}}function makePublic(ctor,methods,opt_target){methods.forEach(func
tion(method){ctor[method]=function(){var target=opt_target?document.getElementBy
Id(opt_target):ctor.getInstance();return target[method+"_"].apply(target,argumen
ts)}})}var chromeSendResolverMap={};function webUIResponse(id,isSuccess,response
){var resolver=chromeSendResolverMap[id];delete chromeSendResolverMap[id];if(isS
uccess)resolver.resolve(response);else resolver.reject(response)}function sendWi
thPromise(methodName,var_args){var args=Array.prototype.slice.call(arguments,1);
var promiseResolver=new PromiseResolver;var id=methodName+"_"+createUid();chrome
SendResolverMap[id]=promiseResolver;chrome.send(methodName,[id].concat(args));re
turn promiseResolver.promise}var webUIListenerMap={};function webUIListenerCallb
ack(event,var_args){var eventListenersMap=webUIListenerMap[event];if(!eventListe
nersMap){return}var args=Array.prototype.slice.call(arguments,1);for(var listene
rId in eventListenersMap){eventListenersMap[listenerId].apply(null,args)}}functi
on addWebUIListener(eventName,callback){webUIListenerMap[eventName]=webUIListene
rMap[eventName]||{};var uid=createUid();webUIListenerMap[eventName][uid]=callbac
k;return{eventName:eventName,uid:uid}}function removeWebUIListener(listener){var
listenerExists=webUIListenerMap[listener.eventName]&&webUIListenerMap[listener.
eventName][listener.uid];if(listenerExists){delete webUIListenerMap[listener.eve
ntName][listener.uid];return true}return false}return{addSingletonGetter:addSing
letonGetter,createUid:createUid,define:define,defineProperty:defineProperty,disp
atchPropertyChange:dispatchPropertyChange,dispatchSimpleEvent:dispatchSimpleEven
t,exportPath:exportPath,getUid:getUid,makePublic:makePublic,PropertyKind:Propert
yKind,addWebUIListener:addWebUIListener,removeWebUIListener:removeWebUIListener,
sendWithPromise:sendWithPromise,webUIListenerCallback:webUIListenerCallback,webU
IResponse:webUIResponse,get doc(){return document},get isMac(){return/Mac/.test(
navigator.platform)},get isWindows(){return/Win/.test(navigator.platform)},get i
sChromeOS(){return/CrOS/.test(navigator.userAgent)},get isLinux(){return/Linux/.
test(navigator.userAgent)},get isAndroid(){return/Android/.test(navigator.userAg
ent)},get isIOS(){return/iPad|iPhone|iPod/.test(navigator.platform)}}}(); |
| 9 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | 9 // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| 10 // Use of this source code is governed by a BSD-style license that can be | 10 // Use of this source code is governed by a BSD-style license that can be |
| (...skipping 19 matching lines...) Expand all Loading... |
| 30 // Use of this source code is governed by a BSD-style license that can be | 30 // Use of this source code is governed by a BSD-style license that can be |
| 31 // found in the LICENSE file. | 31 // found in the LICENSE file. |
| 32 Polymer({is:"cr-toolbar",properties:{pageName:String,searchPrompt:String,clearLa
bel:String,menuLabel:String,menuPromo:String,spinnerActive:Boolean,showMenu:{typ
e:Boolean,value:false},showMenuPromo:{type:Boolean,value:false},closeMenuPromo:S
tring,narrow_:{type:Boolean,reflectToAttribute:true},showingSearch_:{type:Boolea
n,reflectToAttribute:true}},observers:["possiblyShowMenuPromo_(showMenu, showMen
uPromo, showingSearch_)"],getSearchField:function(){return this.$.search},onClos
ePromoTap_:function(){this.fire("cr-toolbar-menu-promo-close")},onMenuTap_:funct
ion(){this.fire("cr-toolbar-menu-tap")},possiblyShowMenuPromo_:function(){Polyme
r.RenderStatus.afterNextRender(this,function(){if(this.showMenu&&this.showMenuPr
omo&&!this.showingSearch_){this.$$("#menuPromo").animate({opacity:[0,.9]},{durat
ion:500,fill:"forwards"});this.fire("cr-toolbar-menu-promo-shown")}}.bind(this))
},titleIfNotShowMenuPromo_:function(title,showMenuPromo){return showMenuPromo?""
:title}}); | 32 Polymer({is:"cr-toolbar",properties:{pageName:String,searchPrompt:String,clearLa
bel:String,menuLabel:String,menuPromo:String,spinnerActive:Boolean,showMenu:{typ
e:Boolean,value:false},showMenuPromo:{type:Boolean,value:false},closeMenuPromo:S
tring,narrow_:{type:Boolean,reflectToAttribute:true},showingSearch_:{type:Boolea
n,reflectToAttribute:true}},observers:["possiblyShowMenuPromo_(showMenu, showMen
uPromo, showingSearch_)"],getSearchField:function(){return this.$.search},onClos
ePromoTap_:function(){this.fire("cr-toolbar-menu-promo-close")},onMenuTap_:funct
ion(){this.fire("cr-toolbar-menu-tap")},possiblyShowMenuPromo_:function(){Polyme
r.RenderStatus.afterNextRender(this,function(){if(this.showMenu&&this.showMenuPr
omo&&!this.showingSearch_){this.$$("#menuPromo").animate({opacity:[0,.9]},{durat
ion:500,fill:"forwards"});this.fire("cr-toolbar-menu-promo-shown")}}.bind(this))
},titleIfNotShowMenuPromo_:function(title,showMenuPromo){return showMenuPromo?""
:title}}); |
| 33 // Copyright 2016 The Chromium Authors. All rights reserved. | 33 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 34 // Use of this source code is governed by a BSD-style license that can be | 34 // Use of this source code is governed by a BSD-style license that can be |
| 35 // found in the LICENSE file. | 35 // found in the LICENSE file. |
| 36 cr.define("md_history",function(){function BrowserService(){this.pendingDeleteIt
ems_=null;this.pendingDeletePromise_=null}BrowserService.prototype={deleteItems:
function(items){if(this.pendingDeleteItems_!=null){return new Promise(function(r
esolve,reject){reject(items)})}var removalList=items.map(function(item){return{u
rl:item.url,timestamps:item.allTimestamps}});this.pendingDeleteItems_=items;this
.pendingDeletePromise_=new PromiseResolver;chrome.send("removeVisits",removalLis
t);return this.pendingDeletePromise_.promise},removeBookmark:function(url){chrom
e.send("removeBookmark",[url])},openForeignSessionAllTabs:function(sessionTag){c
hrome.send("openForeignSession",[sessionTag])},openForeignSessionTab:function(se
ssionTag,windowId,tabId,e){chrome.send("openForeignSession",[sessionTag,String(w
indowId),String(tabId),e.button||0,e.altKey,e.ctrlKey,e.metaKey,e.shiftKey])},de
leteForeignSession:function(sessionTag){chrome.send("deleteForeignSession",[sess
ionTag])},openClearBrowsingData:function(){chrome.send("clearBrowsingData")},rec
ordHistogram:function(histogram,value,max){chrome.send("metricsHandler:recordInH
istogram",[histogram,value,max])},recordAction:function(action){if(action.indexO
f("_")==-1)action="HistoryPage_"+action;chrome.send("metricsHandler:recordAction
",[action])},resolveDelete_:function(successful){if(this.pendingDeleteItems_==nu
ll||this.pendingDeletePromise_==null){return}if(successful)this.pendingDeletePro
mise_.resolve(this.pendingDeleteItems_);else this.pendingDeletePromise_.reject(t
his.pendingDeleteItems_);this.pendingDeleteItems_=null;this.pendingDeletePromise
_=null},menuPromoShown:function(){chrome.send("menuPromoShown")}};cr.addSingleto
nGetter(BrowserService);return{BrowserService:BrowserService}});function deleteC
omplete(){md_history.BrowserService.getInstance().resolveDelete_(true)}function
deleteFailed(){md_history.BrowserService.getInstance().resolveDelete_(false)} | 36 cr.define("md_history",function(){function BrowserService(){this.pendingDeleteIt
ems_=null;this.pendingDeletePromise_=null}BrowserService.prototype={deleteItems:
function(items){if(this.pendingDeleteItems_!=null){return new Promise(function(r
esolve,reject){reject(items)})}var removalList=items.map(function(item){return{u
rl:item.url,timestamps:item.allTimestamps}});this.pendingDeleteItems_=items;this
.pendingDeletePromise_=new PromiseResolver;chrome.send("removeVisits",removalLis
t);return this.pendingDeletePromise_.promise},removeBookmark:function(url){chrom
e.send("removeBookmark",[url])},openForeignSessionAllTabs:function(sessionTag){c
hrome.send("openForeignSession",[sessionTag])},openForeignSessionTab:function(se
ssionTag,windowId,tabId,e){chrome.send("openForeignSession",[sessionTag,String(w
indowId),String(tabId),e.button||0,e.altKey,e.ctrlKey,e.metaKey,e.shiftKey])},de
leteForeignSession:function(sessionTag){chrome.send("deleteForeignSession",[sess
ionTag])},openClearBrowsingData:function(){chrome.send("clearBrowsingData")},rec
ordHistogram:function(histogram,value,max){chrome.send("metricsHandler:recordInH
istogram",[histogram,value,max])},recordAction:function(action){if(action.indexO
f("_")==-1)action="HistoryPage_"+action;chrome.send("metricsHandler:recordAction
",[action])},resolveDelete_:function(successful){if(this.pendingDeleteItems_==nu
ll||this.pendingDeletePromise_==null){return}if(successful)this.pendingDeletePro
mise_.resolve(this.pendingDeleteItems_);else this.pendingDeletePromise_.reject(t
his.pendingDeleteItems_);this.pendingDeleteItems_=null;this.pendingDeletePromise
_=null},menuPromoShown:function(){chrome.send("menuPromoShown")}};cr.addSingleto
nGetter(BrowserService);return{BrowserService:BrowserService}});function deleteC
omplete(){md_history.BrowserService.getInstance().resolveDelete_(true)}function
deleteFailed(){md_history.BrowserService.getInstance().resolveDelete_(false)} |
| 37 // Copyright 2015 The Chromium Authors. All rights reserved. | 37 // Copyright 2015 The Chromium Authors. All rights reserved. |
| 38 // Use of this source code is governed by a BSD-style license that can be | 38 // Use of this source code is governed by a BSD-style license that can be |
| 39 // found in the LICENSE file. | 39 // found in the LICENSE file. |
| 40 Polymer({is:"history-toolbar",properties:{count:{type:Number,value:0,observer:"c
hangeToolbarView_"},itemsSelected_:{type:Boolean,value:false,reflectToAttribute:
true},searchTerm:{type:String,observer:"searchTermChanged_",notify:true},spinner
Active:{type:Boolean,value:false},hasDrawer:{type:Boolean,reflectToAttribute:tru
e},showSyncNotice:Boolean,isGroupedMode:{type:Boolean,reflectToAttribute:true},g
roupedRange:{type:Number,reflectToAttribute:true,notify:true},groupedOffset:{typ
e:Number,notify:true},querying:Boolean,hasMoreResults:Boolean,queryStartTime:Str
ing,queryEndTime:String,showMenuPromo:Boolean},get searchField(){return this.$["
main-toolbar"].getSearchField()},showSearchField:function(){this.searchField.sho
wAndFocus()},changeToolbarView_:function(){this.itemsSelected_=this.count>0},sea
rchTermChanged_:function(){if(this.searchField.getValue()!=this.searchTerm){this
.searchField.showAndFocus();this.searchField.setValue(this.searchTerm)}},onSearc
hChanged_:function(event){this.searchTerm=event.detail},onInfoButtonTap_:functio
n(){var dropdown=this.$.syncNotice.get();dropdown.positionTarget=this.$$("#info-
button-icon");if(dropdown.style.display=="none")dropdown.open()},onClearSelectio
nTap_:function(){this.fire("unselect-all")},onDeleteTap_:function(){this.fire("d
elete-selected")},deletingAllowed_:function(){return loadTimeData.getBoolean("al
lowDeletingHistory")},numberOfItemsSelected_:function(count){return count>0?load
TimeData.getStringF("itemsSelected",count):""},getHistoryInterval_:function(quer
yStartTime,queryEndTime){return loadTimeData.getStringF("historyInterval",queryS
tartTime,queryEndTime)},onTodayTap_:function(){if(!this.querying)this.groupedOff
set=0},onPrevTap_:function(){if(!this.querying)this.groupedOffset=this.groupedOf
fset+1},onNextTap_:function(){if(!this.querying)this.groupedOffset=this.groupedO
ffset-1},isToday_:function(){return this.groupedOffset==0}});(function(){"use st
rict";Polymer.IronA11yAnnouncer=Polymer({is:"iron-a11y-announcer",properties:{mo
de:{type:String,value:"polite"},_text:{type:String,value:""}},created:function()
{if(!Polymer.IronA11yAnnouncer.instance){Polymer.IronA11yAnnouncer.instance=this
}document.body.addEventListener("iron-announce",this._onIronAnnounce.bind(this))
},announce:function(text){this._text="";this.async(function(){this._text=text},1
00)},_onIronAnnounce:function(event){if(event.detail&&event.detail.text){this.an
nounce(event.detail.text)}}});Polymer.IronA11yAnnouncer.instance=null;Polymer.Ir
onA11yAnnouncer.requestAvailability=function(){if(!Polymer.IronA11yAnnouncer.ins
tance){Polymer.IronA11yAnnouncer.instance=document.createElement("iron-a11y-anno
uncer")}document.body.appendChild(Polymer.IronA11yAnnouncer.instance)}})();(func
tion(){var IOS=navigator.userAgent.match(/iP(?:hone|ad;(?: U;)? CPU) OS (\d+)/);
var IOS_TOUCH_SCROLLING=IOS&&IOS[1]>=8;var DEFAULT_PHYSICAL_COUNT=3;var HIDDEN_Y
="-10000px";var ITEM_WIDTH=0;var ITEM_HEIGHT=1;var SECRET_TABINDEX=-100;Polymer(
{is:"iron-list",properties:{items:{type:Array},maxPhysicalCount:{type:Number,val
ue:500},as:{type:String,value:"item"},indexAs:{type:String,value:"index"},select
edAs:{type:String,value:"selected"},grid:{type:Boolean,value:false,reflectToAttr
ibute:true},selectionEnabled:{type:Boolean,value:false},selectedItem:{type:Objec
t,notify:true},selectedItems:{type:Object,notify:true},multiSelection:{type:Bool
ean,value:false}},observers:["_itemsChanged(items.*)","_selectionEnabledChanged(
selectionEnabled)","_multiSelectionChanged(multiSelection)","_setOverflow(scroll
Target)"],behaviors:[Polymer.Templatizer,Polymer.IronResizableBehavior,Polymer.I
ronA11yKeysBehavior,Polymer.IronScrollTargetBehavior],keyBindings:{up:"_didMoveU
p",down:"_didMoveDown",enter:"_didEnter"},_ratio:.5,_scrollerPaddingTop:0,_scrol
lPosition:0,_physicalSize:0,_physicalAverage:0,_physicalAverageCount:0,_physical
Top:0,_virtualCount:0,_physicalIndexForKey:null,_estScrollHeight:0,_scrollHeight
:0,_viewportHeight:0,_viewportWidth:0,_physicalItems:null,_physicalSizes:null,_f
irstVisibleIndexVal:null,_lastVisibleIndexVal:null,_collection:null,_maxPages:2,
_focusedItem:null,_focusedIndex:-1,_offscreenFocusedItem:null,_focusBackfillItem
:null,_itemsPerRow:1,_itemWidth:0,_rowHeight:0,_templateCost:0,get _physicalBott
om(){return this._physicalTop+this._physicalSize},get _scrollBottom(){return thi
s._scrollPosition+this._viewportHeight},get _virtualEnd(){return this._virtualSt
art+this._physicalCount-1},get _hiddenContentSize(){var size=this.grid?this._phy
sicalRows*this._rowHeight:this._physicalSize;return size-this._viewportHeight},g
et _maxScrollTop(){return this._estScrollHeight-this._viewportHeight+this._scrol
lerPaddingTop},_minVirtualStart:0,get _maxVirtualStart(){return Math.max(0,this.
_virtualCount-this._physicalCount)},_virtualStartVal:0,set _virtualStart(val){th
is._virtualStartVal=Math.min(this._maxVirtualStart,Math.max(this._minVirtualStar
t,val))},get _virtualStart(){return this._virtualStartVal||0},_physicalStartVal:
0,set _physicalStart(val){this._physicalStartVal=val%this._physicalCount;if(this
._physicalStartVal<0){this._physicalStartVal=this._physicalCount+this._physicalS
tartVal}this._physicalEnd=(this._physicalStart+this._physicalCount-1)%this._phys
icalCount},get _physicalStart(){return this._physicalStartVal||0},_physicalCount
Val:0,set _physicalCount(val){this._physicalCountVal=val;this._physicalEnd=(this
._physicalStart+this._physicalCount-1)%this._physicalCount},get _physicalCount()
{return this._physicalCountVal},_physicalEnd:0,get _optPhysicalSize(){if(this.gr
id){return this._estRowsInView*this._rowHeight*this._maxPages}return this._viewp
ortHeight*this._maxPages},get _isVisible(){return Boolean(this.offsetWidth||this
.offsetHeight)},get firstVisibleIndex(){if(this._firstVisibleIndexVal===null){va
r physicalOffset=Math.floor(this._physicalTop+this._scrollerPaddingTop);this._fi
rstVisibleIndexVal=this._iterateItems(function(pidx,vidx){physicalOffset+=this._
getPhysicalSizeIncrement(pidx);if(physicalOffset>this._scrollPosition){return th
is.grid?vidx-vidx%this._itemsPerRow:vidx}if(this.grid&&this._virtualCount-1===vi
dx){return vidx-vidx%this._itemsPerRow}})||0}return this._firstVisibleIndexVal},
get lastVisibleIndex(){if(this._lastVisibleIndexVal===null){if(this.grid){var la
stIndex=this.firstVisibleIndex+this._estRowsInView*this._itemsPerRow-1;this._las
tVisibleIndexVal=Math.min(this._virtualCount,lastIndex)}else{var physicalOffset=
this._physicalTop;this._iterateItems(function(pidx,vidx){if(physicalOffset<this.
_scrollBottom){this._lastVisibleIndexVal=vidx}else{return true}physicalOffset+=t
his._getPhysicalSizeIncrement(pidx)})}}return this._lastVisibleIndexVal},get _de
faultScrollTarget(){return this},get _virtualRowCount(){return Math.ceil(this._v
irtualCount/this._itemsPerRow)},get _estRowsInView(){return Math.ceil(this._view
portHeight/this._rowHeight)},get _physicalRows(){return Math.ceil(this._physical
Count/this._itemsPerRow)},ready:function(){this.addEventListener("focus",this._d
idFocus.bind(this),true)},attached:function(){if(this._physicalCount===0){this._
debounceTemplate(this._render)}this.listen(this,"iron-resize","_resizeHandler")}
,detached:function(){this.unlisten(this,"iron-resize","_resizeHandler")},_setOve
rflow:function(scrollTarget){this.style.webkitOverflowScrolling=scrollTarget===t
his?"touch":"";this.style.overflow=scrollTarget===this?"auto":""},updateViewport
Boundaries:function(){this._scrollerPaddingTop=this.scrollTarget===this?0:parseI
nt(window.getComputedStyle(this)["padding-top"],10);this._viewportWidth=this.$.i
tems.offsetWidth;this._viewportHeight=this._scrollTargetHeight;this.grid&&this._
updateGridMetrics()},_scrollHandler:function(){var scrollTop=Math.max(0,Math.min
(this._maxScrollTop,this._scrollTop));var delta=scrollTop-this._scrollPosition;v
ar isScrollingDown=delta>=0;this._scrollPosition=scrollTop;this._firstVisibleInd
exVal=null;this._lastVisibleIndexVal=null;if(Math.abs(delta)>this._physicalSize)
{var idxAdjustment=Math.round(delta/this._physicalAverage)*this._itemsPerRow;thi
s._physicalTop=this._physicalTop+delta;this._virtualStart=this._virtualStart+idx
Adjustment;this._physicalStart=this._physicalStart+idxAdjustment;this._update()}
else{var reusables=this._getReusables(isScrollingDown);if(isScrollingDown){this.
_physicalTop=reusables.physicalTop;this._virtualStart=this._virtualStart+reusabl
es.indexes.length;this._physicalStart=this._physicalStart+reusables.indexes.leng
th}else{this._virtualStart=this._virtualStart-reusables.indexes.length;this._phy
sicalStart=this._physicalStart-reusables.indexes.length}if(reusables.indexes.len
gth===0){this._increasePoolIfNeeded()}else{this._update(reusables.indexes,isScro
llingDown?null:reusables.indexes)}}},_getReusables:function(fromTop){var ith,las
tIth,offsetContent,physicalItemHeight;var idxs=[];var protectedOffsetContent=thi
s._hiddenContentSize*this._ratio;var virtualStart=this._virtualStart;var virtual
End=this._virtualEnd;var physicalCount=this._physicalCount;var physicalTop=this.
_physicalTop+this._scrollerPaddingTop;var scrollTop=this._scrollTop;var scrollBo
ttom=this._scrollBottom;if(fromTop){ith=this._physicalStart;lastIth=this._physic
alEnd;offsetContent=scrollTop-physicalTop}else{ith=this._physicalEnd;lastIth=thi
s._physicalStart;offsetContent=this._physicalBottom-scrollBottom}while(true){phy
sicalItemHeight=this._getPhysicalSizeIncrement(ith);offsetContent=offsetContent-
physicalItemHeight;if(idxs.length>=physicalCount||offsetContent<=protectedOffset
Content){break}if(fromTop){if(virtualEnd+idxs.length+1>=this._virtualCount){brea
k}if(physicalTop+physicalItemHeight>=scrollTop){break}idxs.push(ith);physicalTop
=physicalTop+physicalItemHeight;ith=(ith+1)%physicalCount}else{if(virtualStart-i
dxs.length<=0){break}if(physicalTop+this._physicalSize-physicalItemHeight<=scrol
lBottom){break}idxs.push(ith);physicalTop=physicalTop-physicalItemHeight;ith=ith
===0?physicalCount-1:ith-1}}return{indexes:idxs,physicalTop:physicalTop-this._sc
rollerPaddingTop}},_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._physi
calTop-=this._getPhysicalSizeIncrement(idx)}}this._positionItems();this._updateS
crollerSize();this._increasePoolIfNeeded()},_createPool:function(size){var physi
calItems=new Array(size);this._ensureTemplatized();for(var i=0;i<size;i++){var i
nst=this.stamp(null);physicalItems[i]=inst.root.querySelector("*");Polymer.dom(t
his).appendChild(inst.root)}return physicalItems},_increasePoolIfNeeded:function
(){if(this._viewportHeight===0){return false}var self=this;var isClientFull=this
._physicalBottom>=this._scrollBottom&&this._physicalTop<=this._scrollPosition;if
(this._physicalSize>=this._optPhysicalSize&&isClientFull){return false}var maxPo
olSize=Math.round(this._physicalCount*.5);if(!isClientFull){this._debounceTempla
te(this._increasePool.bind(this,maxPoolSize));return true}this._yield(function()
{self._increasePool(Math.min(maxPoolSize,Math.max(1,Math.round(50/self._template
Cost))))});return true},_yield:function(cb){var g=window;var handle=g.requestIdl
eCallback?g.requestIdleCallback(cb):g.setTimeout(cb,16);Polymer.dom.addDebouncer
({complete:function(){g.cancelIdleCallback?g.cancelIdleCallback(handle):g.clearT
imeout(handle);cb()}})},_increasePool:function(missingItems){var nextPhysicalCou
nt=Math.min(this._physicalCount+missingItems,this._virtualCount-this._virtualSta
rt,Math.max(this.maxPhysicalCount,DEFAULT_PHYSICAL_COUNT));var prevPhysicalCount
=this._physicalCount;var delta=nextPhysicalCount-prevPhysicalCount;var ts=window
.performance.now();if(delta<=0){return}[].push.apply(this._physicalItems,this._c
reatePool(delta));[].push.apply(this._physicalSizes,new Array(delta));this._phys
icalCount=prevPhysicalCount+delta;if(this._physicalStart>this._physicalEnd&&this
._isIndexRendered(this._focusedIndex)&&this._getPhysicalIndex(this._focusedIndex
)<this._physicalEnd){this._physicalStart=this._physicalStart+delta}this._update(
);this._templateCost=(window.performance.now()-ts)/delta},_render:function(){if(
this.isAttached&&this._isVisible){if(this._physicalCount===0){this.updateViewpor
tBoundaries();this._increasePool(DEFAULT_PHYSICAL_COUNT)}else{var reusables=this
._getReusables(true);this._physicalTop=reusables.physicalTop;this._virtualStart=
this._virtualStart+reusables.indexes.length;this._physicalStart=this._physicalSt
art+reusables.indexes.length;this._update(reusables.indexes);this._update()}}},_
ensureTemplatized:function(){if(!this.ctor){var props={};props.__key__=true;prop
s[this.as]=true;props[this.indexAs]=true;props[this.selectedAs]=true;props.tabIn
dex=true;this._instanceProps=props;this._userTemplate=Polymer.dom(this).querySel
ector("template");if(this._userTemplate){this.templatize(this._userTemplate)}els
e{console.warn("iron-list requires a template to be provided in light-dom")}}},_
getStampedChildren:function(){return this._physicalItems},_forwardInstancePath:f
unction(inst,path,value){if(path.indexOf(this.as+".")===0){this.notifyPath("item
s."+inst.__key__+"."+path.slice(this.as.length+1),value)}},_forwardParentProp:fu
nction(prop,value){if(this._physicalItems){this._physicalItems.forEach(function(
item){item._templateInstance[prop]=value},this)}},_forwardParentPath:function(pa
th,value){if(this._physicalItems){this._physicalItems.forEach(function(item){ite
m._templateInstance.notifyPath(path,value,true)},this)}},_forwardItemPath:functi
on(path,value){if(!this._physicalIndexForKey){return}var dot=path.indexOf(".");v
ar key=path.substring(0,dot<0?path.length:dot);var idx=this._physicalIndexForKey
[key];var offscreenItem=this._offscreenFocusedItem;var el=offscreenItem&&offscre
enItem._templateInstance.__key__===key?offscreenItem:this._physicalItems[idx];if
(!el||el._templateInstance.__key__!==key){return}if(dot>=0){path=this.as+"."+pat
h.substring(dot+1);el._templateInstance.notifyPath(path,value,true)}else{var cur
rentItem=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===current
Item){this.set("selectedItem",value)}el._templateInstance[this.as]=value}},_item
sChanged:function(change){if(change.path==="items"){this._virtualStart=0;this._p
hysicalTop=0;this._virtualCount=this.items?this.items.length:0;this._collection=
this.items?Polymer.Collection.get(this.items):null;this._physicalIndexForKey={};
this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null;this._physicalCou
nt=this._physicalCount||0;this._physicalItems=this._physicalItems||[];this._phys
icalSizes=this._physicalSizes||[];this._physicalStart=0;this._resetScrollPositio
n(0);this._removeFocusedItem();this._debounceTemplate(this._render)}else if(chan
ge.path==="items.splices"){this._adjustVirtualIndex(change.value.indexSplices);t
his._virtualCount=this.items?this.items.length:0;this._debounceTemplate(this._re
nder)}else{this._forwardItemPath(change.path.split(".").slice(1).join("."),chang
e.value)}},_adjustVirtualIndex:function(splices){splices.forEach(function(splice
){splice.removed.forEach(this._removeItem,this);if(splice.index<this._virtualSta
rt){var delta=Math.max(splice.addedCount-splice.removed.length,splice.index-this
._virtualStart);this._virtualStart=this._virtualStart+delta;if(this._focusedInde
x>=0){this._focusedIndex=this._focusedIndex+delta}}},this)},_removeItem:function
(item){this.$.selector.deselect(item);if(this._focusedItem&&this._focusedItem._t
emplateInstance[this.as]===item){this._removeFocusedItem()}},_iterateItems:funct
ion(fn,itemSet){var pidx,vidx,rtn,i;if(arguments.length===2&&itemSet){for(i=0;i<
itemSet.length;i++){pidx=itemSet[i];vidx=this._computeVidx(pidx);if((rtn=fn.call
(this,pidx,vidx))!=null){return rtn}}}else{pidx=this._physicalStart;vidx=this._v
irtualStart;for(;pidx<this._physicalCount;pidx++,vidx++){if((rtn=fn.call(this,pi
dx,vidx))!=null){return rtn}}for(pidx=0;pidx<this._physicalStart;pidx++,vidx++){
if((rtn=fn.call(this,pidx,vidx))!=null){return rtn}}}},_computeVidx:function(pid
x){if(pidx>=this._physicalStart){return this._virtualStart+(pidx-this._physicalS
tart)}return this._virtualStart+(this._physicalCount-this._physicalStart)+pidx},
_assignModels:function(itemSet){this._iterateItems(function(pidx,vidx){var el=th
is._physicalItems[pidx];var inst=el._templateInstance;var item=this.items&&this.
items[vidx];if(item!=null){inst[this.as]=item;inst.__key__=this._collection.getK
ey(item);inst[this.selectedAs]=this.$.selector.isSelected(item);inst[this.indexA
s]=vidx;inst.tabIndex=this._focusedIndex===vidx?0:-1;this._physicalIndexForKey[i
nst.__key__]=pidx;el.removeAttribute("hidden")}else{inst.__key__=null;el.setAttr
ibute("hidden","")}},itemSet)},_updateMetrics:function(itemSet){Polymer.dom.flus
h();var newPhysicalSize=0;var oldPhysicalSize=0;var prevAvgCount=this._physicalA
verageCount;var prevPhysicalAvg=this._physicalAverage;this._iterateItems(functio
n(pidx,vidx){oldPhysicalSize+=this._physicalSizes[pidx]||0;this._physicalSizes[p
idx]=this._physicalItems[pidx].offsetHeight;newPhysicalSize+=this._physicalSizes
[pidx];this._physicalAverageCount+=this._physicalSizes[pidx]?1:0},itemSet);if(th
is.grid){this._updateGridMetrics();this._physicalSize=Math.ceil(this._physicalCo
unt/this._itemsPerRow)*this._rowHeight}else{this._physicalSize=this._physicalSiz
e+newPhysicalSize-oldPhysicalSize}if(this._physicalAverageCount!==prevAvgCount){
this._physicalAverage=Math.round((prevPhysicalAvg*prevAvgCount+newPhysicalSize)/
this._physicalAverageCount)}},_updateGridMetrics:function(){this._itemWidth=this
._physicalCount>0?this._physicalItems[0].getBoundingClientRect().width:200;this.
_rowHeight=this._physicalCount>0?this._physicalItems[0].offsetHeight:200;this._i
temsPerRow=this._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 rowOffset=(this._viewportWidth-totalItemWidth)/2;this._iterateItems(function
(pidx,vidx){var modulus=vidx%this._itemsPerRow;var x=Math.floor(modulus*this._it
emWidth+rowOffset);this.translate3d(x+"px",y+"px",0,this._physicalItems[pidx]);i
f(this._shouldRenderNextRow(vidx)){y+=this._rowHeight}})}else{this._iterateItems
(function(pidx,vidx){this.translate3d(0,y+"px",0,this._physicalItems[pidx]);y+=t
his._physicalSizes[pidx]})}},_getPhysicalSizeIncrement:function(pidx){if(!this.g
rid){return this._physicalSizes[pidx]}if(this._computeVidx(pidx)%this._itemsPerR
ow!==this._itemsPerRow-1){return 0}return this._rowHeight},_shouldRenderNextRow:
function(vidx){return vidx%this._itemsPerRow===this._itemsPerRow-1},_adjustScrol
lPosition:function(){var deltaHeight=this._virtualStart===0?this._physicalTop:Ma
th.min(this._scrollPosition+this._physicalTop,0);if(deltaHeight){this._physicalT
op=this._physicalTop-deltaHeight;if(!IOS_TOUCH_SCROLLING&&this._physicalTop!==0)
{this._resetScrollPosition(this._scrollTop-deltaHeight)}}},_resetScrollPosition:
function(pos){if(this.scrollTarget){this._scrollTop=pos;this._scrollPosition=thi
s._scrollTop}},_updateScrollerSize:function(forceUpdate){if(this.grid){this._est
ScrollHeight=this._virtualRowCount*this._rowHeight}else{this._estScrollHeight=th
is._physicalBottom+Math.max(this._virtualCount-this._physicalCount-this._virtual
Start,0)*this._physicalAverage}forceUpdate=forceUpdate||this._scrollHeight===0;f
orceUpdate=forceUpdate||this._scrollPosition>=this._estScrollHeight-this._physic
alSize;forceUpdate=forceUpdate||this.grid&&this.$.items.style.height<this._estSc
rollHeight;if(forceUpdate||Math.abs(this._estScrollHeight-this._scrollHeight)>=t
his._optPhysicalSize){this.$.items.style.height=this._estScrollHeight+"px";this.
_scrollHeight=this._estScrollHeight}},scrollToItem:function(item){return this.sc
rollToIndex(this.items.indexOf(item))},scrollToIndex:function(idx){if(typeof idx
!=="number"||idx<0||idx>this.items.length-1){return}Polymer.dom.flush();if(this.
_physicalCount===0){return}idx=Math.min(Math.max(idx,0),this._virtualCount-1);if
(!this._isIndexRendered(idx)||idx>=this._maxVirtualStart){this._virtualStart=thi
s.grid?idx-this._itemsPerRow*2:idx-1}this._manageFocus();this._assignModels();th
is._updateMetrics();this._physicalTop=Math.floor(this._virtualStart/this._itemsP
erRow)*this._physicalAverage;var currentTopItem=this._physicalStart;var currentV
irtualItem=this._virtualStart;var targetOffsetTop=0;var hiddenContentSize=this._
hiddenContentSize;while(currentVirtualItem<idx&&targetOffsetTop<=hiddenContentSi
ze){targetOffsetTop=targetOffsetTop+this._getPhysicalSizeIncrement(currentTopIte
m);currentTopItem=(currentTopItem+1)%this._physicalCount;currentVirtualItem++}th
is._updateScrollerSize(true);this._positionItems();this._resetScrollPosition(thi
s._physicalTop+this._scrollerPaddingTop+targetOffsetTop);this._increasePoolIfNee
ded();this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null},_resetAver
age:function(){this._physicalAverage=0;this._physicalAverageCount=0},_resizeHand
ler:function(){var delta=Math.abs(this._viewportHeight-this._scrollTargetHeight)
;if(IOS&&delta>0&&delta<100){return}Polymer.dom.addDebouncer(this.debounce("_deb
ounceTemplate",function(){this.updateViewportBoundaries();this._render();if(this
._isVisible){this.toggleScrollListener(true);if(this._physicalCount>0){this._res
etAverage();this.scrollToIndex(this.firstVisibleIndex)}}else{this.toggleScrollLi
stener(false)}}.bind(this),1))},_getModelFromItem:function(item){var key=this._c
ollection.getKey(item);var pidx=this._physicalIndexForKey[key];if(pidx!=null){re
turn this._physicalItems[pidx]._templateInstance}return null},_getNormalizedItem
:function(item){if(this._collection.getKey(item)===undefined){if(typeof item==="
number"){item=this.items[item];if(!item){throw new RangeError("<item> not found"
)}return item}throw new TypeError("<item> should be a valid item")}return item},
selectItem:function(item){item=this._getNormalizedItem(item);var model=this._get
ModelFromItem(item);if(!this.multiSelection&&this.selectedItem){this.deselectIte
m(this.selectedItem)}if(model){model[this.selectedAs]=true}this.$.selector.selec
t(item);this.updateSizeForItem(item)},deselectItem:function(item){item=this._get
NormalizedItem(item);var model=this._getModelFromItem(item);if(model){model[this
.selectedAs]=false}this.$.selector.deselect(item);this.updateSizeForItem(item)},
toggleSelectionForItem:function(item){item=this._getNormalizedItem(item);if(this
.$.selector.isSelected(item)){this.deselectItem(item)}else{this.selectItem(item)
}},clearSelection:function(){function unselect(item){var model=this._getModelFro
mItem(item);if(model){model[this.selectedAs]=false}}if(Array.isArray(this.select
edItems)){this.selectedItems.forEach(unselect,this)}else if(this.selectedItem){u
nselect.call(this,this.selectedItem)}this.$.selector.clearSelection()},_selectio
nEnabledChanged:function(selectionEnabled){var handler=selectionEnabled?this.lis
ten:this.unlisten;handler.call(this,this,"tap","_selectionHandler")},_selectionH
andler:function(e){var model=this.modelForElement(e.target);if(!model){return}va
r modelTabIndex,activeElTabIndex;var target=Polymer.dom(e).path[0];var activeEl=
Polymer.dom(this.domHost?this.domHost.root:document).activeElement;var physicalI
tem=this._physicalItems[this._getPhysicalIndex(model[this.indexAs])];if(target.l
ocalName==="input"||target.localName==="button"||target.localName==="select"){re
turn}modelTabIndex=model.tabIndex;model.tabIndex=SECRET_TABINDEX;activeElTabInde
x=activeEl?activeEl.tabIndex:-1;model.tabIndex=modelTabIndex;if(activeEl&&physic
alItem!==activeEl&&physicalItem.contains(activeEl)&&activeElTabIndex!==SECRET_TA
BINDEX){return}this.toggleSelectionForItem(model[this.as])},_multiSelectionChang
ed:function(multiSelection){this.clearSelection();this.$.selector.multi=multiSel
ection},updateSizeForItem:function(item){item=this._getNormalizedItem(item);var
key=this._collection.getKey(item);var pidx=this._physicalIndexForKey[key];if(pid
x!=null){this._updateMetrics([pidx]);this._positionItems()}},_manageFocus:functi
on(){var fidx=this._focusedIndex;if(fidx>=0&&fidx<this._virtualCount){if(this._i
sIndexRendered(fidx)){this._restoreFocusedItem()}else{this._createFocusBackfillI
tem()}}else if(this._virtualCount>0&&this._physicalCount>0){this._focusedIndex=t
his._virtualStart;this._focusedItem=this._physicalItems[this._physicalStart]}},_
isIndexRendered:function(idx){return idx>=this._virtualStart&&idx<=this._virtual
End},_isIndexVisible:function(idx){return idx>=this.firstVisibleIndex&&idx<=this
.lastVisibleIndex},_getPhysicalIndex:function(idx){return this._physicalIndexFor
Key[this._collection.getKey(this._getNormalizedItem(idx))]},_focusPhysicalItem:f
unction(idx){if(idx<0||idx>=this._virtualCount){return}this._restoreFocusedItem(
);if(!this._isIndexRendered(idx)){this.scrollToIndex(idx)}var physicalItem=this.
_physicalItems[this._getPhysicalIndex(idx)];var model=physicalItem._templateInst
ance;var focusable;model.tabIndex=SECRET_TABINDEX;if(physicalItem.tabIndex===SEC
RET_TABINDEX){focusable=physicalItem}if(!focusable){focusable=Polymer.dom(physic
alItem).querySelector('[tabindex="'+SECRET_TABINDEX+'"]')}model.tabIndex=0;this.
_focusedIndex=idx;focusable&&focusable.focus()},_removeFocusedItem:function(){if
(this._offscreenFocusedItem){Polymer.dom(this).removeChild(this._offscreenFocuse
dItem)}this._offscreenFocusedItem=null;this._focusBackfillItem=null;this._focuse
dItem=null;this._focusedIndex=-1},_createFocusBackfillItem:function(){var fidx=t
his._focusedIndex;var pidx=this._getPhysicalIndex(fidx);if(this._offscreenFocuse
dItem||pidx==null||fidx<0){return}if(!this._focusBackfillItem){var stampedTempla
te=this.stamp(null);this._focusBackfillItem=stampedTemplate.root.querySelector("
*");Polymer.dom(this).appendChild(stampedTemplate.root)}this._offscreenFocusedIt
em=this._physicalItems[pidx];this._offscreenFocusedItem._templateInstance.tabInd
ex=0;this._physicalItems[pidx]=this._focusBackfillItem;this.translate3d(0,HIDDEN
_Y,0,this._offscreenFocusedItem)},_restoreFocusedItem:function(){var pidx,fidx=t
his._focusedIndex;if(!this._offscreenFocusedItem||this._focusedIndex<0){return}t
his._assignModels();pidx=this._getPhysicalIndex(fidx);if(pidx!=null){this._focus
BackfillItem=this._physicalItems[pidx];this._focusBackfillItem._templateInstance
.tabIndex=-1;this._physicalItems[pidx]=this._offscreenFocusedItem;this._offscree
nFocusedItem=null;this.translate3d(0,HIDDEN_Y,0,this._focusBackfillItem)}},_didF
ocus:function(e){var targetModel=this.modelForElement(e.target);var focusedModel
=this._focusedItem?this._focusedItem._templateInstance:null;var hasOffscreenFocu
sedItem=this._offscreenFocusedItem!==null;var fidx=this._focusedIndex;if(!target
Model||!focusedModel){return}if(focusedModel===targetModel){if(!this._isIndexVis
ible(fidx)){this.scrollToIndex(fidx)}}else{this._restoreFocusedItem();focusedMod
el.tabIndex=-1;targetModel.tabIndex=0;fidx=targetModel[this.indexAs];this._focus
edIndex=fidx;this._focusedItem=this._physicalItems[this._getPhysicalIndex(fidx)]
;if(hasOffscreenFocusedItem&&!this._offscreenFocusedItem){this._update()}}},_did
MoveUp:function(){this._focusPhysicalItem(this._focusedIndex-1)},_didMoveDown:fu
nction(e){e.detail.keyboardEvent.preventDefault();this._focusPhysicalItem(this._
focusedIndex+1)},_didEnter:function(e){this._focusPhysicalItem(this._focusedInde
x);this._selectionHandler(e.detail.keyboardEvent)}})})();Polymer({is:"iron-scrol
l-threshold",properties:{upperThreshold:{type:Number,value:100},lowerThreshold:{
type:Number,value:100},upperTriggered:{type:Boolean,value:false,notify:true,read
Only:true},lowerTriggered:{type:Boolean,value:false,notify:true,readOnly:true},h
orizontal:{type:Boolean,value:false}},behaviors:[Polymer.IronScrollTargetBehavio
r],observers:["_setOverflow(scrollTarget)","_initCheck(horizontal, isAttached)"]
,get _defaultScrollTarget(){return this},_setOverflow:function(scrollTarget){thi
s.style.overflow=scrollTarget===this?"auto":""},_scrollHandler:function(){var TH
ROTTLE_THRESHOLD=200;if(!this.isDebouncerActive("_checkTheshold")){this.debounce
("_checkTheshold",function(){this.checkScrollThesholds()},THROTTLE_THRESHOLD)}},
_initCheck:function(horizontal,isAttached){if(isAttached){this.debounce("_init",
function(){this.clearTriggers();this.checkScrollThesholds()})}},checkScrollThesh
olds:function(){if(!this.scrollTarget||this.lowerTriggered&&this.upperTriggered)
{return}var upperScrollValue=this.horizontal?this._scrollLeft:this._scrollTop;va
r lowerScrollValue=this.horizontal?this.scrollTarget.scrollWidth-this._scrollTar
getWidth-this._scrollLeft:this.scrollTarget.scrollHeight-this._scrollTargetHeigh
t-this._scrollTop;if(upperScrollValue<=this.upperThreshold&&!this.upperTriggered
){this._setUpperTriggered(true);this.fire("upper-threshold")}if(lowerScrollValue
<=this.lowerThreshold&&!this.lowerTriggered){this._setLowerTriggered(true);this.
fire("lower-threshold")}},clearTriggers:function(){this._setUpperTriggered(false
);this._setLowerTriggered(false)}}); | 40 Polymer({is:"history-toolbar",properties:{count:{type:Number,value:0,observer:"c
hangeToolbarView_"},itemsSelected_:{type:Boolean,value:false,reflectToAttribute:
true},searchTerm:{type:String,observer:"searchTermChanged_",notify:true},spinner
Active:{type:Boolean,value:false},hasDrawer:{type:Boolean,reflectToAttribute:tru
e},showSyncNotice:Boolean,isGroupedMode:{type:Boolean,reflectToAttribute:true},g
roupedRange:{type:Number,reflectToAttribute:true,notify:true},groupedOffset:{typ
e:Number,notify:true},querying:Boolean,hasMoreResults:Boolean,queryStartTime:Str
ing,queryEndTime:String,showMenuPromo:Boolean},get searchField(){return this.$["
main-toolbar"].getSearchField()},showSearchField:function(){this.searchField.sho
wAndFocus()},changeToolbarView_:function(){this.itemsSelected_=this.count>0},sea
rchTermChanged_:function(){if(this.searchField.getValue()!=this.searchTerm){this
.searchField.showAndFocus();this.searchField.setValue(this.searchTerm)}},onSearc
hChanged_:function(event){this.searchTerm=event.detail},onInfoButtonTap_:functio
n(){var dropdown=this.$.syncNotice.get();dropdown.positionTarget=this.$$("#info-
button-icon");if(dropdown.style.display=="none")dropdown.open()},onClearSelectio
nTap_:function(){this.fire("unselect-all")},onDeleteTap_:function(){this.fire("d
elete-selected")},deletingAllowed_:function(){return loadTimeData.getBoolean("al
lowDeletingHistory")},numberOfItemsSelected_:function(count){return count>0?load
TimeData.getStringF("itemsSelected",count):""},getHistoryInterval_:function(quer
yStartTime,queryEndTime){return loadTimeData.getStringF("historyInterval",queryS
tartTime,queryEndTime)},onTodayTap_:function(){if(!this.querying)this.groupedOff
set=0},onPrevTap_:function(){if(!this.querying)this.groupedOffset=this.groupedOf
fset+1},onNextTap_:function(){if(!this.querying)this.groupedOffset=this.groupedO
ffset-1},isToday_:function(){return this.groupedOffset==0}}); |
| 41 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 42 // Use of this source code is governed by a BSD-style license that can be |
| 43 // found in the LICENSE file. |
| 44 Polymer({is:"cr-action-menu","extends":"dialog",options_:null,anchorElement_:nul
l,onWindowResize_:null,hostAttributes:{tabindex:0},listeners:{keydown:"onKeyDown
_",tap:"onTap_"},attached:function(){this.options_=this.querySelectorAll(".dropd
own-item")},detached:function(){this.removeResizeListener_()},removeResizeListen
er_:function(){window.removeEventListener("resize",this.onWindowResize_)},onTap_
:function(e){if(e.target==this){this.close();e.stopPropagation()}},onKeyDown_:fu
nction(e){if(e.key=="Tab"||e.key=="Escape"){this.close();e.preventDefault();retu
rn}if(e.key!=="ArrowDown"&&e.key!=="ArrowUp")return;var nextOption=this.getNextO
ption_(e.key=="ArrowDown"?1:-1);if(nextOption)nextOption.focus();e.preventDefaul
t()},getNextOption_:function(step){var counter=0;var nextOption=null;var numOpti
ons=this.options_.length;var focusedIndex=Array.prototype.indexOf.call(this.opti
ons_,this.root.activeElement);do{focusedIndex=(numOptions+focusedIndex+step)%num
Options;nextOption=this.options_[focusedIndex];if(nextOption.disabled||nextOptio
n.hidden)nextOption=null;counter++}while(!nextOption&&counter<numOptions);return
nextOption},close:function(){this.removeResizeListener_();HTMLDialogElement.pro
totype.close.call(this);this.anchorElement_.focus();this.anchorElement_=null},sh
owAt:function(anchorElement){this.anchorElement_=anchorElement;this.onWindowResi
ze_=this.onWindowResize_||function(){if(this.open)this.close()}.bind(this);windo
w.addEventListener("resize",this.onWindowResize_);this.showModal();var rect=this
.anchorElement_.getBoundingClientRect();if(getComputedStyle(this.anchorElement_)
.direction=="rtl"){var right=window.innerWidth-rect.left-this.offsetWidth;this.s
tyle.right=right+"px"}else{var left=rect.right-this.offsetWidth;this.style.left=
left+"px"}var top=rect.top+this.offsetHeight<=window.innerHeight?rect.top:rect.b
ottom-this.offsetHeight-Math.max(rect.bottom-window.innerHeight,0);this.style.to
p=top+"px"}});(function(){"use strict";Polymer.IronA11yAnnouncer=Polymer({is:"ir
on-a11y-announcer",properties:{mode:{type:String,value:"polite"},_text:{type:Str
ing,value:""}},created:function(){if(!Polymer.IronA11yAnnouncer.instance){Polyme
r.IronA11yAnnouncer.instance=this}document.body.addEventListener("iron-announce"
,this._onIronAnnounce.bind(this))},announce:function(text){this._text="";this.as
ync(function(){this._text=text},100)},_onIronAnnounce:function(event){if(event.d
etail&&event.detail.text){this.announce(event.detail.text)}}});Polymer.IronA11yA
nnouncer.instance=null;Polymer.IronA11yAnnouncer.requestAvailability=function(){
if(!Polymer.IronA11yAnnouncer.instance){Polymer.IronA11yAnnouncer.instance=docum
ent.createElement("iron-a11y-announcer")}document.body.appendChild(Polymer.IronA
11yAnnouncer.instance)}})();(function(){var IOS=navigator.userAgent.match(/iP(?:
hone|ad;(?: U;)? CPU) OS (\d+)/);var IOS_TOUCH_SCROLLING=IOS&&IOS[1]>=8;var DEFA
ULT_PHYSICAL_COUNT=3;var HIDDEN_Y="-10000px";var ITEM_WIDTH=0;var ITEM_HEIGHT=1;
var SECRET_TABINDEX=-100;Polymer({is:"iron-list",properties:{items:{type:Array},
maxPhysicalCount:{type:Number,value:500},as:{type:String,value:"item"},indexAs:{
type:String,value:"index"},selectedAs:{type:String,value:"selected"},grid:{type:
Boolean,value:false,reflectToAttribute:true},selectionEnabled:{type:Boolean,valu
e:false},selectedItem:{type:Object,notify:true},selectedItems:{type:Object,notif
y:true},multiSelection:{type:Boolean,value:false}},observers:["_itemsChanged(ite
ms.*)","_selectionEnabledChanged(selectionEnabled)","_multiSelectionChanged(mult
iSelection)","_setOverflow(scrollTarget)"],behaviors:[Polymer.Templatizer,Polyme
r.IronResizableBehavior,Polymer.IronA11yKeysBehavior,Polymer.IronScrollTargetBeh
avior],keyBindings:{up:"_didMoveUp",down:"_didMoveDown",enter:"_didEnter"},_rati
o:.5,_scrollerPaddingTop:0,_scrollPosition:0,_physicalSize:0,_physicalAverage:0,
_physicalAverageCount:0,_physicalTop:0,_virtualCount:0,_physicalIndexForKey:null
,_estScrollHeight:0,_scrollHeight:0,_viewportHeight:0,_viewportWidth:0,_physical
Items:null,_physicalSizes:null,_firstVisibleIndexVal:null,_lastVisibleIndexVal:n
ull,_collection:null,_maxPages:2,_focusedItem:null,_focusedIndex:-1,_offscreenFo
cusedItem:null,_focusBackfillItem:null,_itemsPerRow:1,_itemWidth:0,_rowHeight:0,
_templateCost:0,get _physicalBottom(){return this._physicalTop+this._physicalSiz
e},get _scrollBottom(){return this._scrollPosition+this._viewportHeight},get _vi
rtualEnd(){return this._virtualStart+this._physicalCount-1},get _hiddenContentSi
ze(){var size=this.grid?this._physicalRows*this._rowHeight:this._physicalSize;re
turn size-this._viewportHeight},get _maxScrollTop(){return this._estScrollHeight
-this._viewportHeight+this._scrollerPaddingTop},_minVirtualStart:0,get _maxVirtu
alStart(){return Math.max(0,this._virtualCount-this._physicalCount)},_virtualSta
rtVal:0,set _virtualStart(val){this._virtualStartVal=Math.min(this._maxVirtualSt
art,Math.max(this._minVirtualStart,val))},get _virtualStart(){return this._virtu
alStartVal||0},_physicalStartVal:0,set _physicalStart(val){this._physicalStartVa
l=val%this._physicalCount;if(this._physicalStartVal<0){this._physicalStartVal=th
is._physicalCount+this._physicalStartVal}this._physicalEnd=(this._physicalStart+
this._physicalCount-1)%this._physicalCount},get _physicalStart(){return this._ph
ysicalStartVal||0},_physicalCountVal:0,set _physicalCount(val){this._physicalCou
ntVal=val;this._physicalEnd=(this._physicalStart+this._physicalCount-1)%this._ph
ysicalCount},get _physicalCount(){return this._physicalCountVal},_physicalEnd:0,
get _optPhysicalSize(){if(this.grid){return this._estRowsInView*this._rowHeight*
this._maxPages}return this._viewportHeight*this._maxPages},get _isVisible(){retu
rn Boolean(this.offsetWidth||this.offsetHeight)},get firstVisibleIndex(){if(this
._firstVisibleIndexVal===null){var physicalOffset=Math.floor(this._physicalTop+t
his._scrollerPaddingTop);this._firstVisibleIndexVal=this._iterateItems(function(
pidx,vidx){physicalOffset+=this._getPhysicalSizeIncrement(pidx);if(physicalOffse
t>this._scrollPosition){return this.grid?vidx-vidx%this._itemsPerRow:vidx}if(thi
s.grid&&this._virtualCount-1===vidx){return vidx-vidx%this._itemsPerRow}})||0}re
turn this._firstVisibleIndexVal},get lastVisibleIndex(){if(this._lastVisibleInde
xVal===null){if(this.grid){var lastIndex=this.firstVisibleIndex+this._estRowsInV
iew*this._itemsPerRow-1;this._lastVisibleIndexVal=Math.min(this._virtualCount,la
stIndex)}else{var physicalOffset=this._physicalTop;this._iterateItems(function(p
idx,vidx){if(physicalOffset<this._scrollBottom){this._lastVisibleIndexVal=vidx}e
lse{return true}physicalOffset+=this._getPhysicalSizeIncrement(pidx)})}}return t
his._lastVisibleIndexVal},get _defaultScrollTarget(){return this},get _virtualRo
wCount(){return Math.ceil(this._virtualCount/this._itemsPerRow)},get _estRowsInV
iew(){return Math.ceil(this._viewportHeight/this._rowHeight)},get _physicalRows(
){return Math.ceil(this._physicalCount/this._itemsPerRow)},ready:function(){this
.addEventListener("focus",this._didFocus.bind(this),true)},attached:function(){i
f(this._physicalCount===0){this._debounceTemplate(this._render)}this.listen(this
,"iron-resize","_resizeHandler")},detached:function(){this.unlisten(this,"iron-r
esize","_resizeHandler")},_setOverflow:function(scrollTarget){this.style.webkitO
verflowScrolling=scrollTarget===this?"touch":"";this.style.overflow=scrollTarget
===this?"auto":""},updateViewportBoundaries:function(){this._scrollerPaddingTop=
this.scrollTarget===this?0:parseInt(window.getComputedStyle(this)["padding-top"]
,10);this._viewportWidth=this.$.items.offsetWidth;this._viewportHeight=this._scr
ollTargetHeight;this.grid&&this._updateGridMetrics()},_scrollHandler:function(){
var scrollTop=Math.max(0,Math.min(this._maxScrollTop,this._scrollTop));var delta
=scrollTop-this._scrollPosition;var isScrollingDown=delta>=0;this._scrollPositio
n=scrollTop;this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null;if(Ma
th.abs(delta)>this._physicalSize){var idxAdjustment=Math.round(delta/this._physi
calAverage)*this._itemsPerRow;this._physicalTop=this._physicalTop+delta;this._vi
rtualStart=this._virtualStart+idxAdjustment;this._physicalStart=this._physicalSt
art+idxAdjustment;this._update()}else{var reusables=this._getReusables(isScrolli
ngDown);if(isScrollingDown){this._physicalTop=reusables.physicalTop;this._virtua
lStart=this._virtualStart+reusables.indexes.length;this._physicalStart=this._phy
sicalStart+reusables.indexes.length}else{this._virtualStart=this._virtualStart-r
eusables.indexes.length;this._physicalStart=this._physicalStart-reusables.indexe
s.length}if(reusables.indexes.length===0){this._increasePoolIfNeeded()}else{this
._update(reusables.indexes,isScrollingDown?null:reusables.indexes)}}},_getReusab
les:function(fromTop){var ith,lastIth,offsetContent,physicalItemHeight;var idxs=
[];var protectedOffsetContent=this._hiddenContentSize*this._ratio;var virtualSta
rt=this._virtualStart;var virtualEnd=this._virtualEnd;var physicalCount=this._ph
ysicalCount;var physicalTop=this._physicalTop+this._scrollerPaddingTop;var scrol
lTop=this._scrollTop;var scrollBottom=this._scrollBottom;if(fromTop){ith=this._p
hysicalStart;lastIth=this._physicalEnd;offsetContent=scrollTop-physicalTop}else{
ith=this._physicalEnd;lastIth=this._physicalStart;offsetContent=this._physicalBo
ttom-scrollBottom}while(true){physicalItemHeight=this._getPhysicalSizeIncrement(
ith);offsetContent=offsetContent-physicalItemHeight;if(idxs.length>=physicalCoun
t||offsetContent<=protectedOffsetContent){break}if(fromTop){if(virtualEnd+idxs.l
ength+1>=this._virtualCount){break}if(physicalTop+physicalItemHeight>=scrollTop)
{break}idxs.push(ith);physicalTop=physicalTop+physicalItemHeight;ith=(ith+1)%phy
sicalCount}else{if(virtualStart-idxs.length<=0){break}if(physicalTop+this._physi
calSize-physicalItemHeight<=scrollBottom){break}idxs.push(ith);physicalTop=physi
calTop-physicalItemHeight;ith=ith===0?physicalCount-1:ith-1}}return{indexes:idxs
,physicalTop:physicalTop-this._scrollerPaddingTop}},_update:function(itemSet,mov
ingUp){if(itemSet&&itemSet.length===0){return}this._manageFocus();this._assignMo
dels(itemSet);this._updateMetrics(itemSet);if(movingUp){while(movingUp.length){v
ar idx=movingUp.pop();this._physicalTop-=this._getPhysicalSizeIncrement(idx)}}th
is._positionItems();this._updateScrollerSize();this._increasePoolIfNeeded()},_cr
eatePool:function(size){var physicalItems=new Array(size);this._ensureTemplatize
d();for(var i=0;i<size;i++){var inst=this.stamp(null);physicalItems[i]=inst.root
.querySelector("*");Polymer.dom(this).appendChild(inst.root)}return physicalItem
s},_increasePoolIfNeeded:function(){if(this._viewportHeight===0){return false}va
r self=this;var isClientFull=this._physicalBottom>=this._scrollBottom&&this._phy
sicalTop<=this._scrollPosition;if(this._physicalSize>=this._optPhysicalSize&&isC
lientFull){return false}var maxPoolSize=Math.round(this._physicalCount*.5);if(!i
sClientFull){this._debounceTemplate(this._increasePool.bind(this,maxPoolSize));r
eturn true}this._yield(function(){self._increasePool(Math.min(maxPoolSize,Math.m
ax(1,Math.round(50/self._templateCost))))});return true},_yield:function(cb){var
g=window;var handle=g.requestIdleCallback?g.requestIdleCallback(cb):g.setTimeou
t(cb,16);Polymer.dom.addDebouncer({complete:function(){g.cancelIdleCallback?g.ca
ncelIdleCallback(handle):g.clearTimeout(handle);cb()}})},_increasePool:function(
missingItems){var nextPhysicalCount=Math.min(this._physicalCount+missingItems,th
is._virtualCount-this._virtualStart,Math.max(this.maxPhysicalCount,DEFAULT_PHYSI
CAL_COUNT));var prevPhysicalCount=this._physicalCount;var delta=nextPhysicalCoun
t-prevPhysicalCount;var ts=window.performance.now();if(delta<=0){return}[].push.
apply(this._physicalItems,this._createPool(delta));[].push.apply(this._physicalS
izes,new Array(delta));this._physicalCount=prevPhysicalCount+delta;if(this._phys
icalStart>this._physicalEnd&&this._isIndexRendered(this._focusedIndex)&&this._ge
tPhysicalIndex(this._focusedIndex)<this._physicalEnd){this._physicalStart=this._
physicalStart+delta}this._update();this._templateCost=(window.performance.now()-
ts)/delta},_render:function(){if(this.isAttached&&this._isVisible){if(this._phys
icalCount===0){this.updateViewportBoundaries();this._increasePool(DEFAULT_PHYSIC
AL_COUNT)}else{var reusables=this._getReusables(true);this._physicalTop=reusable
s.physicalTop;this._virtualStart=this._virtualStart+reusables.indexes.length;thi
s._physicalStart=this._physicalStart+reusables.indexes.length;this._update(reusa
bles.indexes);this._update()}}},_ensureTemplatized:function(){if(!this.ctor){var
props={};props.__key__=true;props[this.as]=true;props[this.indexAs]=true;props[
this.selectedAs]=true;props.tabIndex=true;this._instanceProps=props;this._userTe
mplate=Polymer.dom(this).querySelector("template");if(this._userTemplate){this.t
emplatize(this._userTemplate)}else{console.warn("iron-list requires a template t
o be provided in light-dom")}}},_getStampedChildren:function(){return this._phys
icalItems},_forwardInstancePath:function(inst,path,value){if(path.indexOf(this.a
s+".")===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){if(this._physicalItems){this._physica
lItems.forEach(function(item){item._templateInstance.notifyPath(path,value,true)
},this)}},_forwardItemPath:function(path,value){if(!this._physicalIndexForKey){r
eturn}var dot=path.indexOf(".");var key=path.substring(0,dot<0?path.length:dot);
var idx=this._physicalIndexForKey[key];var offscreenItem=this._offscreenFocusedI
tem;var el=offscreenItem&&offscreenItem._templateInstance.__key__===key?offscree
nItem:this._physicalItems[idx];if(!el||el._templateInstance.__key__!==key){retur
n}if(dot>=0){path=this.as+"."+path.substring(dot+1);el._templateInstance.notifyP
ath(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(th
is.selectedItems[i]===currentItem){this.set("selectedItems."+i,value);break}}}el
se if(this.selectedItem===currentItem){this.set("selectedItem",value)}el._templa
teInstance[this.as]=value}},_itemsChanged:function(change){if(change.path==="ite
ms"){this._virtualStart=0;this._physicalTop=0;this._virtualCount=this.items?this
.items.length:0;this._collection=this.items?Polymer.Collection.get(this.items):n
ull;this._physicalIndexForKey={};this._firstVisibleIndexVal=null;this._lastVisib
leIndexVal=null;this._physicalCount=this._physicalCount||0;this._physicalItems=t
his._physicalItems||[];this._physicalSizes=this._physicalSizes||[];this._physica
lStart=0;this._resetScrollPosition(0);this._removeFocusedItem();this._debounceTe
mplate(this._render)}else if(change.path==="items.splices"){this._adjustVirtualI
ndex(change.value.indexSplices);this._virtualCount=this.items?this.items.length:
0;this._debounceTemplate(this._render)}else{this._forwardItemPath(change.path.sp
lit(".").slice(1).join("."),change.value)}},_adjustVirtualIndex:function(splices
){splices.forEach(function(splice){splice.removed.forEach(this._removeItem,this)
;if(splice.index<this._virtualStart){var delta=Math.max(splice.addedCount-splice
.removed.length,splice.index-this._virtualStart);this._virtualStart=this._virtua
lStart+delta;if(this._focusedIndex>=0){this._focusedIndex=this._focusedIndex+del
ta}}},this)},_removeItem:function(item){this.$.selector.deselect(item);if(this._
focusedItem&&this._focusedItem._templateInstance[this.as]===item){this._removeFo
cusedItem()}},_iterateItems:function(fn,itemSet){var pidx,vidx,rtn,i;if(argument
s.length===2&&itemSet){for(i=0;i<itemSet.length;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<th
is._physicalStart;pidx++,vidx++){if((rtn=fn.call(this,pidx,vidx))!=null){return
rtn}}}},_computeVidx:function(pidx){if(pidx>=this._physicalStart){return this._v
irtualStart+(pidx-this._physicalStart)}return this._virtualStart+(this._physical
Count-this._physicalStart)+pidx},_assignModels:function(itemSet){this._iterateIt
ems(function(pidx,vidx){var el=this._physicalItems[pidx];var inst=el._templateIn
stance;var item=this.items&&this.items[vidx];if(item!=null){inst[this.as]=item;i
nst.__key__=this._collection.getKey(item);inst[this.selectedAs]=this.$.selector.
isSelected(item);inst[this.indexAs]=vidx;inst.tabIndex=this._focusedIndex===vidx
?0:-1;this._physicalIndexForKey[inst.__key__]=pidx;el.removeAttribute("hidden")}
else{inst.__key__=null;el.setAttribute("hidden","")}},itemSet)},_updateMetrics:f
unction(itemSet){Polymer.dom.flush();var newPhysicalSize=0;var oldPhysicalSize=0
;var prevAvgCount=this._physicalAverageCount;var prevPhysicalAvg=this._physicalA
verage;this._iterateItems(function(pidx,vidx){oldPhysicalSize+=this._physicalSiz
es[pidx]||0;this._physicalSizes[pidx]=this._physicalItems[pidx].offsetHeight;new
PhysicalSize+=this._physicalSizes[pidx];this._physicalAverageCount+=this._physic
alSizes[pidx]?1:0},itemSet);if(this.grid){this._updateGridMetrics();this._physic
alSize=Math.ceil(this._physicalCount/this._itemsPerRow)*this._rowHeight}else{thi
s._physicalSize=this._physicalSize+newPhysicalSize-oldPhysicalSize}if(this._phys
icalAverageCount!==prevAvgCount){this._physicalAverage=Math.round((prevPhysicalA
vg*prevAvgCount+newPhysicalSize)/this._physicalAverageCount)}},_updateGridMetric
s:function(){this._itemWidth=this._physicalCount>0?this._physicalItems[0].getBou
ndingClientRect().width:200;this._rowHeight=this._physicalCount>0?this._physical
Items[0].offsetHeight:200;this._itemsPerRow=this._itemWidth?Math.floor(this._vie
wportWidth/this._itemWidth):this._itemsPerRow},_positionItems:function(){this._a
djustScrollPosition();var y=this._physicalTop;if(this.grid){var totalItemWidth=t
his._itemsPerRow*this._itemWidth;var rowOffset=(this._viewportWidth-totalItemWid
th)/2;this._iterateItems(function(pidx,vidx){var modulus=vidx%this._itemsPerRow;
var x=Math.floor(modulus*this._itemWidth+rowOffset);this.translate3d(x+"px",y+"p
x",0,this._physicalItems[pidx]);if(this._shouldRenderNextRow(vidx)){y+=this._row
Height}})}else{this._iterateItems(function(pidx,vidx){this.translate3d(0,y+"px",
0,this._physicalItems[pidx]);y+=this._physicalSizes[pidx]})}},_getPhysicalSizeIn
crement: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(vidx){return vidx%this._itemsPerRow===
this._itemsPerRow-1},_adjustScrollPosition:function(){var deltaHeight=this._virt
ualStart===0?this._physicalTop:Math.min(this._scrollPosition+this._physicalTop,0
);if(deltaHeight){this._physicalTop=this._physicalTop-deltaHeight;if(!IOS_TOUCH_
SCROLLING&&this._physicalTop!==0){this._resetScrollPosition(this._scrollTop-delt
aHeight)}}},_resetScrollPosition:function(pos){if(this.scrollTarget){this._scrol
lTop=pos;this._scrollPosition=this._scrollTop}},_updateScrollerSize:function(for
ceUpdate){if(this.grid){this._estScrollHeight=this._virtualRowCount*this._rowHei
ght}else{this._estScrollHeight=this._physicalBottom+Math.max(this._virtualCount-
this._physicalCount-this._virtualStart,0)*this._physicalAverage}forceUpdate=forc
eUpdate||this._scrollHeight===0;forceUpdate=forceUpdate||this._scrollPosition>=t
his._estScrollHeight-this._physicalSize;forceUpdate=forceUpdate||this.grid&&this
.$.items.style.height<this._estScrollHeight;if(forceUpdate||Math.abs(this._estSc
rollHeight-this._scrollHeight)>=this._optPhysicalSize){this.$.items.style.height
=this._estScrollHeight+"px";this._scrollHeight=this._estScrollHeight}},scrollToI
tem:function(item){return this.scrollToIndex(this.items.indexOf(item))},scrollTo
Index:function(idx){if(typeof idx!=="number"||idx<0||idx>this.items.length-1){re
turn}Polymer.dom.flush();if(this._physicalCount===0){return}idx=Math.min(Math.ma
x(idx,0),this._virtualCount-1);if(!this._isIndexRendered(idx)||idx>=this._maxVir
tualStart){this._virtualStart=this.grid?idx-this._itemsPerRow*2:idx-1}this._mana
geFocus();this._assignModels();this._updateMetrics();this._physicalTop=Math.floo
r(this._virtualStart/this._itemsPerRow)*this._physicalAverage;var currentTopItem
=this._physicalStart;var currentVirtualItem=this._virtualStart;var targetOffsetT
op=0;var hiddenContentSize=this._hiddenContentSize;while(currentVirtualItem<idx&
&targetOffsetTop<=hiddenContentSize){targetOffsetTop=targetOffsetTop+this._getPh
ysicalSizeIncrement(currentTopItem);currentTopItem=(currentTopItem+1)%this._phys
icalCount;currentVirtualItem++}this._updateScrollerSize(true);this._positionItem
s();this._resetScrollPosition(this._physicalTop+this._scrollerPaddingTop+targetO
ffsetTop);this._increasePoolIfNeeded();this._firstVisibleIndexVal=null;this._las
tVisibleIndexVal=null},_resetAverage:function(){this._physicalAverage=0;this._ph
ysicalAverageCount=0},_resizeHandler:function(){var delta=Math.abs(this._viewpor
tHeight-this._scrollTargetHeight);if(IOS&&delta>0&&delta<100){return}Polymer.dom
.addDebouncer(this.debounce("_debounceTemplate",function(){this.updateViewportBo
undaries();this._render();if(this._isVisible){this.toggleScrollListener(true);if
(this._physicalCount>0){this._resetAverage();this.scrollToIndex(this.firstVisibl
eIndex)}}else{this.toggleScrollListener(false)}}.bind(this),1))},_getModelFromIt
em:function(item){var key=this._collection.getKey(item);var pidx=this._physicalI
ndexForKey[key];if(pidx!=null){return this._physicalItems[pidx]._templateInstanc
e}return null},_getNormalizedItem:function(item){if(this._collection.getKey(item
)===undefined){if(typeof item==="number"){item=this.items[item];if(!item){throw
new RangeError("<item> not found")}return item}throw new TypeError("<item> shoul
d be a valid item")}return item},selectItem:function(item){item=this._getNormali
zedItem(item);var model=this._getModelFromItem(item);if(!this.multiSelection&&th
is.selectedItem){this.deselectItem(this.selectedItem)}if(model){model[this.selec
tedAs]=true}this.$.selector.select(item);this.updateSizeForItem(item)},deselectI
tem:function(item){item=this._getNormalizedItem(item);var model=this._getModelFr
omItem(item);if(model){model[this.selectedAs]=false}this.$.selector.deselect(ite
m);this.updateSizeForItem(item)},toggleSelectionForItem:function(item){item=this
._getNormalizedItem(item);if(this.$.selector.isSelected(item)){this.deselectItem
(item)}else{this.selectItem(item)}},clearSelection:function(){function unselect(
item){var model=this._getModelFromItem(item);if(model){model[this.selectedAs]=fa
lse}}if(Array.isArray(this.selectedItems)){this.selectedItems.forEach(unselect,t
his)}else if(this.selectedItem){unselect.call(this,this.selectedItem)}this.$.sel
ector.clearSelection()},_selectionEnabledChanged:function(selectionEnabled){var
handler=selectionEnabled?this.listen:this.unlisten;handler.call(this,this,"tap",
"_selectionHandler")},_selectionHandler:function(e){var model=this.modelForEleme
nt(e.target);if(!model){return}var modelTabIndex,activeElTabIndex;var target=Pol
ymer.dom(e).path[0];var activeEl=Polymer.dom(this.domHost?this.domHost.root:docu
ment).activeElement;var physicalItem=this._physicalItems[this._getPhysicalIndex(
model[this.indexAs])];if(target.localName==="input"||target.localName==="button"
||target.localName==="select"){return}modelTabIndex=model.tabIndex;model.tabInde
x=SECRET_TABINDEX;activeElTabIndex=activeEl?activeEl.tabIndex:-1;model.tabIndex=
modelTabIndex;if(activeEl&&physicalItem!==activeEl&&physicalItem.contains(active
El)&&activeElTabIndex!==SECRET_TABINDEX){return}this.toggleSelectionForItem(mode
l[this.as])},_multiSelectionChanged:function(multiSelection){this.clearSelection
();this.$.selector.multi=multiSelection},updateSizeForItem:function(item){item=t
his._getNormalizedItem(item);var key=this._collection.getKey(item);var pidx=this
._physicalIndexForKey[key];if(pidx!=null){this._updateMetrics([pidx]);this._posi
tionItems()}},_manageFocus:function(){var fidx=this._focusedIndex;if(fidx>=0&&fi
dx<this._virtualCount){if(this._isIndexRendered(fidx)){this._restoreFocusedItem(
)}else{this._createFocusBackfillItem()}}else if(this._virtualCount>0&&this._phys
icalCount>0){this._focusedIndex=this._virtualStart;this._focusedItem=this._physi
calItems[this._physicalStart]}},_isIndexRendered:function(idx){return idx>=this.
_virtualStart&&idx<=this._virtualEnd},_isIndexVisible:function(idx){return idx>=
this.firstVisibleIndex&&idx<=this.lastVisibleIndex},_getPhysicalIndex:function(i
dx){return this._physicalIndexForKey[this._collection.getKey(this._getNormalized
Item(idx))]},_focusPhysicalItem:function(idx){if(idx<0||idx>=this._virtualCount)
{return}this._restoreFocusedItem();if(!this._isIndexRendered(idx)){this.scrollTo
Index(idx)}var physicalItem=this._physicalItems[this._getPhysicalIndex(idx)];var
model=physicalItem._templateInstance;var focusable;model.tabIndex=SECRET_TABIND
EX;if(physicalItem.tabIndex===SECRET_TABINDEX){focusable=physicalItem}if(!focusa
ble){focusable=Polymer.dom(physicalItem).querySelector('[tabindex="'+SECRET_TABI
NDEX+'"]')}model.tabIndex=0;this._focusedIndex=idx;focusable&&focusable.focus()}
,_removeFocusedItem:function(){if(this._offscreenFocusedItem){Polymer.dom(this).
removeChild(this._offscreenFocusedItem)}this._offscreenFocusedItem=null;this._fo
cusBackfillItem=null;this._focusedItem=null;this._focusedIndex=-1},_createFocusB
ackfillItem:function(){var fidx=this._focusedIndex;var pidx=this._getPhysicalInd
ex(fidx);if(this._offscreenFocusedItem||pidx==null||fidx<0){return}if(!this._foc
usBackfillItem){var stampedTemplate=this.stamp(null);this._focusBackfillItem=sta
mpedTemplate.root.querySelector("*");Polymer.dom(this).appendChild(stampedTempla
te.root)}this._offscreenFocusedItem=this._physicalItems[pidx];this._offscreenFoc
usedItem._templateInstance.tabIndex=0;this._physicalItems[pidx]=this._focusBackf
illItem;this.translate3d(0,HIDDEN_Y,0,this._offscreenFocusedItem)},_restoreFocus
edItem:function(){var pidx,fidx=this._focusedIndex;if(!this._offscreenFocusedIte
m||this._focusedIndex<0){return}this._assignModels();pidx=this._getPhysicalIndex
(fidx);if(pidx!=null){this._focusBackfillItem=this._physicalItems[pidx];this._fo
cusBackfillItem._templateInstance.tabIndex=-1;this._physicalItems[pidx]=this._of
fscreenFocusedItem;this._offscreenFocusedItem=null;this.translate3d(0,HIDDEN_Y,0
,this._focusBackfillItem)}},_didFocus:function(e){var targetModel=this.modelForE
lement(e.target);var focusedModel=this._focusedItem?this._focusedItem._templateI
nstance:null;var hasOffscreenFocusedItem=this._offscreenFocusedItem!==null;var f
idx=this._focusedIndex;if(!targetModel||!focusedModel){return}if(focusedModel===
targetModel){if(!this._isIndexVisible(fidx)){this.scrollToIndex(fidx)}}else{this
._restoreFocusedItem();focusedModel.tabIndex=-1;targetModel.tabIndex=0;fidx=targ
etModel[this.indexAs];this._focusedIndex=fidx;this._focusedItem=this._physicalIt
ems[this._getPhysicalIndex(fidx)];if(hasOffscreenFocusedItem&&!this._offscreenFo
cusedItem){this._update()}}},_didMoveUp:function(){this._focusPhysicalItem(this.
_focusedIndex-1)},_didMoveDown:function(e){e.detail.keyboardEvent.preventDefault
();this._focusPhysicalItem(this._focusedIndex+1)},_didEnter:function(e){this._fo
cusPhysicalItem(this._focusedIndex);this._selectionHandler(e.detail.keyboardEven
t)}})})();Polymer({is:"iron-scroll-threshold",properties:{upperThreshold:{type:N
umber,value:100},lowerThreshold:{type:Number,value:100},upperTriggered:{type:Boo
lean,value:false,notify:true,readOnly:true},lowerTriggered:{type:Boolean,value:f
alse,notify:true,readOnly:true},horizontal:{type:Boolean,value:false}},behaviors
:[Polymer.IronScrollTargetBehavior],observers:["_setOverflow(scrollTarget)","_in
itCheck(horizontal, isAttached)"],get _defaultScrollTarget(){return this},_setOv
erflow:function(scrollTarget){this.style.overflow=scrollTarget===this?"auto":""}
,_scrollHandler:function(){var THROTTLE_THRESHOLD=200;if(!this.isDebouncerActive
("_checkTheshold")){this.debounce("_checkTheshold",function(){this.checkScrollTh
esholds()},THROTTLE_THRESHOLD)}},_initCheck:function(horizontal,isAttached){if(i
sAttached){this.debounce("_init",function(){this.clearTriggers();this.checkScrol
lThesholds()})}},checkScrollThesholds:function(){if(!this.scrollTarget||this.low
erTriggered&&this.upperTriggered){return}var upperScrollValue=this.horizontal?th
is._scrollLeft:this._scrollTop;var lowerScrollValue=this.horizontal?this.scrollT
arget.scrollWidth-this._scrollTargetWidth-this._scrollLeft:this.scrollTarget.scr
ollHeight-this._scrollTargetHeight-this._scrollTop;if(upperScrollValue<=this.upp
erThreshold&&!this.upperTriggered){this._setUpperTriggered(true);this.fire("uppe
r-threshold")}if(lowerScrollValue<=this.lowerThreshold&&!this.lowerTriggered){th
is._setLowerTriggered(true);this.fire("lower-threshold")}},clearTriggers:functio
n(){this._setUpperTriggered(false);this._setLowerTriggered(false)}}); |
| 41 // Copyright (c) 2011 The Chromium Authors. All rights reserved. | 45 // Copyright (c) 2011 The Chromium Authors. All rights reserved. |
| 42 // Use of this source code is governed by a BSD-style license that can be | 46 // Use of this source code is governed by a BSD-style license that can be |
| 43 // found in the LICENSE file. | 47 // found in the LICENSE file. |
| 44 var EventTrackerEntry;function EventTracker(){this.listeners_=[]}EventTracker.pr
ototype={add:function(target,eventType,listener,opt_capture){var capture=!!opt_c
apture;var h={target:target,eventType:eventType,listener:listener,capture:captur
e};this.listeners_.push(h);target.addEventListener(eventType,listener,capture)},
remove:function(target,eventType){this.listeners_=this.listeners_.filter(functio
n(h){if(h.target==target&&(!eventType||h.eventType==eventType)){EventTracker.rem
oveEventListener_(h);return false}return true})},removeAll:function(){this.liste
ners_.forEach(EventTracker.removeEventListener_);this.listeners_=[]}};EventTrack
er.removeEventListener_=function(h){h.target.removeEventListener(h.eventType,h.l
istener,h.capture)}; | 48 var EventTrackerEntry;function EventTracker(){this.listeners_=[]}EventTracker.pr
ototype={add:function(target,eventType,listener,opt_capture){var capture=!!opt_c
apture;var h={target:target,eventType:eventType,listener:listener,capture:captur
e};this.listeners_.push(h);target.addEventListener(eventType,listener,capture)},
remove:function(target,eventType){this.listeners_=this.listeners_.filter(functio
n(h){if(h.target==target&&(!eventType||h.eventType==eventType)){EventTracker.rem
oveEventListener_(h);return false}return true})},removeAll:function(){this.liste
ners_.forEach(EventTracker.removeEventListener_);this.listeners_=[]}};EventTrack
er.removeEventListener_=function(h){h.target.removeEventListener(h.eventType,h.l
istener,h.capture)}; |
| 45 // Copyright 2014 The Chromium Authors. All rights reserved. | 49 // Copyright 2014 The Chromium Authors. All rights reserved. |
| 46 // Use of this source code is governed by a BSD-style license that can be | 50 // Use of this source code is governed by a BSD-style license that can be |
| 47 // found in the LICENSE file. | 51 // found in the LICENSE file. |
| 48 cr.define("cr.ui",function(){function FocusRow(root,boundary,opt_delegate){this.
root=root;this.boundary_=boundary||document.documentElement;this.delegate=opt_de
legate;this.eventTracker=new EventTracker}FocusRow.Delegate=function(){};FocusRo
w.Delegate.prototype={onKeydown:assertNotReached,onFocus:assertNotReached};Focus
Row.ACTIVE_CLASS="focus-row-active";FocusRow.isFocusable=function(element){if(!e
lement||element.disabled)return false;function isVisible(element){assertInstance
of(element,Element);var style=window.getComputedStyle(element);if(style.visibili
ty=="hidden"||style.display=="none")return false;var parent=element.parentNode;i
f(!parent)return false;if(parent==element.ownerDocument||parent instanceof Docum
entFragment)return true;return isVisible(parent)}return isVisible(element)};Focu
sRow.prototype={addItem:function(type,query){assert(type);var element=this.root.
querySelector(query);if(!element)return false;element.setAttribute("focus-type",
type);element.tabIndex=this.isActive()?0:-1;this.eventTracker.add(element,"blur"
,this.onBlur_.bind(this));this.eventTracker.add(element,"focus",this.onFocus_.bi
nd(this));this.eventTracker.add(element,"keydown",this.onKeydown_.bind(this));th
is.eventTracker.add(element,"mousedown",this.onMousedown_.bind(this));return tru
e},destroy:function(){this.eventTracker.removeAll()},getCustomEquivalent:functio
n(sampleElement){return assert(this.getFirstFocusable())},getElements:function()
{var elements=this.root.querySelectorAll("[focus-type]");return Array.prototype.
slice.call(elements)},getEquivalentElement:function(sampleElement){if(this.getFo
cusableElements().indexOf(sampleElement)>=0)return sampleElement;var sampleFocus
Type=this.getTypeForElement(sampleElement);if(sampleFocusType){var sameType=this
.getFirstFocusable(sampleFocusType);if(sameType)return sameType}return this.getC
ustomEquivalent(sampleElement)},getFirstFocusable:function(opt_type){var filter=
opt_type?'="'+opt_type+'"':"";var elements=this.root.querySelectorAll("[focus-ty
pe"+filter+"]");for(var i=0;i<elements.length;++i){if(cr.ui.FocusRow.isFocusable
(elements[i]))return elements[i]}return null},getFocusableElements:function(){re
turn this.getElements().filter(cr.ui.FocusRow.isFocusable)},getTypeForElement:fu
nction(element){return element.getAttribute("focus-type")||""},isActive:function
(){return this.root.classList.contains(FocusRow.ACTIVE_CLASS)},makeActive:functi
on(active){if(active==this.isActive())return;this.getElements().forEach(function
(element){element.tabIndex=active?0:-1});this.root.classList.toggle(FocusRow.ACT
IVE_CLASS,active)},onBlur_:function(e){if(!this.boundary_.contains(e.relatedTarg
et))return;var currentTarget=e.currentTarget;if(this.getFocusableElements().inde
xOf(currentTarget)>=0)this.makeActive(false)},onFocus_:function(e){if(this.deleg
ate)this.delegate.onFocus(this,e)},onMousedown_:function(e){if(e.button)return;i
f(!e.currentTarget.disabled)e.currentTarget.tabIndex=0},onKeydown_:function(e){v
ar elements=this.getFocusableElements();var currentElement=e.currentTarget;var e
lementIndex=elements.indexOf(currentElement);assert(elementIndex>=0);if(this.del
egate&&this.delegate.onKeydown(this,e))return;if(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}}); | 52 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}}); |
| 49 // Copyright 2016 The Chromium Authors. All rights reserved. | 53 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 50 // Use of this source code is governed by a BSD-style license that can be | 54 // Use of this source code is governed by a BSD-style license that can be |
| 51 // found in the LICENSE file. | 55 // found in the LICENSE file. |
| 52 cr.define("cr.icon",function(){function getSupportedScaleFactors(){var supported
ScaleFactors=[];if(!cr.isIOS){supportedScaleFactors.push(1)}if(cr.isMac||cr.isCh
romeOS||cr.isWindows||cr.isLinux){supportedScaleFactors.push(2)}else{supportedSc
aleFactors.push(window.devicePixelRatio)}return supportedScaleFactors}function g
etImageSet(path){var supportedScaleFactors=getSupportedScaleFactors();var replac
eStartIndex=path.indexOf("scalefactor");if(replaceStartIndex<0)return url(path);
var s="";for(var i=0;i<supportedScaleFactors.length;++i){var scaleFactor=support
edScaleFactors[i];var pathWithScaleFactor=path.substr(0,replaceStartIndex)+scale
Factor+path.substr(replaceStartIndex+"scalefactor".length);s+=url(pathWithScaleF
actor)+" "+scaleFactor+"x";if(i!=supportedScaleFactors.length-1)s+=", "}return"-
webkit-image-set("+s+")"}function getImage(path){var chromeThemePath="chrome://t
heme";var isChromeThemeUrl=path.slice(0,chromeThemePath.length)==chromeThemePath
;return isChromeThemeUrl?getImageSet(path+"@scalefactorx"):url(path)}var FAVICON
_URL_REGEX=/\.ico$/i;function getFavicon(url,opt_size,opt_type){var size=opt_siz
e||16;var type=opt_type||"favicon";return getImageSet("chrome://"+type+"/size/"+
size+"@scalefactorx/"+(FAVICON_URL_REGEX.test(url)?"iconurl/":"")+url)}return{ge
tImage:getImage,getFavicon:getFavicon}}); | 56 cr.define("cr.icon",function(){function getSupportedScaleFactors(){var supported
ScaleFactors=[];if(!cr.isIOS){supportedScaleFactors.push(1)}if(cr.isMac||cr.isCh
romeOS||cr.isWindows||cr.isLinux){supportedScaleFactors.push(2)}else{supportedSc
aleFactors.push(window.devicePixelRatio)}return supportedScaleFactors}function g
etImageSet(path){var supportedScaleFactors=getSupportedScaleFactors();var replac
eStartIndex=path.indexOf("scalefactor");if(replaceStartIndex<0)return url(path);
var s="";for(var i=0;i<supportedScaleFactors.length;++i){var scaleFactor=support
edScaleFactors[i];var pathWithScaleFactor=path.substr(0,replaceStartIndex)+scale
Factor+path.substr(replaceStartIndex+"scalefactor".length);s+=url(pathWithScaleF
actor)+" "+scaleFactor+"x";if(i!=supportedScaleFactors.length-1)s+=", "}return"-
webkit-image-set("+s+")"}function getImage(path){var chromeThemePath="chrome://t
heme";var isChromeThemeUrl=path.slice(0,chromeThemePath.length)==chromeThemePath
;return isChromeThemeUrl?getImageSet(path+"@scalefactorx"):url(path)}var FAVICON
_URL_REGEX=/\.ico$/i;function getFavicon(url,opt_size,opt_type){var size=opt_siz
e||16;var type=opt_type||"favicon";return getImageSet("chrome://"+type+"/size/"+
size+"@scalefactorx/"+(FAVICON_URL_REGEX.test(url)?"iconurl/":"")+url)}return{ge
tImage:getImage,getFavicon:getFavicon}}); |
| 53 // Copyright 2016 The Chromium Authors. All rights reserved. | 57 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 54 // Use of this source code is governed by a BSD-style license that can be | 58 // Use of this source code is governed by a BSD-style license that can be |
| 55 // found in the LICENSE file. | 59 // found in the LICENSE file. |
| 56 Polymer({is:"history-searched-label",properties:{title:String,searchTerm:String}
,observers:["setSearchedTextToBold_(title, searchTerm)"],setSearchedTextToBold_:
function(){var i=0;var titleText=this.title;if(this.searchTerm==""||this.searchT
erm==null){this.textContent=titleText;return}var re=new RegExp(quoteString(this.
searchTerm),"gim");var match;this.textContent="";while(match=re.exec(titleText))
{if(match.index>i)this.appendChild(document.createTextNode(titleText.slice(i,mat
ch.index)));i=re.lastIndex;var b=document.createElement("b");b.textContent=title
Text.substring(match.index,i);this.appendChild(b)}if(i<titleText.length)this.app
endChild(document.createTextNode(titleText.slice(i)))}}); | 60 Polymer({is:"history-searched-label",properties:{title:String,searchTerm:String}
,observers:["setSearchedTextToBold_(title, searchTerm)"],setSearchedTextToBold_:
function(){var i=0;var titleText=this.title;if(this.searchTerm==""||this.searchT
erm==null){this.textContent=titleText;return}var re=new RegExp(quoteString(this.
searchTerm),"gim");var match;this.textContent="";while(match=re.exec(titleText))
{if(match.index>i)this.appendChild(document.createTextNode(titleText.slice(i,mat
ch.index)));i=re.lastIndex;var b=document.createElement("b");b.textContent=title
Text.substring(match.index,i);this.appendChild(b)}if(i<titleText.length)this.app
endChild(document.createTextNode(titleText.slice(i)))}}); |
| 57 // Copyright 2015 The Chromium Authors. All rights reserved. | 61 // Copyright 2015 The Chromium Authors. All rights reserved. |
| 58 // Use of this source code is governed by a BSD-style license that can be | 62 // Use of this source code is governed by a BSD-style license that can be |
| 59 // found in the LICENSE file. | 63 // found in the LICENSE file. |
| 60 function HistoryFocusRow(root,boundary,delegate){cr.ui.FocusRow.call(this,root,b
oundary,delegate);this.addItems()}HistoryFocusRow.prototype={__proto__:cr.ui.Foc
usRow.prototype,getCustomEquivalent:function(sampleElement){var equivalent;if(th
is.getTypeForElement(sampleElement)=="star")equivalent=this.getFirstFocusable("t
itle");return equivalent||cr.ui.FocusRow.prototype.getCustomEquivalent.call(this
,sampleElement)},addItems:function(){this.destroy();assert(this.addItem("checkbo
x","#checkbox"));assert(this.addItem("title","#title"));assert(this.addItem("men
u-button","#menu-button"));this.addItem("star","#bookmark-star")}};cr.define("md
_history",function(){function FocusRowDelegate(historyItemElement){this.historyI
temElement=historyItemElement}FocusRowDelegate.prototype={onFocus:function(row,e
){this.historyItemElement.lastFocused=e.path[0]},onKeydown:function(row,e){if(e.
key=="Enter")e.stopPropagation();return false}};var HistoryItem=Polymer({is:"his
tory-item",properties:{item:{type:Object,observer:"showIcon_"},searchTerm:{type:
String},selected:{type:Boolean,reflectToAttribute:true},isCardStart:{type:Boolea
n,reflectToAttribute:true},isCardEnd:{type:Boolean,reflectToAttribute:true},embe
dded:{type:Boolean,reflectToAttribute:true},hasTimeGap:{type:Boolean},numberOfIt
ems:{type:Number},path:String,index:Number,lastFocused:{type:Object,notify:true}
,ironListTabIndex:{type:Number,observer:"ironListTabIndexChanged_"}},row_:null,a
ttached:function(){Polymer.RenderStatus.afterNextRender(this,function(){this.row
_=new HistoryFocusRow(this.$["main-container"],null,new FocusRowDelegate(this));
this.row_.makeActive(this.ironListTabIndex==0);this.listen(this,"focus","onFocus
_");this.listen(this,"dom-change","onDomChange_")})},detached:function(){this.un
listen(this,"focus","onFocus_");this.unlisten(this,"dom-change","onDomChange_");
if(this.row_)this.row_.destroy()},onFocus_:function(){if(this.lastFocused)this.r
ow_.getEquivalentElement(this.lastFocused).focus();else this.row_.getFirstFocusa
ble().focus();this.tabIndex=-1},ironListTabIndexChanged_:function(){if(this.row_
)this.row_.makeActive(this.ironListTabIndex==0)},onDomChange_:function(){if(this
.row_)this.row_.addItems()},onItemClick_:function(e){for(var i=0;i<e.path.length
;i++){var elem=e.path[i];if(elem.id!="checkbox"&&(elem.nodeName=="A"||elem.nodeN
ame=="BUTTON")){return}}if(this.selectionNotAllowed_())return;this.$.checkbox.fo
cus();this.fire("history-checkbox-select",{element:this,shiftKey:e.shiftKey})},o
nItemMousedown_:function(e){if(e.shiftKey)e.preventDefault()},getEntrySummary_:f
unction(){var item=this.item;return loadTimeData.getStringF("entrySummary",item.
dateTimeOfDay,item.starred?loadTimeData.getString("bookmarked"):"",item.title,it
em.domain)},getAriaChecked_:function(selected){return selected?"true":"false"},o
nRemoveBookmarkTap_:function(){if(!this.item.starred)return;if(this.$$("#bookmar
k-star")==this.root.activeElement)this.$["menu-button"].focus();var browserServi
ce=md_history.BrowserService.getInstance();browserService.removeBookmark(this.it
em.url);browserService.recordAction("BookmarkStarClicked");this.fire("remove-boo
kmark-stars",this.item.url)},onMenuButtonTap_:function(e){this.fire("toggle-menu
",{target:Polymer.dom(e).localTarget,index:this.index,item:this.item,path:this.p
ath});e.stopPropagation()},onLinkClick_:function(){var browserService=md_history
.BrowserService.getInstance();browserService.recordAction("EntryLinkClick");if(t
his.searchTerm)browserService.recordAction("SearchResultClick");if(this.index==u
ndefined)return;browserService.recordHistogram("HistoryPage.ClickPosition",Math.
min(this.index,UMA_MAX_BUCKET_VALUE),UMA_MAX_BUCKET_VALUE);if(this.index<=UMA_MA
X_SUBSET_BUCKET_VALUE){browserService.recordHistogram("HistoryPage.ClickPosition
Subset",this.index,UMA_MAX_SUBSET_BUCKET_VALUE)}},onLinkRightClick_:function(){m
d_history.BrowserService.getInstance().recordAction("EntryLinkRightClick")},show
Icon_:function(){this.$.icon.style.backgroundImage=cr.icon.getFavicon(this.item.
url)},selectionNotAllowed_:function(){return!loadTimeData.getBoolean("allowDelet
ingHistory")},cardTitle_:function(numberOfItems,historyDate,search){if(!search)r
eturn this.item.dateRelativeDay;return HistoryItem.searchResultsTitle(numberOfIt
ems,search)},addTimeTitle_:function(){var el=this.$["time-accessed"];el.setAttri
bute("title",new Date(this.item.time).toString());this.unlisten(el,"mouseover","
addTimeTitle_")}});HistoryItem.needsTimeGap=function(visits,currentIndex,searche
dTerm){if(currentIndex>=visits.length-1||visits.length==0)return false;var curre
ntItem=visits[currentIndex];var nextItem=visits[currentIndex+1];if(searchedTerm)
return currentItem.dateShort!=nextItem.dateShort;return currentItem.time-nextIte
m.time>BROWSING_GAP_TIME&¤tItem.dateRelativeDay==nextItem.dateRelativeDay}
;HistoryItem.searchResultsTitle=function(numberOfResults,searchTerm){var resultI
d=numberOfResults==1?"searchResult":"searchResults";return loadTimeData.getStrin
gF("foundSearchResults",numberOfResults,loadTimeData.getString(resultId),searchT
erm)};return{HistoryItem:HistoryItem}}); | 64 function HistoryFocusRow(root,boundary,delegate){cr.ui.FocusRow.call(this,root,b
oundary,delegate);this.addItems()}HistoryFocusRow.prototype={__proto__:cr.ui.Foc
usRow.prototype,getCustomEquivalent:function(sampleElement){var equivalent;if(th
is.getTypeForElement(sampleElement)=="star")equivalent=this.getFirstFocusable("t
itle");return equivalent||cr.ui.FocusRow.prototype.getCustomEquivalent.call(this
,sampleElement)},addItems:function(){this.destroy();assert(this.addItem("checkbo
x","#checkbox"));assert(this.addItem("title","#title"));assert(this.addItem("men
u-button","#menu-button"));this.addItem("star","#bookmark-star")}};cr.define("md
_history",function(){function FocusRowDelegate(historyItemElement){this.historyI
temElement=historyItemElement}FocusRowDelegate.prototype={onFocus:function(row,e
){this.historyItemElement.lastFocused=e.path[0]},onKeydown:function(row,e){if(e.
key=="Enter")e.stopPropagation();return false}};var HistoryItem=Polymer({is:"his
tory-item",properties:{item:{type:Object,observer:"showIcon_"},searchTerm:{type:
String},selected:{type:Boolean,reflectToAttribute:true},isCardStart:{type:Boolea
n,reflectToAttribute:true},isCardEnd:{type:Boolean,reflectToAttribute:true},embe
dded:{type:Boolean,reflectToAttribute:true},hasTimeGap:{type:Boolean},numberOfIt
ems:{type:Number},path:String,index:Number,lastFocused:{type:Object,notify:true}
,ironListTabIndex:{type:Number,observer:"ironListTabIndexChanged_"}},row_:null,a
ttached:function(){Polymer.RenderStatus.afterNextRender(this,function(){this.row
_=new HistoryFocusRow(this.$["main-container"],null,new FocusRowDelegate(this));
this.row_.makeActive(this.ironListTabIndex==0);this.listen(this,"focus","onFocus
_");this.listen(this,"dom-change","onDomChange_")})},detached:function(){this.un
listen(this,"focus","onFocus_");this.unlisten(this,"dom-change","onDomChange_");
if(this.row_)this.row_.destroy()},onFocus_:function(){if(this.lastFocused)this.r
ow_.getEquivalentElement(this.lastFocused).focus();else this.row_.getFirstFocusa
ble().focus();this.tabIndex=-1},ironListTabIndexChanged_:function(){if(this.row_
)this.row_.makeActive(this.ironListTabIndex==0)},onDomChange_:function(){if(this
.row_)this.row_.addItems()},onItemClick_:function(e){for(var i=0;i<e.path.length
;i++){var elem=e.path[i];if(elem.id!="checkbox"&&(elem.nodeName=="A"||elem.nodeN
ame=="BUTTON")){return}}if(this.selectionNotAllowed_())return;this.$.checkbox.fo
cus();this.fire("history-checkbox-select",{element:this,shiftKey:e.shiftKey})},o
nItemMousedown_:function(e){if(e.shiftKey)e.preventDefault()},getEntrySummary_:f
unction(){var item=this.item;return loadTimeData.getStringF("entrySummary",item.
dateTimeOfDay,item.starred?loadTimeData.getString("bookmarked"):"",item.title,it
em.domain)},getAriaChecked_:function(selected){return selected?"true":"false"},o
nRemoveBookmarkTap_:function(){if(!this.item.starred)return;if(this.$$("#bookmar
k-star")==this.root.activeElement)this.$["menu-button"].focus();var browserServi
ce=md_history.BrowserService.getInstance();browserService.removeBookmark(this.it
em.url);browserService.recordAction("BookmarkStarClicked");this.fire("remove-boo
kmark-stars",this.item.url)},onMenuButtonTap_:function(e){this.fire("open-menu",
{target:Polymer.dom(e).localTarget,index:this.index,item:this.item,path:this.pat
h});e.stopPropagation()},onLinkClick_:function(){var browserService=md_history.B
rowserService.getInstance();browserService.recordAction("EntryLinkClick");if(thi
s.searchTerm)browserService.recordAction("SearchResultClick");if(this.index==und
efined)return;browserService.recordHistogram("HistoryPage.ClickPosition",Math.mi
n(this.index,UMA_MAX_BUCKET_VALUE),UMA_MAX_BUCKET_VALUE);if(this.index<=UMA_MAX_
SUBSET_BUCKET_VALUE){browserService.recordHistogram("HistoryPage.ClickPositionSu
bset",this.index,UMA_MAX_SUBSET_BUCKET_VALUE)}},onLinkRightClick_:function(){md_
history.BrowserService.getInstance().recordAction("EntryLinkRightClick")},showIc
on_:function(){this.$.icon.style.backgroundImage=cr.icon.getFavicon(this.item.ur
l)},selectionNotAllowed_:function(){return!loadTimeData.getBoolean("allowDeletin
gHistory")},cardTitle_:function(numberOfItems,historyDate,search){if(!search)ret
urn this.item.dateRelativeDay;return HistoryItem.searchResultsTitle(numberOfItem
s,search)},addTimeTitle_:function(){var el=this.$["time-accessed"];el.setAttribu
te("title",new Date(this.item.time).toString());this.unlisten(el,"mouseover","ad
dTimeTitle_")}});HistoryItem.needsTimeGap=function(visits,currentIndex,searchedT
erm){if(currentIndex>=visits.length-1||visits.length==0)return false;var current
Item=visits[currentIndex];var nextItem=visits[currentIndex+1];if(searchedTerm)re
turn currentItem.dateShort!=nextItem.dateShort;return currentItem.time-nextItem.
time>BROWSING_GAP_TIME&¤tItem.dateRelativeDay==nextItem.dateRelativeDay};H
istoryItem.searchResultsTitle=function(numberOfResults,searchTerm){var resultId=
numberOfResults==1?"searchResult":"searchResults";return loadTimeData.getStringF
("foundSearchResults",numberOfResults,loadTimeData.getString(resultId),searchTer
m)};return{HistoryItem:HistoryItem}}); |
| 61 // Copyright 2016 The Chromium Authors. All rights reserved. | 65 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 62 // Use of this source code is governed by a BSD-style license that can be | 66 // Use of this source code is governed by a BSD-style license that can be |
| 63 // found in the LICENSE file. | 67 // found in the LICENSE file. |
| 64 var SelectionTreeNode=function(currentPath){this.currentPath=currentPath;this.le
af=false;this.indexes=[];this.children=[]};SelectionTreeNode.prototype.addChild=
function(index,path){this.indexes.push(index);this.children[index]=new Selection
TreeNode(path)};var HistoryListBehavior={properties:{selectedPaths:{type:Object,
value:function(){return new Set}},lastSelectedPath:String},listeners:{"history-c
heckbox-select":"itemSelected_"},addNewResults:function(results,incremental,fini
shed){},hasResults:function(historyDataLength){return historyDataLength>0},noRes
ultsMessage:function(searchedTerm,isLoading){if(isLoading)return"";var messageId
=searchedTerm!==""?"noSearchResults":"noResults";return loadTimeData.getString(m
essageId)},unselectAllItems:function(){this.selectedPaths.forEach(function(path)
{this.set(path+".selected",false)}.bind(this));this.selectedPaths.clear()},delet
eSelected:function(){var toBeRemoved=Array.from(this.selectedPaths.values()).map
(function(path){return this.get(path)}.bind(this));md_history.BrowserService.get
Instance().deleteItems(toBeRemoved).then(function(){this.removeItemsByPath(Array
.from(this.selectedPaths));this.fire("unselect-all")}.bind(this))},removeItemsBy
Path:function(paths){if(paths.length==0)return;this.removeItemsBeneathNode_(this
.buildRemovalTree_(paths))},buildRemovalTree_:function(paths){var rootNode=new S
electionTreeNode(paths[0].split(".")[0]);paths.forEach(function(path){var compon
ents=path.split(".");var node=rootNode;components.shift();while(components.lengt
h>1){var index=Number(components.shift());var arrayName=components.shift();if(!n
ode.children[index])node.addChild(index,[node.currentPath,index,arrayName].join(
"."));node=node.children[index]}node.leaf=true;node.indexes.push(Number(componen
ts.shift()))});return rootNode},removeItemsBeneathNode_:function(node){var array
=this.get(node.currentPath);var splices=[];node.indexes.sort(function(a,b){retur
n b-a});node.indexes.forEach(function(index){if(node.leaf||this.removeItemsBenea
thNode_(node.children[index])){var item=array.splice(index,1)[0];splices.push({i
ndex:index,removed:[item],addedCount:0,object:array,type:"splice"})}}.bind(this)
);if(array.length==0&&node.currentPath.indexOf(".")!=-1)return true;this.notifyS
plices(node.currentPath,splices);return false},itemSelected_:function(e){var ite
m=e.detail.element;var paths=[];var itemPath=item.path;if(e.detail.shiftKey&&thi
s.lastSelectedPath){var itemPathComponents=itemPath.split(".");var itemIndex=Num
ber(itemPathComponents.pop());var itemArrayPath=itemPathComponents.join(".");var
lastItemPathComponents=this.lastSelectedPath.split(".");var lastItemIndex=Numbe
r(lastItemPathComponents.pop());if(itemArrayPath==lastItemPathComponents.join(".
")){for(var i=Math.min(itemIndex,lastItemIndex);i<=Math.max(itemIndex,lastItemIn
dex);i++){paths.push(itemArrayPath+"."+i)}}}if(paths.length==0)paths.push(item.p
ath);var selected=!this.selectedPaths.has(item.path);paths.forEach(function(path
){this.set(path+".selected",selected);if(selected){this.selectedPaths.add(path);
return}this.selectedPaths.delete(path)}.bind(this));this.lastSelectedPath=itemPa
th}}; | 68 var SelectionTreeNode=function(currentPath){this.currentPath=currentPath;this.le
af=false;this.indexes=[];this.children=[]};SelectionTreeNode.prototype.addChild=
function(index,path){this.indexes.push(index);this.children[index]=new Selection
TreeNode(path)};var HistoryListBehavior={properties:{selectedPaths:{type:Object,
value:function(){return new Set}},lastSelectedPath:String},listeners:{"history-c
heckbox-select":"itemSelected_"},addNewResults:function(results,incremental,fini
shed){},hasResults:function(historyDataLength){return historyDataLength>0},noRes
ultsMessage:function(searchedTerm,isLoading){if(isLoading)return"";var messageId
=searchedTerm!==""?"noSearchResults":"noResults";return loadTimeData.getString(m
essageId)},unselectAllItems:function(){this.selectedPaths.forEach(function(path)
{this.set(path+".selected",false)}.bind(this));this.selectedPaths.clear()},delet
eSelected:function(){var toBeRemoved=Array.from(this.selectedPaths.values()).map
(function(path){return this.get(path)}.bind(this));md_history.BrowserService.get
Instance().deleteItems(toBeRemoved).then(function(){this.removeItemsByPath(Array
.from(this.selectedPaths));this.fire("unselect-all")}.bind(this))},removeItemsBy
Path:function(paths){if(paths.length==0)return;this.removeItemsBeneathNode_(this
.buildRemovalTree_(paths))},buildRemovalTree_:function(paths){var rootNode=new S
electionTreeNode(paths[0].split(".")[0]);paths.forEach(function(path){var compon
ents=path.split(".");var node=rootNode;components.shift();while(components.lengt
h>1){var index=Number(components.shift());var arrayName=components.shift();if(!n
ode.children[index])node.addChild(index,[node.currentPath,index,arrayName].join(
"."));node=node.children[index]}node.leaf=true;node.indexes.push(Number(componen
ts.shift()))});return rootNode},removeItemsBeneathNode_:function(node){var array
=this.get(node.currentPath);var splices=[];node.indexes.sort(function(a,b){retur
n b-a});node.indexes.forEach(function(index){if(node.leaf||this.removeItemsBenea
thNode_(node.children[index])){var item=array.splice(index,1)[0];splices.push({i
ndex:index,removed:[item],addedCount:0,object:array,type:"splice"})}}.bind(this)
);if(array.length==0&&node.currentPath.indexOf(".")!=-1)return true;this.notifyS
plices(node.currentPath,splices);return false},itemSelected_:function(e){var ite
m=e.detail.element;var paths=[];var itemPath=item.path;if(e.detail.shiftKey&&thi
s.lastSelectedPath){var itemPathComponents=itemPath.split(".");var itemIndex=Num
ber(itemPathComponents.pop());var itemArrayPath=itemPathComponents.join(".");var
lastItemPathComponents=this.lastSelectedPath.split(".");var lastItemIndex=Numbe
r(lastItemPathComponents.pop());if(itemArrayPath==lastItemPathComponents.join(".
")){for(var i=Math.min(itemIndex,lastItemIndex);i<=Math.max(itemIndex,lastItemIn
dex);i++){paths.push(itemArrayPath+"."+i)}}}if(paths.length==0)paths.push(item.p
ath);var selected=!this.selectedPaths.has(item.path);paths.forEach(function(path
){this.set(path+".selected",selected);if(selected){this.selectedPaths.add(path);
return}this.selectedPaths.delete(path)}.bind(this));this.lastSelectedPath=itemPa
th}}; |
| 65 // Copyright 2015 The Chromium Authors. All rights reserved. | 69 // Copyright 2015 The Chromium Authors. All rights reserved. |
| 66 // Use of this source code is governed by a BSD-style license that can be | 70 // Use of this source code is governed by a BSD-style license that can be |
| 67 // found in the LICENSE file. | 71 // found in the LICENSE file. |
| 68 Polymer({is:"history-list",behaviors:[HistoryListBehavior],properties:{searchedT
erm:{type:String,value:""},querying:Boolean,historyData_:Array,resultLoadingDisa
bled_:{type:Boolean,value:false},lastFocused_:Object},listeners:{scroll:"notifyL
istScroll_","remove-bookmark-stars":"removeBookmarkStars_"},attached:function(){
this.$["infinite-list"].notifyResize();this.$["infinite-list"].scrollTarget=this
;this.$["scroll-threshold"].scrollTarget=this},removeBookmarkStars_:function(e){
var url=e.detail;if(this.historyData_===undefined)return;for(var i=0;i<this.hist
oryData_.length;i++){if(this.historyData_[i].url==url)this.set("historyData_."+i
+".starred",false)}},addNewResults:function(historyResults,incremental,finished)
{var results=historyResults.slice();this.$["scroll-threshold"].clearTriggers();i
f(!incremental){this.resultLoadingDisabled_=false;if(this.historyData_)this.spli
ce("historyData_",0,this.historyData_.length);this.fire("unselect-all")}if(this.
historyData_){results.unshift("historyData_");this.push.apply(this,results)}else
{this.set("historyData_",results)}this.resultLoadingDisabled_=finished},loadMore
Data_:function(){if(this.resultLoadingDisabled_||this.querying)return;this.fire(
"load-more-history")},needsTimeGap_:function(item,index,length){return md_histor
y.HistoryItem.needsTimeGap(this.historyData_,index,this.searchedTerm)},isCardSta
rt_:function(item,i,length){if(length==0||i>length-1)return false;return i==0||t
his.historyData_[i].dateRelativeDay!=this.historyData_[i-1].dateRelativeDay},isC
ardEnd_:function(item,i,length){if(length==0||i>length-1)return false;return i==
length-1||this.historyData_[i].dateRelativeDay!=this.historyData_[i+1].dateRelat
iveDay},notifyListScroll_:function(){this.fire("history-list-scrolled")},pathFor
Item_:function(index){return"historyData_."+index}}); | 72 Polymer({is:"history-list",behaviors:[HistoryListBehavior],properties:{searchedT
erm:{type:String,value:""},querying:Boolean,historyData_:Array,resultLoadingDisa
bled_:{type:Boolean,value:false},lastFocused_:Object},listeners:{"remove-bookmar
k-stars":"removeBookmarkStars_"},attached:function(){this.$["infinite-list"].not
ifyResize();this.$["infinite-list"].scrollTarget=this;this.$["scroll-threshold"]
.scrollTarget=this},removeBookmarkStars_:function(e){var url=e.detail;if(this.hi
storyData_===undefined)return;for(var i=0;i<this.historyData_.length;i++){if(thi
s.historyData_[i].url==url)this.set("historyData_."+i+".starred",false)}},addNew
Results:function(historyResults,incremental,finished){var results=historyResults
.slice();this.$["scroll-threshold"].clearTriggers();if(!incremental){this.result
LoadingDisabled_=false;if(this.historyData_)this.splice("historyData_",0,this.hi
storyData_.length);this.fire("unselect-all")}if(this.historyData_){results.unshi
ft("historyData_");this.push.apply(this,results)}else{this.set("historyData_",re
sults)}this.resultLoadingDisabled_=finished},loadMoreData_:function(){if(this.re
sultLoadingDisabled_||this.querying)return;this.fire("load-more-history")},needs
TimeGap_:function(item,index,length){return md_history.HistoryItem.needsTimeGap(
this.historyData_,index,this.searchedTerm)},isCardStart_:function(item,i,length)
{if(length==0||i>length-1)return false;return i==0||this.historyData_[i].dateRel
ativeDay!=this.historyData_[i-1].dateRelativeDay},isCardEnd_:function(item,i,len
gth){if(length==0||i>length-1)return false;return i==length-1||this.historyData_
[i].dateRelativeDay!=this.historyData_[i+1].dateRelativeDay},pathForItem_:functi
on(index){return"historyData_."+index}}); |
| 69 // Copyright 2016 The Chromium Authors. All rights reserved. | 73 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 70 // Use of this source code is governed by a BSD-style license that can be | 74 // Use of this source code is governed by a BSD-style license that can be |
| 71 // found in the LICENSE file. | 75 // found in the LICENSE file. |
| 72 Polymer({is:"history-list-container",properties:{selectedPage_:String,grouped:Bo
olean,groupedRange:{type:Number,observer:"groupedRangeChanged_"},queryState:Obje
ct,queryResult:Object},observers:["searchTermChanged_(queryState.searchTerm)","g
roupedOffsetChanged_(queryState.groupedOffset)"],listeners:{"history-list-scroll
ed":"closeMenu_","load-more-history":"loadMoreHistory_","toggle-menu":"toggleMen
u_"},historyResult:function(info,results){this.initializeResults_(info,results);
this.closeMenu_();if(info.term&&!this.queryState.incremental){Polymer.IronA11yAn
nouncer.requestAvailability();this.fire("iron-announce",{text:md_history.History
Item.searchResultsTitle(results.length,info.term)})}var list=this.getSelectedLis
t_();list.addNewResults(results,this.queryState.incremental,info.finished)},quer
yHistory:function(incremental){var queryState=this.queryState;var noResults=!thi
s.queryResult||this.queryResult.results==null;if(queryState.queryingDisabled||!t
his.queryState.searchTerm&&noResults){return}var dialog=this.$.dialog.getIfExist
s();if(!incremental&&dialog&&dialog.open)dialog.close();this.set("queryState.que
rying",true);this.set("queryState.incremental",incremental);var lastVisitTime=0;
if(incremental){var lastVisit=this.queryResult.results.slice(-1)[0];lastVisitTim
e=lastVisit?Math.floor(lastVisit.time):0}var maxResults=this.groupedRange==Histo
ryRange.ALL_TIME?RESULTS_PER_PAGE:0;chrome.send("queryHistory",[queryState.searc
hTerm,queryState.groupedOffset,queryState.range,lastVisitTime,maxResults])},hist
oryDeleted:function(){if(this.getSelectedItemCount()>0)return;this.queryHistory(
false)},getContentScrollTarget:function(){return this.getSelectedList_()},getSel
ectedItemCount:function(){return this.getSelectedList_().selectedPaths.size},uns
electAllItems:function(count){var selectedList=this.getSelectedList_();if(select
edList)selectedList.unselectAllItems(count)},deleteSelectedWithPrompt:function()
{if(!loadTimeData.getBoolean("allowDeletingHistory"))return;var browserService=m
d_history.BrowserService.getInstance();browserService.recordAction("RemoveSelect
ed");if(this.queryState.searchTerm!="")browserService.recordAction("SearchResult
Remove");this.$.dialog.get().showModal();this.$$(".action-button").focus()},grou
pedRangeChanged_:function(range,oldRange){this.selectedPage_=range==HistoryRange
.ALL_TIME?"infinite-list":"grouped-list";if(oldRange==undefined)return;this.set(
"queryState.groupedOffset",0);if(this.queryResult.info){this.set("queryResult.re
sults",[]);this.historyResult(this.queryResult.info,[])}this.queryHistory(false)
;this.fire("history-view-changed")},searchTermChanged_:function(){this.queryHist
ory(false);if(this.queryState.searchTerm)md_history.BrowserService.getInstance()
.recordAction("Search")},groupedOffsetChanged_:function(){this.queryHistory(fals
e)},loadMoreHistory_:function(){this.queryHistory(true)},initializeResults_:func
tion(info,results){if(results.length==0)return;var currentDate=results[0].dateRe
lativeDay;for(var i=0;i<results.length;i++){results[i].selected=false;results[i]
.readableTimestamp=info.term==""?results[i].dateTimeOfDay:results[i].dateShort;i
f(results[i].dateRelativeDay!=currentDate){currentDate=results[i].dateRelativeDa
y}}},onDialogConfirmTap_:function(){md_history.BrowserService.getInstance().reco
rdAction("ConfirmRemoveSelected");this.getSelectedList_().deleteSelected();var d
ialog=assert(this.$.dialog.getIfExists());dialog.close()},onDialogCancelTap_:fun
ction(){md_history.BrowserService.getInstance().recordAction("CancelRemoveSelect
ed");var dialog=assert(this.$.dialog.getIfExists());dialog.close()},closeMenu_:f
unction(){var menu=this.$.sharedMenu.getIfExists();if(menu)menu.closeMenu()},tog
gleMenu_:function(e){var target=e.detail.target;var menu=this.$.sharedMenu.get()
;menu.toggleMenu(target,e.detail)},onMoreFromSiteTap_:function(){md_history.Brow
serService.getInstance().recordAction("EntryMenuShowMoreFromSite");var menu=asse
rt(this.$.sharedMenu.getIfExists());this.set("queryState.searchTerm",menu.itemDa
ta.item.domain);menu.closeMenu()},onRemoveFromHistoryTap_:function(){var browser
Service=md_history.BrowserService.getInstance();browserService.recordAction("Ent
ryMenuRemoveFromHistory");var menu=assert(this.$.sharedMenu.getIfExists());var i
temData=menu.itemData;browserService.deleteItems([itemData.item]).then(function(
items){this.fire("unselect-all");this.getSelectedList_().removeItemsByPath([item
Data.path]);var index=itemData.index;if(index==undefined)return;var browserServi
ce=md_history.BrowserService.getInstance();browserService.recordHistogram("Histo
ryPage.RemoveEntryPosition",Math.min(index,UMA_MAX_BUCKET_VALUE),UMA_MAX_BUCKET_
VALUE);if(index<=UMA_MAX_SUBSET_BUCKET_VALUE){browserService.recordHistogram("Hi
storyPage.RemoveEntryPositionSubset",index,UMA_MAX_SUBSET_BUCKET_VALUE)}}.bind(t
his));menu.closeMenu()},getSelectedList_:function(){return this.$$("#"+this.sele
ctedPage_)},canDeleteHistory_:function(){return loadTimeData.getBoolean("allowDe
letingHistory")}});(function(){"use strict";Polymer({is:"iron-location",properti
es:{path:{type:String,notify:true,value:function(){return window.decodeURICompon
ent(window.location.pathname)}},query:{type:String,notify:true,value:function(){
return window.decodeURIComponent(window.location.search.slice(1))}},hash:{type:S
tring,notify:true,value:function(){return window.decodeURIComponent(window.locat
ion.hash.slice(1))}},dwellTime:{type:Number,value:2e3},urlSpaceRegex:{type:Strin
g,value:""},_urlSpaceRegExp:{computed:"_makeRegExp(urlSpaceRegex)"},_lastChanged
At:{type:Number},_initialized:{type:Boolean,value:false}},hostAttributes:{hidden
:true},observers:["_updateUrl(path, query, hash)"],attached:function(){this.list
en(window,"hashchange","_hashChanged");this.listen(window,"location-changed","_u
rlChanged");this.listen(window,"popstate","_urlChanged");this.listen(document.bo
dy,"click","_globalOnClick");this._lastChangedAt=window.performance.now()-(this.
dwellTime-200);this._initialized=true;this._urlChanged()},detached:function(){th
is.unlisten(window,"hashchange","_hashChanged");this.unlisten(window,"location-c
hanged","_urlChanged");this.unlisten(window,"popstate","_urlChanged");this.unlis
ten(document.body,"click","_globalOnClick");this._initialized=false},_hashChange
d:function(){this.hash=window.decodeURIComponent(window.location.hash.substring(
1))},_urlChanged:function(){this._dontUpdateUrl=true;this._hashChanged();this.pa
th=window.decodeURIComponent(window.location.pathname);this.query=window.decodeU
RIComponent(window.location.search.substring(1));this._dontUpdateUrl=false;this.
_updateUrl()},_getUrl:function(){var partiallyEncodedPath=window.encodeURI(this.
path).replace(/\#/g,"%23").replace(/\?/g,"%3F");var partiallyEncodedQuery="";if(
this.query){partiallyEncodedQuery="?"+window.encodeURI(this.query).replace(/\#/g
,"%23")}var partiallyEncodedHash="";if(this.hash){partiallyEncodedHash="#"+windo
w.encodeURI(this.hash)}return partiallyEncodedPath+partiallyEncodedQuery+partial
lyEncodedHash},_updateUrl:function(){if(this._dontUpdateUrl||!this._initialized)
{return}if(this.path===window.decodeURIComponent(window.location.pathname)&&this
.query===window.decodeURIComponent(window.location.search.substring(1))&&this.ha
sh===window.decodeURIComponent(window.location.hash.substring(1))){return}var ne
wUrl=this._getUrl();var fullNewUrl=new URL(newUrl,window.location.protocol+"//"+
window.location.host).href;var now=window.performance.now();var shouldReplace=th
is._lastChangedAt+this.dwellTime>now;this._lastChangedAt=now;if(shouldReplace){w
indow.history.replaceState({},"",fullNewUrl)}else{window.history.pushState({},""
,fullNewUrl)}this.fire("location-changed",{},{node:window})},_globalOnClick:func
tion(event){if(event.defaultPrevented){return}var href=this._getSameOriginLinkHr
ef(event);if(!href){return}event.preventDefault();if(href===window.location.href
){return}window.history.pushState({},"",href);this.fire("location-changed",{},{n
ode:window})},_getSameOriginLinkHref:function(event){if(event.button!==0){return
null}if(event.metaKey||event.ctrlKey){return null}var eventPath=Polymer.dom(eve
nt).path;var anchor=null;for(var i=0;i<eventPath.length;i++){var element=eventPa
th[i];if(element.tagName==="A"&&element.href){anchor=element;break}}if(!anchor){
return null}if(anchor.target==="_blank"){return null}if((anchor.target==="_top"|
|anchor.target==="_parent")&&window.top!==window){return null}var href=anchor.hr
ef;var url;if(document.baseURI!=null){url=new URL(href,document.baseURI)}else{ur
l=new URL(href)}var origin;if(window.location.origin){origin=window.location.ori
gin}else{origin=window.location.protocol+"//"+window.location.hostname;if(window
.location.port){origin+=":"+window.location.port}}if(url.origin!==origin){return
null}var normalizedHref=url.pathname+url.search+url.hash;if(this._urlSpaceRegEx
p&&!this._urlSpaceRegExp.test(normalizedHref)){return null}var fullNormalizedHre
f=new URL(normalizedHref,window.location.href).href;return fullNormalizedHref},_
makeRegExp:function(urlSpaceRegex){return RegExp(urlSpaceRegex)}})})();"use stri
ct";Polymer({is:"iron-query-params",properties:{paramsString:{type:String,notify
:true,observer:"paramsStringChanged"},paramsObject:{type:Object,notify:true,valu
e:function(){return{}}},_dontReact:{type:Boolean,value:false}},hostAttributes:{h
idden:true},observers:["paramsObjectChanged(paramsObject.*)"],paramsStringChange
d:function(){this._dontReact=true;this.paramsObject=this._decodeParams(this.para
msString);this._dontReact=false},paramsObjectChanged:function(){if(this._dontRea
ct){return}this.paramsString=this._encodeParams(this.paramsObject)},_encodeParam
s:function(params){var encodedParams=[];for(var key in params){var value=params[
key];if(value===""){encodedParams.push(encodeURIComponent(key))}else if(value){e
ncodedParams.push(encodeURIComponent(key)+"="+encodeURIComponent(value.toString(
)))}}return encodedParams.join("&")},_decodeParams:function(paramString){var par
ams={};paramString=(paramString||"").replace(/\+/g,"%20");var paramList=paramStr
ing.split("&");for(var i=0;i<paramList.length;i++){var param=paramList[i].split(
"=");if(param[0]){params[decodeURIComponent(param[0])]=decodeURIComponent(param[
1]||"")}}return params}}); | 76 Polymer({is:"history-list-container",properties:{selectedPage_:String,grouped:Bo
olean,groupedRange:{type:Number,observer:"groupedRangeChanged_"},queryState:Obje
ct,queryResult:Object,actionMenuModel_:Object},observers:["searchTermChanged_(qu
eryState.searchTerm)","groupedOffsetChanged_(queryState.groupedOffset)"],listene
rs:{"load-more-history":"loadMoreHistory_","open-menu":"openMenu_"},historyResul
t:function(info,results){this.initializeResults_(info,results);this.closeMenu_()
;if(info.term&&!this.queryState.incremental){Polymer.IronA11yAnnouncer.requestAv
ailability();this.fire("iron-announce",{text:md_history.HistoryItem.searchResult
sTitle(results.length,info.term)})}var list=this.getSelectedList_();list.addNewR
esults(results,this.queryState.incremental,info.finished)},queryHistory:function
(incremental){var queryState=this.queryState;var noResults=!this.queryResult||th
is.queryResult.results==null;if(queryState.queryingDisabled||!this.queryState.se
archTerm&&noResults){return}var dialog=this.$.dialog.getIfExists();if(!increment
al&&dialog&&dialog.open)dialog.close();this.set("queryState.querying",true);this
.set("queryState.incremental",incremental);var lastVisitTime=0;if(incremental){v
ar lastVisit=this.queryResult.results.slice(-1)[0];lastVisitTime=lastVisit?Math.
floor(lastVisit.time):0}var maxResults=this.groupedRange==HistoryRange.ALL_TIME?
RESULTS_PER_PAGE:0;chrome.send("queryHistory",[queryState.searchTerm,queryState.
groupedOffset,queryState.range,lastVisitTime,maxResults])},historyDeleted:functi
on(){if(this.getSelectedItemCount()>0)return;this.queryHistory(false)},getConten
tScrollTarget:function(){return this.getSelectedList_()},getSelectedItemCount:fu
nction(){return this.getSelectedList_().selectedPaths.size},unselectAllItems:fun
ction(count){var selectedList=this.getSelectedList_();if(selectedList)selectedLi
st.unselectAllItems(count)},deleteSelectedWithPrompt:function(){if(!loadTimeData
.getBoolean("allowDeletingHistory"))return;var browserService=md_history.Browser
Service.getInstance();browserService.recordAction("RemoveSelected");if(this.quer
yState.searchTerm!="")browserService.recordAction("SearchResultRemove");this.$.d
ialog.get().showModal();this.$$(".action-button").focus()},groupedRangeChanged_:
function(range,oldRange){this.selectedPage_=range==HistoryRange.ALL_TIME?"infini
te-list":"grouped-list";if(oldRange==undefined)return;this.set("queryState.group
edOffset",0);if(this.queryResult.info){this.set("queryResult.results",[]);this.h
istoryResult(this.queryResult.info,[])}this.queryHistory(false);this.fire("histo
ry-view-changed")},searchTermChanged_:function(){this.queryHistory(false);if(thi
s.queryState.searchTerm)md_history.BrowserService.getInstance().recordAction("Se
arch")},groupedOffsetChanged_:function(){this.queryHistory(false)},loadMoreHisto
ry_:function(){this.queryHistory(true)},initializeResults_:function(info,results
){if(results.length==0)return;var currentDate=results[0].dateRelativeDay;for(var
i=0;i<results.length;i++){results[i].selected=false;results[i].readableTimestam
p=info.term==""?results[i].dateTimeOfDay:results[i].dateShort;if(results[i].date
RelativeDay!=currentDate){currentDate=results[i].dateRelativeDay}}},onDialogConf
irmTap_:function(){md_history.BrowserService.getInstance().recordAction("Confirm
RemoveSelected");this.getSelectedList_().deleteSelected();var dialog=assert(this
.$.dialog.getIfExists());dialog.close()},onDialogCancelTap_:function(){md_histor
y.BrowserService.getInstance().recordAction("CancelRemoveSelected");var dialog=a
ssert(this.$.dialog.getIfExists());dialog.close()},closeMenu_:function(){var men
u=this.$.sharedMenu.getIfExists();if(menu&&menu.open){this.actionMenuModel_=null
;menu.close()}},openMenu_:function(e){var target=e.detail.target;this.actionMenu
Model_=e.detail;var menu=this.$.sharedMenu.get();menu.showAt(target)},onMoreFrom
SiteTap_:function(){md_history.BrowserService.getInstance().recordAction("EntryM
enuShowMoreFromSite");var menu=assert(this.$.sharedMenu.getIfExists());this.set(
"queryState.searchTerm",this.actionMenuModel_.item.domain);this.actionMenuModel_
=null;this.closeMenu_()},onRemoveFromHistoryTap_:function(){var browserService=m
d_history.BrowserService.getInstance();browserService.recordAction("EntryMenuRem
oveFromHistory");var menu=assert(this.$.sharedMenu.getIfExists());var itemData=t
his.actionMenuModel_;browserService.deleteItems([itemData.item]).then(function(i
tems){this.fire("unselect-all");this.getSelectedList_().removeItemsByPath([itemD
ata.path]);var index=itemData.index;if(index==undefined)return;var browserServic
e=md_history.BrowserService.getInstance();browserService.recordHistogram("Histor
yPage.RemoveEntryPosition",Math.min(index,UMA_MAX_BUCKET_VALUE),UMA_MAX_BUCKET_V
ALUE);if(index<=UMA_MAX_SUBSET_BUCKET_VALUE){browserService.recordHistogram("His
toryPage.RemoveEntryPositionSubset",index,UMA_MAX_SUBSET_BUCKET_VALUE)}}.bind(th
is));this.closeMenu_()},getSelectedList_:function(){return this.$$("#"+this.sele
ctedPage_)},canDeleteHistory_:function(){return loadTimeData.getBoolean("allowDe
letingHistory")}});(function(){"use strict";Polymer({is:"iron-location",properti
es:{path:{type:String,notify:true,value:function(){return window.decodeURICompon
ent(window.location.pathname)}},query:{type:String,notify:true,value:function(){
return window.decodeURIComponent(window.location.search.slice(1))}},hash:{type:S
tring,notify:true,value:function(){return window.decodeURIComponent(window.locat
ion.hash.slice(1))}},dwellTime:{type:Number,value:2e3},urlSpaceRegex:{type:Strin
g,value:""},_urlSpaceRegExp:{computed:"_makeRegExp(urlSpaceRegex)"},_lastChanged
At:{type:Number},_initialized:{type:Boolean,value:false}},hostAttributes:{hidden
:true},observers:["_updateUrl(path, query, hash)"],attached:function(){this.list
en(window,"hashchange","_hashChanged");this.listen(window,"location-changed","_u
rlChanged");this.listen(window,"popstate","_urlChanged");this.listen(document.bo
dy,"click","_globalOnClick");this._lastChangedAt=window.performance.now()-(this.
dwellTime-200);this._initialized=true;this._urlChanged()},detached:function(){th
is.unlisten(window,"hashchange","_hashChanged");this.unlisten(window,"location-c
hanged","_urlChanged");this.unlisten(window,"popstate","_urlChanged");this.unlis
ten(document.body,"click","_globalOnClick");this._initialized=false},_hashChange
d:function(){this.hash=window.decodeURIComponent(window.location.hash.substring(
1))},_urlChanged:function(){this._dontUpdateUrl=true;this._hashChanged();this.pa
th=window.decodeURIComponent(window.location.pathname);this.query=window.decodeU
RIComponent(window.location.search.substring(1));this._dontUpdateUrl=false;this.
_updateUrl()},_getUrl:function(){var partiallyEncodedPath=window.encodeURI(this.
path).replace(/\#/g,"%23").replace(/\?/g,"%3F");var partiallyEncodedQuery="";if(
this.query){partiallyEncodedQuery="?"+window.encodeURI(this.query).replace(/\#/g
,"%23")}var partiallyEncodedHash="";if(this.hash){partiallyEncodedHash="#"+windo
w.encodeURI(this.hash)}return partiallyEncodedPath+partiallyEncodedQuery+partial
lyEncodedHash},_updateUrl:function(){if(this._dontUpdateUrl||!this._initialized)
{return}if(this.path===window.decodeURIComponent(window.location.pathname)&&this
.query===window.decodeURIComponent(window.location.search.substring(1))&&this.ha
sh===window.decodeURIComponent(window.location.hash.substring(1))){return}var ne
wUrl=this._getUrl();var fullNewUrl=new URL(newUrl,window.location.protocol+"//"+
window.location.host).href;var now=window.performance.now();var shouldReplace=th
is._lastChangedAt+this.dwellTime>now;this._lastChangedAt=now;if(shouldReplace){w
indow.history.replaceState({},"",fullNewUrl)}else{window.history.pushState({},""
,fullNewUrl)}this.fire("location-changed",{},{node:window})},_globalOnClick:func
tion(event){if(event.defaultPrevented){return}var href=this._getSameOriginLinkHr
ef(event);if(!href){return}event.preventDefault();if(href===window.location.href
){return}window.history.pushState({},"",href);this.fire("location-changed",{},{n
ode:window})},_getSameOriginLinkHref:function(event){if(event.button!==0){return
null}if(event.metaKey||event.ctrlKey){return null}var eventPath=Polymer.dom(eve
nt).path;var anchor=null;for(var i=0;i<eventPath.length;i++){var element=eventPa
th[i];if(element.tagName==="A"&&element.href){anchor=element;break}}if(!anchor){
return null}if(anchor.target==="_blank"){return null}if((anchor.target==="_top"|
|anchor.target==="_parent")&&window.top!==window){return null}var href=anchor.hr
ef;var url;if(document.baseURI!=null){url=new URL(href,document.baseURI)}else{ur
l=new URL(href)}var origin;if(window.location.origin){origin=window.location.ori
gin}else{origin=window.location.protocol+"//"+window.location.hostname;if(window
.location.port){origin+=":"+window.location.port}}if(url.origin!==origin){return
null}var normalizedHref=url.pathname+url.search+url.hash;if(this._urlSpaceRegEx
p&&!this._urlSpaceRegExp.test(normalizedHref)){return null}var fullNormalizedHre
f=new URL(normalizedHref,window.location.href).href;return fullNormalizedHref},_
makeRegExp:function(urlSpaceRegex){return RegExp(urlSpaceRegex)}})})();"use stri
ct";Polymer({is:"iron-query-params",properties:{paramsString:{type:String,notify
:true,observer:"paramsStringChanged"},paramsObject:{type:Object,notify:true,valu
e:function(){return{}}},_dontReact:{type:Boolean,value:false}},hostAttributes:{h
idden:true},observers:["paramsObjectChanged(paramsObject.*)"],paramsStringChange
d:function(){this._dontReact=true;this.paramsObject=this._decodeParams(this.para
msString);this._dontReact=false},paramsObjectChanged:function(){if(this._dontRea
ct){return}this.paramsString=this._encodeParams(this.paramsObject)},_encodeParam
s:function(params){var encodedParams=[];for(var key in params){var value=params[
key];if(value===""){encodedParams.push(encodeURIComponent(key))}else if(value){e
ncodedParams.push(encodeURIComponent(key)+"="+encodeURIComponent(value.toString(
)))}}return encodedParams.join("&")},_decodeParams:function(paramString){var par
ams={};paramString=(paramString||"").replace(/\+/g,"%20");var paramList=paramStr
ing.split("&");for(var i=0;i<paramList.length;i++){var param=paramList[i].split(
"=");if(param[0]){params[decodeURIComponent(param[0])]=decodeURIComponent(param[
1]||"")}}return params}}); |
| 73 // Copyright 2016 The Chromium Authors. All rights reserved. | 77 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 74 // Use of this source code is governed by a BSD-style license that can be | 78 // Use of this source code is governed by a BSD-style license that can be |
| 75 // found in the LICENSE file. | 79 // found in the LICENSE file. |
| 76 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]}); | 80 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]}); |
| 77 // Copyright 2016 The Chromium Authors. All rights reserved. | 81 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 78 // Use of this source code is governed by a BSD-style license that can be | 82 // Use of this source code is governed by a BSD-style license that can be |
| 79 // found in the LICENSE file. | 83 // found in the LICENSE file. |
| 80 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()}}); | 84 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()}}); |
| 81 // Copyright 2016 The Chromium Authors. All rights reserved. | 85 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 82 // Use of this source code is governed by a BSD-style license that can be | 86 // Use of this source code is governed by a BSD-style license that can be |
| 83 // found in the LICENSE file. | 87 // found in the LICENSE file. |
| 84 cr.define("md_history",function(){var lazyLoadPromise=null;function ensureLazyLo
aded(){if(!lazyLoadPromise){lazyLoadPromise=new Promise(function(resolve,reject)
{Polymer.Base.importHref("chrome://history/lazy_load.html",resolve,reject,true)}
)}return lazyLoadPromise}return{ensureLazyLoaded:ensureLazyLoaded}});Polymer({is
:"history-app",behaviors:[Polymer.IronScrollTargetBehavior],properties:{showSide
barFooter:Boolean,hasSyncedResults:Boolean,selectedPage_:{type:String,observer:"
selectedPageChanged_"},grouped_:{type:Boolean,reflectToAttribute:true},queryStat
e_:{type:Object,value:function(){return{incremental:false,querying:true,querying
Disabled:false,_range:HistoryRange.ALL_TIME,searchTerm:"",groupedOffset:0,set ra
nge(val){this._range=Number(val)},get range(){return this._range}}}},queryResult
_:{type:Object,value:function(){return{info:null,results:null,sessionList:null}}
},hasDrawer_:Boolean,isUserSignedIn_:{type:Boolean,value:loadTimeData.getBoolean
("isUserSignedIn")},toolbarShadow_:{type:Boolean,reflectToAttribute:true,notify:
true},showMenuPromo_:{type:Boolean,value:function(){return loadTimeData.getBoole
an("showMenuPromo")}}},listeners:{"cr-toolbar-menu-promo-close":"onCrToolbarMenu
PromoClose_","cr-toolbar-menu-promo-shown":"onCrToolbarMenuPromoShown_","cr-tool
bar-menu-tap":"onCrToolbarMenuTap_","delete-selected":"deleteSelected","history-
checkbox-select":"checkboxSelected","history-close-drawer":"closeDrawer_","histo
ry-view-changed":"historyViewChanged_","opened-changed":"onOpenedChanged_","unse
lect-all":"unselectAll"},boundOnCanExecute_:null,boundOnCommand_:null,attached:f
unction(){this.grouped_=loadTimeData.getBoolean("groupByDomain");cr.ui.decorate(
"command",cr.ui.Command);this.boundOnCanExecute_=this.onCanExecute_.bind(this);t
his.boundOnCommand_=this.onCommand_.bind(this);document.addEventListener("canExe
cute",this.boundOnCanExecute_);document.addEventListener("command",this.boundOnC
ommand_)},detached:function(){document.removeEventListener("canExecute",this.bou
ndOnCanExecute_);document.removeEventListener("command",this.boundOnCommand_)},o
nFirstRender:function(){setTimeout(function(){chrome.send("metricsHandler:record
Time",["History.ResultsRenderedTime",window.performance.now()])});var searchFiel
d=this.$.toolbar.searchField;if(!searchField.narrow){searchField.getSearchInput(
).focus()}md_history.ensureLazyLoaded().then(function(){window.requestIdleCallba
ck(function(){document.fonts.load("bold 12px Roboto")})})},_scrollHandler:functi
on(){if(this.scrollTarget)this.toolbarShadow_=this.scrollTarget.scrollTop!=0},on
CrToolbarMenuPromoClose_:function(){this.showMenuPromo_=false},onCrToolbarMenuPr
omoShown_:function(){md_history.BrowserService.getInstance().menuPromoShown()},o
nCrToolbarMenuTap_:function(){var drawer=this.$$("#drawer");if(drawer)drawer.tog
gle()},onOpenedChanged_:function(e){if(e.detail.value)this.showMenuPromo_=false}
,checkboxSelected:function(e){var toolbar=this.$.toolbar;toolbar.count=this.$.hi
story.getSelectedItemCount()},unselectAll:function(){var listContainer=this.$.hi
story;var toolbar=this.$.toolbar;listContainer.unselectAllItems(toolbar.count);t
oolbar.count=0},deleteSelected:function(){this.$.history.deleteSelectedWithPromp
t()},historyResult:function(info,results){this.set("queryState_.querying",false)
;this.set("queryResult_.info",info);this.set("queryResult_.results",results);var
listContainer=this.$["history"];listContainer.historyResult(info,results)},focu
sToolbarSearchField:function(){this.$.toolbar.showSearchField()},onCanExecute_:f
unction(e){e=e;switch(e.command.id){case"find-command":case"toggle-grouped":e.ca
nExecute=true;break;case"slash-command":e.canExecute=!this.$.toolbar.searchField
.isSearchFocused();break;case"delete-command":e.canExecute=this.$.toolbar.count>
0;break}},onCommand_:function(e){if(e.command.id=="find-command"||e.command.id==
"slash-command")this.focusToolbarSearchField();if(e.command.id=="delete-command"
)this.deleteSelected();if(e.command.id=="toggle-grouped")this.grouped_=!this.gro
uped_},setForeignSessions:function(sessionList){this.set("queryResult_.sessionLi
st",sessionList)},historyDeleted:function(){this.$.history.historyDeleted()},upd
ateSignInState:function(isUserSignedIn){this.isUserSignedIn_=isUserSignedIn},syn
cedTabsSelected_:function(selectedPage){return selectedPage=="syncedTabs"},shoul
dShowSpinner_:function(querying,incremental,searchTerm){return querying&&!increm
ental&&searchTerm!=""},showSyncNotice_:function(hasSyncedResults,selectedPage){r
eturn hasSyncedResults&&selectedPage!="syncedTabs"},selectedPageChanged_:functio
n(){this.unselectAll();this.historyViewChanged_()},historyViewChanged_:function(
){requestAnimationFrame(function(){md_history.ensureLazyLoaded().then(function()
{if(!this.$.content.selectedItem)return;this.scrollTarget=this.$.content.selecte
dItem.getContentScrollTarget();this._scrollHandler()}.bind(this))}.bind(this));t
his.recordHistoryPageView_()},getSelectedPage_:function(selectedPage,items){retu
rn selectedPage},closeDrawer_:function(){var drawer=this.$$("#drawer");if(drawer
)drawer.close()},recordHistoryPageView_:function(){var histogramValue=HistoryPag
eViewHistogram.END;switch(this.selectedPage_){case"syncedTabs":histogramValue=th
is.isUserSignedIn_?HistoryPageViewHistogram.SYNCED_TABS:HistoryPageViewHistogram
.SIGNIN_PROMO;break;default:switch(this.queryState_.range){case HistoryRange.ALL
_TIME:histogramValue=HistoryPageViewHistogram.HISTORY;break;case HistoryRange.WE
EK:histogramValue=HistoryPageViewHistogram.GROUPED_WEEK;break;case HistoryRange.
MONTH:histogramValue=HistoryPageViewHistogram.GROUPED_MONTH;break}break}md_histo
ry.BrowserService.getInstance().recordHistogram("History.HistoryPageView",histog
ramValue,HistoryPageViewHistogram.END)}}); | 88 cr.define("md_history",function(){var lazyLoadPromise=null;function ensureLazyLo
aded(){if(!lazyLoadPromise){lazyLoadPromise=new Promise(function(resolve,reject)
{Polymer.Base.importHref("chrome://history/lazy_load.html",resolve,reject,true)}
)}return lazyLoadPromise}return{ensureLazyLoaded:ensureLazyLoaded}});Polymer({is
:"history-app",behaviors:[Polymer.IronScrollTargetBehavior],properties:{showSide
barFooter:Boolean,hasSyncedResults:Boolean,selectedPage_:{type:String,observer:"
selectedPageChanged_"},grouped_:{type:Boolean,reflectToAttribute:true},queryStat
e_:{type:Object,value:function(){return{incremental:false,querying:true,querying
Disabled:false,_range:HistoryRange.ALL_TIME,searchTerm:"",groupedOffset:0,set ra
nge(val){this._range=Number(val)},get range(){return this._range}}}},queryResult
_:{type:Object,value:function(){return{info:null,results:null,sessionList:null}}
},hasDrawer_:Boolean,isUserSignedIn_:{type:Boolean,value:loadTimeData.getBoolean
("isUserSignedIn")},toolbarShadow_:{type:Boolean,reflectToAttribute:true,notify:
true},showMenuPromo_:{type:Boolean,value:function(){return loadTimeData.getBoole
an("showMenuPromo")}}},listeners:{"cr-toolbar-menu-promo-close":"onCrToolbarMenu
PromoClose_","cr-toolbar-menu-promo-shown":"onCrToolbarMenuPromoShown_","cr-tool
bar-menu-tap":"onCrToolbarMenuTap_","delete-selected":"deleteSelected","history-
checkbox-select":"checkboxSelected","history-close-drawer":"closeDrawer_","histo
ry-view-changed":"historyViewChanged_","opened-changed":"onOpenedChanged_","unse
lect-all":"unselectAll"},boundOnCanExecute_:null,boundOnCommand_:null,attached:f
unction(){this.grouped_=loadTimeData.getBoolean("groupByDomain");cr.ui.decorate(
"command",cr.ui.Command);this.boundOnCanExecute_=this.onCanExecute_.bind(this);t
his.boundOnCommand_=this.onCommand_.bind(this);document.addEventListener("canExe
cute",this.boundOnCanExecute_);document.addEventListener("command",this.boundOnC
ommand_)},detached:function(){document.removeEventListener("canExecute",this.bou
ndOnCanExecute_);document.removeEventListener("command",this.boundOnCommand_)},o
nFirstRender:function(){setTimeout(function(){chrome.send("metricsHandler:record
Time",["History.ResultsRenderedTime",window.performance.now()])});var searchFiel
d=this.$.toolbar.searchField;if(!searchField.narrow){searchField.getSearchInput(
).focus()}md_history.ensureLazyLoaded().then(function(){window.requestIdleCallba
ck(function(){document.fonts.load("bold 12px Roboto")})})},_scrollHandler:functi
on(){if(this.scrollTarget)this.toolbarShadow_=this.scrollTarget.scrollTop!=0},on
CrToolbarMenuPromoClose_:function(){this.showMenuPromo_=false},onCrToolbarMenuPr
omoShown_:function(){md_history.BrowserService.getInstance().menuPromoShown()},o
nCrToolbarMenuTap_:function(){var drawer=this.$$("#drawer");if(drawer)drawer.tog
gle()},onOpenedChanged_:function(e){if(e.detail.value)this.showMenuPromo_=false}
,checkboxSelected:function(e){var toolbar=this.$.toolbar;toolbar.count=this.$.hi
story.getSelectedItemCount()},unselectAll:function(){var listContainer=this.$.hi
story;var toolbar=this.$.toolbar;listContainer.unselectAllItems(toolbar.count);t
oolbar.count=0},deleteSelected:function(){this.$.history.deleteSelectedWithPromp
t()},historyResult:function(info,results){this.set("queryState_.querying",false)
;this.set("queryResult_.info",info);this.set("queryResult_.results",results);var
listContainer=this.$["history"];listContainer.historyResult(info,results)},focu
sToolbarSearchField:function(){this.$.toolbar.showSearchField()},onCanExecute_:f
unction(e){e=e;switch(e.command.id){case"find-command":case"toggle-grouped":e.ca
nExecute=true;break;case"slash-command":e.canExecute=!this.$.toolbar.searchField
.isSearchFocused();break;case"delete-command":e.canExecute=this.$.toolbar.count>
0;break}},onCommand_:function(e){if(e.command.id=="find-command"||e.command.id==
"slash-command")this.focusToolbarSearchField();if(e.command.id=="delete-command"
)this.deleteSelected();if(e.command.id=="toggle-grouped")this.grouped_=!this.gro
uped_},setForeignSessions:function(sessionList){this.set("queryResult_.sessionLi
st",sessionList)},historyDeleted:function(){this.$.history.historyDeleted()},upd
ateSignInState:function(isUserSignedIn){this.isUserSignedIn_=isUserSignedIn},syn
cedTabsSelected_:function(selectedPage){return selectedPage=="syncedTabs"},shoul
dShowSpinner_:function(querying,incremental,searchTerm){return querying&&!increm
ental&&searchTerm!=""},showSyncNotice_:function(hasSyncedResults,selectedPage){r
eturn hasSyncedResults&&selectedPage!="syncedTabs"},selectedPageChanged_:functio
n(){this.unselectAll();this.historyViewChanged_()},historyViewChanged_:function(
){requestAnimationFrame(function(){md_history.ensureLazyLoaded().then(function()
{if(!this.$.content.selectedItem)return;this.scrollTarget=this.$.content.selecte
dItem.getContentScrollTarget();this._scrollHandler()}.bind(this))}.bind(this));t
his.recordHistoryPageView_()},getSelectedPage_:function(selectedPage,items){retu
rn selectedPage},closeDrawer_:function(){var drawer=this.$$("#drawer");if(drawer
)drawer.close()},recordHistoryPageView_:function(){var histogramValue=HistoryPag
eViewHistogram.END;switch(this.selectedPage_){case"syncedTabs":histogramValue=th
is.isUserSignedIn_?HistoryPageViewHistogram.SYNCED_TABS:HistoryPageViewHistogram
.SIGNIN_PROMO;break;default:switch(this.queryState_.range){case HistoryRange.ALL
_TIME:histogramValue=HistoryPageViewHistogram.HISTORY;break;case HistoryRange.WE
EK:histogramValue=HistoryPageViewHistogram.GROUPED_WEEK;break;case HistoryRange.
MONTH:histogramValue=HistoryPageViewHistogram.GROUPED_MONTH;break}break}md_histo
ry.BrowserService.getInstance().recordHistogram("History.HistoryPageView",histog
ramValue,HistoryPageViewHistogram.END)}}); |
| OLD | NEW |