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

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

Issue 2503983002: MD History: Focus item checkbox when selecting/deselecting on click (Closed)
Patch Set: Add a test Created 4 years, 1 month 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
« no previous file with comments | « no previous file | chrome/browser/resources/md_history/history_item.js » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
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 41 matching lines...) Expand 10 before | Expand all | Expand 10 after
52 // Use of this source code is governed by a BSD-style license that can be 52 // Use of this source code is governed by a BSD-style license that can be
53 // found in the LICENSE file. 53 // found in the LICENSE file.
54 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}}); 54 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}});
55 // Copyright 2016 The Chromium Authors. All rights reserved. 55 // Copyright 2016 The Chromium Authors. All rights reserved.
56 // Use of this source code is governed by a BSD-style license that can be 56 // Use of this source code is governed by a BSD-style license that can be
57 // found in the LICENSE file. 57 // found in the LICENSE file.
58 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)))}}); 58 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)))}});
59 // Copyright 2015 The Chromium Authors. All rights reserved. 59 // Copyright 2015 The Chromium Authors. All rights reserved.
60 // Use of this source code is governed by a BSD-style license that can be 60 // Use of this source code is governed by a BSD-style license that can be
61 // found in the LICENSE file. 61 // found in the LICENSE file.
62 function HistoryFocusRow(root,boundary,delegate){cr.ui.FocusRow.call(this,root,b oundary,delegate);this.addItems()}HistoryFocusRow.prototype={__proto__:cr.ui.Foc usRow.prototype,getCustomEquivalent:function(sampleElement){var equivalent;if(th is.getTypeForElement(sampleElement)=="star")equivalent=this.getFirstFocusable("t itle");return equivalent||cr.ui.FocusRow.prototype.getCustomEquivalent.call(this ,sampleElement)},addItems:function(){this.destroy();assert(this.addItem("checkbo x","#checkbox"));assert(this.addItem("title","#title"));assert(this.addItem("men u-button","#menu-button"));this.addItem("star","#bookmark-star")}};cr.define("md _history",function(){function FocusRowDelegate(historyItemElement){this.historyI temElement=historyItemElement}FocusRowDelegate.prototype={onFocus:function(row,e ){this.historyItemElement.lastFocused=e.path[0]},onKeydown:function(row,e){if(e. key=="Enter")e.stopPropagation();return false}};var HistoryItem=Polymer({is:"his tory-item",properties:{item:{type:Object,observer:"showIcon_"},searchTerm:{type: String},selected:{type:Boolean,reflectToAttribute:true},isCardStart:{type:Boolea n,reflectToAttribute:true},isCardEnd:{type:Boolean,reflectToAttribute:true},embe dded:{type:Boolean,reflectToAttribute:true},hasTimeGap:{type:Boolean},numberOfIt ems:{type:Number},path:String,index:Number,lastFocused:{type:Object,notify:true} ,ironListTabIndex:{type:Number,observer:"ironListTabIndexChanged_"}},row_:null,a ttached:function(){Polymer.RenderStatus.afterNextRender(this,function(){this.row _=new HistoryFocusRow(this.$["main-container"],null,new FocusRowDelegate(this)); this.row_.makeActive(this.ironListTabIndex==0);this.listen(this,"focus","onFocus _");this.listen(this,"dom-change","onDomChange_")})},detached:function(){this.un listen(this,"focus","onFocus_");this.unlisten(this,"dom-change","onDomChange_"); if(this.row_)this.row_.destroy()},onFocus_:function(){if(this.lastFocused)this.r ow_.getEquivalentElement(this.lastFocused).focus();else this.row_.getFirstFocusa ble().focus();this.tabIndex=-1},ironListTabIndexChanged_:function(){if(this.row_ )this.row_.makeActive(this.ironListTabIndex==0)},onDomChange_:function(){if(this .row_)this.row_.addItems()},onItemClick_:function(e){for(var i=0;i<e.path.length ;i++){var elem=e.path[i];if(elem.id!="checkbox"&&(elem.nodeName=="A"||elem.nodeN ame=="BUTTON")){return}}if(this.selectionNotAllowed_())return;this.fire("history -checkbox-select",{element:this,shiftKey:e.shiftKey})},onItemMousedown_:function (e){if(e.shiftKey)e.preventDefault()},getEntrySummary_:function(){var item=this. item;return loadTimeData.getStringF("entrySummary",item.dateTimeOfDay,item.starr ed?loadTimeData.getString("bookmarked"):"",item.title,item.domain)},getAriaCheck ed_:function(selected){return selected?"true":"false"},onRemoveBookmarkTap_:func tion(){if(!this.item.starred)return;if(this.$$("#bookmark-star")==this.root.acti veElement)this.$["menu-button"].focus();var browserService=md_history.BrowserSer vice.getInstance();browserService.removeBookmark(this.item.url);browserService.r ecordAction("BookmarkStarClicked");this.fire("remove-bookmark-stars",this.item.u rl)},onMenuButtonTap_:function(e){this.fire("toggle-menu",{target:Polymer.dom(e) .localTarget,index:this.index,item:this.item,path:this.path});e.stopPropagation( )},onLinkClick_:function(){var browserService=md_history.BrowserService.getInsta nce();browserService.recordAction("EntryLinkClick");if(this.searchTerm)browserSe rvice.recordAction("SearchResultClick");if(this.index==undefined)return;browserS ervice.recordHistogram("HistoryPage.ClickPosition",Math.min(this.index,UMA_MAX_B UCKET_VALUE),UMA_MAX_BUCKET_VALUE);if(this.index<=UMA_MAX_SUBSET_BUCKET_VALUE){b rowserService.recordHistogram("HistoryPage.ClickPositionSubset",this.index,UMA_M AX_SUBSET_BUCKET_VALUE)}},onLinkRightClick_:function(){md_history.BrowserService .getInstance().recordAction("EntryLinkRightClick")},showIcon_:function(){this.$. icon.style.backgroundImage=cr.icon.getFavicon(this.item.url)},selectionNotAllowe d_:function(){return!loadTimeData.getBoolean("allowDeletingHistory")},cardTitle_ :function(numberOfItems,historyDate,search){if(!search)return this.item.dateRela tiveDay;return HistoryItem.searchResultsTitle(numberOfItems,search)},addTimeTitl e_:function(){var el=this.$["time-accessed"];el.setAttribute("title",new Date(th is.item.time).toString());this.unlisten(el,"mouseover","addTimeTitle_")}});Histo ryItem.needsTimeGap=function(visits,currentIndex,searchedTerm){if(currentIndex>= visits.length-1||visits.length==0)return false;var currentItem=visits[currentInd ex];var nextItem=visits[currentIndex+1];if(searchedTerm)return currentItem.dateS hort!=nextItem.dateShort;return currentItem.time-nextItem.time>BROWSING_GAP_TIME &&currentItem.dateRelativeDay==nextItem.dateRelativeDay};HistoryItem.searchResul tsTitle=function(numberOfResults,searchTerm){var resultId=numberOfResults==1?"se archResult":"searchResults";return loadTimeData.getStringF("foundSearchResults", numberOfResults,loadTimeData.getString(resultId),searchTerm)};return{HistoryItem :HistoryItem}}); 62 function HistoryFocusRow(root,boundary,delegate){cr.ui.FocusRow.call(this,root,b oundary,delegate);this.addItems()}HistoryFocusRow.prototype={__proto__:cr.ui.Foc usRow.prototype,getCustomEquivalent:function(sampleElement){var equivalent;if(th is.getTypeForElement(sampleElement)=="star")equivalent=this.getFirstFocusable("t itle");return equivalent||cr.ui.FocusRow.prototype.getCustomEquivalent.call(this ,sampleElement)},addItems:function(){this.destroy();assert(this.addItem("checkbo x","#checkbox"));assert(this.addItem("title","#title"));assert(this.addItem("men u-button","#menu-button"));this.addItem("star","#bookmark-star")}};cr.define("md _history",function(){function FocusRowDelegate(historyItemElement){this.historyI temElement=historyItemElement}FocusRowDelegate.prototype={onFocus:function(row,e ){this.historyItemElement.lastFocused=e.path[0]},onKeydown:function(row,e){if(e. key=="Enter")e.stopPropagation();return false}};var HistoryItem=Polymer({is:"his tory-item",properties:{item:{type:Object,observer:"showIcon_"},searchTerm:{type: String},selected:{type:Boolean,reflectToAttribute:true},isCardStart:{type:Boolea n,reflectToAttribute:true},isCardEnd:{type:Boolean,reflectToAttribute:true},embe dded:{type:Boolean,reflectToAttribute:true},hasTimeGap:{type:Boolean},numberOfIt ems:{type:Number},path:String,index:Number,lastFocused:{type:Object,notify:true} ,ironListTabIndex:{type:Number,observer:"ironListTabIndexChanged_"}},row_:null,a ttached:function(){Polymer.RenderStatus.afterNextRender(this,function(){this.row _=new HistoryFocusRow(this.$["main-container"],null,new FocusRowDelegate(this)); this.row_.makeActive(this.ironListTabIndex==0);this.listen(this,"focus","onFocus _");this.listen(this,"dom-change","onDomChange_")})},detached:function(){this.un listen(this,"focus","onFocus_");this.unlisten(this,"dom-change","onDomChange_"); if(this.row_)this.row_.destroy()},onFocus_:function(){if(this.lastFocused)this.r ow_.getEquivalentElement(this.lastFocused).focus();else this.row_.getFirstFocusa ble().focus();this.tabIndex=-1},ironListTabIndexChanged_:function(){if(this.row_ )this.row_.makeActive(this.ironListTabIndex==0)},onDomChange_:function(){if(this .row_)this.row_.addItems()},onItemClick_:function(e){for(var i=0;i<e.path.length ;i++){var elem=e.path[i];if(elem.id!="checkbox"&&(elem.nodeName=="A"||elem.nodeN ame=="BUTTON")){return}}if(this.selectionNotAllowed_())return;this.$.checkbox.fo cus();this.fire("history-checkbox-select",{element:this,shiftKey:e.shiftKey})},o nItemMousedown_:function(e){if(e.shiftKey)e.preventDefault()},getEntrySummary_:f unction(){var item=this.item;return loadTimeData.getStringF("entrySummary",item. dateTimeOfDay,item.starred?loadTimeData.getString("bookmarked"):"",item.title,it em.domain)},getAriaChecked_:function(selected){return selected?"true":"false"},o nRemoveBookmarkTap_:function(){if(!this.item.starred)return;if(this.$$("#bookmar k-star")==this.root.activeElement)this.$["menu-button"].focus();var browserServi ce=md_history.BrowserService.getInstance();browserService.removeBookmark(this.it em.url);browserService.recordAction("BookmarkStarClicked");this.fire("remove-boo kmark-stars",this.item.url)},onMenuButtonTap_:function(e){this.fire("toggle-menu ",{target:Polymer.dom(e).localTarget,index:this.index,item:this.item,path:this.p ath});e.stopPropagation()},onLinkClick_:function(){var browserService=md_history .BrowserService.getInstance();browserService.recordAction("EntryLinkClick");if(t his.searchTerm)browserService.recordAction("SearchResultClick");if(this.index==u ndefined)return;browserService.recordHistogram("HistoryPage.ClickPosition",Math. min(this.index,UMA_MAX_BUCKET_VALUE),UMA_MAX_BUCKET_VALUE);if(this.index<=UMA_MA X_SUBSET_BUCKET_VALUE){browserService.recordHistogram("HistoryPage.ClickPosition Subset",this.index,UMA_MAX_SUBSET_BUCKET_VALUE)}},onLinkRightClick_:function(){m d_history.BrowserService.getInstance().recordAction("EntryLinkRightClick")},show Icon_:function(){this.$.icon.style.backgroundImage=cr.icon.getFavicon(this.item. url)},selectionNotAllowed_:function(){return!loadTimeData.getBoolean("allowDelet ingHistory")},cardTitle_:function(numberOfItems,historyDate,search){if(!search)r eturn this.item.dateRelativeDay;return HistoryItem.searchResultsTitle(numberOfIt ems,search)},addTimeTitle_:function(){var el=this.$["time-accessed"];el.setAttri bute("title",new Date(this.item.time).toString());this.unlisten(el,"mouseover"," addTimeTitle_")}});HistoryItem.needsTimeGap=function(visits,currentIndex,searche dTerm){if(currentIndex>=visits.length-1||visits.length==0)return false;var curre ntItem=visits[currentIndex];var nextItem=visits[currentIndex+1];if(searchedTerm) return currentItem.dateShort!=nextItem.dateShort;return currentItem.time-nextIte m.time>BROWSING_GAP_TIME&&currentItem.dateRelativeDay==nextItem.dateRelativeDay} ;HistoryItem.searchResultsTitle=function(numberOfResults,searchTerm){var resultI d=numberOfResults==1?"searchResult":"searchResults";return loadTimeData.getStrin gF("foundSearchResults",numberOfResults,loadTimeData.getString(resultId),searchT erm)};return{HistoryItem:HistoryItem}});
63 // Copyright 2016 The Chromium Authors. All rights reserved. 63 // Copyright 2016 The Chromium Authors. All rights reserved.
64 // Use of this source code is governed by a BSD-style license that can be 64 // Use of this source code is governed by a BSD-style license that can be
65 // found in the LICENSE file. 65 // found in the LICENSE file.
66 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_"},hasResults:function(historyDataLength){return h istoryDataLength>0},noResultsMessage:function(searchedTerm,isLoading){if(isLoadi ng)return"";var messageId=searchedTerm!==""?"noSearchResults":"noResults";return loadTimeData.getString(messageId)},unselectAllItems:function(){this.selectedPat hs.forEach(function(path){this.set(path+".selected",false)}.bind(this));this.sel ectedPaths.clear()},deleteSelected:function(){var toBeRemoved=Array.from(this.se lectedPaths.values()).map(function(path){return this.get(path)}.bind(this));md_h istory.BrowserService.getInstance().deleteItems(toBeRemoved).then(function(){thi s.removeItemsByPath(Array.from(this.selectedPaths));this.fire("unselect-all")}.b ind(this))},removeItemsByPath:function(paths){if(paths.length==0)return;this.rem oveItemsBeneathNode_(this.buildRemovalTree_(paths))},buildRemovalTree_:function( paths){var rootNode=new SelectionTreeNode(paths[0].split(".")[0]);paths.forEach( function(path){var components=path.split(".");var node=rootNode;components.shift ();while(components.length>1){var index=Number(components.shift());var arrayName =components.shift();if(!node.children[index])node.addChild(index,[node.currentPa th,index,arrayName].join("."));node=node.children[index]}node.leaf=true;node.ind exes.push(Number(components.shift()))});return rootNode},removeItemsBeneathNode_ :function(node){var array=this.get(node.currentPath);var splices=[];node.indexes .sort(function(a,b){return b-a});node.indexes.forEach(function(index){if(node.le af||this.removeItemsBeneathNode_(node.children[index])){var item=array.splice(in dex,1)[0];splices.push({index:index,removed:[item],addedCount:0,object:array,typ e:"splice"})}}.bind(this));if(array.length==0&&node.currentPath.indexOf(".")!=-1 )return true;this.notifySplices(node.currentPath,splices);return false},itemSele cted_:function(e){var item=e.detail.element;var paths=[];var itemPath=item.path; if(e.detail.shiftKey&&this.lastSelectedPath){var itemPathComponents=itemPath.spl it(".");var itemIndex=Number(itemPathComponents.pop());var itemArrayPath=itemPat hComponents.join(".");var lastItemPathComponents=this.lastSelectedPath.split("." );var lastItemIndex=Number(lastItemPathComponents.pop());if(itemArrayPath==lastI temPathComponents.join(".")){for(var i=Math.min(itemIndex,lastItemIndex);i<=Math .max(itemIndex,lastItemIndex);i++){paths.push(itemArrayPath+"."+i)}}}if(paths.le ngth==0)paths.push(item.path);var selected=!this.selectedPaths.has(item.path);pa ths.forEach(function(path){this.set(path+".selected",selected);if(selected){this .selectedPaths.add(path);return}this.selectedPaths.delete(path)}.bind(this));thi s.lastSelectedPath=itemPath}}; 66 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_"},hasResults:function(historyDataLength){return h istoryDataLength>0},noResultsMessage:function(searchedTerm,isLoading){if(isLoadi ng)return"";var messageId=searchedTerm!==""?"noSearchResults":"noResults";return loadTimeData.getString(messageId)},unselectAllItems:function(){this.selectedPat hs.forEach(function(path){this.set(path+".selected",false)}.bind(this));this.sel ectedPaths.clear()},deleteSelected:function(){var toBeRemoved=Array.from(this.se lectedPaths.values()).map(function(path){return this.get(path)}.bind(this));md_h istory.BrowserService.getInstance().deleteItems(toBeRemoved).then(function(){thi s.removeItemsByPath(Array.from(this.selectedPaths));this.fire("unselect-all")}.b ind(this))},removeItemsByPath:function(paths){if(paths.length==0)return;this.rem oveItemsBeneathNode_(this.buildRemovalTree_(paths))},buildRemovalTree_:function( paths){var rootNode=new SelectionTreeNode(paths[0].split(".")[0]);paths.forEach( function(path){var components=path.split(".");var node=rootNode;components.shift ();while(components.length>1){var index=Number(components.shift());var arrayName =components.shift();if(!node.children[index])node.addChild(index,[node.currentPa th,index,arrayName].join("."));node=node.children[index]}node.leaf=true;node.ind exes.push(Number(components.shift()))});return rootNode},removeItemsBeneathNode_ :function(node){var array=this.get(node.currentPath);var splices=[];node.indexes .sort(function(a,b){return b-a});node.indexes.forEach(function(index){if(node.le af||this.removeItemsBeneathNode_(node.children[index])){var item=array.splice(in dex,1)[0];splices.push({index:index,removed:[item],addedCount:0,object:array,typ e:"splice"})}}.bind(this));if(array.length==0&&node.currentPath.indexOf(".")!=-1 )return true;this.notifySplices(node.currentPath,splices);return false},itemSele cted_:function(e){var item=e.detail.element;var paths=[];var itemPath=item.path; if(e.detail.shiftKey&&this.lastSelectedPath){var itemPathComponents=itemPath.spl it(".");var itemIndex=Number(itemPathComponents.pop());var itemArrayPath=itemPat hComponents.join(".");var lastItemPathComponents=this.lastSelectedPath.split("." );var lastItemIndex=Number(lastItemPathComponents.pop());if(itemArrayPath==lastI temPathComponents.join(".")){for(var i=Math.min(itemIndex,lastItemIndex);i<=Math .max(itemIndex,lastItemIndex);i++){paths.push(itemArrayPath+"."+i)}}}if(paths.le ngth==0)paths.push(item.path);var selected=!this.selectedPaths.has(item.path);pa ths.forEach(function(path){this.set(path+".selected",selected);if(selected){this .selectedPaths.add(path);return}this.selectedPaths.delete(path)}.bind(this));thi s.lastSelectedPath=itemPath}};
67 // Copyright 2015 The Chromium Authors. All rights reserved. 67 // Copyright 2015 The Chromium Authors. All rights reserved.
68 // Use of this source code is governed by a BSD-style license that can be 68 // Use of this source code is governed by a BSD-style license that can be
69 // found in the LICENSE file. 69 // found in the LICENSE file.
70 Polymer({is:"history-list",behaviors:[HistoryListBehavior],properties:{searchedT erm:{type:String,value:""},querying:Boolean,historyData_:Array,resultLoadingDisa bled_:{type:Boolean,value:false},lastFocused_:Object},listeners:{scroll:"notifyL istScroll_","remove-bookmark-stars":"removeBookmarkStars_"},attached:function(){ this.$["infinite-list"].notifyResize();this.$["infinite-list"].scrollTarget=this ;this.$["scroll-threshold"].scrollTarget=this},removeBookmarkStars_:function(e){ var url=e.detail;if(this.historyData_===undefined)return;for(var i=0;i<this.hist oryData_.length;i++){if(this.historyData_[i].url==url)this.set("historyData_."+i +".starred",false)}},disableResultLoading:function(){this.resultLoadingDisabled_ =true},addNewResults:function(historyResults,incremental){var results=historyRes ults.slice();this.$["scroll-threshold"].clearTriggers();if(!incremental){this.re sultLoadingDisabled_=false;if(this.historyData_)this.splice("historyData_",0,thi s.historyData_.length);this.fire("unselect-all")}if(this.historyData_){results.u nshift("historyData_");this.push.apply(this,results)}else{this.set("historyData_ ",results)}},loadMoreData_:function(){if(this.resultLoadingDisabled_||this.query ing)return;this.fire("load-more-history")},needsTimeGap_:function(item,index,len gth){return md_history.HistoryItem.needsTimeGap(this.historyData_,index,this.sea rchedTerm)},isCardStart_:function(item,i,length){if(length==0||i>length-1)return false;return i==0||this.historyData_[i].dateRelativeDay!=this.historyData_[i-1] .dateRelativeDay},isCardEnd_:function(item,i,length){if(length==0||i>length-1)re turn false;return i==length-1||this.historyData_[i].dateRelativeDay!=this.histor yData_[i+1].dateRelativeDay},notifyListScroll_:function(){this.fire("history-lis t-scrolled")},pathForItem_:function(index){return"historyData_."+index}}); 70 Polymer({is:"history-list",behaviors:[HistoryListBehavior],properties:{searchedT erm:{type:String,value:""},querying:Boolean,historyData_:Array,resultLoadingDisa bled_:{type:Boolean,value:false},lastFocused_:Object},listeners:{scroll:"notifyL istScroll_","remove-bookmark-stars":"removeBookmarkStars_"},attached:function(){ this.$["infinite-list"].notifyResize();this.$["infinite-list"].scrollTarget=this ;this.$["scroll-threshold"].scrollTarget=this},removeBookmarkStars_:function(e){ var url=e.detail;if(this.historyData_===undefined)return;for(var i=0;i<this.hist oryData_.length;i++){if(this.historyData_[i].url==url)this.set("historyData_."+i +".starred",false)}},disableResultLoading:function(){this.resultLoadingDisabled_ =true},addNewResults:function(historyResults,incremental){var results=historyRes ults.slice();this.$["scroll-threshold"].clearTriggers();if(!incremental){this.re sultLoadingDisabled_=false;if(this.historyData_)this.splice("historyData_",0,thi s.historyData_.length);this.fire("unselect-all")}if(this.historyData_){results.u nshift("historyData_");this.push.apply(this,results)}else{this.set("historyData_ ",results)}},loadMoreData_:function(){if(this.resultLoadingDisabled_||this.query ing)return;this.fire("load-more-history")},needsTimeGap_:function(item,index,len gth){return md_history.HistoryItem.needsTimeGap(this.historyData_,index,this.sea rchedTerm)},isCardStart_:function(item,i,length){if(length==0||i>length-1)return false;return i==0||this.historyData_[i].dateRelativeDay!=this.historyData_[i-1] .dateRelativeDay},isCardEnd_:function(item,i,length){if(length==0||i>length-1)re turn false;return i==length-1||this.historyData_[i].dateRelativeDay!=this.histor yData_[i+1].dateRelativeDay},notifyListScroll_:function(){this.fire("history-lis t-scrolled")},pathForItem_:function(index){return"historyData_."+index}});
71 // Copyright 2016 The Chromium Authors. All rights reserved. 71 // Copyright 2016 The Chromium Authors. All rights reserved.
72 // Use of this source code is governed by a BSD-style license that can be 72 // Use of this source code is governed by a BSD-style license that can be
73 // found in the LICENSE file. 73 // found in the LICENSE file.
74 Polymer({is:"history-list-container",properties:{selectedPage_:String,grouped:Bo olean,groupedRange:{type:Number,observer:"groupedRangeChanged_"},queryState:Obje ct,queryResult:Object},observers:["searchTermChanged_(queryState.searchTerm)"],l isteners:{"history-list-scrolled":"closeMenu_","load-more-history":"loadMoreHist ory_","toggle-menu":"toggleMenu_"},historyResult:function(info,results){this.ini tializeResults_(info,results);this.closeMenu_();if(info.term&&!this.queryState.i ncremental){Polymer.IronA11yAnnouncer.requestAvailability();this.fire("iron-anno unce",{text:md_history.HistoryItem.searchResultsTitle(results.length,info.term)} )}if(this.selectedPage_=="grouped-list"){this.$$("#grouped-list").historyData=re sults;return}var list=this.$["infinite-list"];list.addNewResults(results,this.qu eryState.incremental);if(info.finished)list.disableResultLoading()},queryHistory :function(incremental){var queryState=this.queryState;var noResults=!this.queryR esult||this.queryResult.results==null;if(queryState.queryingDisabled||!this.quer yState.searchTerm&&noResults){return}var dialog=this.$.dialog.getIfExists();if(! incremental&&dialog&&dialog.open)dialog.close();this.set("queryState.querying",t rue);this.set("queryState.incremental",incremental);var lastVisitTime=0;if(incre mental){var lastVisit=this.queryResult.results.slice(-1)[0];lastVisitTime=lastVi sit?Math.floor(lastVisit.time):0}var maxResults=this.groupedRange==HistoryRange. ALL_TIME?RESULTS_PER_PAGE:0;chrome.send("queryHistory",[queryState.searchTerm,qu eryState.groupedOffset,queryState.range,lastVisitTime,maxResults])},historyDelet ed:function(){if(this.getSelectedItemCount()>0)return;this.queryHistory(false)}, getContentScrollTarget:function(){return this.getSelectedList_()},getSelectedIte mCount:function(){return this.getSelectedList_().selectedPaths.size},unselectAll Items:function(count){var selectedList=this.getSelectedList_();if(selectedList)s electedList.unselectAllItems(count)},deleteSelectedWithPrompt:function(){if(!loa dTimeData.getBoolean("allowDeletingHistory"))return;var browserService=md_histor y.BrowserService.getInstance();browserService.recordAction("RemoveSelected");if( this.queryState.searchTerm!="")browserService.recordAction("SearchResultRemove") ;this.$.dialog.get().showModal();this.$$(".action-button").focus()},groupedRange Changed_:function(range,oldRange){this.selectedPage_=range==HistoryRange.ALL_TIM E?"infinite-list":"grouped-list";if(oldRange==undefined)return;this.queryHistory (false);this.fire("history-view-changed")},searchTermChanged_:function(){this.qu eryHistory(false);if(this.queryState.searchTerm)md_history.BrowserService.getIns tance().recordAction("Search")},loadMoreHistory_:function(){this.queryHistory(tr ue)},initializeResults_:function(info,results){if(results.length==0)return;var c urrentDate=results[0].dateRelativeDay;for(var i=0;i<results.length;i++){results[ i].selected=false;results[i].readableTimestamp=info.term==""?results[i].dateTime OfDay:results[i].dateShort;if(results[i].dateRelativeDay!=currentDate){currentDa te=results[i].dateRelativeDay}}},onDialogConfirmTap_:function(){md_history.Brows erService.getInstance().recordAction("ConfirmRemoveSelected");this.getSelectedLi st_().deleteSelected();var dialog=assert(this.$.dialog.getIfExists());dialog.clo se()},onDialogCancelTap_:function(){md_history.BrowserService.getInstance().reco rdAction("CancelRemoveSelected");var dialog=assert(this.$.dialog.getIfExists()); dialog.close()},closeMenu_:function(){var menu=this.$.sharedMenu.getIfExists();i f(menu)menu.closeMenu()},toggleMenu_:function(e){var target=e.detail.target;var menu=this.$.sharedMenu.get();menu.toggleMenu(target,e.detail)},onMoreFromSiteTap _:function(){md_history.BrowserService.getInstance().recordAction("EntryMenuShow MoreFromSite");var menu=assert(this.$.sharedMenu.getIfExists());this.set("queryS tate.searchTerm",menu.itemData.item.domain);menu.closeMenu()},onRemoveFromHistor yTap_:function(){var browserService=md_history.BrowserService.getInstance();brow serService.recordAction("EntryMenuRemoveFromHistory");var menu=assert(this.$.sha redMenu.getIfExists());var itemData=menu.itemData;browserService.deleteItems([it emData.item]).then(function(items){this.fire("unselect-all");this.getSelectedLis t_().removeItemsByPath([itemData.path]);var index=itemData.index;if(index==undef ined)return;var browserService=md_history.BrowserService.getInstance();browserSe rvice.recordHistogram("HistoryPage.RemoveEntryPosition",Math.min(index,UMA_MAX_B UCKET_VALUE),UMA_MAX_BUCKET_VALUE);if(index<=UMA_MAX_SUBSET_BUCKET_VALUE){browse rService.recordHistogram("HistoryPage.RemoveEntryPositionSubset",index,UMA_MAX_S UBSET_BUCKET_VALUE)}}.bind(this));menu.closeMenu()},getSelectedList_:function(){ return this.$.content.selectedItem},canDeleteHistory_:function(){return loadTime Data.getBoolean("allowDeletingHistory")}});(function(){"use strict";Polymer({is: "iron-location",properties:{path:{type:String,notify:true,value:function(){retur n window.decodeURIComponent(window.location.pathname)}},query:{type:String,notif y:true,value:function(){return window.decodeURIComponent(window.location.search. slice(1))}},hash:{type:String,notify:true,value:function(){return window.decodeU RIComponent(window.location.hash.slice(1))}},dwellTime:{type:Number,value:2e3},u rlSpaceRegex:{type:String,value:""},_urlSpaceRegExp:{computed:"_makeRegExp(urlSp aceRegex)"},_lastChangedAt:{type:Number},_initialized:{type:Boolean,value:false} },hostAttributes:{hidden:true},observers:["_updateUrl(path, query, hash)"],attac hed:function(){this.listen(window,"hashchange","_hashChanged");this.listen(windo w,"location-changed","_urlChanged");this.listen(window,"popstate","_urlChanged") ;this.listen(document.body,"click","_globalOnClick");this._lastChangedAt=window. performance.now()-(this.dwellTime-200);this._initialized=true;this._urlChanged() },detached:function(){this.unlisten(window,"hashchange","_hashChanged");this.unl isten(window,"location-changed","_urlChanged");this.unlisten(window,"popstate"," _urlChanged");this.unlisten(document.body,"click","_globalOnClick");this._initia lized=false},_hashChanged:function(){this.hash=window.decodeURIComponent(window. location.hash.substring(1))},_urlChanged:function(){this._dontUpdateUrl=true;thi s._hashChanged();this.path=window.decodeURIComponent(window.location.pathname);t his.query=window.decodeURIComponent(window.location.search.substring(1));this._d ontUpdateUrl=false;this._updateUrl()},_getUrl:function(){var partiallyEncodedPat h=window.encodeURI(this.path).replace(/\#/g,"%23").replace(/\?/g,"%3F");var part iallyEncodedQuery="";if(this.query){partiallyEncodedQuery="?"+window.encodeURI(t his.query).replace(/\#/g,"%23")}var partiallyEncodedHash="";if(this.hash){partia llyEncodedHash="#"+window.encodeURI(this.hash)}return partiallyEncodedPath+parti allyEncodedQuery+partiallyEncodedHash},_updateUrl:function(){if(this._dontUpdate Url||!this._initialized){return}if(this.path===window.decodeURIComponent(window. location.pathname)&&this.query===window.decodeURIComponent(window.location.searc h.substring(1))&&this.hash===window.decodeURIComponent(window.location.hash.subs tring(1))){return}var newUrl=this._getUrl();var fullNewUrl=new URL(newUrl,window .location.protocol+"//"+window.location.host).href;var now=window.performance.no w();var shouldReplace=this._lastChangedAt+this.dwellTime>now;this._lastChangedAt =now;if(shouldReplace){window.history.replaceState({},"",fullNewUrl)}else{window .history.pushState({},"",fullNewUrl)}this.fire("location-changed",{},{node:windo w})},_globalOnClick:function(event){if(event.defaultPrevented){return}var href=t his._getSameOriginLinkHref(event);if(!href){return}event.preventDefault();if(hre f===window.location.href){return}window.history.pushState({},"",href);this.fire( "location-changed",{},{node:window})},_getSameOriginLinkHref:function(event){if( event.button!==0){return null}if(event.metaKey||event.ctrlKey){return null}var e ventPath=Polymer.dom(event).path;var anchor=null;for(var i=0;i<eventPath.length; i++){var element=eventPath[i];if(element.tagName==="A"&&element.href){anchor=ele ment;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.href;var url;if(document.baseURI!=null){url=new URL(href,d ocument.baseURI)}else{url=new URL(href)}var origin;if(window.location.origin){or igin=window.location.origin}else{origin=window.location.protocol+"//"+window.loc ation.hostname;if(window.location.port){origin+=":"+window.location.port}}if(url .origin!==origin){return null}var normalizedHref=url.pathname+url.search+url.has h;if(this._urlSpaceRegExp&&!this._urlSpaceRegExp.test(normalizedHref)){return nu ll}var fullNormalizedHref=new URL(normalizedHref,window.location.href).href;retu rn fullNormalizedHref},_makeRegExp:function(urlSpaceRegex){return RegExp(urlSpac eRegex)}})})();"use strict";Polymer({is:"iron-query-params",properties:{paramsSt ring:{type:String,notify:true,observer:"paramsStringChanged"},paramsObject:{type :Object,notify:true,value:function(){return{}}},_dontReact:{type:Boolean,value:f alse}},hostAttributes:{hidden:true},observers:["paramsObjectChanged(paramsObject .*)"],paramsStringChanged:function(){this._dontReact=true;this.paramsObject=this ._decodeParams(this.paramsString);this._dontReact=false},paramsObjectChanged:fun ction(){if(this._dontReact){return}this.paramsString=this._encodeParams(this.par amsObject)},_encodeParams:function(params){var encodedParams=[];for(var key in p arams){var value=params[key];if(value===""){encodedParams.push(encodeURIComponen t(key))}else if(value){encodedParams.push(encodeURIComponent(key)+"="+encodeURIC omponent(value.toString()))}}return encodedParams.join("&")},_decodeParams:funct ion(paramString){var params={};paramString=(paramString||"").replace(/\+/g,"%20" );var paramList=paramString.split("&");for(var i=0;i<paramList.length;i++){var p aram=paramList[i].split("=");if(param[0]){params[decodeURIComponent(param[0])]=d ecodeURIComponent(param[1]||"")}}return params}}); 74 Polymer({is:"history-list-container",properties:{selectedPage_:String,grouped:Bo olean,groupedRange:{type:Number,observer:"groupedRangeChanged_"},queryState:Obje ct,queryResult:Object},observers:["searchTermChanged_(queryState.searchTerm)"],l isteners:{"history-list-scrolled":"closeMenu_","load-more-history":"loadMoreHist ory_","toggle-menu":"toggleMenu_"},historyResult:function(info,results){this.ini tializeResults_(info,results);this.closeMenu_();if(info.term&&!this.queryState.i ncremental){Polymer.IronA11yAnnouncer.requestAvailability();this.fire("iron-anno unce",{text:md_history.HistoryItem.searchResultsTitle(results.length,info.term)} )}if(this.selectedPage_=="grouped-list"){this.$$("#grouped-list").historyData=re sults;return}var list=this.$["infinite-list"];list.addNewResults(results,this.qu eryState.incremental);if(info.finished)list.disableResultLoading()},queryHistory :function(incremental){var queryState=this.queryState;var noResults=!this.queryR esult||this.queryResult.results==null;if(queryState.queryingDisabled||!this.quer yState.searchTerm&&noResults){return}var dialog=this.$.dialog.getIfExists();if(! incremental&&dialog&&dialog.open)dialog.close();this.set("queryState.querying",t rue);this.set("queryState.incremental",incremental);var lastVisitTime=0;if(incre mental){var lastVisit=this.queryResult.results.slice(-1)[0];lastVisitTime=lastVi sit?Math.floor(lastVisit.time):0}var maxResults=this.groupedRange==HistoryRange. ALL_TIME?RESULTS_PER_PAGE:0;chrome.send("queryHistory",[queryState.searchTerm,qu eryState.groupedOffset,queryState.range,lastVisitTime,maxResults])},historyDelet ed:function(){if(this.getSelectedItemCount()>0)return;this.queryHistory(false)}, getContentScrollTarget:function(){return this.getSelectedList_()},getSelectedIte mCount:function(){return this.getSelectedList_().selectedPaths.size},unselectAll Items:function(count){var selectedList=this.getSelectedList_();if(selectedList)s electedList.unselectAllItems(count)},deleteSelectedWithPrompt:function(){if(!loa dTimeData.getBoolean("allowDeletingHistory"))return;var browserService=md_histor y.BrowserService.getInstance();browserService.recordAction("RemoveSelected");if( this.queryState.searchTerm!="")browserService.recordAction("SearchResultRemove") ;this.$.dialog.get().showModal();this.$$(".action-button").focus()},groupedRange Changed_:function(range,oldRange){this.selectedPage_=range==HistoryRange.ALL_TIM E?"infinite-list":"grouped-list";if(oldRange==undefined)return;this.queryHistory (false);this.fire("history-view-changed")},searchTermChanged_:function(){this.qu eryHistory(false);if(this.queryState.searchTerm)md_history.BrowserService.getIns tance().recordAction("Search")},loadMoreHistory_:function(){this.queryHistory(tr ue)},initializeResults_:function(info,results){if(results.length==0)return;var c urrentDate=results[0].dateRelativeDay;for(var i=0;i<results.length;i++){results[ i].selected=false;results[i].readableTimestamp=info.term==""?results[i].dateTime OfDay:results[i].dateShort;if(results[i].dateRelativeDay!=currentDate){currentDa te=results[i].dateRelativeDay}}},onDialogConfirmTap_:function(){md_history.Brows erService.getInstance().recordAction("ConfirmRemoveSelected");this.getSelectedLi st_().deleteSelected();var dialog=assert(this.$.dialog.getIfExists());dialog.clo se()},onDialogCancelTap_:function(){md_history.BrowserService.getInstance().reco rdAction("CancelRemoveSelected");var dialog=assert(this.$.dialog.getIfExists()); dialog.close()},closeMenu_:function(){var menu=this.$.sharedMenu.getIfExists();i f(menu)menu.closeMenu()},toggleMenu_:function(e){var target=e.detail.target;var menu=this.$.sharedMenu.get();menu.toggleMenu(target,e.detail)},onMoreFromSiteTap _:function(){md_history.BrowserService.getInstance().recordAction("EntryMenuShow MoreFromSite");var menu=assert(this.$.sharedMenu.getIfExists());this.set("queryS tate.searchTerm",menu.itemData.item.domain);menu.closeMenu()},onRemoveFromHistor yTap_:function(){var browserService=md_history.BrowserService.getInstance();brow serService.recordAction("EntryMenuRemoveFromHistory");var menu=assert(this.$.sha redMenu.getIfExists());var itemData=menu.itemData;browserService.deleteItems([it emData.item]).then(function(items){this.fire("unselect-all");this.getSelectedLis t_().removeItemsByPath([itemData.path]);var index=itemData.index;if(index==undef ined)return;var browserService=md_history.BrowserService.getInstance();browserSe rvice.recordHistogram("HistoryPage.RemoveEntryPosition",Math.min(index,UMA_MAX_B UCKET_VALUE),UMA_MAX_BUCKET_VALUE);if(index<=UMA_MAX_SUBSET_BUCKET_VALUE){browse rService.recordHistogram("HistoryPage.RemoveEntryPositionSubset",index,UMA_MAX_S UBSET_BUCKET_VALUE)}}.bind(this));menu.closeMenu()},getSelectedList_:function(){ return this.$.content.selectedItem},canDeleteHistory_:function(){return loadTime Data.getBoolean("allowDeletingHistory")}});(function(){"use strict";Polymer({is: "iron-location",properties:{path:{type:String,notify:true,value:function(){retur n window.decodeURIComponent(window.location.pathname)}},query:{type:String,notif y:true,value:function(){return window.decodeURIComponent(window.location.search. slice(1))}},hash:{type:String,notify:true,value:function(){return window.decodeU RIComponent(window.location.hash.slice(1))}},dwellTime:{type:Number,value:2e3},u rlSpaceRegex:{type:String,value:""},_urlSpaceRegExp:{computed:"_makeRegExp(urlSp aceRegex)"},_lastChangedAt:{type:Number},_initialized:{type:Boolean,value:false} },hostAttributes:{hidden:true},observers:["_updateUrl(path, query, hash)"],attac hed:function(){this.listen(window,"hashchange","_hashChanged");this.listen(windo w,"location-changed","_urlChanged");this.listen(window,"popstate","_urlChanged") ;this.listen(document.body,"click","_globalOnClick");this._lastChangedAt=window. performance.now()-(this.dwellTime-200);this._initialized=true;this._urlChanged() },detached:function(){this.unlisten(window,"hashchange","_hashChanged");this.unl isten(window,"location-changed","_urlChanged");this.unlisten(window,"popstate"," _urlChanged");this.unlisten(document.body,"click","_globalOnClick");this._initia lized=false},_hashChanged:function(){this.hash=window.decodeURIComponent(window. location.hash.substring(1))},_urlChanged:function(){this._dontUpdateUrl=true;thi s._hashChanged();this.path=window.decodeURIComponent(window.location.pathname);t his.query=window.decodeURIComponent(window.location.search.substring(1));this._d ontUpdateUrl=false;this._updateUrl()},_getUrl:function(){var partiallyEncodedPat h=window.encodeURI(this.path).replace(/\#/g,"%23").replace(/\?/g,"%3F");var part iallyEncodedQuery="";if(this.query){partiallyEncodedQuery="?"+window.encodeURI(t his.query).replace(/\#/g,"%23")}var partiallyEncodedHash="";if(this.hash){partia llyEncodedHash="#"+window.encodeURI(this.hash)}return partiallyEncodedPath+parti allyEncodedQuery+partiallyEncodedHash},_updateUrl:function(){if(this._dontUpdate Url||!this._initialized){return}if(this.path===window.decodeURIComponent(window. location.pathname)&&this.query===window.decodeURIComponent(window.location.searc h.substring(1))&&this.hash===window.decodeURIComponent(window.location.hash.subs tring(1))){return}var newUrl=this._getUrl();var fullNewUrl=new URL(newUrl,window .location.protocol+"//"+window.location.host).href;var now=window.performance.no w();var shouldReplace=this._lastChangedAt+this.dwellTime>now;this._lastChangedAt =now;if(shouldReplace){window.history.replaceState({},"",fullNewUrl)}else{window .history.pushState({},"",fullNewUrl)}this.fire("location-changed",{},{node:windo w})},_globalOnClick:function(event){if(event.defaultPrevented){return}var href=t his._getSameOriginLinkHref(event);if(!href){return}event.preventDefault();if(hre f===window.location.href){return}window.history.pushState({},"",href);this.fire( "location-changed",{},{node:window})},_getSameOriginLinkHref:function(event){if( event.button!==0){return null}if(event.metaKey||event.ctrlKey){return null}var e ventPath=Polymer.dom(event).path;var anchor=null;for(var i=0;i<eventPath.length; i++){var element=eventPath[i];if(element.tagName==="A"&&element.href){anchor=ele ment;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.href;var url;if(document.baseURI!=null){url=new URL(href,d ocument.baseURI)}else{url=new URL(href)}var origin;if(window.location.origin){or igin=window.location.origin}else{origin=window.location.protocol+"//"+window.loc ation.hostname;if(window.location.port){origin+=":"+window.location.port}}if(url .origin!==origin){return null}var normalizedHref=url.pathname+url.search+url.has h;if(this._urlSpaceRegExp&&!this._urlSpaceRegExp.test(normalizedHref)){return nu ll}var fullNormalizedHref=new URL(normalizedHref,window.location.href).href;retu rn fullNormalizedHref},_makeRegExp:function(urlSpaceRegex){return RegExp(urlSpac eRegex)}})})();"use strict";Polymer({is:"iron-query-params",properties:{paramsSt ring:{type:String,notify:true,observer:"paramsStringChanged"},paramsObject:{type :Object,notify:true,value:function(){return{}}},_dontReact:{type:Boolean,value:f alse}},hostAttributes:{hidden:true},observers:["paramsObjectChanged(paramsObject .*)"],paramsStringChanged:function(){this._dontReact=true;this.paramsObject=this ._decodeParams(this.paramsString);this._dontReact=false},paramsObjectChanged:fun ction(){if(this._dontReact){return}this.paramsString=this._encodeParams(this.par amsObject)},_encodeParams:function(params){var encodedParams=[];for(var key in p arams){var value=params[key];if(value===""){encodedParams.push(encodeURIComponen t(key))}else if(value){encodedParams.push(encodeURIComponent(key)+"="+encodeURIC omponent(value.toString()))}}return encodedParams.join("&")},_decodeParams:funct ion(paramString){var params={};paramString=(paramString||"").replace(/\+/g,"%20" );var paramList=paramString.split("&");for(var i=0;i<paramList.length;i++){var p aram=paramList[i].split("=");if(param[0]){params[decodeURIComponent(param[0])]=d ecodeURIComponent(param[1]||"")}}return params}});
75 // Copyright 2016 The Chromium Authors. All rights reserved. 75 // Copyright 2016 The Chromium Authors. All rights reserved.
76 // Use of this source code is governed by a BSD-style license that can be 76 // Use of this source code is governed by a BSD-style license that can be
77 // found in the LICENSE file. 77 // found in the LICENSE file.
78 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]}); 78 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]});
79 // Copyright 2016 The Chromium Authors. All rights reserved. 79 // Copyright 2016 The Chromium Authors. All rights reserved.
80 // Use of this source code is governed by a BSD-style license that can be 80 // Use of this source code is governed by a BSD-style license that can be
81 // found in the LICENSE file. 81 // found in the LICENSE file.
82 Polymer({is:"history-side-bar",behaviors:[Polymer.IronA11yKeysBehavior],properti es:{selectedPage:{type:String,notify:true},showFooter:Boolean,drawer:{type:Boole an,reflectToAttribute:true}},keyBindings:{"space:keydown":"onSpacePressed_"},onS pacePressed_:function(e){e.detail.keyboardEvent.path[0].click()},onSelectorActiv ate_:function(){this.fire("history-close-drawer")},onClearBrowsingDataTap_:funct ion(e){var browserService=md_history.BrowserService.getInstance();browserService .recordAction("InitClearBrowsingData");browserService.openClearBrowsingData();th is.$["cbd-ripple"].upAction();e.preventDefault()},onItemClick_:function(e){e.pre ventDefault()}}); 82 Polymer({is:"history-side-bar",behaviors:[Polymer.IronA11yKeysBehavior],properti es:{selectedPage:{type:String,notify:true},showFooter:Boolean,drawer:{type:Boole an,reflectToAttribute:true}},keyBindings:{"space:keydown":"onSpacePressed_"},onS pacePressed_:function(e){e.detail.keyboardEvent.path[0].click()},onSelectorActiv ate_:function(){this.fire("history-close-drawer")},onClearBrowsingDataTap_:funct ion(e){var browserService=md_history.BrowserService.getInstance();browserService .recordAction("InitClearBrowsingData");browserService.openClearBrowsingData();th is.$["cbd-ripple"].upAction();e.preventDefault()},onItemClick_:function(e){e.pre ventDefault()}});
83 // Copyright 2016 The Chromium Authors. All rights reserved. 83 // Copyright 2016 The Chromium Authors. All rights reserved.
84 // Use of this source code is governed by a BSD-style license that can be 84 // Use of this source code is governed by a BSD-style license that can be
85 // found in the LICENSE file. 85 // found in the LICENSE file.
86 cr.define("md_history",function(){var lazyLoadPromise=null;function ensureLazyLo aded(){if(!lazyLoadPromise){lazyLoadPromise=new Promise(function(resolve,reject) {Polymer.Base.importHref("chrome://history/lazy_load.html",resolve,reject,true)} )}return lazyLoadPromise}return{ensureLazyLoaded:ensureLazyLoaded}});Polymer({is :"history-app",behaviors:[Polymer.IronScrollTargetBehavior],properties:{showSide barFooter:Boolean,hasSyncedResults:Boolean,selectedPage_:{type:String,observer:" selectedPageChanged_"},grouped_:{type:Boolean,reflectToAttribute:true},queryStat e_:{type:Object,value:function(){return{incremental:false,querying:true,querying Disabled:false,_range:HistoryRange.ALL_TIME,searchTerm:"",groupedOffset:0,set ra nge(val){this._range=Number(val)},get range(){return this._range}}}},queryResult _:{type:Object,value:function(){return{info:null,results:null,sessionList:null}} },hasDrawer_:Boolean,isUserSignedIn_:{type:Boolean,value:loadTimeData.getBoolean ("isUserSignedIn")},toolbarShadow_:{type:Boolean,reflectToAttribute:true,notify: true},showMenuPromo_:{type:Boolean,value:function(){return loadTimeData.getBoole an("showMenuPromo")}}},listeners:{"cr-toolbar-menu-promo-close":"onCrToolbarMenu PromoClose_","cr-toolbar-menu-promo-shown":"onCrToolbarMenuPromoShown_","cr-tool bar-menu-tap":"onCrToolbarMenuTap_","delete-selected":"deleteSelected","history- checkbox-select":"checkboxSelected","history-close-drawer":"closeDrawer_","histo ry-view-changed":"historyViewChanged_","opened-changed":"onOpenedChanged_","unse lect-all":"unselectAll"},boundOnCanExecute_:null,boundOnCommand_:null,attached:f unction(){this.grouped_=loadTimeData.getBoolean("groupByDomain");cr.ui.decorate( "command",cr.ui.Command);this.boundOnCanExecute_=this.onCanExecute_.bind(this);t his.boundOnCommand_=this.onCommand_.bind(this);document.addEventListener("canExe cute",this.boundOnCanExecute_);document.addEventListener("command",this.boundOnC ommand_)},detached:function(){document.removeEventListener("canExecute",this.bou ndOnCanExecute_);document.removeEventListener("command",this.boundOnCommand_)},o nFirstRender:function(){setTimeout(function(){chrome.send("metricsHandler:record Time",["History.ResultsRenderedTime",window.performance.now()])});var searchFiel d=this.$.toolbar.searchField;if(!searchField.narrow){searchField.getSearchInput( ).focus()}md_history.ensureLazyLoaded()},_scrollHandler:function(){if(this.scrol lTarget)this.toolbarShadow_=this.scrollTarget.scrollTop!=0},onCrToolbarMenuPromo Close_:function(){this.showMenuPromo_=false},onCrToolbarMenuPromoShown_:function (){md_history.BrowserService.getInstance().menuPromoShown()},onCrToolbarMenuTap_ :function(){var drawer=this.$$("#drawer");if(drawer)drawer.toggle()},onOpenedCha nged_:function(e){if(e.detail.value)this.showMenuPromo_=false},checkboxSelected: function(e){var toolbar=this.$.toolbar;toolbar.count=this.$.history.getSelectedI temCount()},unselectAll:function(){var listContainer=this.$.history;var toolbar= this.$.toolbar;listContainer.unselectAllItems(toolbar.count);toolbar.count=0},de leteSelected:function(){this.$.history.deleteSelectedWithPrompt()},historyResult :function(info,results){this.set("queryState_.querying",false);this.set("queryRe sult_.info",info);this.set("queryResult_.results",results);var listContainer=thi s.$["history"];listContainer.historyResult(info,results)},focusToolbarSearchFiel d:function(){this.$.toolbar.showSearchField()},onCanExecute_:function(e){e=e;swi tch(e.command.id){case"find-command":e.canExecute=true;break;case"slash-command" :e.canExecute=!this.$.toolbar.searchField.isSearchFocused();break;case"delete-co mmand":e.canExecute=this.$.toolbar.count>0;break}},onCommand_:function(e){if(e.c ommand.id=="find-command"||e.command.id=="slash-command")this.focusToolbarSearch Field();if(e.command.id=="delete-command")this.deleteSelected()},setForeignSessi ons:function(sessionList,isTabSyncEnabled){if(!isTabSyncEnabled){var syncedDevic eManagerElem=this.$$("history-synced-device-manager");if(syncedDeviceManagerElem ){md_history.ensureLazyLoaded().then(function(){syncedDeviceManagerElem.tabSyncD isabled()})}return}this.set("queryResult_.sessionList",sessionList)},historyDele ted:function(){this.$.history.historyDeleted()},updateSignInState:function(isUse rSignedIn){this.isUserSignedIn_=isUserSignedIn},syncedTabsSelected_:function(sel ectedPage){return selectedPage=="syncedTabs"},shouldShowSpinner_:function(queryi ng,incremental,searchTerm){return querying&&!incremental&&searchTerm!=""},showSy ncNotice_:function(hasSyncedResults,selectedPage){return hasSyncedResults&&selec tedPage!="syncedTabs"},selectedPageChanged_:function(){this.unselectAll();this.h istoryViewChanged_()},historyViewChanged_:function(){requestAnimationFrame(funct ion(){md_history.ensureLazyLoaded().then(function(){if(!this.$.content.selectedI tem)return;this.scrollTarget=this.$.content.selectedItem.getContentScrollTarget( );this._scrollHandler()}.bind(this))}.bind(this));this.recordHistoryPageView_()} ,getSelectedPage_:function(selectedPage,items){return selectedPage},closeDrawer_ :function(){var drawer=this.$$("#drawer");if(drawer)drawer.close()},recordHistor yPageView_:function(){var histogramValue=HistoryPageViewHistogram.END;switch(thi s.selectedPage_){case"syncedTabs":histogramValue=this.isUserSignedIn_?HistoryPag eViewHistogram.SYNCED_TABS:HistoryPageViewHistogram.SIGNIN_PROMO;break;default:s witch(this.queryState_.range){case HistoryRange.ALL_TIME:histogramValue=HistoryP ageViewHistogram.HISTORY;break;case HistoryRange.WEEK:histogramValue=HistoryPage ViewHistogram.GROUPED_WEEK;break;case HistoryRange.MONTH:histogramValue=HistoryP ageViewHistogram.GROUPED_MONTH;break}break}md_history.BrowserService.getInstance ().recordHistogram("History.HistoryPageView",histogramValue,HistoryPageViewHisto gram.END)}}); 86 cr.define("md_history",function(){var lazyLoadPromise=null;function ensureLazyLo aded(){if(!lazyLoadPromise){lazyLoadPromise=new Promise(function(resolve,reject) {Polymer.Base.importHref("chrome://history/lazy_load.html",resolve,reject,true)} )}return lazyLoadPromise}return{ensureLazyLoaded:ensureLazyLoaded}});Polymer({is :"history-app",behaviors:[Polymer.IronScrollTargetBehavior],properties:{showSide barFooter:Boolean,hasSyncedResults:Boolean,selectedPage_:{type:String,observer:" selectedPageChanged_"},grouped_:{type:Boolean,reflectToAttribute:true},queryStat e_:{type:Object,value:function(){return{incremental:false,querying:true,querying Disabled:false,_range:HistoryRange.ALL_TIME,searchTerm:"",groupedOffset:0,set ra nge(val){this._range=Number(val)},get range(){return this._range}}}},queryResult _:{type:Object,value:function(){return{info:null,results:null,sessionList:null}} },hasDrawer_:Boolean,isUserSignedIn_:{type:Boolean,value:loadTimeData.getBoolean ("isUserSignedIn")},toolbarShadow_:{type:Boolean,reflectToAttribute:true,notify: true},showMenuPromo_:{type:Boolean,value:function(){return loadTimeData.getBoole an("showMenuPromo")}}},listeners:{"cr-toolbar-menu-promo-close":"onCrToolbarMenu PromoClose_","cr-toolbar-menu-promo-shown":"onCrToolbarMenuPromoShown_","cr-tool bar-menu-tap":"onCrToolbarMenuTap_","delete-selected":"deleteSelected","history- checkbox-select":"checkboxSelected","history-close-drawer":"closeDrawer_","histo ry-view-changed":"historyViewChanged_","opened-changed":"onOpenedChanged_","unse lect-all":"unselectAll"},boundOnCanExecute_:null,boundOnCommand_:null,attached:f unction(){this.grouped_=loadTimeData.getBoolean("groupByDomain");cr.ui.decorate( "command",cr.ui.Command);this.boundOnCanExecute_=this.onCanExecute_.bind(this);t his.boundOnCommand_=this.onCommand_.bind(this);document.addEventListener("canExe cute",this.boundOnCanExecute_);document.addEventListener("command",this.boundOnC ommand_)},detached:function(){document.removeEventListener("canExecute",this.bou ndOnCanExecute_);document.removeEventListener("command",this.boundOnCommand_)},o nFirstRender:function(){setTimeout(function(){chrome.send("metricsHandler:record Time",["History.ResultsRenderedTime",window.performance.now()])});var searchFiel d=this.$.toolbar.searchField;if(!searchField.narrow){searchField.getSearchInput( ).focus()}md_history.ensureLazyLoaded()},_scrollHandler:function(){if(this.scrol lTarget)this.toolbarShadow_=this.scrollTarget.scrollTop!=0},onCrToolbarMenuPromo Close_:function(){this.showMenuPromo_=false},onCrToolbarMenuPromoShown_:function (){md_history.BrowserService.getInstance().menuPromoShown()},onCrToolbarMenuTap_ :function(){var drawer=this.$$("#drawer");if(drawer)drawer.toggle()},onOpenedCha nged_:function(e){if(e.detail.value)this.showMenuPromo_=false},checkboxSelected: function(e){var toolbar=this.$.toolbar;toolbar.count=this.$.history.getSelectedI temCount()},unselectAll:function(){var listContainer=this.$.history;var toolbar= this.$.toolbar;listContainer.unselectAllItems(toolbar.count);toolbar.count=0},de leteSelected:function(){this.$.history.deleteSelectedWithPrompt()},historyResult :function(info,results){this.set("queryState_.querying",false);this.set("queryRe sult_.info",info);this.set("queryResult_.results",results);var listContainer=thi s.$["history"];listContainer.historyResult(info,results)},focusToolbarSearchFiel d:function(){this.$.toolbar.showSearchField()},onCanExecute_:function(e){e=e;swi tch(e.command.id){case"find-command":e.canExecute=true;break;case"slash-command" :e.canExecute=!this.$.toolbar.searchField.isSearchFocused();break;case"delete-co mmand":e.canExecute=this.$.toolbar.count>0;break}},onCommand_:function(e){if(e.c ommand.id=="find-command"||e.command.id=="slash-command")this.focusToolbarSearch Field();if(e.command.id=="delete-command")this.deleteSelected()},setForeignSessi ons:function(sessionList,isTabSyncEnabled){if(!isTabSyncEnabled){var syncedDevic eManagerElem=this.$$("history-synced-device-manager");if(syncedDeviceManagerElem ){md_history.ensureLazyLoaded().then(function(){syncedDeviceManagerElem.tabSyncD isabled()})}return}this.set("queryResult_.sessionList",sessionList)},historyDele ted:function(){this.$.history.historyDeleted()},updateSignInState:function(isUse rSignedIn){this.isUserSignedIn_=isUserSignedIn},syncedTabsSelected_:function(sel ectedPage){return selectedPage=="syncedTabs"},shouldShowSpinner_:function(queryi ng,incremental,searchTerm){return querying&&!incremental&&searchTerm!=""},showSy ncNotice_:function(hasSyncedResults,selectedPage){return hasSyncedResults&&selec tedPage!="syncedTabs"},selectedPageChanged_:function(){this.unselectAll();this.h istoryViewChanged_()},historyViewChanged_:function(){requestAnimationFrame(funct ion(){md_history.ensureLazyLoaded().then(function(){if(!this.$.content.selectedI tem)return;this.scrollTarget=this.$.content.selectedItem.getContentScrollTarget( );this._scrollHandler()}.bind(this))}.bind(this));this.recordHistoryPageView_()} ,getSelectedPage_:function(selectedPage,items){return selectedPage},closeDrawer_ :function(){var drawer=this.$$("#drawer");if(drawer)drawer.close()},recordHistor yPageView_:function(){var histogramValue=HistoryPageViewHistogram.END;switch(thi s.selectedPage_){case"syncedTabs":histogramValue=this.isUserSignedIn_?HistoryPag eViewHistogram.SYNCED_TABS:HistoryPageViewHistogram.SIGNIN_PROMO;break;default:s witch(this.queryState_.range){case HistoryRange.ALL_TIME:histogramValue=HistoryP ageViewHistogram.HISTORY;break;case HistoryRange.WEEK:histogramValue=HistoryPage ViewHistogram.GROUPED_WEEK;break;case HistoryRange.MONTH:histogramValue=HistoryP ageViewHistogram.GROUPED_MONTH;break}break}md_history.BrowserService.getInstance ().recordHistogram("History.HistoryPageView",histogramValue,HistoryPageViewHisto gram.END)}});
OLDNEW
« no previous file with comments | « no previous file | chrome/browser/resources/md_history/history_item.js » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698