| 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_"},spinnerActive:{type
:Boolean,value:false},hasDrawer:{type:Boolean,reflectToAttribute:true},isGrouped
Mode:{type:Boolean,reflectToAttribute:true},groupedRange:{type:Number,reflectToA
ttribute:true},groupedOffset:Number,showSyncNotice:{type:Boolean,observer:"showS
yncNoticeChanged_"},syncNoticeVisible_:{type:Boolean,value:false},hasMoreResults
:Boolean,querying:Boolean,queryInfo:Object,showMenuPromo:Boolean},hasDismissList
eners_:false,boundOnDocumentClick_:null,boundOnDocumentKeydown_:null,detached:fu
nction(){if(this.hasDismissListeners_){document.removeEventListener("click",this
.boundOnDocumentClick_);document.removeEventListener("keydown",this.boundOnDocum
entKeydown_)}},get searchField(){return this.$["main-toolbar"].getSearchField()}
,showSearchField:function(){this.searchField.showAndFocus()},changeToolbarView_:
function(){this.itemsSelected_=this.count>0},searchTermChanged_:function(){if(th
is.searchField.getValue()!=this.searchTerm){this.searchField.showAndFocus();this
.searchField.setValue(this.searchTerm)}},showSyncNoticeChanged_:function(){if(!t
his.showSyncNotice)this.syncNoticeVisible_=false},onSearchChanged_:function(even
t){this.fire("change-query",{search:event.detail})},onInfoButtonTap_:function(e)
{this.syncNoticeVisible_=!this.syncNoticeVisible_;e.stopPropagation();if(this.ha
sDismissListeners_)return;this.boundOnDocumentClick_=this.onDocumentClick_.bind(
this);this.boundOnDocumentKeydown_=this.onDocumentKeydown_.bind(this);document.a
ddEventListener("click",this.boundOnDocumentClick_);document.addEventListener("k
eydown",this.boundOnDocumentKeydown_);this.hasDismissListeners_=true},onDocument
Click_:function(e){if(e.path.indexOf(this.$["sync-notice"])==-1)this.syncNoticeV
isible_=false},onDocumentKeydown_:function(e){if(e.key=="Escape")this.syncNotice
Visible_=false},onClearSelectionTap_:function(){this.fire("unselect-all")},onDel
eteTap_:function(){this.fire("delete-selected")},deletingAllowed_:function(){ret
urn loadTimeData.getBoolean("allowDeletingHistory")},numberOfItemsSelected_:func
tion(count){return count>0?loadTimeData.getStringF("itemsSelected",count):""},ge
tHistoryInterval_:function(){var info=this.queryInfo;if(!info)return;if(this.gro
upedRange==HistoryRange.WEEK)return info.queryInterval;if(this.groupedRange==His
toryRange.MONTH)return info.queryStartMonth},onTabSelected_:function(e){this.fir
e("change-query",{range:Number(e.detail.item.getAttribute("value"))})},changeOff
set_:function(newOffset){if(!this.querying)this.fire("change-query",{offset:newO
ffset})},onTodayTap_:function(){this.changeOffset_(0)},onPrevTap_:function(){thi
s.changeOffset_(this.groupedOffset+1)},onNextTap_:function(){this.changeOffset_(
this.groupedOffset-1)},isToday_:function(){return this.groupedOffset==0}});(func
tion(){"use strict";Polymer.IronA11yAnnouncer=Polymer({is:"iron-a11y-announcer",
properties:{mode:{type:String,value:"polite"},_text:{type:String,value:""}},crea
ted:function(){if(!Polymer.IronA11yAnnouncer.instance){Polymer.IronA11yAnnouncer
.instance=this}document.body.addEventListener("iron-announce",this._onIronAnnoun
ce.bind(this))},announce:function(text){this._text="";this.async(function(){this
._text=text},100)},_onIronAnnounce:function(event){if(event.detail&&event.detail
.text){this.announce(event.detail.text)}}});Polymer.IronA11yAnnouncer.instance=n
ull;Polymer.IronA11yAnnouncer.requestAvailability=function(){if(!Polymer.IronA11
yAnnouncer.instance){Polymer.IronA11yAnnouncer.instance=document.createElement("
iron-a11y-announcer")}document.body.appendChild(Polymer.IronA11yAnnouncer.instan
ce)}})();(function(){var IOS=navigator.userAgent.match(/iP(?:hone|ad;(?: U;)? CP
U) 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:{t
ype: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,value:false},selectedIt
em:{type:Object,notify:true},selectedItems:{type:Object,notify:true},multiSelect
ion:{type:Boolean,value:false}},observers:["_itemsChanged(items.*)","_selectionE
nabledChanged(selectionEnabled)","_multiSelectionChanged(multiSelection)","_setO
verflow(scrollTarget)"],behaviors:[Polymer.Templatizer,Polymer.IronResizableBeha
vior,Polymer.IronA11yKeysBehavior,Polymer.IronScrollTargetBehavior],keyBindings:
{up:"_didMoveUp",down:"_didMoveDown",enter:"_didEnter"},_ratio:.5,_scrollerPaddi
ngTop:0,_scrollPosition:0,_physicalSize:0,_physicalAverage:0,_physicalAverageCou
nt:0,_physicalTop:0,_virtualCount:0,_physicalIndexForKey:null,_estScrollHeight:0
,_scrollHeight:0,_viewportHeight:0,_viewportWidth:0,_physicalItems:null,_physica
lSizes:null,_firstVisibleIndexVal:null,_lastVisibleIndexVal:null,_collection:nul
l,_maxPages:2,_focusedItem:null,_focusedIndex:-1,_offscreenFocusedItem:null,_foc
usBackfillItem:null,_itemsPerRow:1,_itemWidth:0,_rowHeight:0,_templateCost:0,get
_physicalBottom(){return this._physicalTop+this._physicalSize},get _scrollBotto
m(){return this._scrollPosition+this._viewportHeight},get _virtualEnd(){return t
his._virtualStart+this._physicalCount-1},get _hiddenContentSize(){var size=this.
grid?this._physicalRows*this._rowHeight:this._physicalSize;return size-this._vie
wportHeight},get _maxScrollTop(){return this._estScrollHeight-this._viewportHeig
ht+this._scrollerPaddingTop},_minVirtualStart:0,get _maxVirtualStart(){return Ma
th.max(0,this._virtualCount-this._physicalCount)},_virtualStartVal:0,set _virtua
lStart(val){this._virtualStartVal=Math.min(this._maxVirtualStart,Math.max(this._
minVirtualStart,val))},get _virtualStart(){return this._virtualStartVal||0},_phy
sicalStartVal:0,set _physicalStart(val){this._physicalStartVal=val%this._physica
lCount;if(this._physicalStartVal<0){this._physicalStartVal=this._physicalCount+t
his._physicalStartVal}this._physicalEnd=(this._physicalStart+this._physicalCount
-1)%this._physicalCount},get _physicalStart(){return this._physicalStartVal||0},
_physicalCountVal:0,set _physicalCount(val){this._physicalCountVal=val;this._phy
sicalEnd=(this._physicalStart+this._physicalCount-1)%this._physicalCount},get _p
hysicalCount(){return this._physicalCountVal},_physicalEnd:0,get _optPhysicalSiz
e(){if(this.grid){return this._estRowsInView*this._rowHeight*this._maxPages}retu
rn this._viewportHeight*this._maxPages},get _isVisible(){return Boolean(this.off
setWidth||this.offsetHeight)},get firstVisibleIndex(){if(this._firstVisibleIndex
Val===null){var physicalOffset=Math.floor(this._physicalTop+this._scrollerPaddin
gTop);this._firstVisibleIndexVal=this._iterateItems(function(pidx,vidx){physical
Offset+=this._getPhysicalSizeIncrement(pidx);if(physicalOffset>this._scrollPosit
ion){return this.grid?vidx-vidx%this._itemsPerRow:vidx}if(this.grid&&this._virtu
alCount-1===vidx){return vidx-vidx%this._itemsPerRow}})||0}return this._firstVis
ibleIndexVal},get lastVisibleIndex(){if(this._lastVisibleIndexVal===null){if(thi
s.grid){var lastIndex=this.firstVisibleIndex+this._estRowsInView*this._itemsPerR
ow-1;this._lastVisibleIndexVal=Math.min(this._virtualCount,lastIndex)}else{var p
hysicalOffset=this._physicalTop;this._iterateItems(function(pidx,vidx){if(physic
alOffset<this._scrollBottom){this._lastVisibleIndexVal=vidx}else{return true}phy
sicalOffset+=this._getPhysicalSizeIncrement(pidx)})}}return this._lastVisibleInd
exVal},get _defaultScrollTarget(){return this},get _virtualRowCount(){return Mat
h.ceil(this._virtualCount/this._itemsPerRow)},get _estRowsInView(){return Math.c
eil(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(){if(this._physicalCou
nt===0){this._debounceTemplate(this._render)}this.listen(this,"iron-resize","_re
sizeHandler")},detached:function(){this.unlisten(this,"iron-resize","_resizeHand
ler")},_setOverflow:function(scrollTarget){this.style.webkitOverflowScrolling=sc
rollTarget===this?"touch":"";this.style.overflow=scrollTarget===this?"auto":""},
updateViewportBoundaries:function(){this._scrollerPaddingTop=this.scrollTarget==
=this?0:parseInt(window.getComputedStyle(this)["padding-top"],10);this._viewport
Width=this.$.items.offsetWidth;this._viewportHeight=this._scrollTargetHeight;thi
s.grid&&this._updateGridMetrics()},_scrollHandler:function(){var scrollTop=Math.
max(0,Math.min(this._maxScrollTop,this._scrollTop));var delta=scrollTop-this._sc
rollPosition;var isScrollingDown=delta>=0;this._scrollPosition=scrollTop;this._f
irstVisibleIndexVal=null;this._lastVisibleIndexVal=null;if(Math.abs(delta)>this.
_physicalSize){var idxAdjustment=Math.round(delta/this._physicalAverage)*this._i
temsPerRow;this._physicalTop=this._physicalTop+delta;this._virtualStart=this._vi
rtualStart+idxAdjustment;this._physicalStart=this._physicalStart+idxAdjustment;t
his._update()}else{var reusables=this._getReusables(isScrollingDown);if(isScroll
ingDown){this._physicalTop=reusables.physicalTop;this._virtualStart=this._virtua
lStart+reusables.indexes.length;this._physicalStart=this._physicalStart+reusable
s.indexes.length}else{this._virtualStart=this._virtualStart-reusables.indexes.le
ngth;this._physicalStart=this._physicalStart-reusables.indexes.length}if(reusabl
es.indexes.length===0){this._increasePoolIfNeeded()}else{this._update(reusables.
indexes,isScrollingDown?null:reusables.indexes)}}},_getReusables:function(fromTo
p){var ith,lastIth,offsetContent,physicalItemHeight;var idxs=[];var protectedOff
setContent=this._hiddenContentSize*this._ratio;var virtualStart=this._virtualSta
rt;var virtualEnd=this._virtualEnd;var physicalCount=this._physicalCount;var phy
sicalTop=this._physicalTop+this._scrollerPaddingTop;var scrollTop=this._scrollTo
p;var scrollBottom=this._scrollBottom;if(fromTop){ith=this._physicalStart;lastIt
h=this._physicalEnd;offsetContent=scrollTop-physicalTop}else{ith=this._physicalE
nd;lastIth=this._physicalStart;offsetContent=this._physicalBottom-scrollBottom}w
hile(true){physicalItemHeight=this._getPhysicalSizeIncrement(ith);offsetContent=
offsetContent-physicalItemHeight;if(idxs.length>=physicalCount||offsetContent<=p
rotectedOffsetContent){break}if(fromTop){if(virtualEnd+idxs.length+1>=this._virt
ualCount){break}if(physicalTop+physicalItemHeight>=scrollTop){break}idxs.push(it
h);physicalTop=physicalTop+physicalItemHeight;ith=(ith+1)%physicalCount}else{if(
virtualStart-idxs.length<=0){break}if(physicalTop+this._physicalSize-physicalIte
mHeight<=scrollBottom){break}idxs.push(ith);physicalTop=physicalTop-physicalItem
Height;ith=ith===0?physicalCount-1:ith-1}}return{indexes:idxs,physicalTop:physic
alTop-this._scrollerPaddingTop}},_update:function(itemSet,movingUp){if(itemSet&&
itemSet.length===0){return}this._manageFocus();this._assignModels(itemSet);this.
_updateMetrics(itemSet);if(movingUp){while(movingUp.length){var idx=movingUp.pop
();this._physicalTop-=this._getPhysicalSizeIncrement(idx)}}this._positionItems()
;this._updateScrollerSize();this._increasePoolIfNeeded()},_createPool:function(s
ize){var physicalItems=new Array(size);this._ensureTemplatized();for(var i=0;i<s
ize;i++){var inst=this.stamp(null);physicalItems[i]=inst.root.querySelector("*")
;Polymer.dom(this).appendChild(inst.root)}return physicalItems},_increasePoolIfN
eeded:function(){if(this._viewportHeight===0){return false}var self=this;var isC
lientFull=this._physicalBottom>=this._scrollBottom&&this._physicalTop<=this._scr
ollPosition;if(this._physicalSize>=this._optPhysicalSize&&isClientFull){return f
alse}var maxPoolSize=Math.round(this._physicalCount*.5);if(!isClientFull){this._
debounceTemplate(this._increasePool.bind(this,maxPoolSize));return true}this._yi
eld(function(){self._increasePool(Math.min(maxPoolSize,Math.max(1,Math.round(50/
self._templateCost))))});return true},_yield:function(cb){var g=window;var handl
e=g.requestIdleCallback?g.requestIdleCallback(cb):g.setTimeout(cb,16);Polymer.do
m.addDebouncer({complete:function(){g.cancelIdleCallback?g.cancelIdleCallback(ha
ndle):g.clearTimeout(handle);cb()}})},_increasePool:function(missingItems){var n
extPhysicalCount=Math.min(this._physicalCount+missingItems,this._virtualCount-th
is._virtualStart,Math.max(this.maxPhysicalCount,DEFAULT_PHYSICAL_COUNT));var pre
vPhysicalCount=this._physicalCount;var delta=nextPhysicalCount-prevPhysicalCount
;var ts=window.performance.now();if(delta<=0){return}[].push.apply(this._physica
lItems,this._createPool(delta));[].push.apply(this._physicalSizes,new Array(delt
a));this._physicalCount=prevPhysicalCount+delta;if(this._physicalStart>this._phy
sicalEnd&&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
.updateViewportBoundaries();this._increasePool(DEFAULT_PHYSICAL_COUNT)}else{var
reusables=this._getReusables(true);this._physicalTop=reusables.physicalTop;this.
_virtualStart=this._virtualStart+reusables.indexes.length;this._physicalStart=th
is._physicalStart+reusables.indexes.length;this._update(reusables.indexes);this.
_update()}}},_ensureTemplatized:function(){if(!this.ctor){var props={};props.__k
ey__=true;props[this.as]=true;props[this.indexAs]=true;props[this.selectedAs]=tr
ue;props.tabIndex=true;this._instanceProps=props;this._userTemplate=Polymer.dom(
this).querySelector("template");if(this._userTemplate){this.templatize(this._use
rTemplate)}else{console.warn("iron-list requires a template to be provided in li
ght-dom")}}},_getStampedChildren:function(){return this._physicalItems},_forward
InstancePath:function(inst,path,value){if(path.indexOf(this.as+".")===0){this.no
tifyPath("items."+inst.__key__+"."+path.slice(this.as.length+1),value)}},_forwar
dParentProp:function(prop,value){if(this._physicalItems){this._physicalItems.for
Each(function(item){item._templateInstance[prop]=value},this)}},_forwardParentPa
th:function(path,value){if(this._physicalItems){this._physicalItems.forEach(func
tion(item){item._templateInstance.notifyPath(path,value,true)},this)}},_forwardI
temPath:function(path,value){if(!this._physicalIndexForKey){return}var dot=path.
indexOf(".");var key=path.substring(0,dot<0?path.length:dot);var idx=this._physi
calIndexForKey[key];var offscreenItem=this._offscreenFocusedItem;var el=offscree
nItem&&offscreenItem._templateInstance.__key__===key?offscreenItem:this._physica
lItems[idx];if(!el||el._templateInstance.__key__!==key){return}if(dot>=0){path=t
his.as+"."+path.substring(dot+1);el._templateInstance.notifyPath(path,value,true
)}else{var currentItem=el._templateInstance[this.as];if(Array.isArray(this.selec
tedItems)){for(var i=0;i<this.selectedItems.length;i++){if(this.selectedItems[i]
===currentItem){this.set("selectedItems."+i,value);break}}}else if(this.selected
Item===currentItem){this.set("selectedItem",value)}el._templateInstance[this.as]
=value}},_itemsChanged:function(change){if(change.path==="items"){this._virtualS
tart=0;this._physicalTop=0;this._virtualCount=this.items?this.items.length:0;thi
s._collection=this.items?Polymer.Collection.get(this.items):null;this._physicalI
ndexForKey={};this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null;thi
s._physicalCount=this._physicalCount||0;this._physicalItems=this._physicalItems|
|[];this._physicalSizes=this._physicalSizes||[];this._physicalStart=0;this._rese
tScrollPosition(0);this._removeFocusedItem();this._debounceTemplate(this._render
)}else if(change.path==="items.splices"){this._adjustVirtualIndex(change.value.i
ndexSplices);this._virtualCount=this.items?this.items.length:0;this._debounceTem
plate(this._render)}else{this._forwardItemPath(change.path.split(".").slice(1).j
oin("."),change.value)}},_adjustVirtualIndex:function(splices){splices.forEach(f
unction(splice){splice.removed.forEach(this._removeItem,this);if(splice.index<th
is._virtualStart){var delta=Math.max(splice.addedCount-splice.removed.length,spl
ice.index-this._virtualStart);this._virtualStart=this._virtualStart+delta;if(thi
s._focusedIndex>=0){this._focusedIndex=this._focusedIndex+delta}}},this)},_remov
eItem:function(item){this.$.selector.deselect(item);if(this._focusedItem&&this._
focusedItem._templateInstance[this.as]===item){this._removeFocusedItem()}},_iter
ateItems:function(fn,itemSet){var pidx,vidx,rtn,i;if(arguments.length===2&&itemS
et){for(i=0;i<itemSet.length;i++){pidx=itemSet[i];vidx=this._computeVidx(pidx);i
f((rtn=fn.call(this,pidx,vidx))!=null){return rtn}}}else{pidx=this._physicalStar
t;vidx=this._virtualStart;for(;pidx<this._physicalCount;pidx++,vidx++){if((rtn=f
n.call(this,pidx,vidx))!=null){return rtn}}for(pidx=0;pidx<this._physicalStart;p
idx++,vidx++){if((rtn=fn.call(this,pidx,vidx))!=null){return rtn}}}},_computeVid
x:function(pidx){if(pidx>=this._physicalStart){return this._virtualStart+(pidx-t
his._physicalStart)}return this._virtualStart+(this._physicalCount-this._physica
lStart)+pidx},_assignModels:function(itemSet){this._iterateItems(function(pidx,v
idx){var el=this._physicalItems[pidx];var inst=el._templateInstance;var item=thi
s.items&&this.items[vidx];if(item!=null){inst[this.as]=item;inst.__key__=this._c
ollection.getKey(item);inst[this.selectedAs]=this.$.selector.isSelected(item);in
st[this.indexAs]=vidx;inst.tabIndex=this._focusedIndex===vidx?0:-1;this._physica
lIndexForKey[inst.__key__]=pidx;el.removeAttribute("hidden")}else{inst.__key__=n
ull;el.setAttribute("hidden","")}},itemSet)},_updateMetrics:function(itemSet){Po
lymer.dom.flush();var newPhysicalSize=0;var oldPhysicalSize=0;var prevAvgCount=t
his._physicalAverageCount;var prevPhysicalAvg=this._physicalAverage;this._iterat
eItems(function(pidx,vidx){oldPhysicalSize+=this._physicalSizes[pidx]||0;this._p
hysicalSizes[pidx]=this._physicalItems[pidx].offsetHeight;newPhysicalSize+=this.
_physicalSizes[pidx];this._physicalAverageCount+=this._physicalSizes[pidx]?1:0},
itemSet);if(this.grid){this._updateGridMetrics();this._physicalSize=Math.ceil(th
is._physicalCount/this._itemsPerRow)*this._rowHeight}else{this._physicalSize=thi
s._physicalSize+newPhysicalSize-oldPhysicalSize}if(this._physicalAverageCount!==
prevAvgCount){this._physicalAverage=Math.round((prevPhysicalAvg*prevAvgCount+new
PhysicalSize)/this._physicalAverageCount)}},_updateGridMetrics:function(){this._
itemWidth=this._physicalCount>0?this._physicalItems[0].getBoundingClientRect().w
idth:200;this._rowHeight=this._physicalCount>0?this._physicalItems[0].offsetHeig
ht:200;this._itemsPerRow=this._itemWidth?Math.floor(this._viewportWidth/this._it
emWidth):this._itemsPerRow},_positionItems:function(){this._adjustScrollPosition
();var y=this._physicalTop;if(this.grid){var totalItemWidth=this._itemsPerRow*th
is._itemWidth;var rowOffset=(this._viewportWidth-totalItemWidth)/2;this._iterate
Items(function(pidx,vidx){var modulus=vidx%this._itemsPerRow;var x=Math.floor(mo
dulus*this._itemWidth+rowOffset);this.translate3d(x+"px",y+"px",0,this._physical
Items[pidx]);if(this._shouldRenderNextRow(vidx)){y+=this._rowHeight}})}else{this
._iterateItems(function(pidx,vidx){this.translate3d(0,y+"px",0,this._physicalIte
ms[pidx]);y+=this._physicalSizes[pidx]})}},_getPhysicalSizeIncrement:function(pi
dx){if(!this.grid){return this._physicalSizes[pidx]}if(this._computeVidx(pidx)%t
his._itemsPerRow!==this._itemsPerRow-1){return 0}return this._rowHeight},_should
RenderNextRow:function(vidx){return vidx%this._itemsPerRow===this._itemsPerRow-1
},_adjustScrollPosition:function(){var deltaHeight=this._virtualStart===0?this._
physicalTop:Math.min(this._scrollPosition+this._physicalTop,0);if(deltaHeight){t
his._physicalTop=this._physicalTop-deltaHeight;if(!IOS_TOUCH_SCROLLING&&this._ph
ysicalTop!==0){this._resetScrollPosition(this._scrollTop-deltaHeight)}}},_resetS
crollPosition:function(pos){if(this.scrollTarget){this._scrollTop=pos;this._scro
llPosition=this._scrollTop}},_updateScrollerSize:function(forceUpdate){if(this.g
rid){this._estScrollHeight=this._virtualRowCount*this._rowHeight}else{this._estS
crollHeight=this._physicalBottom+Math.max(this._virtualCount-this._physicalCount
-this._virtualStart,0)*this._physicalAverage}forceUpdate=forceUpdate||this._scro
llHeight===0;forceUpdate=forceUpdate||this._scrollPosition>=this._estScrollHeigh
t-this._physicalSize;forceUpdate=forceUpdate||this.grid&&this.$.items.style.heig
ht<this._estScrollHeight;if(forceUpdate||Math.abs(this._estScrollHeight-this._sc
rollHeight)>=this._optPhysicalSize){this.$.items.style.height=this._estScrollHei
ght+"px";this._scrollHeight=this._estScrollHeight}},scrollToItem:function(item){
return this.scrollToIndex(this.items.indexOf(item))},scrollToIndex:function(idx)
{if(typeof idx!=="number"||idx<0||idx>this.items.length-1){return}Polymer.dom.fl
ush();if(this._physicalCount===0){return}idx=Math.min(Math.max(idx,0),this._virt
ualCount-1);if(!this._isIndexRendered(idx)||idx>=this._maxVirtualStart){this._vi
rtualStart=this.grid?idx-this._itemsPerRow*2:idx-1}this._manageFocus();this._ass
ignModels();this._updateMetrics();this._physicalTop=Math.floor(this._virtualStar
t/this._itemsPerRow)*this._physicalAverage;var currentTopItem=this._physicalStar
t;var currentVirtualItem=this._virtualStart;var targetOffsetTop=0;var hiddenCont
entSize=this._hiddenContentSize;while(currentVirtualItem<idx&&targetOffsetTop<=h
iddenContentSize){targetOffsetTop=targetOffsetTop+this._getPhysicalSizeIncrement
(currentTopItem);currentTopItem=(currentTopItem+1)%this._physicalCount;currentVi
rtualItem++}this._updateScrollerSize(true);this._positionItems();this._resetScro
llPosition(this._physicalTop+this._scrollerPaddingTop+targetOffsetTop);this._inc
reasePoolIfNeeded();this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=nu
ll},_resetAverage:function(){this._physicalAverage=0;this._physicalAverageCount=
0},_resizeHandler:function(){var delta=Math.abs(this._viewportHeight-this._scrol
lTargetHeight);if(IOS&&delta>0&&delta<100){return}Polymer.dom.addDebouncer(this.
debounce("_debounceTemplate",function(){this.updateViewportBoundaries();this._re
nder();if(this._isVisible){this.toggleScrollListener(true);if(this._physicalCoun
t>0){this._resetAverage();this.scrollToIndex(this.firstVisibleIndex)}}else{this.
toggleScrollListener(false)}}.bind(this),1))},_getModelFromItem:function(item){v
ar key=this._collection.getKey(item);var pidx=this._physicalIndexForKey[key];if(
pidx!=null){return this._physicalItems[pidx]._templateInstance}return null},_get
NormalizedItem:function(item){if(this._collection.getKey(item)===undefined){if(t
ypeof item==="number"){item=this.items[item];if(!item){throw new RangeError("<it
em> not found")}return item}throw new TypeError("<item> should be a valid item")
}return item},selectItem:function(item){item=this._getNormalizedItem(item);var m
odel=this._getModelFromItem(item);if(!this.multiSelection&&this.selectedItem){th
is.deselectItem(this.selectedItem)}if(model){model[this.selectedAs]=true}this.$.
selector.select(item);this.updateSizeForItem(item)},deselectItem:function(item){
item=this._getNormalizedItem(item);var model=this._getModelFromItem(item);if(mod
el){model[this.selectedAs]=false}this.$.selector.deselect(item);this.updateSizeF
orItem(item)},toggleSelectionForItem:function(item){item=this._getNormalizedItem
(item);if(this.$.selector.isSelected(item)){this.deselectItem(item)}else{this.se
lectItem(item)}},clearSelection:function(){function unselect(item){var model=thi
s._getModelFromItem(item);if(model){model[this.selectedAs]=false}}if(Array.isArr
ay(this.selectedItems)){this.selectedItems.forEach(unselect,this)}else if(this.s
electedItem){unselect.call(this,this.selectedItem)}this.$.selector.clearSelectio
n()},_selectionEnabledChanged:function(selectionEnabled){var handler=selectionEn
abled?this.listen:this.unlisten;handler.call(this,this,"tap","_selectionHandler"
)},_selectionHandler:function(e){var model=this.modelForElement(e.target);if(!mo
del){return}var modelTabIndex,activeElTabIndex;var target=Polymer.dom(e).path[0]
;var activeEl=Polymer.dom(this.domHost?this.domHost.root:document).activeElement
;var physicalItem=this._physicalItems[this._getPhysicalIndex(model[this.indexAs]
)];if(target.localName==="input"||target.localName==="button"||target.localName=
=="select"){return}modelTabIndex=model.tabIndex;model.tabIndex=SECRET_TABINDEX;a
ctiveElTabIndex=activeEl?activeEl.tabIndex:-1;model.tabIndex=modelTabIndex;if(ac
tiveEl&&physicalItem!==activeEl&&physicalItem.contains(activeEl)&&activeElTabInd
ex!==SECRET_TABINDEX){return}this.toggleSelectionForItem(model[this.as])},_multi
SelectionChanged:function(multiSelection){this.clearSelection();this.$.selector.
multi=multiSelection},updateSizeForItem:function(item){item=this._getNormalizedI
tem(item);var key=this._collection.getKey(item);var pidx=this._physicalIndexForK
ey[key];if(pidx!=null){this._updateMetrics([pidx]);this._positionItems()}},_mana
geFocus:function(){var fidx=this._focusedIndex;if(fidx>=0&&fidx<this._virtualCou
nt){if(this._isIndexRendered(fidx)){this._restoreFocusedItem()}else{this._create
FocusBackfillItem()}}else if(this._virtualCount>0&&this._physicalCount>0){this._
focusedIndex=this._virtualStart;this._focusedItem=this._physicalItems[this._phys
icalStart]}},_isIndexRendered:function(idx){return idx>=this._virtualStart&&idx<
=this._virtualEnd},_isIndexVisible:function(idx){return idx>=this.firstVisibleIn
dex&&idx<=this.lastVisibleIndex},_getPhysicalIndex:function(idx){return this._ph
ysicalIndexForKey[this._collection.getKey(this._getNormalizedItem(idx))]},_focus
PhysicalItem:function(idx){if(idx<0||idx>=this._virtualCount){return}this._resto
reFocusedItem();if(!this._isIndexRendered(idx)){this.scrollToIndex(idx)}var phys
icalItem=this._physicalItems[this._getPhysicalIndex(idx)];var model=physicalItem
._templateInstance;var focusable;model.tabIndex=SECRET_TABINDEX;if(physicalItem.
tabIndex===SECRET_TABINDEX){focusable=physicalItem}if(!focusable){focusable=Poly
mer.dom(physicalItem).querySelector('[tabindex="'+SECRET_TABINDEX+'"]')}model.ta
bIndex=0;this._focusedIndex=idx;focusable&&focusable.focus()},_removeFocusedItem
:function(){if(this._offscreenFocusedItem){Polymer.dom(this).removeChild(this._o
ffscreenFocusedItem)}this._offscreenFocusedItem=null;this._focusBackfillItem=nul
l;this._focusedItem=null;this._focusedIndex=-1},_createFocusBackfillItem:functio
n(){var fidx=this._focusedIndex;var pidx=this._getPhysicalIndex(fidx);if(this._o
ffscreenFocusedItem||pidx==null||fidx<0){return}if(!this._focusBackfillItem){var
stampedTemplate=this.stamp(null);this._focusBackfillItem=stampedTemplate.root.q
uerySelector("*");Polymer.dom(this).appendChild(stampedTemplate.root)}this._offs
creenFocusedItem=this._physicalItems[pidx];this._offscreenFocusedItem._templateI
nstance.tabIndex=0;this._physicalItems[pidx]=this._focusBackfillItem;this.transl
ate3d(0,HIDDEN_Y,0,this._offscreenFocusedItem)},_restoreFocusedItem:function(){v
ar pidx,fidx=this._focusedIndex;if(!this._offscreenFocusedItem||this._focusedInd
ex<0){return}this._assignModels();pidx=this._getPhysicalIndex(fidx);if(pidx!=nul
l){this._focusBackfillItem=this._physicalItems[pidx];this._focusBackfillItem._te
mplateInstance.tabIndex=-1;this._physicalItems[pidx]=this._offscreenFocusedItem;
this._offscreenFocusedItem=null;this.translate3d(0,HIDDEN_Y,0,this._focusBackfil
lItem)}},_didFocus:function(e){var targetModel=this.modelForElement(e.target);va
r focusedModel=this._focusedItem?this._focusedItem._templateInstance:null;var ha
sOffscreenFocusedItem=this._offscreenFocusedItem!==null;var fidx=this._focusedIn
dex;if(!targetModel||!focusedModel){return}if(focusedModel===targetModel){if(!th
is._isIndexVisible(fidx)){this.scrollToIndex(fidx)}}else{this._restoreFocusedIte
m();focusedModel.tabIndex=-1;targetModel.tabIndex=0;fidx=targetModel[this.indexA
s];this._focusedIndex=fidx;this._focusedItem=this._physicalItems[this._getPhysic
alIndex(fidx)];if(hasOffscreenFocusedItem&&!this._offscreenFocusedItem){this._up
date()}}},_didMoveUp:function(){this._focusPhysicalItem(this._focusedIndex-1)},_
didMoveDown:function(e){e.detail.keyboardEvent.preventDefault();this._focusPhysi
calItem(this._focusedIndex+1)},_didEnter:function(e){this._focusPhysicalItem(thi
s._focusedIndex);this._selectionHandler(e.detail.keyboardEvent)}})})();Polymer({
is:"iron-scroll-threshold",properties:{upperThreshold:{type:Number,value:100},lo
werThreshold:{type:Number,value:100},upperTriggered:{type:Boolean,value:false,no
tify:true,readOnly:true},lowerTriggered:{type:Boolean,value:false,notify:true,re
adOnly:true},horizontal:{type:Boolean,value:false}},behaviors:[Polymer.IronScrol
lTargetBehavior],observers:["_setOverflow(scrollTarget)","_initCheck(horizontal,
isAttached)"],get _defaultScrollTarget(){return this},_setOverflow:function(scr
ollTarget){this.style.overflow=scrollTarget===this?"auto":""},_scrollHandler:fun
ction(){var THROTTLE_THRESHOLD=200;if(!this.isDebouncerActive("_checkTheshold"))
{this.debounce("_checkTheshold",function(){this.checkScrollThesholds()},THROTTLE
_THRESHOLD)}},_initCheck:function(horizontal,isAttached){if(isAttached){this.deb
ounce("_init",function(){this.clearTriggers();this.checkScrollThesholds()})}},ch
eckScrollThesholds:function(){if(!this.scrollTarget||this.lowerTriggered&&this.u
pperTriggered){return}var upperScrollValue=this.horizontal?this._scrollLeft:this
._scrollTop;var lowerScrollValue=this.horizontal?this.scrollTarget.scrollWidth-t
his._scrollTargetWidth-this._scrollLeft:this.scrollTarget.scrollHeight-this._scr
ollTargetHeight-this._scrollTop;if(upperScrollValue<=this.upperThreshold&&!this.
upperTriggered){this._setUpperTriggered(true);this.fire("upper-threshold")}if(lo
werScrollValue<=this.lowerThreshold&&!this.lowerTriggered){this._setLowerTrigger
ed(true);this.fire("lower-threshold")}},clearTriggers:function(){this._setUpperT
riggered(false);this._setLowerTriggered(false)}}); | 40 Polymer({is:"history-toolbar",properties:{count:{type:Number,value:0,observer:"c
hangeToolbarView_"},itemsSelected_:{type:Boolean,value:false,reflectToAttribute:
true},searchTerm:{type:String,observer:"searchTermChanged_"},spinnerActive:{type
:Boolean,value:false},hasDrawer:{type:Boolean,reflectToAttribute:true},isGrouped
Mode:{type:Boolean,reflectToAttribute:true},groupedRange:{type:Number,reflectToA
ttribute:true},groupedOffset:Number,showSyncNotice:{type:Boolean,observer:"showS
yncNoticeChanged_"},syncNoticeVisible_:{type:Boolean,value:false},hasMoreResults
:Boolean,querying:Boolean,queryInfo:Object,showMenuPromo:Boolean},hasDismissList
eners_:false,boundOnDocumentClick_:null,boundOnDocumentKeydown_:null,detached:fu
nction(){if(this.hasDismissListeners_){document.removeEventListener("click",this
.boundOnDocumentClick_);document.removeEventListener("keydown",this.boundOnDocum
entKeydown_)}},get searchField(){return this.$["main-toolbar"].getSearchField()}
,showSearchField:function(){this.searchField.showAndFocus()},changeToolbarView_:
function(){this.itemsSelected_=this.count>0},searchTermChanged_:function(){if(th
is.searchField.getValue()!=this.searchTerm){this.searchField.showAndFocus();this
.searchField.setValue(this.searchTerm)}},showSyncNoticeChanged_:function(){if(!t
his.showSyncNotice)this.syncNoticeVisible_=false},onSearchChanged_:function(even
t){this.fire("change-query",{search:event.detail})},onInfoButtonTap_:function(e)
{this.syncNoticeVisible_=!this.syncNoticeVisible_;e.stopPropagation();if(this.ha
sDismissListeners_)return;this.boundOnDocumentClick_=this.onDocumentClick_.bind(
this);this.boundOnDocumentKeydown_=this.onDocumentKeydown_.bind(this);document.a
ddEventListener("click",this.boundOnDocumentClick_);document.addEventListener("k
eydown",this.boundOnDocumentKeydown_);this.hasDismissListeners_=true},onDocument
Click_:function(e){if(e.path.indexOf(this.$["sync-notice"])==-1)this.syncNoticeV
isible_=false},onDocumentKeydown_:function(e){if(e.key=="Escape")this.syncNotice
Visible_=false},onClearSelectionTap_:function(){this.fire("unselect-all")},onDel
eteTap_:function(){this.fire("delete-selected")},numberOfItemsSelected_:function
(count){return count>0?loadTimeData.getStringF("itemsSelected",count):""},getHis
toryInterval_:function(){var info=this.queryInfo;if(!info)return;if(this.grouped
Range==HistoryRange.WEEK)return info.queryInterval;if(this.groupedRange==History
Range.MONTH)return info.queryStartMonth},onTabSelected_:function(e){this.fire("c
hange-query",{range:Number(e.detail.item.getAttribute("value"))})},changeOffset_
:function(newOffset){if(!this.querying)this.fire("change-query",{offset:newOffse
t})},onTodayTap_:function(){this.changeOffset_(0)},onPrevTap_:function(){this.ch
angeOffset_(this.groupedOffset+1)},onNextTap_:function(){this.changeOffset_(this
.groupedOffset-1)},isToday_:function(){return this.groupedOffset==0}});(function
(){"use strict";Polymer.IronA11yAnnouncer=Polymer({is:"iron-a11y-announcer",prop
erties:{mode:{type:String,value:"polite"},_text:{type:String,value:""}},created:
function(){if(!Polymer.IronA11yAnnouncer.instance){Polymer.IronA11yAnnouncer.ins
tance=this}document.body.addEventListener("iron-announce",this._onIronAnnounce.b
ind(this))},announce:function(text){this._text="";this.async(function(){this._te
xt=text},100)},_onIronAnnounce:function(event){if(event.detail&&event.detail.tex
t){this.announce(event.detail.text)}}});Polymer.IronA11yAnnouncer.instance=null;
Polymer.IronA11yAnnouncer.requestAvailability=function(){if(!Polymer.IronA11yAnn
ouncer.instance){Polymer.IronA11yAnnouncer.instance=document.createElement("iron
-a11y-announcer")}document.body.appendChild(Polymer.IronA11yAnnouncer.instance)}
})();(function(){var IOS=navigator.userAgent.match(/iP(?:hone|ad;(?: U;)? CPU) O
S (\d+)/);var IOS_TOUCH_SCROLLING=IOS&&IOS[1]>=8;var DEFAULT_PHYSICAL_COUNT=3;va
r HIDDEN_Y="-10000px";var ITEM_WIDTH=0;var ITEM_HEIGHT=1;var SECRET_TABINDEX=-10
0;Polymer({is:"iron-list",properties:{items:{type:Array},maxPhysicalCount:{type:
Number,value:500},as:{type:String,value:"item"},indexAs:{type:String,value:"inde
x"},selectedAs:{type:String,value:"selected"},grid:{type:Boolean,value:false,ref
lectToAttribute:true},selectionEnabled:{type:Boolean,value:false},selectedItem:{
type:Object,notify:true},selectedItems:{type:Object,notify:true},multiSelection:
{type:Boolean,value:false}},observers:["_itemsChanged(items.*)","_selectionEnabl
edChanged(selectionEnabled)","_multiSelectionChanged(multiSelection)","_setOverf
low(scrollTarget)"],behaviors:[Polymer.Templatizer,Polymer.IronResizableBehavior
,Polymer.IronA11yKeysBehavior,Polymer.IronScrollTargetBehavior],keyBindings:{up:
"_didMoveUp",down:"_didMoveDown",enter:"_didEnter"},_ratio:.5,_scrollerPaddingTo
p:0,_scrollPosition:0,_physicalSize:0,_physicalAverage:0,_physicalAverageCount:0
,_physicalTop:0,_virtualCount:0,_physicalIndexForKey:null,_estScrollHeight:0,_sc
rollHeight:0,_viewportHeight:0,_viewportWidth:0,_physicalItems:null,_physicalSiz
es:null,_firstVisibleIndexVal:null,_lastVisibleIndexVal:null,_collection:null,_m
axPages:2,_focusedItem:null,_focusedIndex:-1,_offscreenFocusedItem:null,_focusBa
ckfillItem:null,_itemsPerRow:1,_itemWidth:0,_rowHeight:0,_templateCost:0,get _ph
ysicalBottom(){return this._physicalTop+this._physicalSize},get _scrollBottom(){
return this._scrollPosition+this._viewportHeight},get _virtualEnd(){return this.
_virtualStart+this._physicalCount-1},get _hiddenContentSize(){var size=this.grid
?this._physicalRows*this._rowHeight:this._physicalSize;return size-this._viewpor
tHeight},get _maxScrollTop(){return this._estScrollHeight-this._viewportHeight+t
his._scrollerPaddingTop},_minVirtualStart:0,get _maxVirtualStart(){return Math.m
ax(0,this._virtualCount-this._physicalCount)},_virtualStartVal:0,set _virtualSta
rt(val){this._virtualStartVal=Math.min(this._maxVirtualStart,Math.max(this._minV
irtualStart,val))},get _virtualStart(){return this._virtualStartVal||0},_physica
lStartVal:0,set _physicalStart(val){this._physicalStartVal=val%this._physicalCou
nt;if(this._physicalStartVal<0){this._physicalStartVal=this._physicalCount+this.
_physicalStartVal}this._physicalEnd=(this._physicalStart+this._physicalCount-1)%
this._physicalCount},get _physicalStart(){return this._physicalStartVal||0},_phy
sicalCountVal:0,set _physicalCount(val){this._physicalCountVal=val;this._physica
lEnd=(this._physicalStart+this._physicalCount-1)%this._physicalCount},get _physi
calCount(){return this._physicalCountVal},_physicalEnd:0,get _optPhysicalSize(){
if(this.grid){return this._estRowsInView*this._rowHeight*this._maxPages}return t
his._viewportHeight*this._maxPages},get _isVisible(){return Boolean(this.offsetW
idth||this.offsetHeight)},get firstVisibleIndex(){if(this._firstVisibleIndexVal=
==null){var physicalOffset=Math.floor(this._physicalTop+this._scrollerPaddingTop
);this._firstVisibleIndexVal=this._iterateItems(function(pidx,vidx){physicalOffs
et+=this._getPhysicalSizeIncrement(pidx);if(physicalOffset>this._scrollPosition)
{return this.grid?vidx-vidx%this._itemsPerRow:vidx}if(this.grid&&this._virtualCo
unt-1===vidx){return vidx-vidx%this._itemsPerRow}})||0}return this._firstVisible
IndexVal},get lastVisibleIndex(){if(this._lastVisibleIndexVal===null){if(this.gr
id){var lastIndex=this.firstVisibleIndex+this._estRowsInView*this._itemsPerRow-1
;this._lastVisibleIndexVal=Math.min(this._virtualCount,lastIndex)}else{var physi
calOffset=this._physicalTop;this._iterateItems(function(pidx,vidx){if(physicalOf
fset<this._scrollBottom){this._lastVisibleIndexVal=vidx}else{return true}physica
lOffset+=this._getPhysicalSizeIncrement(pidx)})}}return this._lastVisibleIndexVa
l},get _defaultScrollTarget(){return this},get _virtualRowCount(){return Math.ce
il(this._virtualCount/this._itemsPerRow)},get _estRowsInView(){return Math.ceil(
this._viewportHeight/this._rowHeight)},get _physicalRows(){return Math.ceil(this
._physicalCount/this._itemsPerRow)},ready:function(){this.addEventListener("focu
s",this._didFocus.bind(this),true)},attached:function(){if(this._physicalCount==
=0){this._debounceTemplate(this._render)}this.listen(this,"iron-resize","_resize
Handler")},detached:function(){this.unlisten(this,"iron-resize","_resizeHandler"
)},_setOverflow:function(scrollTarget){this.style.webkitOverflowScrolling=scroll
Target===this?"touch":"";this.style.overflow=scrollTarget===this?"auto":""},upda
teViewportBoundaries:function(){this._scrollerPaddingTop=this.scrollTarget===thi
s?0:parseInt(window.getComputedStyle(this)["padding-top"],10);this._viewportWidt
h=this.$.items.offsetWidth;this._viewportHeight=this._scrollTargetHeight;this.gr
id&&this._updateGridMetrics()},_scrollHandler:function(){var scrollTop=Math.max(
0,Math.min(this._maxScrollTop,this._scrollTop));var delta=scrollTop-this._scroll
Position;var isScrollingDown=delta>=0;this._scrollPosition=scrollTop;this._first
VisibleIndexVal=null;this._lastVisibleIndexVal=null;if(Math.abs(delta)>this._phy
sicalSize){var idxAdjustment=Math.round(delta/this._physicalAverage)*this._items
PerRow;this._physicalTop=this._physicalTop+delta;this._virtualStart=this._virtua
lStart+idxAdjustment;this._physicalStart=this._physicalStart+idxAdjustment;this.
_update()}else{var reusables=this._getReusables(isScrollingDown);if(isScrollingD
own){this._physicalTop=reusables.physicalTop;this._virtualStart=this._virtualSta
rt+reusables.indexes.length;this._physicalStart=this._physicalStart+reusables.in
dexes.length}else{this._virtualStart=this._virtualStart-reusables.indexes.length
;this._physicalStart=this._physicalStart-reusables.indexes.length}if(reusables.i
ndexes.length===0){this._increasePoolIfNeeded()}else{this._update(reusables.inde
xes,isScrollingDown?null:reusables.indexes)}}},_getReusables:function(fromTop){v
ar ith,lastIth,offsetContent,physicalItemHeight;var idxs=[];var protectedOffsetC
ontent=this._hiddenContentSize*this._ratio;var virtualStart=this._virtualStart;v
ar virtualEnd=this._virtualEnd;var physicalCount=this._physicalCount;var physica
lTop=this._physicalTop+this._scrollerPaddingTop;var scrollTop=this._scrollTop;va
r scrollBottom=this._scrollBottom;if(fromTop){ith=this._physicalStart;lastIth=th
is._physicalEnd;offsetContent=scrollTop-physicalTop}else{ith=this._physicalEnd;l
astIth=this._physicalStart;offsetContent=this._physicalBottom-scrollBottom}while
(true){physicalItemHeight=this._getPhysicalSizeIncrement(ith);offsetContent=offs
etContent-physicalItemHeight;if(idxs.length>=physicalCount||offsetContent<=prote
ctedOffsetContent){break}if(fromTop){if(virtualEnd+idxs.length+1>=this._virtualC
ount){break}if(physicalTop+physicalItemHeight>=scrollTop){break}idxs.push(ith);p
hysicalTop=physicalTop+physicalItemHeight;ith=(ith+1)%physicalCount}else{if(virt
ualStart-idxs.length<=0){break}if(physicalTop+this._physicalSize-physicalItemHei
ght<=scrollBottom){break}idxs.push(ith);physicalTop=physicalTop-physicalItemHeig
ht;ith=ith===0?physicalCount-1:ith-1}}return{indexes:idxs,physicalTop:physicalTo
p-this._scrollerPaddingTop}},_update:function(itemSet,movingUp){if(itemSet&&item
Set.length===0){return}this._manageFocus();this._assignModels(itemSet);this._upd
ateMetrics(itemSet);if(movingUp){while(movingUp.length){var idx=movingUp.pop();t
his._physicalTop-=this._getPhysicalSizeIncrement(idx)}}this._positionItems();thi
s._updateScrollerSize();this._increasePoolIfNeeded()},_createPool:function(size)
{var physicalItems=new Array(size);this._ensureTemplatized();for(var i=0;i<size;
i++){var inst=this.stamp(null);physicalItems[i]=inst.root.querySelector("*");Pol
ymer.dom(this).appendChild(inst.root)}return physicalItems},_increasePoolIfNeede
d:function(){if(this._viewportHeight===0){return false}var self=this;var isClien
tFull=this._physicalBottom>=this._scrollBottom&&this._physicalTop<=this._scrollP
osition;if(this._physicalSize>=this._optPhysicalSize&&isClientFull){return false
}var maxPoolSize=Math.round(this._physicalCount*.5);if(!isClientFull){this._debo
unceTemplate(this._increasePool.bind(this,maxPoolSize));return true}this._yield(
function(){self._increasePool(Math.min(maxPoolSize,Math.max(1,Math.round(50/self
._templateCost))))});return true},_yield:function(cb){var g=window;var handle=g.
requestIdleCallback?g.requestIdleCallback(cb):g.setTimeout(cb,16);Polymer.dom.ad
dDebouncer({complete:function(){g.cancelIdleCallback?g.cancelIdleCallback(handle
):g.clearTimeout(handle);cb()}})},_increasePool:function(missingItems){var nextP
hysicalCount=Math.min(this._physicalCount+missingItems,this._virtualCount-this._
virtualStart,Math.max(this.maxPhysicalCount,DEFAULT_PHYSICAL_COUNT));var prevPhy
sicalCount=this._physicalCount;var delta=nextPhysicalCount-prevPhysicalCount;var
ts=window.performance.now();if(delta<=0){return}[].push.apply(this._physicalIte
ms,this._createPool(delta));[].push.apply(this._physicalSizes,new Array(delta));
this._physicalCount=prevPhysicalCount+delta;if(this._physicalStart>this._physica
lEnd&&this._isIndexRendered(this._focusedIndex)&&this._getPhysicalIndex(this._fo
cusedIndex)<this._physicalEnd){this._physicalStart=this._physicalStart+delta}thi
s._update();this._templateCost=(window.performance.now()-ts)/delta},_render:func
tion(){if(this.isAttached&&this._isVisible){if(this._physicalCount===0){this.upd
ateViewportBoundaries();this._increasePool(DEFAULT_PHYSICAL_COUNT)}else{var reus
ables=this._getReusables(true);this._physicalTop=reusables.physicalTop;this._vir
tualStart=this._virtualStart+reusables.indexes.length;this._physicalStart=this._
physicalStart+reusables.indexes.length;this._update(reusables.indexes);this._upd
ate()}}},_ensureTemplatized:function(){if(!this.ctor){var props={};props.__key__
=true;props[this.as]=true;props[this.indexAs]=true;props[this.selectedAs]=true;p
rops.tabIndex=true;this._instanceProps=props;this._userTemplate=Polymer.dom(this
).querySelector("template");if(this._userTemplate){this.templatize(this._userTem
plate)}else{console.warn("iron-list requires a template to be provided in light-
dom")}}},_getStampedChildren:function(){return this._physicalItems},_forwardInst
ancePath:function(inst,path,value){if(path.indexOf(this.as+".")===0){this.notify
Path("items."+inst.__key__+"."+path.slice(this.as.length+1),value)}},_forwardPar
entProp:function(prop,value){if(this._physicalItems){this._physicalItems.forEach
(function(item){item._templateInstance[prop]=value},this)}},_forwardParentPath:f
unction(path,value){if(this._physicalItems){this._physicalItems.forEach(function
(item){item._templateInstance.notifyPath(path,value,true)},this)}},_forwardItemP
ath:function(path,value){if(!this._physicalIndexForKey){return}var dot=path.inde
xOf(".");var key=path.substring(0,dot<0?path.length:dot);var idx=this._physicalI
ndexForKey[key];var offscreenItem=this._offscreenFocusedItem;var el=offscreenIte
m&&offscreenItem._templateInstance.__key__===key?offscreenItem:this._physicalIte
ms[idx];if(!el||el._templateInstance.__key__!==key){return}if(dot>=0){path=this.
as+"."+path.substring(dot+1);el._templateInstance.notifyPath(path,value,true)}el
se{var currentItem=el._templateInstance[this.as];if(Array.isArray(this.selectedI
tems)){for(var i=0;i<this.selectedItems.length;i++){if(this.selectedItems[i]===c
urrentItem){this.set("selectedItems."+i,value);break}}}else if(this.selectedItem
===currentItem){this.set("selectedItem",value)}el._templateInstance[this.as]=val
ue}},_itemsChanged:function(change){if(change.path==="items"){this._virtualStart
=0;this._physicalTop=0;this._virtualCount=this.items?this.items.length:0;this._c
ollection=this.items?Polymer.Collection.get(this.items):null;this._physicalIndex
ForKey={};this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null;this._p
hysicalCount=this._physicalCount||0;this._physicalItems=this._physicalItems||[];
this._physicalSizes=this._physicalSizes||[];this._physicalStart=0;this._resetScr
ollPosition(0);this._removeFocusedItem();this._debounceTemplate(this._render)}el
se if(change.path==="items.splices"){this._adjustVirtualIndex(change.value.index
Splices);this._virtualCount=this.items?this.items.length:0;this._debounceTemplat
e(this._render)}else{this._forwardItemPath(change.path.split(".").slice(1).join(
"."),change.value)}},_adjustVirtualIndex:function(splices){splices.forEach(funct
ion(splice){splice.removed.forEach(this._removeItem,this);if(splice.index<this._
virtualStart){var delta=Math.max(splice.addedCount-splice.removed.length,splice.
index-this._virtualStart);this._virtualStart=this._virtualStart+delta;if(this._f
ocusedIndex>=0){this._focusedIndex=this._focusedIndex+delta}}},this)},_removeIte
m:function(item){this.$.selector.deselect(item);if(this._focusedItem&&this._focu
sedItem._templateInstance[this.as]===item){this._removeFocusedItem()}},_iterateI
tems:function(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((r
tn=fn.call(this,pidx,vidx))!=null){return rtn}}}else{pidx=this._physicalStart;vi
dx=this._virtualStart;for(;pidx<this._physicalCount;pidx++,vidx++){if((rtn=fn.ca
ll(this,pidx,vidx))!=null){return rtn}}for(pidx=0;pidx<this._physicalStart;pidx+
+,vidx++){if((rtn=fn.call(this,pidx,vidx))!=null){return rtn}}}},_computeVidx:fu
nction(pidx){if(pidx>=this._physicalStart){return this._virtualStart+(pidx-this.
_physicalStart)}return this._virtualStart+(this._physicalCount-this._physicalSta
rt)+pidx},_assignModels:function(itemSet){this._iterateItems(function(pidx,vidx)
{var el=this._physicalItems[pidx];var inst=el._templateInstance;var item=this.it
ems&&this.items[vidx];if(item!=null){inst[this.as]=item;inst.__key__=this._colle
ction.getKey(item);inst[this.selectedAs]=this.$.selector.isSelected(item);inst[t
his.indexAs]=vidx;inst.tabIndex=this._focusedIndex===vidx?0:-1;this._physicalInd
exForKey[inst.__key__]=pidx;el.removeAttribute("hidden")}else{inst.__key__=null;
el.setAttribute("hidden","")}},itemSet)},_updateMetrics:function(itemSet){Polyme
r.dom.flush();var newPhysicalSize=0;var oldPhysicalSize=0;var prevAvgCount=this.
_physicalAverageCount;var prevPhysicalAvg=this._physicalAverage;this._iterateIte
ms(function(pidx,vidx){oldPhysicalSize+=this._physicalSizes[pidx]||0;this._physi
calSizes[pidx]=this._physicalItems[pidx].offsetHeight;newPhysicalSize+=this._phy
sicalSizes[pidx];this._physicalAverageCount+=this._physicalSizes[pidx]?1:0},item
Set);if(this.grid){this._updateGridMetrics();this._physicalSize=Math.ceil(this._
physicalCount/this._itemsPerRow)*this._rowHeight}else{this._physicalSize=this._p
hysicalSize+newPhysicalSize-oldPhysicalSize}if(this._physicalAverageCount!==prev
AvgCount){this._physicalAverage=Math.round((prevPhysicalAvg*prevAvgCount+newPhys
icalSize)/this._physicalAverageCount)}},_updateGridMetrics:function(){this._item
Width=this._physicalCount>0?this._physicalItems[0].getBoundingClientRect().width
:200;this._rowHeight=this._physicalCount>0?this._physicalItems[0].offsetHeight:2
00;this._itemsPerRow=this._itemWidth?Math.floor(this._viewportWidth/this._itemWi
dth):this._itemsPerRow},_positionItems:function(){this._adjustScrollPosition();v
ar y=this._physicalTop;if(this.grid){var totalItemWidth=this._itemsPerRow*this._
itemWidth;var rowOffset=(this._viewportWidth-totalItemWidth)/2;this._iterateItem
s(function(pidx,vidx){var modulus=vidx%this._itemsPerRow;var x=Math.floor(modulu
s*this._itemWidth+rowOffset);this.translate3d(x+"px",y+"px",0,this._physicalItem
s[pidx]);if(this._shouldRenderNextRow(vidx)){y+=this._rowHeight}})}else{this._it
erateItems(function(pidx,vidx){this.translate3d(0,y+"px",0,this._physicalItems[p
idx]);y+=this._physicalSizes[pidx]})}},_getPhysicalSizeIncrement:function(pidx){
if(!this.grid){return this._physicalSizes[pidx]}if(this._computeVidx(pidx)%this.
_itemsPerRow!==this._itemsPerRow-1){return 0}return this._rowHeight},_shouldRend
erNextRow:function(vidx){return vidx%this._itemsPerRow===this._itemsPerRow-1},_a
djustScrollPosition:function(){var deltaHeight=this._virtualStart===0?this._phys
icalTop:Math.min(this._scrollPosition+this._physicalTop,0);if(deltaHeight){this.
_physicalTop=this._physicalTop-deltaHeight;if(!IOS_TOUCH_SCROLLING&&this._physic
alTop!==0){this._resetScrollPosition(this._scrollTop-deltaHeight)}}},_resetScrol
lPosition:function(pos){if(this.scrollTarget){this._scrollTop=pos;this._scrollPo
sition=this._scrollTop}},_updateScrollerSize:function(forceUpdate){if(this.grid)
{this._estScrollHeight=this._virtualRowCount*this._rowHeight}else{this._estScrol
lHeight=this._physicalBottom+Math.max(this._virtualCount-this._physicalCount-thi
s._virtualStart,0)*this._physicalAverage}forceUpdate=forceUpdate||this._scrollHe
ight===0;forceUpdate=forceUpdate||this._scrollPosition>=this._estScrollHeight-th
is._physicalSize;forceUpdate=forceUpdate||this.grid&&this.$.items.style.height<t
his._estScrollHeight;if(forceUpdate||Math.abs(this._estScrollHeight-this._scroll
Height)>=this._optPhysicalSize){this.$.items.style.height=this._estScrollHeight+
"px";this._scrollHeight=this._estScrollHeight}},scrollToItem:function(item){retu
rn this.scrollToIndex(this.items.indexOf(item))},scrollToIndex:function(idx){if(
typeof idx!=="number"||idx<0||idx>this.items.length-1){return}Polymer.dom.flush(
);if(this._physicalCount===0){return}idx=Math.min(Math.max(idx,0),this._virtualC
ount-1);if(!this._isIndexRendered(idx)||idx>=this._maxVirtualStart){this._virtua
lStart=this.grid?idx-this._itemsPerRow*2:idx-1}this._manageFocus();this._assignM
odels();this._updateMetrics();this._physicalTop=Math.floor(this._virtualStart/th
is._itemsPerRow)*this._physicalAverage;var currentTopItem=this._physicalStart;va
r currentVirtualItem=this._virtualStart;var targetOffsetTop=0;var hiddenContentS
ize=this._hiddenContentSize;while(currentVirtualItem<idx&&targetOffsetTop<=hidde
nContentSize){targetOffsetTop=targetOffsetTop+this._getPhysicalSizeIncrement(cur
rentTopItem);currentTopItem=(currentTopItem+1)%this._physicalCount;currentVirtua
lItem++}this._updateScrollerSize(true);this._positionItems();this._resetScrollPo
sition(this._physicalTop+this._scrollerPaddingTop+targetOffsetTop);this._increas
ePoolIfNeeded();this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null},
_resetAverage:function(){this._physicalAverage=0;this._physicalAverageCount=0},_
resizeHandler:function(){var delta=Math.abs(this._viewportHeight-this._scrollTar
getHeight);if(IOS&&delta>0&&delta<100){return}Polymer.dom.addDebouncer(this.debo
unce("_debounceTemplate",function(){this.updateViewportBoundaries();this._render
();if(this._isVisible){this.toggleScrollListener(true);if(this._physicalCount>0)
{this._resetAverage();this.scrollToIndex(this.firstVisibleIndex)}}else{this.togg
leScrollListener(false)}}.bind(this),1))},_getModelFromItem:function(item){var k
ey=this._collection.getKey(item);var pidx=this._physicalIndexForKey[key];if(pidx
!=null){return this._physicalItems[pidx]._templateInstance}return null},_getNorm
alizedItem:function(item){if(this._collection.getKey(item)===undefined){if(typeo
f 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")}ret
urn item},selectItem:function(item){item=this._getNormalizedItem(item);var model
=this._getModelFromItem(item);if(!this.multiSelection&&this.selectedItem){this.d
eselectItem(this.selectedItem)}if(model){model[this.selectedAs]=true}this.$.sele
ctor.select(item);this.updateSizeForItem(item)},deselectItem:function(item){item
=this._getNormalizedItem(item);var model=this._getModelFromItem(item);if(model){
model[this.selectedAs]=false}this.$.selector.deselect(item);this.updateSizeForIt
em(item)},toggleSelectionForItem:function(item){item=this._getNormalizedItem(ite
m);if(this.$.selector.isSelected(item)){this.deselectItem(item)}else{this.select
Item(item)}},clearSelection:function(){function unselect(item){var model=this._g
etModelFromItem(item);if(model){model[this.selectedAs]=false}}if(Array.isArray(t
his.selectedItems)){this.selectedItems.forEach(unselect,this)}else if(this.selec
tedItem){unselect.call(this,this.selectedItem)}this.$.selector.clearSelection()}
,_selectionEnabledChanged:function(selectionEnabled){var handler=selectionEnable
d?this.listen:this.unlisten;handler.call(this,this,"tap","_selectionHandler")},_
selectionHandler:function(e){var model=this.modelForElement(e.target);if(!model)
{return}var modelTabIndex,activeElTabIndex;var target=Polymer.dom(e).path[0];var
activeEl=Polymer.dom(this.domHost?this.domHost.root:document).activeElement;var
physicalItem=this._physicalItems[this._getPhysicalIndex(model[this.indexAs])];i
f(target.localName==="input"||target.localName==="button"||target.localName==="s
elect"){return}modelTabIndex=model.tabIndex;model.tabIndex=SECRET_TABINDEX;activ
eElTabIndex=activeEl?activeEl.tabIndex:-1;model.tabIndex=modelTabIndex;if(active
El&&physicalItem!==activeEl&&physicalItem.contains(activeEl)&&activeElTabIndex!=
=SECRET_TABINDEX){return}this.toggleSelectionForItem(model[this.as])},_multiSele
ctionChanged:function(multiSelection){this.clearSelection();this.$.selector.mult
i=multiSelection},updateSizeForItem:function(item){item=this._getNormalizedItem(
item);var key=this._collection.getKey(item);var pidx=this._physicalIndexForKey[k
ey];if(pidx!=null){this._updateMetrics([pidx]);this._positionItems()}},_manageFo
cus:function(){var fidx=this._focusedIndex;if(fidx>=0&&fidx<this._virtualCount){
if(this._isIndexRendered(fidx)){this._restoreFocusedItem()}else{this._createFocu
sBackfillItem()}}else if(this._virtualCount>0&&this._physicalCount>0){this._focu
sedIndex=this._virtualStart;this._focusedItem=this._physicalItems[this._physical
Start]}},_isIndexRendered:function(idx){return idx>=this._virtualStart&&idx<=thi
s._virtualEnd},_isIndexVisible:function(idx){return idx>=this.firstVisibleIndex&
&idx<=this.lastVisibleIndex},_getPhysicalIndex:function(idx){return this._physic
alIndexForKey[this._collection.getKey(this._getNormalizedItem(idx))]},_focusPhys
icalItem:function(idx){if(idx<0||idx>=this._virtualCount){return}this._restoreFo
cusedItem();if(!this._isIndexRendered(idx)){this.scrollToIndex(idx)}var physical
Item=this._physicalItems[this._getPhysicalIndex(idx)];var model=physicalItem._te
mplateInstance;var focusable;model.tabIndex=SECRET_TABINDEX;if(physicalItem.tabI
ndex===SECRET_TABINDEX){focusable=physicalItem}if(!focusable){focusable=Polymer.
dom(physicalItem).querySelector('[tabindex="'+SECRET_TABINDEX+'"]')}model.tabInd
ex=0;this._focusedIndex=idx;focusable&&focusable.focus()},_removeFocusedItem:fun
ction(){if(this._offscreenFocusedItem){Polymer.dom(this).removeChild(this._offsc
reenFocusedItem)}this._offscreenFocusedItem=null;this._focusBackfillItem=null;th
is._focusedItem=null;this._focusedIndex=-1},_createFocusBackfillItem:function(){
var fidx=this._focusedIndex;var pidx=this._getPhysicalIndex(fidx);if(this._offsc
reenFocusedItem||pidx==null||fidx<0){return}if(!this._focusBackfillItem){var sta
mpedTemplate=this.stamp(null);this._focusBackfillItem=stampedTemplate.root.query
Selector("*");Polymer.dom(this).appendChild(stampedTemplate.root)}this._offscree
nFocusedItem=this._physicalItems[pidx];this._offscreenFocusedItem._templateInsta
nce.tabIndex=0;this._physicalItems[pidx]=this._focusBackfillItem;this.translate3
d(0,HIDDEN_Y,0,this._offscreenFocusedItem)},_restoreFocusedItem:function(){var p
idx,fidx=this._focusedIndex;if(!this._offscreenFocusedItem||this._focusedIndex<0
){return}this._assignModels();pidx=this._getPhysicalIndex(fidx);if(pidx!=null){t
his._focusBackfillItem=this._physicalItems[pidx];this._focusBackfillItem._templa
teInstance.tabIndex=-1;this._physicalItems[pidx]=this._offscreenFocusedItem;this
._offscreenFocusedItem=null;this.translate3d(0,HIDDEN_Y,0,this._focusBackfillIte
m)}},_didFocus:function(e){var targetModel=this.modelForElement(e.target);var fo
cusedModel=this._focusedItem?this._focusedItem._templateInstance:null;var hasOff
screenFocusedItem=this._offscreenFocusedItem!==null;var fidx=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=targetModel[this.indexAs];t
his._focusedIndex=fidx;this._focusedItem=this._physicalItems[this._getPhysicalIn
dex(fidx)];if(hasOffscreenFocusedItem&&!this._offscreenFocusedItem){this._update
()}}},_didMoveUp:function(){this._focusPhysicalItem(this._focusedIndex-1)},_didM
oveDown:function(e){e.detail.keyboardEvent.preventDefault();this._focusPhysicalI
tem(this._focusedIndex+1)},_didEnter:function(e){this._focusPhysicalItem(this._f
ocusedIndex);this._selectionHandler(e.detail.keyboardEvent)}})})();Polymer({is:"
iron-scroll-threshold",properties:{upperThreshold:{type:Number,value:100},lowerT
hreshold:{type:Number,value:100},upperTriggered:{type:Boolean,value:false,notify
:true,readOnly:true},lowerTriggered:{type:Boolean,value:false,notify:true,readOn
ly:true},horizontal:{type:Boolean,value:false}},behaviors:[Polymer.IronScrollTar
getBehavior],observers:["_setOverflow(scrollTarget)","_initCheck(horizontal, isA
ttached)"],get _defaultScrollTarget(){return this},_setOverflow:function(scrollT
arget){this.style.overflow=scrollTarget===this?"auto":""},_scrollHandler:functio
n(){var THROTTLE_THRESHOLD=200;if(!this.isDebouncerActive("_checkTheshold")){thi
s.debounce("_checkTheshold",function(){this.checkScrollThesholds()},THROTTLE_THR
ESHOLD)}},_initCheck:function(horizontal,isAttached){if(isAttached){this.debounc
e("_init",function(){this.clearTriggers();this.checkScrollThesholds()})}},checkS
crollThesholds:function(){if(!this.scrollTarget||this.lowerTriggered&&this.upper
Triggered){return}var upperScrollValue=this.horizontal?this._scrollLeft:this._sc
rollTop;var lowerScrollValue=this.horizontal?this.scrollTarget.scrollWidth-this.
_scrollTargetWidth-this._scrollLeft:this.scrollTarget.scrollHeight-this._scrollT
argetHeight-this._scrollTop;if(upperScrollValue<=this.upperThreshold&&!this.uppe
rTriggered){this._setUpperTriggered(true);this.fire("upper-threshold")}if(lowerS
crollValue<=this.lowerThreshold&&!this.lowerTriggered){this._setLowerTriggered(t
rue);this.fire("lower-threshold")}},clearTriggers:function(){this._setUpperTrigg
ered(false);this._setLowerTriggered(false)}}); |
| 41 // Copyright (c) 2011 The Chromium Authors. All rights reserved. | 41 // Copyright (c) 2011 The Chromium Authors. All rights reserved. |
| 42 // Use of this source code is governed by a BSD-style license that can be | 42 // Use of this source code is governed by a BSD-style license that can be |
| 43 // found in the LICENSE file. | 43 // found in the LICENSE file. |
| 44 var EventTrackerEntry;function EventTracker(){this.listeners_=[]}EventTracker.pr
ototype={add:function(target,eventType,listener,opt_capture){var capture=!!opt_c
apture;var h={target:target,eventType:eventType,listener:listener,capture:captur
e};this.listeners_.push(h);target.addEventListener(eventType,listener,capture)},
remove:function(target,eventType){this.listeners_=this.listeners_.filter(functio
n(h){if(h.target==target&&(!eventType||h.eventType==eventType)){EventTracker.rem
oveEventListener_(h);return false}return true})},removeAll:function(){this.liste
ners_.forEach(EventTracker.removeEventListener_);this.listeners_=[]}};EventTrack
er.removeEventListener_=function(h){h.target.removeEventListener(h.eventType,h.l
istener,h.capture)}; | 44 var EventTrackerEntry;function EventTracker(){this.listeners_=[]}EventTracker.pr
ototype={add:function(target,eventType,listener,opt_capture){var capture=!!opt_c
apture;var h={target:target,eventType:eventType,listener:listener,capture:captur
e};this.listeners_.push(h);target.addEventListener(eventType,listener,capture)},
remove:function(target,eventType){this.listeners_=this.listeners_.filter(functio
n(h){if(h.target==target&&(!eventType||h.eventType==eventType)){EventTracker.rem
oveEventListener_(h);return false}return true})},removeAll:function(){this.liste
ners_.forEach(EventTracker.removeEventListener_);this.listeners_=[]}};EventTrack
er.removeEventListener_=function(h){h.target.removeEventListener(h.eventType,h.l
istener,h.capture)}; |
| 45 // Copyright 2014 The Chromium Authors. All rights reserved. | 45 // Copyright 2014 The Chromium Authors. All rights reserved. |
| 46 // Use of this source code is governed by a BSD-style license that can be | 46 // Use of this source code is governed by a BSD-style license that can be |
| 47 // found in the LICENSE file. | 47 // found in the LICENSE file. |
| 48 cr.define("cr.ui",function(){function FocusRow(root,boundary,opt_delegate){this.
root=root;this.boundary_=boundary||document.documentElement;this.delegate=opt_de
legate;this.eventTracker=new EventTracker}FocusRow.Delegate=function(){};FocusRo
w.Delegate.prototype={onKeydown:assertNotReached,onFocus:assertNotReached};Focus
Row.ACTIVE_CLASS="focus-row-active";FocusRow.isFocusable=function(element){if(!e
lement||element.disabled)return false;function isVisible(element){assertInstance
of(element,Element);var style=window.getComputedStyle(element);if(style.visibili
ty=="hidden"||style.display=="none")return false;var parent=element.parentNode;i
f(!parent)return false;if(parent==element.ownerDocument||parent instanceof Docum
entFragment)return true;return isVisible(parent)}return isVisible(element)};Focu
sRow.prototype={addItem:function(type,query){assert(type);var element=this.root.
querySelector(query);if(!element)return false;element.setAttribute("focus-type",
type);element.tabIndex=this.isActive()?0:-1;this.eventTracker.add(element,"blur"
,this.onBlur_.bind(this));this.eventTracker.add(element,"focus",this.onFocus_.bi
nd(this));this.eventTracker.add(element,"keydown",this.onKeydown_.bind(this));th
is.eventTracker.add(element,"mousedown",this.onMousedown_.bind(this));return tru
e},destroy:function(){this.eventTracker.removeAll()},getCustomEquivalent:functio
n(sampleElement){return assert(this.getFirstFocusable())},getElements:function()
{var elements=this.root.querySelectorAll("[focus-type]");return Array.prototype.
slice.call(elements)},getEquivalentElement:function(sampleElement){if(this.getFo
cusableElements().indexOf(sampleElement)>=0)return sampleElement;var sampleFocus
Type=this.getTypeForElement(sampleElement);if(sampleFocusType){var sameType=this
.getFirstFocusable(sampleFocusType);if(sameType)return sameType}return this.getC
ustomEquivalent(sampleElement)},getFirstFocusable:function(opt_type){var filter=
opt_type?'="'+opt_type+'"':"";var elements=this.root.querySelectorAll("[focus-ty
pe"+filter+"]");for(var i=0;i<elements.length;++i){if(cr.ui.FocusRow.isFocusable
(elements[i]))return elements[i]}return null},getFocusableElements:function(){re
turn this.getElements().filter(cr.ui.FocusRow.isFocusable)},getTypeForElement:fu
nction(element){return element.getAttribute("focus-type")||""},isActive:function
(){return this.root.classList.contains(FocusRow.ACTIVE_CLASS)},makeActive:functi
on(active){if(active==this.isActive())return;this.getElements().forEach(function
(element){element.tabIndex=active?0:-1});this.root.classList.toggle(FocusRow.ACT
IVE_CLASS,active)},onBlur_:function(e){if(!this.boundary_.contains(e.relatedTarg
et))return;var currentTarget=e.currentTarget;if(this.getFocusableElements().inde
xOf(currentTarget)>=0)this.makeActive(false)},onFocus_:function(e){if(this.deleg
ate)this.delegate.onFocus(this,e)},onMousedown_:function(e){if(e.button)return;i
f(!e.currentTarget.disabled)e.currentTarget.tabIndex=0},onKeydown_:function(e){v
ar elements=this.getFocusableElements();var currentElement=e.currentTarget;var e
lementIndex=elements.indexOf(currentElement);assert(elementIndex>=0);if(this.del
egate&&this.delegate.onKeydown(this,e))return;if(hasKeyModifiers(e))return;var i
ndex=-1;if(e.key=="ArrowLeft")index=elementIndex+(isRTL()?1:-1);else if(e.key=="
ArrowRight")index=elementIndex+(isRTL()?-1:1);else if(e.key=="Home")index=0;else
if(e.key=="End")index=elements.length-1;var elementToFocus=elements[index];if(e
lementToFocus){this.getEquivalentElement(elementToFocus).focus();e.preventDefaul
t()}}};return{FocusRow:FocusRow}}); | 48 cr.define("cr.ui",function(){function FocusRow(root,boundary,opt_delegate){this.
root=root;this.boundary_=boundary||document.documentElement;this.delegate=opt_de
legate;this.eventTracker=new EventTracker}FocusRow.Delegate=function(){};FocusRo
w.Delegate.prototype={onKeydown:assertNotReached,onFocus:assertNotReached};Focus
Row.ACTIVE_CLASS="focus-row-active";FocusRow.isFocusable=function(element){if(!e
lement||element.disabled)return false;function isVisible(element){assertInstance
of(element,Element);var style=window.getComputedStyle(element);if(style.visibili
ty=="hidden"||style.display=="none")return false;var parent=element.parentNode;i
f(!parent)return false;if(parent==element.ownerDocument||parent instanceof Docum
entFragment)return true;return isVisible(parent)}return isVisible(element)};Focu
sRow.prototype={addItem:function(type,query){assert(type);var element=this.root.
querySelector(query);if(!element)return false;element.setAttribute("focus-type",
type);element.tabIndex=this.isActive()?0:-1;this.eventTracker.add(element,"blur"
,this.onBlur_.bind(this));this.eventTracker.add(element,"focus",this.onFocus_.bi
nd(this));this.eventTracker.add(element,"keydown",this.onKeydown_.bind(this));th
is.eventTracker.add(element,"mousedown",this.onMousedown_.bind(this));return tru
e},destroy:function(){this.eventTracker.removeAll()},getCustomEquivalent:functio
n(sampleElement){return assert(this.getFirstFocusable())},getElements:function()
{var elements=this.root.querySelectorAll("[focus-type]");return Array.prototype.
slice.call(elements)},getEquivalentElement:function(sampleElement){if(this.getFo
cusableElements().indexOf(sampleElement)>=0)return sampleElement;var sampleFocus
Type=this.getTypeForElement(sampleElement);if(sampleFocusType){var sameType=this
.getFirstFocusable(sampleFocusType);if(sameType)return sameType}return this.getC
ustomEquivalent(sampleElement)},getFirstFocusable:function(opt_type){var filter=
opt_type?'="'+opt_type+'"':"";var elements=this.root.querySelectorAll("[focus-ty
pe"+filter+"]");for(var i=0;i<elements.length;++i){if(cr.ui.FocusRow.isFocusable
(elements[i]))return elements[i]}return null},getFocusableElements:function(){re
turn this.getElements().filter(cr.ui.FocusRow.isFocusable)},getTypeForElement:fu
nction(element){return element.getAttribute("focus-type")||""},isActive:function
(){return this.root.classList.contains(FocusRow.ACTIVE_CLASS)},makeActive:functi
on(active){if(active==this.isActive())return;this.getElements().forEach(function
(element){element.tabIndex=active?0:-1});this.root.classList.toggle(FocusRow.ACT
IVE_CLASS,active)},onBlur_:function(e){if(!this.boundary_.contains(e.relatedTarg
et))return;var currentTarget=e.currentTarget;if(this.getFocusableElements().inde
xOf(currentTarget)>=0)this.makeActive(false)},onFocus_:function(e){if(this.deleg
ate)this.delegate.onFocus(this,e)},onMousedown_:function(e){if(e.button)return;i
f(!e.currentTarget.disabled)e.currentTarget.tabIndex=0},onKeydown_:function(e){v
ar elements=this.getFocusableElements();var currentElement=e.currentTarget;var e
lementIndex=elements.indexOf(currentElement);assert(elementIndex>=0);if(this.del
egate&&this.delegate.onKeydown(this,e))return;if(hasKeyModifiers(e))return;var i
ndex=-1;if(e.key=="ArrowLeft")index=elementIndex+(isRTL()?1:-1);else if(e.key=="
ArrowRight")index=elementIndex+(isRTL()?-1:1);else if(e.key=="Home")index=0;else
if(e.key=="End")index=elements.length-1;var elementToFocus=elements[index];if(e
lementToFocus){this.getEquivalentElement(elementToFocus).focus();e.preventDefaul
t()}}};return{FocusRow:FocusRow}}); |
| 49 // Copyright 2016 The Chromium Authors. All rights reserved. | 49 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 50 // Use of this source code is governed by a BSD-style license that can be | 50 // Use of this source code is governed by a BSD-style license that can be |
| (...skipping 23 matching lines...) Expand all Loading... |
| 74 // Use of this source code is governed by a BSD-style license that can be | 74 // Use of this source code is governed by a BSD-style license that can be |
| 75 // found in the LICENSE file. | 75 // found in the LICENSE file. |
| 76 Polymer({is:"history-query-manager",properties:{queryState:{type:Object,notify:t
rue,value:function(){return{incremental:false,querying:true,queryingDisabled:fal
se,_range:HistoryRange.ALL_TIME,searchTerm:"",groupedOffset:0,set range(val){thi
s._range=Number(val)},get range(){return this._range}}}},queryResult:Object,rout
er:Object},observers:["searchTermChanged_(queryState.searchTerm)"],documentListe
ners_:{},attached:function(){this.documentListeners_["change-query"]=this.onChan
geQuery_.bind(this);this.documentListeners_["query-history"]=this.onQueryHistory
_.bind(this);for(var e in this.documentListeners_)document.addEventListener(e,th
is.documentListeners_[e])},detached:function(){for(var e in this.documentListene
rs_)document.removeEventListener(e,this.documentListeners_[e])},queryHistory_:fu
nction(incremental){var queryState=this.queryState;if(queryState.queryingDisable
d)return;this.set("queryState.querying",true);this.set("queryState.incremental",
incremental);var lastVisitTime=0;if(incremental){var lastVisit=this.queryResult.
results.slice(-1)[0];lastVisitTime=lastVisit?Math.floor(lastVisit.time):0}var ma
xResults=this.queryState.range==HistoryRange.ALL_TIME?RESULTS_PER_PAGE:0;chrome.
send("queryHistory",[queryState.searchTerm,queryState.groupedOffset,queryState.r
ange,lastVisitTime,maxResults])},onChangeQuery_:function(e){var changes=e.detail
;var needsUpdate=false;if(changes.range!=null&&changes.range!=this.queryState.ra
nge){this.set("queryState.range",changes.range);needsUpdate=true;if(!changes.off
set)this.set("queryState.groupedOffset",0);this.fire("history-view-changed")}if(
changes.offset!=null&&changes.offset!=this.queryState.groupedOffset){this.set("q
ueryState.groupedOffset",changes.offset);needsUpdate=true}if(changes.search!=nul
l&&changes.search!=this.queryState.searchTerm){this.set("queryState.searchTerm",
changes.search);needsUpdate=true}if(needsUpdate){this.queryHistory_(false);if(th
is.router)this.router.serializeUrl()}},onQueryHistory_:function(e){this.queryHis
tory_(e.detail);return false},searchTermChanged_:function(){if(this.queryState.s
earchTerm)md_history.BrowserService.getInstance().recordAction("Search")}});(fun
ction(){"use strict";Polymer({is:"iron-location",properties:{path:{type:String,n
otify:true,value:function(){return window.decodeURIComponent(window.location.pat
hname)}},query:{type:String,notify:true,value:function(){return window.decodeURI
Component(window.location.search.slice(1))}},hash:{type:String,notify:true,value
:function(){return window.decodeURIComponent(window.location.hash.slice(1))}},dw
ellTime:{type:Number,value:2e3},urlSpaceRegex:{type:String,value:""},_urlSpaceRe
gExp:{computed:"_makeRegExp(urlSpaceRegex)"},_lastChangedAt:{type:Number},_initi
alized:{type:Boolean,value:false}},hostAttributes:{hidden:true},observers:["_upd
ateUrl(path, query, hash)"],attached:function(){this.listen(window,"hashchange",
"_hashChanged");this.listen(window,"location-changed","_urlChanged");this.listen
(window,"popstate","_urlChanged");this.listen(document.body,"click","_globalOnCl
ick");this._lastChangedAt=window.performance.now()-(this.dwellTime-200);this._in
itialized=true;this._urlChanged()},detached:function(){this.unlisten(window,"has
hchange","_hashChanged");this.unlisten(window,"location-changed","_urlChanged");
this.unlisten(window,"popstate","_urlChanged");this.unlisten(document.body,"clic
k","_globalOnClick");this._initialized=false},_hashChanged:function(){this.hash=
window.decodeURIComponent(window.location.hash.substring(1))},_urlChanged:functi
on(){this._dontUpdateUrl=true;this._hashChanged();this.path=window.decodeURIComp
onent(window.location.pathname);this.query=window.decodeURIComponent(window.loca
tion.search.substring(1));this._dontUpdateUrl=false;this._updateUrl()},_getUrl:f
unction(){var partiallyEncodedPath=window.encodeURI(this.path).replace(/\#/g,"%2
3").replace(/\?/g,"%3F");var partiallyEncodedQuery="";if(this.query){partiallyEn
codedQuery="?"+window.encodeURI(this.query).replace(/\#/g,"%23")}var partiallyEn
codedHash="";if(this.hash){partiallyEncodedHash="#"+window.encodeURI(this.hash)}
return partiallyEncodedPath+partiallyEncodedQuery+partiallyEncodedHash},_updateU
rl:function(){if(this._dontUpdateUrl||!this._initialized){return}if(this.path===
window.decodeURIComponent(window.location.pathname)&&this.query===window.decodeU
RIComponent(window.location.search.substring(1))&&this.hash===window.decodeURICo
mponent(window.location.hash.substring(1))){return}var newUrl=this._getUrl();var
fullNewUrl=new URL(newUrl,window.location.protocol+"//"+window.location.host).h
ref;var now=window.performance.now();var shouldReplace=this._lastChangedAt+this.
dwellTime>now;this._lastChangedAt=now;if(shouldReplace){window.history.replaceSt
ate({},"",fullNewUrl)}else{window.history.pushState({},"",fullNewUrl)}this.fire(
"location-changed",{},{node:window})},_globalOnClick:function(event){if(event.de
faultPrevented){return}var href=this._getSameOriginLinkHref(event);if(!href){ret
urn}event.preventDefault();if(href===window.location.href){return}window.history
.pushState({},"",href);this.fire("location-changed",{},{node:window})},_getSameO
riginLinkHref:function(event){if(event.button!==0){return null}if(event.metaKey|
|event.ctrlKey){return null}var eventPath=Polymer.dom(event).path;var anchor=nul
l;for(var i=0;i<eventPath.length;i++){var element=eventPath[i];if(element.tagNam
e==="A"&&element.href){anchor=element;break}}if(!anchor){return null}if(anchor.t
arget==="_blank"){return null}if((anchor.target==="_top"||anchor.target==="_pare
nt")&&window.top!==window){return null}var href=anchor.href;var url;if(document.
baseURI!=null){url=new URL(href,document.baseURI)}else{url=new URL(href)}var ori
gin;if(window.location.origin){origin=window.location.origin}else{origin=window.
location.protocol+"//"+window.location.hostname;if(window.location.port){origin+
=":"+window.location.port}}if(url.origin!==origin){return null}var normalizedHre
f=url.pathname+url.search+url.hash;if(this._urlSpaceRegExp&&!this._urlSpaceRegEx
p.test(normalizedHref)){return null}var fullNormalizedHref=new URL(normalizedHre
f,window.location.href).href;return fullNormalizedHref},_makeRegExp:function(url
SpaceRegex){return RegExp(urlSpaceRegex)}})})();"use strict";Polymer({is:"iron-q
uery-params",properties:{paramsString:{type:String,notify:true,observer:"paramsS
tringChanged"},paramsObject:{type:Object,notify:true,value:function(){return{}}}
,_dontReact:{type:Boolean,value:false}},hostAttributes:{hidden:true},observers:[
"paramsObjectChanged(paramsObject.*)"],paramsStringChanged:function(){this._dont
React=true;this.paramsObject=this._decodeParams(this.paramsString);this._dontRea
ct=false},paramsObjectChanged:function(){if(this._dontReact){return}this.paramsS
tring=this._encodeParams(this.paramsObject)},_encodeParams:function(params){var
encodedParams=[];for(var key in params){var value=params[key];if(value===""){enc
odedParams.push(encodeURIComponent(key))}else if(value){encodedParams.push(encod
eURIComponent(key)+"="+encodeURIComponent(value.toString()))}}return encodedPara
ms.join("&")},_decodeParams:function(paramString){var params={};paramString=(par
amString||"").replace(/\+/g,"%20");var paramList=paramString.split("&");for(var
i=0;i<paramList.length;i++){var param=paramList[i].split("=");if(param[0]){param
s[decodeURIComponent(param[0])]=decodeURIComponent(param[1]||"")}}return params}
}); | 76 Polymer({is:"history-query-manager",properties:{queryState:{type:Object,notify:t
rue,value:function(){return{incremental:false,querying:true,queryingDisabled:fal
se,_range:HistoryRange.ALL_TIME,searchTerm:"",groupedOffset:0,set range(val){thi
s._range=Number(val)},get range(){return this._range}}}},queryResult:Object,rout
er:Object},observers:["searchTermChanged_(queryState.searchTerm)"],documentListe
ners_:{},attached:function(){this.documentListeners_["change-query"]=this.onChan
geQuery_.bind(this);this.documentListeners_["query-history"]=this.onQueryHistory
_.bind(this);for(var e in this.documentListeners_)document.addEventListener(e,th
is.documentListeners_[e])},detached:function(){for(var e in this.documentListene
rs_)document.removeEventListener(e,this.documentListeners_[e])},queryHistory_:fu
nction(incremental){var queryState=this.queryState;if(queryState.queryingDisable
d)return;this.set("queryState.querying",true);this.set("queryState.incremental",
incremental);var lastVisitTime=0;if(incremental){var lastVisit=this.queryResult.
results.slice(-1)[0];lastVisitTime=lastVisit?Math.floor(lastVisit.time):0}var ma
xResults=this.queryState.range==HistoryRange.ALL_TIME?RESULTS_PER_PAGE:0;chrome.
send("queryHistory",[queryState.searchTerm,queryState.groupedOffset,queryState.r
ange,lastVisitTime,maxResults])},onChangeQuery_:function(e){var changes=e.detail
;var needsUpdate=false;if(changes.range!=null&&changes.range!=this.queryState.ra
nge){this.set("queryState.range",changes.range);needsUpdate=true;if(!changes.off
set)this.set("queryState.groupedOffset",0);this.fire("history-view-changed")}if(
changes.offset!=null&&changes.offset!=this.queryState.groupedOffset){this.set("q
ueryState.groupedOffset",changes.offset);needsUpdate=true}if(changes.search!=nul
l&&changes.search!=this.queryState.searchTerm){this.set("queryState.searchTerm",
changes.search);needsUpdate=true}if(needsUpdate){this.queryHistory_(false);if(th
is.router)this.router.serializeUrl()}},onQueryHistory_:function(e){this.queryHis
tory_(e.detail);return false},searchTermChanged_:function(){if(this.queryState.s
earchTerm)md_history.BrowserService.getInstance().recordAction("Search")}});(fun
ction(){"use strict";Polymer({is:"iron-location",properties:{path:{type:String,n
otify:true,value:function(){return window.decodeURIComponent(window.location.pat
hname)}},query:{type:String,notify:true,value:function(){return window.decodeURI
Component(window.location.search.slice(1))}},hash:{type:String,notify:true,value
:function(){return window.decodeURIComponent(window.location.hash.slice(1))}},dw
ellTime:{type:Number,value:2e3},urlSpaceRegex:{type:String,value:""},_urlSpaceRe
gExp:{computed:"_makeRegExp(urlSpaceRegex)"},_lastChangedAt:{type:Number},_initi
alized:{type:Boolean,value:false}},hostAttributes:{hidden:true},observers:["_upd
ateUrl(path, query, hash)"],attached:function(){this.listen(window,"hashchange",
"_hashChanged");this.listen(window,"location-changed","_urlChanged");this.listen
(window,"popstate","_urlChanged");this.listen(document.body,"click","_globalOnCl
ick");this._lastChangedAt=window.performance.now()-(this.dwellTime-200);this._in
itialized=true;this._urlChanged()},detached:function(){this.unlisten(window,"has
hchange","_hashChanged");this.unlisten(window,"location-changed","_urlChanged");
this.unlisten(window,"popstate","_urlChanged");this.unlisten(document.body,"clic
k","_globalOnClick");this._initialized=false},_hashChanged:function(){this.hash=
window.decodeURIComponent(window.location.hash.substring(1))},_urlChanged:functi
on(){this._dontUpdateUrl=true;this._hashChanged();this.path=window.decodeURIComp
onent(window.location.pathname);this.query=window.decodeURIComponent(window.loca
tion.search.substring(1));this._dontUpdateUrl=false;this._updateUrl()},_getUrl:f
unction(){var partiallyEncodedPath=window.encodeURI(this.path).replace(/\#/g,"%2
3").replace(/\?/g,"%3F");var partiallyEncodedQuery="";if(this.query){partiallyEn
codedQuery="?"+window.encodeURI(this.query).replace(/\#/g,"%23")}var partiallyEn
codedHash="";if(this.hash){partiallyEncodedHash="#"+window.encodeURI(this.hash)}
return partiallyEncodedPath+partiallyEncodedQuery+partiallyEncodedHash},_updateU
rl:function(){if(this._dontUpdateUrl||!this._initialized){return}if(this.path===
window.decodeURIComponent(window.location.pathname)&&this.query===window.decodeU
RIComponent(window.location.search.substring(1))&&this.hash===window.decodeURICo
mponent(window.location.hash.substring(1))){return}var newUrl=this._getUrl();var
fullNewUrl=new URL(newUrl,window.location.protocol+"//"+window.location.host).h
ref;var now=window.performance.now();var shouldReplace=this._lastChangedAt+this.
dwellTime>now;this._lastChangedAt=now;if(shouldReplace){window.history.replaceSt
ate({},"",fullNewUrl)}else{window.history.pushState({},"",fullNewUrl)}this.fire(
"location-changed",{},{node:window})},_globalOnClick:function(event){if(event.de
faultPrevented){return}var href=this._getSameOriginLinkHref(event);if(!href){ret
urn}event.preventDefault();if(href===window.location.href){return}window.history
.pushState({},"",href);this.fire("location-changed",{},{node:window})},_getSameO
riginLinkHref:function(event){if(event.button!==0){return null}if(event.metaKey|
|event.ctrlKey){return null}var eventPath=Polymer.dom(event).path;var anchor=nul
l;for(var i=0;i<eventPath.length;i++){var element=eventPath[i];if(element.tagNam
e==="A"&&element.href){anchor=element;break}}if(!anchor){return null}if(anchor.t
arget==="_blank"){return null}if((anchor.target==="_top"||anchor.target==="_pare
nt")&&window.top!==window){return null}var href=anchor.href;var url;if(document.
baseURI!=null){url=new URL(href,document.baseURI)}else{url=new URL(href)}var ori
gin;if(window.location.origin){origin=window.location.origin}else{origin=window.
location.protocol+"//"+window.location.hostname;if(window.location.port){origin+
=":"+window.location.port}}if(url.origin!==origin){return null}var normalizedHre
f=url.pathname+url.search+url.hash;if(this._urlSpaceRegExp&&!this._urlSpaceRegEx
p.test(normalizedHref)){return null}var fullNormalizedHref=new URL(normalizedHre
f,window.location.href).href;return fullNormalizedHref},_makeRegExp:function(url
SpaceRegex){return RegExp(urlSpaceRegex)}})})();"use strict";Polymer({is:"iron-q
uery-params",properties:{paramsString:{type:String,notify:true,observer:"paramsS
tringChanged"},paramsObject:{type:Object,notify:true,value:function(){return{}}}
,_dontReact:{type:Boolean,value:false}},hostAttributes:{hidden:true},observers:[
"paramsObjectChanged(paramsObject.*)"],paramsStringChanged:function(){this._dont
React=true;this.paramsObject=this._decodeParams(this.paramsString);this._dontRea
ct=false},paramsObjectChanged:function(){if(this._dontReact){return}this.paramsS
tring=this._encodeParams(this.paramsObject)},_encodeParams:function(params){var
encodedParams=[];for(var key in params){var value=params[key];if(value===""){enc
odedParams.push(encodeURIComponent(key))}else if(value){encodedParams.push(encod
eURIComponent(key)+"="+encodeURIComponent(value.toString()))}}return encodedPara
ms.join("&")},_decodeParams:function(paramString){var params={};paramString=(par
amString||"").replace(/\+/g,"%20");var paramList=paramString.split("&");for(var
i=0;i<paramList.length;i++){var param=paramList[i].split("=");if(param[0]){param
s[decodeURIComponent(param[0])]=decodeURIComponent(param[1]||"")}}return params}
}); |
| 77 // Copyright 2016 The Chromium Authors. All rights reserved. | 77 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 78 // Use of this source code is governed by a BSD-style license that can be | 78 // Use of this source code is governed by a BSD-style license that can be |
| 79 // found in the LICENSE file. | 79 // found in the LICENSE file. |
| 80 Polymer({is:"history-router",properties:{selectedPage:{type:String,notify:true,o
bserver:"selectedPageChanged_"},queryState:Object,grouped:Boolean,path_:String,q
ueryParams_:Object},parsing_:false,observers:["onUrlChanged_(path_, queryParams_
)"],attached:function(){if(window.location.hash){window.location.href=window.loc
ation.href.split("#")[0]+"?"+window.location.hash.substr(1)}},serializeUrl:funct
ion(){var path=this.selectedPage;if(path=="history"&&this.queryState.range!=Hist
oryRange.ALL_TIME)path+="/"+this.rangeToString_(this.queryState.range);if(path==
"history")path="";var offsetParam=null;if(this.selectedPage=="history"&&this.que
ryState.groupedOffset)offsetParam=this.queryState.groupedOffset;this.path_="/"+p
ath;this.set("queryParams_.offset",offsetParam);this.set("queryParams_.q",this.q
ueryState.searchTerm||null)},selectedPageChanged_:function(){if(!this.parsing_)t
his.serializeUrl()},parseUrl_:function(){this.parsing_=true;var changes={};var s
ections=this.path_.substr(1).split("/");var page=sections[0]||"history";if(page=
="history"&&this.grouped){var range=sections.length>1?this.stringToRange_(sectio
ns[1]):HistoryRange.ALL_TIME;changes.range=range;changes.offset=Number(this.quer
yParams_.offset)||0}changes.search=this.queryParams_.q||"";this.selectedPage=pag
e;this.fire("change-query",changes);this.serializeUrl();this.parsing_=false},onU
rlChanged_:function(){this.debounce("parseUrl",this.parseUrl_.bind(this))},range
ToString_:function(range){switch(range){case HistoryRange.WEEK:return"week";case
HistoryRange.MONTH:return"month";default:return""}},stringToRange_:function(str
){switch(str){case"week":return HistoryRange.WEEK;case"month":return HistoryRang
e.MONTH;default:return HistoryRange.ALL_TIME}}});Polymer.IronMultiSelectableBeha
viorImpl={properties:{multi:{type:Boolean,value:false,observer:"multiChanged"},s
electedValues:{type:Array,notify:true},selectedItems:{type:Array,readOnly:true,n
otify:true}},observers:["_updateSelected(selectedValues.splices)"],select:functi
on(value){if(this.multi){if(this.selectedValues){this._toggleSelected(value)}els
e{this.selectedValues=[value]}}else{this.selected=value}},multiChanged:function(
multi){this._selection.multi=multi},get _shouldUpdateSelection(){return this.sel
ected!=null||this.selectedValues!=null&&this.selectedValues.length},_updateAttrF
orSelected:function(){if(!this.multi){Polymer.IronSelectableBehavior._updateAttr
ForSelected.apply(this)}else if(this._shouldUpdateSelection){this.selectedValues
=this.selectedItems.map(function(selectedItem){return this._indexToValue(this.in
dexOf(selectedItem))},this).filter(function(unfilteredValue){return unfilteredVa
lue!=null},this)}},_updateSelected:function(){if(this.multi){this._selectMulti(t
his.selectedValues)}else{this._selectSelected(this.selected)}},_selectMulti:func
tion(values){if(values){var selectedItems=this._valuesToItems(values);this._sele
ction.clear(selectedItems);for(var i=0;i<selectedItems.length;i++){this._selecti
on.setItemSelected(selectedItems[i],true)}if(this.fallbackSelection&&this.items.
length&&!this._selection.get().length){var fallback=this._valueToItem(this.fallb
ackSelection);if(fallback){this.selectedValues=[this.fallbackSelection]}}}else{t
his._selection.clear()}},_selectionChange:function(){var s=this._selection.get()
;if(this.multi){this._setSelectedItems(s)}else{this._setSelectedItems([s]);this.
_setSelectedItem(s)}},_toggleSelected:function(value){var i=this.selectedValues.
indexOf(value);var unselected=i<0;if(unselected){this.push("selectedValues",valu
e)}else{this.splice("selectedValues",i,1)}},_valuesToItems:function(values){retu
rn values==null?null:values.map(function(value){return this._valueToItem(value)}
,this)}};Polymer.IronMultiSelectableBehavior=[Polymer.IronSelectableBehavior,Pol
ymer.IronMultiSelectableBehaviorImpl];Polymer({is:"iron-selector",behaviors:[Pol
ymer.IronMultiSelectableBehavior]}); | 80 Polymer({is:"history-router",properties:{selectedPage:{type:String,notify:true,o
bserver:"selectedPageChanged_"},queryState:Object,grouped:Boolean,path_:String,q
ueryParams_:Object},parsing_:false,observers:["onUrlChanged_(path_, queryParams_
)"],attached:function(){if(window.location.hash){window.location.href=window.loc
ation.href.split("#")[0]+"?"+window.location.hash.substr(1)}},serializeUrl:funct
ion(){var path=this.selectedPage;if(path=="history"&&this.queryState.range!=Hist
oryRange.ALL_TIME)path+="/"+this.rangeToString_(this.queryState.range);if(path==
"history")path="";var offsetParam=null;if(this.selectedPage=="history"&&this.que
ryState.groupedOffset)offsetParam=this.queryState.groupedOffset;this.path_="/"+p
ath;this.set("queryParams_.offset",offsetParam);this.set("queryParams_.q",this.q
ueryState.searchTerm||null)},selectedPageChanged_:function(){if(!this.parsing_)t
his.serializeUrl()},parseUrl_:function(){this.parsing_=true;var changes={};var s
ections=this.path_.substr(1).split("/");var page=sections[0]||"history";if(page=
="history"&&this.grouped){var range=sections.length>1?this.stringToRange_(sectio
ns[1]):HistoryRange.ALL_TIME;changes.range=range;changes.offset=Number(this.quer
yParams_.offset)||0}changes.search=this.queryParams_.q||"";this.selectedPage=pag
e;this.fire("change-query",changes);this.serializeUrl();this.parsing_=false},onU
rlChanged_:function(){this.debounce("parseUrl",this.parseUrl_.bind(this))},range
ToString_:function(range){switch(range){case HistoryRange.WEEK:return"week";case
HistoryRange.MONTH:return"month";default:return""}},stringToRange_:function(str
){switch(str){case"week":return HistoryRange.WEEK;case"month":return HistoryRang
e.MONTH;default:return HistoryRange.ALL_TIME}}});Polymer.IronMultiSelectableBeha
viorImpl={properties:{multi:{type:Boolean,value:false,observer:"multiChanged"},s
electedValues:{type:Array,notify:true},selectedItems:{type:Array,readOnly:true,n
otify:true}},observers:["_updateSelected(selectedValues.splices)"],select:functi
on(value){if(this.multi){if(this.selectedValues){this._toggleSelected(value)}els
e{this.selectedValues=[value]}}else{this.selected=value}},multiChanged:function(
multi){this._selection.multi=multi},get _shouldUpdateSelection(){return this.sel
ected!=null||this.selectedValues!=null&&this.selectedValues.length},_updateAttrF
orSelected:function(){if(!this.multi){Polymer.IronSelectableBehavior._updateAttr
ForSelected.apply(this)}else if(this._shouldUpdateSelection){this.selectedValues
=this.selectedItems.map(function(selectedItem){return this._indexToValue(this.in
dexOf(selectedItem))},this).filter(function(unfilteredValue){return unfilteredVa
lue!=null},this)}},_updateSelected:function(){if(this.multi){this._selectMulti(t
his.selectedValues)}else{this._selectSelected(this.selected)}},_selectMulti:func
tion(values){if(values){var selectedItems=this._valuesToItems(values);this._sele
ction.clear(selectedItems);for(var i=0;i<selectedItems.length;i++){this._selecti
on.setItemSelected(selectedItems[i],true)}if(this.fallbackSelection&&this.items.
length&&!this._selection.get().length){var fallback=this._valueToItem(this.fallb
ackSelection);if(fallback){this.selectedValues=[this.fallbackSelection]}}}else{t
his._selection.clear()}},_selectionChange:function(){var s=this._selection.get()
;if(this.multi){this._setSelectedItems(s)}else{this._setSelectedItems([s]);this.
_setSelectedItem(s)}},_toggleSelected:function(value){var i=this.selectedValues.
indexOf(value);var unselected=i<0;if(unselected){this.push("selectedValues",valu
e)}else{this.splice("selectedValues",i,1)}},_valuesToItems:function(values){retu
rn values==null?null:values.map(function(value){return this._valueToItem(value)}
,this)}};Polymer.IronMultiSelectableBehavior=[Polymer.IronSelectableBehavior,Pol
ymer.IronMultiSelectableBehaviorImpl];Polymer({is:"iron-selector",behaviors:[Pol
ymer.IronMultiSelectableBehavior]}); |
| 81 // Copyright 2016 The Chromium Authors. All rights reserved. | 81 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 82 // Use of this source code is governed by a BSD-style license that can be | 82 // Use of this source code is governed by a BSD-style license that can be |
| 83 // found in the LICENSE file. | 83 // found in the LICENSE file. |
| 84 Polymer({is:"history-side-bar",behaviors:[Polymer.IronA11yKeysBehavior],properti
es:{selectedPage:{type:String,notify:true},showFooter:Boolean},keyBindings:{"spa
ce:keydown":"onSpacePressed_"},onSpacePressed_:function(e){e.detail.keyboardEven
t.path[0].click()},onSelectorActivate_:function(){this.fire("history-close-drawe
r")},onClearBrowsingDataTap_:function(e){var browserService=md_history.BrowserSe
rvice.getInstance();browserService.recordAction("InitClearBrowsingData");browser
Service.openClearBrowsingData();this.$["cbd-ripple"].upAction();e.preventDefault
()},onItemClick_:function(e){e.preventDefault()}}); | 84 Polymer({is:"history-side-bar",behaviors:[Polymer.IronA11yKeysBehavior],properti
es:{selectedPage:{type:String,notify:true},showFooter:Boolean},keyBindings:{"spa
ce:keydown":"onSpacePressed_"},onSpacePressed_:function(e){e.detail.keyboardEven
t.path[0].click()},onSelectorActivate_:function(){this.fire("history-close-drawe
r")},onClearBrowsingDataTap_:function(e){var browserService=md_history.BrowserSe
rvice.getInstance();browserService.recordAction("InitClearBrowsingData");browser
Service.openClearBrowsingData();this.$["cbd-ripple"].upAction();e.preventDefault
()},onItemClick_:function(e){e.preventDefault()},deletingAllowed_:function(){ret
urn loadTimeData.getBoolean("allowDeletingHistory")}}); |
| 85 // Copyright 2016 The Chromium Authors. All rights reserved. | 85 // Copyright 2016 The Chromium Authors. All rights reserved. |
| 86 // Use of this source code is governed by a BSD-style license that can be | 86 // Use of this source code is governed by a BSD-style license that can be |
| 87 // found in the LICENSE file. | 87 // found in the LICENSE file. |
| 88 cr.define("md_history",function(){var lazyLoadPromise=null;function ensureLazyLo
aded(){if(!lazyLoadPromise){lazyLoadPromise=new Promise(function(resolve,reject)
{Polymer.Base.importHref("chrome://history/lazy_load.html",resolve,reject,true)}
)}return lazyLoadPromise}return{ensureLazyLoaded:ensureLazyLoaded}});Polymer({is
:"history-app",behaviors:[Polymer.IronScrollTargetBehavior],properties:{selected
Page_:{type:String,observer:"selectedPageChanged_"},grouped_:{type:Boolean,refle
ctToAttribute:true},queryResult_:{type:Object,value:function(){return{info:null,
results:null,sessionList:null}}},isUserSignedIn_:{type:Boolean,value:loadTimeDat
a.getBoolean("isUserSignedIn")},toolbarShadow_:{type:Boolean,reflectToAttribute:
true,notify:true},showMenuPromo_:{type:Boolean,value:function(){return loadTimeD
ata.getBoolean("showMenuPromo")}},queryState_:Object,hasDrawer_:{type:Boolean,ob
server:"hasDrawerChanged_"},showSidebarFooter:Boolean,hasSyncedResults:Boolean},
listeners:{"cr-toolbar-menu-promo-close":"onCrToolbarMenuPromoClose_","cr-toolba
r-menu-promo-shown":"onCrToolbarMenuPromoShown_","cr-toolbar-menu-tap":"onCrTool
barMenuTap_","delete-selected":"deleteSelected","history-checkbox-select":"check
boxSelected","history-close-drawer":"closeDrawer_","history-view-changed":"histo
ryViewChanged_","opened-changed":"onOpenedChanged_","unselect-all":"unselectAll"
},boundOnCanExecute_:null,boundOnCommand_:null,attached:function(){this.grouped_
=loadTimeData.getBoolean("groupByDomain");cr.ui.decorate("command",cr.ui.Command
);this.boundOnCanExecute_=this.onCanExecute_.bind(this);this.boundOnCommand_=thi
s.onCommand_.bind(this);document.addEventListener("canExecute",this.boundOnCanEx
ecute_);document.addEventListener("command",this.boundOnCommand_)},detached:func
tion(){document.removeEventListener("canExecute",this.boundOnCanExecute_);docume
nt.removeEventListener("command",this.boundOnCommand_)},onFirstRender:function()
{setTimeout(function(){chrome.send("metricsHandler:recordTime",["History.Results
RenderedTime",window.performance.now()])});var searchField=this.$.toolbar.search
Field;if(!searchField.narrow){searchField.getSearchInput().focus()}md_history.en
sureLazyLoaded().then(function(){window.requestIdleCallback(function(){document.
fonts.load("bold 12px Roboto")})})},_scrollHandler:function(){if(this.scrollTarg
et)this.toolbarShadow_=this.scrollTarget.scrollTop!=0},onCrToolbarMenuPromoClose
_:function(){this.showMenuPromo_=false},onCrToolbarMenuPromoShown_:function(){md
_history.BrowserService.getInstance().menuPromoShown()},onCrToolbarMenuTap_:func
tion(){var drawer=this.$.drawer.get();drawer.align=document.documentElement.dir=
="ltr"?"left":"right";drawer.toggle()},onOpenedChanged_:function(e){if(e.detail.
value)this.showMenuPromo_=false},checkboxSelected:function(e){var toolbar=this.$
.toolbar;toolbar.count=this.$.history.getSelectedItemCount()},unselectAll:functi
on(){var listContainer=this.$.history;var toolbar=this.$.toolbar;listContainer.u
nselectAllItems(toolbar.count);toolbar.count=0},deleteSelected:function(){this.$
.history.deleteSelectedWithPrompt()},historyResult:function(info,results){this.s
et("queryState_.querying",false);this.set("queryResult_.info",info);this.set("qu
eryResult_.results",results);var listContainer=this.$["history"];listContainer.h
istoryResult(info,results)},focusToolbarSearchField:function(){this.$.toolbar.sh
owSearchField()},onCanExecute_:function(e){e=e;switch(e.command.id){case"find-co
mmand":case"toggle-grouped":e.canExecute=true;break;case"slash-command":e.canExe
cute=!this.$.toolbar.searchField.isSearchFocused();break;case"delete-command":e.
canExecute=this.$.toolbar.count>0;break}},onCommand_:function(e){if(e.command.id
=="find-command"||e.command.id=="slash-command")this.focusToolbarSearchField();i
f(e.command.id=="delete-command")this.deleteSelected();if(e.command.id=="toggle-
grouped")this.grouped_=!this.grouped_},setForeignSessions:function(sessionList){
this.set("queryResult_.sessionList",sessionList)},historyDeleted:function(){this
.$.history.historyDeleted()},updateSignInState:function(isUserSignedIn){this.isU
serSignedIn_=isUserSignedIn},syncedTabsSelected_:function(selectedPage){return s
electedPage=="syncedTabs"},shouldShowSpinner_:function(querying,incremental,sear
chTerm){return querying&&!incremental&&searchTerm!=""},showSyncNotice_:function(
hasSyncedResults,selectedPage){return hasSyncedResults&&selectedPage!="syncedTab
s"},selectedPageChanged_:function(){this.unselectAll();this.historyViewChanged_(
)},historyViewChanged_:function(){requestAnimationFrame(function(){md_history.en
sureLazyLoaded().then(function(){if(!this.$.content.selectedItem)return;this.scr
ollTarget=this.$.content.selectedItem.getContentScrollTarget();this._scrollHandl
er()}.bind(this))}.bind(this));this.recordHistoryPageView_()},hasDrawerChanged_:
function(){var drawer=this.$.drawer.getIfExists();if(!this.hasDrawer_&&drawer&&d
rawer.open)drawer.closeDrawer()},getSelectedPage_:function(selectedPage,items){r
eturn selectedPage},closeDrawer_:function(){var drawer=this.$.drawer.get();if(dr
awer&&drawer.open)drawer.closeDrawer()},recordHistoryPageView_:function(){var hi
stogramValue=HistoryPageViewHistogram.END;switch(this.selectedPage_){case"synced
Tabs":histogramValue=this.isUserSignedIn_?HistoryPageViewHistogram.SYNCED_TABS:H
istoryPageViewHistogram.SIGNIN_PROMO;break;default:switch(this.queryState_.range
){case HistoryRange.ALL_TIME:histogramValue=HistoryPageViewHistogram.HISTORY;bre
ak;case HistoryRange.WEEK:histogramValue=HistoryPageViewHistogram.GROUPED_WEEK;b
reak;case HistoryRange.MONTH:histogramValue=HistoryPageViewHistogram.GROUPED_MON
TH;break}break}md_history.BrowserService.getInstance().recordHistogram("History.
HistoryPageView",histogramValue,HistoryPageViewHistogram.END)}}); | 88 cr.define("md_history",function(){var lazyLoadPromise=null;function ensureLazyLo
aded(){if(!lazyLoadPromise){lazyLoadPromise=new Promise(function(resolve,reject)
{Polymer.Base.importHref("chrome://history/lazy_load.html",resolve,reject,true)}
)}return lazyLoadPromise}return{ensureLazyLoaded:ensureLazyLoaded}});Polymer({is
:"history-app",behaviors:[Polymer.IronScrollTargetBehavior],properties:{selected
Page_:{type:String,observer:"selectedPageChanged_"},grouped_:{type:Boolean,refle
ctToAttribute:true},queryResult_:{type:Object,value:function(){return{info:null,
results:null,sessionList:null}}},isUserSignedIn_:{type:Boolean,value:loadTimeDat
a.getBoolean("isUserSignedIn")},toolbarShadow_:{type:Boolean,reflectToAttribute:
true,notify:true},showMenuPromo_:{type:Boolean,value:function(){return loadTimeD
ata.getBoolean("showMenuPromo")}},queryState_:Object,hasDrawer_:{type:Boolean,ob
server:"hasDrawerChanged_"},showSidebarFooter:Boolean,hasSyncedResults:Boolean},
listeners:{"cr-toolbar-menu-promo-close":"onCrToolbarMenuPromoClose_","cr-toolba
r-menu-promo-shown":"onCrToolbarMenuPromoShown_","cr-toolbar-menu-tap":"onCrTool
barMenuTap_","delete-selected":"deleteSelected","history-checkbox-select":"check
boxSelected","history-close-drawer":"closeDrawer_","history-view-changed":"histo
ryViewChanged_","opened-changed":"onOpenedChanged_","unselect-all":"unselectAll"
},boundOnCanExecute_:null,boundOnCommand_:null,attached:function(){this.grouped_
=loadTimeData.getBoolean("groupByDomain");cr.ui.decorate("command",cr.ui.Command
);this.boundOnCanExecute_=this.onCanExecute_.bind(this);this.boundOnCommand_=thi
s.onCommand_.bind(this);document.addEventListener("canExecute",this.boundOnCanEx
ecute_);document.addEventListener("command",this.boundOnCommand_)},detached:func
tion(){document.removeEventListener("canExecute",this.boundOnCanExecute_);docume
nt.removeEventListener("command",this.boundOnCommand_)},onFirstRender:function()
{setTimeout(function(){chrome.send("metricsHandler:recordTime",["History.Results
RenderedTime",window.performance.now()])});var searchField=this.$.toolbar.search
Field;if(!searchField.narrow){searchField.getSearchInput().focus()}md_history.en
sureLazyLoaded().then(function(){window.requestIdleCallback(function(){document.
fonts.load("bold 12px Roboto")})})},_scrollHandler:function(){if(this.scrollTarg
et)this.toolbarShadow_=this.scrollTarget.scrollTop!=0},onCrToolbarMenuPromoClose
_:function(){this.showMenuPromo_=false},onCrToolbarMenuPromoShown_:function(){md
_history.BrowserService.getInstance().menuPromoShown()},onCrToolbarMenuTap_:func
tion(){var drawer=this.$.drawer.get();drawer.align=document.documentElement.dir=
="ltr"?"left":"right";drawer.toggle()},onOpenedChanged_:function(e){if(e.detail.
value)this.showMenuPromo_=false},checkboxSelected:function(e){var toolbar=this.$
.toolbar;toolbar.count=this.$.history.getSelectedItemCount()},unselectAll:functi
on(){var listContainer=this.$.history;var toolbar=this.$.toolbar;listContainer.u
nselectAllItems(toolbar.count);toolbar.count=0},deleteSelected:function(){this.$
.history.deleteSelectedWithPrompt()},historyResult:function(info,results){this.s
et("queryState_.querying",false);this.set("queryResult_.info",info);this.set("qu
eryResult_.results",results);var listContainer=this.$["history"];listContainer.h
istoryResult(info,results)},focusToolbarSearchField:function(){this.$.toolbar.sh
owSearchField()},onCanExecute_:function(e){e=e;switch(e.command.id){case"find-co
mmand":case"toggle-grouped":e.canExecute=true;break;case"slash-command":e.canExe
cute=!this.$.toolbar.searchField.isSearchFocused();break;case"delete-command":e.
canExecute=this.$.toolbar.count>0;break}},onCommand_:function(e){if(e.command.id
=="find-command"||e.command.id=="slash-command")this.focusToolbarSearchField();i
f(e.command.id=="delete-command")this.deleteSelected();if(e.command.id=="toggle-
grouped")this.grouped_=!this.grouped_},setForeignSessions:function(sessionList){
this.set("queryResult_.sessionList",sessionList)},historyDeleted:function(){this
.$.history.historyDeleted()},updateSignInState:function(isUserSignedIn){this.isU
serSignedIn_=isUserSignedIn},syncedTabsSelected_:function(selectedPage){return s
electedPage=="syncedTabs"},shouldShowSpinner_:function(querying,incremental,sear
chTerm){return querying&&!incremental&&searchTerm!=""},showSyncNotice_:function(
hasSyncedResults,selectedPage){return hasSyncedResults&&selectedPage!="syncedTab
s"},selectedPageChanged_:function(){this.unselectAll();this.historyViewChanged_(
)},historyViewChanged_:function(){requestAnimationFrame(function(){md_history.en
sureLazyLoaded().then(function(){if(!this.$.content.selectedItem)return;this.scr
ollTarget=this.$.content.selectedItem.getContentScrollTarget();this._scrollHandl
er()}.bind(this))}.bind(this));this.recordHistoryPageView_()},hasDrawerChanged_:
function(){var drawer=this.$.drawer.getIfExists();if(!this.hasDrawer_&&drawer&&d
rawer.open)drawer.closeDrawer()},getSelectedPage_:function(selectedPage,items){r
eturn selectedPage},closeDrawer_:function(){var drawer=this.$.drawer.get();if(dr
awer&&drawer.open)drawer.closeDrawer()},recordHistoryPageView_:function(){var hi
stogramValue=HistoryPageViewHistogram.END;switch(this.selectedPage_){case"synced
Tabs":histogramValue=this.isUserSignedIn_?HistoryPageViewHistogram.SYNCED_TABS:H
istoryPageViewHistogram.SIGNIN_PROMO;break;default:switch(this.queryState_.range
){case HistoryRange.ALL_TIME:histogramValue=HistoryPageViewHistogram.HISTORY;bre
ak;case HistoryRange.WEEK:histogramValue=HistoryPageViewHistogram.GROUPED_WEEK;b
reak;case HistoryRange.MONTH:histogramValue=HistoryPageViewHistogram.GROUPED_MON
TH;break}break}md_history.BrowserService.getInstance().recordHistogram("History.
HistoryPageView",histogramValue,HistoryPageViewHistogram.END)}}); |
| OLD | NEW |