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

Side by Side Diff: chrome/browser/resources/md_downloads/crisper.js

Issue 2586113002: MD Settings: ignore modified key events in the profile avatar grid (Closed)
Patch Set: closure Created 3 years, 12 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2013 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 assert(condition,opt_message){if(!condition){var message="Assertion fai led";if(opt_message)message=message+": "+opt_message;var error=new Error(message );var global=function(){return this}();if(global.traceAssertionsForTesting)conso le.warn(error.stack);throw error}return condition}function assertNotReached(opt_ message){assert(false,opt_message||"Unreachable code hit")}function assertInstan ceof(value,type,opt_message){if(!(value instanceof type)){assertNotReached(opt_m essage||"Value "+value+" is not a[n] "+(type.name||typeof type))}return value} 4 function assert(condition,opt_message){if(!condition){var message="Assertion fai led";if(opt_message)message=message+": "+opt_message;var error=new Error(message );var global=function(){return this}();if(global.traceAssertionsForTesting)conso le.warn(error.stack);throw error}return condition}function assertNotReached(opt_ message){assert(false,opt_message||"Unreachable code hit")}function assertInstan ceof(value,type,opt_message){if(!(value instanceof type)){assertNotReached(opt_m essage||"Value "+value+" is not a[n] "+(type.name||typeof type))}return value}
5 // Copyright 2016 The Chromium Authors. All rights reserved. 5 // Copyright 2016 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 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()}}; 8 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()}};
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
11 // found in the LICENSE file. 11 // found in the LICENSE file.
12 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)}}}(); 12 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)}}}();
13 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 13 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
14 // Use of this source code is governed by a BSD-style license that can be 14 // Use of this source code is governed by a BSD-style license that can be
15 // found in the LICENSE file. 15 // found in the LICENSE file.
16 cr.define("cr.ui",function(){function decorate(source,constr){var elements;if(ty peof source=="string")elements=cr.doc.querySelectorAll(source);else elements=[so urce];for(var i=0,el;el=elements[i];i++){if(!(el instanceof constr))constr.decor ate(el)}}function createElementHelper(tagName,opt_bag){var doc;if(opt_bag&&opt_b ag.ownerDocument)doc=opt_bag.ownerDocument;else doc=cr.doc;return doc.createElem ent(tagName)}function define(tagNameOrFunction){var createFunction,tagName;if(ty peof tagNameOrFunction=="function"){createFunction=tagNameOrFunction;tagName=""} else{createFunction=createElementHelper;tagName=tagNameOrFunction}function f(opt _propertyBag){var el=createFunction(tagName,opt_propertyBag);f.decorate(el);for( var propertyName in opt_propertyBag){el[propertyName]=opt_propertyBag[propertyNa me]}return el}f.decorate=function(el){el.__proto__=f.prototype;el.decorate()};re turn f}function limitInputWidth(el,parentEl,min,opt_scale){el.style.width="10px" ;var doc=el.ownerDocument;var win=doc.defaultView;var computedStyle=win.getCompu tedStyle(el);var parentComputedStyle=win.getComputedStyle(parentEl);var rtl=comp utedStyle.direction=="rtl";var inputRect=el.getBoundingClientRect();var parentRe ct=parentEl.getBoundingClientRect();var startPos=rtl?parentRect.right-inputRect. right:inputRect.left-parentRect.left;var inner=parseInt(computedStyle.borderLeft Width,10)+parseInt(computedStyle.paddingLeft,10)+parseInt(computedStyle.paddingR ight,10)+parseInt(computedStyle.borderRightWidth,10);var parentPadding=rtl?parse Int(parentComputedStyle.paddingLeft,10):parseInt(parentComputedStyle.paddingRigh t,10);var max=parentEl.clientWidth-startPos-inner-parentPadding;if(opt_scale)max *=opt_scale;function limit(){if(el.scrollWidth>max){el.style.width=max+"px"}else {el.style.width=0;var sw=el.scrollWidth;if(sw<min){el.style.width=min+"px"}else{ el.style.width=sw+"px"}}}el.addEventListener("input",limit);limit()}function toC ssPx(pixels){if(!window.isFinite(pixels))console.error("Pixel value is not a num ber: "+pixels);return Math.round(pixels)+"px"}function swallowDoubleClick(e){var doc=e.target.ownerDocument;var counter=Math.min(1,e.detail);function swallow(e) {e.stopPropagation();e.preventDefault()}function onclick(e){if(e.detail>counter) {counter=e.detail;swallow(e)}else{doc.removeEventListener("dblclick",swallow,tru e);doc.removeEventListener("click",onclick,true)}}setTimeout(function(){doc.addE ventListener("click",onclick,true);doc.addEventListener("dblclick",swallow,true) },0)}return{decorate:decorate,define:define,limitInputWidth:limitInputWidth,toCs sPx:toCssPx,swallowDoubleClick:swallowDoubleClick}}); 16 cr.define("cr.ui",function(){function decorate(source,constr){var elements;if(ty peof source=="string")elements=cr.doc.querySelectorAll(source);else elements=[so urce];for(var i=0,el;el=elements[i];i++){if(!(el instanceof constr))constr.decor ate(el)}}function createElementHelper(tagName,opt_bag){var doc;if(opt_bag&&opt_b ag.ownerDocument)doc=opt_bag.ownerDocument;else doc=cr.doc;return doc.createElem ent(tagName)}function define(tagNameOrFunction){var createFunction,tagName;if(ty peof tagNameOrFunction=="function"){createFunction=tagNameOrFunction;tagName=""} else{createFunction=createElementHelper;tagName=tagNameOrFunction}function f(opt _propertyBag){var el=createFunction(tagName,opt_propertyBag);f.decorate(el);for( var propertyName in opt_propertyBag){el[propertyName]=opt_propertyBag[propertyNa me]}return el}f.decorate=function(el){el.__proto__=f.prototype;el.decorate()};re turn f}function limitInputWidth(el,parentEl,min,opt_scale){el.style.width="10px" ;var doc=el.ownerDocument;var win=doc.defaultView;var computedStyle=win.getCompu tedStyle(el);var parentComputedStyle=win.getComputedStyle(parentEl);var rtl=comp utedStyle.direction=="rtl";var inputRect=el.getBoundingClientRect();var parentRe ct=parentEl.getBoundingClientRect();var startPos=rtl?parentRect.right-inputRect. right:inputRect.left-parentRect.left;var inner=parseInt(computedStyle.borderLeft Width,10)+parseInt(computedStyle.paddingLeft,10)+parseInt(computedStyle.paddingR ight,10)+parseInt(computedStyle.borderRightWidth,10);var parentPadding=rtl?parse Int(parentComputedStyle.paddingLeft,10):parseInt(parentComputedStyle.paddingRigh t,10);var max=parentEl.clientWidth-startPos-inner-parentPadding;if(opt_scale)max *=opt_scale;function limit(){if(el.scrollWidth>max){el.style.width=max+"px"}else {el.style.width=0;var sw=el.scrollWidth;if(sw<min){el.style.width=min+"px"}else{ el.style.width=sw+"px"}}}el.addEventListener("input",limit);limit()}function toC ssPx(pixels){if(!window.isFinite(pixels))console.error("Pixel value is not a num ber: "+pixels);return Math.round(pixels)+"px"}function swallowDoubleClick(e){var doc=e.target.ownerDocument;var counter=Math.min(1,e.detail);function swallow(e) {e.stopPropagation();e.preventDefault()}function onclick(e){if(e.detail>counter) {counter=e.detail;swallow(e)}else{doc.removeEventListener("dblclick",swallow,tru e);doc.removeEventListener("click",onclick,true)}}setTimeout(function(){doc.addE ventListener("click",onclick,true);doc.addEventListener("dblclick",swallow,true) },0)}return{decorate:decorate,define:define,limitInputWidth:limitInputWidth,toCs sPx:toCssPx,swallowDoubleClick:swallowDoubleClick}});
17 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 17 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
18 // Use of this source code is governed by a BSD-style license that can be 18 // Use of this source code is governed by a BSD-style license that can be
19 // found in the LICENSE file. 19 // found in the LICENSE file.
20 cr.define("cr.ui",function(){function KeyboardShortcut(shortcut){var mods={};var ident="";shortcut.split("|").forEach(function(part){var partLc=part.toLowerCase ();switch(partLc){case"alt":case"ctrl":case"meta":case"shift":mods[partLc+"Key"] =true;break;default:if(ident)throw Error("Invalid shortcut");ident=part}});this. ident_=ident;this.mods_=mods}KeyboardShortcut.prototype={matchesEvent:function(e ){if(e.key==this.ident_){var mods=this.mods_;return["altKey","ctrlKey","metaKey" ,"shiftKey"].every(function(k){return e[k]==!!mods[k]})}return false}};var Comma nd=cr.ui.define("command");Command.prototype={__proto__:HTMLElement.prototype,de corate:function(){CommandManager.init(assert(this.ownerDocument));if(this.hasAtt ribute("shortcut"))this.shortcut=this.getAttribute("shortcut")},execute:function (opt_element){if(this.disabled)return;var doc=this.ownerDocument;if(doc.activeEl ement){var e=new Event("command",{bubbles:true});e.command=this;(opt_element||do c.activeElement).dispatchEvent(e)}},canExecuteChange:function(opt_node){dispatch CanExecuteEvent(this,opt_node||this.ownerDocument.activeElement)},shortcut_:"",g et shortcut(){return this.shortcut_},set shortcut(shortcut){var oldShortcut=this .shortcut_;if(shortcut!==oldShortcut){this.keyboardShortcuts_=shortcut.split(/\s +/).map(function(shortcut){return new KeyboardShortcut(shortcut)});this.shortcut _=shortcut;cr.dispatchPropertyChange(this,"shortcut",this.shortcut_,oldShortcut) }},matchesEvent:function(e){if(!this.keyboardShortcuts_)return false;return this .keyboardShortcuts_.some(function(keyboardShortcut){return keyboardShortcut.matc hesEvent(e)})}};cr.defineProperty(Command,"label",cr.PropertyKind.ATTR);cr.defin eProperty(Command,"disabled",cr.PropertyKind.BOOL_ATTR);cr.defineProperty(Comman d,"hidden",cr.PropertyKind.BOOL_ATTR);cr.defineProperty(Command,"checked",cr.Pro pertyKind.BOOL_ATTR);cr.defineProperty(Command,"hideShortcutText",cr.PropertyKin d.BOOL_ATTR);function dispatchCanExecuteEvent(command,target){var e=new CanExecu teEvent(command);target.dispatchEvent(e);command.disabled=!e.canExecute}var comm andManagers={};function CommandManager(doc){doc.addEventListener("focus",this.ha ndleFocus_.bind(this),true);doc.addEventListener("keydown",this.handleKeyDown_.b ind(this),false)}CommandManager.init=function(doc){var uid=cr.getUid(doc);if(!(u id in commandManagers)){commandManagers[uid]=new CommandManager(doc)}};CommandMa nager.prototype={handleFocus_:function(e){var target=e.target;if(target.menu||ta rget.command)return;var commands=Array.prototype.slice.call(target.ownerDocument .querySelectorAll("command"));commands.forEach(function(command){dispatchCanExec uteEvent(command,target)})},handleKeyDown_:function(e){var target=e.target;var c ommands=Array.prototype.slice.call(target.ownerDocument.querySelectorAll("comman d"));for(var i=0,command;command=commands[i];i++){if(command.matchesEvent(e)){co mmand.canExecuteChange();if(!command.disabled){e.preventDefault();e.stopPropagat ion();command.execute();return}}}}};function CanExecuteEvent(command){var e=new Event("canExecute",{bubbles:true,cancelable:true});e.__proto__=CanExecuteEvent.p rototype;e.command=command;return e}CanExecuteEvent.prototype={__proto__:Event.p rototype,command:null,canExecute_:false,get canExecute(){return this.canExecute_ },set canExecute(canExecute){this.canExecute_=!!canExecute;this.stopPropagation( );this.preventDefault()}};return{Command:Command,CanExecuteEvent:CanExecuteEvent }}); 20 cr.define("cr.ui",function(){function KeyboardShortcut(shortcut){var mods={};var ident="";shortcut.split("|").forEach(function(part){var partLc=part.toLowerCase ();switch(partLc){case"alt":case"ctrl":case"meta":case"shift":mods[partLc+"Key"] =true;break;default:if(ident)throw Error("Invalid shortcut");ident=part}});this. ident_=ident;this.mods_=mods}KeyboardShortcut.prototype={matchesEvent:function(e ){if(e.key==this.ident_){var mods=this.mods_;return["altKey","ctrlKey","metaKey" ,"shiftKey"].every(function(k){return e[k]==!!mods[k]})}return false}};var Comma nd=cr.ui.define("command");Command.prototype={__proto__:HTMLElement.prototype,de corate:function(){CommandManager.init(assert(this.ownerDocument));if(this.hasAtt ribute("shortcut"))this.shortcut=this.getAttribute("shortcut")},execute:function (opt_element){if(this.disabled)return;var doc=this.ownerDocument;if(doc.activeEl ement){var e=new Event("command",{bubbles:true});e.command=this;(opt_element||do c.activeElement).dispatchEvent(e)}},canExecuteChange:function(opt_node){dispatch CanExecuteEvent(this,opt_node||this.ownerDocument.activeElement)},shortcut_:"",g et shortcut(){return this.shortcut_},set shortcut(shortcut){var oldShortcut=this .shortcut_;if(shortcut!==oldShortcut){this.keyboardShortcuts_=shortcut.split(/\s +/).map(function(shortcut){return new KeyboardShortcut(shortcut)});this.shortcut _=shortcut;cr.dispatchPropertyChange(this,"shortcut",this.shortcut_,oldShortcut) }},matchesEvent:function(e){if(!this.keyboardShortcuts_)return false;return this .keyboardShortcuts_.some(function(keyboardShortcut){return keyboardShortcut.matc hesEvent(e)})}};cr.defineProperty(Command,"label",cr.PropertyKind.ATTR);cr.defin eProperty(Command,"disabled",cr.PropertyKind.BOOL_ATTR);cr.defineProperty(Comman d,"hidden",cr.PropertyKind.BOOL_ATTR);cr.defineProperty(Command,"checked",cr.Pro pertyKind.BOOL_ATTR);cr.defineProperty(Command,"hideShortcutText",cr.PropertyKin d.BOOL_ATTR);function dispatchCanExecuteEvent(command,target){var e=new CanExecu teEvent(command);target.dispatchEvent(e);command.disabled=!e.canExecute}var comm andManagers={};function CommandManager(doc){doc.addEventListener("focus",this.ha ndleFocus_.bind(this),true);doc.addEventListener("keydown",this.handleKeyDown_.b ind(this),false)}CommandManager.init=function(doc){var uid=cr.getUid(doc);if(!(u id in commandManagers)){commandManagers[uid]=new CommandManager(doc)}};CommandMa nager.prototype={handleFocus_:function(e){var target=e.target;if(target.menu||ta rget.command)return;var commands=Array.prototype.slice.call(target.ownerDocument .querySelectorAll("command"));commands.forEach(function(command){dispatchCanExec uteEvent(command,target)})},handleKeyDown_:function(e){var target=e.target;var c ommands=Array.prototype.slice.call(target.ownerDocument.querySelectorAll("comman d"));for(var i=0,command;command=commands[i];i++){if(command.matchesEvent(e)){co mmand.canExecuteChange();if(!command.disabled){e.preventDefault();e.stopPropagat ion();command.execute();return}}}}};function CanExecuteEvent(command){var e=new Event("canExecute",{bubbles:true,cancelable:true});e.__proto__=CanExecuteEvent.p rototype;e.command=command;return e}CanExecuteEvent.prototype={__proto__:Event.p rototype,command:null,canExecute_:false,get canExecute(){return this.canExecute_ },set canExecute(canExecute){this.canExecute_=!!canExecute;this.stopPropagation( );this.preventDefault()}};return{Command:Command,CanExecuteEvent:CanExecuteEvent }});
21 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 21 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
22 // Use of this source code is governed by a BSD-style license that can be 22 // Use of this source code is governed by a BSD-style license that can be
23 // found in the LICENSE file. 23 // found in the LICENSE file.
24 function $(id){var el=document.getElementById(id);return el?assertInstanceof(el, HTMLElement):null}function getSVGElement(id){var el=document.getElementById(id); return el?assertInstanceof(el,Element):null}function announceAccessibleMessage(m sg){var element=document.createElement("div");element.setAttribute("aria-live"," polite");element.style.position="fixed";element.style.left="-9999px";element.sty le.height="0px";element.innerText=msg;document.body.appendChild(element);window. setTimeout(function(){document.body.removeChild(element)},0)}function url(s){var s2=s.replace(/(\(|\)|\,|\s|\'|\"|\\)/g,"\\$1");if(/\\\\$/.test(s2)){s2+=" "}ret urn'url("'+s2+'")'}function parseQueryParams(location){var params={};var query=u nescape(location.search.substring(1));var vars=query.split("&");for(var i=0;i<va rs.length;i++){var pair=vars[i].split("=");params[pair[0]]=pair[1]}return params }function setQueryParam(location,key,value){var query=parseQueryParams(location) ;query[encodeURIComponent(key)]=encodeURIComponent(value);var newQuery="";for(va r q in query){newQuery+=(newQuery?"&":"?")+q+"="+query[q]}return location.origin +location.pathname+newQuery+location.hash}function findAncestorByClass(el,classN ame){return findAncestor(el,function(el){return el.classList&&el.classList.conta ins(className)})}function findAncestor(node,predicate){var last=false;while(node !=null&&!(last=predicate(node))){node=node.parentNode}return last?node:null}func tion swapDomNodes(a,b){var afterA=a.nextSibling;if(afterA==b){swapDomNodes(b,a); return}var aParent=a.parentNode;b.parentNode.replaceChild(a,b);aParent.insertBef ore(b,afterA)}function disableTextSelectAndDrag(opt_allowSelectStart,opt_allowDr agStart){document.onselectstart=function(e){if(!(opt_allowSelectStart&&opt_allow SelectStart.call(this,e)))e.preventDefault()};document.ondragstart=function(e){i f(!(opt_allowDragStart&&opt_allowDragStart.call(this,e)))e.preventDefault()}}fun ction preventDefaultOnPoundLinkClicks(){document.addEventListener("click",functi on(e){var anchor=findAncestor(e.target,function(el){return el.tagName=="A"});if( anchor&&anchor.getAttribute("href")=="#")e.preventDefault()})}function isRTL(){r eturn document.documentElement.dir=="rtl"}function getRequiredElement(id){return assertInstanceof($(id),HTMLElement,"Missing required element: "+id)}function qu eryRequiredElement(selectors,opt_context){var element=(opt_context||document).qu erySelector(selectors);return assertInstanceof(element,HTMLElement,"Missing requ ired element: "+selectors)}["click","auxclick"].forEach(function(eventName){docu ment.addEventListener(eventName,function(e){if(e.button>1)return;if(e.defaultPre vented)return;var eventPath=e.path;var anchor=null;if(eventPath){for(var i=0;i<e ventPath.length;i++){var element=eventPath[i];if(element.tagName==="A"&&element. href){anchor=element;break}}}var el=e.target;if(!anchor&&el.nodeType==Node.ELEME NT_NODE&&el.webkitMatchesSelector("A, A *")){while(el.tagName!="A"){el=el.parent Element}anchor=el}if(!anchor)return;anchor=anchor;if((anchor.protocol=="file:"|| anchor.protocol=="about:")&&(e.button==0||e.button==1)){chrome.send("navigateToU rl",[anchor.href,anchor.target,e.button,e.altKey,e.ctrlKey,e.metaKey,e.shiftKey] );e.preventDefault()}})});function appendParam(url,key,value){var param=encodeUR IComponent(key)+"="+encodeURIComponent(value);if(url.indexOf("?")==-1)return url +"?"+param;return url+"&"+param}function createElementWithClassName(type,classNa me){var elm=document.createElement(type);elm.className=className;return elm}func tion ensureTransitionEndEvent(el,opt_timeOut){if(opt_timeOut===undefined){var st yle=getComputedStyle(el);opt_timeOut=parseFloat(style.transitionDuration)*1e3;op t_timeOut+=50}var fired=false;el.addEventListener("webkitTransitionEnd",function f(e){el.removeEventListener("webkitTransitionEnd",f);fired=true});window.setTim eout(function(){if(!fired)cr.dispatchSimpleEvent(el,"webkitTransitionEnd",true)} ,opt_timeOut)}function scrollTopForDocument(doc){return doc.documentElement.scro llTop||doc.body.scrollTop}function setScrollTopForDocument(doc,value){doc.docume ntElement.scrollTop=doc.body.scrollTop=value}function scrollLeftForDocument(doc) {return doc.documentElement.scrollLeft||doc.body.scrollLeft}function setScrollLe ftForDocument(doc,value){doc.documentElement.scrollLeft=doc.body.scrollLeft=valu e}function HTMLEscape(original){return original.replace(/&/g,"&amp;").replace(/< /g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}fun ction elide(original,maxLength){if(original.length<=maxLength)return original;re turn original.substring(0,maxLength-1)+"…"}function quoteString(str){return str. replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g,"\\$1")}function listenOnc e(target,eventNames,callback){if(!Array.isArray(eventNames))eventNames=eventName s.split(/ +/);var removeAllAndCallCallback=function(event){eventNames.forEach(fu nction(eventName){target.removeEventListener(eventName,removeAllAndCallCallback, false)});return callback(event)};eventNames.forEach(function(eventName){target.a ddEventListener(eventName,removeAllAndCallCallback,false)})} 24 function $(id){var el=document.getElementById(id);return el?assertInstanceof(el, HTMLElement):null}function getSVGElement(id){var el=document.getElementById(id); return el?assertInstanceof(el,Element):null}function announceAccessibleMessage(m sg){var element=document.createElement("div");element.setAttribute("aria-live"," polite");element.style.position="fixed";element.style.left="-9999px";element.sty le.height="0px";element.innerText=msg;document.body.appendChild(element);window. setTimeout(function(){document.body.removeChild(element)},0)}function url(s){var s2=s.replace(/(\(|\)|\,|\s|\'|\"|\\)/g,"\\$1");if(/\\\\$/.test(s2)){s2+=" "}ret urn'url("'+s2+'")'}function parseQueryParams(location){var params={};var query=u nescape(location.search.substring(1));var vars=query.split("&");for(var i=0;i<va rs.length;i++){var pair=vars[i].split("=");params[pair[0]]=pair[1]}return params }function setQueryParam(location,key,value){var query=parseQueryParams(location) ;query[encodeURIComponent(key)]=encodeURIComponent(value);var newQuery="";for(va r q in query){newQuery+=(newQuery?"&":"?")+q+"="+query[q]}return location.origin +location.pathname+newQuery+location.hash}function findAncestorByClass(el,classN ame){return findAncestor(el,function(el){return el.classList&&el.classList.conta ins(className)})}function findAncestor(node,predicate){var last=false;while(node !=null&&!(last=predicate(node))){node=node.parentNode}return last?node:null}func tion swapDomNodes(a,b){var afterA=a.nextSibling;if(afterA==b){swapDomNodes(b,a); return}var aParent=a.parentNode;b.parentNode.replaceChild(a,b);aParent.insertBef ore(b,afterA)}function disableTextSelectAndDrag(opt_allowSelectStart,opt_allowDr agStart){document.onselectstart=function(e){if(!(opt_allowSelectStart&&opt_allow SelectStart.call(this,e)))e.preventDefault()};document.ondragstart=function(e){i f(!(opt_allowDragStart&&opt_allowDragStart.call(this,e)))e.preventDefault()}}fun ction preventDefaultOnPoundLinkClicks(){document.addEventListener("click",functi on(e){var anchor=findAncestor(e.target,function(el){return el.tagName=="A"});if( anchor&&anchor.getAttribute("href")=="#")e.preventDefault()})}function isRTL(){r eturn document.documentElement.dir=="rtl"}function getRequiredElement(id){return assertInstanceof($(id),HTMLElement,"Missing required element: "+id)}function qu eryRequiredElement(selectors,opt_context){var element=(opt_context||document).qu erySelector(selectors);return assertInstanceof(element,HTMLElement,"Missing requ ired element: "+selectors)}["click","auxclick"].forEach(function(eventName){docu ment.addEventListener(eventName,function(e){if(e.button>1)return;if(e.defaultPre vented)return;var eventPath=e.path;var anchor=null;if(eventPath){for(var i=0;i<e ventPath.length;i++){var element=eventPath[i];if(element.tagName==="A"&&element. href){anchor=element;break}}}var el=e.target;if(!anchor&&el.nodeType==Node.ELEME NT_NODE&&el.webkitMatchesSelector("A, A *")){while(el.tagName!="A"){el=el.parent Element}anchor=el}if(!anchor)return;anchor=anchor;if((anchor.protocol=="file:"|| anchor.protocol=="about:")&&(e.button==0||e.button==1)){chrome.send("navigateToU rl",[anchor.href,anchor.target,e.button,e.altKey,e.ctrlKey,e.metaKey,e.shiftKey] );e.preventDefault()}})});function appendParam(url,key,value){var param=encodeUR IComponent(key)+"="+encodeURIComponent(value);if(url.indexOf("?")==-1)return url +"?"+param;return url+"&"+param}function createElementWithClassName(type,classNa me){var elm=document.createElement(type);elm.className=className;return elm}func tion ensureTransitionEndEvent(el,opt_timeOut){if(opt_timeOut===undefined){var st yle=getComputedStyle(el);opt_timeOut=parseFloat(style.transitionDuration)*1e3;op t_timeOut+=50}var fired=false;el.addEventListener("webkitTransitionEnd",function f(e){el.removeEventListener("webkitTransitionEnd",f);fired=true});window.setTim eout(function(){if(!fired)cr.dispatchSimpleEvent(el,"webkitTransitionEnd",true)} ,opt_timeOut)}function scrollTopForDocument(doc){return doc.documentElement.scro llTop||doc.body.scrollTop}function setScrollTopForDocument(doc,value){doc.docume ntElement.scrollTop=doc.body.scrollTop=value}function scrollLeftForDocument(doc) {return doc.documentElement.scrollLeft||doc.body.scrollLeft}function setScrollLe ftForDocument(doc,value){doc.documentElement.scrollLeft=doc.body.scrollLeft=valu e}function HTMLEscape(original){return original.replace(/&/g,"&amp;").replace(/< /g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}fun ction elide(original,maxLength){if(original.length<=maxLength)return original;re turn original.substring(0,maxLength-1)+"…"}function quoteString(str){return str. replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g,"\\$1")}function listenOnc e(target,eventNames,callback){if(!Array.isArray(eventNames))eventNames=eventName s.split(/ +/);var removeAllAndCallCallback=function(event){eventNames.forEach(fu nction(eventName){target.removeEventListener(eventName,removeAllAndCallCallback, false)});return callback(event)};eventNames.forEach(function(eventName){target.a ddEventListener(eventName,removeAllAndCallCallback,false)})}
25 // <if expr="is_ios"> 25 // <if expr="is_ios">
26 if(!("key"in KeyboardEvent.prototype)){Object.defineProperty(KeyboardEvent.proto type,"key",{get:function(){if(this.keyCode>=48&&this.keyCode<=57)return String.f romCharCode(this.keyCode);if(this.keyCode>=65&&this.keyCode<=90){var result=Stri ng.fromCharCode(this.keyCode).toLowerCase();if(this.shiftKey)result=result.toUpp erCase();return result}switch(this.keyCode){case 8:return"Backspace";case 9:retu rn"Tab";case 13:return"Enter";case 16:return"Shift";case 17:return"Control";case 18:return"Alt";case 27:return"Escape";case 32:return" ";case 33:return"PageUp"; case 34:return"PageDown";case 35:return"End";case 36:return"Home";case 37:return "ArrowLeft";case 38:return"ArrowUp";case 39:return"ArrowRight";case 40:return"Ar rowDown";case 45:return"Insert";case 46:return"Delete";case 91:return"Meta";case 112:return"F1";case 113:return"F2";case 114:return"F3";case 115:return"F4";case 116:return"F5";case 117:return"F6";case 118:return"F7";case 119:return"F8";case 120:return"F9";case 121:return"F10";case 122:return"F11";case 123:return"F12";c ase 187:return"=";case 189:return"-";case 219:return"[";case 221:return"]"}retur n"Unidentified"}})}else{window.console.log("KeyboardEvent.Key polyfill not requi red")} 26 if(!("key"in KeyboardEvent.prototype)){Object.defineProperty(KeyboardEvent.proto type,"key",{get:function(){if(this.keyCode>=48&&this.keyCode<=57)return String.f romCharCode(this.keyCode);if(this.keyCode>=65&&this.keyCode<=90){var result=Stri ng.fromCharCode(this.keyCode).toLowerCase();if(this.shiftKey)result=result.toUpp erCase();return result}switch(this.keyCode){case 8:return"Backspace";case 9:retu rn"Tab";case 13:return"Enter";case 16:return"Shift";case 17:return"Control";case 18:return"Alt";case 27:return"Escape";case 32:return" ";case 33:return"PageUp"; case 34:return"PageDown";case 35:return"End";case 36:return"Home";case 37:return "ArrowLeft";case 38:return"ArrowUp";case 39:return"ArrowRight";case 40:return"Ar rowDown";case 45:return"Insert";case 46:return"Delete";case 91:return"Meta";case 112:return"F1";case 113:return"F2";case 114:return"F3";case 115:return"F4";case 116:return"F5";case 117:return"F6";case 118:return"F7";case 119:return"F8";case 120:return"F9";case 121:return"F10";case 122:return"F11";case 123:return"F12";c ase 187:return"=";case 189:return"-";case 219:return"[";case 221:return"]"}retur n"Unidentified"}})}else{window.console.log("KeyboardEvent.Key polyfill not requi red")}
27 // </if> /* is_ios */ 27 // </if> /* is_ios */
28 function importModules(moduleNames){return new Promise(function(resolve){define( moduleNames,function(){resolve(Array.from(arguments))})})}Polymer.IronResizableB ehavior={properties:{_parentResizable:{type:Object,observer:"_parentResizableCha nged"},_notifyingDescendant:{type:Boolean,value:false}},listeners:{"iron-request -resize-notifications":"_onIronRequestResizeNotifications"},created:function(){t his._interestedResizables=[];this._boundNotifyResize=this.notifyResize.bind(this )},attached:function(){this.fire("iron-request-resize-notifications",null,{node: this,bubbles:true,cancelable:true});if(!this._parentResizable){window.addEventLi stener("resize",this._boundNotifyResize);this.notifyResize()}},detached:function (){if(this._parentResizable){this._parentResizable.stopResizeNotificationsFor(th is)}else{window.removeEventListener("resize",this._boundNotifyResize)}this._pare ntResizable=null},notifyResize:function(){if(!this.isAttached){return}this._inte restedResizables.forEach(function(resizable){if(this.resizerShouldNotify(resizab le)){this._notifyDescendant(resizable)}},this);this._fireResize()},assignParentR esizable:function(parentResizable){this._parentResizable=parentResizable},stopRe sizeNotificationsFor:function(target){var index=this._interestedResizables.index Of(target);if(index>-1){this._interestedResizables.splice(index,1);this.unlisten (target,"iron-resize","_onDescendantIronResize")}},resizerShouldNotify:function( element){return true},_onDescendantIronResize:function(event){if(this._notifying Descendant){event.stopPropagation();return}if(!Polymer.Settings.useShadow){this. _fireResize()}},_fireResize:function(){this.fire("iron-resize",null,{node:this,b ubbles:false})},_onIronRequestResizeNotifications:function(event){var target=eve nt.path?event.path[0]:event.target;if(target===this){return}if(this._interestedR esizables.indexOf(target)===-1){this._interestedResizables.push(target);this.lis ten(target,"iron-resize","_onDescendantIronResize")}target.assignParentResizable (this);this._notifyDescendant(target);event.stopPropagation()},_parentResizableC hanged:function(parentResizable){if(parentResizable){window.removeEventListener( "resize",this._boundNotifyResize)}},_notifyDescendant:function(descendant){if(!t his.isAttached){return}this._notifyingDescendant=true;descendant.notifyResize(); this._notifyingDescendant=false}};(function(){"use strict";var KEY_IDENTIFIER={" U+0008":"backspace","U+0009":"tab","U+001B":"esc","U+0020":"space","U+007F":"del "};var KEY_CODE={8:"backspace",9:"tab",13:"enter",27:"esc",33:"pageup",34:"paged own",35:"end",36:"home",32:"space",37:"left",38:"up",39:"right",40:"down",46:"de l",106:"*"};var MODIFIER_KEYS={shift:"shiftKey",ctrl:"ctrlKey",alt:"altKey",meta :"metaKey"};var KEY_CHAR=/[a-z0-9*]/;var IDENT_CHAR=/U\+/;var ARROW_KEY=/^arrow/ ;var SPACE_KEY=/^space(bar)?/;var ESC_KEY=/^escape$/;function transformKey(key,n oSpecialChars){var validKey="";if(key){var lKey=key.toLowerCase();if(lKey===" "| |SPACE_KEY.test(lKey)){validKey="space"}else if(ESC_KEY.test(lKey)){validKey="es c"}else if(lKey.length==1){if(!noSpecialChars||KEY_CHAR.test(lKey)){validKey=lKe y}}else if(ARROW_KEY.test(lKey)){validKey=lKey.replace("arrow","")}else if(lKey= ="multiply"){validKey="*"}else{validKey=lKey}}return validKey}function transform KeyIdentifier(keyIdent){var validKey="";if(keyIdent){if(keyIdent in KEY_IDENTIFI ER){validKey=KEY_IDENTIFIER[keyIdent]}else if(IDENT_CHAR.test(keyIdent)){keyIden t=parseInt(keyIdent.replace("U+","0x"),16);validKey=String.fromCharCode(keyIdent ).toLowerCase()}else{validKey=keyIdent.toLowerCase()}}return validKey}function t ransformKeyCode(keyCode){var validKey="";if(Number(keyCode)){if(keyCode>=65&&key Code<=90){validKey=String.fromCharCode(32+keyCode)}else if(keyCode>=112&&keyCode <=123){validKey="f"+(keyCode-112)}else if(keyCode>=48&&keyCode<=57){validKey=Str ing(keyCode-48)}else if(keyCode>=96&&keyCode<=105){validKey=String(keyCode-96)}e lse{validKey=KEY_CODE[keyCode]}}return validKey}function normalizedKeyForEvent(k eyEvent,noSpecialChars){if(keyEvent.key){return transformKey(keyEvent.key,noSpec ialChars)}if(keyEvent.detail&&keyEvent.detail.key){return transformKey(keyEvent. detail.key,noSpecialChars)}return transformKeyIdentifier(keyEvent.keyIdentifier) ||transformKeyCode(keyEvent.keyCode)||""}function keyComboMatchesEvent(keyCombo, event){var keyEvent=normalizedKeyForEvent(event,keyCombo.hasModifiers);return ke yEvent===keyCombo.key&&(!keyCombo.hasModifiers||!!event.shiftKey===!!keyCombo.sh iftKey&&!!event.ctrlKey===!!keyCombo.ctrlKey&&!!event.altKey===!!keyCombo.altKey &&!!event.metaKey===!!keyCombo.metaKey)}function parseKeyComboString(keyComboStr ing){if(keyComboString.length===1){return{combo:keyComboString,key:keyComboStrin g,event:"keydown"}}return keyComboString.split("+").reduce(function(parsedKeyCom bo,keyComboPart){var eventParts=keyComboPart.split(":");var keyName=eventParts[0 ];var event=eventParts[1];if(keyName in MODIFIER_KEYS){parsedKeyCombo[MODIFIER_K EYS[keyName]]=true;parsedKeyCombo.hasModifiers=true}else{parsedKeyCombo.key=keyN ame;parsedKeyCombo.event=event||"keydown"}return parsedKeyCombo},{combo:keyCombo String.split(":").shift()})}function parseEventString(eventString){return eventS tring.trim().split(" ").map(function(keyComboString){return parseKeyComboString( keyComboString)})}Polymer.IronA11yKeysBehavior={properties:{keyEventTarget:{type :Object,value:function(){return this}},stopKeyboardEventPropagation:{type:Boolea n,value:false},_boundKeyHandlers:{type:Array,value:function(){return[]}},_impera tiveKeyBindings:{type:Object,value:function(){return{}}}},observers:["_resetKeyE ventListeners(keyEventTarget, _boundKeyHandlers)"],keyBindings:{},registered:fun ction(){this._prepKeyBindings()},attached:function(){this._listenKeyEventListene rs()},detached:function(){this._unlistenKeyEventListeners()},addOwnKeyBinding:fu nction(eventString,handlerName){this._imperativeKeyBindings[eventString]=handler Name;this._prepKeyBindings();this._resetKeyEventListeners()},removeOwnKeyBinding s:function(){this._imperativeKeyBindings={};this._prepKeyBindings();this._resetK eyEventListeners()},keyboardEventMatchesKeys:function(event,eventString){var key Combos=parseEventString(eventString);for(var i=0;i<keyCombos.length;++i){if(keyC omboMatchesEvent(keyCombos[i],event)){return true}}return false},_collectKeyBind ings:function(){var keyBindings=this.behaviors.map(function(behavior){return beh avior.keyBindings});if(keyBindings.indexOf(this.keyBindings)===-1){keyBindings.p ush(this.keyBindings)}return keyBindings},_prepKeyBindings:function(){this._keyB indings={};this._collectKeyBindings().forEach(function(keyBindings){for(var even tString in keyBindings){this._addKeyBinding(eventString,keyBindings[eventString] )}},this);for(var eventString in this._imperativeKeyBindings){this._addKeyBindin g(eventString,this._imperativeKeyBindings[eventString])}for(var eventName in thi s._keyBindings){this._keyBindings[eventName].sort(function(kb1,kb2){var b1=kb1[0 ].hasModifiers;var b2=kb2[0].hasModifiers;return b1===b2?0:b1?-1:1})}},_addKeyBi nding:function(eventString,handlerName){parseEventString(eventString).forEach(fu nction(keyCombo){this._keyBindings[keyCombo.event]=this._keyBindings[keyCombo.ev ent]||[];this._keyBindings[keyCombo.event].push([keyCombo,handlerName])},this)}, _resetKeyEventListeners:function(){this._unlistenKeyEventListeners();if(this.isA ttached){this._listenKeyEventListeners()}},_listenKeyEventListeners:function(){i f(!this.keyEventTarget){return}Object.keys(this._keyBindings).forEach(function(e ventName){var keyBindings=this._keyBindings[eventName];var boundKeyHandler=this. _onKeyBindingEvent.bind(this,keyBindings);this._boundKeyHandlers.push([this.keyE ventTarget,eventName,boundKeyHandler]);this.keyEventTarget.addEventListener(even tName,boundKeyHandler)},this)},_unlistenKeyEventListeners:function(){var keyHand lerTuple;var keyEventTarget;var eventName;var boundKeyHandler;while(this._boundK eyHandlers.length){keyHandlerTuple=this._boundKeyHandlers.pop();keyEventTarget=k eyHandlerTuple[0];eventName=keyHandlerTuple[1];boundKeyHandler=keyHandlerTuple[2 ];keyEventTarget.removeEventListener(eventName,boundKeyHandler)}},_onKeyBindingE vent:function(keyBindings,event){if(this.stopKeyboardEventPropagation){event.sto pPropagation()}if(event.defaultPrevented){return}for(var i=0;i<keyBindings.lengt h;i++){var keyCombo=keyBindings[i][0];var handlerName=keyBindings[i][1];if(keyCo mboMatchesEvent(keyCombo,event)){this._triggerKeyHandler(keyCombo,handlerName,ev ent);if(event.defaultPrevented){return}}}},_triggerKeyHandler:function(keyCombo, handlerName,keyboardEvent){var detail=Object.create(keyCombo);detail.keyboardEve nt=keyboardEvent;var event=new CustomEvent(keyCombo.event,{detail:detail,cancela ble:true});this[handlerName].call(this,event);if(event.defaultPrevented){keyboar dEvent.preventDefault()}}}})();Polymer.IronScrollTargetBehavior={properties:{scr ollTarget:{type:HTMLElement,value:function(){return this._defaultScrollTarget}}} ,observers:["_scrollTargetChanged(scrollTarget, isAttached)"],_shouldHaveListene r:true,_scrollTargetChanged:function(scrollTarget,isAttached){var eventTarget;if (this._oldScrollTarget){this._toggleScrollListener(false,this._oldScrollTarget); this._oldScrollTarget=null}if(!isAttached){return}if(scrollTarget==="document"){ this.scrollTarget=this._doc}else if(typeof scrollTarget==="string"){this.scrollT arget=this.domHost?this.domHost.$[scrollTarget]:Polymer.dom(this.ownerDocument). querySelector("#"+scrollTarget)}else if(this._isValidScrollTarget()){this._bound ScrollHandler=this._boundScrollHandler||this._scrollHandler.bind(this);this._old ScrollTarget=scrollTarget;this._toggleScrollListener(this._shouldHaveListener,sc rollTarget)}},_scrollHandler:function scrollHandler(){},get _defaultScrollTarget (){return this._doc},get _doc(){return this.ownerDocument.documentElement},get _ scrollTop(){if(this._isValidScrollTarget()){return this.scrollTarget===this._doc ?window.pageYOffset:this.scrollTarget.scrollTop}return 0},get _scrollLeft(){if(t his._isValidScrollTarget()){return this.scrollTarget===this._doc?window.pageXOff set:this.scrollTarget.scrollLeft}return 0},set _scrollTop(top){if(this.scrollTar get===this._doc){window.scrollTo(window.pageXOffset,top)}else if(this._isValidSc rollTarget()){this.scrollTarget.scrollTop=top}},set _scrollLeft(left){if(this.sc rollTarget===this._doc){window.scrollTo(left,window.pageYOffset)}else if(this._i sValidScrollTarget()){this.scrollTarget.scrollLeft=left}},scroll:function(left,t op){if(this.scrollTarget===this._doc){window.scrollTo(left,top)}else if(this._is ValidScrollTarget()){this.scrollTarget.scrollLeft=left;this.scrollTarget.scrollT op=top}},get _scrollTargetWidth(){if(this._isValidScrollTarget()){return this.sc rollTarget===this._doc?window.innerWidth:this.scrollTarget.offsetWidth}return 0} ,get _scrollTargetHeight(){if(this._isValidScrollTarget()){return this.scrollTar get===this._doc?window.innerHeight:this.scrollTarget.offsetHeight}return 0},_isV alidScrollTarget:function(){return this.scrollTarget instanceof HTMLElement},_to ggleScrollListener:function(yes,scrollTarget){if(!this._boundScrollHandler){retu rn}var eventTarget=scrollTarget===this._doc?window:scrollTarget;if(yes){eventTar get.addEventListener("scroll",this._boundScrollHandler)}else{eventTarget.removeE ventListener("scroll",this._boundScrollHandler)}},toggleScrollListener:function( yes){this._shouldHaveListener=yes;this._toggleScrollListener(yes,this.scrollTarg et)}};(function(){var IOS=navigator.userAgent.match(/iP(?:hone|ad;(?: U;)? CPU) OS (\d+)/);var IOS_TOUCH_SCROLLING=IOS&&IOS[1]>=8;var DEFAULT_PHYSICAL_COUNT=3;v ar HIDDEN_Y="-10000px";var ITEM_WIDTH=0;var ITEM_HEIGHT=1;var SECRET_TABINDEX=-1 00;Polymer({is:"iron-list",properties:{items:{type:Array},maxPhysicalCount:{type :Number,value:500},as:{type:String,value:"item"},indexAs:{type:String,value:"ind ex"},selectedAs:{type:String,value:"selected"},grid:{type:Boolean,value:false,re flectToAttribute:true},selectionEnabled:{type:Boolean,value:false},selectedItem: {type:Object,notify:true},selectedItems:{type:Object,notify:true},multiSelection :{type:Boolean,value:false}},observers:["_itemsChanged(items.*)","_selectionEnab ledChanged(selectionEnabled)","_multiSelectionChanged(multiSelection)","_setOver flow(scrollTarget)"],behaviors:[Polymer.Templatizer,Polymer.IronResizableBehavio r,Polymer.IronA11yKeysBehavior,Polymer.IronScrollTargetBehavior],keyBindings:{up :"_didMoveUp",down:"_didMoveDown",enter:"_didEnter"},_ratio:.5,_scrollerPaddingT op:0,_scrollPosition:0,_physicalSize:0,_physicalAverage:0,_physicalAverageCount: 0,_physicalTop:0,_virtualCount:0,_physicalIndexForKey:null,_estScrollHeight:0,_s crollHeight:0,_viewportHeight:0,_viewportWidth:0,_physicalItems:null,_physicalSi zes:null,_firstVisibleIndexVal:null,_lastVisibleIndexVal:null,_collection:null,_ maxPages:2,_focusedItem:null,_focusedIndex:-1,_offscreenFocusedItem:null,_focusB ackfillItem:null,_itemsPerRow:1,_itemWidth:0,_rowHeight:0,_templateCost:0,get _p hysicalBottom(){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.gri d?this._physicalRows*this._rowHeight:this._physicalSize;return size-this._viewpo rtHeight},get _maxScrollTop(){return this._estScrollHeight-this._viewportHeight+ this._scrollerPaddingTop},_minVirtualStart:0,get _maxVirtualStart(){return Math. max(0,this._virtualCount-this._physicalCount)},_virtualStartVal:0,set _virtualSt art(val){this._virtualStartVal=Math.min(this._maxVirtualStart,Math.max(this._min VirtualStart,val))},get _virtualStart(){return this._virtualStartVal||0},_physic alStartVal:0,set _physicalStart(val){this._physicalStartVal=val%this._physicalCo unt;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},_ph ysicalCountVal:0,set _physicalCount(val){this._physicalCountVal=val;this._physic alEnd=(this._physicalStart+this._physicalCount-1)%this._physicalCount},get _phys icalCount(){return this._physicalCountVal},_physicalEnd:0,get _optPhysicalSize() {if(this.grid){return this._estRowsInView*this._rowHeight*this._maxPages}return this._viewportHeight*this._maxPages},get _isVisible(){return Boolean(this.offset Width||this.offsetHeight)},get firstVisibleIndex(){if(this._firstVisibleIndexVal ===null){var physicalOffset=Math.floor(this._physicalTop+this._scrollerPaddingTo p);this._firstVisibleIndexVal=this._iterateItems(function(pidx,vidx){physicalOff set+=this._getPhysicalSizeIncrement(pidx);if(physicalOffset>this._scrollPosition ){return this.grid?vidx-vidx%this._itemsPerRow:vidx}if(this.grid&&this._virtualC ount-1===vidx){return vidx-vidx%this._itemsPerRow}})||0}return this._firstVisibl eIndexVal},get lastVisibleIndex(){if(this._lastVisibleIndexVal===null){if(this.g rid){var lastIndex=this.firstVisibleIndex+this._estRowsInView*this._itemsPerRow- 1;this._lastVisibleIndexVal=Math.min(this._virtualCount,lastIndex)}else{var phys icalOffset=this._physicalTop;this._iterateItems(function(pidx,vidx){if(physicalO ffset<this._scrollBottom){this._lastVisibleIndexVal=vidx}else{return true}physic alOffset+=this._getPhysicalSizeIncrement(pidx)})}}return this._lastVisibleIndexV al},get _defaultScrollTarget(){return this},get _virtualRowCount(){return Math.c eil(this._virtualCount/this._itemsPerRow)},get _estRowsInView(){return Math.ceil (this._viewportHeight/this._rowHeight)},get _physicalRows(){return Math.ceil(thi s._physicalCount/this._itemsPerRow)},ready:function(){this.addEventListener("foc us",this._didFocus.bind(this),true)},attached:function(){if(this._physicalCount= ==0){this._debounceTemplate(this._render)}this.listen(this,"iron-resize","_resiz eHandler")},detached:function(){this.unlisten(this,"iron-resize","_resizeHandler ")},_setOverflow:function(scrollTarget){this.style.webkitOverflowScrolling=scrol lTarget===this?"touch":"";this.style.overflow=scrollTarget===this?"auto":""},upd ateViewportBoundaries:function(){this._scrollerPaddingTop=this.scrollTarget===th is?0:parseInt(window.getComputedStyle(this)["padding-top"],10);this._viewportWid th=this.$.items.offsetWidth;this._viewportHeight=this._scrollTargetHeight;this.g rid&&this._updateGridMetrics()},_scrollHandler:function(){var scrollTop=Math.max (0,Math.min(this._maxScrollTop,this._scrollTop));var delta=scrollTop-this._scrol lPosition;var isScrollingDown=delta>=0;this._scrollPosition=scrollTop;this._firs tVisibleIndexVal=null;this._lastVisibleIndexVal=null;if(Math.abs(delta)>this._ph ysicalSize){var idxAdjustment=Math.round(delta/this._physicalAverage)*this._item sPerRow;this._physicalTop=this._physicalTop+delta;this._virtualStart=this._virtu alStart+idxAdjustment;this._physicalStart=this._physicalStart+idxAdjustment;this ._update()}else{var reusables=this._getReusables(isScrollingDown);if(isScrolling Down){this._physicalTop=reusables.physicalTop;this._virtualStart=this._virtualSt art+reusables.indexes.length;this._physicalStart=this._physicalStart+reusables.i ndexes.length}else{this._virtualStart=this._virtualStart-reusables.indexes.lengt h;this._physicalStart=this._physicalStart-reusables.indexes.length}if(reusables. indexes.length===0){this._increasePoolIfNeeded()}else{this._update(reusables.ind exes,isScrollingDown?null:reusables.indexes)}}},_getReusables:function(fromTop){ var ith,lastIth,offsetContent,physicalItemHeight;var idxs=[];var protectedOffset Content=this._hiddenContentSize*this._ratio;var virtualStart=this._virtualStart; var virtualEnd=this._virtualEnd;var physicalCount=this._physicalCount;var physic alTop=this._physicalTop+this._scrollerPaddingTop;var scrollTop=this._scrollTop;v ar scrollBottom=this._scrollBottom;if(fromTop){ith=this._physicalStart;lastIth=t his._physicalEnd;offsetContent=scrollTop-physicalTop}else{ith=this._physicalEnd; lastIth=this._physicalStart;offsetContent=this._physicalBottom-scrollBottom}whil e(true){physicalItemHeight=this._getPhysicalSizeIncrement(ith);offsetContent=off setContent-physicalItemHeight;if(idxs.length>=physicalCount||offsetContent<=prot ectedOffsetContent){break}if(fromTop){if(virtualEnd+idxs.length+1>=this._virtual Count){break}if(physicalTop+physicalItemHeight>=scrollTop){break}idxs.push(ith); physicalTop=physicalTop+physicalItemHeight;ith=(ith+1)%physicalCount}else{if(vir tualStart-idxs.length<=0){break}if(physicalTop+this._physicalSize-physicalItemHe ight<=scrollBottom){break}idxs.push(ith);physicalTop=physicalTop-physicalItemHei ght;ith=ith===0?physicalCount-1:ith-1}}return{indexes:idxs,physicalTop:physicalT op-this._scrollerPaddingTop}},_update:function(itemSet,movingUp){if(itemSet&&ite mSet.length===0){return}this._manageFocus();this._assignModels(itemSet);this._up dateMetrics(itemSet);if(movingUp){while(movingUp.length){var idx=movingUp.pop(); this._physicalTop-=this._getPhysicalSizeIncrement(idx)}}this._positionItems();th is._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("*");Po lymer.dom(this).appendChild(inst.root)}return physicalItems},_increasePoolIfNeed ed:function(){if(this._viewportHeight===0){return false}var self=this;var isClie ntFull=this._physicalBottom>=this._scrollBottom&&this._physicalTop<=this._scroll Position;if(this._physicalSize>=this._optPhysicalSize&&isClientFull){return fals e}var maxPoolSize=Math.round(this._physicalCount*.5);if(!isClientFull){this._deb ounceTemplate(this._increasePool.bind(this,maxPoolSize));return true}this._yield (function(){self._increasePool(Math.min(maxPoolSize,Math.max(1,Math.round(50/sel f._templateCost))))});return true},_yield:function(cb){var g=window;var handle=g .requestIdleCallback?g.requestIdleCallback(cb):g.setTimeout(cb,16);Polymer.dom.a ddDebouncer({complete:function(){g.cancelIdleCallback?g.cancelIdleCallback(handl e):g.clearTimeout(handle);cb()}})},_increasePool:function(missingItems){var next PhysicalCount=Math.min(this._physicalCount+missingItems,this._virtualCount-this. _virtualStart,Math.max(this.maxPhysicalCount,DEFAULT_PHYSICAL_COUNT));var prevPh ysicalCount=this._physicalCount;var delta=nextPhysicalCount-prevPhysicalCount;va r ts=window.performance.now();if(delta<=0){return}[].push.apply(this._physicalIt ems,this._createPool(delta));[].push.apply(this._physicalSizes,new Array(delta)) ;this._physicalCount=prevPhysicalCount+delta;if(this._physicalStart>this._physic alEnd&&this._isIndexRendered(this._focusedIndex)&&this._getPhysicalIndex(this._f ocusedIndex)<this._physicalEnd){this._physicalStart=this._physicalStart+delta}th is._update();this._templateCost=(window.performance.now()-ts)/delta},_render:fun ction(){if(this.isAttached&&this._isVisible){if(this._physicalCount===0){this.up dateViewportBoundaries();this._increasePool(DEFAULT_PHYSICAL_COUNT)}else{var reu sables=this._getReusables(true);this._physicalTop=reusables.physicalTop;this._vi rtualStart=this._virtualStart+reusables.indexes.length;this._physicalStart=this. _physicalStart+reusables.indexes.length;this._update(reusables.indexes);this._up date()}}},_ensureTemplatized:function(){if(!this.ctor){var props={};props.__key_ _=true;props[this.as]=true;props[this.indexAs]=true;props[this.selectedAs]=true; props.tabIndex=true;this._instanceProps=props;this._userTemplate=Polymer.dom(thi s).querySelector("template");if(this._userTemplate){this.templatize(this._userTe mplate)}else{console.warn("iron-list requires a template to be provided in light -dom")}}},_getStampedChildren:function(){return this._physicalItems},_forwardIns tancePath:function(inst,path,value){if(path.indexOf(this.as+".")===0){this.notif yPath("items."+inst.__key__+"."+path.slice(this.as.length+1),value)}},_forwardPa rentProp:function(prop,value){if(this._physicalItems){this._physicalItems.forEac h(function(item){item._templateInstance[prop]=value},this)}},_forwardParentPath: function(path,value){if(this._physicalItems){this._physicalItems.forEach(functio n(item){item._templateInstance.notifyPath(path,value,true)},this)}},_forwardItem Path:function(path,value){if(!this._physicalIndexForKey){return}var dot=path.ind exOf(".");var key=path.substring(0,dot<0?path.length:dot);var idx=this._physical IndexForKey[key];var offscreenItem=this._offscreenFocusedItem;var el=offscreenIt em&&offscreenItem._templateInstance.__key__===key?offscreenItem:this._physicalIt ems[idx];if(!el||el._templateInstance.__key__!==key){return}if(dot>=0){path=this .as+"."+path.substring(dot+1);el._templateInstance.notifyPath(path,value,true)}e lse{var currentItem=el._templateInstance[this.as];if(Array.isArray(this.selected Items)){for(var i=0;i<this.selectedItems.length;i++){if(this.selectedItems[i]=== currentItem){this.set("selectedItems."+i,value);break}}}else if(this.selectedIte m===currentItem){this.set("selectedItem",value)}el._templateInstance[this.as]=va lue}},_itemsChanged:function(change){if(change.path==="items"){this._virtualStar t=0;this._physicalTop=0;this._virtualCount=this.items?this.items.length:0;this._ collection=this.items?Polymer.Collection.get(this.items):null;this._physicalInde xForKey={};this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null;this._ physicalCount=this._physicalCount||0;this._physicalItems=this._physicalItems||[] ;this._physicalSizes=this._physicalSizes||[];this._physicalStart=0;this._resetSc rollPosition(0);this._removeFocusedItem();this._debounceTemplate(this._render)}e lse if(change.path==="items.splices"){this._adjustVirtualIndex(change.value.inde xSplices);this._virtualCount=this.items?this.items.length:0;this._debounceTempla te(this._render)}else{this._forwardItemPath(change.path.split(".").slice(1).join ("."),change.value)}},_adjustVirtualIndex:function(splices){splices.forEach(func tion(splice){splice.removed.forEach(this._removeItem,this);if(splice.index<this. _virtualStart){var delta=Math.max(splice.addedCount-splice.removed.length,splice .index-this._virtualStart);this._virtualStart=this._virtualStart+delta;if(this._ focusedIndex>=0){this._focusedIndex=this._focusedIndex+delta}}},this)},_removeIt em:function(item){this.$.selector.deselect(item);if(this._focusedItem&&this._foc usedItem._templateInstance[this.as]===item){this._removeFocusedItem()}},_iterate Items: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(( rtn=fn.call(this,pidx,vidx))!=null){return rtn}}}else{pidx=this._physicalStart;v idx=this._virtualStart;for(;pidx<this._physicalCount;pidx++,vidx++){if((rtn=fn.c all(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:f unction(pidx){if(pidx>=this._physicalStart){return this._virtualStart+(pidx-this ._physicalStart)}return this._virtualStart+(this._physicalCount-this._physicalSt art)+pidx},_assignModels:function(itemSet){this._iterateItems(function(pidx,vidx ){var el=this._physicalItems[pidx];var inst=el._templateInstance;var item=this.i tems&&this.items[vidx];if(item!=null){inst[this.as]=item;inst.__key__=this._coll ection.getKey(item);inst[this.selectedAs]=this.$.selector.isSelected(item);inst[ this.indexAs]=vidx;inst.tabIndex=this._focusedIndex===vidx?0:-1;this._physicalIn dexForKey[inst.__key__]=pidx;el.removeAttribute("hidden")}else{inst.__key__=null ;el.setAttribute("hidden","")}},itemSet)},_updateMetrics:function(itemSet){Polym er.dom.flush();var newPhysicalSize=0;var oldPhysicalSize=0;var prevAvgCount=this ._physicalAverageCount;var prevPhysicalAvg=this._physicalAverage;this._iterateIt ems(function(pidx,vidx){oldPhysicalSize+=this._physicalSizes[pidx]||0;this._phys icalSizes[pidx]=this._physicalItems[pidx].offsetHeight;newPhysicalSize+=this._ph ysicalSizes[pidx];this._physicalAverageCount+=this._physicalSizes[pidx]?1:0},ite mSet);if(this.grid){this._updateGridMetrics();this._physicalSize=Math.ceil(this. _physicalCount/this._itemsPerRow)*this._rowHeight}else{this._physicalSize=this._ physicalSize+newPhysicalSize-oldPhysicalSize}if(this._physicalAverageCount!==pre vAvgCount){this._physicalAverage=Math.round((prevPhysicalAvg*prevAvgCount+newPhy sicalSize)/this._physicalAverageCount)}},_updateGridMetrics:function(){this._ite mWidth=this._physicalCount>0?this._physicalItems[0].getBoundingClientRect().widt h:200;this._rowHeight=this._physicalCount>0?this._physicalItems[0].offsetHeight: 200;this._itemsPerRow=this._itemWidth?Math.floor(this._viewportWidth/this._itemW idth):this._itemsPerRow},_positionItems:function(){this._adjustScrollPosition(); var y=this._physicalTop;if(this.grid){var totalItemWidth=this._itemsPerRow*this. _itemWidth;var rowOffset=(this._viewportWidth-totalItemWidth)/2;this._iterateIte ms(function(pidx,vidx){var modulus=vidx%this._itemsPerRow;var x=Math.floor(modul us*this._itemWidth+rowOffset);this.translate3d(x+"px",y+"px",0,this._physicalIte ms[pidx]);if(this._shouldRenderNextRow(vidx)){y+=this._rowHeight}})}else{this._i terateItems(function(pidx,vidx){this.translate3d(0,y+"px",0,this._physicalItems[ pidx]);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},_shouldRen derNextRow:function(vidx){return vidx%this._itemsPerRow===this._itemsPerRow-1},_ adjustScrollPosition:function(){var deltaHeight=this._virtualStart===0?this._phy sicalTop:Math.min(this._scrollPosition+this._physicalTop,0);if(deltaHeight){this ._physicalTop=this._physicalTop-deltaHeight;if(!IOS_TOUCH_SCROLLING&&this._physi calTop!==0){this._resetScrollPosition(this._scrollTop-deltaHeight)}}},_resetScro llPosition:function(pos){if(this.scrollTarget){this._scrollTop=pos;this._scrollP osition=this._scrollTop}},_updateScrollerSize:function(forceUpdate){if(this.grid ){this._estScrollHeight=this._virtualRowCount*this._rowHeight}else{this._estScro llHeight=this._physicalBottom+Math.max(this._virtualCount-this._physicalCount-th is._virtualStart,0)*this._physicalAverage}forceUpdate=forceUpdate||this._scrollH eight===0;forceUpdate=forceUpdate||this._scrollPosition>=this._estScrollHeight-t his._physicalSize;forceUpdate=forceUpdate||this.grid&&this.$.items.style.height< this._estScrollHeight;if(forceUpdate||Math.abs(this._estScrollHeight-this._scrol lHeight)>=this._optPhysicalSize){this.$.items.style.height=this._estScrollHeight +"px";this._scrollHeight=this._estScrollHeight}},scrollToItem:function(item){ret urn 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._virtual Count-1);if(!this._isIndexRendered(idx)||idx>=this._maxVirtualStart){this._virtu alStart=this.grid?idx-this._itemsPerRow*2:idx-1}this._manageFocus();this._assign Models();this._updateMetrics();this._physicalTop=Math.floor(this._virtualStart/t his._itemsPerRow)*this._physicalAverage;var currentTopItem=this._physicalStart;v ar currentVirtualItem=this._virtualStart;var targetOffsetTop=0;var hiddenContent Size=this._hiddenContentSize;while(currentVirtualItem<idx&&targetOffsetTop<=hidd enContentSize){targetOffsetTop=targetOffsetTop+this._getPhysicalSizeIncrement(cu rrentTopItem);currentTopItem=(currentTopItem+1)%this._physicalCount;currentVirtu alItem++}this._updateScrollerSize(true);this._positionItems();this._resetScrollP osition(this._physicalTop+this._scrollerPaddingTop+targetOffsetTop);this._increa sePoolIfNeeded();this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null} ,_resetAverage:function(){this._physicalAverage=0;this._physicalAverageCount=0}, _resizeHandler:function(){var delta=Math.abs(this._viewportHeight-this._scrollTa rgetHeight);if(IOS&&delta>0&&delta<100){return}Polymer.dom.addDebouncer(this.deb ounce("_debounceTemplate",function(){this.updateViewportBoundaries();this._rende r();if(this._isVisible){this.toggleScrollListener(true);if(this._physicalCount>0 ){this._resetAverage();this.scrollToIndex(this.firstVisibleIndex)}}else{this.tog gleScrollListener(false)}}.bind(this),1))},_getModelFromItem:function(item){var key=this._collection.getKey(item);var pidx=this._physicalIndexForKey[key];if(pid x!=null){return this._physicalItems[pidx]._templateInstance}return null},_getNor malizedItem:function(item){if(this._collection.getKey(item)===undefined){if(type of 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")}re turn item},selectItem:function(item){item=this._getNormalizedItem(item);var mode l=this._getModelFromItem(item);if(!this.multiSelection&&this.selectedItem){this. deselectItem(this.selectedItem)}if(model){model[this.selectedAs]=true}this.$.sel ector.select(item);this.updateSizeForItem(item)},deselectItem:function(item){ite m=this._getNormalizedItem(item);var model=this._getModelFromItem(item);if(model) {model[this.selectedAs]=false}this.$.selector.deselect(item);this.updateSizeForI tem(item)},toggleSelectionForItem:function(item){item=this._getNormalizedItem(it em);if(this.$.selector.isSelected(item)){this.deselectItem(item)}else{this.selec tItem(item)}},clearSelection:function(){function unselect(item){var model=this._ getModelFromItem(item);if(model){model[this.selectedAs]=false}}if(Array.isArray( this.selectedItems)){this.selectedItems.forEach(unselect,this)}else if(this.sele ctedItem){unselect.call(this,this.selectedItem)}this.$.selector.clearSelection() },_selectionEnabledChanged:function(selectionEnabled){var handler=selectionEnabl ed?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];va r activeEl=Polymer.dom(this.domHost?this.domHost.root:document).activeElement;va r physicalItem=this._physicalItems[this._getPhysicalIndex(model[this.indexAs])]; 28 function importModules(moduleNames){return new Promise(function(resolve){define( moduleNames,function(){resolve(Array.from(arguments))})})}function hasKeyModifie rs(e){return!!(e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)}Polymer.IronResizable Behavior={properties:{_parentResizable:{type:Object,observer:"_parentResizableCh anged"},_notifyingDescendant:{type:Boolean,value:false}},listeners:{"iron-reques t-resize-notifications":"_onIronRequestResizeNotifications"},created:function(){ this._interestedResizables=[];this._boundNotifyResize=this.notifyResize.bind(thi s)},attached:function(){this.fire("iron-request-resize-notifications",null,{node :this,bubbles:true,cancelable:true});if(!this._parentResizable){window.addEventL istener("resize",this._boundNotifyResize);this.notifyResize()}},detached:functio n(){if(this._parentResizable){this._parentResizable.stopResizeNotificationsFor(t his)}else{window.removeEventListener("resize",this._boundNotifyResize)}this._par entResizable=null},notifyResize:function(){if(!this.isAttached){return}this._int erestedResizables.forEach(function(resizable){if(this.resizerShouldNotify(resiza ble)){this._notifyDescendant(resizable)}},this);this._fireResize()},assignParent Resizable:function(parentResizable){this._parentResizable=parentResizable},stopR esizeNotificationsFor:function(target){var index=this._interestedResizables.inde xOf(target);if(index>-1){this._interestedResizables.splice(index,1);this.unliste n(target,"iron-resize","_onDescendantIronResize")}},resizerShouldNotify:function (element){return true},_onDescendantIronResize:function(event){if(this._notifyin gDescendant){event.stopPropagation();return}if(!Polymer.Settings.useShadow){this ._fireResize()}},_fireResize:function(){this.fire("iron-resize",null,{node:this, bubbles:false})},_onIronRequestResizeNotifications:function(event){var target=ev ent.path?event.path[0]:event.target;if(target===this){return}if(this._interested Resizables.indexOf(target)===-1){this._interestedResizables.push(target);this.li sten(target,"iron-resize","_onDescendantIronResize")}target.assignParentResizabl e(this);this._notifyDescendant(target);event.stopPropagation()},_parentResizable Changed:function(parentResizable){if(parentResizable){window.removeEventListener ("resize",this._boundNotifyResize)}},_notifyDescendant:function(descendant){if(! this.isAttached){return}this._notifyingDescendant=true;descendant.notifyResize() ;this._notifyingDescendant=false}};(function(){"use strict";var KEY_IDENTIFIER={ "U+0008":"backspace","U+0009":"tab","U+001B":"esc","U+0020":"space","U+007F":"de l"};var KEY_CODE={8:"backspace",9:"tab",13:"enter",27:"esc",33:"pageup",34:"page down",35:"end",36:"home",32:"space",37:"left",38:"up",39:"right",40:"down",46:"d el",106:"*"};var MODIFIER_KEYS={shift:"shiftKey",ctrl:"ctrlKey",alt:"altKey",met a:"metaKey"};var KEY_CHAR=/[a-z0-9*]/;var IDENT_CHAR=/U\+/;var ARROW_KEY=/^arrow /;var SPACE_KEY=/^space(bar)?/;var ESC_KEY=/^escape$/;function transformKey(key, noSpecialChars){var validKey="";if(key){var lKey=key.toLowerCase();if(lKey===" " ||SPACE_KEY.test(lKey)){validKey="space"}else if(ESC_KEY.test(lKey)){validKey="e sc"}else if(lKey.length==1){if(!noSpecialChars||KEY_CHAR.test(lKey)){validKey=lK ey}}else if(ARROW_KEY.test(lKey)){validKey=lKey.replace("arrow","")}else if(lKey =="multiply"){validKey="*"}else{validKey=lKey}}return validKey}function transfor mKeyIdentifier(keyIdent){var validKey="";if(keyIdent){if(keyIdent in KEY_IDENTIF IER){validKey=KEY_IDENTIFIER[keyIdent]}else if(IDENT_CHAR.test(keyIdent)){keyIde nt=parseInt(keyIdent.replace("U+","0x"),16);validKey=String.fromCharCode(keyIden t).toLowerCase()}else{validKey=keyIdent.toLowerCase()}}return validKey}function transformKeyCode(keyCode){var validKey="";if(Number(keyCode)){if(keyCode>=65&&ke yCode<=90){validKey=String.fromCharCode(32+keyCode)}else if(keyCode>=112&&keyCod e<=123){validKey="f"+(keyCode-112)}else if(keyCode>=48&&keyCode<=57){validKey=St ring(keyCode-48)}else if(keyCode>=96&&keyCode<=105){validKey=String(keyCode-96)} else{validKey=KEY_CODE[keyCode]}}return validKey}function normalizedKeyForEvent( keyEvent,noSpecialChars){if(keyEvent.key){return transformKey(keyEvent.key,noSpe cialChars)}if(keyEvent.detail&&keyEvent.detail.key){return transformKey(keyEvent .detail.key,noSpecialChars)}return transformKeyIdentifier(keyEvent.keyIdentifier )||transformKeyCode(keyEvent.keyCode)||""}function keyComboMatchesEvent(keyCombo ,event){var keyEvent=normalizedKeyForEvent(event,keyCombo.hasModifiers);return k eyEvent===keyCombo.key&&(!keyCombo.hasModifiers||!!event.shiftKey===!!keyCombo.s hiftKey&&!!event.ctrlKey===!!keyCombo.ctrlKey&&!!event.altKey===!!keyCombo.altKe y&&!!event.metaKey===!!keyCombo.metaKey)}function parseKeyComboString(keyComboSt ring){if(keyComboString.length===1){return{combo:keyComboString,key:keyComboStri ng,event:"keydown"}}return keyComboString.split("+").reduce(function(parsedKeyCo mbo,keyComboPart){var eventParts=keyComboPart.split(":");var keyName=eventParts[ 0];var event=eventParts[1];if(keyName in MODIFIER_KEYS){parsedKeyCombo[MODIFIER_ KEYS[keyName]]=true;parsedKeyCombo.hasModifiers=true}else{parsedKeyCombo.key=key Name;parsedKeyCombo.event=event||"keydown"}return parsedKeyCombo},{combo:keyComb oString.split(":").shift()})}function parseEventString(eventString){return event String.trim().split(" ").map(function(keyComboString){return parseKeyComboString (keyComboString)})}Polymer.IronA11yKeysBehavior={properties:{keyEventTarget:{typ e:Object,value:function(){return this}},stopKeyboardEventPropagation:{type:Boole an,value:false},_boundKeyHandlers:{type:Array,value:function(){return[]}},_imper ativeKeyBindings:{type:Object,value:function(){return{}}}},observers:["_resetKey EventListeners(keyEventTarget, _boundKeyHandlers)"],keyBindings:{},registered:fu nction(){this._prepKeyBindings()},attached:function(){this._listenKeyEventListen ers()},detached:function(){this._unlistenKeyEventListeners()},addOwnKeyBinding:f unction(eventString,handlerName){this._imperativeKeyBindings[eventString]=handle rName;this._prepKeyBindings();this._resetKeyEventListeners()},removeOwnKeyBindin gs:function(){this._imperativeKeyBindings={};this._prepKeyBindings();this._reset KeyEventListeners()},keyboardEventMatchesKeys:function(event,eventString){var ke yCombos=parseEventString(eventString);for(var i=0;i<keyCombos.length;++i){if(key ComboMatchesEvent(keyCombos[i],event)){return true}}return false},_collectKeyBin dings:function(){var keyBindings=this.behaviors.map(function(behavior){return be havior.keyBindings});if(keyBindings.indexOf(this.keyBindings)===-1){keyBindings. push(this.keyBindings)}return keyBindings},_prepKeyBindings:function(){this._key Bindings={};this._collectKeyBindings().forEach(function(keyBindings){for(var eve ntString in keyBindings){this._addKeyBinding(eventString,keyBindings[eventString ])}},this);for(var eventString in this._imperativeKeyBindings){this._addKeyBindi ng(eventString,this._imperativeKeyBindings[eventString])}for(var eventName in th is._keyBindings){this._keyBindings[eventName].sort(function(kb1,kb2){var b1=kb1[ 0].hasModifiers;var b2=kb2[0].hasModifiers;return b1===b2?0:b1?-1:1})}},_addKeyB inding:function(eventString,handlerName){parseEventString(eventString).forEach(f unction(keyCombo){this._keyBindings[keyCombo.event]=this._keyBindings[keyCombo.e vent]||[];this._keyBindings[keyCombo.event].push([keyCombo,handlerName])},this)} ,_resetKeyEventListeners:function(){this._unlistenKeyEventListeners();if(this.is Attached){this._listenKeyEventListeners()}},_listenKeyEventListeners:function(){ if(!this.keyEventTarget){return}Object.keys(this._keyBindings).forEach(function( eventName){var keyBindings=this._keyBindings[eventName];var boundKeyHandler=this ._onKeyBindingEvent.bind(this,keyBindings);this._boundKeyHandlers.push([this.key EventTarget,eventName,boundKeyHandler]);this.keyEventTarget.addEventListener(eve ntName,boundKeyHandler)},this)},_unlistenKeyEventListeners:function(){var keyHan dlerTuple;var keyEventTarget;var eventName;var boundKeyHandler;while(this._bound KeyHandlers.length){keyHandlerTuple=this._boundKeyHandlers.pop();keyEventTarget= keyHandlerTuple[0];eventName=keyHandlerTuple[1];boundKeyHandler=keyHandlerTuple[ 2];keyEventTarget.removeEventListener(eventName,boundKeyHandler)}},_onKeyBinding Event:function(keyBindings,event){if(this.stopKeyboardEventPropagation){event.st opPropagation()}if(event.defaultPrevented){return}for(var i=0;i<keyBindings.leng th;i++){var keyCombo=keyBindings[i][0];var handlerName=keyBindings[i][1];if(keyC omboMatchesEvent(keyCombo,event)){this._triggerKeyHandler(keyCombo,handlerName,e vent);if(event.defaultPrevented){return}}}},_triggerKeyHandler:function(keyCombo ,handlerName,keyboardEvent){var detail=Object.create(keyCombo);detail.keyboardEv ent=keyboardEvent;var event=new CustomEvent(keyCombo.event,{detail:detail,cancel able:true});this[handlerName].call(this,event);if(event.defaultPrevented){keyboa rdEvent.preventDefault()}}}})();Polymer.IronScrollTargetBehavior={properties:{sc rollTarget:{type:HTMLElement,value:function(){return this._defaultScrollTarget}} },observers:["_scrollTargetChanged(scrollTarget, isAttached)"],_shouldHaveListen er:true,_scrollTargetChanged:function(scrollTarget,isAttached){var eventTarget;i f(this._oldScrollTarget){this._toggleScrollListener(false,this._oldScrollTarget) ;this._oldScrollTarget=null}if(!isAttached){return}if(scrollTarget==="document") {this.scrollTarget=this._doc}else if(typeof scrollTarget==="string"){this.scroll Target=this.domHost?this.domHost.$[scrollTarget]:Polymer.dom(this.ownerDocument) .querySelector("#"+scrollTarget)}else if(this._isValidScrollTarget()){this._boun dScrollHandler=this._boundScrollHandler||this._scrollHandler.bind(this);this._ol dScrollTarget=scrollTarget;this._toggleScrollListener(this._shouldHaveListener,s crollTarget)}},_scrollHandler:function scrollHandler(){},get _defaultScrollTarge t(){return this._doc},get _doc(){return this.ownerDocument.documentElement},get _scrollTop(){if(this._isValidScrollTarget()){return this.scrollTarget===this._do c?window.pageYOffset:this.scrollTarget.scrollTop}return 0},get _scrollLeft(){if( this._isValidScrollTarget()){return this.scrollTarget===this._doc?window.pageXOf fset:this.scrollTarget.scrollLeft}return 0},set _scrollTop(top){if(this.scrollTa rget===this._doc){window.scrollTo(window.pageXOffset,top)}else if(this._isValidS crollTarget()){this.scrollTarget.scrollTop=top}},set _scrollLeft(left){if(this.s crollTarget===this._doc){window.scrollTo(left,window.pageYOffset)}else if(this._ isValidScrollTarget()){this.scrollTarget.scrollLeft=left}},scroll:function(left, top){if(this.scrollTarget===this._doc){window.scrollTo(left,top)}else if(this._i sValidScrollTarget()){this.scrollTarget.scrollLeft=left;this.scrollTarget.scroll Top=top}},get _scrollTargetWidth(){if(this._isValidScrollTarget()){return this.s crollTarget===this._doc?window.innerWidth:this.scrollTarget.offsetWidth}return 0 },get _scrollTargetHeight(){if(this._isValidScrollTarget()){return this.scrollTa rget===this._doc?window.innerHeight:this.scrollTarget.offsetHeight}return 0},_is ValidScrollTarget:function(){return this.scrollTarget instanceof HTMLElement},_t oggleScrollListener:function(yes,scrollTarget){if(!this._boundScrollHandler){ret urn}var eventTarget=scrollTarget===this._doc?window:scrollTarget;if(yes){eventTa rget.addEventListener("scroll",this._boundScrollHandler)}else{eventTarget.remove EventListener("scroll",this._boundScrollHandler)}},toggleScrollListener:function (yes){this._shouldHaveListener=yes;this._toggleScrollListener(yes,this.scrollTar get)}};(function(){var IOS=navigator.userAgent.match(/iP(?:hone|ad;(?: U;)? CPU) OS (\d+)/);var IOS_TOUCH_SCROLLING=IOS&&IOS[1]>=8;var DEFAULT_PHYSICAL_COUNT=3; var HIDDEN_Y="-10000px";var ITEM_WIDTH=0;var ITEM_HEIGHT=1;var SECRET_TABINDEX=- 100;Polymer({is:"iron-list",properties:{items:{type:Array},maxPhysicalCount:{typ e:Number,value:500},as:{type:String,value:"item"},indexAs:{type:String,value:"in dex"},selectedAs:{type:String,value:"selected"},grid:{type:Boolean,value:false,r eflectToAttribute:true},selectionEnabled:{type:Boolean,value:false},selectedItem :{type:Object,notify:true},selectedItems:{type:Object,notify:true},multiSelectio n:{type:Boolean,value:false}},observers:["_itemsChanged(items.*)","_selectionEna bledChanged(selectionEnabled)","_multiSelectionChanged(multiSelection)","_setOve rflow(scrollTarget)"],behaviors:[Polymer.Templatizer,Polymer.IronResizableBehavi or,Polymer.IronA11yKeysBehavior,Polymer.IronScrollTargetBehavior],keyBindings:{u p:"_didMoveUp",down:"_didMoveDown",enter:"_didEnter"},_ratio:.5,_scrollerPadding Top:0,_scrollPosition:0,_physicalSize:0,_physicalAverage:0,_physicalAverageCount :0,_physicalTop:0,_virtualCount:0,_physicalIndexForKey:null,_estScrollHeight:0,_ scrollHeight:0,_viewportHeight:0,_viewportWidth:0,_physicalItems:null,_physicalS izes:null,_firstVisibleIndexVal:null,_lastVisibleIndexVal:null,_collection:null, _maxPages:2,_focusedItem:null,_focusedIndex:-1,_offscreenFocusedItem:null,_focus BackfillItem:null,_itemsPerRow:1,_itemWidth:0,_rowHeight:0,_templateCost:0,get _ physicalBottom(){return this._physicalTop+this._physicalSize},get _scrollBottom( ){return this._scrollPosition+this._viewportHeight},get _virtualEnd(){return thi s._virtualStart+this._physicalCount-1},get _hiddenContentSize(){var size=this.gr id?this._physicalRows*this._rowHeight:this._physicalSize;return size-this._viewp ortHeight},get _maxScrollTop(){return this._estScrollHeight-this._viewportHeight +this._scrollerPaddingTop},_minVirtualStart:0,get _maxVirtualStart(){return Math .max(0,this._virtualCount-this._physicalCount)},_virtualStartVal:0,set _virtualS tart(val){this._virtualStartVal=Math.min(this._maxVirtualStart,Math.max(this._mi nVirtualStart,val))},get _virtualStart(){return this._virtualStartVal||0},_physi calStartVal:0,set _physicalStart(val){this._physicalStartVal=val%this._physicalC ount;if(this._physicalStartVal<0){this._physicalStartVal=this._physicalCount+thi s._physicalStartVal}this._physicalEnd=(this._physicalStart+this._physicalCount-1 )%this._physicalCount},get _physicalStart(){return this._physicalStartVal||0},_p hysicalCountVal:0,set _physicalCount(val){this._physicalCountVal=val;this._physi calEnd=(this._physicalStart+this._physicalCount-1)%this._physicalCount},get _phy sicalCount(){return this._physicalCountVal},_physicalEnd:0,get _optPhysicalSize( ){if(this.grid){return this._estRowsInView*this._rowHeight*this._maxPages}return this._viewportHeight*this._maxPages},get _isVisible(){return Boolean(this.offse tWidth||this.offsetHeight)},get firstVisibleIndex(){if(this._firstVisibleIndexVa l===null){var physicalOffset=Math.floor(this._physicalTop+this._scrollerPaddingT op);this._firstVisibleIndexVal=this._iterateItems(function(pidx,vidx){physicalOf fset+=this._getPhysicalSizeIncrement(pidx);if(physicalOffset>this._scrollPositio n){return this.grid?vidx-vidx%this._itemsPerRow:vidx}if(this.grid&&this._virtual Count-1===vidx){return vidx-vidx%this._itemsPerRow}})||0}return this._firstVisib leIndexVal},get lastVisibleIndex(){if(this._lastVisibleIndexVal===null){if(this. grid){var lastIndex=this.firstVisibleIndex+this._estRowsInView*this._itemsPerRow -1;this._lastVisibleIndexVal=Math.min(this._virtualCount,lastIndex)}else{var phy sicalOffset=this._physicalTop;this._iterateItems(function(pidx,vidx){if(physical Offset<this._scrollBottom){this._lastVisibleIndexVal=vidx}else{return true}physi calOffset+=this._getPhysicalSizeIncrement(pidx)})}}return this._lastVisibleIndex Val},get _defaultScrollTarget(){return this},get _virtualRowCount(){return Math. ceil(this._virtualCount/this._itemsPerRow)},get _estRowsInView(){return Math.cei l(this._viewportHeight/this._rowHeight)},get _physicalRows(){return Math.ceil(th is._physicalCount/this._itemsPerRow)},ready:function(){this.addEventListener("fo cus",this._didFocus.bind(this),true)},attached:function(){if(this._physicalCount ===0){this._debounceTemplate(this._render)}this.listen(this,"iron-resize","_resi zeHandler")},detached:function(){this.unlisten(this,"iron-resize","_resizeHandle r")},_setOverflow:function(scrollTarget){this.style.webkitOverflowScrolling=scro llTarget===this?"touch":"";this.style.overflow=scrollTarget===this?"auto":""},up dateViewportBoundaries:function(){this._scrollerPaddingTop=this.scrollTarget===t his?0:parseInt(window.getComputedStyle(this)["padding-top"],10);this._viewportWi dth=this.$.items.offsetWidth;this._viewportHeight=this._scrollTargetHeight;this. grid&&this._updateGridMetrics()},_scrollHandler:function(){var scrollTop=Math.ma x(0,Math.min(this._maxScrollTop,this._scrollTop));var delta=scrollTop-this._scro llPosition;var isScrollingDown=delta>=0;this._scrollPosition=scrollTop;this._fir stVisibleIndexVal=null;this._lastVisibleIndexVal=null;if(Math.abs(delta)>this._p hysicalSize){var idxAdjustment=Math.round(delta/this._physicalAverage)*this._ite msPerRow;this._physicalTop=this._physicalTop+delta;this._virtualStart=this._virt ualStart+idxAdjustment;this._physicalStart=this._physicalStart+idxAdjustment;thi s._update()}else{var reusables=this._getReusables(isScrollingDown);if(isScrollin gDown){this._physicalTop=reusables.physicalTop;this._virtualStart=this._virtualS tart+reusables.indexes.length;this._physicalStart=this._physicalStart+reusables. indexes.length}else{this._virtualStart=this._virtualStart-reusables.indexes.leng th;this._physicalStart=this._physicalStart-reusables.indexes.length}if(reusables .indexes.length===0){this._increasePoolIfNeeded()}else{this._update(reusables.in dexes,isScrollingDown?null:reusables.indexes)}}},_getReusables:function(fromTop) {var ith,lastIth,offsetContent,physicalItemHeight;var idxs=[];var protectedOffse tContent=this._hiddenContentSize*this._ratio;var virtualStart=this._virtualStart ;var virtualEnd=this._virtualEnd;var physicalCount=this._physicalCount;var physi calTop=this._physicalTop+this._scrollerPaddingTop;var scrollTop=this._scrollTop; var scrollBottom=this._scrollBottom;if(fromTop){ith=this._physicalStart;lastIth= this._physicalEnd;offsetContent=scrollTop-physicalTop}else{ith=this._physicalEnd ;lastIth=this._physicalStart;offsetContent=this._physicalBottom-scrollBottom}whi le(true){physicalItemHeight=this._getPhysicalSizeIncrement(ith);offsetContent=of fsetContent-physicalItemHeight;if(idxs.length>=physicalCount||offsetContent<=pro tectedOffsetContent){break}if(fromTop){if(virtualEnd+idxs.length+1>=this._virtua lCount){break}if(physicalTop+physicalItemHeight>=scrollTop){break}idxs.push(ith) ;physicalTop=physicalTop+physicalItemHeight;ith=(ith+1)%physicalCount}else{if(vi rtualStart-idxs.length<=0){break}if(physicalTop+this._physicalSize-physicalItemH eight<=scrollBottom){break}idxs.push(ith);physicalTop=physicalTop-physicalItemHe ight;ith=ith===0?physicalCount-1:ith-1}}return{indexes:idxs,physicalTop:physical Top-this._scrollerPaddingTop}},_update:function(itemSet,movingUp){if(itemSet&&it emSet.length===0){return}this._manageFocus();this._assignModels(itemSet);this._u pdateMetrics(itemSet);if(movingUp){while(movingUp.length){var idx=movingUp.pop() ;this._physicalTop-=this._getPhysicalSizeIncrement(idx)}}this._positionItems();t his._updateScrollerSize();this._increasePoolIfNeeded()},_createPool:function(siz e){var physicalItems=new Array(size);this._ensureTemplatized();for(var i=0;i<siz e;i++){var inst=this.stamp(null);physicalItems[i]=inst.root.querySelector("*");P olymer.dom(this).appendChild(inst.root)}return physicalItems},_increasePoolIfNee ded:function(){if(this._viewportHeight===0){return false}var self=this;var isCli entFull=this._physicalBottom>=this._scrollBottom&&this._physicalTop<=this._scrol lPosition;if(this._physicalSize>=this._optPhysicalSize&&isClientFull){return fal se}var maxPoolSize=Math.round(this._physicalCount*.5);if(!isClientFull){this._de bounceTemplate(this._increasePool.bind(this,maxPoolSize));return true}this._yiel d(function(){self._increasePool(Math.min(maxPoolSize,Math.max(1,Math.round(50/se lf._templateCost))))});return true},_yield:function(cb){var g=window;var handle= g.requestIdleCallback?g.requestIdleCallback(cb):g.setTimeout(cb,16);Polymer.dom. addDebouncer({complete:function(){g.cancelIdleCallback?g.cancelIdleCallback(hand le):g.clearTimeout(handle);cb()}})},_increasePool:function(missingItems){var nex tPhysicalCount=Math.min(this._physicalCount+missingItems,this._virtualCount-this ._virtualStart,Math.max(this.maxPhysicalCount,DEFAULT_PHYSICAL_COUNT));var prevP hysicalCount=this._physicalCount;var delta=nextPhysicalCount-prevPhysicalCount;v ar ts=window.performance.now();if(delta<=0){return}[].push.apply(this._physicalI tems,this._createPool(delta));[].push.apply(this._physicalSizes,new Array(delta) );this._physicalCount=prevPhysicalCount+delta;if(this._physicalStart>this._physi calEnd&&this._isIndexRendered(this._focusedIndex)&&this._getPhysicalIndex(this._ focusedIndex)<this._physicalEnd){this._physicalStart=this._physicalStart+delta}t his._update();this._templateCost=(window.performance.now()-ts)/delta},_render:fu nction(){if(this.isAttached&&this._isVisible){if(this._physicalCount===0){this.u pdateViewportBoundaries();this._increasePool(DEFAULT_PHYSICAL_COUNT)}else{var re usables=this._getReusables(true);this._physicalTop=reusables.physicalTop;this._v irtualStart=this._virtualStart+reusables.indexes.length;this._physicalStart=this ._physicalStart+reusables.indexes.length;this._update(reusables.indexes);this._u pdate()}}},_ensureTemplatized:function(){if(!this.ctor){var props={};props.__key __=true;props[this.as]=true;props[this.indexAs]=true;props[this.selectedAs]=true ;props.tabIndex=true;this._instanceProps=props;this._userTemplate=Polymer.dom(th is).querySelector("template");if(this._userTemplate){this.templatize(this._userT emplate)}else{console.warn("iron-list requires a template to be provided in ligh t-dom")}}},_getStampedChildren:function(){return this._physicalItems},_forwardIn stancePath:function(inst,path,value){if(path.indexOf(this.as+".")===0){this.noti fyPath("items."+inst.__key__+"."+path.slice(this.as.length+1),value)}},_forwardP arentProp:function(prop,value){if(this._physicalItems){this._physicalItems.forEa ch(function(item){item._templateInstance[prop]=value},this)}},_forwardParentPath :function(path,value){if(this._physicalItems){this._physicalItems.forEach(functi on(item){item._templateInstance.notifyPath(path,value,true)},this)}},_forwardIte mPath:function(path,value){if(!this._physicalIndexForKey){return}var dot=path.in dexOf(".");var key=path.substring(0,dot<0?path.length:dot);var idx=this._physica lIndexForKey[key];var offscreenItem=this._offscreenFocusedItem;var el=offscreenI tem&&offscreenItem._templateInstance.__key__===key?offscreenItem:this._physicalI tems[idx];if(!el||el._templateInstance.__key__!==key){return}if(dot>=0){path=thi s.as+"."+path.substring(dot+1);el._templateInstance.notifyPath(path,value,true)} else{var currentItem=el._templateInstance[this.as];if(Array.isArray(this.selecte dItems)){for(var i=0;i<this.selectedItems.length;i++){if(this.selectedItems[i]== =currentItem){this.set("selectedItems."+i,value);break}}}else if(this.selectedIt em===currentItem){this.set("selectedItem",value)}el._templateInstance[this.as]=v alue}},_itemsChanged:function(change){if(change.path==="items"){this._virtualSta rt=0;this._physicalTop=0;this._virtualCount=this.items?this.items.length:0;this. _collection=this.items?Polymer.Collection.get(this.items):null;this._physicalInd exForKey={};this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null;this. _physicalCount=this._physicalCount||0;this._physicalItems=this._physicalItems||[ ];this._physicalSizes=this._physicalSizes||[];this._physicalStart=0;this._resetS crollPosition(0);this._removeFocusedItem();this._debounceTemplate(this._render)} else if(change.path==="items.splices"){this._adjustVirtualIndex(change.value.ind exSplices);this._virtualCount=this.items?this.items.length:0;this._debounceTempl ate(this._render)}else{this._forwardItemPath(change.path.split(".").slice(1).joi n("."),change.value)}},_adjustVirtualIndex:function(splices){splices.forEach(fun ction(splice){splice.removed.forEach(this._removeItem,this);if(splice.index<this ._virtualStart){var delta=Math.max(splice.addedCount-splice.removed.length,splic e.index-this._virtualStart);this._virtualStart=this._virtualStart+delta;if(this. _focusedIndex>=0){this._focusedIndex=this._focusedIndex+delta}}},this)},_removeI tem:function(item){this.$.selector.deselect(item);if(this._focusedItem&&this._fo cusedItem._templateInstance[this.as]===item){this._removeFocusedItem()}},_iterat eItems: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( (rtn=fn.call(this,pidx,vidx))!=null){return rtn}}}else{pidx=this._physicalStart; vidx=this._virtualStart;for(;pidx<this._physicalCount;pidx++,vidx++){if((rtn=fn. call(this,pidx,vidx))!=null){return rtn}}for(pidx=0;pidx<this._physicalStart;pid x++,vidx++){if((rtn=fn.call(this,pidx,vidx))!=null){return rtn}}}},_computeVidx: function(pidx){if(pidx>=this._physicalStart){return this._virtualStart+(pidx-thi s._physicalStart)}return this._virtualStart+(this._physicalCount-this._physicalS tart)+pidx},_assignModels:function(itemSet){this._iterateItems(function(pidx,vid x){var el=this._physicalItems[pidx];var inst=el._templateInstance;var item=this. items&&this.items[vidx];if(item!=null){inst[this.as]=item;inst.__key__=this._col lection.getKey(item);inst[this.selectedAs]=this.$.selector.isSelected(item);inst [this.indexAs]=vidx;inst.tabIndex=this._focusedIndex===vidx?0:-1;this._physicalI ndexForKey[inst.__key__]=pidx;el.removeAttribute("hidden")}else{inst.__key__=nul l;el.setAttribute("hidden","")}},itemSet)},_updateMetrics:function(itemSet){Poly mer.dom.flush();var newPhysicalSize=0;var oldPhysicalSize=0;var prevAvgCount=thi s._physicalAverageCount;var prevPhysicalAvg=this._physicalAverage;this._iterateI tems(function(pidx,vidx){oldPhysicalSize+=this._physicalSizes[pidx]||0;this._phy sicalSizes[pidx]=this._physicalItems[pidx].offsetHeight;newPhysicalSize+=this._p hysicalSizes[pidx];this._physicalAverageCount+=this._physicalSizes[pidx]?1:0},it emSet);if(this.grid){this._updateGridMetrics();this._physicalSize=Math.ceil(this ._physicalCount/this._itemsPerRow)*this._rowHeight}else{this._physicalSize=this. _physicalSize+newPhysicalSize-oldPhysicalSize}if(this._physicalAverageCount!==pr evAvgCount){this._physicalAverage=Math.round((prevPhysicalAvg*prevAvgCount+newPh ysicalSize)/this._physicalAverageCount)}},_updateGridMetrics:function(){this._it emWidth=this._physicalCount>0?this._physicalItems[0].getBoundingClientRect().wid th:200;this._rowHeight=this._physicalCount>0?this._physicalItems[0].offsetHeight :200;this._itemsPerRow=this._itemWidth?Math.floor(this._viewportWidth/this._item Width):this._itemsPerRow},_positionItems:function(){this._adjustScrollPosition() ;var y=this._physicalTop;if(this.grid){var totalItemWidth=this._itemsPerRow*this ._itemWidth;var rowOffset=(this._viewportWidth-totalItemWidth)/2;this._iterateIt ems(function(pidx,vidx){var modulus=vidx%this._itemsPerRow;var x=Math.floor(modu lus*this._itemWidth+rowOffset);this.translate3d(x+"px",y+"px",0,this._physicalIt ems[pidx]);if(this._shouldRenderNextRow(vidx)){y+=this._rowHeight}})}else{this._ iterateItems(function(pidx,vidx){this.translate3d(0,y+"px",0,this._physicalItems [pidx]);y+=this._physicalSizes[pidx]})}},_getPhysicalSizeIncrement:function(pidx ){if(!this.grid){return this._physicalSizes[pidx]}if(this._computeVidx(pidx)%thi s._itemsPerRow!==this._itemsPerRow-1){return 0}return this._rowHeight},_shouldRe nderNextRow:function(vidx){return vidx%this._itemsPerRow===this._itemsPerRow-1}, _adjustScrollPosition:function(){var deltaHeight=this._virtualStart===0?this._ph ysicalTop:Math.min(this._scrollPosition+this._physicalTop,0);if(deltaHeight){thi s._physicalTop=this._physicalTop-deltaHeight;if(!IOS_TOUCH_SCROLLING&&this._phys icalTop!==0){this._resetScrollPosition(this._scrollTop-deltaHeight)}}},_resetScr ollPosition:function(pos){if(this.scrollTarget){this._scrollTop=pos;this._scroll Position=this._scrollTop}},_updateScrollerSize:function(forceUpdate){if(this.gri d){this._estScrollHeight=this._virtualRowCount*this._rowHeight}else{this._estScr ollHeight=this._physicalBottom+Math.max(this._virtualCount-this._physicalCount-t his._virtualStart,0)*this._physicalAverage}forceUpdate=forceUpdate||this._scroll Height===0;forceUpdate=forceUpdate||this._scrollPosition>=this._estScrollHeight- this._physicalSize;forceUpdate=forceUpdate||this.grid&&this.$.items.style.height <this._estScrollHeight;if(forceUpdate||Math.abs(this._estScrollHeight-this._scro llHeight)>=this._optPhysicalSize){this.$.items.style.height=this._estScrollHeigh t+"px";this._scrollHeight=this._estScrollHeight}},scrollToItem:function(item){re turn this.scrollToIndex(this.items.indexOf(item))},scrollToIndex:function(idx){i f(typeof idx!=="number"||idx<0||idx>this.items.length-1){return}Polymer.dom.flus h();if(this._physicalCount===0){return}idx=Math.min(Math.max(idx,0),this._virtua lCount-1);if(!this._isIndexRendered(idx)||idx>=this._maxVirtualStart){this._virt ualStart=this.grid?idx-this._itemsPerRow*2:idx-1}this._manageFocus();this._assig nModels();this._updateMetrics();this._physicalTop=Math.floor(this._virtualStart/ this._itemsPerRow)*this._physicalAverage;var currentTopItem=this._physicalStart; var currentVirtualItem=this._virtualStart;var targetOffsetTop=0;var hiddenConten tSize=this._hiddenContentSize;while(currentVirtualItem<idx&&targetOffsetTop<=hid denContentSize){targetOffsetTop=targetOffsetTop+this._getPhysicalSizeIncrement(c urrentTopItem);currentTopItem=(currentTopItem+1)%this._physicalCount;currentVirt ualItem++}this._updateScrollerSize(true);this._positionItems();this._resetScroll Position(this._physicalTop+this._scrollerPaddingTop+targetOffsetTop);this._incre asePoolIfNeeded();this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null },_resetAverage:function(){this._physicalAverage=0;this._physicalAverageCount=0} ,_resizeHandler:function(){var delta=Math.abs(this._viewportHeight-this._scrollT argetHeight);if(IOS&&delta>0&&delta<100){return}Polymer.dom.addDebouncer(this.de bounce("_debounceTemplate",function(){this.updateViewportBoundaries();this._rend er();if(this._isVisible){this.toggleScrollListener(true);if(this._physicalCount> 0){this._resetAverage();this.scrollToIndex(this.firstVisibleIndex)}}else{this.to ggleScrollListener(false)}}.bind(this),1))},_getModelFromItem:function(item){var key=this._collection.getKey(item);var pidx=this._physicalIndexForKey[key];if(pi dx!=null){return this._physicalItems[pidx]._templateInstance}return null},_getNo rmalizedItem:function(item){if(this._collection.getKey(item)===undefined){if(typ eof 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")}r eturn item},selectItem:function(item){item=this._getNormalizedItem(item);var mod el=this._getModelFromItem(item);if(!this.multiSelection&&this.selectedItem){this .deselectItem(this.selectedItem)}if(model){model[this.selectedAs]=true}this.$.se lector.select(item);this.updateSizeForItem(item)},deselectItem:function(item){it em=this._getNormalizedItem(item);var model=this._getModelFromItem(item);if(model ){model[this.selectedAs]=false}this.$.selector.deselect(item);this.updateSizeFor Item(item)},toggleSelectionForItem:function(item){item=this._getNormalizedItem(i tem);if(this.$.selector.isSelected(item)){this.deselectItem(item)}else{this.sele ctItem(item)}},clearSelection:function(){function unselect(item){var model=this. _getModelFromItem(item);if(model){model[this.selectedAs]=false}}if(Array.isArray (this.selectedItems)){this.selectedItems.forEach(unselect,this)}else if(this.sel ectedItem){unselect.call(this,this.selectedItem)}this.$.selector.clearSelection( )},_selectionEnabledChanged:function(selectionEnabled){var handler=selectionEnab led?this.listen:this.unlisten;handler.call(this,this,"tap","_selectionHandler")} ,_selectionHandler:function(e){var model=this.modelForElement(e.target);if(!mode l){return}var modelTabIndex,activeElTabIndex;var target=Polymer.dom(e).path[0];v ar activeEl=Polymer.dom(this.domHost?this.domHost.root:document).activeElement;
29 29
30 if(target.localName==="input"||target.localName==="button"||target.localName===" select"){return}modelTabIndex=model.tabIndex;model.tabIndex=SECRET_TABINDEX;acti veElTabIndex=activeEl?activeEl.tabIndex:-1;model.tabIndex=modelTabIndex;if(activ eEl&&physicalItem!==activeEl&&physicalItem.contains(activeEl)&&activeElTabIndex! ==SECRET_TABINDEX){return}this.toggleSelectionForItem(model[this.as])},_multiSel ectionChanged:function(multiSelection){this.clearSelection();this.$.selector.mul ti=multiSelection},updateSizeForItem:function(item){item=this._getNormalizedItem (item);var key=this._collection.getKey(item);var pidx=this._physicalIndexForKey[ key];if(pidx!=null){this._updateMetrics([pidx]);this._positionItems()}},_manageF ocus:function(){var fidx=this._focusedIndex;if(fidx>=0&&fidx<this._virtualCount) {if(this._isIndexRendered(fidx)){this._restoreFocusedItem()}else{this._createFoc usBackfillItem()}}else if(this._virtualCount>0&&this._physicalCount>0){this._foc usedIndex=this._virtualStart;this._focusedItem=this._physicalItems[this._physica lStart]}},_isIndexRendered:function(idx){return idx>=this._virtualStart&&idx<=th is._virtualEnd},_isIndexVisible:function(idx){return idx>=this.firstVisibleIndex &&idx<=this.lastVisibleIndex},_getPhysicalIndex:function(idx){return this._physi calIndexForKey[this._collection.getKey(this._getNormalizedItem(idx))]},_focusPhy sicalItem:function(idx){if(idx<0||idx>=this._virtualCount){return}this._restoreF ocusedItem();if(!this._isIndexRendered(idx)){this.scrollToIndex(idx)}var physica lItem=this._physicalItems[this._getPhysicalIndex(idx)];var model=physicalItem._t emplateInstance;var focusable;model.tabIndex=SECRET_TABINDEX;if(physicalItem.tab Index===SECRET_TABINDEX){focusable=physicalItem}if(!focusable){focusable=Polymer .dom(physicalItem).querySelector('[tabindex="'+SECRET_TABINDEX+'"]')}model.tabIn dex=0;this._focusedIndex=idx;focusable&&focusable.focus()},_removeFocusedItem:fu nction(){if(this._offscreenFocusedItem){Polymer.dom(this).removeChild(this._offs creenFocusedItem)}this._offscreenFocusedItem=null;this._focusBackfillItem=null;t his._focusedItem=null;this._focusedIndex=-1},_createFocusBackfillItem:function() {var fidx=this._focusedIndex;var pidx=this._getPhysicalIndex(fidx);if(this._offs creenFocusedItem||pidx==null||fidx<0){return}if(!this._focusBackfillItem){var st ampedTemplate=this.stamp(null);this._focusBackfillItem=stampedTemplate.root.quer ySelector("*");Polymer.dom(this).appendChild(stampedTemplate.root)}this._offscre enFocusedItem=this._physicalItems[pidx];this._offscreenFocusedItem._templateInst ance.tabIndex=0;this._physicalItems[pidx]=this._focusBackfillItem;this.translate 3d(0,HIDDEN_Y,0,this._offscreenFocusedItem)},_restoreFocusedItem:function(){var pidx,fidx=this._focusedIndex;if(!this._offscreenFocusedItem||this._focusedIndex< 0){return}this._assignModels();pidx=this._getPhysicalIndex(fidx);if(pidx!=null){ this._focusBackfillItem=this._physicalItems[pidx];this._focusBackfillItem._templ ateInstance.tabIndex=-1;this._physicalItems[pidx]=this._offscreenFocusedItem;thi s._offscreenFocusedItem=null;this.translate3d(0,HIDDEN_Y,0,this._focusBackfillIt em)}},_didFocus:function(e){var targetModel=this.modelForElement(e.target);var f ocusedModel=this._focusedItem?this._focusedItem._templateInstance:null;var hasOf fscreenFocusedItem=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]; this._focusedIndex=fidx;this._focusedItem=this._physicalItems[this._getPhysicalI ndex(fidx)];if(hasOffscreenFocusedItem&&!this._offscreenFocusedItem){this._updat e()}}},_didMoveUp:function(){this._focusPhysicalItem(this._focusedIndex-1)},_did MoveDown:function(e){e.detail.keyboardEvent.preventDefault();this._focusPhysical Item(this._focusedIndex+1)},_didEnter:function(e){this._focusPhysicalItem(this._ focusedIndex);this._selectionHandler(e.detail.keyboardEvent)}})})(); 30 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;ac tiveElTabIndex=activeEl?activeEl.tabIndex:-1;model.tabIndex=modelTabIndex;if(act iveEl&&physicalItem!==activeEl&&physicalItem.contains(activeEl)&&activeElTabInde x!==SECRET_TABINDEX){return}this.toggleSelectionForItem(model[this.as])},_multiS electionChanged:function(multiSelection){this.clearSelection();this.$.selector.m ulti=multiSelection},updateSizeForItem:function(item){item=this._getNormalizedIt em(item);var key=this._collection.getKey(item);var pidx=this._physicalIndexForKe y[key];if(pidx!=null){this._updateMetrics([pidx]);this._positionItems()}},_manag eFocus:function(){var fidx=this._focusedIndex;if(fidx>=0&&fidx<this._virtualCoun t){if(this._isIndexRendered(fidx)){this._restoreFocusedItem()}else{this._createF ocusBackfillItem()}}else if(this._virtualCount>0&&this._physicalCount>0){this._f ocusedIndex=this._virtualStart;this._focusedItem=this._physicalItems[this._physi calStart]}},_isIndexRendered:function(idx){return idx>=this._virtualStart&&idx<= this._virtualEnd},_isIndexVisible:function(idx){return idx>=this.firstVisibleInd ex&&idx<=this.lastVisibleIndex},_getPhysicalIndex:function(idx){return this._phy sicalIndexForKey[this._collection.getKey(this._getNormalizedItem(idx))]},_focusP hysicalItem:function(idx){if(idx<0||idx>=this._virtualCount){return}this._restor eFocusedItem();if(!this._isIndexRendered(idx)){this.scrollToIndex(idx)}var physi calItem=this._physicalItems[this._getPhysicalIndex(idx)];var model=physicalItem. _templateInstance;var focusable;model.tabIndex=SECRET_TABINDEX;if(physicalItem.t abIndex===SECRET_TABINDEX){focusable=physicalItem}if(!focusable){focusable=Polym er.dom(physicalItem).querySelector('[tabindex="'+SECRET_TABINDEX+'"]')}model.tab Index=0;this._focusedIndex=idx;focusable&&focusable.focus()},_removeFocusedItem: function(){if(this._offscreenFocusedItem){Polymer.dom(this).removeChild(this._of fscreenFocusedItem)}this._offscreenFocusedItem=null;this._focusBackfillItem=null ;this._focusedItem=null;this._focusedIndex=-1},_createFocusBackfillItem:function (){var fidx=this._focusedIndex;var pidx=this._getPhysicalIndex(fidx);if(this._of fscreenFocusedItem||pidx==null||fidx<0){return}if(!this._focusBackfillItem){var stampedTemplate=this.stamp(null);this._focusBackfillItem=stampedTemplate.root.qu erySelector("*");Polymer.dom(this).appendChild(stampedTemplate.root)}this._offsc reenFocusedItem=this._physicalItems[pidx];this._offscreenFocusedItem._templateIn stance.tabIndex=0;this._physicalItems[pidx]=this._focusBackfillItem;this.transla te3d(0,HIDDEN_Y,0,this._offscreenFocusedItem)},_restoreFocusedItem:function(){va r pidx,fidx=this._focusedIndex;if(!this._offscreenFocusedItem||this._focusedInde x<0){return}this._assignModels();pidx=this._getPhysicalIndex(fidx);if(pidx!=null ){this._focusBackfillItem=this._physicalItems[pidx];this._focusBackfillItem._tem plateInstance.tabIndex=-1;this._physicalItems[pidx]=this._offscreenFocusedItem;t his._offscreenFocusedItem=null;this.translate3d(0,HIDDEN_Y,0,this._focusBackfill Item)}},_didFocus:function(e){var targetModel=this.modelForElement(e.target);var focusedModel=this._focusedItem?this._focusedItem._templateInstance:null;var has OffscreenFocusedItem=this._offscreenFocusedItem!==null;var fidx=this._focusedInd ex;if(!targetModel||!focusedModel){return}if(focusedModel===targetModel){if(!thi s._isIndexVisible(fidx)){this.scrollToIndex(fidx)}}else{this._restoreFocusedItem ();focusedModel.tabIndex=-1;targetModel.tabIndex=0;fidx=targetModel[this.indexAs ];this._focusedIndex=fidx;this._focusedItem=this._physicalItems[this._getPhysica lIndex(fidx)];if(hasOffscreenFocusedItem&&!this._offscreenFocusedItem){this._upd ate()}}},_didMoveUp:function(){this._focusPhysicalItem(this._focusedIndex-1)},_d idMoveDown:function(e){e.detail.keyboardEvent.preventDefault();this._focusPhysic alItem(this._focusedIndex+1)},_didEnter:function(e){this._focusPhysicalItem(this ._focusedIndex);this._selectionHandler(e.detail.keyboardEvent)}})})();
31 // Copyright 2015 The Chromium Authors. All rights reserved. 31 // Copyright 2015 The Chromium Authors. All rights reserved.
32 // Use of this source code is governed by a BSD-style license that can be 32 // Use of this source code is governed by a BSD-style license that can be
33 // found in the LICENSE file. 33 // found in the LICENSE file.
34 cr.define("downloads",function(){function chromeSendWithId(chromeSendName){retur n function(id){chrome.send(chromeSendName,[id])}}function ActionService(){this.s earchTerms_=[]}function trim(s){return s.trim()}function truthy(value){return!!v alue}ActionService.splitTerms=function(searchText){return searchText.split(/"([^ "]*)"/).map(trim).filter(truthy)};ActionService.prototype={cancel:chromeSendWith Id("cancel"),clearAll:function(){if(loadTimeData.getBoolean("allowDeletingHistor y")){chrome.send("clearAll");this.search("")}},discardDangerous:chromeSendWithId ("discardDangerous"),download:function(url){var a=document.createElement("a");a. href=url;a.setAttribute("download","");a.click()},drag:chromeSendWithId("drag"), loadMore:function(){chrome.send("getDownloads",this.searchTerms_)},isSearching:f unction(){return this.searchTerms_.length>0},openDownloadsFolder:function(){chro me.send("openDownloadsFolderRequiringGesture")},openFile:chromeSendWithId("openF ileRequiringGesture"),pause:chromeSendWithId("pause"),remove:chromeSendWithId("r emove"),resume:chromeSendWithId("resume"),saveDangerous:chromeSendWithId("saveDa ngerousRequiringGesture"),search:function(searchText){var searchTerms=ActionServ ice.splitTerms(searchText);var sameTerms=searchTerms.length==this.searchTerms_.l ength;for(var i=0;sameTerms&&i<searchTerms.length;++i){if(searchTerms[i]!=this.s earchTerms_[i])sameTerms=false}if(sameTerms)return false;this.searchTerms_=searc hTerms;this.loadMore();return true},show:chromeSendWithId("show"),undo:chrome.se nd.bind(chrome,"undo")};cr.addSingletonGetter(ActionService);return{ActionServic e:ActionService}}); 34 cr.define("downloads",function(){function chromeSendWithId(chromeSendName){retur n function(id){chrome.send(chromeSendName,[id])}}function ActionService(){this.s earchTerms_=[]}function trim(s){return s.trim()}function truthy(value){return!!v alue}ActionService.splitTerms=function(searchText){return searchText.split(/"([^ "]*)"/).map(trim).filter(truthy)};ActionService.prototype={cancel:chromeSendWith Id("cancel"),clearAll:function(){if(loadTimeData.getBoolean("allowDeletingHistor y")){chrome.send("clearAll");this.search("")}},discardDangerous:chromeSendWithId ("discardDangerous"),download:function(url){var a=document.createElement("a");a. href=url;a.setAttribute("download","");a.click()},drag:chromeSendWithId("drag"), loadMore:function(){chrome.send("getDownloads",this.searchTerms_)},isSearching:f unction(){return this.searchTerms_.length>0},openDownloadsFolder:function(){chro me.send("openDownloadsFolderRequiringGesture")},openFile:chromeSendWithId("openF ileRequiringGesture"),pause:chromeSendWithId("pause"),remove:chromeSendWithId("r emove"),resume:chromeSendWithId("resume"),saveDangerous:chromeSendWithId("saveDa ngerousRequiringGesture"),search:function(searchText){var searchTerms=ActionServ ice.splitTerms(searchText);var sameTerms=searchTerms.length==this.searchTerms_.l ength;for(var i=0;sameTerms&&i<searchTerms.length;++i){if(searchTerms[i]!=this.s earchTerms_[i])sameTerms=false}if(sameTerms)return false;this.searchTerms_=searc hTerms;this.loadMore();return true},show:chromeSendWithId("show"),undo:chrome.se nd.bind(chrome,"undo")};cr.addSingletonGetter(ActionService);return{ActionServic e:ActionService}});
35 // Copyright 2015 The Chromium Authors. All rights reserved. 35 // Copyright 2015 The Chromium Authors. All rights reserved.
36 // Use of this source code is governed by a BSD-style license that can be 36 // Use of this source code is governed by a BSD-style license that can be
37 // found in the LICENSE file. 37 // found in the LICENSE file.
38 cr.define("downloads",function(){var DangerType={NOT_DANGEROUS:"NOT_DANGEROUS",D ANGEROUS_FILE:"DANGEROUS_FILE",DANGEROUS_URL:"DANGEROUS_URL",DANGEROUS_CONTENT:" DANGEROUS_CONTENT",UNCOMMON_CONTENT:"UNCOMMON_CONTENT",DANGEROUS_HOST:"DANGEROUS _HOST",POTENTIALLY_UNWANTED:"POTENTIALLY_UNWANTED"};var States={IN_PROGRESS:"IN_ PROGRESS",CANCELLED:"CANCELLED",COMPLETE:"COMPLETE",PAUSED:"PAUSED",DANGEROUS:"D ANGEROUS",INTERRUPTED:"INTERRUPTED"};return{DangerType:DangerType,States:States} }); 38 cr.define("downloads",function(){var DangerType={NOT_DANGEROUS:"NOT_DANGEROUS",D ANGEROUS_FILE:"DANGEROUS_FILE",DANGEROUS_URL:"DANGEROUS_URL",DANGEROUS_CONTENT:" DANGEROUS_CONTENT",UNCOMMON_CONTENT:"UNCOMMON_CONTENT",DANGEROUS_HOST:"DANGEROUS _HOST",POTENTIALLY_UNWANTED:"POTENTIALLY_UNWANTED"};var States={IN_PROGRESS:"IN_ PROGRESS",CANCELLED:"CANCELLED",COMPLETE:"COMPLETE",PAUSED:"PAUSED",DANGEROUS:"D ANGEROUS",INTERRUPTED:"INTERRUPTED"};return{DangerType:DangerType,States:States} });
39 // Copyright 2014 The Chromium Authors. All rights reserved. 39 // Copyright 2014 The Chromium Authors. All rights reserved.
40 // Use of this source code is governed by a BSD-style license that can be 40 // Use of this source code is governed by a BSD-style license that can be
(...skipping 21 matching lines...) Expand all
62 // found in the LICENSE file. 62 // found in the LICENSE file.
63 cr.define("downloads",function(){var Toolbar=Polymer({is:"downloads-toolbar",pro perties:{downloadsShowing:{reflectToAttribute:true,type:Boolean,value:false,obse rver:"downloadsShowingChanged_"},spinnerActive:{type:Boolean,notify:true}},liste ners:{"paper-dropdown-close":"onPaperDropdownClose_","paper-dropdown-open":"onPa perDropdownOpen_"},canUndo:function(){return!this.$.toolbar.getSearchField().isS earchFocused()},canClearAll:function(){return!this.$.toolbar.getSearchField().ge tValue()&&this.downloadsShowing},onFindCommand:function(){this.$.toolbar.getSear chField().showAndFocus()},closeMoreActions_:function(){this.$.more.close()},down loadsShowingChanged_:function(){this.updateClearAll_()},onClearAllTap_:function( ){assert(this.canClearAll());downloads.ActionService.getInstance().clearAll()},o nPaperDropdownClose_:function(){window.removeEventListener("resize",assert(this. boundClose_))},onItemBlur_:function(e){var menu=this.$$("paper-menu");if(menu.it ems.indexOf(e.relatedTarget)>=0)return;this.$.more.restoreFocusOnClose=false;thi s.closeMoreActions_();this.$.more.restoreFocusOnClose=true},onPaperDropdownOpen_ :function(){this.boundClose_=this.boundClose_||this.closeMoreActions_.bind(this) ;window.addEventListener("resize",this.boundClose_)},onSearchChanged_:function(e vent){var actionService=downloads.ActionService.getInstance();if(actionService.s earch(event.detail))this.spinnerActive=actionService.isSearching();this.updateCl earAll_()},onOpenDownloadsFolderTap_:function(){downloads.ActionService.getInsta nce().openDownloadsFolder()},updateClearAll_:function(){this.$$("paper-menu .cle ar-all").hidden=!this.canClearAll()}});return{Toolbar:Toolbar}}); 63 cr.define("downloads",function(){var Toolbar=Polymer({is:"downloads-toolbar",pro perties:{downloadsShowing:{reflectToAttribute:true,type:Boolean,value:false,obse rver:"downloadsShowingChanged_"},spinnerActive:{type:Boolean,notify:true}},liste ners:{"paper-dropdown-close":"onPaperDropdownClose_","paper-dropdown-open":"onPa perDropdownOpen_"},canUndo:function(){return!this.$.toolbar.getSearchField().isS earchFocused()},canClearAll:function(){return!this.$.toolbar.getSearchField().ge tValue()&&this.downloadsShowing},onFindCommand:function(){this.$.toolbar.getSear chField().showAndFocus()},closeMoreActions_:function(){this.$.more.close()},down loadsShowingChanged_:function(){this.updateClearAll_()},onClearAllTap_:function( ){assert(this.canClearAll());downloads.ActionService.getInstance().clearAll()},o nPaperDropdownClose_:function(){window.removeEventListener("resize",assert(this. boundClose_))},onItemBlur_:function(e){var menu=this.$$("paper-menu");if(menu.it ems.indexOf(e.relatedTarget)>=0)return;this.$.more.restoreFocusOnClose=false;thi s.closeMoreActions_();this.$.more.restoreFocusOnClose=true},onPaperDropdownOpen_ :function(){this.boundClose_=this.boundClose_||this.closeMoreActions_.bind(this) ;window.addEventListener("resize",this.boundClose_)},onSearchChanged_:function(e vent){var actionService=downloads.ActionService.getInstance();if(actionService.s earch(event.detail))this.spinnerActive=actionService.isSearching();this.updateCl earAll_()},onOpenDownloadsFolderTap_:function(){downloads.ActionService.getInsta nce().openDownloadsFolder()},updateClearAll_:function(){this.$$("paper-menu .cle ar-all").hidden=!this.canClearAll()}});return{Toolbar:Toolbar}});
64 // Copyright 2015 The Chromium Authors. All rights reserved. 64 // Copyright 2015 The Chromium Authors. All rights reserved.
65 // Use of this source code is governed by a BSD-style license that can be 65 // Use of this source code is governed by a BSD-style license that can be
66 // found in the LICENSE file. 66 // found in the LICENSE file.
67 cr.define("downloads",function(){var Manager=Polymer({is:"downloads-manager",pro perties:{hasDownloads_:{observer:"hasDownloadsChanged_",type:Boolean},hasShadow_ :{type:Boolean,value:false,reflectToAttribute:true},inSearchMode_:{type:Boolean, value:false},items_:{type:Array,value:function(){return[]}},spinnerActive_:{type :Boolean,notify:true}},hostAttributes:{loading:true},listeners:{"downloads-list. scroll":"onListScroll_","toolbar.search-changed":"onSearchChanged_"},observers:[ "itemsChanged_(items_.*)"],clearAll_:function(){this.set("items_",[])},hasDownlo adsChanged_:function(){if(loadTimeData.getBoolean("allowDeletingHistory"))this.$ .toolbar.downloadsShowing=this.hasDownloads_;if(this.hasDownloads_)this.$["downl oads-list"].fire("iron-resize")},insertItems_:function(index,list){this.splice.a pply(this,["items_",index,0].concat(list));this.updateHideDates_(index,index+lis t.length);this.removeAttribute("loading");this.spinnerActive_=false},itemsChange d_:function(){this.hasDownloads_=this.items_.length>0},noDownloadsText_:function (){return loadTimeData.getString(this.inSearchMode_?"noSearchResults":"noDownloa ds")},onCanExecute_:function(e){e=e;switch(e.command.id){case"undo-command":e.ca nExecute=this.$.toolbar.canUndo();break;case"clear-all-command":e.canExecute=thi s.$.toolbar.canClearAll();break;case"find-command":e.canExecute=true;break}},onC ommand_:function(e){if(e.command.id=="clear-all-command")downloads.ActionService .getInstance().clearAll();else if(e.command.id=="undo-command")downloads.ActionS ervice.getInstance().undo();else if(e.command.id=="find-command")this.$.toolbar. onFindCommand()},onListScroll_:function(){var list=this.$["downloads-list"];if(l ist.scrollHeight-list.scrollTop-list.offsetHeight<=100){downloads.ActionService. getInstance().loadMore()}this.hasShadow_=list.scrollTop>0},onLoad_:function(){cr .ui.decorate("command",cr.ui.Command);document.addEventListener("canExecute",thi s.onCanExecute_.bind(this));document.addEventListener("command",this.onCommand_. bind(this));downloads.ActionService.getInstance().loadMore()},onSearchChanged_:f unction(){this.inSearchMode_=downloads.ActionService.getInstance().isSearching() },removeItem_:function(index){this.splice("items_",index,1);this.updateHideDates _(index,index);this.onListScroll_()},updateHideDates_:function(start,end){for(va r i=start;i<=end;++i){var current=this.items_[i];if(!current)continue;var prev=t his.items_[i-1];var hideDate=!!prev&&prev.date_string==current.date_string;this. set("items_."+i+".hideDate",hideDate)}},updateItem_:function(index,data){this.se t("items_."+index,data);this.updateHideDates_(index,index);var list=this.$["down loads-list"];list.updateSizeForItem(index)}});Manager.clearAll=function(){Manage r.get().clearAll_()};Manager.get=function(){return queryRequiredElement("downloa ds-manager")};Manager.insertItems=function(index,list){Manager.get().insertItems _(index,list)};Manager.onLoad=function(){Manager.get().onLoad_()};Manager.remove Item=function(index){Manager.get().removeItem_(index)};Manager.updateItem=functi on(index,data){Manager.get().updateItem_(index,data)};return{Manager:Manager}}); 67 cr.define("downloads",function(){var Manager=Polymer({is:"downloads-manager",pro perties:{hasDownloads_:{observer:"hasDownloadsChanged_",type:Boolean},hasShadow_ :{type:Boolean,value:false,reflectToAttribute:true},inSearchMode_:{type:Boolean, value:false},items_:{type:Array,value:function(){return[]}},spinnerActive_:{type :Boolean,notify:true}},hostAttributes:{loading:true},listeners:{"downloads-list. scroll":"onListScroll_","toolbar.search-changed":"onSearchChanged_"},observers:[ "itemsChanged_(items_.*)"],clearAll_:function(){this.set("items_",[])},hasDownlo adsChanged_:function(){if(loadTimeData.getBoolean("allowDeletingHistory"))this.$ .toolbar.downloadsShowing=this.hasDownloads_;if(this.hasDownloads_)this.$["downl oads-list"].fire("iron-resize")},insertItems_:function(index,list){this.splice.a pply(this,["items_",index,0].concat(list));this.updateHideDates_(index,index+lis t.length);this.removeAttribute("loading");this.spinnerActive_=false},itemsChange d_:function(){this.hasDownloads_=this.items_.length>0},noDownloadsText_:function (){return loadTimeData.getString(this.inSearchMode_?"noSearchResults":"noDownloa ds")},onCanExecute_:function(e){e=e;switch(e.command.id){case"undo-command":e.ca nExecute=this.$.toolbar.canUndo();break;case"clear-all-command":e.canExecute=thi s.$.toolbar.canClearAll();break;case"find-command":e.canExecute=true;break}},onC ommand_:function(e){if(e.command.id=="clear-all-command")downloads.ActionService .getInstance().clearAll();else if(e.command.id=="undo-command")downloads.ActionS ervice.getInstance().undo();else if(e.command.id=="find-command")this.$.toolbar. onFindCommand()},onListScroll_:function(){var list=this.$["downloads-list"];if(l ist.scrollHeight-list.scrollTop-list.offsetHeight<=100){downloads.ActionService. getInstance().loadMore()}this.hasShadow_=list.scrollTop>0},onLoad_:function(){cr .ui.decorate("command",cr.ui.Command);document.addEventListener("canExecute",thi s.onCanExecute_.bind(this));document.addEventListener("command",this.onCommand_. bind(this));downloads.ActionService.getInstance().loadMore()},onSearchChanged_:f unction(){this.inSearchMode_=downloads.ActionService.getInstance().isSearching() },removeItem_:function(index){this.splice("items_",index,1);this.updateHideDates _(index,index);this.onListScroll_()},updateHideDates_:function(start,end){for(va r i=start;i<=end;++i){var current=this.items_[i];if(!current)continue;var prev=t his.items_[i-1];var hideDate=!!prev&&prev.date_string==current.date_string;this. set("items_."+i+".hideDate",hideDate)}},updateItem_:function(index,data){this.se t("items_."+index,data);this.updateHideDates_(index,index);var list=this.$["down loads-list"];list.updateSizeForItem(index)}});Manager.clearAll=function(){Manage r.get().clearAll_()};Manager.get=function(){return queryRequiredElement("downloa ds-manager")};Manager.insertItems=function(index,list){Manager.get().insertItems _(index,list)};Manager.onLoad=function(){Manager.get().onLoad_()};Manager.remove Item=function(index){Manager.get().removeItem_(index)};Manager.updateItem=functi on(index,data){Manager.get().updateItem_(index,data)};return{Manager:Manager}});
68 // Copyright 2015 The Chromium Authors. All rights reserved. 68 // Copyright 2015 The Chromium Authors. All rights reserved.
69 // Use of this source code is governed by a BSD-style license that can be 69 // Use of this source code is governed by a BSD-style license that can be
70 // found in the LICENSE file. 70 // found in the LICENSE file.
71 window.addEventListener("load",function(){downloads.Manager.onLoad();document.fo nts.load("bold 12px Roboto")}); 71 window.addEventListener("load",function(){downloads.Manager.onLoad();document.fo nts.load("bold 12px Roboto")});
OLDNEW
« no previous file with comments | « chrome/browser/resources/inspect/inspect.js ('k') | chrome/browser/resources/md_history/app.crisper.js » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698