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

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

Issue 2670723002: [MD History] Vulcanize as part of GN build. (Closed)
Patch Set: address nits Created 3 years, 10 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
(Empty)
1 // Copyright 2016 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 function PromiseResolver(){this.resolve_;this.reject_;this.promise_=new Promise( function(resolve,reject){this.resolve_=resolve;this.reject_=reject}.bind(this))} PromiseResolver.prototype={get promise(){return this.promise_},set promise(p){as sertNotReached()},get resolve(){return this.resolve_},set resolve(r){assertNotRe ached()},get reject(){return this.reject_},set reject(s){assertNotReached()}};
5 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
6 // Use of this source code is governed by a BSD-style license that can be
7 // found in the LICENSE file.
8 var global=this;var WebUIListener;var cr=cr||function(){"use strict";function ex portPath(name,opt_object,opt_objectToExportTo){var parts=name.split(".");var cur =opt_objectToExportTo||global;for(var part;parts.length&&(part=parts.shift());){ if(!parts.length&&opt_object!==undefined){cur[part]=opt_object}else if(part in c ur){cur=cur[part]}else{cur=cur[part]={}}}return cur}function dispatchPropertyCha nge(target,propertyName,newValue,oldValue){var e=new Event(propertyName+"Change" );e.propertyName=propertyName;e.newValue=newValue;e.oldValue=oldValue;target.dis patchEvent(e)}function getAttributeName(jsName){return jsName.replace(/([A-Z])/g ,"-$1").toLowerCase()}var PropertyKind={JS:"js",ATTR:"attr",BOOL_ATTR:"boolAttr" };function getGetter(name,kind){switch(kind){case PropertyKind.JS:var privateNam e=name+"_";return function(){return this[privateName]};case PropertyKind.ATTR:va r attributeName=getAttributeName(name);return function(){return this.getAttribut e(attributeName)};case PropertyKind.BOOL_ATTR:var attributeName=getAttributeName (name);return function(){return this.hasAttribute(attributeName)}}throw"not reac hed"}function getSetter(name,kind,opt_setHook){switch(kind){case PropertyKind.JS :var privateName=name+"_";return function(value){var oldValue=this[name];if(valu e!==oldValue){this[privateName]=value;if(opt_setHook)opt_setHook.call(this,value ,oldValue);dispatchPropertyChange(this,name,value,oldValue)}};case PropertyKind. ATTR:var attributeName=getAttributeName(name);return function(value){var oldValu e=this[name];if(value!==oldValue){if(value==undefined)this.removeAttribute(attri buteName);else this.setAttribute(attributeName,value);if(opt_setHook)opt_setHook .call(this,value,oldValue);dispatchPropertyChange(this,name,value,oldValue)}};ca se PropertyKind.BOOL_ATTR:var attributeName=getAttributeName(name);return functi on(value){var oldValue=this[name];if(value!==oldValue){if(value)this.setAttribut e(attributeName,name);else this.removeAttribute(attributeName);if(opt_setHook)op t_setHook.call(this,value,oldValue);dispatchPropertyChange(this,name,value,oldVa lue)}}}throw"not reached"}function defineProperty(obj,name,opt_kind,opt_setHook) {if(typeof obj=="function")obj=obj.prototype;var kind=opt_kind||PropertyKind.JS; if(!obj.__lookupGetter__(name))obj.__defineGetter__(name,getGetter(name,kind));i f(!obj.__lookupSetter__(name))obj.__defineSetter__(name,getSetter(name,kind,opt_ setHook))}var uidCounter=1;function createUid(){return uidCounter++}function get Uid(item){if(item.hasOwnProperty("uid"))return item.uid;return item.uid=createUi d()}function dispatchSimpleEvent(target,type,opt_bubbles,opt_cancelable){var e=n ew Event(type,{bubbles:opt_bubbles,cancelable:opt_cancelable===undefined||opt_ca ncelable});return target.dispatchEvent(e)}function define(name,fun){var obj=expo rtPath(name);var exports=fun();for(var propertyName in exports){var propertyDesc riptor=Object.getOwnPropertyDescriptor(exports,propertyName);if(propertyDescript or)Object.defineProperty(obj,propertyName,propertyDescriptor)}}function addSingl etonGetter(ctor){ctor.getInstance=function(){return ctor.instance_||(ctor.instan ce_=new ctor)}}function makePublic(ctor,methods,opt_target){methods.forEach(func tion(method){ctor[method]=function(){var target=opt_target?document.getElementBy Id(opt_target):ctor.getInstance();return target[method+"_"].apply(target,argumen ts)}})}var chromeSendResolverMap={};function webUIResponse(id,isSuccess,response ){var resolver=chromeSendResolverMap[id];delete chromeSendResolverMap[id];if(isS uccess)resolver.resolve(response);else resolver.reject(response)}function sendWi thPromise(methodName,var_args){var args=Array.prototype.slice.call(arguments,1); var promiseResolver=new PromiseResolver;var id=methodName+"_"+createUid();chrome SendResolverMap[id]=promiseResolver;chrome.send(methodName,[id].concat(args));re turn promiseResolver.promise}var webUIListenerMap={};function webUIListenerCallb ack(event,var_args){var eventListenersMap=webUIListenerMap[event];if(!eventListe nersMap){return}var args=Array.prototype.slice.call(arguments,1);for(var listene rId in eventListenersMap){eventListenersMap[listenerId].apply(null,args)}}functi on addWebUIListener(eventName,callback){webUIListenerMap[eventName]=webUIListene rMap[eventName]||{};var uid=createUid();webUIListenerMap[eventName][uid]=callbac k;return{eventName:eventName,uid:uid}}function removeWebUIListener(listener){var listenerExists=webUIListenerMap[listener.eventName]&&webUIListenerMap[listener. eventName][listener.uid];if(listenerExists){delete webUIListenerMap[listener.eve ntName][listener.uid];return true}return false}return{addSingletonGetter:addSing letonGetter,createUid:createUid,define:define,defineProperty:defineProperty,disp atchPropertyChange:dispatchPropertyChange,dispatchSimpleEvent:dispatchSimpleEven t,exportPath:exportPath,getUid:getUid,makePublic:makePublic,PropertyKind:Propert yKind,addWebUIListener:addWebUIListener,removeWebUIListener:removeWebUIListener, sendWithPromise:sendWithPromise,webUIListenerCallback:webUIListenerCallback,webU IResponse:webUIResponse,get doc(){return document},get isMac(){return/Mac/.test( navigator.platform)},get isWindows(){return/Win/.test(navigator.platform)},get i sChromeOS(){return/CrOS/.test(navigator.userAgent)},get isLinux(){return/Linux/. test(navigator.userAgent)},get isAndroid(){return/Android/.test(navigator.userAg ent)},get isIOS(){return/iPad|iPhone|iPod/.test(navigator.platform)}}}();
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
11 // found in the LICENSE file.
12 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}});
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
15 // found in the LICENSE file.
16 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 }});Polymer({is:"iron-media-query",properties:{queryMatches:{type:Boolean,value: false,readOnly:true,notify:true},query:{type:String,observer:"queryChanged"},ful l:{type:Boolean,value:false},_boundMQHandler:{value:function(){return this.query Handler.bind(this)}},_mq:{value:null}},attached:function(){this.style.display="n one";this.queryChanged()},detached:function(){this._remove()},_add:function(){if (this._mq){this._mq.addListener(this._boundMQHandler)}},_remove:function(){if(th is._mq){this._mq.removeListener(this._boundMQHandler)}this._mq=null},queryChange d:function(){this._remove();var query=this.query;if(!query){return}if(!this.full &&query[0]!=="("){query="("+query+")"}this._mq=window.matchMedia(query);this._ad d();this.queryHandler(this._mq)},queryHandler:function(mq){this._setQueryMatches (mq.matches)}});Polymer.IronResizableBehavior={properties:{_parentResizable:{typ e:Object,observer:"_parentResizableChanged"},_notifyingDescendant:{type:Boolean, value:false}},listeners:{"iron-request-resize-notifications":"_onIronRequestResi zeNotifications"},created:function(){this._interestedResizables=[];this._boundNo tifyResize=this.notifyResize.bind(this)},attached:function(){this.fire("iron-req uest-resize-notifications",null,{node:this,bubbles:true,cancelable:true});if(!th is._parentResizable){window.addEventListener("resize",this._boundNotifyResize);t his.notifyResize()}},detached:function(){if(this._parentResizable){this._parentR esizable.stopResizeNotificationsFor(this)}else{window.removeEventListener("resiz e",this._boundNotifyResize)}this._parentResizable=null},notifyResize:function(){ if(!this.isAttached){return}this._interestedResizables.forEach(function(resizabl e){if(this.resizerShouldNotify(resizable)){this._notifyDescendant(resizable)}},t his);this._fireResize()},assignParentResizable:function(parentResizable){this._p arentResizable=parentResizable},stopResizeNotificationsFor:function(target){var index=this._interestedResizables.indexOf(target);if(index>-1){this._interestedRe sizables.splice(index,1);this.unlisten(target,"iron-resize","_onDescendantIronRe size")}},resizerShouldNotify:function(element){return true},_onDescendantIronRes ize:function(event){if(this._notifyingDescendant){event.stopPropagation();return }if(!Polymer.Settings.useShadow){this._fireResize()}},_fireResize:function(){thi s.fire("iron-resize",null,{node:this,bubbles:false})},_onIronRequestResizeNotifi cations:function(event){var target=event.path?event.path[0]:event.target;if(targ et===this){return}if(this._interestedResizables.indexOf(target)===-1){this._inte restedResizables.push(target);this.listen(target,"iron-resize","_onDescendantIro nResize")}target.assignParentResizable(this);this._notifyDescendant(target);even t.stopPropagation()},_parentResizableChanged:function(parentResizable){if(parent Resizable){window.removeEventListener("resize",this._boundNotifyResize)}},_notif yDescendant:function(descendant){if(!this.isAttached){return}this._notifyingDesc endant=true;descendant.notifyResize();this._notifyingDescendant=false}};Polymer. IronSelection=function(selectCallback){this.selection=[];this.selectCallback=sel ectCallback};Polymer.IronSelection.prototype={get:function(){return this.multi?t his.selection.slice():this.selection[0]},clear:function(excludes){this.selection .slice().forEach(function(item){if(!excludes||excludes.indexOf(item)<0){this.set ItemSelected(item,false)}},this)},isSelected:function(item){return this.selectio n.indexOf(item)>=0},setItemSelected:function(item,isSelected){if(item!=null){if( isSelected!==this.isSelected(item)){if(isSelected){this.selection.push(item)}els e{var i=this.selection.indexOf(item);if(i>=0){this.selection.splice(i,1)}}if(thi s.selectCallback){this.selectCallback(item,isSelected)}}}},select:function(item) {if(this.multi){this.toggle(item)}else if(this.get()!==item){this.setItemSelecte d(this.get(),false);this.setItemSelected(item,true)}},toggle:function(item){this .setItemSelected(item,!this.isSelected(item))}};Polymer.IronSelectableBehavior={ properties:{attrForSelected:{type:String,value:null},selected:{type:String,notif y:true},selectedItem:{type:Object,readOnly:true,notify:true},activateEvent:{type :String,value:"tap",observer:"_activateEventChanged"},selectable:String,selected Class:{type:String,value:"iron-selected"},selectedAttribute:{type:String,value:n ull},fallbackSelection:{type:String,value:null},items:{type:Array,readOnly:true, notify:true,value:function(){return[]}},_excludedLocalNames:{type:Object,value:f unction(){return{template:1}}}},observers:["_updateAttrForSelected(attrForSelect ed)","_updateSelected(selected)","_checkFallback(fallbackSelection)"],created:fu nction(){this._bindFilterItem=this._filterItem.bind(this);this._selection=new Po lymer.IronSelection(this._applySelection.bind(this))},attached:function(){this._ observer=this._observeItems(this);this._updateItems();if(!this._shouldUpdateSele ction){this._updateSelected()}this._addListener(this.activateEvent)},detached:fu nction(){if(this._observer){Polymer.dom(this).unobserveNodes(this._observer)}thi s._removeListener(this.activateEvent)},indexOf:function(item){return this.items. indexOf(item)},select:function(value){this.selected=value},selectPrevious:functi on(){var length=this.items.length;var index=(Number(this._valueToIndex(this.sele cted))-1+length)%length;this.selected=this._indexToValue(index)},selectNext:func tion(){var index=(Number(this._valueToIndex(this.selected))+1)%this.items.length ;this.selected=this._indexToValue(index)},selectIndex:function(index){this.selec t(this._indexToValue(index))},forceSynchronousItemUpdate:function(){this._update Items()},get _shouldUpdateSelection(){return this.selected!=null},_checkFallback :function(){if(this._shouldUpdateSelection){this._updateSelected()}},_addListene r:function(eventName){this.listen(this,eventName,"_activateHandler")},_removeLis tener:function(eventName){this.unlisten(this,eventName,"_activateHandler")},_act ivateEventChanged:function(eventName,old){this._removeListener(old);this._addLis tener(eventName)},_updateItems:function(){var nodes=Polymer.dom(this).queryDistr ibutedElements(this.selectable||"*");nodes=Array.prototype.filter.call(nodes,thi s._bindFilterItem);this._setItems(nodes)},_updateAttrForSelected:function(){if(t his._shouldUpdateSelection){this.selected=this._indexToValue(this.indexOf(this.s electedItem))}},_updateSelected:function(){this._selectSelected(this.selected)}, _selectSelected:function(selected){this._selection.select(this._valueToItem(this .selected));if(this.fallbackSelection&&this.items.length&&this._selection.get()= ==undefined){this.selected=this.fallbackSelection}},_filterItem:function(node){r eturn!this._excludedLocalNames[node.localName]},_valueToItem:function(value){ret urn value==null?null:this.items[this._valueToIndex(value)]},_valueToIndex:functi on(value){if(this.attrForSelected){for(var i=0,item;item=this.items[i];i++){if(t his._valueForItem(item)==value){return i}}}else{return Number(value)}},_indexToV alue:function(index){if(this.attrForSelected){var item=this.items[index];if(item ){return this._valueForItem(item)}}else{return index}},_valueForItem:function(it em){var propValue=item[Polymer.CaseMap.dashToCamelCase(this.attrForSelected)];re turn propValue!=undefined?propValue:item.getAttribute(this.attrForSelected)},_ap plySelection:function(item,isSelected){if(this.selectedClass){this.toggleClass(t his.selectedClass,isSelected,item)}if(this.selectedAttribute){this.toggleAttribu te(this.selectedAttribute,isSelected,item)}this._selectionChange();this.fire("ir on-"+(isSelected?"select":"deselect"),{item:item})},_selectionChange:function(){ this._setSelectedItem(this._selection.get())},_observeItems:function(node){retur n Polymer.dom(node).observeNodes(function(mutation){this._updateItems();if(this. _shouldUpdateSelection){this._updateSelected()}this.fire("iron-items-changed",mu tation,{bubbles:false,cancelable:false})})},_activateHandler:function(e){var t=e .target;var items=this.items;while(t&&t!=this){var i=items.indexOf(t);if(i>=0){v ar value=this._indexToValue(i);this._itemActivate(value,t);return}t=t.parentNode }},_itemActivate:function(value,item){if(!this.fire("iron-activate",{selected:va lue,item:item},{cancelable:true}).defaultPrevented){this.select(value)}}};Polyme r({is:"iron-pages",behaviors:[Polymer.IronResizableBehavior,Polymer.IronSelectab leBehavior],properties:{activateEvent:{type:String,value:null}},observers:["_sel ectedPageChanged(selected)"],_selectedPageChanged:function(selected,old){this.as ync(this.notifyResize)}});Polymer.IronScrollTargetBehavior={properties:{scrollTa rget:{type:HTMLElement,value:function(){return this._defaultScrollTarget}}},obse rvers:["_scrollTargetChanged(scrollTarget, isAttached)"],_shouldHaveListener:tru e,_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.scrollTarget =this.domHost?this.domHost.$[scrollTarget]:Polymer.dom(this.ownerDocument).query Selector("#"+scrollTarget)}else if(this._isValidScrollTarget()){this._boundScrol lHandler=this._boundScrollHandler||this._scrollHandler.bind(this);this._oldScrol lTarget=scrollTarget;this._toggleScrollListener(this._shouldHaveListener,scrollT arget)}},_scrollHandler:function scrollHandler(){},get _defaultScrollTarget(){re turn this._doc},get _doc(){return this.ownerDocument.documentElement},get _scrol lTop(){if(this._isValidScrollTarget()){return this.scrollTarget===this._doc?wind ow.pageYOffset:this.scrollTarget.scrollTop}return 0},get _scrollLeft(){if(this._ isValidScrollTarget()){return this.scrollTarget===this._doc?window.pageXOffset:t his.scrollTarget.scrollLeft}return 0},set _scrollTop(top){if(this.scrollTarget== =this._doc){window.scrollTo(window.pageXOffset,top)}else if(this._isValidScrollT arget()){this.scrollTarget.scrollTop=top}},set _scrollLeft(left){if(this.scrollT arget===this._doc){window.scrollTo(left,window.pageYOffset)}else if(this._isVali dScrollTarget()){this.scrollTarget.scrollLeft=left}},scroll:function(left,top){i f(this.scrollTarget===this._doc){window.scrollTo(left,top)}else if(this._isValid ScrollTarget()){this.scrollTarget.scrollLeft=left;this.scrollTarget.scrollTop=to p}},get _scrollTargetWidth(){if(this._isValidScrollTarget()){return this.scrollT arget===this._doc?window.innerWidth:this.scrollTarget.offsetWidth}return 0},get _scrollTargetHeight(){if(this._isValidScrollTarget()){return this.scrollTarget== =this._doc?window.innerHeight:this.scrollTarget.offsetHeight}return 0},_isValidS crollTarget:function(){return this.scrollTarget instanceof HTMLElement},_toggleS crollListener:function(yes,scrollTarget){if(!this._boundScrollHandler){return}va r eventTarget=scrollTarget===this._doc?window:scrollTarget;if(yes){eventTarget.a ddEventListener("scroll",this._boundScrollHandler)}else{eventTarget.removeEventL istener("scroll",this._boundScrollHandler)}},toggleScrollListener:function(yes){ this._shouldHaveListener=yes;this._toggleScrollListener(yes,this.scrollTarget)}} ;(function(){var metaDatas={};var metaArrays={};var singleton=null;Polymer.IronM eta=Polymer({is:"iron-meta",properties:{type:{type:String,value:"default",observ er:"_typeChanged"},key:{type:String,observer:"_keyChanged"},value:{type:Object,n otify:true,observer:"_valueChanged"},self:{type:Boolean,observer:"_selfChanged"} ,list:{type:Array,notify:true}},hostAttributes:{hidden:true},factoryImpl:functio n(config){if(config){for(var n in config){switch(n){case"type":case"key":case"va lue":this[n]=config[n];break}}}},created:function(){this._metaDatas=metaDatas;th is._metaArrays=metaArrays},_keyChanged:function(key,old){this._resetRegistration (old)},_valueChanged:function(value){this._resetRegistration(this.key)},_selfCha nged:function(self){if(self){this.value=this}},_typeChanged:function(type){this. _unregisterKey(this.key);if(!metaDatas[type]){metaDatas[type]={}}this._metaData= metaDatas[type];if(!metaArrays[type]){metaArrays[type]=[]}this.list=metaArrays[t ype];this._registerKeyValue(this.key,this.value)},byKey:function(key){return thi s._metaData&&this._metaData[key]},_resetRegistration:function(oldKey){this._unre gisterKey(oldKey);this._registerKeyValue(this.key,this.value)},_unregisterKey:fu nction(key){this._unregister(key,this._metaData,this.list)},_registerKeyValue:fu nction(key,value){this._register(key,value,this._metaData,this.list)},_register: function(key,value,data,list){if(key&&data&&value!==undefined){data[key]=value;l ist.push(value)}},_unregister:function(key,data,list){if(key&&data){if(key in da ta){var value=data[key];delete data[key];this.arrayDelete(list,value)}}}});Polym er.IronMeta.getIronMeta=function getIronMeta(){if(singleton===null){singleton=ne w Polymer.IronMeta}return singleton};Polymer.IronMetaQuery=Polymer({is:"iron-met a-query",properties:{type:{type:String,value:"default",observer:"_typeChanged"}, key:{type:String,observer:"_keyChanged"},value:{type:Object,notify:true,readOnly :true},list:{type:Array,notify:true}},factoryImpl:function(config){if(config){fo r(var n in config){switch(n){case"type":case"key":this[n]=config[n];break}}}},cr eated:function(){this._metaDatas=metaDatas;this._metaArrays=metaArrays},_keyChan ged:function(key){this._setValue(this._metaData&&this._metaData[key])},_typeChan ged:function(type){this._metaData=metaDatas[type];this.list=metaArrays[type];if( this.key){this._keyChanged(this.key)}},byKey:function(key){return this._metaData &&this._metaData[key]}})})();Polymer({is:"iron-icon",properties:{icon:{type:Stri ng,observer:"_iconChanged"},theme:{type:String,observer:"_updateIcon"},src:{type :String,observer:"_srcChanged"},_meta:{value:Polymer.Base.create("iron-meta",{ty pe:"iconset"}),observer:"_updateIcon"}},_DEFAULT_ICONSET:"icons",_iconChanged:fu nction(icon){var parts=(icon||"").split(":");this._iconName=parts.pop();this._ic onsetName=parts.pop()||this._DEFAULT_ICONSET;this._updateIcon()},_srcChanged:fun ction(src){this._updateIcon()},_usesIconset:function(){return this.icon||!this.s rc},_updateIcon:function(){if(this._usesIconset()){if(this._img&&this._img.paren tNode){Polymer.dom(this.root).removeChild(this._img)}if(this._iconName===""){if( this._iconset){this._iconset.removeIcon(this)}}else if(this._iconsetName&&this._ meta){this._iconset=this._meta.byKey(this._iconsetName);if(this._iconset){this._ iconset.applyIcon(this,this._iconName,this.theme);this.unlisten(window,"iron-ico nset-added","_updateIcon")}else{this.listen(window,"iron-iconset-added","_update Icon")}}}else{if(this._iconset){this._iconset.removeIcon(this)}if(!this._img){th is._img=document.createElement("img");this._img.style.width="100%";this._img.sty le.height="100%";this._img.draggable=false}this._img.src=this.src;Polymer.dom(th is.root).appendChild(this._img)}}});Polymer({is:"iron-iconset-svg",properties:{n ame:{type:String,observer:"_nameChanged"},size:{type:Number,value:24},rtlMirrori ng:{type:Boolean,value:false}},_targetIsRTL:function(target){if(target&&target.n odeType!==Node.ELEMENT_NODE){target=target.host}return target&&window.getCompute dStyle(target)["direction"]==="rtl"},attached:function(){this.style.display="non e"},getIconNames:function(){this._icons=this._createIconMap();return Object.keys (this._icons).map(function(n){return this.name+":"+n},this)},applyIcon:function( element,iconName){element=element.root||element;this.removeIcon(element);var svg =this._cloneIcon(iconName,this.rtlMirroring&&this._targetIsRTL(element));if(svg) {var pde=Polymer.dom(element);pde.insertBefore(svg,pde.childNodes[0]);return ele ment._svgIcon=svg}return null},removeIcon:function(element){element=element.root ||element;if(element._svgIcon){Polymer.dom(element).removeChild(element._svgIcon );element._svgIcon=null}},_nameChanged:function(){new Polymer.IronMeta({type:"ic onset",key:this.name,value:this});this.async(function(){this.fire("iron-iconset- added",this,{node:window})})},_createIconMap:function(){var icons=Object.create( null);Polymer.dom(this).querySelectorAll("[id]").forEach(function(icon){icons[ic on.id]=icon});return icons},_cloneIcon:function(id,mirrorAllowed){this._icons=th is._icons||this._createIconMap();return this._prepareSvgClone(this._icons[id],th is.size,mirrorAllowed)},_prepareSvgClone:function(sourceSvg,size,mirrorAllowed){ if(sourceSvg){var content=sourceSvg.cloneNode(true),svg=document.createElementNS ("http://www.w3.org/2000/svg","svg"),viewBox=content.getAttribute("viewBox")||"0 0 "+size+" "+size,cssText="pointer-events: none; display: block; width: 100%; h eight: 100%;";if(mirrorAllowed&&content.hasAttribute("mirror-in-rtl")){cssText+= "-webkit-transform:scale(-1,1);transform:scale(-1,1);"}svg.setAttribute("viewBox ",viewBox);svg.setAttribute("preserveAspectRatio","xMidYMid meet");svg.style.css Text=cssText;svg.appendChild(content).removeAttribute("id");return svg}return nu ll}});
17 // Copyright 2016 The Chromium Authors. All rights reserved.
18 // Use of this source code is governed by a BSD-style license that can be
19 // found in the LICENSE file.
20 Polymer({is:"cr-lazy-render","extends":"template",behaviors:[Polymer.Templatizer ],child_:null,get:function(){if(!this.child_)this.render_();return this.child_}, getIfExists:function(){return this.child_},render_:function(){if(!this.ctor)this .templatize(this);var parentNode=this.parentNode;if(parentNode&&!this.child_){va r instance=this.stamp({});this.child_=instance.root.firstElementChild;parentNode .insertBefore(instance.root,this)}},_forwardParentProp:function(prop,value){if(t his.child_)this.child_._templateInstance[prop]=value},_forwardParentPath:functio n(path,value){if(this.child_)this.child_._templateInstance.notifyPath(path,value ,true)}});(function(){"use strict";var KEY_IDENTIFIER={"U+0008":"backspace","U+0 009":"tab","U+001B":"esc","U+0020":"space","U+007F":"del"};var KEY_CODE={8:"back space",9:"tab",13:"enter",27:"esc",33:"pageup",34:"pagedown",35:"end",36:"home", 32:"space",37:"left",38:"up",39:"right",40:"down",46:"del",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(b ar)?/;var ESC_KEY=/^escape$/;function transformKey(key,noSpecialChars){var valid Key="";if(key){var lKey=key.toLowerCase();if(lKey===" "||SPACE_KEY.test(lKey)){v alidKey="space"}else if(ESC_KEY.test(lKey)){validKey="esc"}else if(lKey.length== 1){if(!noSpecialChars||KEY_CHAR.test(lKey)){validKey=lKey}}else if(ARROW_KEY.tes t(lKey)){validKey=lKey.replace("arrow","")}else if(lKey=="multiply"){validKey="* "}else{validKey=lKey}}return validKey}function transformKeyIdentifier(keyIdent){ var validKey="";if(keyIdent){if(keyIdent in KEY_IDENTIFIER){validKey=KEY_IDENTIF IER[keyIdent]}else if(IDENT_CHAR.test(keyIdent)){keyIdent=parseInt(keyIdent.repl ace("U+","0x"),16);validKey=String.fromCharCode(keyIdent).toLowerCase()}else{val idKey=keyIdent.toLowerCase()}}return validKey}function transformKeyCode(keyCode) {var validKey="";if(Number(keyCode)){if(keyCode>=65&&keyCode<=90){validKey=Strin g.fromCharCode(32+keyCode)}else if(keyCode>=112&&keyCode<=123){validKey="f"+(key Code-112)}else if(keyCode>=48&&keyCode<=57){validKey=String(keyCode-48)}else if( keyCode>=96&&keyCode<=105){validKey=String(keyCode-96)}else{validKey=KEY_CODE[ke yCode]}}return validKey}function normalizedKeyForEvent(keyEvent,noSpecialChars){ if(keyEvent.key){return transformKey(keyEvent.key,noSpecialChars)}if(keyEvent.de tail&&keyEvent.detail.key){return transformKey(keyEvent.detail.key,noSpecialChar s)}return transformKeyIdentifier(keyEvent.keyIdentifier)||transformKeyCode(keyEv ent.keyCode)||""}function keyComboMatchesEvent(keyCombo,event){var keyEvent=norm alizedKeyForEvent(event,keyCombo.hasModifiers);return keyEvent===keyCombo.key&&( !keyCombo.hasModifiers||!!event.shiftKey===!!keyCombo.shiftKey&&!!event.ctrlKey= ==!!keyCombo.ctrlKey&&!!event.altKey===!!keyCombo.altKey&&!!event.metaKey===!!ke yCombo.metaKey)}function parseKeyComboString(keyComboString){if(keyComboString.l ength===1){return{combo:keyComboString,key:keyComboString,event:"keydown"}}retur n keyComboString.split("+").reduce(function(parsedKeyCombo,keyComboPart){var eve ntParts=keyComboPart.split(":");var keyName=eventParts[0];var event=eventParts[1 ];if(keyName in MODIFIER_KEYS){parsedKeyCombo[MODIFIER_KEYS[keyName]]=true;parse dKeyCombo.hasModifiers=true}else{parsedKeyCombo.key=keyName;parsedKeyCombo.event =event||"keydown"}return parsedKeyCombo},{combo:keyComboString.split(":").shift( )})}function parseEventString(eventString){return eventString.trim().split(" "). map(function(keyComboString){return parseKeyComboString(keyComboString)})}Polyme r.IronA11yKeysBehavior={properties:{keyEventTarget:{type:Object,value:function() {return this}},stopKeyboardEventPropagation:{type:Boolean,value:false},_boundKey Handlers:{type:Array,value:function(){return[]}},_imperativeKeyBindings:{type:Ob ject,value:function(){return{}}}},observers:["_resetKeyEventListeners(keyEventTa rget, _boundKeyHandlers)"],keyBindings:{},registered:function(){this._prepKeyBin dings()},attached:function(){this._listenKeyEventListeners()},detached:function( ){this._unlistenKeyEventListeners()},addOwnKeyBinding:function(eventString,handl erName){this._imperativeKeyBindings[eventString]=handlerName;this._prepKeyBindin gs();this._resetKeyEventListeners()},removeOwnKeyBindings:function(){this._imper ativeKeyBindings={};this._prepKeyBindings();this._resetKeyEventListeners()},keyb oardEventMatchesKeys:function(event,eventString){var keyCombos=parseEventString( eventString);for(var i=0;i<keyCombos.length;++i){if(keyComboMatchesEvent(keyComb os[i],event)){return true}}return false},_collectKeyBindings:function(){var keyB indings=this.behaviors.map(function(behavior){return behavior.keyBindings});if(k eyBindings.indexOf(this.keyBindings)===-1){keyBindings.push(this.keyBindings)}re turn keyBindings},_prepKeyBindings:function(){this._keyBindings={};this._collect KeyBindings().forEach(function(keyBindings){for(var eventString in keyBindings){ this._addKeyBinding(eventString,keyBindings[eventString])}},this);for(var eventS tring in this._imperativeKeyBindings){this._addKeyBinding(eventString,this._impe rativeKeyBindings[eventString])}for(var eventName in this._keyBindings){this._ke yBindings[eventName].sort(function(kb1,kb2){var b1=kb1[0].hasModifiers;var b2=kb 2[0].hasModifiers;return b1===b2?0:b1?-1:1})}},_addKeyBinding:function(eventStri ng,handlerName){parseEventString(eventString).forEach(function(keyCombo){this._k eyBindings[keyCombo.event]=this._keyBindings[keyCombo.event]||[];this._keyBindin gs[keyCombo.event].push([keyCombo,handlerName])},this)},_resetKeyEventListeners: function(){this._unlistenKeyEventListeners();if(this.isAttached){this._listenKey EventListeners()}},_listenKeyEventListeners:function(){if(!this.keyEventTarget){ return}Object.keys(this._keyBindings).forEach(function(eventName){var keyBinding s=this._keyBindings[eventName];var boundKeyHandler=this._onKeyBindingEvent.bind( this,keyBindings);this._boundKeyHandlers.push([this.keyEventTarget,eventName,bou ndKeyHandler]);this.keyEventTarget.addEventListener(eventName,boundKeyHandler)}, this)},_unlistenKeyEventListeners:function(){var keyHandlerTuple;var keyEventTar get;var eventName;var boundKeyHandler;while(this._boundKeyHandlers.length){keyHa ndlerTuple=this._boundKeyHandlers.pop();keyEventTarget=keyHandlerTuple[0];eventN ame=keyHandlerTuple[1];boundKeyHandler=keyHandlerTuple[2];keyEventTarget.removeE ventListener(eventName,boundKeyHandler)}},_onKeyBindingEvent:function(keyBinding s,event){if(this.stopKeyboardEventPropagation){event.stopPropagation()}if(event. defaultPrevented){return}for(var i=0;i<keyBindings.length;i++){var keyCombo=keyB indings[i][0];var handlerName=keyBindings[i][1];if(keyComboMatchesEvent(keyCombo ,event)){this._triggerKeyHandler(keyCombo,handlerName,event);if(event.defaultPre vented){return}}}},_triggerKeyHandler:function(keyCombo,handlerName,keyboardEven t){var detail=Object.create(keyCombo);detail.keyboardEvent=keyboardEvent;var eve nt=new CustomEvent(keyCombo.event,{detail:detail,cancelable:true});this[handlerN ame].call(this,event);if(event.defaultPrevented){keyboardEvent.preventDefault()} }}})();Polymer.IronControlState={properties:{focused:{type:Boolean,value:false,n otify:true,readOnly:true,reflectToAttribute:true},disabled:{type:Boolean,value:f alse,notify:true,observer:"_disabledChanged",reflectToAttribute:true},_oldTabInd ex:{type:Number},_boundFocusBlurHandler:{type:Function,value:function(){return t his._focusBlurHandler.bind(this)}}},observers:["_changedControlState(focused, di sabled)"],ready:function(){this.addEventListener("focus",this._boundFocusBlurHan dler,true);this.addEventListener("blur",this._boundFocusBlurHandler,true)},_focu sBlurHandler:function(event){if(event.target===this){this._setFocused(event.type ==="focus")}else if(!this.shadowRoot){var target=Polymer.dom(event).localTarget; if(!this.isLightDescendant(target)){this.fire(event.type,{sourceEvent:event},{no de:this,bubbles:event.bubbles,cancelable:event.cancelable})}}},_disabledChanged: function(disabled,old){this.setAttribute("aria-disabled",disabled?"true":"false" );this.style.pointerEvents=disabled?"none":"";if(disabled){this._oldTabIndex=thi s.tabIndex;this._setFocused(false);this.tabIndex=-1;this.blur()}else if(this._ol dTabIndex!==undefined){this.tabIndex=this._oldTabIndex}},_changedControlState:fu nction(){if(this._controlStateChanged){this._controlStateChanged()}}};Polymer.Ir onButtonStateImpl={properties:{pressed:{type:Boolean,readOnly:true,value:false,r eflectToAttribute:true,observer:"_pressedChanged"},toggles:{type:Boolean,value:f alse,reflectToAttribute:true},active:{type:Boolean,value:false,notify:true,refle ctToAttribute:true},pointerDown:{type:Boolean,readOnly:true,value:false},receive dFocusFromKeyboard:{type:Boolean,readOnly:true},ariaActiveAttribute:{type:String ,value:"aria-pressed",observer:"_ariaActiveAttributeChanged"}},listeners:{down:" _downHandler",up:"_upHandler",tap:"_tapHandler"},observers:["_detectKeyboardFocu s(focused)","_activeChanged(active, ariaActiveAttribute)"],keyBindings:{"enter:k eydown":"_asyncClick","space:keydown":"_spaceKeyDownHandler","space:keyup":"_spa ceKeyUpHandler"},_mouseEventRe:/^mouse/,_tapHandler:function(){if(this.toggles){ this._userActivate(!this.active)}else{this.active=false}},_detectKeyboardFocus:f unction(focused){this._setReceivedFocusFromKeyboard(!this.pointerDown&&focused)} ,_userActivate:function(active){if(this.active!==active){this.active=active;this .fire("change")}},_downHandler:function(event){this._setPointerDown(true);this._ setPressed(true);this._setReceivedFocusFromKeyboard(false)},_upHandler:function( ){this._setPointerDown(false);this._setPressed(false)},_spaceKeyDownHandler:func tion(event){var keyboardEvent=event.detail.keyboardEvent;var target=Polymer.dom( keyboardEvent).localTarget;if(this.isLightDescendant(target))return;keyboardEven t.preventDefault();keyboardEvent.stopImmediatePropagation();this._setPressed(tru e)},_spaceKeyUpHandler:function(event){var keyboardEvent=event.detail.keyboardEv ent;var target=Polymer.dom(keyboardEvent).localTarget;if(this.isLightDescendant( target))return;if(this.pressed){this._asyncClick()}this._setPressed(false)},_asy ncClick:function(){this.async(function(){this.click()},1)},_pressedChanged:funct ion(pressed){this._changedButtonState()},_ariaActiveAttributeChanged:function(va lue,oldValue){if(oldValue&&oldValue!=value&&this.hasAttribute(oldValue)){this.re moveAttribute(oldValue)}},_activeChanged:function(active,ariaActiveAttribute){if (this.toggles){this.setAttribute(this.ariaActiveAttribute,active?"true":"false") }else{this.removeAttribute(this.ariaActiveAttribute)}this._changedButtonState()} ,_controlStateChanged:function(){if(this.disabled){this._setPressed(false)}else{ this._changedButtonState()}},_changedButtonState:function(){if(this._buttonState Changed){this._buttonStateChanged()}}};Polymer.IronButtonState=[Polymer.IronA11y KeysBehavior,Polymer.IronButtonStateImpl];(function(){var Utility={distance:func tion(x1,y1,x2,y2){var xDelta=x1-x2;var yDelta=y1-y2;return Math.sqrt(xDelta*xDel ta+yDelta*yDelta)},now:window.performance&&window.performance.now?window.perform ance.now.bind(window.performance):Date.now};function ElementMetrics(element){thi s.element=element;this.width=this.boundingRect.width;this.height=this.boundingRe ct.height;this.size=Math.max(this.width,this.height)}ElementMetrics.prototype={g et boundingRect(){return this.element.getBoundingClientRect()},furthestCornerDis tanceFrom:function(x,y){var topLeft=Utility.distance(x,y,0,0);var topRight=Utili ty.distance(x,y,this.width,0);var bottomLeft=Utility.distance(x,y,0,this.height) ;var bottomRight=Utility.distance(x,y,this.width,this.height);return Math.max(to pLeft,topRight,bottomLeft,bottomRight)}};function Ripple(element){this.element=e lement;this.color=window.getComputedStyle(element).color;this.wave=document.crea teElement("div");this.waveContainer=document.createElement("div");this.wave.styl e.backgroundColor=this.color;this.wave.classList.add("wave");this.waveContainer. classList.add("wave-container");Polymer.dom(this.waveContainer).appendChild(this .wave);this.resetInteractionState()}Ripple.MAX_RADIUS=300;Ripple.prototype={get recenters(){return this.element.recenters},get center(){return this.element.cent er},get mouseDownElapsed(){var elapsed;if(!this.mouseDownStart){return 0}elapsed =Utility.now()-this.mouseDownStart;if(this.mouseUpStart){elapsed-=this.mouseUpEl apsed}return elapsed},get mouseUpElapsed(){return this.mouseUpStart?Utility.now( )-this.mouseUpStart:0},get mouseDownElapsedSeconds(){return this.mouseDownElapse d/1e3},get mouseUpElapsedSeconds(){return this.mouseUpElapsed/1e3},get mouseInte ractionSeconds(){return this.mouseDownElapsedSeconds+this.mouseUpElapsedSeconds} ,get initialOpacity(){return this.element.initialOpacity},get opacityDecayVeloci ty(){return this.element.opacityDecayVelocity},get radius(){var width2=this.cont ainerMetrics.width*this.containerMetrics.width;var height2=this.containerMetrics .height*this.containerMetrics.height;var waveRadius=Math.min(Math.sqrt(width2+he ight2),Ripple.MAX_RADIUS)*1.1+5;var duration=1.1-.2*(waveRadius/Ripple.MAX_RADIU S);var timeNow=this.mouseInteractionSeconds/duration;var size=waveRadius*(1-Math .pow(80,-timeNow));return Math.abs(size)},get opacity(){if(!this.mouseUpStart){r eturn this.initialOpacity}return Math.max(0,this.initialOpacity-this.mouseUpElap sedSeconds*this.opacityDecayVelocity)},get outerOpacity(){var outerOpacity=this. mouseUpElapsedSeconds*.3;var waveOpacity=this.opacity;return Math.max(0,Math.min (outerOpacity,waveOpacity))},get isOpacityFullyDecayed(){return this.opacity<.01 &&this.radius>=Math.min(this.maxRadius,Ripple.MAX_RADIUS)},get isRestingAtMaxRad ius(){return this.opacity>=this.initialOpacity&&this.radius>=Math.min(this.maxRa dius,Ripple.MAX_RADIUS)},get isAnimationComplete(){return this.mouseUpStart?this .isOpacityFullyDecayed:this.isRestingAtMaxRadius},get translationFraction(){retu rn Math.min(1,this.radius/this.containerMetrics.size*2/Math.sqrt(2))},get xNow() {if(this.xEnd){return this.xStart+this.translationFraction*(this.xEnd-this.xStar t)}return this.xStart},get yNow(){if(this.yEnd){return this.yStart+this.translat ionFraction*(this.yEnd-this.yStart)}return this.yStart},get isMouseDown(){return this.mouseDownStart&&!this.mouseUpStart},resetInteractionState:function(){this. maxRadius=0;this.mouseDownStart=0;this.mouseUpStart=0;this.xStart=0;this.yStart= 0;this.xEnd=0;this.yEnd=0;this.slideDistance=0;this.containerMetrics=new Element Metrics(this.element)},draw:function(){var scale;var translateString;var dx;var dy;this.wave.style.opacity=this.opacity;scale=this.radius/(this.containerMetrics .size/2);dx=this.xNow-this.containerMetrics.width/2;dy=this.yNow-this.containerM etrics.height/2;this.waveContainer.style.webkitTransform="translate("+dx+"px, "+ dy+"px)";this.waveContainer.style.transform="translate3d("+dx+"px, "+dy+"px, 0)" ;this.wave.style.webkitTransform="scale("+scale+","+scale+")";this.wave.style.tr ansform="scale3d("+scale+","+scale+",1)"},downAction:function(event){var xCenter =this.containerMetrics.width/2;var yCenter=this.containerMetrics.height/2;this.r esetInteractionState();this.mouseDownStart=Utility.now();if(this.center){this.xS tart=xCenter;this.yStart=yCenter;this.slideDistance=Utility.distance(this.xStart ,this.yStart,this.xEnd,this.yEnd)}else{this.xStart=event?event.detail.x-this.con tainerMetrics.boundingRect.left:this.containerMetrics.width/2;this.yStart=event? event.detail.y-this.containerMetrics.boundingRect.top:this.containerMetrics.heig ht/2}if(this.recenters){this.xEnd=xCenter;this.yEnd=yCenter;this.slideDistance=U tility.distance(this.xStart,this.yStart,this.xEnd,this.yEnd)}this.maxRadius=this .containerMetrics.furthestCornerDistanceFrom(this.xStart,this.yStart);this.waveC ontainer.style.top=(this.containerMetrics.height-this.containerMetrics.size)/2+" px";this.waveContainer.style.left=(this.containerMetrics.width-this.containerMet rics.size)/2+"px";this.waveContainer.style.width=this.containerMetrics.size+"px" ;this.waveContainer.style.height=this.containerMetrics.size+"px"},upAction:funct ion(event){if(!this.isMouseDown){return}this.mouseUpStart=Utility.now()},remove: function(){Polymer.dom(this.waveContainer.parentNode).removeChild(this.waveConta iner)}};Polymer({is:"paper-ripple",behaviors:[Polymer.IronA11yKeysBehavior],prop erties:{initialOpacity:{type:Number,value:.25},opacityDecayVelocity:{type:Number ,value:.8},recenters:{type:Boolean,value:false},center:{type:Boolean,value:false },ripples:{type:Array,value:function(){return[]}},animating:{type:Boolean,readOn ly:true,reflectToAttribute:true,value:false},holdDown:{type:Boolean,value:false, observer:"_holdDownChanged"},noink:{type:Boolean,value:false},_animating:{type:B oolean},_boundAnimate:{type:Function,value:function(){return this.animate.bind(t his)}}},get target(){return this.keyEventTarget},keyBindings:{"enter:keydown":"_ onEnterKeydown","space:keydown":"_onSpaceKeydown","space:keyup":"_onSpaceKeyup"} ,attached:function(){if(this.parentNode.nodeType==11){this.keyEventTarget=Polyme r.dom(this).getOwnerRoot().host}else{this.keyEventTarget=this.parentNode}var key EventTarget=this.keyEventTarget;this.listen(keyEventTarget,"up","uiUpAction");th is.listen(keyEventTarget,"down","uiDownAction")},detached:function(){this.unlist en(this.keyEventTarget,"up","uiUpAction");this.unlisten(this.keyEventTarget,"dow n","uiDownAction");this.keyEventTarget=null},get shouldKeepAnimating(){for(var i ndex=0;index<this.ripples.length;++index){if(!this.ripples[index].isAnimationCom plete){return true}}return false},simulatedRipple:function(){this.downAction(nul l);this.async(function(){this.upAction()},1)},uiDownAction:function(event){if(!t his.noink){this.downAction(event)}},downAction:function(event){if(this.holdDown& &this.ripples.length>0){return}var ripple=this.addRipple();ripple.downAction(eve nt);if(!this._animating){this._animating=true;this.animate()}},uiUpAction:functi on(event){if(!this.noink){this.upAction(event)}},upAction:function(event){if(thi s.holdDown){return}this.ripples.forEach(function(ripple){ripple.upAction(event)} );this._animating=true;this.animate()},onAnimationComplete:function(){this._anim ating=false;this.$.background.style.backgroundColor=null;this.fire("transitionen d")},addRipple:function(){var ripple=new Ripple(this);Polymer.dom(this.$.waves). appendChild(ripple.waveContainer);this.$.background.style.backgroundColor=ripple .color;this.ripples.push(ripple);this._setAnimating(true);return ripple},removeR ipple:function(ripple){var rippleIndex=this.ripples.indexOf(ripple);if(rippleInd ex<0){return}this.ripples.splice(rippleIndex,1);ripple.remove();if(!this.ripples .length){this._setAnimating(false)}},animate:function(){if(!this._animating){ret urn}var index;var ripple;for(index=0;index<this.ripples.length;++index){ripple=t his.ripples[index];ripple.draw();this.$.background.style.opacity=ripple.outerOpa city;if(ripple.isOpacityFullyDecayed&&!ripple.isRestingAtMaxRadius){this.removeR ipple(ripple)}}if(!this.shouldKeepAnimating&&this.ripples.length===0){this.onAni mationComplete()}else{window.requestAnimationFrame(this._boundAnimate)}},_onEnte rKeydown:function(){this.uiDownAction();this.async(this.uiUpAction,1)},_onSpaceK eydown:function(){this.uiDownAction()},_onSpaceKeyup:function(){this.uiUpAction( )},_holdDownChanged:function(newVal,oldVal){if(oldVal===undefined){return}if(new Val){this.downAction()}else{this.upAction()}}})})();Polymer.PaperRippleBehavior= {properties:{noink:{type:Boolean,observer:"_noinkChanged"},_rippleContainer:{typ e:Object}},_buttonStateChanged:function(){if(this.focused){this.ensureRipple()}} ,_downHandler:function(event){Polymer.IronButtonStateImpl._downHandler.call(this ,event);if(this.pressed){this.ensureRipple(event)}},ensureRipple:function(optTri ggeringEvent){if(!this.hasRipple()){this._ripple=this._createRipple();this._ripp le.noink=this.noink;var rippleContainer=this._rippleContainer||this.root;if(ripp leContainer){Polymer.dom(rippleContainer).appendChild(this._ripple)}if(optTrigge ringEvent){var domContainer=Polymer.dom(this._rippleContainer||this);var target= Polymer.dom(optTriggeringEvent).rootTarget;if(domContainer.deepContains(target)) {this._ripple.uiDownAction(optTriggeringEvent)}}}},getRipple:function(){this.ens ureRipple();return this._ripple},hasRipple:function(){return Boolean(this._rippl e)},_createRipple:function(){return document.createElement("paper-ripple")},_noi nkChanged:function(noink){if(this.hasRipple()){this._ripple.noink=noink}}};Polym er.PaperInkyFocusBehaviorImpl={observers:["_focusedChanged(receivedFocusFromKeyb oard)"],_focusedChanged:function(receivedFocusFromKeyboard){if(receivedFocusFrom Keyboard){this.ensureRipple()}if(this.hasRipple()){this._ripple.holdDown=receive dFocusFromKeyboard}},_createRipple:function(){var ripple=Polymer.PaperRippleBeha vior._createRipple();ripple.id="ink";ripple.setAttribute("center","");ripple.cla ssList.add("circle");return ripple}};Polymer.PaperInkyFocusBehavior=[Polymer.Iro nButtonState,Polymer.IronControlState,Polymer.PaperRippleBehavior,Polymer.PaperI nkyFocusBehaviorImpl];Polymer({is:"paper-icon-button",hostAttributes:{role:"butt on",tabindex:"0"},behaviors:[Polymer.PaperInkyFocusBehavior],properties:{src:{ty pe:String},icon:{type:String},alt:{type:String,observer:"_altChanged"}},_altChan ged:function(newValue,oldValue){var label=this.getAttribute("aria-label");if(!la bel||oldValue==label){this.setAttribute("aria-label",newValue)}}});Polymer.Paper SpinnerBehavior={listeners:{animationend:"__reset",webkitAnimationEnd:"__reset"} ,properties:{active:{type:Boolean,value:false,reflectToAttribute:true,observer:" __activeChanged"},alt:{type:String,value:"loading",observer:"__altChanged"},__co olingDown:{type:Boolean,value:false}},__computeContainerClasses:function(active, coolingDown){return[active||coolingDown?"active":"",coolingDown?"cooldown":""].j oin(" ")},__activeChanged:function(active,old){this.__setAriaHidden(!active);thi s.__coolingDown=!active&&old},__altChanged:function(alt){if(alt===this.getProper tyInfo("alt").value){this.alt=this.getAttribute("aria-label")||alt}else{this.__s etAriaHidden(alt==="");this.setAttribute("aria-label",alt)}},__setAriaHidden:fun ction(hidden){var attr="aria-hidden";if(hidden){this.setAttribute(attr,"true")}e lse{this.removeAttribute(attr)}},__reset:function(){this.active=false;this.__coo lingDown=false}};Polymer({is:"paper-spinner-lite",behaviors:[Polymer.PaperSpinne rBehavior]});
21 // Copyright 2016 The Chromium Authors. All rights reserved.
22 // Use of this source code is governed by a BSD-style license that can be
23 // found in the LICENSE file.
24 var CrSearchFieldBehavior={properties:{label:{type:String,value:""},clearLabel:{ type:String,value:""},hasSearchText:{type:Boolean,reflectToAttribute:true,value: false},lastValue_:{type:String,value:""}},getSearchInput:function(){},getValue:f unction(){return this.getSearchInput().value},setValue:function(value,opt_noEven t){var searchInput=this.getSearchInput();searchInput.value=value;this.onSearchTe rmInput();this.onValueChanged_(value,!!opt_noEvent)},onSearchTermSearch:function (){this.onValueChanged_(this.getValue(),false)},onSearchTermInput:function(){thi s.hasSearchText=this.$.searchInput.value!=""},onValueChanged_:function(newValue, noEvent){if(newValue==this.lastValue_)return;this.lastValue_=newValue;if(!noEven t)this.fire("search-changed",newValue)}};
25 // Copyright 2016 The Chromium Authors. All rights reserved.
26 // Use of this source code is governed by a BSD-style license that can be
27 // found in the LICENSE file.
28 Polymer({is:"cr-toolbar-search-field",behaviors:[CrSearchFieldBehavior],properti es:{narrow:{type:Boolean,reflectToAttribute:true},showingSearch:{type:Boolean,va lue:false,notify:true,observer:"showingSearchChanged_",reflectToAttribute:true}, label:String,clearLabel:String,spinnerActive:{type:Boolean,reflectToAttribute:tr ue},isSpinnerShown_:{type:Boolean,computed:"computeIsSpinnerShown_(spinnerActive , showingSearch)"},searchFocused_:{type:Boolean,value:false}},listeners:{click:" showSearch_"},getSearchInput:function(){return this.$.searchInput},isSearchFocus ed:function(){return this.searchFocused_},showAndFocus:function(){this.showingSe arch=true;this.focus_()},onSearchTermInput:function(){CrSearchFieldBehavior.onSe archTermInput.call(this);this.showingSearch=this.hasSearchText||this.isSearchFoc used()},focus_:function(){this.getSearchInput().focus()},computeIconTabIndex_:fu nction(narrow){return narrow?0:-1},computeIsSpinnerShown_:function(){return this .spinnerActive&&this.showingSearch},onInputFocus_:function(){this.searchFocused_ =true},onInputBlur_:function(){this.searchFocused_=false;if(!this.hasSearchText) this.showingSearch=false},onSearchTermKeydown_:function(e){if(e.key=="Escape")th is.showingSearch=false},showSearch_:function(e){if(e.target!=this.$.clearSearch) this.showingSearch=true},clearSearch_:function(e){this.setValue("");this.focus_( )},showingSearchChanged_:function(current,previous){if(previous==undefined)retur n;if(this.showingSearch){this.focus_();return}this.setValue("");this.getSearchIn put().blur()}});
29 // Copyright 2016 The Chromium Authors. All rights reserved.
30 // Use of this source code is governed by a BSD-style license that can be
31 // found in the LICENSE file.
32 Polymer({is:"cr-toolbar",properties:{pageName:String,searchPrompt:String,clearLa bel:String,menuLabel:String,menuPromo:String,spinnerActive:Boolean,showMenu:{typ e:Boolean,value:false},showMenuPromo:{type:Boolean,value:false},closeMenuPromo:S tring,narrow_:{type:Boolean,reflectToAttribute:true},showingSearch_:{type:Boolea n,reflectToAttribute:true}},observers:["possiblyShowMenuPromo_(showMenu, showMen uPromo, showingSearch_)"],getSearchField:function(){return this.$.search},onClos ePromoTap_:function(){this.fire("cr-toolbar-menu-promo-close")},onMenuTap_:funct ion(){this.fire("cr-toolbar-menu-tap")},possiblyShowMenuPromo_:function(){Polyme r.RenderStatus.afterNextRender(this,function(){if(this.showMenu&&this.showMenuPr omo&&!this.showingSearch_){this.$$("#menuPromo").animate({opacity:[0,.9]},{durat ion:500,fill:"forwards"});this.fire("cr-toolbar-menu-promo-shown")}}.bind(this)) },titleIfNotShowMenuPromo_:function(title,showMenuPromo){return showMenuPromo?"" :title}});
33 // Copyright 2016 The Chromium Authors. All rights reserved.
34 // Use of this source code is governed by a BSD-style license that can be
35 // found in the LICENSE file.
36 cr.define("md_history",function(){function BrowserService(){this.pendingDeleteIt ems_=null;this.pendingDeletePromise_=null}BrowserService.prototype={deleteItems: function(items){if(this.pendingDeleteItems_!=null){return new Promise(function(r esolve,reject){reject(items)})}var removalList=items.map(function(item){return{u rl:item.url,timestamps:item.allTimestamps}});this.pendingDeleteItems_=items;this .pendingDeletePromise_=new PromiseResolver;chrome.send("removeVisits",removalLis t);return this.pendingDeletePromise_.promise},removeBookmark:function(url){chrom e.send("removeBookmark",[url])},openForeignSessionAllTabs:function(sessionTag){c hrome.send("openForeignSession",[sessionTag])},openForeignSessionTab:function(se ssionTag,windowId,tabId,e){chrome.send("openForeignSession",[sessionTag,String(w indowId),String(tabId),e.button||0,e.altKey,e.ctrlKey,e.metaKey,e.shiftKey])},de leteForeignSession:function(sessionTag){chrome.send("deleteForeignSession",[sess ionTag])},openClearBrowsingData:function(){chrome.send("clearBrowsingData")},rec ordHistogram:function(histogram,value,max){chrome.send("metricsHandler:recordInH istogram",[histogram,value,max])},recordAction:function(action){if(action.indexO f("_")==-1)action="HistoryPage_"+action;chrome.send("metricsHandler:recordAction ",[action])},resolveDelete_:function(successful){if(this.pendingDeleteItems_==nu ll||this.pendingDeletePromise_==null){return}if(successful)this.pendingDeletePro mise_.resolve(this.pendingDeleteItems_);else this.pendingDeletePromise_.reject(t his.pendingDeleteItems_);this.pendingDeleteItems_=null;this.pendingDeletePromise _=null},menuPromoShown:function(){chrome.send("menuPromoShown")}};cr.addSingleto nGetter(BrowserService);return{BrowserService:BrowserService}});function deleteC omplete(){md_history.BrowserService.getInstance().resolveDelete_(true)}function deleteFailed(){md_history.BrowserService.getInstance().resolveDelete_(false)}
37 // Copyright 2015 The Chromium Authors. All rights reserved.
38 // Use of this source code is governed by a BSD-style license that can be
39 // found in the LICENSE file.
40 Polymer({is:"history-toolbar",properties:{count:{type:Number,value:0,observer:"c hangeToolbarView_"},itemsSelected_:{type:Boolean,value:false,reflectToAttribute: true},searchTerm:{type:String,observer:"searchTermChanged_"},spinnerActive:{type :Boolean,value:false},hasDrawer:{type:Boolean,reflectToAttribute:true},groupedRa nge:{type:Number,reflectToAttribute:true},showGroupedControls:{type:Boolean,refl ectToAttribute:true},showSyncNotice:{type:Boolean,observer:"showSyncNoticeChange d_"},syncNoticeVisible_:{type:Boolean,value:false},hasMoreResults:Boolean,groupe dOffset:Number,isGroupedMode:Boolean,querying:Boolean,queryInfo:Object,showMenuP romo:Boolean},hasDismissListeners_:false,boundOnDocumentClick_:null,boundOnDocum entKeydown_:null,detached:function(){if(this.hasDismissListeners_){document.remo veEventListener("click",this.boundOnDocumentClick_);document.removeEventListener ("keydown",this.boundOnDocumentKeydown_)}},get searchField(){return this.$["main -toolbar"].getSearchField()},showSearchField:function(){this.searchField.showAnd Focus()},changeToolbarView_:function(){this.itemsSelected_=this.count>0},searchT ermChanged_:function(){if(this.searchField.getValue()!=this.searchTerm){this.sea rchField.showAndFocus();this.searchField.setValue(this.searchTerm)}},showSyncNot iceChanged_:function(){if(!this.showSyncNotice)this.syncNoticeVisible_=false},on SearchChanged_:function(event){this.fire("change-query",{search:event.detail})}, onInfoButtonTap_:function(e){this.syncNoticeVisible_=!this.syncNoticeVisible_;e. stopPropagation();if(this.hasDismissListeners_)return;this.boundOnDocumentClick_ =this.onDocumentClick_.bind(this);this.boundOnDocumentKeydown_=this.onDocumentKe ydown_.bind(this);document.addEventListener("click",this.boundOnDocumentClick_); document.addEventListener("keydown",this.boundOnDocumentKeydown_);this.hasDismis sListeners_=true},onDocumentClick_:function(e){if(e.path.indexOf(this.$["sync-no tice"])==-1)this.syncNoticeVisible_=false},onDocumentKeydown_:function(e){if(e.k ey=="Escape")this.syncNoticeVisible_=false},onClearSelectionTap_:function(){this .fire("unselect-all")},onDeleteTap_:function(){this.fire("delete-selected")},del etingAllowed_:function(){return loadTimeData.getBoolean("allowDeletingHistory")} ,numberOfItemsSelected_:function(count){return count>0?loadTimeData.getStringF(" itemsSelected",count):""},getHistoryInterval_:function(){var info=this.queryInfo ;if(!info)return;if(this.groupedRange==HistoryRange.WEEK)return info.queryInterv al;if(this.groupedRange==HistoryRange.MONTH)return info.queryStartMonth},onTabSe lected_:function(e){this.fire("change-query",{range:Number(e.detail.item.getAttr ibute("value"))})},changeOffset_:function(newOffset){if(!this.querying)this.fire ("change-query",{offset:newOffset})},onTodayTap_:function(){this.changeOffset_(0 )},onPrevTap_:function(){this.changeOffset_(this.groupedOffset+1)},onNextTap_:fu nction(){this.changeOffset_(this.groupedOffset-1)},isToday_:function(){return th is.groupedOffset==0}});(function(){"use strict";Polymer.IronA11yAnnouncer=Polyme r({is:"iron-a11y-announcer",properties:{mode:{type:String,value:"polite"},_text: {type:String,value:""}},created:function(){if(!Polymer.IronA11yAnnouncer.instanc e){Polymer.IronA11yAnnouncer.instance=this}document.body.addEventListener("iron- announce",this._onIronAnnounce.bind(this))},announce:function(text){this._text=" ";this.async(function(){this._text=text},100)},_onIronAnnounce:function(event){i f(event.detail&&event.detail.text){this.announce(event.detail.text)}}});Polymer. IronA11yAnnouncer.instance=null;Polymer.IronA11yAnnouncer.requestAvailability=fu nction(){if(!Polymer.IronA11yAnnouncer.instance){Polymer.IronA11yAnnouncer.insta nce=document.createElement("iron-a11y-announcer")}document.body.appendChild(Poly mer.IronA11yAnnouncer.instance)}})();(function(){var IOS=navigator.userAgent.mat ch(/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:{typ e:Array},maxPhysicalCount:{type:Number,value:500},as:{type:String,value:"item"}, indexAs:{type:String,value:"index"},selectedAs:{type:String,value:"selected"},gr id:{type:Boolean,value:false,reflectToAttribute:true},selectionEnabled:{type:Boo lean,value:false},selectedItem:{type:Object,notify:true},selectedItems:{type:Obj ect,notify:true},multiSelection:{type:Boolean,value:false}},observers:["_itemsCh anged(items.*)","_selectionEnabledChanged(selectionEnabled)","_multiSelectionCha nged(multiSelection)","_setOverflow(scrollTarget)"],behaviors:[Polymer.Templatiz er,Polymer.IronResizableBehavior,Polymer.IronA11yKeysBehavior,Polymer.IronScroll TargetBehavior],keyBindings:{up:"_didMoveUp",down:"_didMoveDown",enter:"_didEnte r"},_ratio:.5,_scrollerPaddingTop:0,_scrollPosition:0,_physicalSize:0,_physicalA verage:0,_physicalAverageCount:0,_physicalTop:0,_virtualCount:0,_physicalIndexFo rKey:null,_estScrollHeight:0,_scrollHeight:0,_viewportHeight:0,_viewportWidth:0, _physicalItems:null,_physicalSizes:null,_firstVisibleIndexVal:null,_lastVisibleI ndexVal:null,_collection:null,_maxPages:2,_focusedItem:null,_focusedIndex:-1,_of fscreenFocusedItem:null,_focusBackfillItem:null,_itemsPerRow:1,_itemWidth:0,_row Height:0,_templateCost:0,get _physicalBottom(){return this._physicalTop+this._ph ysicalSize},get _scrollBottom(){return this._scrollPosition+this._viewportHeight },get _virtualEnd(){return this._virtualStart+this._physicalCount-1},get _hidden ContentSize(){var size=this.grid?this._physicalRows*this._rowHeight:this._physic alSize;return size-this._viewportHeight},get _maxScrollTop(){return this._estScr ollHeight-this._viewportHeight+this._scrollerPaddingTop},_minVirtualStart:0,get _maxVirtualStart(){return Math.max(0,this._virtualCount-this._physicalCount)},_v irtualStartVal:0,set _virtualStart(val){this._virtualStartVal=Math.min(this._max VirtualStart,Math.max(this._minVirtualStart,val))},get _virtualStart(){return th is._virtualStartVal||0},_physicalStartVal:0,set _physicalStart(val){this._physic alStartVal=val%this._physicalCount;if(this._physicalStartVal<0){this._physicalSt artVal=this._physicalCount+this._physicalStartVal}this._physicalEnd=(this._physi calStart+this._physicalCount-1)%this._physicalCount},get _physicalStart(){return this._physicalStartVal||0},_physicalCountVal:0,set _physicalCount(val){this._ph ysicalCountVal=val;this._physicalEnd=(this._physicalStart+this._physicalCount-1) %this._physicalCount},get _physicalCount(){return this._physicalCountVal},_physi calEnd:0,get _optPhysicalSize(){if(this.grid){return this._estRowsInView*this._r owHeight*this._maxPages}return this._viewportHeight*this._maxPages},get _isVisib le(){return Boolean(this.offsetWidth||this.offsetHeight)},get firstVisibleIndex( ){if(this._firstVisibleIndexVal===null){var physicalOffset=Math.floor(this._phys icalTop+this._scrollerPaddingTop);this._firstVisibleIndexVal=this._iterateItems( function(pidx,vidx){physicalOffset+=this._getPhysicalSizeIncrement(pidx);if(phys icalOffset>this._scrollPosition){return this.grid?vidx-vidx%this._itemsPerRow:vi dx}if(this.grid&&this._virtualCount-1===vidx){return vidx-vidx%this._itemsPerRow }})||0}return this._firstVisibleIndexVal},get lastVisibleIndex(){if(this._lastVi sibleIndexVal===null){if(this.grid){var lastIndex=this.firstVisibleIndex+this._e stRowsInView*this._itemsPerRow-1;this._lastVisibleIndexVal=Math.min(this._virtua lCount,lastIndex)}else{var physicalOffset=this._physicalTop;this._iterateItems(f unction(pidx,vidx){if(physicalOffset<this._scrollBottom){this._lastVisibleIndexV al=vidx}else{return true}physicalOffset+=this._getPhysicalSizeIncrement(pidx)})} }return this._lastVisibleIndexVal},get _defaultScrollTarget(){return this},get _ virtualRowCount(){return Math.ceil(this._virtualCount/this._itemsPerRow)},get _e stRowsInView(){return Math.ceil(this._viewportHeight/this._rowHeight)},get _phys icalRows(){return Math.ceil(this._physicalCount/this._itemsPerRow)},ready:functi on(){this.addEventListener("focus",this._didFocus.bind(this),true)},attached:fun ction(){if(this._physicalCount===0){this._debounceTemplate(this._render)}this.li sten(this,"iron-resize","_resizeHandler")},detached:function(){this.unlisten(thi s,"iron-resize","_resizeHandler")},_setOverflow:function(scrollTarget){this.styl e.webkitOverflowScrolling=scrollTarget===this?"touch":"";this.style.overflow=scr ollTarget===this?"auto":""},updateViewportBoundaries:function(){this._scrollerPa ddingTop=this.scrollTarget===this?0:parseInt(window.getComputedStyle(this)["padd ing-top"],10);this._viewportWidth=this.$.items.offsetWidth;this._viewportHeight= this._scrollTargetHeight;this.grid&&this._updateGridMetrics()},_scrollHandler:fu nction(){var scrollTop=Math.max(0,Math.min(this._maxScrollTop,this._scrollTop)); var delta=scrollTop-this._scrollPosition;var isScrollingDown=delta>=0;this._scro llPosition=scrollTop;this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=n ull;if(Math.abs(delta)>this._physicalSize){var idxAdjustment=Math.round(delta/th is._physicalAverage)*this._itemsPerRow;this._physicalTop=this._physicalTop+delta ;this._virtualStart=this._virtualStart+idxAdjustment;this._physicalStart=this._p hysicalStart+idxAdjustment;this._update()}else{var reusables=this._getReusables( isScrollingDown);if(isScrollingDown){this._physicalTop=reusables.physicalTop;thi s._virtualStart=this._virtualStart+reusables.indexes.length;this._physicalStart= this._physicalStart+reusables.indexes.length}else{this._virtualStart=this._virtu alStart-reusables.indexes.length;this._physicalStart=this._physicalStart-reusabl es.indexes.length}if(reusables.indexes.length===0){this._increasePoolIfNeeded()} else{this._update(reusables.indexes,isScrollingDown?null:reusables.indexes)}}},_ getReusables:function(fromTop){var ith,lastIth,offsetContent,physicalItemHeight; var idxs=[];var protectedOffsetContent=this._hiddenContentSize*this._ratio;var v irtualStart=this._virtualStart;var virtualEnd=this._virtualEnd;var physicalCount =this._physicalCount;var physicalTop=this._physicalTop+this._scrollerPaddingTop; var scrollTop=this._scrollTop;var scrollBottom=this._scrollBottom;if(fromTop){it h=this._physicalStart;lastIth=this._physicalEnd;offsetContent=scrollTop-physical Top}else{ith=this._physicalEnd;lastIth=this._physicalStart;offsetContent=this._p hysicalBottom-scrollBottom}while(true){physicalItemHeight=this._getPhysicalSizeI ncrement(ith);offsetContent=offsetContent-physicalItemHeight;if(idxs.length>=phy sicalCount||offsetContent<=protectedOffsetContent){break}if(fromTop){if(virtualE nd+idxs.length+1>=this._virtualCount){break}if(physicalTop+physicalItemHeight>=s crollTop){break}idxs.push(ith);physicalTop=physicalTop+physicalItemHeight;ith=(i th+1)%physicalCount}else{if(virtualStart-idxs.length<=0){break}if(physicalTop+th is._physicalSize-physicalItemHeight<=scrollBottom){break}idxs.push(ith);physical Top=physicalTop-physicalItemHeight;ith=ith===0?physicalCount-1:ith-1}}return{ind exes:idxs,physicalTop:physicalTop-this._scrollerPaddingTop}},_update:function(it emSet,movingUp){if(itemSet&&itemSet.length===0){return}this._manageFocus();this. _assignModels(itemSet);this._updateMetrics(itemSet);if(movingUp){while(movingUp. length){var idx=movingUp.pop();this._physicalTop-=this._getPhysicalSizeIncrement (idx)}}this._positionItems();this._updateScrollerSize();this._increasePoolIfNeed ed()},_createPool:function(size){var physicalItems=new Array(size);this._ensureT emplatized();for(var i=0;i<size;i++){var inst=this.stamp(null);physicalItems[i]= inst.root.querySelector("*");Polymer.dom(this).appendChild(inst.root)}return phy sicalItems},_increasePoolIfNeeded:function(){if(this._viewportHeight===0){return false}var self=this;var isClientFull=this._physicalBottom>=this._scrollBottom&& this._physicalTop<=this._scrollPosition;if(this._physicalSize>=this._optPhysical Size&&isClientFull){return false}var maxPoolSize=Math.round(this._physicalCount* .5);if(!isClientFull){this._debounceTemplate(this._increasePool.bind(this,maxPoo lSize));return true}this._yield(function(){self._increasePool(Math.min(maxPoolSi ze,Math.max(1,Math.round(50/self._templateCost))))});return true},_yield:functio n(cb){var g=window;var handle=g.requestIdleCallback?g.requestIdleCallback(cb):g. setTimeout(cb,16);Polymer.dom.addDebouncer({complete:function(){g.cancelIdleCall back?g.cancelIdleCallback(handle):g.clearTimeout(handle);cb()}})},_increasePool: function(missingItems){var nextPhysicalCount=Math.min(this._physicalCount+missin gItems,this._virtualCount-this._virtualStart,Math.max(this.maxPhysicalCount,DEFA ULT_PHYSICAL_COUNT));var prevPhysicalCount=this._physicalCount;var delta=nextPhy sicalCount-prevPhysicalCount;var ts=window.performance.now();if(delta<=0){return }[].push.apply(this._physicalItems,this._createPool(delta));[].push.apply(this._ physicalSizes,new Array(delta));this._physicalCount=prevPhysicalCount+delta;if(t his._physicalStart>this._physicalEnd&&this._isIndexRendered(this._focusedIndex)& &this._getPhysicalIndex(this._focusedIndex)<this._physicalEnd){this._physicalSta rt=this._physicalStart+delta}this._update();this._templateCost=(window.performan ce.now()-ts)/delta},_render:function(){if(this.isAttached&&this._isVisible){if(t his._physicalCount===0){this.updateViewportBoundaries();this._increasePool(DEFAU LT_PHYSICAL_COUNT)}else{var reusables=this._getReusables(true);this._physicalTop =reusables.physicalTop;this._virtualStart=this._virtualStart+reusables.indexes.l ength;this._physicalStart=this._physicalStart+reusables.indexes.length;this._upd ate(reusables.indexes);this._update()}}},_ensureTemplatized:function(){if(!this. ctor){var props={};props.__key__=true;props[this.as]=true;props[this.indexAs]=tr ue;props[this.selectedAs]=true;props.tabIndex=true;this._instanceProps=props;thi s._userTemplate=Polymer.dom(this).querySelector("template");if(this._userTemplat e){this.templatize(this._userTemplate)}else{console.warn("iron-list requires a t emplate to be provided in light-dom")}}},_getStampedChildren:function(){return t his._physicalItems},_forwardInstancePath:function(inst,path,value){if(path.index Of(this.as+".")===0){this.notifyPath("items."+inst.__key__+"."+path.slice(this.a s.length+1),value)}},_forwardParentProp:function(prop,value){if(this._physicalIt ems){this._physicalItems.forEach(function(item){item._templateInstance[prop]=val ue},this)}},_forwardParentPath:function(path,value){if(this._physicalItems){this ._physicalItems.forEach(function(item){item._templateInstance.notifyPath(path,va lue,true)},this)}},_forwardItemPath:function(path,value){if(!this._physicalIndex ForKey){return}var dot=path.indexOf(".");var key=path.substring(0,dot<0?path.len gth:dot);var idx=this._physicalIndexForKey[key];var offscreenItem=this._offscree nFocusedItem;var el=offscreenItem&&offscreenItem._templateInstance.__key__===key ?offscreenItem:this._physicalItems[idx];if(!el||el._templateInstance.__key__!==k ey){return}if(dot>=0){path=this.as+"."+path.substring(dot+1);el._templateInstanc e.notifyPath(path,value,true)}else{var currentItem=el._templateInstance[this.as] ;if(Array.isArray(this.selectedItems)){for(var i=0;i<this.selectedItems.length;i ++){if(this.selectedItems[i]===currentItem){this.set("selectedItems."+i,value);b reak}}}else if(this.selectedItem===currentItem){this.set("selectedItem",value)}e l._templateInstance[this.as]=value}},_itemsChanged:function(change){if(change.pa th==="items"){this._virtualStart=0;this._physicalTop=0;this._virtualCount=this.i tems?this.items.length:0;this._collection=this.items?Polymer.Collection.get(this .items):null;this._physicalIndexForKey={};this._firstVisibleIndexVal=null;this._ lastVisibleIndexVal=null;this._physicalCount=this._physicalCount||0;this._physic alItems=this._physicalItems||[];this._physicalSizes=this._physicalSizes||[];this ._physicalStart=0;this._resetScrollPosition(0);this._removeFocusedItem();this._d ebounceTemplate(this._render)}else if(change.path==="items.splices"){this._adjus tVirtualIndex(change.value.indexSplices);this._virtualCount=this.items?this.item s.length:0;this._debounceTemplate(this._render)}else{this._forwardItemPath(chang e.path.split(".").slice(1).join("."),change.value)}},_adjustVirtualIndex:functio n(splices){splices.forEach(function(splice){splice.removed.forEach(this._removeI tem,this);if(splice.index<this._virtualStart){var delta=Math.max(splice.addedCou nt-splice.removed.length,splice.index-this._virtualStart);this._virtualStart=thi s._virtualStart+delta;if(this._focusedIndex>=0){this._focusedIndex=this._focused Index+delta}}},this)},_removeItem:function(item){this.$.selector.deselect(item); if(this._focusedItem&&this._focusedItem._templateInstance[this.as]===item){this. _removeFocusedItem()}},_iterateItems:function(fn,itemSet){var pidx,vidx,rtn,i;if (arguments.length===2&&itemSet){for(i=0;i<itemSet.length;i++){pidx=itemSet[i];vi dx=this._computeVidx(pidx);if((rtn=fn.call(this,pidx,vidx))!=null){return rtn}}} else{pidx=this._physicalStart;vidx=this._virtualStart;for(;pidx<this._physicalCo unt;pidx++,vidx++){if((rtn=fn.call(this,pidx,vidx))!=null){return rtn}}for(pidx= 0;pidx<this._physicalStart;pidx++,vidx++){if((rtn=fn.call(this,pidx,vidx))!=null ){return rtn}}}},_computeVidx:function(pidx){if(pidx>=this._physicalStart){retur n this._virtualStart+(pidx-this._physicalStart)}return this._virtualStart+(this. _physicalCount-this._physicalStart)+pidx},_assignModels:function(itemSet){this._ iterateItems(function(pidx,vidx){var el=this._physicalItems[pidx];var inst=el._t emplateInstance;var item=this.items&&this.items[vidx];if(item!=null){inst[this.a s]=item;inst.__key__=this._collection.getKey(item);inst[this.selectedAs]=this.$. selector.isSelected(item);inst[this.indexAs]=vidx;inst.tabIndex=this._focusedInd ex===vidx?0:-1;this._physicalIndexForKey[inst.__key__]=pidx;el.removeAttribute(" hidden")}else{inst.__key__=null;el.setAttribute("hidden","")}},itemSet)},_update Metrics:function(itemSet){Polymer.dom.flush();var newPhysicalSize=0;var oldPhysi calSize=0;var prevAvgCount=this._physicalAverageCount;var prevPhysicalAvg=this._ physicalAverage;this._iterateItems(function(pidx,vidx){oldPhysicalSize+=this._ph ysicalSizes[pidx]||0;this._physicalSizes[pidx]=this._physicalItems[pidx].offsetH eight;newPhysicalSize+=this._physicalSizes[pidx];this._physicalAverageCount+=thi s._physicalSizes[pidx]?1:0},itemSet);if(this.grid){this._updateGridMetrics();thi s._physicalSize=Math.ceil(this._physicalCount/this._itemsPerRow)*this._rowHeight }else{this._physicalSize=this._physicalSize+newPhysicalSize-oldPhysicalSize}if(t his._physicalAverageCount!==prevAvgCount){this._physicalAverage=Math.round((prev PhysicalAvg*prevAvgCount+newPhysicalSize)/this._physicalAverageCount)}},_updateG ridMetrics:function(){this._itemWidth=this._physicalCount>0?this._physicalItems[ 0].getBoundingClientRect().width:200;this._rowHeight=this._physicalCount>0?this. _physicalItems[0].offsetHeight:200;this._itemsPerRow=this._itemWidth?Math.floor( this._viewportWidth/this._itemWidth):this._itemsPerRow},_positionItems:function( ){this._adjustScrollPosition();var y=this._physicalTop;if(this.grid){var totalIt emWidth=this._itemsPerRow*this._itemWidth;var rowOffset=(this._viewportWidth-tot alItemWidth)/2;this._iterateItems(function(pidx,vidx){var modulus=vidx%this._ite msPerRow;var x=Math.floor(modulus*this._itemWidth+rowOffset);this.translate3d(x+ "px",y+"px",0,this._physicalItems[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]})}},_getPhysi calSizeIncrement:function(pidx){if(!this.grid){return this._physicalSizes[pidx]} if(this._computeVidx(pidx)%this._itemsPerRow!==this._itemsPerRow-1){return 0}ret urn this._rowHeight},_shouldRenderNextRow:function(vidx){return vidx%this._items PerRow===this._itemsPerRow-1},_adjustScrollPosition:function(){var deltaHeight=t his._virtualStart===0?this._physicalTop:Math.min(this._scrollPosition+this._phys icalTop,0);if(deltaHeight){this._physicalTop=this._physicalTop-deltaHeight;if(!I OS_TOUCH_SCROLLING&&this._physicalTop!==0){this._resetScrollPosition(this._scrol lTop-deltaHeight)}}},_resetScrollPosition:function(pos){if(this.scrollTarget){th is._scrollTop=pos;this._scrollPosition=this._scrollTop}},_updateScrollerSize:fun ction(forceUpdate){if(this.grid){this._estScrollHeight=this._virtualRowCount*thi s._rowHeight}else{this._estScrollHeight=this._physicalBottom+Math.max(this._virt ualCount-this._physicalCount-this._virtualStart,0)*this._physicalAverage}forceUp date=forceUpdate||this._scrollHeight===0;forceUpdate=forceUpdate||this._scrollPo sition>=this._estScrollHeight-this._physicalSize;forceUpdate=forceUpdate||this.g rid&&this.$.items.style.height<this._estScrollHeight;if(forceUpdate||Math.abs(th is._estScrollHeight-this._scrollHeight)>=this._optPhysicalSize){this.$.items.sty le.height=this._estScrollHeight+"px";this._scrollHeight=this._estScrollHeight}}, scrollToItem:function(item){return this.scrollToIndex(this.items.indexOf(item))} ,scrollToIndex:function(idx){if(typeof idx!=="number"||idx<0||idx>this.items.len gth-1){return}Polymer.dom.flush();if(this._physicalCount===0){return}idx=Math.mi n(Math.max(idx,0),this._virtualCount-1);if(!this._isIndexRendered(idx)||idx>=thi s._maxVirtualStart){this._virtualStart=this.grid?idx-this._itemsPerRow*2:idx-1}t his._manageFocus();this._assignModels();this._updateMetrics();this._physicalTop= Math.floor(this._virtualStart/this._itemsPerRow)*this._physicalAverage;var curre ntTopItem=this._physicalStart;var currentVirtualItem=this._virtualStart;var targ etOffsetTop=0;var hiddenContentSize=this._hiddenContentSize;while(currentVirtual Item<idx&&targetOffsetTop<=hiddenContentSize){targetOffsetTop=targetOffsetTop+th is._getPhysicalSizeIncrement(currentTopItem);currentTopItem=(currentTopItem+1)%t his._physicalCount;currentVirtualItem++}this._updateScrollerSize(true);this._pos itionItems();this._resetScrollPosition(this._physicalTop+this._scrollerPaddingTo p+targetOffsetTop);this._increasePoolIfNeeded();this._firstVisibleIndexVal=null; this._lastVisibleIndexVal=null},_resetAverage:function(){this._physicalAverage=0 ;this._physicalAverageCount=0},_resizeHandler:function(){var delta=Math.abs(this ._viewportHeight-this._scrollTargetHeight);if(IOS&&delta>0&&delta<100){return}Po lymer.dom.addDebouncer(this.debounce("_debounceTemplate",function(){this.updateV iewportBoundaries();this._render();if(this._isVisible){this.toggleScrollListener (true);if(this._physicalCount>0){this._resetAverage();this.scrollToIndex(this.fi rstVisibleIndex)}}else{this.toggleScrollListener(false)}}.bind(this),1))},_getMo delFromItem:function(item){var key=this._collection.getKey(item);var pidx=this._ physicalIndexForKey[key];if(pidx!=null){return this._physicalItems[pidx]._templa teInstance}return null},_getNormalizedItem:function(item){if(this._collection.ge tKey(item)===undefined){if(typeof item==="number"){item=this.items[item];if(!ite m){throw new RangeError("<item> not found")}return item}throw new TypeError("<it em> should be a valid item")}return item},selectItem:function(item){item=this._g etNormalizedItem(item);var model=this._getModelFromItem(item);if(!this.multiSele ction&&this.selectedItem){this.deselectItem(this.selectedItem)}if(model){model[t his.selectedAs]=true}this.$.selector.select(item);this.updateSizeForItem(item)}, deselectItem:function(item){item=this._getNormalizedItem(item);var model=this._g etModelFromItem(item);if(model){model[this.selectedAs]=false}this.$.selector.des elect(item);this.updateSizeForItem(item)},toggleSelectionForItem:function(item){ item=this._getNormalizedItem(item);if(this.$.selector.isSelected(item)){this.des electItem(item)}else{this.selectItem(item)}},clearSelection:function(){function unselect(item){var model=this._getModelFromItem(item);if(model){model[this.selec tedAs]=false}}if(Array.isArray(this.selectedItems)){this.selectedItems.forEach(u nselect,this)}else if(this.selectedItem){unselect.call(this,this.selectedItem)}t his.$.selector.clearSelection()},_selectionEnabledChanged:function(selectionEnab led){var handler=selectionEnabled?this.listen:this.unlisten;handler.call(this,th is,"tap","_selectionHandler")},_selectionHandler:function(e){var model=this.mode lForElement(e.target);if(!model){return}var modelTabIndex,activeElTabIndex;var t arget=Polymer.dom(e).path[0];var activeEl=Polymer.dom(this.domHost?this.domHost. root:document).activeElement;var physicalItem=this._physicalItems[this._getPhysi calIndex(model[this.indexAs])];if(target.localName==="input"||target.localName== ="button"||target.localName==="select"){return}modelTabIndex=model.tabIndex;mode l.tabIndex=SECRET_TABINDEX;activeElTabIndex=activeEl?activeEl.tabIndex:-1;model. tabIndex=modelTabIndex;if(activeEl&&physicalItem!==activeEl&&physicalItem.contai ns(activeEl)&&activeElTabIndex!==SECRET_TABINDEX){return}this.toggleSelectionFor Item(model[this.as])},_multiSelectionChanged:function(multiSelection){this.clear Selection();this.$.selector.multi=multiSelection},updateSizeForItem:function(ite m){item=this._getNormalizedItem(item);var key=this._collection.getKey(item);var pidx=this._physicalIndexForKey[key];if(pidx!=null){this._updateMetrics([pidx]);t his._positionItems()}},_manageFocus:function(){var fidx=this._focusedIndex;if(fi dx>=0&&fidx<this._virtualCount){if(this._isIndexRendered(fidx)){this._restoreFoc usedItem()}else{this._createFocusBackfillItem()}}else if(this._virtualCount>0&&t his._physicalCount>0){this._focusedIndex=this._virtualStart;this._focusedItem=th is._physicalItems[this._physicalStart]}},_isIndexRendered:function(idx){return i dx>=this._virtualStart&&idx<=this._virtualEnd},_isIndexVisible:function(idx){ret urn idx>=this.firstVisibleIndex&&idx<=this.lastVisibleIndex},_getPhysicalIndex:f unction(idx){return this._physicalIndexForKey[this._collection.getKey(this._getN ormalizedItem(idx))]},_focusPhysicalItem:function(idx){if(idx<0||idx>=this._virt ualCount){return}this._restoreFocusedItem();if(!this._isIndexRendered(idx)){this .scrollToIndex(idx)}var physicalItem=this._physicalItems[this._getPhysicalIndex( idx)];var model=physicalItem._templateInstance;var focusable;model.tabIndex=SECR ET_TABINDEX;if(physicalItem.tabIndex===SECRET_TABINDEX){focusable=physicalItem}i f(!focusable){focusable=Polymer.dom(physicalItem).querySelector('[tabindex="'+SE CRET_TABINDEX+'"]')}model.tabIndex=0;this._focusedIndex=idx;focusable&&focusable .focus()},_removeFocusedItem:function(){if(this._offscreenFocusedItem){Polymer.d om(this).removeChild(this._offscreenFocusedItem)}this._offscreenFocusedItem=null ;this._focusBackfillItem=null;this._focusedItem=null;this._focusedIndex=-1},_cre ateFocusBackfillItem:function(){var fidx=this._focusedIndex;var pidx=this._getPh ysicalIndex(fidx);if(this._offscreenFocusedItem||pidx==null||fidx<0){return}if(! this._focusBackfillItem){var stampedTemplate=this.stamp(null);this._focusBackfil lItem=stampedTemplate.root.querySelector("*");Polymer.dom(this).appendChild(stam pedTemplate.root)}this._offscreenFocusedItem=this._physicalItems[pidx];this._off screenFocusedItem._templateInstance.tabIndex=0;this._physicalItems[pidx]=this._f ocusBackfillItem;this.translate3d(0,HIDDEN_Y,0,this._offscreenFocusedItem)},_res toreFocusedItem:function(){var pidx,fidx=this._focusedIndex;if(!this._offscreenF ocusedItem||this._focusedIndex<0){return}this._assignModels();pidx=this._getPhys icalIndex(fidx);if(pidx!=null){this._focusBackfillItem=this._physicalItems[pidx] ;this._focusBackfillItem._templateInstance.tabIndex=-1;this._physicalItems[pidx] =this._offscreenFocusedItem;this._offscreenFocusedItem=null;this.translate3d(0,H IDDEN_Y,0,this._focusBackfillItem)}},_didFocus:function(e){var targetModel=this. modelForElement(e.target);var focusedModel=this._focusedItem?this._focusedItem._ templateInstance:null;var hasOffscreenFocusedItem=this._offscreenFocusedItem!==n ull;var fidx=this._focusedIndex;if(!targetModel||!focusedModel){return}if(focuse dModel===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._p hysicalItems[this._getPhysicalIndex(fidx)];if(hasOffscreenFocusedItem&&!this._of fscreenFocusedItem){this._update()}}},_didMoveUp:function(){this._focusPhysicalI tem(this._focusedIndex-1)},_didMoveDown:function(e){e.detail.keyboardEvent.preve ntDefault();this._focusPhysicalItem(this._focusedIndex+1)},_didEnter:function(e) {this._focusPhysicalItem(this._focusedIndex);this._selectionHandler(e.detail.key boardEvent)}})})();Polymer({is:"iron-scroll-threshold",properties:{upperThreshol d:{type:Number,value:100},lowerThreshold:{type:Number,value:100},upperTriggered: {type:Boolean,value:false,notify:true,readOnly:true},lowerTriggered:{type:Boolea n,value:false,notify:true,readOnly:true},horizontal:{type:Boolean,value:false}}, behaviors:[Polymer.IronScrollTargetBehavior],observers:["_setOverflow(scrollTarg et)","_initCheck(horizontal, isAttached)"],get _defaultScrollTarget(){return thi s},_setOverflow:function(scrollTarget){this.style.overflow=scrollTarget===this?" auto":""},_scrollHandler:function(){var THROTTLE_THRESHOLD=200;if(!this.isDeboun cerActive("_checkTheshold")){this.debounce("_checkTheshold",function(){this.chec kScrollThesholds()},THROTTLE_THRESHOLD)}},_initCheck:function(horizontal,isAttac hed){if(isAttached){this.debounce("_init",function(){this.clearTriggers();this.c heckScrollThesholds()})}},checkScrollThesholds:function(){if(!this.scrollTarget| |this.lowerTriggered&&this.upperTriggered){return}var upperScrollValue=this.hori zontal?this._scrollLeft:this._scrollTop;var lowerScrollValue=this.horizontal?thi s.scrollTarget.scrollWidth-this._scrollTargetWidth-this._scrollLeft:this.scrollT arget.scrollHeight-this._scrollTargetHeight-this._scrollTop;if(upperScrollValue< =this.upperThreshold&&!this.upperTriggered){this._setUpperTriggered(true);this.f ire("upper-threshold")}if(lowerScrollValue<=this.lowerThreshold&&!this.lowerTrig gered){this._setLowerTriggered(true);this.fire("lower-threshold")}},clearTrigger s:function(){this._setUpperTriggered(false);this._setLowerTriggered(false)}});
41 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
42 // Use of this source code is governed by a BSD-style license that can be
43 // found in the LICENSE file.
44 var EventTrackerEntry;function EventTracker(){this.listeners_=[]}EventTracker.pr ototype={add:function(target,eventType,listener,opt_capture){var capture=!!opt_c apture;var h={target:target,eventType:eventType,listener:listener,capture:captur e};this.listeners_.push(h);target.addEventListener(eventType,listener,capture)}, remove:function(target,eventType){this.listeners_=this.listeners_.filter(functio n(h){if(h.target==target&&(!eventType||h.eventType==eventType)){EventTracker.rem oveEventListener_(h);return false}return true})},removeAll:function(){this.liste ners_.forEach(EventTracker.removeEventListener_);this.listeners_=[]}};EventTrack er.removeEventListener_=function(h){h.target.removeEventListener(h.eventType,h.l istener,h.capture)};
45 // Copyright 2014 The Chromium Authors. All rights reserved.
46 // Use of this source code is governed by a BSD-style license that can be
47 // found in the LICENSE file.
48 cr.define("cr.ui",function(){function FocusRow(root,boundary,opt_delegate){this. root=root;this.boundary_=boundary||document.documentElement;this.delegate=opt_de legate;this.eventTracker=new EventTracker}FocusRow.Delegate=function(){};FocusRo w.Delegate.prototype={onKeydown:assertNotReached,onFocus:assertNotReached};Focus Row.ACTIVE_CLASS="focus-row-active";FocusRow.isFocusable=function(element){if(!e lement||element.disabled)return false;function isVisible(element){assertInstance of(element,Element);var style=window.getComputedStyle(element);if(style.visibili ty=="hidden"||style.display=="none")return false;var parent=element.parentNode;i f(!parent)return false;if(parent==element.ownerDocument||parent instanceof Docum entFragment)return true;return isVisible(parent)}return isVisible(element)};Focu sRow.prototype={addItem:function(type,query){assert(type);var element=this.root. querySelector(query);if(!element)return false;element.setAttribute("focus-type", type);element.tabIndex=this.isActive()?0:-1;this.eventTracker.add(element,"blur" ,this.onBlur_.bind(this));this.eventTracker.add(element,"focus",this.onFocus_.bi nd(this));this.eventTracker.add(element,"keydown",this.onKeydown_.bind(this));th is.eventTracker.add(element,"mousedown",this.onMousedown_.bind(this));return tru e},destroy:function(){this.eventTracker.removeAll()},getCustomEquivalent:functio n(sampleElement){return assert(this.getFirstFocusable())},getElements:function() {var elements=this.root.querySelectorAll("[focus-type]");return Array.prototype. slice.call(elements)},getEquivalentElement:function(sampleElement){if(this.getFo cusableElements().indexOf(sampleElement)>=0)return sampleElement;var sampleFocus Type=this.getTypeForElement(sampleElement);if(sampleFocusType){var sameType=this .getFirstFocusable(sampleFocusType);if(sameType)return sameType}return this.getC ustomEquivalent(sampleElement)},getFirstFocusable:function(opt_type){var filter= opt_type?'="'+opt_type+'"':"";var elements=this.root.querySelectorAll("[focus-ty pe"+filter+"]");for(var i=0;i<elements.length;++i){if(cr.ui.FocusRow.isFocusable (elements[i]))return elements[i]}return null},getFocusableElements:function(){re turn this.getElements().filter(cr.ui.FocusRow.isFocusable)},getTypeForElement:fu nction(element){return element.getAttribute("focus-type")||""},isActive:function (){return this.root.classList.contains(FocusRow.ACTIVE_CLASS)},makeActive:functi on(active){if(active==this.isActive())return;this.getElements().forEach(function (element){element.tabIndex=active?0:-1});this.root.classList.toggle(FocusRow.ACT IVE_CLASS,active)},onBlur_:function(e){if(!this.boundary_.contains(e.relatedTarg et))return;var currentTarget=e.currentTarget;if(this.getFocusableElements().inde xOf(currentTarget)>=0)this.makeActive(false)},onFocus_:function(e){if(this.deleg ate)this.delegate.onFocus(this,e)},onMousedown_:function(e){if(e.button)return;i f(!e.currentTarget.disabled)e.currentTarget.tabIndex=0},onKeydown_:function(e){v ar elements=this.getFocusableElements();var currentElement=e.currentTarget;var e lementIndex=elements.indexOf(currentElement);assert(elementIndex>=0);if(this.del egate&&this.delegate.onKeydown(this,e))return;if(hasKeyModifiers(e))return;var i ndex=-1;if(e.key=="ArrowLeft")index=elementIndex+(isRTL()?1:-1);else if(e.key==" ArrowRight")index=elementIndex+(isRTL()?-1:1);else if(e.key=="Home")index=0;else if(e.key=="End")index=elements.length-1;var elementToFocus=elements[index];if(e lementToFocus){this.getEquivalentElement(elementToFocus).focus();e.preventDefaul t()}}};return{FocusRow:FocusRow}});
49 // Copyright 2016 The Chromium Authors. All rights reserved.
50 // Use of this source code is governed by a BSD-style license that can be
51 // found in the LICENSE file.
52 cr.define("cr.icon",function(){function getSupportedScaleFactors(){var supported ScaleFactors=[];if(!cr.isIOS){supportedScaleFactors.push(1)}if(cr.isMac||cr.isCh romeOS||cr.isWindows||cr.isLinux){supportedScaleFactors.push(2)}else{supportedSc aleFactors.push(window.devicePixelRatio)}return supportedScaleFactors}function g etImageSet(path){var supportedScaleFactors=getSupportedScaleFactors();var replac eStartIndex=path.indexOf("scalefactor");if(replaceStartIndex<0)return url(path); var s="";for(var i=0;i<supportedScaleFactors.length;++i){var scaleFactor=support edScaleFactors[i];var pathWithScaleFactor=path.substr(0,replaceStartIndex)+scale Factor+path.substr(replaceStartIndex+"scalefactor".length);s+=url(pathWithScaleF actor)+" "+scaleFactor+"x";if(i!=supportedScaleFactors.length-1)s+=", "}return"- webkit-image-set("+s+")"}function getImage(path){var chromeThemePath="chrome://t heme";var isChromeThemeUrl=path.slice(0,chromeThemePath.length)==chromeThemePath ;return isChromeThemeUrl?getImageSet(path+"@scalefactorx"):url(path)}var FAVICON _URL_REGEX=/\.ico$/i;function getFavicon(url,opt_size,opt_type){var size=opt_siz e||16;var type=opt_type||"favicon";return getImageSet("chrome://"+type+"/size/"+ size+"@scalefactorx/"+(FAVICON_URL_REGEX.test(url)?"iconurl/":"")+url)}return{ge tImage:getImage,getFavicon:getFavicon}});
53 // Copyright 2016 The Chromium Authors. All rights reserved.
54 // Use of this source code is governed by a BSD-style license that can be
55 // found in the LICENSE file.
56 Polymer({is:"history-searched-label",properties:{title:String,searchTerm:String} ,observers:["setSearchedTextToBold_(title, searchTerm)"],setSearchedTextToBold_: function(){var i=0;var titleText=this.title;if(this.searchTerm==""||this.searchT erm==null){this.textContent=titleText;return}var re=new RegExp(quoteString(this. searchTerm),"gim");var match;this.textContent="";while(match=re.exec(titleText)) {if(match.index>i)this.appendChild(document.createTextNode(titleText.slice(i,mat ch.index)));i=re.lastIndex;var b=document.createElement("b");b.textContent=title Text.substring(match.index,i);this.appendChild(b)}if(i<titleText.length)this.app endChild(document.createTextNode(titleText.slice(i)))}});
57 // Copyright 2015 The Chromium Authors. All rights reserved.
58 // Use of this source code is governed by a BSD-style license that can be
59 // found in the LICENSE file.
60 function HistoryFocusRow(root,boundary,delegate){cr.ui.FocusRow.call(this,root,b oundary,delegate);this.addItems()}HistoryFocusRow.prototype={__proto__:cr.ui.Foc usRow.prototype,getCustomEquivalent:function(sampleElement){var equivalent;if(th is.getTypeForElement(sampleElement)=="star")equivalent=this.getFirstFocusable("t itle");return equivalent||cr.ui.FocusRow.prototype.getCustomEquivalent.call(this ,sampleElement)},addItems:function(){this.destroy();assert(this.addItem("checkbo x","#checkbox"));assert(this.addItem("title","#title"));assert(this.addItem("men u-button","#menu-button"));this.addItem("star","#bookmark-star")}};cr.define("md _history",function(){function FocusRowDelegate(historyItemElement){this.historyI temElement=historyItemElement}FocusRowDelegate.prototype={onFocus:function(row,e ){this.historyItemElement.lastFocused=e.path[0]},onKeydown:function(row,e){if(e. key=="Enter")e.stopPropagation();return false}};var HistoryItem=Polymer({is:"his tory-item",properties:{item:{type:Object,observer:"showIcon_"},selected:{type:Bo olean,reflectToAttribute:true},isCardStart:{type:Boolean,reflectToAttribute:true },isCardEnd:{type:Boolean,reflectToAttribute:true},embedded:{type:Boolean,reflec tToAttribute:true},lastFocused:{type:Object,notify:true},ironListTabIndex:{type: Number,observer:"ironListTabIndexChanged_"},hasTimeGap:Boolean,index:Number,numb erOfItems:Number,path:String,searchTerm:String},row_:null,attached:function(){Po lymer.RenderStatus.afterNextRender(this,function(){this.row_=new HistoryFocusRow (this.$["main-container"],null,new FocusRowDelegate(this));this.row_.makeActive( this.ironListTabIndex==0);this.listen(this,"focus","onFocus_");this.listen(this, "dom-change","onDomChange_")})},detached:function(){this.unlisten(this,"focus"," onFocus_");this.unlisten(this,"dom-change","onDomChange_");if(this.row_)this.row _.destroy()},onFocus_:function(){if(this.lastFocused)this.row_.getEquivalentElem ent(this.lastFocused).focus();else this.row_.getFirstFocusable().focus();this.ta bIndex=-1},ironListTabIndexChanged_:function(){if(this.row_)this.row_.makeActive (this.ironListTabIndex==0)},onDomChange_:function(){if(this.row_)this.row_.addIt ems()},onItemClick_:function(e){for(var i=0;i<e.path.length;i++){var elem=e.path [i];if(elem.id!="checkbox"&&(elem.nodeName=="A"||elem.nodeName=="BUTTON")){retur n}}if(this.selectionNotAllowed_())return;this.$.checkbox.focus();this.fire("hist ory-checkbox-select",{element:this,shiftKey:e.shiftKey})},onItemMousedown_:funct ion(e){if(e.shiftKey)e.preventDefault()},getEntrySummary_:function(){var item=th is.item;return loadTimeData.getStringF("entrySummary",item.dateTimeOfDay,item.st arred?loadTimeData.getString("bookmarked"):"",item.title,item.domain)},getAriaCh ecked_:function(selected){return selected?"true":"false"},onRemoveBookmarkTap_:f unction(){if(!this.item.starred)return;if(this.$$("#bookmark-star")==this.root.a ctiveElement)this.$["menu-button"].focus();var browserService=md_history.Browser Service.getInstance();browserService.removeBookmark(this.item.url);browserServic e.recordAction("BookmarkStarClicked");this.fire("remove-bookmark-stars",this.ite m.url)},onMenuButtonTap_:function(e){this.fire("open-menu",{target:Polymer.dom(e ).localTarget,index:this.index,item:this.item,path:this.path});e.stopPropagation ()},onLinkClick_:function(){var browserService=md_history.BrowserService.getInst ance();browserService.recordAction("EntryLinkClick");if(this.searchTerm)browserS ervice.recordAction("SearchResultClick");if(this.index==undefined)return;browser Service.recordHistogram("HistoryPage.ClickPosition",Math.min(this.index,UMA_MAX_ BUCKET_VALUE),UMA_MAX_BUCKET_VALUE);if(this.index<=UMA_MAX_SUBSET_BUCKET_VALUE){ browserService.recordHistogram("HistoryPage.ClickPositionSubset",this.index,UMA_ MAX_SUBSET_BUCKET_VALUE)}},onLinkRightClick_:function(){md_history.BrowserServic e.getInstance().recordAction("EntryLinkRightClick")},showIcon_:function(){this.$ .icon.style.backgroundImage=cr.icon.getFavicon(this.item.url)},selectionNotAllow ed_:function(){return!loadTimeData.getBoolean("allowDeletingHistory")},cardTitle _:function(numberOfItems,historyDate,search){if(!search)return this.item.dateRel ativeDay;return HistoryItem.searchResultsTitle(numberOfItems,search)},addTimeTit le_:function(){var el=this.$["time-accessed"];el.setAttribute("title",new Date(t his.item.time).toString());this.unlisten(el,"mouseover","addTimeTitle_")}});Hist oryItem.needsTimeGap=function(visits,currentIndex,searchedTerm){if(currentIndex> =visits.length-1||visits.length==0)return false;var currentItem=visits[currentIn dex];var nextItem=visits[currentIndex+1];if(searchedTerm)return currentItem.date Short!=nextItem.dateShort;return currentItem.time-nextItem.time>BROWSING_GAP_TIM E&&currentItem.dateRelativeDay==nextItem.dateRelativeDay};HistoryItem.searchResu ltsTitle=function(numberOfResults,searchTerm){var resultId=numberOfResults==1?"s earchResult":"searchResults";return loadTimeData.getStringF("foundSearchResults" ,numberOfResults,loadTimeData.getString(resultId),searchTerm)};return{HistoryIte m:HistoryItem}});
61 // Copyright 2016 The Chromium Authors. All rights reserved.
62 // Use of this source code is governed by a BSD-style license that can be
63 // found in the LICENSE file.
64 var SelectionTreeNode=function(currentPath){this.currentPath=currentPath;this.le af=false;this.indexes=[];this.children=[]};SelectionTreeNode.prototype.addChild= function(index,path){this.indexes.push(index);this.children[index]=new Selection TreeNode(path)};var HistoryListBehavior={properties:{initialData:Array,selectedP aths:{type:Object,value:function(){return new Set}},lastSelectedPath:String},lis teners:{"history-checkbox-select":"itemSelected_"},attached:function(){if(this.i nitialData)this.addNewResults(this.initialData,false,false)},addNewResults:funct ion(results,incremental,finished){},hasResults:function(historyDataLength){retur n historyDataLength>0},noResultsMessage:function(searchedTerm,isLoading){if(isLo ading)return"";var messageId=searchedTerm!==""?"noSearchResults":"noResults";ret urn loadTimeData.getString(messageId)},unselectAllItems:function(){this.selected Paths.forEach(function(path){this.set(path+".selected",false)}.bind(this));this. selectedPaths.clear()},deleteSelected:function(){var toBeRemoved=Array.from(this .selectedPaths.values()).map(function(path){return this.get(path)}.bind(this));m d_history.BrowserService.getInstance().deleteItems(toBeRemoved).then(function(){ this.removeItemsByPath(Array.from(this.selectedPaths));this.fire("unselect-all") }.bind(this))},removeItemsByPath:function(paths){if(paths.length==0)return;this. removeItemsBeneathNode_(this.buildRemovalTree_(paths))},buildRemovalTree_:functi on(paths){var rootNode=new SelectionTreeNode(paths[0].split(".")[0]);paths.forEa ch(function(path){var components=path.split(".");var node=rootNode;components.sh ift();while(components.length>1){var index=Number(components.shift());var arrayN ame=components.shift();if(!node.children[index])node.addChild(index,[node.curren tPath,index,arrayName].join("."));node=node.children[index]}node.leaf=true;node. indexes.push(Number(components.shift()))});return rootNode},removeItemsBeneathNo de_:function(node){var array=this.get(node.currentPath);var splices=[];node.inde xes.sort(function(a,b){return b-a});node.indexes.forEach(function(index){if(node .leaf||this.removeItemsBeneathNode_(node.children[index])){var item=array.splice (index,1)[0];splices.push({index:index,removed:[item],addedCount:0,object:array, type:"splice"})}}.bind(this));if(array.length==0&&node.currentPath.indexOf(".")! =-1)return true;this.notifySplices(node.currentPath,splices);return false},itemS elected_:function(e){var item=e.detail.element;var paths=[];var itemPath=item.pa th;if(e.detail.shiftKey&&this.lastSelectedPath){var itemPathComponents=itemPath. split(".");var itemIndex=Number(itemPathComponents.pop());var itemArrayPath=item PathComponents.join(".");var lastItemPathComponents=this.lastSelectedPath.split( ".");var lastItemIndex=Number(lastItemPathComponents.pop());if(itemArrayPath==la stItemPathComponents.join(".")){for(var i=Math.min(itemIndex,lastItemIndex);i<=M ath.max(itemIndex,lastItemIndex);i++){paths.push(itemArrayPath+"."+i)}}}if(paths .length==0)paths.push(item.path);var selected=!this.selectedPaths.has(item.path) ;paths.forEach(function(path){this.set(path+".selected",selected);if(selected){t his.selectedPaths.add(path);return}this.selectedPaths.delete(path)}.bind(this)); this.lastSelectedPath=itemPath}};
65 // Copyright 2015 The Chromium Authors. All rights reserved.
66 // Use of this source code is governed by a BSD-style license that can be
67 // found in the LICENSE file.
68 Polymer({is:"history-list",behaviors:[HistoryListBehavior],properties:{searchedT erm:{type:String,value:""},resultLoadingDisabled_:{type:Boolean,value:false},his toryData_:Array,lastFocused_:Object,querying:Boolean},listeners:{"remove-bookmar k-stars":"removeBookmarkStars_","open-menu":"onOpenMenu_"},attached:function(){t his.$["infinite-list"].notifyResize();this.$["infinite-list"].scrollTarget=this; this.$["scroll-threshold"].scrollTarget=this},removeBookmarkStars_:function(e){v ar url=e.detail;if(this.historyData_===undefined)return;for(var i=0;i<this.histo ryData_.length;i++){if(this.historyData_[i].url==url)this.set("historyData_."+i+ ".starred",false)}},addNewResults:function(historyResults,incremental,finished){ var results=historyResults.slice();this.$["scroll-threshold"].clearTriggers();if (!incremental){this.resultLoadingDisabled_=false;if(this.historyData_)this.splic e("historyData_",0,this.historyData_.length);this.fire("unselect-all")}if(this.h istoryData_){results.unshift("historyData_");this.push.apply(this,results)}else{ this.set("historyData_",results)}this.resultLoadingDisabled_=finished},loadMoreD ata_:function(){if(this.resultLoadingDisabled_||this.querying)return;this.fire(" query-history",true)},onOpenMenu_:function(e){var index=e.detail.index;var list= this.$["infinite-list"];if(index<list.firstVisibleIndex||index>list.lastVisibleI ndex)list.scrollToIndex(index)},needsTimeGap_:function(item,index,length){return md_history.HistoryItem.needsTimeGap(this.historyData_,index,this.searchedTerm)} ,isCardStart_:function(item,i,length){if(length==0||i>length-1)return false;retu rn i==0||this.historyData_[i].dateRelativeDay!=this.historyData_[i-1].dateRelati veDay},isCardEnd_:function(item,i,length){if(length==0||i>length-1)return false; return i==length-1||this.historyData_[i].dateRelativeDay!=this.historyData_[i+1] .dateRelativeDay},pathForItem_:function(index){return"historyData_."+index}});
69 // Copyright 2016 The Chromium Authors. All rights reserved.
70 // Use of this source code is governed by a BSD-style license that can be
71 // found in the LICENSE file.
72 Polymer({is:"history-list-container",properties:{selectedPage_:{type:String,comp uted:"computeSelectedPage_(queryState.range)"},grouped:Boolean,queryState:Object ,queryResult:Object,actionMenuModel_:Object},listeners:{"open-menu":"openMenu_"} ,historyResult:function(info,results){this.initializeResults_(info,results);this .closeMenu_();if(info.term&&!this.queryState.incremental){Polymer.IronA11yAnnoun cer.requestAvailability();this.fire("iron-announce",{text:md_history.HistoryItem .searchResultsTitle(results.length,info.term)})}var list=this.getSelectedList_() ;if(Polymer.isInstance(list))list.addNewResults(results,this.queryState.incremen tal,info.finished);else list.initialData=results},historyDeleted:function(){if(t his.getSelectedItemCount()>0)return;this.fire("query-history",false)},getContent ScrollTarget:function(){return this.getSelectedList_()},getSelectedItemCount:fun ction(){return this.getSelectedList_().selectedPaths.size},unselectAllItems:func tion(count){var selectedList=this.getSelectedList_();if(selectedList)selectedLis t.unselectAllItems(count)},deleteSelectedWithPrompt:function(){if(!loadTimeData. getBoolean("allowDeletingHistory"))return;var browserService=md_history.BrowserS ervice.getInstance();browserService.recordAction("RemoveSelected");if(this.query State.searchTerm!="")browserService.recordAction("SearchResultRemove");this.$.di alog.get().showModal();this.$$(".action-button").focus()},computeSelectedPage_:f unction(range){return range==HistoryRange.ALL_TIME?"infinite-list":"grouped-list "},initializeResults_:function(info,results){if(results.length==0)return;var cur rentDate=results[0].dateRelativeDay;for(var i=0;i<results.length;i++){results[i] .selected=false;results[i].readableTimestamp=info.term==""?results[i].dateTimeOf Day:results[i].dateShort;if(results[i].dateRelativeDay!=currentDate){currentDate =results[i].dateRelativeDay}}},onDialogConfirmTap_:function(){md_history.Browser Service.getInstance().recordAction("ConfirmRemoveSelected");this.getSelectedList _().deleteSelected();var dialog=assert(this.$.dialog.getIfExists());dialog.close ()},onDialogCancelTap_:function(){md_history.BrowserService.getInstance().record Action("CancelRemoveSelected");var dialog=assert(this.$.dialog.getIfExists());di alog.close()},closeMenu_:function(){var menu=this.$.sharedMenu.getIfExists();if( menu&&menu.open){this.actionMenuModel_=null;menu.close()}},openMenu_:function(e) {var target=e.detail.target;this.actionMenuModel_=e.detail;var menu=this.$.share dMenu.get();menu.showAt(target)},onMoreFromSiteTap_:function(){md_history.Browse rService.getInstance().recordAction("EntryMenuShowMoreFromSite");var menu=assert (this.$.sharedMenu.getIfExists());this.fire("change-query",{search:this.actionMe nuModel_.item.domain});this.actionMenuModel_=null;this.closeMenu_()},onRemoveFro mHistoryTap_:function(){var browserService=md_history.BrowserService.getInstance ();browserService.recordAction("EntryMenuRemoveFromHistory");var menu=assert(thi s.$.sharedMenu.getIfExists());var itemData=this.actionMenuModel_;browserService. deleteItems([itemData.item]).then(function(items){this.fire("unselect-all");this .getSelectedList_().removeItemsByPath([itemData.path]);var index=itemData.index; if(index==undefined)return;var browserService=md_history.BrowserService.getInsta nce();browserService.recordHistogram("HistoryPage.RemoveEntryPosition",Math.min( index,UMA_MAX_BUCKET_VALUE),UMA_MAX_BUCKET_VALUE);if(index<=UMA_MAX_SUBSET_BUCKE T_VALUE){browserService.recordHistogram("HistoryPage.RemoveEntryPositionSubset", index,UMA_MAX_SUBSET_BUCKET_VALUE)}}.bind(this));this.closeMenu_()},getSelectedL ist_:function(){return this.$$("#"+this.selectedPage_)},canDeleteHistory_:functi on(){return loadTimeData.getBoolean("allowDeletingHistory")}});
73 // Copyright 2017 The Chromium Authors. All rights reserved.
74 // Use of this source code is governed by a BSD-style license that can be
75 // found in the LICENSE file.
76 Polymer({is:"history-query-manager",properties:{queryState:{type:Object,notify:t rue,value:function(){return{incremental:false,querying:true,queryingDisabled:fal se,_range:HistoryRange.ALL_TIME,searchTerm:"",groupedOffset:0,set range(val){thi s._range=Number(val)},get range(){return this._range}}}},queryResult:Object,rout er:Object},observers:["searchTermChanged_(queryState.searchTerm)"],documentListe ners_:{},attached:function(){this.documentListeners_["change-query"]=this.onChan geQuery_.bind(this);this.documentListeners_["query-history"]=this.onQueryHistory _.bind(this);for(var e in this.documentListeners_)document.addEventListener(e,th is.documentListeners_[e])},detached:function(){for(var e in this.documentListene rs_)document.removeEventListener(e,this.documentListeners_[e])},queryHistory_:fu nction(incremental){var queryState=this.queryState;if(queryState.queryingDisable d)return;this.set("queryState.querying",true);this.set("queryState.incremental", incremental);var lastVisitTime=0;if(incremental){var lastVisit=this.queryResult. results.slice(-1)[0];lastVisitTime=lastVisit?Math.floor(lastVisit.time):0}var ma xResults=this.queryState.range==HistoryRange.ALL_TIME?RESULTS_PER_PAGE:0;chrome. send("queryHistory",[queryState.searchTerm,queryState.groupedOffset,queryState.r ange,lastVisitTime,maxResults])},onChangeQuery_:function(e){var changes=e.detail ;var needsUpdate=false;if(changes.range!=null&&changes.range!=this.queryState.ra nge){this.set("queryState.range",changes.range);needsUpdate=true;if(!changes.off set)this.set("queryState.groupedOffset",0);this.fire("history-view-changed")}if( changes.offset!=null&&changes.offset!=this.queryState.groupedOffset){this.set("q ueryState.groupedOffset",changes.offset);needsUpdate=true}if(changes.search!=nul l&&changes.search!=this.queryState.searchTerm){this.set("queryState.searchTerm", changes.search);needsUpdate=true}if(needsUpdate){this.queryHistory_(false);if(th is.router)this.router.serializeUrl()}},onQueryHistory_:function(e){this.queryHis tory_(e.detail);return false},searchTermChanged_:function(){if(this.queryState.s earchTerm)md_history.BrowserService.getInstance().recordAction("Search")}});(fun ction(){"use strict";Polymer({is:"iron-location",properties:{path:{type:String,n otify:true,value:function(){return window.decodeURIComponent(window.location.pat hname)}},query:{type:String,notify:true,value:function(){return window.decodeURI Component(window.location.search.slice(1))}},hash:{type:String,notify:true,value :function(){return window.decodeURIComponent(window.location.hash.slice(1))}},dw ellTime:{type:Number,value:2e3},urlSpaceRegex:{type:String,value:""},_urlSpaceRe gExp:{computed:"_makeRegExp(urlSpaceRegex)"},_lastChangedAt:{type:Number},_initi alized:{type:Boolean,value:false}},hostAttributes:{hidden:true},observers:["_upd ateUrl(path, query, hash)"],attached:function(){this.listen(window,"hashchange", "_hashChanged");this.listen(window,"location-changed","_urlChanged");this.listen (window,"popstate","_urlChanged");this.listen(document.body,"click","_globalOnCl ick");this._lastChangedAt=window.performance.now()-(this.dwellTime-200);this._in itialized=true;this._urlChanged()},detached:function(){this.unlisten(window,"has hchange","_hashChanged");this.unlisten(window,"location-changed","_urlChanged"); this.unlisten(window,"popstate","_urlChanged");this.unlisten(document.body,"clic k","_globalOnClick");this._initialized=false},_hashChanged:function(){this.hash= window.decodeURIComponent(window.location.hash.substring(1))},_urlChanged:functi on(){this._dontUpdateUrl=true;this._hashChanged();this.path=window.decodeURIComp onent(window.location.pathname);this.query=window.decodeURIComponent(window.loca tion.search.substring(1));this._dontUpdateUrl=false;this._updateUrl()},_getUrl:f unction(){var partiallyEncodedPath=window.encodeURI(this.path).replace(/\#/g,"%2 3").replace(/\?/g,"%3F");var partiallyEncodedQuery="";if(this.query){partiallyEn codedQuery="?"+window.encodeURI(this.query).replace(/\#/g,"%23")}var partiallyEn codedHash="";if(this.hash){partiallyEncodedHash="#"+window.encodeURI(this.hash)} return partiallyEncodedPath+partiallyEncodedQuery+partiallyEncodedHash},_updateU rl:function(){if(this._dontUpdateUrl||!this._initialized){return}if(this.path=== window.decodeURIComponent(window.location.pathname)&&this.query===window.decodeU RIComponent(window.location.search.substring(1))&&this.hash===window.decodeURICo mponent(window.location.hash.substring(1))){return}var newUrl=this._getUrl();var fullNewUrl=new URL(newUrl,window.location.protocol+"//"+window.location.host).h ref;var now=window.performance.now();var shouldReplace=this._lastChangedAt+this. dwellTime>now;this._lastChangedAt=now;if(shouldReplace){window.history.replaceSt ate({},"",fullNewUrl)}else{window.history.pushState({},"",fullNewUrl)}this.fire( "location-changed",{},{node:window})},_globalOnClick:function(event){if(event.de faultPrevented){return}var href=this._getSameOriginLinkHref(event);if(!href){ret urn}event.preventDefault();if(href===window.location.href){return}window.history .pushState({},"",href);this.fire("location-changed",{},{node:window})},_getSameO riginLinkHref:function(event){if(event.button!==0){return null}if(event.metaKey| |event.ctrlKey){return null}var eventPath=Polymer.dom(event).path;var anchor=nul l;for(var i=0;i<eventPath.length;i++){var element=eventPath[i];if(element.tagNam e==="A"&&element.href){anchor=element;break}}if(!anchor){return null}if(anchor.t arget==="_blank"){return null}if((anchor.target==="_top"||anchor.target==="_pare nt")&&window.top!==window){return null}var href=anchor.href;var url;if(document. baseURI!=null){url=new URL(href,document.baseURI)}else{url=new URL(href)}var ori gin;if(window.location.origin){origin=window.location.origin}else{origin=window. location.protocol+"//"+window.location.hostname;if(window.location.port){origin+ =":"+window.location.port}}if(url.origin!==origin){return null}var normalizedHre f=url.pathname+url.search+url.hash;if(this._urlSpaceRegExp&&!this._urlSpaceRegEx p.test(normalizedHref)){return null}var fullNormalizedHref=new URL(normalizedHre f,window.location.href).href;return fullNormalizedHref},_makeRegExp:function(url SpaceRegex){return RegExp(urlSpaceRegex)}})})();"use strict";Polymer({is:"iron-q uery-params",properties:{paramsString:{type:String,notify:true,observer:"paramsS tringChanged"},paramsObject:{type:Object,notify:true,value:function(){return{}}} ,_dontReact:{type:Boolean,value:false}},hostAttributes:{hidden:true},observers:[ "paramsObjectChanged(paramsObject.*)"],paramsStringChanged:function(){this._dont React=true;this.paramsObject=this._decodeParams(this.paramsString);this._dontRea ct=false},paramsObjectChanged:function(){if(this._dontReact){return}this.paramsS tring=this._encodeParams(this.paramsObject)},_encodeParams:function(params){var encodedParams=[];for(var key in params){var value=params[key];if(value===""){enc odedParams.push(encodeURIComponent(key))}else if(value){encodedParams.push(encod eURIComponent(key)+"="+encodeURIComponent(value.toString()))}}return encodedPara ms.join("&")},_decodeParams:function(paramString){var params={};paramString=(par amString||"").replace(/\+/g,"%20");var paramList=paramString.split("&");for(var i=0;i<paramList.length;i++){var param=paramList[i].split("=");if(param[0]){param s[decodeURIComponent(param[0])]=decodeURIComponent(param[1]||"")}}return params} });
77 // Copyright 2016 The Chromium Authors. All rights reserved.
78 // Use of this source code is governed by a BSD-style license that can be
79 // found in the LICENSE file.
80 Polymer({is:"history-router",properties:{selectedPage:{type:String,notify:true,o bserver:"selectedPageChanged_"},queryState:Object,grouped:Boolean,path_:String,q ueryParams_:Object},parsing_:false,observers:["onUrlChanged_(path_, queryParams_ )"],attached:function(){if(window.location.hash){window.location.href=window.loc ation.href.split("#")[0]+"?"+window.location.hash.substr(1)}},serializeUrl:funct ion(){var path=this.selectedPage;if(path=="history"&&this.queryState.range!=Hist oryRange.ALL_TIME)path+="/"+this.rangeToString_(this.queryState.range);if(path== "history")path="";var offsetParam=null;if(this.selectedPage=="history"&&this.que ryState.groupedOffset)offsetParam=this.queryState.groupedOffset;this.path_="/"+p ath;this.set("queryParams_.offset",offsetParam);this.set("queryParams_.q",this.q ueryState.searchTerm||null)},selectedPageChanged_:function(){if(!this.parsing_)t his.serializeUrl()},parseUrl_:function(){this.parsing_=true;var changes={};var s ections=this.path_.substr(1).split("/");var page=sections[0]||"history";if(page= ="history"&&this.grouped){var range=sections.length>1?this.stringToRange_(sectio ns[1]):HistoryRange.ALL_TIME;changes.range=range;changes.offset=Number(this.quer yParams_.offset)||0}changes.search=this.queryParams_.q||"";this.selectedPage=pag e;this.fire("change-query",changes);this.serializeUrl();this.parsing_=false},onU rlChanged_:function(){this.debounce("parseUrl",this.parseUrl_.bind(this))},range ToString_:function(range){switch(range){case HistoryRange.WEEK:return"week";case HistoryRange.MONTH:return"month";default:return""}},stringToRange_:function(str ){switch(str){case"week":return HistoryRange.WEEK;case"month":return HistoryRang e.MONTH;default:return HistoryRange.ALL_TIME}}});Polymer.IronMultiSelectableBeha viorImpl={properties:{multi:{type:Boolean,value:false,observer:"multiChanged"},s electedValues:{type:Array,notify:true},selectedItems:{type:Array,readOnly:true,n otify:true}},observers:["_updateSelected(selectedValues.splices)"],select:functi on(value){if(this.multi){if(this.selectedValues){this._toggleSelected(value)}els e{this.selectedValues=[value]}}else{this.selected=value}},multiChanged:function( multi){this._selection.multi=multi},get _shouldUpdateSelection(){return this.sel ected!=null||this.selectedValues!=null&&this.selectedValues.length},_updateAttrF orSelected:function(){if(!this.multi){Polymer.IronSelectableBehavior._updateAttr ForSelected.apply(this)}else if(this._shouldUpdateSelection){this.selectedValues =this.selectedItems.map(function(selectedItem){return this._indexToValue(this.in dexOf(selectedItem))},this).filter(function(unfilteredValue){return unfilteredVa lue!=null},this)}},_updateSelected:function(){if(this.multi){this._selectMulti(t his.selectedValues)}else{this._selectSelected(this.selected)}},_selectMulti:func tion(values){if(values){var selectedItems=this._valuesToItems(values);this._sele ction.clear(selectedItems);for(var i=0;i<selectedItems.length;i++){this._selecti on.setItemSelected(selectedItems[i],true)}if(this.fallbackSelection&&this.items. length&&!this._selection.get().length){var fallback=this._valueToItem(this.fallb ackSelection);if(fallback){this.selectedValues=[this.fallbackSelection]}}}else{t his._selection.clear()}},_selectionChange:function(){var s=this._selection.get() ;if(this.multi){this._setSelectedItems(s)}else{this._setSelectedItems([s]);this. _setSelectedItem(s)}},_toggleSelected:function(value){var i=this.selectedValues. indexOf(value);var unselected=i<0;if(unselected){this.push("selectedValues",valu e)}else{this.splice("selectedValues",i,1)}},_valuesToItems:function(values){retu rn values==null?null:values.map(function(value){return this._valueToItem(value)} ,this)}};Polymer.IronMultiSelectableBehavior=[Polymer.IronSelectableBehavior,Pol ymer.IronMultiSelectableBehaviorImpl];Polymer({is:"iron-selector",behaviors:[Pol ymer.IronMultiSelectableBehavior]});
81 // Copyright 2016 The Chromium Authors. All rights reserved.
82 // Use of this source code is governed by a BSD-style license that can be
83 // found in the LICENSE file.
84 Polymer({is:"history-side-bar",behaviors:[Polymer.IronA11yKeysBehavior],properti es:{selectedPage:{type:String,notify:true},showFooter:Boolean},keyBindings:{"spa ce:keydown":"onSpacePressed_"},onSpacePressed_:function(e){e.detail.keyboardEven t.path[0].click()},onSelectorActivate_:function(){this.fire("history-close-drawe r")},onClearBrowsingDataTap_:function(e){var browserService=md_history.BrowserSe rvice.getInstance();browserService.recordAction("InitClearBrowsingData");browser Service.openClearBrowsingData();this.$["cbd-ripple"].upAction();e.preventDefault ()},onItemClick_:function(e){e.preventDefault()}});
85 // Copyright 2016 The Chromium Authors. All rights reserved.
86 // Use of this source code is governed by a BSD-style license that can be
87 // found in the LICENSE file.
88 cr.define("md_history",function(){var lazyLoadPromise=null;function ensureLazyLo aded(){if(!lazyLoadPromise){lazyLoadPromise=new Promise(function(resolve,reject) {Polymer.Base.importHref("chrome://history/lazy_load.html",resolve,reject,true)} )}return lazyLoadPromise}return{ensureLazyLoaded:ensureLazyLoaded}});Polymer({is :"history-app",behaviors:[Polymer.IronScrollTargetBehavior],properties:{selected Page_:{type:String,observer:"selectedPageChanged_"},grouped_:{type:Boolean,refle ctToAttribute:true},queryResult_:{type:Object,value:function(){return{info:null, results:null,sessionList:null}}},isUserSignedIn_:{type:Boolean,value:loadTimeDat a.getBoolean("isUserSignedIn")},toolbarShadow_:{type:Boolean,reflectToAttribute: true,notify:true},showMenuPromo_:{type:Boolean,value:function(){return loadTimeD ata.getBoolean("showMenuPromo")}},queryState_:Object,hasDrawer_:{type:Boolean,ob server:"hasDrawerChanged_"},showSidebarFooter:Boolean,hasSyncedResults:Boolean}, listeners:{"cr-toolbar-menu-promo-close":"onCrToolbarMenuPromoClose_","cr-toolba r-menu-promo-shown":"onCrToolbarMenuPromoShown_","cr-toolbar-menu-tap":"onCrTool barMenuTap_","delete-selected":"deleteSelected","history-checkbox-select":"check boxSelected","history-close-drawer":"closeDrawer_","history-view-changed":"histo ryViewChanged_","opened-changed":"onOpenedChanged_","unselect-all":"unselectAll" },boundOnCanExecute_:null,boundOnCommand_:null,attached:function(){this.grouped_ =loadTimeData.getBoolean("groupByDomain");cr.ui.decorate("command",cr.ui.Command );this.boundOnCanExecute_=this.onCanExecute_.bind(this);this.boundOnCommand_=thi s.onCommand_.bind(this);document.addEventListener("canExecute",this.boundOnCanEx ecute_);document.addEventListener("command",this.boundOnCommand_)},detached:func tion(){document.removeEventListener("canExecute",this.boundOnCanExecute_);docume nt.removeEventListener("command",this.boundOnCommand_)},onFirstRender:function() {setTimeout(function(){chrome.send("metricsHandler:recordTime",["History.Results RenderedTime",window.performance.now()])});var searchField=this.$.toolbar.search Field;if(!searchField.narrow){searchField.getSearchInput().focus()}md_history.en sureLazyLoaded().then(function(){window.requestIdleCallback(function(){document. fonts.load("bold 12px Roboto")})})},_scrollHandler:function(){if(this.scrollTarg et)this.toolbarShadow_=this.scrollTarget.scrollTop!=0},onCrToolbarMenuPromoClose _:function(){this.showMenuPromo_=false},onCrToolbarMenuPromoShown_:function(){md _history.BrowserService.getInstance().menuPromoShown()},onCrToolbarMenuTap_:func tion(){var drawer=this.$.drawer.get();drawer.align=document.documentElement.dir= ="ltr"?"left":"right";drawer.toggle()},onOpenedChanged_:function(e){if(e.detail. value)this.showMenuPromo_=false},checkboxSelected:function(e){var toolbar=this.$ .toolbar;toolbar.count=this.$.history.getSelectedItemCount()},unselectAll:functi on(){var listContainer=this.$.history;var toolbar=this.$.toolbar;listContainer.u nselectAllItems(toolbar.count);toolbar.count=0},deleteSelected:function(){this.$ .history.deleteSelectedWithPrompt()},historyResult:function(info,results){this.s et("queryState_.querying",false);this.set("queryResult_.info",info);this.set("qu eryResult_.results",results);var listContainer=this.$["history"];listContainer.h istoryResult(info,results)},focusToolbarSearchField:function(){this.$.toolbar.sh owSearchField()},onCanExecute_:function(e){e=e;switch(e.command.id){case"find-co mmand":case"toggle-grouped":e.canExecute=true;break;case"slash-command":e.canExe cute=!this.$.toolbar.searchField.isSearchFocused();break;case"delete-command":e. canExecute=this.$.toolbar.count>0;break}},onCommand_:function(e){if(e.command.id =="find-command"||e.command.id=="slash-command")this.focusToolbarSearchField();i f(e.command.id=="delete-command")this.deleteSelected();if(e.command.id=="toggle- grouped")this.grouped_=!this.grouped_},setForeignSessions:function(sessionList){ this.set("queryResult_.sessionList",sessionList)},historyDeleted:function(){this .$.history.historyDeleted()},updateSignInState:function(isUserSignedIn){this.isU serSignedIn_=isUserSignedIn},syncedTabsSelected_:function(selectedPage){return s electedPage=="syncedTabs"},shouldShowSpinner_:function(querying,incremental,sear chTerm){return querying&&!incremental&&searchTerm!=""},showSyncNotice_:function( hasSyncedResults,selectedPage){return hasSyncedResults&&selectedPage!="syncedTab s"},selectedPageChanged_:function(){this.unselectAll();this.historyViewChanged_( )},historyViewChanged_:function(){requestAnimationFrame(function(){md_history.en sureLazyLoaded().then(function(){if(!this.$.content.selectedItem)return;this.scr ollTarget=this.$.content.selectedItem.getContentScrollTarget();this._scrollHandl er()}.bind(this))}.bind(this));this.recordHistoryPageView_()},hasDrawerChanged_: function(){var drawer=this.$.drawer.getIfExists();if(!this.hasDrawer_&&drawer&&d rawer.open)drawer.closeDrawer()},getSelectedPage_:function(selectedPage,items){r eturn selectedPage},closeDrawer_:function(){var drawer=this.$.drawer.get();if(dr awer&&drawer.open)drawer.closeDrawer()},recordHistoryPageView_:function(){var hi stogramValue=HistoryPageViewHistogram.END;switch(this.selectedPage_){case"synced Tabs":histogramValue=this.isUserSignedIn_?HistoryPageViewHistogram.SYNCED_TABS:H istoryPageViewHistogram.SIGNIN_PROMO;break;default:switch(this.queryState_.range ){case HistoryRange.ALL_TIME:histogramValue=HistoryPageViewHistogram.HISTORY;bre ak;case HistoryRange.WEEK:histogramValue=HistoryPageViewHistogram.GROUPED_WEEK;b reak;case HistoryRange.MONTH:histogramValue=HistoryPageViewHistogram.GROUPED_MON TH;break}break}md_history.BrowserService.getInstance().recordHistogram("History. HistoryPageView",histogramValue,HistoryPageViewHistogram.END)}});
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698