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

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

Issue 2590093002: MD History: Move queryState to be managed by history-router (Closed)
Patch Set: Rebase Created 3 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2016 The Chromium Authors. All rights reserved. 1 // Copyright 2016 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 function PromiseResolver(){this.resolve_;this.reject_;this.promise_=new Promise( function(resolve,reject){this.resolve_=resolve;this.reject_=reject}.bind(this))} PromiseResolver.prototype={get promise(){return this.promise_},set promise(p){as sertNotReached()},get resolve(){return this.resolve_},set resolve(r){assertNotRe ached()},get reject(){return this.reject_},set reject(s){assertNotReached()}}; 4 function PromiseResolver(){this.resolve_;this.reject_;this.promise_=new Promise( function(resolve,reject){this.resolve_=resolve;this.reject_=reject}.bind(this))} PromiseResolver.prototype={get promise(){return this.promise_},set promise(p){as sertNotReached()},get resolve(){return this.resolve_},set resolve(r){assertNotRe ached()},get reject(){return this.reject_},set reject(s){assertNotReached()}};
5 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 5 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
6 // Use of this source code is governed by a BSD-style license that can be 6 // Use of this source code is governed by a BSD-style license that can be
7 // found in the LICENSE file. 7 // found in the LICENSE file.
8 var global=this;var WebUIListener;var cr=cr||function(){"use strict";function ex portPath(name,opt_object,opt_objectToExportTo){var parts=name.split(".");var cur =opt_objectToExportTo||global;for(var part;parts.length&&(part=parts.shift());){ if(!parts.length&&opt_object!==undefined){cur[part]=opt_object}else if(part in c ur){cur=cur[part]}else{cur=cur[part]={}}}return cur}function dispatchPropertyCha nge(target,propertyName,newValue,oldValue){var e=new Event(propertyName+"Change" );e.propertyName=propertyName;e.newValue=newValue;e.oldValue=oldValue;target.dis patchEvent(e)}function getAttributeName(jsName){return jsName.replace(/([A-Z])/g ,"-$1").toLowerCase()}var PropertyKind={JS:"js",ATTR:"attr",BOOL_ATTR:"boolAttr" };function getGetter(name,kind){switch(kind){case PropertyKind.JS:var privateNam e=name+"_";return function(){return this[privateName]};case PropertyKind.ATTR:va r attributeName=getAttributeName(name);return function(){return this.getAttribut e(attributeName)};case PropertyKind.BOOL_ATTR:var attributeName=getAttributeName (name);return function(){return this.hasAttribute(attributeName)}}throw"not reac hed"}function getSetter(name,kind,opt_setHook){switch(kind){case PropertyKind.JS :var privateName=name+"_";return function(value){var oldValue=this[name];if(valu e!==oldValue){this[privateName]=value;if(opt_setHook)opt_setHook.call(this,value ,oldValue);dispatchPropertyChange(this,name,value,oldValue)}};case PropertyKind. ATTR:var attributeName=getAttributeName(name);return function(value){var oldValu e=this[name];if(value!==oldValue){if(value==undefined)this.removeAttribute(attri buteName);else this.setAttribute(attributeName,value);if(opt_setHook)opt_setHook .call(this,value,oldValue);dispatchPropertyChange(this,name,value,oldValue)}};ca se PropertyKind.BOOL_ATTR:var attributeName=getAttributeName(name);return functi on(value){var oldValue=this[name];if(value!==oldValue){if(value)this.setAttribut e(attributeName,name);else this.removeAttribute(attributeName);if(opt_setHook)op t_setHook.call(this,value,oldValue);dispatchPropertyChange(this,name,value,oldVa lue)}}}throw"not reached"}function defineProperty(obj,name,opt_kind,opt_setHook) {if(typeof obj=="function")obj=obj.prototype;var kind=opt_kind||PropertyKind.JS; if(!obj.__lookupGetter__(name))obj.__defineGetter__(name,getGetter(name,kind));i f(!obj.__lookupSetter__(name))obj.__defineSetter__(name,getSetter(name,kind,opt_ setHook))}var uidCounter=1;function createUid(){return uidCounter++}function get Uid(item){if(item.hasOwnProperty("uid"))return item.uid;return item.uid=createUi d()}function dispatchSimpleEvent(target,type,opt_bubbles,opt_cancelable){var e=n ew Event(type,{bubbles:opt_bubbles,cancelable:opt_cancelable===undefined||opt_ca ncelable});return target.dispatchEvent(e)}function define(name,fun){var obj=expo rtPath(name);var exports=fun();for(var propertyName in exports){var propertyDesc riptor=Object.getOwnPropertyDescriptor(exports,propertyName);if(propertyDescript or)Object.defineProperty(obj,propertyName,propertyDescriptor)}}function addSingl etonGetter(ctor){ctor.getInstance=function(){return ctor.instance_||(ctor.instan ce_=new ctor)}}function makePublic(ctor,methods,opt_target){methods.forEach(func tion(method){ctor[method]=function(){var target=opt_target?document.getElementBy Id(opt_target):ctor.getInstance();return target[method+"_"].apply(target,argumen ts)}})}var chromeSendResolverMap={};function webUIResponse(id,isSuccess,response ){var resolver=chromeSendResolverMap[id];delete chromeSendResolverMap[id];if(isS uccess)resolver.resolve(response);else resolver.reject(response)}function sendWi thPromise(methodName,var_args){var args=Array.prototype.slice.call(arguments,1); var promiseResolver=new PromiseResolver;var id=methodName+"_"+createUid();chrome SendResolverMap[id]=promiseResolver;chrome.send(methodName,[id].concat(args));re turn promiseResolver.promise}var webUIListenerMap={};function webUIListenerCallb ack(event,var_args){var eventListenersMap=webUIListenerMap[event];if(!eventListe nersMap){return}var args=Array.prototype.slice.call(arguments,1);for(var listene rId in eventListenersMap){eventListenersMap[listenerId].apply(null,args)}}functi on addWebUIListener(eventName,callback){webUIListenerMap[eventName]=webUIListene rMap[eventName]||{};var uid=createUid();webUIListenerMap[eventName][uid]=callbac k;return{eventName:eventName,uid:uid}}function removeWebUIListener(listener){var listenerExists=webUIListenerMap[listener.eventName]&&webUIListenerMap[listener. eventName][listener.uid];if(listenerExists){delete webUIListenerMap[listener.eve ntName][listener.uid];return true}return false}return{addSingletonGetter:addSing letonGetter,createUid:createUid,define:define,defineProperty:defineProperty,disp atchPropertyChange:dispatchPropertyChange,dispatchSimpleEvent:dispatchSimpleEven t,exportPath:exportPath,getUid:getUid,makePublic:makePublic,PropertyKind:Propert yKind,addWebUIListener:addWebUIListener,removeWebUIListener:removeWebUIListener, sendWithPromise:sendWithPromise,webUIListenerCallback:webUIListenerCallback,webU IResponse:webUIResponse,get doc(){return document},get isMac(){return/Mac/.test( navigator.platform)},get isWindows(){return/Win/.test(navigator.platform)},get i sChromeOS(){return/CrOS/.test(navigator.userAgent)},get isLinux(){return/Linux/. test(navigator.userAgent)},get isAndroid(){return/Android/.test(navigator.userAg ent)},get isIOS(){return/iPad|iPhone|iPod/.test(navigator.platform)}}}(); 8 var global=this;var WebUIListener;var cr=cr||function(){"use strict";function ex portPath(name,opt_object,opt_objectToExportTo){var parts=name.split(".");var cur =opt_objectToExportTo||global;for(var part;parts.length&&(part=parts.shift());){ if(!parts.length&&opt_object!==undefined){cur[part]=opt_object}else if(part in c ur){cur=cur[part]}else{cur=cur[part]={}}}return cur}function dispatchPropertyCha nge(target,propertyName,newValue,oldValue){var e=new Event(propertyName+"Change" );e.propertyName=propertyName;e.newValue=newValue;e.oldValue=oldValue;target.dis patchEvent(e)}function getAttributeName(jsName){return jsName.replace(/([A-Z])/g ,"-$1").toLowerCase()}var PropertyKind={JS:"js",ATTR:"attr",BOOL_ATTR:"boolAttr" };function getGetter(name,kind){switch(kind){case PropertyKind.JS:var privateNam e=name+"_";return function(){return this[privateName]};case PropertyKind.ATTR:va r attributeName=getAttributeName(name);return function(){return this.getAttribut e(attributeName)};case PropertyKind.BOOL_ATTR:var attributeName=getAttributeName (name);return function(){return this.hasAttribute(attributeName)}}throw"not reac hed"}function getSetter(name,kind,opt_setHook){switch(kind){case PropertyKind.JS :var privateName=name+"_";return function(value){var oldValue=this[name];if(valu e!==oldValue){this[privateName]=value;if(opt_setHook)opt_setHook.call(this,value ,oldValue);dispatchPropertyChange(this,name,value,oldValue)}};case PropertyKind. ATTR:var attributeName=getAttributeName(name);return function(value){var oldValu e=this[name];if(value!==oldValue){if(value==undefined)this.removeAttribute(attri buteName);else this.setAttribute(attributeName,value);if(opt_setHook)opt_setHook .call(this,value,oldValue);dispatchPropertyChange(this,name,value,oldValue)}};ca se PropertyKind.BOOL_ATTR:var attributeName=getAttributeName(name);return functi on(value){var oldValue=this[name];if(value!==oldValue){if(value)this.setAttribut e(attributeName,name);else this.removeAttribute(attributeName);if(opt_setHook)op t_setHook.call(this,value,oldValue);dispatchPropertyChange(this,name,value,oldVa lue)}}}throw"not reached"}function defineProperty(obj,name,opt_kind,opt_setHook) {if(typeof obj=="function")obj=obj.prototype;var kind=opt_kind||PropertyKind.JS; if(!obj.__lookupGetter__(name))obj.__defineGetter__(name,getGetter(name,kind));i f(!obj.__lookupSetter__(name))obj.__defineSetter__(name,getSetter(name,kind,opt_ setHook))}var uidCounter=1;function createUid(){return uidCounter++}function get Uid(item){if(item.hasOwnProperty("uid"))return item.uid;return item.uid=createUi d()}function dispatchSimpleEvent(target,type,opt_bubbles,opt_cancelable){var e=n ew Event(type,{bubbles:opt_bubbles,cancelable:opt_cancelable===undefined||opt_ca ncelable});return target.dispatchEvent(e)}function define(name,fun){var obj=expo rtPath(name);var exports=fun();for(var propertyName in exports){var propertyDesc riptor=Object.getOwnPropertyDescriptor(exports,propertyName);if(propertyDescript or)Object.defineProperty(obj,propertyName,propertyDescriptor)}}function addSingl etonGetter(ctor){ctor.getInstance=function(){return ctor.instance_||(ctor.instan ce_=new ctor)}}function makePublic(ctor,methods,opt_target){methods.forEach(func tion(method){ctor[method]=function(){var target=opt_target?document.getElementBy Id(opt_target):ctor.getInstance();return target[method+"_"].apply(target,argumen ts)}})}var chromeSendResolverMap={};function webUIResponse(id,isSuccess,response ){var resolver=chromeSendResolverMap[id];delete chromeSendResolverMap[id];if(isS uccess)resolver.resolve(response);else resolver.reject(response)}function sendWi thPromise(methodName,var_args){var args=Array.prototype.slice.call(arguments,1); var promiseResolver=new PromiseResolver;var id=methodName+"_"+createUid();chrome SendResolverMap[id]=promiseResolver;chrome.send(methodName,[id].concat(args));re turn promiseResolver.promise}var webUIListenerMap={};function webUIListenerCallb ack(event,var_args){var eventListenersMap=webUIListenerMap[event];if(!eventListe nersMap){return}var args=Array.prototype.slice.call(arguments,1);for(var listene rId in eventListenersMap){eventListenersMap[listenerId].apply(null,args)}}functi on addWebUIListener(eventName,callback){webUIListenerMap[eventName]=webUIListene rMap[eventName]||{};var uid=createUid();webUIListenerMap[eventName][uid]=callbac k;return{eventName:eventName,uid:uid}}function removeWebUIListener(listener){var listenerExists=webUIListenerMap[listener.eventName]&&webUIListenerMap[listener. eventName][listener.uid];if(listenerExists){delete webUIListenerMap[listener.eve ntName][listener.uid];return true}return false}return{addSingletonGetter:addSing letonGetter,createUid:createUid,define:define,defineProperty:defineProperty,disp atchPropertyChange:dispatchPropertyChange,dispatchSimpleEvent:dispatchSimpleEven t,exportPath:exportPath,getUid:getUid,makePublic:makePublic,PropertyKind:Propert yKind,addWebUIListener:addWebUIListener,removeWebUIListener:removeWebUIListener, sendWithPromise:sendWithPromise,webUIListenerCallback:webUIListenerCallback,webU IResponse:webUIResponse,get doc(){return document},get isMac(){return/Mac/.test( navigator.platform)},get isWindows(){return/Win/.test(navigator.platform)},get i sChromeOS(){return/CrOS/.test(navigator.userAgent)},get isLinux(){return/Linux/. test(navigator.userAgent)},get isAndroid(){return/Android/.test(navigator.userAg ent)},get isIOS(){return/iPad|iPhone|iPod/.test(navigator.platform)}}}();
9 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 9 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
10 // Use of this source code is governed by a BSD-style license that can be 10 // Use of this source code is governed by a BSD-style license that can be
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
58 // Use of this source code is governed by a BSD-style license that can be 58 // Use of this source code is governed by a BSD-style license that can be
59 // found in the LICENSE file. 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}}); 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. 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 62 // Use of this source code is governed by a BSD-style license that can be
63 // found in the LICENSE file. 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:{selectedPaths:{type:Object, value:function(){return new Set}},lastSelectedPath:String},listeners:{"history-c heckbox-select":"itemSelected_"},addNewResults:function(results,incremental,fini shed){},hasResults:function(historyDataLength){return historyDataLength>0},noRes ultsMessage:function(searchedTerm,isLoading){if(isLoading)return"";var messageId =searchedTerm!==""?"noSearchResults":"noResults";return loadTimeData.getString(m essageId)},unselectAllItems:function(){this.selectedPaths.forEach(function(path) {this.set(path+".selected",false)}.bind(this));this.selectedPaths.clear()},delet eSelected:function(){var toBeRemoved=Array.from(this.selectedPaths.values()).map (function(path){return this.get(path)}.bind(this));md_history.BrowserService.get Instance().deleteItems(toBeRemoved).then(function(){this.removeItemsByPath(Array .from(this.selectedPaths));this.fire("unselect-all")}.bind(this))},removeItemsBy Path:function(paths){if(paths.length==0)return;this.removeItemsBeneathNode_(this .buildRemovalTree_(paths))},buildRemovalTree_:function(paths){var rootNode=new S electionTreeNode(paths[0].split(".")[0]);paths.forEach(function(path){var compon ents=path.split(".");var node=rootNode;components.shift();while(components.lengt h>1){var index=Number(components.shift());var arrayName=components.shift();if(!n ode.children[index])node.addChild(index,[node.currentPath,index,arrayName].join( "."));node=node.children[index]}node.leaf=true;node.indexes.push(Number(componen ts.shift()))});return rootNode},removeItemsBeneathNode_:function(node){var array =this.get(node.currentPath);var splices=[];node.indexes.sort(function(a,b){retur n b-a});node.indexes.forEach(function(index){if(node.leaf||this.removeItemsBenea thNode_(node.children[index])){var item=array.splice(index,1)[0];splices.push({i ndex:index,removed:[item],addedCount:0,object:array,type:"splice"})}}.bind(this) );if(array.length==0&&node.currentPath.indexOf(".")!=-1)return true;this.notifyS plices(node.currentPath,splices);return false},itemSelected_:function(e){var ite m=e.detail.element;var paths=[];var itemPath=item.path;if(e.detail.shiftKey&&thi s.lastSelectedPath){var itemPathComponents=itemPath.split(".");var itemIndex=Num ber(itemPathComponents.pop());var itemArrayPath=itemPathComponents.join(".");var lastItemPathComponents=this.lastSelectedPath.split(".");var lastItemIndex=Numbe r(lastItemPathComponents.pop());if(itemArrayPath==lastItemPathComponents.join(". ")){for(var i=Math.min(itemIndex,lastItemIndex);i<=Math.max(itemIndex,lastItemIn dex);i++){paths.push(itemArrayPath+"."+i)}}}if(paths.length==0)paths.push(item.p ath);var selected=!this.selectedPaths.has(item.path);paths.forEach(function(path ){this.set(path+".selected",selected);if(selected){this.selectedPaths.add(path); return}this.selectedPaths.delete(path)}.bind(this));this.lastSelectedPath=itemPa th}}; 64 var SelectionTreeNode=function(currentPath){this.currentPath=currentPath;this.le af=false;this.indexes=[];this.children=[]};SelectionTreeNode.prototype.addChild= function(index,path){this.indexes.push(index);this.children[index]=new Selection TreeNode(path)};var HistoryListBehavior={properties:{selectedPaths:{type:Object, value:function(){return new Set}},lastSelectedPath:String},listeners:{"history-c heckbox-select":"itemSelected_"},addNewResults:function(results,incremental,fini shed){},hasResults:function(historyDataLength){return historyDataLength>0},noRes ultsMessage:function(searchedTerm,isLoading){if(isLoading)return"";var messageId =searchedTerm!==""?"noSearchResults":"noResults";return loadTimeData.getString(m essageId)},unselectAllItems:function(){this.selectedPaths.forEach(function(path) {this.set(path+".selected",false)}.bind(this));this.selectedPaths.clear()},delet eSelected:function(){var toBeRemoved=Array.from(this.selectedPaths.values()).map (function(path){return this.get(path)}.bind(this));md_history.BrowserService.get Instance().deleteItems(toBeRemoved).then(function(){this.removeItemsByPath(Array .from(this.selectedPaths));this.fire("unselect-all")}.bind(this))},removeItemsBy Path:function(paths){if(paths.length==0)return;this.removeItemsBeneathNode_(this .buildRemovalTree_(paths))},buildRemovalTree_:function(paths){var rootNode=new S electionTreeNode(paths[0].split(".")[0]);paths.forEach(function(path){var compon ents=path.split(".");var node=rootNode;components.shift();while(components.lengt h>1){var index=Number(components.shift());var arrayName=components.shift();if(!n ode.children[index])node.addChild(index,[node.currentPath,index,arrayName].join( "."));node=node.children[index]}node.leaf=true;node.indexes.push(Number(componen ts.shift()))});return rootNode},removeItemsBeneathNode_:function(node){var array =this.get(node.currentPath);var splices=[];node.indexes.sort(function(a,b){retur n b-a});node.indexes.forEach(function(index){if(node.leaf||this.removeItemsBenea thNode_(node.children[index])){var item=array.splice(index,1)[0];splices.push({i ndex:index,removed:[item],addedCount:0,object:array,type:"splice"})}}.bind(this) );if(array.length==0&&node.currentPath.indexOf(".")!=-1)return true;this.notifyS plices(node.currentPath,splices);return false},itemSelected_:function(e){var ite m=e.detail.element;var paths=[];var itemPath=item.path;if(e.detail.shiftKey&&thi s.lastSelectedPath){var itemPathComponents=itemPath.split(".");var itemIndex=Num ber(itemPathComponents.pop());var itemArrayPath=itemPathComponents.join(".");var lastItemPathComponents=this.lastSelectedPath.split(".");var lastItemIndex=Numbe r(lastItemPathComponents.pop());if(itemArrayPath==lastItemPathComponents.join(". ")){for(var i=Math.min(itemIndex,lastItemIndex);i<=Math.max(itemIndex,lastItemIn dex);i++){paths.push(itemArrayPath+"."+i)}}}if(paths.length==0)paths.push(item.p ath);var selected=!this.selectedPaths.has(item.path);paths.forEach(function(path ){this.set(path+".selected",selected);if(selected){this.selectedPaths.add(path); return}this.selectedPaths.delete(path)}.bind(this));this.lastSelectedPath=itemPa th}};
65 // Copyright 2015 The Chromium Authors. All rights reserved. 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 66 // Use of this source code is governed by a BSD-style license that can be
67 // found in the LICENSE file. 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(" load-more-history")},onOpenMenu_:function(e){var index=e.detail.index;var list=t his.$["infinite-list"];if(index<list.firstVisibleIndex||index>list.lastVisibleIn dex)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;retur n i==0||this.historyData_[i].dateRelativeDay!=this.historyData_[i-1].dateRelativ eDay},isCardEnd_:function(item,i,length){if(length==0||i>length-1)return false;r eturn i==length-1||this.historyData_[i].dateRelativeDay!=this.historyData_[i+1]. dateRelativeDay},pathForItem_:function(index){return"historyData_."+index}}); 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. 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 70 // Use of this source code is governed by a BSD-style license that can be
71 // found in the LICENSE file. 71 // found in the LICENSE file.
72 Polymer({is:"history-list-container",properties:{groupedRange:{type:Number,obser ver:"groupedRangeChanged_"},selectedPage_:String,grouped:Boolean,queryState:Obje ct,queryResult:Object,actionMenuModel_:Object},observers:["searchTermChanged_(qu eryState.searchTerm)","groupedOffsetChanged_(queryState.groupedOffset)"],listene rs:{"load-more-history":"loadMoreHistory_","open-menu":"openMenu_"},historyResul t:function(info,results){this.initializeResults_(info,results);this.closeMenu_() ;if(info.term&&!this.queryState.incremental){Polymer.IronA11yAnnouncer.requestAv ailability();this.fire("iron-announce",{text:md_history.HistoryItem.searchResult sTitle(results.length,info.term)})}var list=this.getSelectedList_();list.addNewR esults(results,this.queryState.incremental,info.finished)},queryHistory:function (incremental){var queryState=this.queryState;var noResults=!this.queryResult||th is.queryResult.results==null;if(queryState.queryingDisabled||!this.queryState.se archTerm&&noResults){return}var dialog=this.$.dialog.getIfExists();if(!increment al&&dialog&&dialog.open)dialog.close();this.set("queryState.querying",true);this .set("queryState.incremental",incremental);var lastVisitTime=0;if(incremental){v ar lastVisit=this.queryResult.results.slice(-1)[0];lastVisitTime=lastVisit?Math. floor(lastVisit.time):0}var maxResults=this.groupedRange==HistoryRange.ALL_TIME? RESULTS_PER_PAGE:0;chrome.send("queryHistory",[queryState.searchTerm,queryState. groupedOffset,queryState.range,lastVisitTime,maxResults])},historyDeleted:functi on(){if(this.getSelectedItemCount()>0)return;this.queryHistory(false)},getConten tScrollTarget:function(){return this.getSelectedList_()},getSelectedItemCount:fu nction(){return this.getSelectedList_().selectedPaths.size},unselectAllItems:fun ction(count){var selectedList=this.getSelectedList_();if(selectedList)selectedLi st.unselectAllItems(count)},deleteSelectedWithPrompt:function(){if(!loadTimeData .getBoolean("allowDeletingHistory"))return;var browserService=md_history.Browser Service.getInstance();browserService.recordAction("RemoveSelected");if(this.quer yState.searchTerm!="")browserService.recordAction("SearchResultRemove");this.$.d ialog.get().showModal();this.$$(".action-button").focus()},groupedRangeChanged_: function(range,oldRange){this.selectedPage_=range==HistoryRange.ALL_TIME?"infini te-list":"grouped-list";if(oldRange==undefined)return;this.set("queryState.group edOffset",0);if(this.queryResult.info){this.set("queryResult.results",[]);this.h istoryResult(this.queryResult.info,[])}this.queryHistory(false);this.fire("histo ry-view-changed")},searchTermChanged_:function(){this.queryHistory(false);if(thi s.queryState.searchTerm)md_history.BrowserService.getInstance().recordAction("Se arch")},groupedOffsetChanged_:function(){this.queryHistory(false)},loadMoreHisto ry_:function(){this.queryHistory(true)},initializeResults_:function(info,results ){if(results.length==0)return;var currentDate=results[0].dateRelativeDay;for(var i=0;i<results.length;i++){results[i].selected=false;results[i].readableTimestam p=info.term==""?results[i].dateTimeOfDay:results[i].dateShort;if(results[i].date RelativeDay!=currentDate){currentDate=results[i].dateRelativeDay}}},onDialogConf irmTap_:function(){md_history.BrowserService.getInstance().recordAction("Confirm RemoveSelected");this.getSelectedList_().deleteSelected();var dialog=assert(this .$.dialog.getIfExists());dialog.close()},onDialogCancelTap_:function(){md_histor y.BrowserService.getInstance().recordAction("CancelRemoveSelected");var dialog=a ssert(this.$.dialog.getIfExists());dialog.close()},closeMenu_:function(){var men u=this.$.sharedMenu.getIfExists();if(menu&&menu.open){this.actionMenuModel_=null ;menu.close()}},openMenu_:function(e){var target=e.detail.target;this.actionMenu Model_=e.detail;var menu=this.$.sharedMenu.get();menu.showAt(target)},onMoreFrom SiteTap_:function(){md_history.BrowserService.getInstance().recordAction("EntryM enuShowMoreFromSite");var menu=assert(this.$.sharedMenu.getIfExists());this.set( "queryState.searchTerm",this.actionMenuModel_.item.domain);this.actionMenuModel_ =null;this.closeMenu_()},onRemoveFromHistoryTap_:function(){var browserService=m d_history.BrowserService.getInstance();browserService.recordAction("EntryMenuRem oveFromHistory");var menu=assert(this.$.sharedMenu.getIfExists());var itemData=t his.actionMenuModel_;browserService.deleteItems([itemData.item]).then(function(i tems){this.fire("unselect-all");this.getSelectedList_().removeItemsByPath([itemD ata.path]);var index=itemData.index;if(index==undefined)return;var browserServic e=md_history.BrowserService.getInstance();browserService.recordHistogram("Histor yPage.RemoveEntryPosition",Math.min(index,UMA_MAX_BUCKET_VALUE),UMA_MAX_BUCKET_V ALUE);if(index<=UMA_MAX_SUBSET_BUCKET_VALUE){browserService.recordHistogram("His toryPage.RemoveEntryPositionSubset",index,UMA_MAX_SUBSET_BUCKET_VALUE)}}.bind(th is));this.closeMenu_()},getSelectedList_:function(){return this.$$("#"+this.sele ctedPage_)},canDeleteHistory_:function(){return loadTimeData.getBoolean("allowDe letingHistory")}});(function(){"use strict";Polymer({is:"iron-location",properti es:{path:{type:String,notify:true,value:function(){return window.decodeURICompon ent(window.location.pathname)}},query:{type:String,notify:true,value:function(){ return window.decodeURIComponent(window.location.search.slice(1))}},hash:{type:S tring,notify:true,value:function(){return window.decodeURIComponent(window.locat ion.hash.slice(1))}},dwellTime:{type:Number,value:2e3},urlSpaceRegex:{type:Strin g,value:""},_urlSpaceRegExp:{computed:"_makeRegExp(urlSpaceRegex)"},_lastChanged At:{type:Number},_initialized:{type:Boolean,value:false}},hostAttributes:{hidden :true},observers:["_updateUrl(path, query, hash)"],attached:function(){this.list en(window,"hashchange","_hashChanged");this.listen(window,"location-changed","_u rlChanged");this.listen(window,"popstate","_urlChanged");this.listen(document.bo dy,"click","_globalOnClick");this._lastChangedAt=window.performance.now()-(this. dwellTime-200);this._initialized=true;this._urlChanged()},detached:function(){th is.unlisten(window,"hashchange","_hashChanged");this.unlisten(window,"location-c hanged","_urlChanged");this.unlisten(window,"popstate","_urlChanged");this.unlis ten(document.body,"click","_globalOnClick");this._initialized=false},_hashChange d:function(){this.hash=window.decodeURIComponent(window.location.hash.substring( 1))},_urlChanged:function(){this._dontUpdateUrl=true;this._hashChanged();this.pa th=window.decodeURIComponent(window.location.pathname);this.query=window.decodeU RIComponent(window.location.search.substring(1));this._dontUpdateUrl=false;this. _updateUrl()},_getUrl:function(){var partiallyEncodedPath=window.encodeURI(this. path).replace(/\#/g,"%23").replace(/\?/g,"%3F");var partiallyEncodedQuery="";if( this.query){partiallyEncodedQuery="?"+window.encodeURI(this.query).replace(/\#/g ,"%23")}var partiallyEncodedHash="";if(this.hash){partiallyEncodedHash="#"+windo w.encodeURI(this.hash)}return partiallyEncodedPath+partiallyEncodedQuery+partial lyEncodedHash},_updateUrl:function(){if(this._dontUpdateUrl||!this._initialized) {return}if(this.path===window.decodeURIComponent(window.location.pathname)&&this .query===window.decodeURIComponent(window.location.search.substring(1))&&this.ha sh===window.decodeURIComponent(window.location.hash.substring(1))){return}var ne wUrl=this._getUrl();var fullNewUrl=new URL(newUrl,window.location.protocol+"//"+ window.location.host).href;var now=window.performance.now();var shouldReplace=th is._lastChangedAt+this.dwellTime>now;this._lastChangedAt=now;if(shouldReplace){w indow.history.replaceState({},"",fullNewUrl)}else{window.history.pushState({},"" ,fullNewUrl)}this.fire("location-changed",{},{node:window})},_globalOnClick:func tion(event){if(event.defaultPrevented){return}var href=this._getSameOriginLinkHr ef(event);if(!href){return}event.preventDefault();if(href===window.location.href ){return}window.history.pushState({},"",href);this.fire("location-changed",{},{n ode:window})},_getSameOriginLinkHref:function(event){if(event.button!==0){return null}if(event.metaKey||event.ctrlKey){return null}var eventPath=Polymer.dom(eve nt).path;var anchor=null;for(var i=0;i<eventPath.length;i++){var element=eventPa th[i];if(element.tagName==="A"&&element.href){anchor=element;break}}if(!anchor){ return null}if(anchor.target==="_blank"){return null}if((anchor.target==="_top"| |anchor.target==="_parent")&&window.top!==window){return null}var href=anchor.hr ef;var url;if(document.baseURI!=null){url=new URL(href,document.baseURI)}else{ur l=new URL(href)}var origin;if(window.location.origin){origin=window.location.ori gin}else{origin=window.location.protocol+"//"+window.location.hostname;if(window .location.port){origin+=":"+window.location.port}}if(url.origin!==origin){return null}var normalizedHref=url.pathname+url.search+url.hash;if(this._urlSpaceRegEx p&&!this._urlSpaceRegExp.test(normalizedHref)){return null}var fullNormalizedHre f=new URL(normalizedHref,window.location.href).href;return fullNormalizedHref},_ makeRegExp:function(urlSpaceRegex){return RegExp(urlSpaceRegex)}})})();"use stri ct";Polymer({is:"iron-query-params",properties:{paramsString:{type:String,notify :true,observer:"paramsStringChanged"},paramsObject:{type:Object,notify:true,valu e:function(){return{}}},_dontReact:{type:Boolean,value:false}},hostAttributes:{h idden:true},observers:["paramsObjectChanged(paramsObject.*)"],paramsStringChange d:function(){this._dontReact=true;this.paramsObject=this._decodeParams(this.para msString);this._dontReact=false},paramsObjectChanged:function(){if(this._dontRea ct){return}this.paramsString=this._encodeParams(this.paramsObject)},_encodeParam s:function(params){var encodedParams=[];for(var key in params){var value=params[ key];if(value===""){encodedParams.push(encodeURIComponent(key))}else if(value){e ncodedParams.push(encodeURIComponent(key)+"="+encodeURIComponent(value.toString( )))}}return encodedParams.join("&")},_decodeParams:function(paramString){var par ams={};paramString=(paramString||"").replace(/\+/g,"%20");var paramList=paramStr ing.split("&");for(var i=0;i<paramList.length;i++){var param=paramList[i].split( "=");if(param[0]){params[decodeURIComponent(param[0])]=decodeURIComponent(param[ 1]||"")}}return params}}); 72 Polymer({is:"history-list-container",properties:{groupedRange:{type:Number,obser ver:"groupedRangeChanged_"},selectedPage_:{type:String,computed:"computeSelected Page_(groupedRange)"},grouped:Boolean,queryState:Object,queryResult:Object,actio nMenuModel_:Object},observers:["groupedRangeChanged_(queryState.range)"],listene rs:{"open-menu":"openMenu_"},historyResult:function(info,results){this.initializ eResults_(info,results);this.closeMenu_();if(info.term&&!this.queryState.increme ntal){Polymer.IronA11yAnnouncer.requestAvailability();this.fire("iron-announce", {text:md_history.HistoryItem.searchResultsTitle(results.length,info.term)})}var list=this.getSelectedList_();list.addNewResults(results,this.queryState.incremen tal,info.finished)},historyDeleted:function(){if(this.getSelectedItemCount()>0)r eturn;this.fire("query-history",false)},getContentScrollTarget:function(){return this.getSelectedList_()},getSelectedItemCount:function(){return this.getSelecte dList_().selectedPaths.size},unselectAllItems:function(count){var selectedList=t his.getSelectedList_();if(selectedList)selectedList.unselectAllItems(count)},del eteSelectedWithPrompt:function(){if(!loadTimeData.getBoolean("allowDeletingHisto ry"))return;var browserService=md_history.BrowserService.getInstance();browserSe rvice.recordAction("RemoveSelected");if(this.queryState.searchTerm!="")browserSe rvice.recordAction("SearchResultRemove");this.$.dialog.get().showModal();this.$$ (".action-button").focus()},computeSelectedPage_:function(range){return range==H istoryRange.ALL_TIME?"infinite-list":"grouped-list"},groupedRangeChanged_:functi on(range){if(range!=HistoryRange.ALL_TIME&&this.queryResult.info){this.set("quer yResult.results",[]);this.historyResult(this.queryResult.info,[])}},initializeRe sults_:function(info,results){if(results.length==0)return;var currentDate=result s[0].dateRelativeDay;for(var i=0;i<results.length;i++){results[i].selected=false ;results[i].readableTimestamp=info.term==""?results[i].dateTimeOfDay:results[i]. dateShort;if(results[i].dateRelativeDay!=currentDate){currentDate=results[i].dat eRelativeDay}}},onDialogConfirmTap_:function(){md_history.BrowserService.getInst ance().recordAction("ConfirmRemoveSelected");this.getSelectedList_().deleteSelec ted();var dialog=assert(this.$.dialog.getIfExists());dialog.close()},onDialogCan celTap_:function(){md_history.BrowserService.getInstance().recordAction("CancelR emoveSelected");var dialog=assert(this.$.dialog.getIfExists());dialog.close()},c loseMenu_:function(){var menu=this.$.sharedMenu.getIfExists();if(menu&&menu.open ){this.actionMenuModel_=null;menu.close()}},openMenu_:function(e){var target=e.d etail.target;this.actionMenuModel_=e.detail;var menu=this.$.sharedMenu.get();men u.showAt(target)},onMoreFromSiteTap_:function(){md_history.BrowserService.getIns tance().recordAction("EntryMenuShowMoreFromSite");var menu=assert(this.$.sharedM enu.getIfExists());this.set("queryState.searchTerm",this.actionMenuModel_.item.d omain);this.actionMenuModel_=null;this.closeMenu_()},onRemoveFromHistoryTap_:fun ction(){var browserService=md_history.BrowserService.getInstance();browserServic e.recordAction("EntryMenuRemoveFromHistory");var menu=assert(this.$.sharedMenu.g etIfExists());var itemData=this.actionMenuModel_;browserService.deleteItems([ite mData.item]).then(function(items){this.fire("unselect-all");this.getSelectedList _().removeItemsByPath([itemData.path]);var index=itemData.index;if(index==undefi ned)return;var browserService=md_history.BrowserService.getInstance();browserSer vice.recordHistogram("HistoryPage.RemoveEntryPosition",Math.min(index,UMA_MAX_BU CKET_VALUE),UMA_MAX_BUCKET_VALUE);if(index<=UMA_MAX_SUBSET_BUCKET_VALUE){browser Service.recordHistogram("HistoryPage.RemoveEntryPositionSubset",index,UMA_MAX_SU BSET_BUCKET_VALUE)}}.bind(this));this.closeMenu_()},getSelectedList_:function(){ return this.$$("#"+this.selectedPage_)},canDeleteHistory_:function(){return load TimeData.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},groupedRange_:{type:Number,computed:"computeGroupedRange_(queryState.range) "},queryResult:Object},observers:["searchTermChanged_(queryState.searchTerm)","g roupedOffsetChanged_(queryState.groupedOffset)"],boundOnQueryHistory_:null,attac hed:function(){this.boundOnQueryHistory_=this.onQueryHistory_.bind(this);documen t.addEventListener("query-history",this.boundOnQueryHistory_)},detached:function (){document.removeEventListener("query-history",this.boundOnQueryHistory_)},quer yHistory_:function(incremental){var queryState=this.queryState;var noResults=!th is.queryResult||this.queryResult.results==null;if(queryState.queryingDisabled||! this.queryState.searchTerm&&noResults){return}this.set("queryState.querying",tru e);this.set("queryState.incremental",incremental);var lastVisitTime=0;if(increme ntal){var lastVisit=this.queryResult.results.slice(-1)[0];lastVisitTime=lastVisi t?Math.floor(lastVisit.time):0}var maxResults=this.queryState.range==HistoryRang e.ALL_TIME?RESULTS_PER_PAGE:0;chrome.send("queryHistory",[queryState.searchTerm, queryState.groupedOffset,queryState.range,lastVisitTime,maxResults])},onQueryHis tory_:function(e){this.queryHistory_(e.detail);return false},groupedOffsetChange d_:function(){this.queryHistory_(false)},computeGroupedRange_:function(range){if (this.groupedRange_!=undefined){this.set("queryState.groupedOffset",0);this.quer yHistory_(false);this.fire("history-view-changed")}return range},searchTermChang ed_:function(){this.queryHistory_(false);if(this.queryState.searchTerm)md_histor y.BrowserService.getInstance().recordAction("Search")}});(function(){"use strict ";Polymer({is:"iron-location",properties:{path:{type:String,notify:true,value:fu nction(){return window.decodeURIComponent(window.location.pathname)}},query:{typ e:String,notify:true,value:function(){return window.decodeURIComponent(window.lo cation.search.slice(1))}},hash:{type:String,notify:true,value:function(){return window.decodeURIComponent(window.location.hash.slice(1))}},dwellTime:{type:Numbe r,value:2e3},urlSpaceRegex:{type:String,value:""},_urlSpaceRegExp:{computed:"_ma keRegExp(urlSpaceRegex)"},_lastChangedAt:{type:Number},_initialized:{type:Boolea n,value:false}},hostAttributes:{hidden:true},observers:["_updateUrl(path, query, hash)"],attached:function(){this.listen(window,"hashchange","_hashChanged");thi s.listen(window,"location-changed","_urlChanged");this.listen(window,"popstate", "_urlChanged");this.listen(document.body,"click","_globalOnClick");this._lastCha ngedAt=window.performance.now()-(this.dwellTime-200);this._initialized=true;this ._urlChanged()},detached:function(){this.unlisten(window,"hashchange","_hashChan ged");this.unlisten(window,"location-changed","_urlChanged");this.unlisten(windo w,"popstate","_urlChanged");this.unlisten(document.body,"click","_globalOnClick" );this._initialized=false},_hashChanged:function(){this.hash=window.decodeURICom ponent(window.location.hash.substring(1))},_urlChanged:function(){this._dontUpda teUrl=true;this._hashChanged();this.path=window.decodeURIComponent(window.locati on.pathname);this.query=window.decodeURIComponent(window.location.search.substri ng(1));this._dontUpdateUrl=false;this._updateUrl()},_getUrl:function(){var parti allyEncodedPath=window.encodeURI(this.path).replace(/\#/g,"%23").replace(/\?/g," %3F");var partiallyEncodedQuery="";if(this.query){partiallyEncodedQuery="?"+wind ow.encodeURI(this.query).replace(/\#/g,"%23")}var partiallyEncodedHash="";if(thi s.hash){partiallyEncodedHash="#"+window.encodeURI(this.hash)}return partiallyEnc odedPath+partiallyEncodedQuery+partiallyEncodedHash},_updateUrl:function(){if(th is._dontUpdateUrl||!this._initialized){return}if(this.path===window.decodeURICom ponent(window.location.pathname)&&this.query===window.decodeURIComponent(window. location.search.substring(1))&&this.hash===window.decodeURIComponent(window.loca tion.hash.substring(1))){return}var newUrl=this._getUrl();var fullNewUrl=new URL (newUrl,window.location.protocol+"//"+window.location.host).href;var now=window. performance.now();var shouldReplace=this._lastChangedAt+this.dwellTime>now;this. _lastChangedAt=now;if(shouldReplace){window.history.replaceState({},"",fullNewUr l)}else{window.history.pushState({},"",fullNewUrl)}this.fire("location-changed", {},{node:window})},_globalOnClick:function(event){if(event.defaultPrevented){ret urn}var href=this._getSameOriginLinkHref(event);if(!href){return}event.preventDe fault();if(href===window.location.href){return}window.history.pushState({},"",hr ef);this.fire("location-changed",{},{node:window})},_getSameOriginLinkHref:funct ion(event){if(event.button!==0){return null}if(event.metaKey||event.ctrlKey){ret urn null}var eventPath=Polymer.dom(event).path;var anchor=null;for(var i=0;i<eve ntPath.length;i++){var element=eventPath[i];if(element.tagName==="A"&&element.hr ef){anchor=element;break}}if(!anchor){return null}if(anchor.target==="_blank"){r eturn null}if((anchor.target==="_top"||anchor.target==="_parent")&&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 origin;if(window.locat ion.origin){origin=window.location.origin}else{origin=window.location.protocol+" //"+window.location.hostname;if(window.location.port){origin+=":"+window.locatio n.port}}if(url.origin!==origin){return null}var normalizedHref=url.pathname+url. search+url.hash;if(this._urlSpaceRegExp&&!this._urlSpaceRegExp.test(normalizedHr ef)){return null}var fullNormalizedHref=new URL(normalizedHref,window.location.h ref).href;return fullNormalizedHref},_makeRegExp:function(urlSpaceRegex){return RegExp(urlSpaceRegex)}})})();"use strict";Polymer({is:"iron-query-params",proper ties:{paramsString:{type:String,notify:true,observer:"paramsStringChanged"},para msObject:{type:Object,notify:true,value:function(){return{}}},_dontReact:{type:B oolean,value:false}},hostAttributes:{hidden:true},observers:["paramsObjectChange d(paramsObject.*)"],paramsStringChanged:function(){this._dontReact=true;this.par amsObject=this._decodeParams(this.paramsString);this._dontReact=false},paramsObj ectChanged:function(){if(this._dontReact){return}this.paramsString=this._encodeP arams(this.paramsObject)},_encodeParams:function(params){var encodedParams=[];fo r(var key in params){var value=params[key];if(value===""){encodedParams.push(enc odeURIComponent(key))}else if(value){encodedParams.push(encodeURIComponent(key)+ "="+encodeURIComponent(value.toString()))}}return encodedParams.join("&")},_deco deParams:function(paramString){var params={};paramString=(paramString||"").repla ce(/\+/g,"%20");var paramList=paramString.split("&");for(var i=0;i<paramList.len gth;i++){var param=paramList[i].split("=");if(param[0]){params[decodeURIComponen t(param[0])]=decodeURIComponent(param[1]||"")}}return params}});
73 // Copyright 2016 The Chromium Authors. All rights reserved. 77 // Copyright 2016 The Chromium Authors. All rights reserved.
74 // Use of this source code is governed by a BSD-style license that can be 78 // Use of this source code is governed by a BSD-style license that can be
75 // found in the LICENSE file. 79 // found in the LICENSE file.
76 Polymer({is:"history-router",properties:{selectedPage:{type:String,observer:"ser ializePath_",notify:true},queryState:{type:Object,notify:true},path_:{type:Strin g,observer:"pathChanged_"},queryParams_:Object},observers:["queryParamsChanged_( queryParams_.*)","searchTermChanged_(queryState.searchTerm)"],attached:function( ){if(window.location.hash){window.location.href=window.location.href.split("#")[ 0]+"?"+window.location.hash.substr(1)}},serializePath_:function(){var page=this. selectedPage=="history"?"":this.selectedPage;this.path_="/"+page},pathChanged_:f unction(){var sections=this.path_.substr(1).split("/");this.selectedPage=section s[0]||"history"},queryParamsChanged_:function(){this.set("queryState.searchTerm" ,this.queryParams_.q||"")},searchTermChanged_:function(){this.set("queryParams_. q",this.queryState.searchTerm||null)}});Polymer.IronMultiSelectableBehaviorImpl= {properties:{multi:{type:Boolean,value:false,observer:"multiChanged"},selectedVa lues:{type:Array,notify:true},selectedItems:{type:Array,readOnly:true,notify:tru e}},observers:["_updateSelected(selectedValues.splices)"],select:function(value) {if(this.multi){if(this.selectedValues){this._toggleSelected(value)}else{this.se lectedValues=[value]}}else{this.selected=value}},multiChanged:function(multi){th is._selection.multi=multi},get _shouldUpdateSelection(){return this.selected!=nu ll||this.selectedValues!=null&&this.selectedValues.length},_updateAttrForSelecte d:function(){if(!this.multi){Polymer.IronSelectableBehavior._updateAttrForSelect ed.apply(this)}else if(this._shouldUpdateSelection){this.selectedValues=this.sel ectedItems.map(function(selectedItem){return this._indexToValue(this.indexOf(sel ectedItem))},this).filter(function(unfilteredValue){return unfilteredValue!=null },this)}},_updateSelected:function(){if(this.multi){this._selectMulti(this.selec tedValues)}else{this._selectSelected(this.selected)}},_selectMulti:function(valu es){if(values){var selectedItems=this._valuesToItems(values);this._selection.cle ar(selectedItems);for(var i=0;i<selectedItems.length;i++){this._selection.setIte mSelected(selectedItems[i],true)}if(this.fallbackSelection&&this.items.length&&! this._selection.get().length){var fallback=this._valueToItem(this.fallbackSelect ion);if(fallback){this.selectedValues=[this.fallbackSelection]}}}else{this._sele ction.clear()}},_selectionChange:function(){var s=this._selection.get();if(this. multi){this._setSelectedItems(s)}else{this._setSelectedItems([s]);this._setSelec tedItem(s)}},_toggleSelected:function(value){var i=this.selectedValues.indexOf(v alue);var unselected=i<0;if(unselected){this.push("selectedValues",value)}else{t his.splice("selectedValues",i,1)}},_valuesToItems:function(values){return values ==null?null:values.map(function(value){return this._valueToItem(value)},this)}}; Polymer.IronMultiSelectableBehavior=[Polymer.IronSelectableBehavior,Polymer.Iron MultiSelectableBehaviorImpl];Polymer({is:"iron-selector",behaviors:[Polymer.Iron MultiSelectableBehavior]}); 80 Polymer({is:"history-router",properties:{selectedPage:{type:String,observer:"ser ializePath_",notify:true},queryState:{type:Object,notify:true,value:function(){r eturn{incremental:false,querying:true,queryingDisabled:false,_range:HistoryRange .ALL_TIME,searchTerm:"",groupedOffset:0,set range(val){this._range=Number(val)}, get range(){return this._range}}}},path_:{type:String,observer:"pathChanged_"},q ueryParams_:Object},observers:["queryParamsChanged_(queryParams_.*)","searchTerm Changed_(queryState.searchTerm)"],attached:function(){if(window.location.hash){w indow.location.href=window.location.href.split("#")[0]+"?"+window.location.hash. substr(1)}},serializePath_:function(){var page=this.selectedPage=="history"?"":t his.selectedPage;this.path_="/"+page},pathChanged_:function(){var sections=this. path_.substr(1).split("/");this.selectedPage=sections[0]||"history"},queryParams Changed_:function(){this.set("queryState.searchTerm",this.queryParams_.q||"")},s earchTermChanged_:function(){this.set("queryParams_.q",this.queryState.searchTer m||null)}});Polymer.IronMultiSelectableBehaviorImpl={properties:{multi:{type:Boo lean,value:false,observer:"multiChanged"},selectedValues:{type:Array,notify:true },selectedItems:{type:Array,readOnly:true,notify:true}},observers:["_updateSelec ted(selectedValues.splices)"],select:function(value){if(this.multi){if(this.sele ctedValues){this._toggleSelected(value)}else{this.selectedValues=[value]}}else{t his.selected=value}},multiChanged:function(multi){this._selection.multi=multi},g et _shouldUpdateSelection(){return this.selected!=null||this.selectedValues!=nul l&&this.selectedValues.length},_updateAttrForSelected:function(){if(!this.multi) {Polymer.IronSelectableBehavior._updateAttrForSelected.apply(this)}else if(this. _shouldUpdateSelection){this.selectedValues=this.selectedItems.map(function(sele ctedItem){return this._indexToValue(this.indexOf(selectedItem))},this).filter(fu nction(unfilteredValue){return unfilteredValue!=null},this)}},_updateSelected:fu nction(){if(this.multi){this._selectMulti(this.selectedValues)}else{this._select Selected(this.selected)}},_selectMulti:function(values){if(values){var selectedI tems=this._valuesToItems(values);this._selection.clear(selectedItems);for(var i= 0;i<selectedItems.length;i++){this._selection.setItemSelected(selectedItems[i],t rue)}if(this.fallbackSelection&&this.items.length&&!this._selection.get().length ){var fallback=this._valueToItem(this.fallbackSelection);if(fallback){this.selec tedValues=[this.fallbackSelection]}}}else{this._selection.clear()}},_selectionCh ange:function(){var s=this._selection.get();if(this.multi){this._setSelectedItem s(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",value)}else{this.splice("selectedValues", i,1)}},_valuesToItems:function(values){return values==null?null:values.map(funct ion(value){return this._valueToItem(value)},this)}};Polymer.IronMultiSelectableB ehavior=[Polymer.IronSelectableBehavior,Polymer.IronMultiSelectableBehaviorImpl] ;Polymer({is:"iron-selector",behaviors:[Polymer.IronMultiSelectableBehavior]});
77 // Copyright 2016 The Chromium Authors. All rights reserved. 81 // Copyright 2016 The Chromium Authors. All rights reserved.
78 // Use of this source code is governed by a BSD-style license that can be 82 // Use of this source code is governed by a BSD-style license that can be
79 // found in the LICENSE file. 83 // found in the LICENSE file.
80 Polymer({is:"history-side-bar",behaviors:[Polymer.IronA11yKeysBehavior],properti es:{selectedPage:{type:String,notify:true},showFooter:Boolean},keyBindings:{"spa ce:keydown":"onSpacePressed_"},onSpacePressed_:function(e){e.detail.keyboardEven t.path[0].click()},onSelectorActivate_:function(){this.fire("history-close-drawe r")},onClearBrowsingDataTap_:function(e){var browserService=md_history.BrowserSe rvice.getInstance();browserService.recordAction("InitClearBrowsingData");browser Service.openClearBrowsingData();this.$["cbd-ripple"].upAction();e.preventDefault ()},onItemClick_:function(e){e.preventDefault()}}); 84 Polymer({is:"history-side-bar",behaviors:[Polymer.IronA11yKeysBehavior],properti es:{selectedPage:{type:String,notify:true},showFooter:Boolean},keyBindings:{"spa ce:keydown":"onSpacePressed_"},onSpacePressed_:function(e){e.detail.keyboardEven t.path[0].click()},onSelectorActivate_:function(){this.fire("history-close-drawe r")},onClearBrowsingDataTap_:function(e){var browserService=md_history.BrowserSe rvice.getInstance();browserService.recordAction("InitClearBrowsingData");browser Service.openClearBrowsingData();this.$["cbd-ripple"].upAction();e.preventDefault ()},onItemClick_:function(e){e.preventDefault()}});
81 // Copyright 2016 The Chromium Authors. All rights reserved. 85 // Copyright 2016 The Chromium Authors. All rights reserved.
82 // Use of this source code is governed by a BSD-style license that can be 86 // Use of this source code is governed by a BSD-style license that can be
83 // found in the LICENSE file. 87 // found in the LICENSE file.
84 cr.define("md_history",function(){var lazyLoadPromise=null;function ensureLazyLo aded(){if(!lazyLoadPromise){lazyLoadPromise=new Promise(function(resolve,reject) {Polymer.Base.importHref("chrome://history/lazy_load.html",resolve,reject,true)} )}return lazyLoadPromise}return{ensureLazyLoaded:ensureLazyLoaded}});Polymer({is :"history-app",behaviors:[Polymer.IronScrollTargetBehavior],properties:{selected Page_:{type:String,observer:"selectedPageChanged_"},grouped_:{type:Boolean,refle ctToAttribute:true},queryState_:{type:Object,value:function(){return{incremental :false,querying:true,queryingDisabled:false,_range:HistoryRange.ALL_TIME,searchT erm:"",groupedOffset:0,set range(val){this._range=Number(val)},get range(){retur n this._range}}}},queryResult_:{type:Object,value:function(){return{info:null,re sults:null,sessionList:null}}},isUserSignedIn_:{type:Boolean,value:loadTimeData. getBoolean("isUserSignedIn")},toolbarShadow_:{type:Boolean,reflectToAttribute:tr ue,notify:true},showMenuPromo_:{type:Boolean,value:function(){return loadTimeDat a.getBoolean("showMenuPromo")}},hasDrawer_:{type:Boolean,observer:"hasDrawerChan ged_"},showSidebarFooter:Boolean,hasSyncedResults:Boolean},listeners:{"cr-toolba r-menu-promo-close":"onCrToolbarMenuPromoClose_","cr-toolbar-menu-promo-shown":" onCrToolbarMenuPromoShown_","cr-toolbar-menu-tap":"onCrToolbarMenuTap_","delete- selected":"deleteSelected","history-checkbox-select":"checkboxSelected","history -close-drawer":"closeDrawer_","history-view-changed":"historyViewChanged_","open ed-changed":"onOpenedChanged_","unselect-all":"unselectAll"},boundOnCanExecute_: null,boundOnCommand_:null,attached:function(){this.grouped_=loadTimeData.getBool ean("groupByDomain");cr.ui.decorate("command",cr.ui.Command);this.boundOnCanExec ute_=this.onCanExecute_.bind(this);this.boundOnCommand_=this.onCommand_.bind(thi s);document.addEventListener("canExecute",this.boundOnCanExecute_);document.addE ventListener("command",this.boundOnCommand_)},detached:function(){document.remov eEventListener("canExecute",this.boundOnCanExecute_);document.removeEventListene r("command",this.boundOnCommand_)},onFirstRender:function(){setTimeout(function( ){chrome.send("metricsHandler:recordTime",["History.ResultsRenderedTime",window. performance.now()])});var searchField=this.$.toolbar.searchField;if(!searchField .narrow){searchField.getSearchInput().focus()}md_history.ensureLazyLoaded().then (function(){window.requestIdleCallback(function(){document.fonts.load("bold 12px Roboto")})})},_scrollHandler:function(){if(this.scrollTarget)this.toolbarShadow _=this.scrollTarget.scrollTop!=0},onCrToolbarMenuPromoClose_:function(){this.sho wMenuPromo_=false},onCrToolbarMenuPromoShown_:function(){md_history.BrowserServi ce.getInstance().menuPromoShown()},onCrToolbarMenuTap_:function(){var drawer=thi s.$.drawer.get();drawer.align=document.documentElement.dir=="ltr"?"left":"right" ;drawer.toggle()},onOpenedChanged_:function(e){if(e.detail.value)this.showMenuPr omo_=false},checkboxSelected:function(e){var toolbar=this.$.toolbar;toolbar.coun t=this.$.history.getSelectedItemCount()},unselectAll:function(){var listContaine r=this.$.history;var toolbar=this.$.toolbar;listContainer.unselectAllItems(toolb ar.count);toolbar.count=0},deleteSelected:function(){this.$.history.deleteSelect edWithPrompt()},historyResult:function(info,results){this.set("queryState_.query ing",false);this.set("queryResult_.info",info);this.set("queryResult_.results",r esults);var listContainer=this.$["history"];listContainer.historyResult(info,res ults)},focusToolbarSearchField:function(){this.$.toolbar.showSearchField()},onCa nExecute_:function(e){e=e;switch(e.command.id){case"find-command":case"toggle-gr ouped":e.canExecute=true;break;case"slash-command":e.canExecute=!this.$.toolbar. searchField.isSearchFocused();break;case"delete-command":e.canExecute=this.$.too lbar.count>0;break}},onCommand_:function(e){if(e.command.id=="find-command"||e.c ommand.id=="slash-command")this.focusToolbarSearchField();if(e.command.id=="dele te-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.historyDel eted()},updateSignInState:function(isUserSignedIn){this.isUserSignedIn_=isUserSi gnedIn},syncedTabsSelected_:function(selectedPage){return selectedPage=="syncedT abs"},shouldShowSpinner_:function(querying,incremental,searchTerm){return queryi ng&&!incremental&&searchTerm!=""},showSyncNotice_:function(hasSyncedResults,sele ctedPage){return hasSyncedResults&&selectedPage!="syncedTabs"},selectedPageChang ed_:function(){this.unselectAll();this.historyViewChanged_()},historyViewChanged _:function(){requestAnimationFrame(function(){md_history.ensureLazyLoaded().then (function(){if(!this.$.content.selectedItem)return;this.scrollTarget=this.$.cont ent.selectedItem.getContentScrollTarget();this._scrollHandler()}.bind(this))}.bi nd(this));this.recordHistoryPageView_()},hasDrawerChanged_:function(){var drawer =this.$.drawer.getIfExists();if(!this.hasDrawer_&&drawer&&drawer.open)drawer.clo seDrawer()},getSelectedPage_:function(selectedPage,items){return selectedPage},c loseDrawer_:function(){var drawer=this.$.drawer.get();if(drawer&&drawer.open)dra wer.closeDrawer()},recordHistoryPageView_:function(){var histogramValue=HistoryP ageViewHistogram.END;switch(this.selectedPage_){case"syncedTabs":histogramValue= this.isUserSignedIn_?HistoryPageViewHistogram.SYNCED_TABS:HistoryPageViewHistogr am.SIGNIN_PROMO;break;default:switch(this.queryState_.range){case HistoryRange.A LL_TIME:histogramValue=HistoryPageViewHistogram.HISTORY;break;case HistoryRange. WEEK:histogramValue=HistoryPageViewHistogram.GROUPED_WEEK;break;case HistoryRang e.MONTH:histogramValue=HistoryPageViewHistogram.GROUPED_MONTH;break}break}md_his tory.BrowserService.getInstance().recordHistogram("History.HistoryPageView",hist ogramValue,HistoryPageViewHistogram.END)}}); 88 cr.define("md_history",function(){var lazyLoadPromise=null;function ensureLazyLo aded(){if(!lazyLoadPromise){lazyLoadPromise=new Promise(function(resolve,reject) {Polymer.Base.importHref("chrome://history/lazy_load.html",resolve,reject,true)} )}return lazyLoadPromise}return{ensureLazyLoaded:ensureLazyLoaded}});Polymer({is :"history-app",behaviors:[Polymer.IronScrollTargetBehavior],properties:{selected Page_:{type:String,observer:"selectedPageChanged_"},grouped_:{type:Boolean,refle ctToAttribute:true},queryResult_:{type:Object,value:function(){return{info:null, results:null,sessionList:null}}},isUserSignedIn_:{type:Boolean,value:loadTimeDat a.getBoolean("isUserSignedIn")},toolbarShadow_:{type:Boolean,reflectToAttribute: true,notify:true},showMenuPromo_:{type:Boolean,value:function(){return loadTimeD ata.getBoolean("showMenuPromo")}},queryState_:Object,hasDrawer_:{type:Boolean,ob server:"hasDrawerChanged_"},showSidebarFooter:Boolean,hasSyncedResults:Boolean}, listeners:{"cr-toolbar-menu-promo-close":"onCrToolbarMenuPromoClose_","cr-toolba r-menu-promo-shown":"onCrToolbarMenuPromoShown_","cr-toolbar-menu-tap":"onCrTool barMenuTap_","delete-selected":"deleteSelected","history-checkbox-select":"check boxSelected","history-close-drawer":"closeDrawer_","history-view-changed":"histo ryViewChanged_","opened-changed":"onOpenedChanged_","unselect-all":"unselectAll" },boundOnCanExecute_:null,boundOnCommand_:null,attached:function(){this.grouped_ =loadTimeData.getBoolean("groupByDomain");cr.ui.decorate("command",cr.ui.Command );this.boundOnCanExecute_=this.onCanExecute_.bind(this);this.boundOnCommand_=thi s.onCommand_.bind(this);document.addEventListener("canExecute",this.boundOnCanEx ecute_);document.addEventListener("command",this.boundOnCommand_)},detached:func tion(){document.removeEventListener("canExecute",this.boundOnCanExecute_);docume nt.removeEventListener("command",this.boundOnCommand_)},onFirstRender:function() {setTimeout(function(){chrome.send("metricsHandler:recordTime",["History.Results RenderedTime",window.performance.now()])});var searchField=this.$.toolbar.search Field;if(!searchField.narrow){searchField.getSearchInput().focus()}md_history.en sureLazyLoaded().then(function(){window.requestIdleCallback(function(){document. fonts.load("bold 12px Roboto")})})},_scrollHandler:function(){if(this.scrollTarg et)this.toolbarShadow_=this.scrollTarget.scrollTop!=0},onCrToolbarMenuPromoClose _:function(){this.showMenuPromo_=false},onCrToolbarMenuPromoShown_:function(){md _history.BrowserService.getInstance().menuPromoShown()},onCrToolbarMenuTap_:func tion(){var drawer=this.$.drawer.get();drawer.align=document.documentElement.dir= ="ltr"?"left":"right";drawer.toggle()},onOpenedChanged_:function(e){if(e.detail. value)this.showMenuPromo_=false},checkboxSelected:function(e){var toolbar=this.$ .toolbar;toolbar.count=this.$.history.getSelectedItemCount()},unselectAll:functi on(){var listContainer=this.$.history;var toolbar=this.$.toolbar;listContainer.u nselectAllItems(toolbar.count);toolbar.count=0},deleteSelected:function(){this.$ .history.deleteSelectedWithPrompt()},historyResult:function(info,results){this.s et("queryState_.querying",false);this.set("queryResult_.info",info);this.set("qu eryResult_.results",results);var listContainer=this.$["history"];listContainer.h istoryResult(info,results)},focusToolbarSearchField:function(){this.$.toolbar.sh owSearchField()},onCanExecute_:function(e){e=e;switch(e.command.id){case"find-co mmand":case"toggle-grouped":e.canExecute=true;break;case"slash-command":e.canExe cute=!this.$.toolbar.searchField.isSearchFocused();break;case"delete-command":e. canExecute=this.$.toolbar.count>0;break}},onCommand_:function(e){if(e.command.id =="find-command"||e.command.id=="slash-command")this.focusToolbarSearchField();i f(e.command.id=="delete-command")this.deleteSelected();if(e.command.id=="toggle- grouped")this.grouped_=!this.grouped_},setForeignSessions:function(sessionList){ this.set("queryResult_.sessionList",sessionList)},historyDeleted:function(){this .$.history.historyDeleted()},updateSignInState:function(isUserSignedIn){this.isU serSignedIn_=isUserSignedIn},syncedTabsSelected_:function(selectedPage){return s electedPage=="syncedTabs"},shouldShowSpinner_:function(querying,incremental,sear chTerm){return querying&&!incremental&&searchTerm!=""},showSyncNotice_:function( hasSyncedResults,selectedPage){return hasSyncedResults&&selectedPage!="syncedTab s"},selectedPageChanged_:function(){this.unselectAll();this.historyViewChanged_( )},historyViewChanged_:function(){requestAnimationFrame(function(){md_history.en sureLazyLoaded().then(function(){if(!this.$.content.selectedItem)return;this.scr ollTarget=this.$.content.selectedItem.getContentScrollTarget();this._scrollHandl er()}.bind(this))}.bind(this));this.recordHistoryPageView_()},hasDrawerChanged_: function(){var drawer=this.$.drawer.getIfExists();if(!this.hasDrawer_&&drawer&&d rawer.open)drawer.closeDrawer()},getSelectedPage_:function(selectedPage,items){r eturn selectedPage},closeDrawer_:function(){var drawer=this.$.drawer.get();if(dr awer&&drawer.open)drawer.closeDrawer()},recordHistoryPageView_:function(){var hi stogramValue=HistoryPageViewHistogram.END;switch(this.selectedPage_){case"synced Tabs":histogramValue=this.isUserSignedIn_?HistoryPageViewHistogram.SYNCED_TABS:H istoryPageViewHistogram.SIGNIN_PROMO;break;default:switch(this.queryState_.range ){case HistoryRange.ALL_TIME:histogramValue=HistoryPageViewHistogram.HISTORY;bre ak;case HistoryRange.WEEK:histogramValue=HistoryPageViewHistogram.GROUPED_WEEK;b reak;case HistoryRange.MONTH:histogramValue=HistoryPageViewHistogram.GROUPED_MON TH;break}break}md_history.BrowserService.getInstance().recordHistogram("History. HistoryPageView",histogramValue,HistoryPageViewHistogram.END)}});
OLDNEW
« no previous file with comments | « chrome/browser/resources/md_history/app.js ('k') | chrome/browser/resources/md_history/app.vulcanized.html » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698