431 lines
309 KiB
JavaScript
Executable File
431 lines
309 KiB
JavaScript
Executable File
// Copyright 2017 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
var CrContainerShadowBehavior={intersectionObserver_:null,attached:function(){var dropShadow=document.createElement("div");dropShadow.id="cr-container-shadow";this.shadowRoot.insertBefore(dropShadow,this.$.container);var intersectionProbe=document.createElement("div");this.$.container.prepend(intersectionProbe);var callback=entries=>{dropShadow.classList.toggle("has-shadow",entries[entries.length-1].intersectionRatio==0)};this.intersectionObserver_=new IntersectionObserver(callback,{root:this.$.container,threshold:0});window.setTimeout(()=>{if(this.intersectionObserver_)this.intersectionObserver_.observe(intersectionProbe)})},detached:function(){this.intersectionObserver_.disconnect();this.intersectionObserver_=null}};
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"cr-drawer",properties:{heading:String,open:{type:Boolean,notify:true},align:{type:String,value:"ltr",reflectToAttribute:true}},listeners:{transitionend:"onDialogTransitionEnd_"},toggle:function(){if(this.$.dialog.open)this.closeDrawer();else this.openDrawer()},openDrawer:function(){if(!this.$.dialog.open){this.$.dialog.showModal();this.open=true;this.classList.add("opening")}},closeDrawer:function(){if(this.$.dialog.open){this.classList.remove("opening");this.classList.add("closing")}},onContainerTap_:function(event){event.stopPropagation()},onDialogTap_:function(){this.closeDrawer()},onDialogCancel_:function(event){event.preventDefault();this.closeDrawer()},onDialogTransitionEnd_:function(){if(this.classList.contains("closing")){this.classList.remove("closing");this.$.dialog.close();this.open=false}else if(this.classList.contains("opening")){this.fire("cr-drawer-opened")}}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
var CrSearchFieldBehavior={properties:{label:{type:String,value:""},clearLabel:{type:String,value:""},hasSearchText:{type:Boolean,reflectToAttribute:true,value:false},lastValue_:{type:String,value:""}},getSearchInput:function(){},getValue:function(){return this.getSearchInput().value},setValue:function(value,opt_noEvent){var searchInput=this.getSearchInput();searchInput.value=value;this.onSearchTermInput();this.onValueChanged_(value,!!opt_noEvent)},onSearchTermSearch:function(){this.onValueChanged_(this.getValue(),false)},onSearchTermInput:function(){this.hasSearchText=this.$.searchInput.value!=""},onValueChanged_:function(newValue,noEvent){if(newValue==this.lastValue_)return;this.lastValue_=newValue;if(!noEvent)this.fire("search-changed",newValue)}};(function(){Polymer.IronMeta=function(options){Polymer.IronMeta[" "](options);this.type=options&&options.type||"default";this.key=options&&options.key;if(options&&"value"in options){this.value=options.value}};Polymer.IronMeta[" "]=function(){};Polymer.IronMeta.types={};Polymer.IronMeta.prototype={get value(){var type=this.type;var key=this.key;if(type&&key){return Polymer.IronMeta.types[type]&&Polymer.IronMeta.types[type][key]}},set value(value){var type=this.type;var key=this.key;if(type&&key){type=Polymer.IronMeta.types[type]=Polymer.IronMeta.types[type]||{};if(value==null){delete type[key]}else{type[key]=value}}},get list(){var type=this.type;if(type){var items=Polymer.IronMeta.types[this.type];if(!items){return[]}return Object.keys(items).map(function(key){return metaDatas[this.type][key]},this)}},byKey:function(key){this.key=key;return this.value}};var metaDatas=Polymer.IronMeta.types;Polymer({is:"iron-meta",properties:{type:{type:String,value:"default"},key:{type:String},value:{type:String,notify:true},self:{type:Boolean,observer:"_selfChanged"},__meta:{type:Boolean,computed:"__computeMeta(type, key, value)"}},hostAttributes:{hidden:true},__computeMeta:function(type,key,value){var meta=new Polymer.IronMeta({type:type,key:key});if(value!==undefined&&value!==meta.value){meta.value=value}else if(this.value!==meta.value){this.value=meta.value}return meta},get list(){return this.__meta&&this.__meta.list},_selfChanged:function(self){if(self){this.value=this}},byKey:function(key){return new Polymer.IronMeta({type:this.type,key:key}).value}})})();Polymer({is:"iron-iconset-svg",properties:{name:{type:String,observer:"_nameChanged"},size:{type:Number,value:24},rtlMirroring:{type:Boolean,value:false},useGlobalRtlAttribute:{type:Boolean,value:false}},created:function(){this._meta=new Polymer.IronMeta({type:"iconset",key:null,value:null})},attached:function(){this.style.display="none"},getIconNames:function(){this._icons=this._createIconMap();return Object.keys(this._icons).map(function(n){return this.name+":"+n},this)},applyIcon:function(element,iconName){this.removeIcon(element);var svg=this._cloneIcon(iconName,this.rtlMirroring&&this._targetIsRTL(element));if(svg){var pde=Polymer.dom(element.root||element);pde.insertBefore(svg,pde.childNodes[0]);return element._svgIcon=svg}return null},removeIcon:function(element){if(element._svgIcon){Polymer.dom(element.root||element).removeChild(element._svgIcon);element._svgIcon=null}},_targetIsRTL:function(target){if(this.__targetIsRTL==null){if(this.useGlobalRtlAttribute){var globalElement=document.body&&document.body.hasAttribute("dir")?document.body:document.documentElement;this.__targetIsRTL=globalElement.getAttribute("dir")==="rtl"}else{if(target&&target.nodeType!==Node.ELEMENT_NODE){target=target.host}this.__targetIsRTL=target&&window.getComputedStyle(target)["direction"]==="rtl"}}return this.__targetIsRTL},_nameChanged:function(){this._meta.value=null;this._meta.key=this.name;this._meta.value=this;this.async(function(){this.fire("iron-iconset-added",this,{node:window})})},_createIconMap:function(){var icons=Object.create(null);Polymer.dom(this).querySelectorAll("[id]").forEach(function(icon){icons[icon.id]=icon});return icons},_cloneIcon:function(id,mirrorAllowed){this._icons=this._icons||this._createIconMap();return this._prepareSvgClone(this._icons[id],this.size,mirrorAllowed)},_prepareSvgClone:function(sourceSvg,size,mirrorAllowed){if(sourceSvg){var content=sourceSvg.cloneNode(true),svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),viewBox=content.getAttribute("viewBox")||"0 0 "+size+" "+size,cssText="pointer-events: none; display: block; width: 100%; height: 100%;";if(mirrorAllowed&&content.hasAttribute("mirror-in-rtl")){cssText+="-webkit-transform:scale(-1,1);transform:scale(-1,1);transform-origin:center;"}svg.setAttribute("viewBox",viewBox);svg.setAttribute("preserveAspectRatio","xMidYMid meet");svg.setAttribute("focusable","false");svg.style.cssText=cssText;svg.appendChild(content).removeAttribute("id");return svg}return null}});(function(){"use strict";var KEY_IDENTIFIER={"U+0008":"backspace","U+0009":"tab","U+001B":"esc","U+0020":"space","U+007F":"del"};var KEY_CODE={8:"backspace",9:"tab",13:"enter",27:"esc",33:"pageup",34:"pagedown",35:"end",36:"home",32:"space",37:"left",38:"up",39:"right",40:"down",46:"del",106:"*"};var MODIFIER_KEYS={shift:"shiftKey",ctrl:"ctrlKey",alt:"altKey",meta:"metaKey"};var KEY_CHAR=/[a-z0-9*]/;var IDENT_CHAR=/U\+/;var ARROW_KEY=/^arrow/;var SPACE_KEY=/^space(bar)?/;var ESC_KEY=/^escape$/;function transformKey(key,noSpecialChars){var validKey="";if(key){var lKey=key.toLowerCase();if(lKey===" "||SPACE_KEY.test(lKey)){validKey="space"}else if(ESC_KEY.test(lKey)){validKey="esc"}else if(lKey.length==1){if(!noSpecialChars||KEY_CHAR.test(lKey)){validKey=lKey}}else if(ARROW_KEY.test(lKey)){validKey=lKey.replace("arrow","")}else if(lKey=="multiply"){validKey="*"}else{validKey=lKey}}return validKey}function transformKeyIdentifier(keyIdent){var validKey="";if(keyIdent){if(keyIdent in KEY_IDENTIFIER){validKey=KEY_IDENTIFIER[keyIdent]}else if(IDENT_CHAR.test(keyIdent)){keyIdent=parseInt(keyIdent.replace("U+","0x"),16);validKey=String.fromCharCode(keyIdent).toLowerCase()}else{validKey=keyIdent.toLowerCase()}}return validKey}function transformKeyCode(keyCode){var validKey="";if(Number(keyCode)){if(keyCode>=65&&keyCode<=90){validKey=String.fromCharCode(32+keyCode)}else if(keyCode>=112&&keyCode<=123){validKey="f"+(keyCode-112+1)}else if(keyCode>=48&&keyCode<=57){validKey=String(keyCode-48)}else if(keyCode>=96&&keyCode<=105){validKey=String(keyCode-96)}else{validKey=KEY_CODE[keyCode]}}return validKey}function normalizedKeyForEvent(keyEvent,noSpecialChars){if(keyEvent.key){return transformKey(keyEvent.key,noSpecialChars)}if(keyEvent.detail&&keyEvent.detail.key){return transformKey(keyEvent.detail.key,noSpecialChars)}return transformKeyIdentifier(keyEvent.keyIdentifier)||transformKeyCode(keyEvent.keyCode)||""}function keyComboMatchesEvent(keyCombo,event){var keyEvent=normalizedKeyForEvent(event,keyCombo.hasModifiers);return keyEvent===keyCombo.key&&(!keyCombo.hasModifiers||!!event.shiftKey===!!keyCombo.shiftKey&&!!event.ctrlKey===!!keyCombo.ctrlKey&&!!event.altKey===!!keyCombo.altKey&&!!event.metaKey===!!keyCombo.metaKey)}function parseKeyComboString(keyComboString){if(keyComboString.length===1){return{combo:keyComboString,key:keyComboString,event:"keydown"}}return keyComboString.split("+").reduce(function(parsedKeyCombo,keyComboPart){var eventParts=keyComboPart.split(":");var keyName=eventParts[0];var event=eventParts[1];if(keyName in MODIFIER_KEYS){parsedKeyCombo[MODIFIER_KEYS[keyName]]=true;parsedKeyCombo.hasModifiers=true}else{parsedKeyCombo.key=keyName;parsedKeyCombo.event=event||"keydown"}return parsedKeyCombo},{combo:keyComboString.split(":").shift()})}function parseEventString(eventString){return eventString.trim().split(" ").map(function(keyComboString){return parseKeyComboString(keyComboString)})}Polymer.IronA11yKeysBehavior={properties:{keyEventTarget:{type:Object,value:function(){return this}},stopKeyboardEventPropagation:{type:Boolean,value:false},_boundKeyHandlers:{type:Array,value:function(){return[]}},_imperativeKeyBindings:{type:Object,value:function(){return{}}}},observers:["_resetKeyEventListeners(keyEventTarget, _boundKeyHandlers)"],keyBindings:{},registered:function(){this._prepKeyBindings()},attached:function(){this._listenKeyEventListeners()},detached:function(){this._unlistenKeyEventListeners()},addOwnKeyBinding:function(eventString,handlerName){this._imperativeKeyBindings[eventString]=handlerName;this._prepKeyBindings();this._resetKeyEventListeners()},removeOwnKeyBindings:function(){this._imperativeKeyBindings={};this._prepKeyBindings();this._resetKeyEventListeners()},keyboardEventMatchesKeys:function(event,eventString){var keyCombos=parseEventString(eventString);for(var i=0;i<keyCombos.length;++i){if(keyComboMatchesEvent(keyCombos[i],event)){return true}}return false},_collectKeyBindings:function(){var keyBindings=this.behaviors.map(function(behavior){return behavior.keyBindings});if(keyBindings.indexOf(this.keyBindings)===-1){keyBindings.push(this.keyBindings)}return keyBindings},_prepKeyBindings:function(){this._keyBindings={};this._collectKeyBindings().forEach(function(keyBindings){for(var eventString in keyBindings){this._addKeyBinding(eventString,keyBindings[eventString])}},this);for(var eventString in this._imperativeKeyBindings){this._addKeyBinding(eventString,this._imperativeKeyBindings[eventString])}for(var eventName in this._keyBindings){this._keyBindings[eventName].sort(function(kb1,kb2){var b1=kb1[0].hasModifiers;var b2=kb2[0].hasModifiers;return b1===b2?0:b1?-1:1})}},_addKeyBinding:function(eventString,handlerName){parseEventString(eventString).forEach(function(keyCombo){this._keyBindings[keyCombo.event]=this._keyBindings[keyCombo.event]||[];this._keyBindings[keyCombo.event].push([keyCombo,handlerName])},this)},_resetKeyEventListeners:function(){this._unlistenKeyEventListeners();if(this.isAttached){this._listenKeyEventListeners()}},_listenKeyEventListeners:function(){if(!this.keyEventTarget){return}Object.keys(this._keyBindings).forEach(function(eventName){var keyBindings=this._keyBindings[eventName];var boundKeyHandler=this._onKeyBindingEvent.bind(this,keyBindings);this._boundKeyHandlers.push([this.keyEventTarget,eventName,boundKeyHandler]);this.keyEventTarget.addEventListener(eventName,boundKeyHandler)},this)},_unlistenKeyEventListeners:function(){var keyHandlerTuple;var keyEventTarget;var eventName;var boundKeyHandler;while(this._boundKeyHandlers.length){keyHandlerTuple=this._boundKeyHandlers.pop();keyEventTarget=keyHandlerTuple[0];eventName=keyHandlerTuple[1];boundKeyHandler=keyHandlerTuple[2];keyEventTarget.removeEventListener(eventName,boundKeyHandler)}},_onKeyBindingEvent:function(keyBindings,event){if(this.stopKeyboardEventPropagation){event.stopPropagation()}if(event.defaultPrevented){return}for(var i=0;i<keyBindings.length;i++){var keyCombo=keyBindings[i][0];var handlerName=keyBindings[i][1];if(keyComboMatchesEvent(keyCombo,event)){this._triggerKeyHandler(keyCombo,handlerName,event);if(event.defaultPrevented){return}}}},_triggerKeyHandler:function(keyCombo,handlerName,keyboardEvent){var detail=Object.create(keyCombo);detail.keyboardEvent=keyboardEvent;var event=new CustomEvent(keyCombo.event,{detail:detail,cancelable:true});this[handlerName].call(this,event);if(event.defaultPrevented){keyboardEvent.preventDefault()}}}})();Polymer.IronControlState={properties:{focused:{type:Boolean,value:false,notify:true,readOnly:true,reflectToAttribute:true},disabled:{type:Boolean,value:false,notify:true,observer:"_disabledChanged",reflectToAttribute:true},_oldTabIndex:{type:String},_boundFocusBlurHandler:{type:Function,value:function(){return this._focusBlurHandler.bind(this)}},__handleEventRetargeting:{type:Boolean,value:function(){return!this.shadowRoot&&!Polymer.Element}}},observers:["_changedControlState(focused, disabled)"],ready:function(){this.addEventListener("focus",this._boundFocusBlurHandler,true);this.addEventListener("blur",this._boundFocusBlurHandler,true)},_focusBlurHandler:function(event){if(Polymer.Element){this._setFocused(event.type==="focus");return}if(event.target===this){this._setFocused(event.type==="focus")}else if(this.__handleEventRetargeting){var target=Polymer.dom(event).localTarget;if(!this.isLightDescendant(target)){this.fire(event.type,{sourceEvent:event},{node:this,bubbles:event.bubbles,cancelable:event.cancelable})}}},_disabledChanged:function(disabled,old){this.setAttribute("aria-disabled",disabled?"true":"false");this.style.pointerEvents=disabled?"none":"";if(disabled){this._oldTabIndex=this.getAttribute("tabindex");this._setFocused(false);this.tabIndex=-1;this.blur()}else if(this._oldTabIndex!==undefined){if(this._oldTabIndex===null){this.removeAttribute("tabindex")}else{this.setAttribute("tabindex",this._oldTabIndex)}}},_changedControlState:function(){if(this._controlStateChanged){this._controlStateChanged()}}};Polymer.IronButtonStateImpl={properties:{pressed:{type:Boolean,readOnly:true,value:false,reflectToAttribute:true,observer:"_pressedChanged"},toggles:{type:Boolean,value:false,reflectToAttribute:true},active:{type:Boolean,value:false,notify:true,reflectToAttribute:true},pointerDown:{type:Boolean,readOnly:true,value:false},receivedFocusFromKeyboard:{type:Boolean,readOnly:true},ariaActiveAttribute:{type:String,value:"aria-pressed",observer:"_ariaActiveAttributeChanged"}},listeners:{down:"_downHandler",up:"_upHandler",tap:"_tapHandler"},observers:["_focusChanged(focused)","_activeChanged(active, ariaActiveAttribute)"],keyBindings:{"enter:keydown":"_asyncClick","space:keydown":"_spaceKeyDownHandler","space:keyup":"_spaceKeyUpHandler"},_mouseEventRe:/^mouse/,_tapHandler:function(){if(this.toggles){this._userActivate(!this.active)}else{this.active=false}},_focusChanged:function(focused){this._detectKeyboardFocus(focused);if(!focused){this._setPressed(false)}},_detectKeyboardFocus:function(focused){this._setReceivedFocusFromKeyboard(!this.pointerDown&&focused)},_userActivate:function(active){if(this.active!==active){this.active=active;this.fire("change")}},_downHandler:function(event){this._setPointerDown(true);this._setPressed(true);this._setReceivedFocusFromKeyboard(false)},_upHandler:function(){this._setPointerDown(false);this._setPressed(false)},_spaceKeyDownHandler:function(event){var keyboardEvent=event.detail.keyboardEvent;var target=Polymer.dom(keyboardEvent).localTarget;if(this.isLightDescendant(target))return;keyboardEvent.preventDefault();keyboardEvent.stopImmediatePropagation();this._setPressed(true)},_spaceKeyUpHandler:function(event){var keyboardEvent=event.detail.keyboardEvent;var target=Polymer.dom(keyboardEvent).localTarget;if(this.isLightDescendant(target))return;if(this.pressed){this._asyncClick()}this._setPressed(false)},_asyncClick:function(){this.async(function(){this.click()},1)},_pressedChanged:function(pressed){this._changedButtonState()},_ariaActiveAttributeChanged:function(value,oldValue){if(oldValue&&oldValue!=value&&this.hasAttribute(oldValue)){this.removeAttribute(oldValue)}},_activeChanged:function(active,ariaActiveAttribute){if(this.toggles){this.setAttribute(this.ariaActiveAttribute,active?"true":"false")}else{this.removeAttribute(this.ariaActiveAttribute)}this._changedButtonState()},_controlStateChanged:function(){if(this.disabled){this._setPressed(false)}else{this._changedButtonState()}},_changedButtonState:function(){if(this._buttonStateChanged){this._buttonStateChanged()}}};Polymer.IronButtonState=[Polymer.IronA11yKeysBehavior,Polymer.IronButtonStateImpl];(function(){var MAX_RADIUS_PX=300;var MIN_DURATION_MS=800;var distance=function(x1,y1,x2,y2){var xDelta=x1-x2;var yDelta=y1-y2;return Math.sqrt(xDelta*xDelta+yDelta*yDelta)};Polymer({is:"paper-ripple",behaviors:[Polymer.IronA11yKeysBehavior],properties:{center:{type:Boolean,value:false},holdDown:{type:Boolean,value:false,observer:"_holdDownChanged"},recenters:{type:Boolean,value:false},noink:{type:Boolean,value:false}},keyBindings:{"enter:keydown":"_onEnterKeydown","space:keydown":"_onSpaceKeydown","space:keyup":"_onSpaceKeyup"},created:function(){this.ripples=[]},attached:function(){this.keyEventTarget=this.parentNode.nodeType==11?Polymer.dom(this).getOwnerRoot().host:this.parentNode;this.keyEventTarget=this.keyEventTarget;this.listen(this.keyEventTarget,"up","uiUpAction");this.listen(this.keyEventTarget,"down","uiDownAction")},detached:function(){this.unlisten(this.keyEventTarget,"up","uiUpAction");this.unlisten(this.keyEventTarget,"down","uiDownAction");this.keyEventTarget=null},simulatedRipple:function(){this.downAction();this.async(function(){this.upAction()}.bind(this),1)},uiDownAction:function(e){if(!this.noink)this.downAction(e)},downAction:function(e){if(this.ripples.length&&this.holdDown)return;this.debounce("show ripple",function(){this.__showRipple(e)},1)},__showRipple:function(e){var rect=this.getBoundingClientRect();var roundedCenterX=function(){return Math.round(rect.width/2)};var roundedCenterY=function(){return Math.round(rect.height/2)};var centered=!e||this.center;if(centered){var x=roundedCenterX();var y=roundedCenterY()}else{var sourceEvent=e.detail.sourceEvent;var x=Math.round(sourceEvent.clientX-rect.left);var y=Math.round(sourceEvent.clientY-rect.top)}var corners=[{x:0,y:0},{x:rect.width,y:0},{x:0,y:rect.height},{x:rect.width,y:rect.height}];var cornerDistances=corners.map(function(corner){return Math.round(distance(x,y,corner.x,corner.y))});var radius=Math.min(MAX_RADIUS_PX,Math.max.apply(Math,cornerDistances));var startTranslate=x-radius+"px, "+(y-radius)+"px";if(this.recenters&&!centered){var endTranslate=roundedCenterX()-radius+"px, "+(roundedCenterY()-radius)+"px"}else{var endTranslate=startTranslate}var ripple=document.createElement("div");ripple.classList.add("ripple");ripple.style.height=ripple.style.width=2*radius+"px";this.ripples.push(ripple);this.shadowRoot.appendChild(ripple);ripple.animate({transform:["translate("+startTranslate+") scale(0)","translate("+endTranslate+") scale(1)"]},{duration:Math.max(MIN_DURATION_MS,Math.log(radius)*radius)||0,easing:"cubic-bezier(.2, .9, .1, .9)",fill:"forwards"})},uiUpAction:function(e){if(!this.noink)this.upAction()},upAction:function(e){if(!this.holdDown)this.debounce("hide ripple",function(){this.__hideRipple()},1)},__hideRipple:function(){Promise.all(this.ripples.map(function(ripple){return new Promise(function(resolve){var removeRipple=function(){ripple.remove();resolve()};var opacity=getComputedStyle(ripple).opacity;if(!opacity.length){removeRipple()}else{var animation=ripple.animate({opacity:[opacity,0]},{duration:150,fill:"forwards"});animation.addEventListener("finish",removeRipple);animation.addEventListener("cancel",removeRipple)}})})).then(function(){this.fire("transitionend")}.bind(this));this.ripples=[]},_onEnterKeydown:function(){this.uiDownAction();this.async(this.uiUpAction,1)},_onSpaceKeydown:function(){this.uiDownAction()},_onSpaceKeyup:function(){this.uiUpAction()},_holdDownChanged:function(newHoldDown,oldHoldDown){if(oldHoldDown===undefined)return;if(newHoldDown)this.downAction();else this.upAction()}})})();Polymer.PaperRippleBehavior={properties:{noink:{type:Boolean,observer:"_noinkChanged"},_rippleContainer:{type:Object}},_buttonStateChanged:function(){if(this.focused){this.ensureRipple()}},_downHandler:function(event){Polymer.IronButtonStateImpl._downHandler.call(this,event);if(this.pressed){this.ensureRipple(event)}},ensureRipple:function(optTriggeringEvent){if(!this.hasRipple()){this._ripple=this._createRipple();this._ripple.noink=this.noink;var rippleContainer=this._rippleContainer||this.root;if(rippleContainer){Polymer.dom(rippleContainer).appendChild(this._ripple)}if(optTriggeringEvent){var domContainer=Polymer.dom(this._rippleContainer||this);var target=Polymer.dom(optTriggeringEvent).rootTarget;if(domContainer.deepContains(target)){this._ripple.uiDownAction(optTriggeringEvent)}}}},getRipple:function(){this.ensureRipple();return this._ripple},hasRipple:function(){return Boolean(this._ripple)},_createRipple:function(){var element=document.createElement("paper-ripple");return element},_noinkChanged:function(noink){if(this.hasRipple()){this._ripple.noink=noink}}};Polymer({is:"paper-icon-button-light",behaviors:[Polymer.PaperRippleBehavior],ready:function(){Polymer.RenderStatus.afterNextRender(this,()=>{this.addEventListener("down",this._rippleDown.bind(this));this.addEventListener("up",this._rippleUp.bind(this));var button=this.getEffectiveChildren()[0];this._rippleContainer=button;button.addEventListener("focus",this._rippleDown.bind(this));button.addEventListener("blur",this._rippleUp.bind(this))})},_rippleDown:function(){this.getRipple().uiDownAction()},_rippleUp:function(){this.getRipple().uiUpAction()},ensureRipple:function(var_args){var lastRipple=this._ripple;Polymer.PaperRippleBehavior.ensureRipple.apply(this,arguments);if(this._ripple&&this._ripple!==lastRipple){this._ripple.center=true;this._ripple.classList.add("circle")}}});Polymer({is:"iron-icon",properties:{icon:{type:String},theme:{type:String},src:{type:String},_meta:{value:Polymer.Base.create("iron-meta",{type:"iconset"})}},observers:["_updateIcon(_meta, isAttached)","_updateIcon(theme, isAttached)","_srcChanged(src, isAttached)","_iconChanged(icon, isAttached)"],_DEFAULT_ICONSET:"icons",_iconChanged:function(icon){var parts=(icon||"").split(":");this._iconName=parts.pop();this._iconsetName=parts.pop()||this._DEFAULT_ICONSET;this._updateIcon()},_srcChanged:function(src){this._updateIcon()},_usesIconset:function(){return this.icon||!this.src},_updateIcon:function(){if(this._usesIconset()){if(this._img&&this._img.parentNode){Polymer.dom(this.root).removeChild(this._img)}if(this._iconName===""){if(this._iconset){this._iconset.removeIcon(this)}}else if(this._iconsetName&&this._meta){this._iconset=this._meta.byKey(this._iconsetName);if(this._iconset){this._iconset.applyIcon(this,this._iconName,this.theme);this.unlisten(window,"iron-iconset-added","_updateIcon")}else{this.listen(window,"iron-iconset-added","_updateIcon")}}}else{if(this._iconset){this._iconset.removeIcon(this)}if(!this._img){this._img=document.createElement("img");this._img.style.width="100%";this._img.style.height="100%";this._img.draggable=false}this._img.src=this.src;Polymer.dom(this.root).appendChild(this._img)}}});Polymer.PaperInkyFocusBehaviorImpl={observers:["_focusedChanged(receivedFocusFromKeyboard)"],_focusedChanged:function(receivedFocusFromKeyboard){if(receivedFocusFromKeyboard){this.ensureRipple()}if(this.hasRipple()){this._ripple.holdDown=receivedFocusFromKeyboard}},_createRipple:function(){var ripple=Polymer.PaperRippleBehavior._createRipple();ripple.id="ink";ripple.setAttribute("center","");ripple.classList.add("circle");return ripple}};Polymer.PaperInkyFocusBehavior=[Polymer.IronButtonState,Polymer.IronControlState,Polymer.PaperRippleBehavior,Polymer.PaperInkyFocusBehaviorImpl];Polymer({is:"paper-icon-button",hostAttributes:{role:"button",tabindex:"0"},behaviors:[Polymer.PaperInkyFocusBehavior],properties:{src:{type:String},icon:{type:String},alt:{type:String,observer:"_altChanged"}},_altChanged:function(newValue,oldValue){var label=this.getAttribute("aria-label");if(!label||oldValue==label){this.setAttribute("aria-label",newValue)}}});Polymer.PaperSpinnerBehavior={properties:{active:{type:Boolean,value:false,reflectToAttribute:true,observer:"__activeChanged"},alt:{type:String,value:"loading",observer:"__altChanged"},__coolingDown:{type:Boolean,value:false}},__computeContainerClasses:function(active,coolingDown){return[active||coolingDown?"active":"",coolingDown?"cooldown":""].join(" ")},__activeChanged:function(active,old){this.__setAriaHidden(!active);this.__coolingDown=!active&&old},__altChanged:function(alt){if(alt==="loading"){this.alt=this.getAttribute("aria-label")||alt}else{this.__setAriaHidden(alt==="");this.setAttribute("aria-label",alt)}},__setAriaHidden:function(hidden){var attr="aria-hidden";if(hidden){this.setAttribute(attr,"true")}else{this.removeAttribute(attr)}},__reset:function(){this.active=false;this.__coolingDown=false}};Polymer({is:"paper-spinner-lite",behaviors:[Polymer.PaperSpinnerBehavior]});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"cr-toolbar-search-field",behaviors:[CrSearchFieldBehavior],properties:{narrow:{type:Boolean,reflectToAttribute:true},showingSearch:{type:Boolean,value:false,notify:true,observer:"showingSearchChanged_",reflectToAttribute:true},label:String,clearLabel:String,spinnerActive:{type:Boolean,reflectToAttribute:true},isSpinnerShown_:{type:Boolean,computed:"computeIsSpinnerShown_(spinnerActive, showingSearch)"},searchFocused_:{type:Boolean,value:false}},listeners:{click:"showSearch_"},getSearchInput:function(){return this.$.searchInput},isSearchFocused:function(){return this.searchFocused_},showAndFocus:function(){this.showingSearch=true;this.focus_()},onSearchTermInput:function(){CrSearchFieldBehavior.onSearchTermInput.call(this);this.showingSearch=this.hasSearchText||this.isSearchFocused()},focus_:function(){this.getSearchInput().focus()},computeIconTabIndex_:function(narrow){return narrow?0:-1},computeIconAriaHidden_:function(narrow){return Boolean(!narrow).toString()},computeIsSpinnerShown_:function(){var showSpinner=this.spinnerActive&&this.showingSearch;if(showSpinner)this.$.spinnerTemplate.if=true;return showSpinner},onInputFocus_:function(){this.searchFocused_=true},onInputBlur_:function(){this.searchFocused_=false;if(!this.hasSearchText)this.showingSearch=false},onSearchTermKeydown_:function(e){if(e.key=="Escape")this.showingSearch=false},showSearch_:function(e){if(e.target!=this.$.clearSearch)this.showingSearch=true},clearSearch_:function(e){this.setValue("");this.focus_()},showingSearchChanged_:function(current,previous){if(previous==undefined)return;if(this.showingSearch){this.focus_();return}this.setValue("");this.getSearchInput().blur()}});Polymer({is:"iron-media-query",properties:{queryMatches:{type:Boolean,value:false,readOnly:true,notify:true},query:{type:String,observer:"queryChanged"},full:{type:Boolean,value:false},_boundMQHandler:{value:function(){return this.queryHandler.bind(this)}},_mq:{value:null}},attached:function(){this.style.display="none";this.queryChanged()},detached:function(){this._remove()},_add:function(){if(this._mq){this._mq.addListener(this._boundMQHandler)}},_remove:function(){if(this._mq){this._mq.removeListener(this._boundMQHandler)}this._mq=null},queryChanged:function(){this._remove();var query=this.query;if(!query){return}if(!this.full&&query[0]!=="("){query="("+query+")"}this._mq=window.matchMedia(query);this._add();this.queryHandler(this._mq)},queryHandler:function(mq){this._setQueryMatches(mq.matches)}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"cr-toolbar",properties:{pageName:String,searchPrompt:String,clearLabel:String,menuLabel:String,menuPromo:String,spinnerActive:Boolean,showMenu:{type:Boolean,value:false},showMenuPromo:{type:Boolean,value:false},showSearch:{type:Boolean,value:true},narrow:{type:Boolean,reflectToAttribute:true,readonly:true,notify:true},narrowThreshold:{type:Number,value:900},closeMenuPromo:String,showingSearch_:{type:Boolean,reflectToAttribute:true}},observers:["possiblyShowMenuPromo_(showMenu, showMenuPromo, showingSearch_)"],getSearchField:function(){return this.$.search},onClosePromoTap_:function(){this.fire("cr-toolbar-menu-promo-close")},onMenuTap_:function(){this.fire("cr-toolbar-menu-tap")},possiblyShowMenuPromo_:function(){Polymer.RenderStatus.afterNextRender(this,function(){if(this.showMenu&&this.showMenuPromo&&!this.showingSearch_){this.$$("#menuPromo").animate({opacity:[0,.9]},{duration:500,fill:"forwards"});this.fire("cr-toolbar-menu-promo-shown")}}.bind(this))},titleIfNotShowMenuPromo_:function(title,showMenuPromo){return showMenuPromo?"":title}});
|
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
function assert(condition,opt_message){if(!condition){var message="Assertion failed";if(opt_message)message=message+": "+opt_message;var error=new Error(message);var global=function(){return this}();if(global.traceAssertionsForTesting)console.warn(error.stack);throw error}return condition}function assertNotReached(opt_message){assert(false,opt_message||"Unreachable code hit")}function assertInstanceof(value,type,opt_message){if(!(value instanceof type)){assertNotReached(opt_message||"Value "+value+" is not a[n] "+(type.name||typeof type))}return value}
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
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){assertNotReached()},get resolve(){return this.resolve_},set resolve(r){assertNotReached()},get reject(){return this.reject_},set reject(s){assertNotReached()}};
|
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
var global=this;var WebUIListener;var cr=cr||function(){"use strict";function exportPath(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 cur){cur=cur[part]}else{cur=cur[part]={}}}return cur}function dispatchPropertyChange(target,propertyName,newValue,oldValue){var e=new Event(propertyName+"Change");e.propertyName=propertyName;e.newValue=newValue;e.oldValue=oldValue;target.dispatchEvent(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 privateName=name+"_";return function(){return this[privateName]};case PropertyKind.ATTR:var attributeName=getAttributeName(name);return function(){return this.getAttribute(attributeName)};case PropertyKind.BOOL_ATTR:var attributeName=getAttributeName(name);return function(){return this.hasAttribute(attributeName)}}throw"not reached"}function getSetter(name,kind,opt_setHook){switch(kind){case PropertyKind.JS:var privateName=name+"_";return function(value){var oldValue=this[name];if(value!==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 oldValue=this[name];if(value!==oldValue){if(value==undefined)this.removeAttribute(attributeName);else this.setAttribute(attributeName,value);if(opt_setHook)opt_setHook.call(this,value,oldValue);dispatchPropertyChange(this,name,value,oldValue)}};case PropertyKind.BOOL_ATTR:var attributeName=getAttributeName(name);return function(value){var oldValue=this[name];if(value!==oldValue){if(value)this.setAttribute(attributeName,name);else this.removeAttribute(attributeName);if(opt_setHook)opt_setHook.call(this,value,oldValue);dispatchPropertyChange(this,name,value,oldValue)}}}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));if(!obj.__lookupSetter__(name))obj.__defineSetter__(name,getSetter(name,kind,opt_setHook))}var uidCounter=1;function createUid(){return uidCounter++}function getUid(item){if(item.hasOwnProperty("uid"))return item.uid;return item.uid=createUid()}function dispatchSimpleEvent(target,type,opt_bubbles,opt_cancelable){var e=new Event(type,{bubbles:opt_bubbles,cancelable:opt_cancelable===undefined||opt_cancelable});return target.dispatchEvent(e)}function define(name,fun){var obj=exportPath(name);var exports=fun();for(var propertyName in exports){var propertyDescriptor=Object.getOwnPropertyDescriptor(exports,propertyName);if(propertyDescriptor)Object.defineProperty(obj,propertyName,propertyDescriptor)}}function addSingletonGetter(ctor){ctor.getInstance=function(){return ctor.instance_||(ctor.instance_=new ctor)}}function makePublic(ctor,methods,opt_target){methods.forEach(function(method){ctor[method]=function(){var target=opt_target?document.getElementById(opt_target):ctor.getInstance();return target[method+"_"].apply(target,arguments)}})}var chromeSendResolverMap={};function webUIResponse(id,isSuccess,response){var resolver=chromeSendResolverMap[id];delete chromeSendResolverMap[id];if(isSuccess)resolver.resolve(response);else resolver.reject(response)}function sendWithPromise(methodName,var_args){var args=Array.prototype.slice.call(arguments,1);var promiseResolver=new PromiseResolver;var id=methodName+"_"+createUid();chromeSendResolverMap[id]=promiseResolver;chrome.send(methodName,[id].concat(args));return promiseResolver.promise}var webUIListenerMap={};function webUIListenerCallback(event,var_args){var eventListenersMap=webUIListenerMap[event];if(!eventListenersMap){return}var args=Array.prototype.slice.call(arguments,1);for(var listenerId in eventListenersMap){eventListenersMap[listenerId].apply(null,args)}}function addWebUIListener(eventName,callback){webUIListenerMap[eventName]=webUIListenerMap[eventName]||{};var uid=createUid();webUIListenerMap[eventName][uid]=callback;return{eventName:eventName,uid:uid}}function removeWebUIListener(listener){var listenerExists=webUIListenerMap[listener.eventName]&&webUIListenerMap[listener.eventName][listener.uid];if(listenerExists){delete webUIListenerMap[listener.eventName][listener.uid];return true}return false}return{addSingletonGetter:addSingletonGetter,createUid:createUid,define:define,defineProperty:defineProperty,dispatchPropertyChange:dispatchPropertyChange,dispatchSimpleEvent:dispatchSimpleEvent,exportPath:exportPath,getUid:getUid,makePublic:makePublic,PropertyKind:PropertyKind,addWebUIListener:addWebUIListener,removeWebUIListener:removeWebUIListener,sendWithPromise:sendWithPromise,webUIListenerCallback:webUIListenerCallback,webUIResponse:webUIResponse,get doc(){return document},get isMac(){return/Mac/.test(navigator.platform)},get isWindows(){return/Win/.test(navigator.platform)},get isChromeOS(){return/CrOS/.test(navigator.userAgent)},get isLinux(){return/Linux/.test(navigator.userAgent)},get isAndroid(){return/Android/.test(navigator.userAgent)},get isIOS(){return/iPad|iPhone|iPod/.test(navigator.platform)}}}();
|
|
// Copyright 2018 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.exportPath("settings");settings.FindShortcutBehaviorImpl={keyBindings:{"ctrl+f":"onFindShortcut_"},onFindShortcut_:function(e){if(!e.defaultPrevented&&this.canHandleFindShortcut()){this.handleFindShortcut();e.preventDefault()}},canHandleFindShortcut:function(){assertNotReached()},handleFindShortcut:function(){assertNotReached()}};settings.FindShortcutBehavior=[Polymer.IronA11yKeysBehavior,settings.FindShortcutBehaviorImpl];
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
let GuestModePageVisibility;let AppearancePageVisibility;let DateTimePageVisibility;let DownloadsPageVisibility;let PrivacyPageVisibility;cr.define("settings",function(){let pageVisibility;if(loadTimeData.getBoolean("isGuest")){pageVisibility={passwordsAndForms:false,people:false,onStartup:false,reset:false,appearance:false,defaultBrowser:false,advancedSettings:false}}else{}return{pageVisibility:pageVisibility}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
let SettingsRoutes;cr.define("settings",function(){class Route{constructor(path){this.path=path;this.parent=null;this.depth=0;this.isNavigableDialog=false;this.section=""}createChild(path){assert(path);const newUrl=path[0]=="/"?path:`${this.path}/${path}`;const route=new Route(newUrl);route.parent=this;route.section=this.section;route.depth=this.depth+1;return route}createSection(path,section){const route=this.createChild(path);route.section=section;return route}getAbsolutePath(){return window.location.origin+this.path}contains(route){for(let r=route;r!=null;r=r.parent){if(this==r)return true}return false}isSubpage(){return!!this.parent&&!!this.section&&this.parent.section==this.section}}const computeAvailableRoutes=function(){const pageVisibility=settings.pageVisibility||{};const r={};r.BASIC=new Route("/");r.ABOUT=new Route("/help");r.IMPORT_DATA=r.BASIC.createChild("/importData");r.IMPORT_DATA.isNavigableDialog=true;r.SIGN_OUT=r.BASIC.createChild("/signOut");r.SIGN_OUT.isNavigableDialog=true;if(pageVisibility.appearance!==false){r.APPEARANCE=r.BASIC.createSection("/appearance","appearance");r.FONTS=r.APPEARANCE.createChild("/fonts")}if(pageVisibility.defaultBrowser!==false){r.DEFAULT_BROWSER=r.BASIC.createSection("/defaultBrowser","defaultBrowser")}r.SEARCH=r.BASIC.createSection("/search","search");r.SEARCH_ENGINES=r.SEARCH.createChild("/searchEngines");if(pageVisibility.onStartup!==false){r.ON_STARTUP=r.BASIC.createSection("/onStartup","onStartup");r.STARTUP_PAGES=r.ON_STARTUP.createChild("/startupPages")}if(pageVisibility.people!==false){r.PEOPLE=r.BASIC.createSection("/people","people");r.SYNC=r.PEOPLE.createChild("/syncSetup");r.MANAGE_PROFILE=r.PEOPLE.createChild("/manageProfile")}if(pageVisibility.advancedSettings!==false){r.ADVANCED=new Route("/advanced");r.CLEAR_BROWSER_DATA=r.ADVANCED.createChild("/clearBrowserData");r.CLEAR_BROWSER_DATA.isNavigableDialog=true;if(pageVisibility.privacy!==false){r.PRIVACY=r.ADVANCED.createSection("/privacy","privacy");r.CERTIFICATES=r.PRIVACY.createChild("/certificates");r.SITE_SETTINGS=r.PRIVACY.createChild("/content")}if(loadTimeData.getBoolean("enableSiteSettings")){r.SITE_SETTINGS_ALL=r.SITE_SETTINGS.createChild("all");r.SITE_SETTINGS_SITE_DETAILS=r.SITE_SETTINGS_ALL.createChild("/content/siteDetails")}else{r.SITE_SETTINGS_SITE_DETAILS=r.SITE_SETTINGS.createChild("/content/siteDetails")}r.SITE_SETTINGS_HANDLERS=r.SITE_SETTINGS.createChild("/handlers");r.SITE_SETTINGS_ADS=r.SITE_SETTINGS.createChild("ads");r.SITE_SETTINGS_AUTOMATIC_DOWNLOADS=r.SITE_SETTINGS.createChild("automaticDownloads");r.SITE_SETTINGS_BACKGROUND_SYNC=r.SITE_SETTINGS.createChild("backgroundSync");r.SITE_SETTINGS_CAMERA=r.SITE_SETTINGS.createChild("camera");r.SITE_SETTINGS_CLIPBOARD=r.SITE_SETTINGS.createChild("clipboard");r.SITE_SETTINGS_COOKIES=r.SITE_SETTINGS.createChild("cookies");r.SITE_SETTINGS_SITE_DATA=r.SITE_SETTINGS_COOKIES.createChild("/siteData");r.SITE_SETTINGS_DATA_DETAILS=r.SITE_SETTINGS_SITE_DATA.createChild("/cookies/detail");r.SITE_SETTINGS_IMAGES=r.SITE_SETTINGS.createChild("images");r.SITE_SETTINGS_JAVASCRIPT=r.SITE_SETTINGS.createChild("javascript");r.SITE_SETTINGS_SOUND=r.SITE_SETTINGS.createChild("sound");r.SITE_SETTINGS_SENSORS=r.SITE_SETTINGS.createChild("sensors");r.SITE_SETTINGS_LOCATION=r.SITE_SETTINGS.createChild("location");r.SITE_SETTINGS_MICROPHONE=r.SITE_SETTINGS.createChild("microphone");r.SITE_SETTINGS_NOTIFICATIONS=r.SITE_SETTINGS.createChild("notifications");r.SITE_SETTINGS_FLASH=r.SITE_SETTINGS.createChild("flash");r.SITE_SETTINGS_POPUPS=r.SITE_SETTINGS.createChild("popups");r.SITE_SETTINGS_UNSANDBOXED_PLUGINS=r.SITE_SETTINGS.createChild("unsandboxedPlugins");r.SITE_SETTINGS_MIDI_DEVICES=r.SITE_SETTINGS.createChild("midiDevices");r.SITE_SETTINGS_USB_DEVICES=r.SITE_SETTINGS.createChild("usbDevices");r.SITE_SETTINGS_ZOOM_LEVELS=r.SITE_SETTINGS.createChild("zoomLevels");r.SITE_SETTINGS_PDF_DOCUMENTS=r.SITE_SETTINGS.createChild("pdfDocuments");r.SITE_SETTINGS_PROTECTED_CONTENT=r.SITE_SETTINGS.createChild("protectedContent");if(loadTimeData.getBoolean("enablePaymentHandlerContentSetting")){r.SITE_SETTINGS_PAYMENT_HANDLER=r.SITE_SETTINGS.createChild("paymentHandler")}if(pageVisibility.passwordsAndForms!==false){r.PASSWORDS=r.ADVANCED.createSection("/passwordsAndForms","passwordsAndForms");r.AUTOFILL=r.PASSWORDS.createChild("/autofill");r.MANAGE_PASSWORDS=r.PASSWORDS.createChild("/passwords")}r.LANGUAGES=r.ADVANCED.createSection("/languages","languages");r.EDIT_DICTIONARY=r.LANGUAGES.createChild("/editDictionary");if(pageVisibility.downloads!==false){r.DOWNLOADS=r.ADVANCED.createSection("/downloads","downloads")}r.PRINTING=r.ADVANCED.createSection("/printing","printing");r.CLOUD_PRINTERS=r.PRINTING.createChild("/cloudPrinters");r.ACCESSIBILITY=r.ADVANCED.createSection("/accessibility","a11y");r.SYSTEM=r.ADVANCED.createSection("/system","system");if(pageVisibility.reset!==false){r.RESET=r.ADVANCED.createSection("/reset","reset");r.RESET_DIALOG=r.ADVANCED.createChild("/resetProfileSettings");r.RESET_DIALOG.isNavigableDialog=true;r.TRIGGERED_RESET_DIALOG=r.ADVANCED.createChild("/triggeredResetProfileSettings");r.TRIGGERED_RESET_DIALOG.isNavigableDialog=true}}return r};class Router{constructor(){this.routes_=computeAvailableRoutes();this.currentRoute=this.routes_.BASIC;this.currentQueryParameters_=new URLSearchParams;this.wasLastRouteChangePopstate_=false;this.initializeRouteFromUrlCalled_=false}getRoute(routeName){return this.routes_[routeName]}getRoutes(){return this.routes_}setCurrentRoute(route,queryParameters,isPopstate){this.recordMetrics(route.path);const oldRoute=this.currentRoute;this.currentRoute=route;this.currentQueryParameters_=queryParameters;this.wasLastRouteChangePopstate_=isPopstate;new Set(routeObservers).forEach(observer=>{observer.currentRouteChanged(this.currentRoute,oldRoute)})}getCurrentRoute(){return this.currentRoute}getQueryParameters(){return new URLSearchParams(this.currentQueryParameters_)}lastRouteChangeWasPopstate(){return this.wasLastRouteChangePopstate_}getRouteForPath(path){const canonicalPath=path.replace(CANONICAL_PATH_REGEX,"$1$2");const matchingKey=Object.keys(this.routes_).find(key=>this.routes_[key].path==canonicalPath);return!!matchingKey?this.routes_[matchingKey]:null}navigateTo(route,opt_dynamicParameters,opt_removeSearch){if(route==this.routes_.ADVANCED)route=this.routes_.BASIC;const params=opt_dynamicParameters||new URLSearchParams;const removeSearch=!!opt_removeSearch;const oldSearchParam=this.getQueryParameters().get("search")||"";const newSearchParam=params.get("search")||"";if(!removeSearch&&oldSearchParam&&!newSearchParam)params.append("search",oldSearchParam);let url=route.path;const queryString=params.toString();if(queryString)url+="?"+queryString;window.history.pushState(this.currentRoute.path,"",url);this.setCurrentRoute(route,params,false)}navigateToPreviousRoute(){const previousRoute=window.history.state&&assert(this.getRouteForPath(window.history.state));if(previousRoute&&previousRoute.depth<=this.currentRoute.depth)window.history.back();else this.navigateTo(this.currentRoute.parent||this.routes_.BASIC)}initializeRouteFromUrl(){this.recordMetrics(window.location.pathname);assert(!this.initializeRouteFromUrlCalled_);this.initializeRouteFromUrlCalled_=true;const route=this.getRouteForPath(window.location.pathname);if(route&&route!=this.routes_.ADVANCED){this.currentRoute=route;this.currentQueryParameters_=new URLSearchParams(window.location.search)}else{window.history.replaceState(undefined,"",this.routes_.BASIC.path)}}recordMetrics(urlPath){assert(!urlPath.startsWith("chrome://"));assert(!urlPath.startsWith("settings"));assert(urlPath.startsWith("/"));chrome.metricsPrivate.recordSparseHashable("WebUI.Settings.PathVisited",urlPath)}resetRouteForTesting(){this.initializeRouteFromUrlCalled_=false;this.wasLastRouteChangePopstate_=false;this.currentRoute=this.routes_.BASIC;this.currentQueryParameters_=new URLSearchParams}}const routerInstance=new Router;const routeObservers=new Set;const RouteObserverBehavior={attached:function(){assert(!routeObservers.has(this));routeObservers.add(this);this.currentRouteChanged(routerInstance.currentRoute,undefined)},detached:function(){assert(routeObservers.delete(this))},currentRouteChanged:function(opt_newRoute,opt_oldRoute){assertNotReached()}};const CANONICAL_PATH_REGEX=/(^\/)([\/-\w]+)(\/$)/;window.addEventListener("popstate",function(event){routerInstance.setCurrentRoute(routerInstance.getRouteForPath(window.location.pathname)||routerInstance.getRoutes().BASIC,new URLSearchParams(window.location.search),true)});const routes=routerInstance.getRoutes();const getCurrentRoute=routerInstance.getCurrentRoute.bind(routerInstance);const getRouteForPath=routerInstance.getRouteForPath.bind(routerInstance);const initializeRouteFromUrl=routerInstance.initializeRouteFromUrl.bind(routerInstance);const resetRouteForTesting=routerInstance.resetRouteForTesting.bind(routerInstance);const getQueryParameters=routerInstance.getQueryParameters.bind(routerInstance);const lastRouteChangeWasPopstate=routerInstance.lastRouteChangeWasPopstate.bind(routerInstance);const navigateTo=routerInstance.navigateTo.bind(routerInstance);const navigateToPreviousRoute=routerInstance.navigateToPreviousRoute.bind(routerInstance);return{Route:Route,Router:Router,router:routerInstance,routes:routes,RouteObserverBehavior:RouteObserverBehavior,getRouteForPath:getRouteForPath,initializeRouteFromUrl:initializeRouteFromUrl,resetRouteForTesting:resetRouteForTesting,getCurrentRoute:getCurrentRoute,getQueryParameters:getQueryParameters,lastRouteChangeWasPopstate:lastRouteChangeWasPopstate,navigateTo:navigateTo,navigateToPreviousRoute:navigateToPreviousRoute}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.define("settings",function(){const scrollTargetResolver=new PromiseResolver;const GlobalScrollTargetBehaviorImpl={properties:{scrollTarget:{type:Object,readOnly:true},subpageScrollTarget:{type:Object,computed:"getActiveTarget_(scrollTarget, active_)"},subpageRoute:Object,active_:Boolean},attached:function(){scrollTargetResolver.promise.then(this._setScrollTarget.bind(this))},currentRouteChanged:function(route){this.active_=route==this.subpageRoute},getActiveTarget_:function(target,active){return active?target:null}};const setGlobalScrollTarget=function(scrollTarget){scrollTargetResolver.resolve(scrollTarget)};return{GlobalScrollTargetBehaviorImpl:GlobalScrollTargetBehaviorImpl,setGlobalScrollTarget:setGlobalScrollTarget,scrollTargetResolver:scrollTargetResolver}});settings.GlobalScrollTargetBehavior=[settings.RouteObserverBehavior,settings.GlobalScrollTargetBehaviorImpl];
|
|
// Copyright 2018 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.define("cr.search_highlight_utils",function(){const WRAPPER_CSS_CLASS="search-highlight-wrapper";const ORIGINAL_CONTENT_CSS_CLASS="search-highlight-original-content";const HIT_CSS_CLASS="search-highlight-hit";const SEARCH_BUBBLE_CSS_CLASS="search-bubble";function highlight(node,tokens){const wrapper=document.createElement("span");wrapper.classList.add(WRAPPER_CSS_CLASS);node.parentNode.replaceChild(wrapper,node);const span=document.createElement("span");span.classList.add(ORIGINAL_CONTENT_CSS_CLASS);span.style.display="none";span.appendChild(node);wrapper.appendChild(span);for(let i=0;i<tokens.length;++i){if(i%2==0){wrapper.appendChild(document.createTextNode(tokens[i]))}else{const hitSpan=document.createElement("span");hitSpan.classList.add(HIT_CSS_CLASS);hitSpan.style.backgroundColor="#ffeb3b";hitSpan.textContent=tokens[i];wrapper.appendChild(hitSpan)}}}function findAndRemoveHighlights(node){const wrappers=node.querySelectorAll(`* /deep/ .${WRAPPER_CSS_CLASS}`);for(let i=0;i<wrappers.length;i++){const wrapper=wrappers[i];const textNode=wrapper.querySelector(`.${ORIGINAL_CONTENT_CSS_CLASS}`).firstChild;wrapper.parentElement.replaceChild(textNode,wrapper)}}function findAndRemoveBubbles(node){const searchBubbles=node.querySelectorAll(`* /deep/ .${SEARCH_BUBBLE_CSS_CLASS}`);for(let bubble of searchBubbles)bubble.remove()}function highlightControlWithBubble(element,rawQuery){let searchBubble=element.querySelector(`.${SEARCH_BUBBLE_CSS_CLASS}`);if(searchBubble)return;searchBubble=document.createElement("div");searchBubble.classList.add(SEARCH_BUBBLE_CSS_CLASS);const innards=document.createElement("div");innards.classList.add("search-bubble-innards");innards.textContent=rawQuery;searchBubble.appendChild(innards);element.appendChild(searchBubble);const updatePosition=function(){searchBubble.style.top=element.offsetTop+(innards.classList.contains("above")?-searchBubble.offsetHeight:element.offsetHeight)+"px"};updatePosition();searchBubble.addEventListener("mouseover",function(){innards.classList.toggle("above");updatePosition()})}return{highlight:highlight,highlightControlWithBubble:highlightControlWithBubble,findAndRemoveBubbles:findAndRemoveBubbles,findAndRemoveHighlights:findAndRemoveHighlights}});(function(){"use strict";Polymer.IronA11yAnnouncer=Polymer({is:"iron-a11y-announcer",properties:{mode:{type:String,value:"polite"},_text:{type:String,value:""}},created:function(){if(!Polymer.IronA11yAnnouncer.instance){Polymer.IronA11yAnnouncer.instance=this}document.body.addEventListener("iron-announce",this._onIronAnnounce.bind(this))},announce:function(text){this._text="";this.async(function(){this._text=text},100)},_onIronAnnounce:function(event){if(event.detail&&event.detail.text){this.announce(event.detail.text)}}});Polymer.IronA11yAnnouncer.instance=null;Polymer.IronA11yAnnouncer.requestAvailability=function(){if(!Polymer.IronA11yAnnouncer.instance){Polymer.IronA11yAnnouncer.instance=document.createElement("iron-a11y-announcer")}document.body.appendChild(Polymer.IronA11yAnnouncer.instance)}})();Polymer.PaperButtonBehaviorImpl={properties:{elevation:{type:Number,reflectToAttribute:true,readOnly:true}},observers:["_calculateElevation(focused, disabled, active, pressed, receivedFocusFromKeyboard)","_computeKeyboardClass(receivedFocusFromKeyboard)"],hostAttributes:{role:"button",tabindex:"0",animated:true},_calculateElevation:function(){var e=1;if(this.disabled){e=0}else if(this.active||this.pressed){e=4}else if(this.receivedFocusFromKeyboard){e=3}this._setElevation(e)},_computeKeyboardClass:function(receivedFocusFromKeyboard){this.toggleClass("keyboard-focus",receivedFocusFromKeyboard)},_spaceKeyDownHandler:function(event){Polymer.IronButtonStateImpl._spaceKeyDownHandler.call(this,event);if(this.hasRipple()&&this.getRipple().ripples.length<1){this._ripple.uiDownAction()}},_spaceKeyUpHandler:function(event){Polymer.IronButtonStateImpl._spaceKeyUpHandler.call(this,event);if(this.hasRipple()){this._ripple.uiUpAction()}}};Polymer.PaperButtonBehavior=[Polymer.IronButtonState,Polymer.IronControlState,Polymer.PaperRippleBehavior,Polymer.PaperButtonBehaviorImpl];Polymer({is:"paper-button",behaviors:[Polymer.PaperButtonBehavior],properties:{raised:{type:Boolean,reflectToAttribute:true,value:false,observer:"_calculateElevation"}},_calculateElevation:function(){if(!this.raised){this._setElevation(0)}else{Polymer.PaperButtonBehaviorImpl._calculateElevation.apply(this)}}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
const UpdateStatus={CHECKING:"checking",UPDATING:"updating",NEARLY_UPDATED:"nearly_updated",UPDATED:"updated",FAILED:"failed",DISABLED:"disabled",DISABLED_BY_ADMIN:"disabled_by_admin",NEED_PERMISSION_TO_UPDATE:"need_permission_to_update"};let UpdateStatusChangedEvent;cr.define("settings",function(){function browserChannelToI18nId(channel){switch(channel){case BrowserChannel.BETA:return"aboutChannelBeta";case BrowserChannel.CANARY:return"aboutChannelCanary";case BrowserChannel.DEV:return"aboutChannelDev";case BrowserChannel.STABLE:return"aboutChannelStable"}assertNotReached()}function isTargetChannelMoreStable(currentChannel,targetChannel){const channelList=[BrowserChannel.CANARY,BrowserChannel.DEV,BrowserChannel.BETA,BrowserChannel.STABLE];const currentIndex=channelList.indexOf(currentChannel);const targetIndex=channelList.indexOf(targetChannel);return currentIndex<targetIndex}class AboutPageBrowserProxy{pageReady(){}refreshUpdateStatus(){}openHelpPage(){}}class AboutPageBrowserProxyImpl{pageReady(){chrome.send("aboutPageReady")}refreshUpdateStatus(){chrome.send("refreshUpdateStatus")}openHelpPage(){chrome.send("openHelpPage")}}cr.addSingletonGetter(AboutPageBrowserProxyImpl);return{AboutPageBrowserProxy:AboutPageBrowserProxy,AboutPageBrowserProxyImpl:AboutPageBrowserProxyImpl,browserChannelToI18nId:browserChannelToI18nId,isTargetChannelMoreStable:isTargetChannelMoreStable}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.define("settings",function(){class LifetimeBrowserProxy{restart(){}relaunch(){}}class LifetimeBrowserProxyImpl{restart(){chrome.send("restart")}relaunch(){chrome.send("relaunch")}}cr.addSingletonGetter(LifetimeBrowserProxyImpl);return{LifetimeBrowserProxy:LifetimeBrowserProxy,LifetimeBrowserProxyImpl:LifetimeBrowserProxyImpl}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
const MainPageBehaviorImpl={properties:{isSubpageAnimating:{reflectToAttribute:true,type:Boolean},inSearchMode:{type:Boolean,value:false,observer:"inSearchModeChanged_"}},scroller:null,listeners:{"neon-animation-finish":"onNeonAnimationFinish_"},attached:function(){this.scroller=this.domHost?this.domHost.parentNode:document.body},onNeonAnimationFinish_:function(){this.isSubpageAnimating=false},currentRouteChanged:function(newRoute,oldRoute){const oldRouteWasSection=!!oldRoute&&!!oldRoute.parent&&!!oldRoute.section&&oldRoute.parent.section!=oldRoute.section;if(this.scroller){if(oldRouteWasSection&&newRoute==settings.routes.BASIC){this.scroller.scrollTop=0;return}if(newRoute==settings.routes.ABOUT)this.scroller.scrollTop=0}const scrollToSection=!settings.lastRouteChangeWasPopstate()||oldRouteWasSection||oldRoute==settings.routes.BASIC||oldRoute==settings.routes.ABOUT;if(oldRoute&&oldRoute.isSubpage()&&newRoute.isSubpage())this.isSubpageAnimating=true;if(!oldRoute){this.fire("hide-container");setTimeout(()=>{this.fire("show-container");this.tryTransitionToSection_(scrollToSection,true)})}else if(this.scrollHeight==0){setTimeout(this.tryTransitionToSection_.bind(this,scrollToSection))}else{this.tryTransitionToSection_(scrollToSection)}},inSearchModeChanged_:function(inSearchMode){if(!this.isAttached)return;if(!inSearchMode)this.tryTransitionToSection_(!settings.lastRouteChangeWasPopstate())},tryTransitionToSection_:function(scrollToSection,immediate){const currentRoute=settings.getCurrentRoute();const currentSection=this.getSection(currentRoute.section);if(this.currentAnimation_){this.maybeStopCurrentAnimation_();return}let promise;const expandedSection=this.$$("settings-section.expanded");if(expandedSection){if(!currentRoute.isSubpage()||expandedSection!=currentSection){promise=this.collapseSection_(expandedSection)}else{this.scroller.scrollTop=0}}else if(currentSection){if(currentRoute.isSubpage()){if(immediate)this.expandSectionImmediate_(currentSection);else promise=this.expandSection_(currentSection)}else if(scrollToSection){currentSection.scrollIntoView()}}else if(this.tagName=="SETTINGS-BASIC-PAGE"&&settings.routes.ADVANCED&&settings.routes.ADVANCED.contains(currentRoute)&&!currentRoute.isNavigableDialog){assert(currentRoute.section);this.fire("hide-container");promise=this.$$("#advancedPageTemplate").get()}if(promise){promise.then(this.tryTransitionToSection_.bind(this,scrollToSection)).then(()=>{this.fire("show-container")})}},maybeStopCurrentAnimation_:function(){const currentRoute=settings.getCurrentRoute();const animatingSection=this.$$("settings-section.expanding, settings-section.collapsing");assert(animatingSection);if(animatingSection.classList.contains("expanding")){if(animatingSection.section!=currentRoute.section||!currentRoute.isSubpage()){this.currentAnimation_.cancel()}return}assert(animatingSection.classList.contains("collapsing"));if(!currentRoute.isSubpage())return;if(animatingSection.section==currentRoute.section){this.currentAnimation_.cancel();return}this.currentAnimation_.finish()},expandSectionImmediate_:function(section){assert(this.scroller);section.immediateExpand(this.scroller);this.finishedExpanding_(section);this.fire("resize")},expandSection_:function(section){assert(this.scroller);if(!section.canAnimateExpand()){return new Promise(function(resolve,reject){setTimeout(resolve)})}this.origScrollTop_=this.scroller.scrollTop;this.fire("freeze-scroll",true);section.setFrozen(true);this.currentAnimation_=section.animateExpand(this.scroller);return this.currentAnimation_.finished.then(()=>{this.finishedExpanding_(section)},()=>{section.setFrozen(false);this.scroller.scrollTop=this.origScrollTop_}).then(()=>{this.fire("freeze-scroll",false);this.currentAnimation_=null})},finishedExpanding_:function(section){this.classList.add("showing-subpage");this.toggleOtherSectionsHidden_(section.section,true);this.scroller.scrollTop=0;section.setFrozen(false);this.fire("subpage-expand")},collapseSection_:function(section){assert(this.scroller);assert(section.classList.contains("expanded"));const needAnimate=settings.routes.ABOUT.contains(settings.getCurrentRoute())==(section.domHost.tagName=="SETTINGS-ABOUT-PAGE");const shouldAnimateCollapse=needAnimate&§ion.canAnimateCollapse();if(shouldAnimateCollapse){this.fire("freeze-scroll",true);section.setUpAnimateCollapse(this.scroller)}else{section.classList.remove("expanded")}this.toggleOtherSectionsHidden_(section.section,false);this.classList.remove("showing-subpage");if(!shouldAnimateCollapse){section.setFrozen(false);return Promise.resolve()}return new Promise((resolve,reject)=>{setTimeout(()=>{const newSection=settings.getCurrentRoute().section&&this.getSection(settings.getCurrentRoute().section);if(newSection&&!settings.lastRouteChangeWasPopstate()&&!settings.getCurrentRoute().isSubpage()){newSection.scrollIntoView()}else{this.scroller.scrollTop=this.origScrollTop_}this.currentAnimation_=section.animateCollapse(this.scroller);this.currentAnimation_.finished.catch(()=>{this.fire("subpage-expand")}).then(()=>{section.setFrozen(false);section.classList.remove("collapsing");this.fire("freeze-scroll",false);this.currentAnimation_=null;resolve()})})})},toggleOtherSectionsHidden_:function(sectionName,hidden){const sections=Polymer.dom(this.root).querySelectorAll("settings-section");for(let i=0;i<sections.length;i++)sections[i].hidden=hidden&§ions[i].section!=sectionName},getSection:function(section){if(!section)return null;return this.$$('settings-section[section="'+section+'"]')}};const MainPageBehavior=[settings.RouteObserverBehavior,MainPageBehaviorImpl];
|
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.define("cr.ui",function(){function decorate(source,constr){var elements;if(typeof source=="string")elements=cr.doc.querySelectorAll(source);else elements=[source];for(var i=0,el;el=elements[i];i++){if(!(el instanceof constr))constr.decorate(el)}}function createElementHelper(tagName,opt_bag){var doc;if(opt_bag&&opt_bag.ownerDocument)doc=opt_bag.ownerDocument;else doc=cr.doc;return doc.createElement(tagName)}function define(tagNameOrFunction){var createFunction,tagName;if(typeof tagNameOrFunction=="function"){createFunction=tagNameOrFunction;tagName=""}else{createFunction=createElementHelper;tagName=tagNameOrFunction}function f(opt_propertyBag){var el=createFunction(tagName,opt_propertyBag);f.decorate(el);for(var propertyName in opt_propertyBag){el[propertyName]=opt_propertyBag[propertyName]}return el}f.decorate=function(el){el.__proto__=f.prototype;el.decorate()};return f}function limitInputWidth(el,parentEl,min,opt_scale){el.style.width="10px";var doc=el.ownerDocument;var win=doc.defaultView;var computedStyle=win.getComputedStyle(el);var parentComputedStyle=win.getComputedStyle(parentEl);var rtl=computedStyle.direction=="rtl";var inputRect=el.getBoundingClientRect();var parentRect=parentEl.getBoundingClientRect();var startPos=rtl?parentRect.right-inputRect.right:inputRect.left-parentRect.left;var inner=parseInt(computedStyle.borderLeftWidth,10)+parseInt(computedStyle.paddingLeft,10)+parseInt(computedStyle.paddingRight,10)+parseInt(computedStyle.borderRightWidth,10);var parentPadding=rtl?parseInt(parentComputedStyle.paddingLeft,10):parseInt(parentComputedStyle.paddingRight,10);var max=parentEl.clientWidth-startPos-inner-parentPadding;if(opt_scale)max*=opt_scale;function limit(){if(el.scrollWidth>max){el.style.width=max+"px"}else{el.style.width=0;var sw=el.scrollWidth;if(sw<min){el.style.width=min+"px"}else{el.style.width=sw+"px"}}}el.addEventListener("input",limit);limit()}function toCssPx(pixels){if(!window.isFinite(pixels))console.error("Pixel value is not a number: "+pixels);return Math.round(pixels)+"px"}function swallowDoubleClick(e){var doc=e.target.ownerDocument;var counter=Math.min(1,e.detail);function swallow(e){e.stopPropagation();e.preventDefault()}function onclick(e){if(e.detail>counter){counter=e.detail;swallow(e)}else{doc.removeEventListener("dblclick",swallow,true);doc.removeEventListener("click",onclick,true)}}setTimeout(function(){doc.addEventListener("click",onclick,true);doc.addEventListener("dblclick",swallow,true)},0)}return{decorate:decorate,define:define,limitInputWidth:limitInputWidth,toCssPx:toCssPx,swallowDoubleClick:swallowDoubleClick}});
|
|
// Copyright 2017 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.define("cr.ui",function(){if(cr.ui.focusWithoutInk)return;var hideInk=false;assert(!cr.isIOS,"pointerdown doesn't work on iOS");document.addEventListener("pointerdown",function(){hideInk=true},true);document.addEventListener("keydown",function(){hideInk=false},true);var focusWithoutInk=function(toFocus){var innerButton=null;if(toFocus.parentElement.tagName=="PAPER-ICON-BUTTON-LIGHT"){innerButton=toFocus;toFocus=toFocus.parentElement}if(!("noink"in toFocus)){toFocus.focus();return}assert(document==toFocus.ownerDocument);var origNoInk;if(hideInk){origNoInk=toFocus.noink;toFocus.noink=true}if(innerButton)innerButton.focus();else toFocus.focus();if(hideInk)toFocus.noink=origNoInk};return{focusWithoutInk:focusWithoutInk}});Polymer.NeonAnimationBehavior={properties:{animationTiming:{type:Object,value:function(){return{duration:500,easing:"cubic-bezier(0.4, 0, 0.2, 1)",fill:"both"}}}},isNeonAnimation:true,created:function(){if(!document.body.animate){console.warn("No web animations detected. This element will not"+" function without a web animations polyfill.")}},timingFromConfig:function(config){if(config.timing){for(var property in config.timing){this.animationTiming[property]=config.timing[property]}}return this.animationTiming},setPrefixedProperty:function(node,property,value){var map={transform:["webkitTransform"],transformOrigin:["mozTransformOrigin","webkitTransformOrigin"]};var prefixes=map[property];for(var prefix,index=0;prefix=prefixes[index];index++){node.style[prefix]=value}node.style[property]=value},complete:function(){}};Polymer({is:"slide-from-left-animation",behaviors:[Polymer.NeonAnimationBehavior],configure:function(config){var node=config.node;this._effect=new KeyframeEffect(node,[{transform:"translateX(-100%)"},{transform:"none"}],this.timingFromConfig(config));if(config.transformOrigin){this.setPrefixedProperty(node,"transformOrigin",config.transformOrigin)}else{this.setPrefixedProperty(node,"transformOrigin","0 50%")}return this._effect}});Polymer({is:"slide-from-right-animation",behaviors:[Polymer.NeonAnimationBehavior],configure:function(config){var node=config.node;this._effect=new KeyframeEffect(node,[{transform:"translateX(100%)"},{transform:"none"}],this.timingFromConfig(config));if(config.transformOrigin){this.setPrefixedProperty(node,"transformOrigin",config.transformOrigin)}else{this.setPrefixedProperty(node,"transformOrigin","0 50%")}return this._effect}});Polymer({is:"slide-left-animation",behaviors:[Polymer.NeonAnimationBehavior],configure:function(config){var node=config.node;this._effect=new KeyframeEffect(node,[{transform:"none"},{transform:"translateX(-100%)"}],this.timingFromConfig(config));if(config.transformOrigin){this.setPrefixedProperty(node,"transformOrigin",config.transformOrigin)}else{this.setPrefixedProperty(node,"transformOrigin","0 50%")}return this._effect}});Polymer({is:"slide-right-animation",behaviors:[Polymer.NeonAnimationBehavior],configure:function(config){var node=config.node;this._effect=new KeyframeEffect(node,[{transform:"none"},{transform:"translateX(100%)"}],this.timingFromConfig(config));if(config.transformOrigin){this.setPrefixedProperty(node,"transformOrigin",config.transformOrigin)}else{this.setPrefixedProperty(node,"transformOrigin","0 50%")}return this._effect}});Polymer.IronResizableBehavior={properties:{_parentResizable:{type:Object,observer:"_parentResizableChanged"},_notifyingDescendant:{type:Boolean,value:false}},listeners:{"iron-request-resize-notifications":"_onIronRequestResizeNotifications"},created:function(){this._interestedResizables=[];this._boundNotifyResize=this.notifyResize.bind(this)},attached:function(){this._requestResizeNotifications()},detached:function(){if(this._parentResizable){this._parentResizable.stopResizeNotificationsFor(this)}else{window.removeEventListener("resize",this._boundNotifyResize)}this._parentResizable=null},notifyResize:function(){if(!this.isAttached){return}this._interestedResizables.forEach(function(resizable){if(this.resizerShouldNotify(resizable)){this._notifyDescendant(resizable)}},this);this._fireResize()},assignParentResizable:function(parentResizable){this._parentResizable=parentResizable},stopResizeNotificationsFor:function(target){var index=this._interestedResizables.indexOf(target);if(index>-1){this._interestedResizables.splice(index,1);this.unlisten(target,"iron-resize","_onDescendantIronResize")}},resizerShouldNotify:function(element){return true},_onDescendantIronResize:function(event){if(this._notifyingDescendant){event.stopPropagation();return}if(!Polymer.Settings.useShadow){this._fireResize()}},_fireResize:function(){this.fire("iron-resize",null,{node:this,bubbles:false})},_onIronRequestResizeNotifications:function(event){var target=Polymer.dom(event).rootTarget;if(target===this){return}if(this._interestedResizables.indexOf(target)===-1){this._interestedResizables.push(target);this.listen(target,"iron-resize","_onDescendantIronResize")}target.assignParentResizable(this);this._notifyDescendant(target);event.stopPropagation()},_parentResizableChanged:function(parentResizable){if(parentResizable){window.removeEventListener("resize",this._boundNotifyResize)}},_notifyDescendant:function(descendant){if(!this.isAttached){return}this._notifyingDescendant=true;descendant.notifyResize();this._notifyingDescendant=false},_requestResizeNotifications:function(){if(!this.isAttached)return;if(document.readyState==="loading"){var _requestResizeNotifications=this._requestResizeNotifications.bind(this);document.addEventListener("readystatechange",function readystatechanged(){document.removeEventListener("readystatechange",readystatechanged);_requestResizeNotifications()})}else{this.fire("iron-request-resize-notifications",null,{node:this,bubbles:true,cancelable:true});if(!this._parentResizable){window.addEventListener("resize",this._boundNotifyResize);this.notifyResize()}}}};Polymer.NeonAnimatableBehavior={properties:{animationConfig:{type:Object},entryAnimation:{observer:"_entryAnimationChanged",type:String},exitAnimation:{observer:"_exitAnimationChanged",type:String}},_entryAnimationChanged:function(){this.animationConfig=this.animationConfig||{};this.animationConfig["entry"]=[{name:this.entryAnimation,node:this}]},_exitAnimationChanged:function(){this.animationConfig=this.animationConfig||{};this.animationConfig["exit"]=[{name:this.exitAnimation,node:this}]},_copyProperties:function(config1,config2){for(var property in config2){config1[property]=config2[property]}},_cloneConfig:function(config){var clone={isClone:true};this._copyProperties(clone,config);return clone},_getAnimationConfigRecursive:function(type,map,allConfigs){if(!this.animationConfig){return}if(this.animationConfig.value&&typeof this.animationConfig.value==="function"){this._warn(this._logf("playAnimation","Please put 'animationConfig' inside of your components 'properties' object instead of outside of it."));return}var thisConfig;if(type){thisConfig=this.animationConfig[type]}else{thisConfig=this.animationConfig}if(!Array.isArray(thisConfig)){thisConfig=[thisConfig]}if(thisConfig){for(var config,index=0;config=thisConfig[index];index++){if(config.animatable){config.animatable._getAnimationConfigRecursive(config.type||type,map,allConfigs)}else{if(config.id){var cachedConfig=map[config.id];if(cachedConfig){if(!cachedConfig.isClone){map[config.id]=this._cloneConfig(cachedConfig);cachedConfig=map[config.id]}this._copyProperties(cachedConfig,config)}else{map[config.id]=config}}else{allConfigs.push(config)}}}}},getAnimationConfig:function(type){var map={};var allConfigs=[];this._getAnimationConfigRecursive(type,map,allConfigs);for(var key in map){allConfigs.push(map[key])}return allConfigs}};Polymer({is:"neon-animatable",behaviors:[Polymer.NeonAnimatableBehavior,Polymer.IronResizableBehavior]});Polymer.IronSelection=function(selectCallback){this.selection=[];this.selectCallback=selectCallback};Polymer.IronSelection.prototype={get:function(){return this.multi?this.selection.slice():this.selection[0]},clear:function(excludes){this.selection.slice().forEach(function(item){if(!excludes||excludes.indexOf(item)<0){this.setItemSelected(item,false)}},this)},isSelected:function(item){return this.selection.indexOf(item)>=0},setItemSelected:function(item,isSelected){if(item!=null){if(isSelected!==this.isSelected(item)){if(isSelected){this.selection.push(item)}else{var i=this.selection.indexOf(item);if(i>=0){this.selection.splice(i,1)}}if(this.selectCallback){this.selectCallback(item,isSelected)}}}},select:function(item){if(this.multi){this.toggle(item)}else if(this.get()!==item){this.setItemSelected(this.get(),false);this.setItemSelected(item,true)}},toggle:function(item){this.setItemSelected(item,!this.isSelected(item))}};Polymer.IronSelectableBehavior={properties:{attrForSelected:{type:String,value:null},selected:{type:String,notify:true},selectedItem:{type:Object,readOnly:true,notify:true},activateEvent:{type:String,value:"tap",observer:"_activateEventChanged"},selectable:String,selectedClass:{type:String,value:"iron-selected"},selectedAttribute:{type:String,value:null},fallbackSelection:{type:String,value:null},items:{type:Array,readOnly:true,notify:true,value:function(){return[]}},_excludedLocalNames:{type:Object,value:function(){return{template:1,"dom-bind":1,"dom-if":1,"dom-repeat":1}}}},observers:["_updateAttrForSelected(attrForSelected)","_updateSelected(selected)","_checkFallback(fallbackSelection)"],created:function(){this._bindFilterItem=this._filterItem.bind(this);this._selection=new Polymer.IronSelection(this._applySelection.bind(this))},attached:function(){this._observer=this._observeItems(this);this._addListener(this.activateEvent)},detached:function(){if(this._observer){Polymer.dom(this).unobserveNodes(this._observer)}this._removeListener(this.activateEvent)},indexOf:function(item){return this.items?this.items.indexOf(item):-1},select:function(value){this.selected=value},selectPrevious:function(){var length=this.items.length;var index=(Number(this._valueToIndex(this.selected))-1+length)%length;this.selected=this._indexToValue(index)},selectNext:function(){var index=(Number(this._valueToIndex(this.selected))+1)%this.items.length;this.selected=this._indexToValue(index)},selectIndex:function(index){this.select(this._indexToValue(index))},forceSynchronousItemUpdate:function(){if(this._observer&&typeof this._observer.flush==="function"){this._observer.flush()}else{this._updateItems()}},get _shouldUpdateSelection(){return this.selected!=null},_checkFallback:function(){this._updateSelected()},_addListener:function(eventName){this.listen(this,eventName,"_activateHandler")},_removeListener:function(eventName){this.unlisten(this,eventName,"_activateHandler")},_activateEventChanged:function(eventName,old){this._removeListener(old);this._addListener(eventName)},_updateItems:function(){var nodes=Polymer.dom(this).queryDistributedElements(this.selectable||"*");nodes=Array.prototype.filter.call(nodes,this._bindFilterItem);this._setItems(nodes)},_updateAttrForSelected:function(){if(this.selectedItem){this.selected=this._valueForItem(this.selectedItem)}},_updateSelected:function(){this._selectSelected(this.selected)},_selectSelected:function(selected){if(!this.items){return}var item=this._valueToItem(this.selected);if(item){this._selection.select(item)}else{this._selection.clear()}if(this.fallbackSelection&&this.items.length&&this._selection.get()===undefined){this.selected=this.fallbackSelection}},_filterItem:function(node){return!this._excludedLocalNames[node.localName]},_valueToItem:function(value){return value==null?null:this.items[this._valueToIndex(value)]},_valueToIndex:function(value){if(this.attrForSelected){for(var i=0,item;item=this.items[i];i++){if(this._valueForItem(item)==value){return i}}}else{return Number(value)}},_indexToValue:function(index){if(this.attrForSelected){var item=this.items[index];if(item){return this._valueForItem(item)}}else{return index}},_valueForItem:function(item){if(!item){return null}if(!this.attrForSelected){var i=this.indexOf(item);return i===-1?null:i}var propValue=item[Polymer.CaseMap.dashToCamelCase(this.attrForSelected)];return propValue!=undefined?propValue:item.getAttribute(this.attrForSelected)},_applySelection:function(item,isSelected){if(this.selectedClass){this.toggleClass(this.selectedClass,isSelected,item)}if(this.selectedAttribute){this.toggleAttribute(this.selectedAttribute,isSelected,item)}this._selectionChange();this.fire("iron-"+(isSelected?"select":"deselect"),{item:item})},_selectionChange:function(){this._setSelectedItem(this._selection.get())},_observeItems:function(node){return Polymer.dom(node).observeNodes(function(mutation){this._updateItems();this._updateSelected();this.fire("iron-items-changed",mutation,{bubbles:false,cancelable:false})})},_activateHandler:function(e){var t=e.target;var items=this.items;while(t&&t!=this){var i=items.indexOf(t);if(i>=0){var value=this._indexToValue(i);this._itemActivate(value,t);return}t=t.parentNode}},_itemActivate:function(value,item){if(!this.fire("iron-activate",{selected:value,item:item},{cancelable:true}).defaultPrevented){this.select(value)}}};Polymer.NeonAnimationRunnerBehaviorImpl={_configureAnimations:function(configs){var results=[];var resultsToPlay=[];if(configs.length>0){for(var config,index=0;config=configs[index];index++){var neonAnimation=document.createElement(config.name);if(neonAnimation.isNeonAnimation){var result=null;if(!neonAnimation.configure){neonAnimation.configure=function(config){return null}}result=neonAnimation.configure(config);resultsToPlay.push({result:result,config:config})}else{console.warn(this.is+":",config.name,"not found!")}}}for(var i=0;i<resultsToPlay.length;i++){var result=resultsToPlay[i].result;var config=resultsToPlay[i].config;try{if(typeof result.cancel!="function"){result=document.timeline.play(result)}}catch(e){result=null;console.warn("Couldnt play","(",config.name,").",e)}if(result){results.push({neonAnimation:neonAnimation,config:config,animation:result})}}return results},_shouldComplete:function(activeEntries){var finished=true;for(var i=0;i<activeEntries.length;i++){if(activeEntries[i].animation.playState!="finished"){finished=false;break}}return finished},_complete:function(activeEntries){for(var i=0;i<activeEntries.length;i++){activeEntries[i].neonAnimation.complete(activeEntries[i].config)}for(var i=0;i<activeEntries.length;i++){activeEntries[i].animation.cancel()}},playAnimation:function(type,cookie){var configs=this.getAnimationConfig(type);if(!configs){return}this._active=this._active||{};if(this._active[type]){this._complete(this._active[type]);delete this._active[type]}var activeEntries=this._configureAnimations(configs);if(activeEntries.length==0){this.fire("neon-animation-finish",cookie,{bubbles:false});return}this._active[type]=activeEntries;for(var i=0;i<activeEntries.length;i++){activeEntries[i].animation.onfinish=function(){if(this._shouldComplete(activeEntries)){this._complete(activeEntries);delete this._active[type];this.fire("neon-animation-finish",cookie,{bubbles:false})}}.bind(this)}},cancelAnimation:function(){for(var k in this._active){var entries=this._active[k];for(var j in entries){entries[j].animation.cancel()}}this._active={}}};Polymer.NeonAnimationRunnerBehavior=[Polymer.NeonAnimatableBehavior,Polymer.NeonAnimationRunnerBehaviorImpl];(function(){Polymer({is:"neon-animated-pages",behaviors:[Polymer.IronResizableBehavior,Polymer.IronSelectableBehavior,Polymer.NeonAnimationRunnerBehavior],properties:{activateEvent:{type:String,value:""},animateInitialSelection:{type:Boolean,value:false}},listeners:{"iron-select":"_onIronSelect","neon-animation-finish":"_onNeonAnimationFinish"},_onIronSelect:function(event){var selectedPage=event.detail.item;if(this.items.indexOf(selectedPage)<0){return}var oldPage=this._valueToItem(this._prevSelected)||false;this._prevSelected=this.selected;if(!oldPage&&!this.animateInitialSelection){this._completeSelectedChanged();return}this.animationConfig=[];if(this.entryAnimation){this.animationConfig.push({name:this.entryAnimation,node:selectedPage})}else{if(selectedPage.getAnimationConfig){this.animationConfig.push({animatable:selectedPage,type:"entry"})}}if(oldPage){if(oldPage.classList.contains("neon-animating")){this._squelchNextFinishEvent=true;this.cancelAnimation();this._completeSelectedChanged();this._squelchNextFinishEvent=false}if(this.exitAnimation){this.animationConfig.push({name:this.exitAnimation,node:oldPage})}else{if(oldPage.getAnimationConfig){this.animationConfig.push({animatable:oldPage,type:"exit"})}}oldPage.classList.add("neon-animating")}selectedPage.classList.add("neon-animating");if(this.animationConfig.length>=1){if(!this.isAttached){this.async(function(){this.playAnimation(undefined,{fromPage:null,toPage:selectedPage})})}else{this.playAnimation(undefined,{fromPage:oldPage,toPage:selectedPage})}}else{this._completeSelectedChanged(oldPage,selectedPage)}},_completeSelectedChanged:function(oldPage,selectedPage){if(selectedPage){selectedPage.classList.remove("neon-animating")}if(oldPage){oldPage.classList.remove("neon-animating")}if(!selectedPage||!oldPage){var nodes=Polymer.dom(this.$.content).getDistributedNodes();for(var node,index=0;node=nodes[index];index++){node.classList&&node.classList.remove("neon-animating")}}this.async(this._notifyPageResize)},_onNeonAnimationFinish:function(event){if(this._squelchNextFinishEvent){this._squelchNextFinishEvent=false;return}this._completeSelectedChanged(event.detail.fromPage,event.detail.toPage)},_notifyPageResize:function(){var selectedPage=this.selectedItem||this._valueToItem(this.selected);this.resizerShouldNotify=function(element){return element==selectedPage};this.notifyResize()}})})();
|
|
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
var EventListenerType;cr.define("cr",function(){function EventTarget(){}EventTarget.prototype={addEventListener:function(type,handler){if(!this.listeners_)this.listeners_=Object.create(null);if(!(type in this.listeners_)){this.listeners_[type]=[handler]}else{var handlers=this.listeners_[type];if(handlers.indexOf(handler)<0)handlers.push(handler)}},removeEventListener:function(type,handler){if(!this.listeners_)return;if(type in this.listeners_){var handlers=this.listeners_[type];var index=handlers.indexOf(handler);if(index>=0){if(handlers.length==1)delete this.listeners_[type];else handlers.splice(index,1)}}},dispatchEvent:function(event){if(!this.listeners_)return true;var self=this;event.__defineGetter__("target",function(){return self});var type=event.type;var prevented=0;if(type in this.listeners_){var handlers=this.listeners_[type].concat();for(var i=0,handler;handler=handlers[i];i++){if(handler.handleEvent)prevented|=handler.handleEvent.call(handler,event)===false;else prevented|=handler.call(this,event)===false}}return!prevented&&!event.defaultPrevented}};return{EventTarget:EventTarget}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.define("settings.animation",function(){"use strict";const Timing={DURATION:250,EASING:"cubic-bezier(0.4, 0, 0.2, 1)"};function Animation(el,keyframes,opt_options){this.animation_=el.animate(keyframes,opt_options);const self=this;this.finished=new Promise(function(resolve,reject){self.animation_.addEventListener("finish",function(e){resolve();self.queueDispatch_(e)});self.animation_.addEventListener("cancel",function(e){reject(new DOMException("","AbortError"));self.queueDispatch_(e)})})}Animation.prototype={__proto__:cr.EventTarget.prototype,finish:function(){assert(this.animation_);this.animation_.finish()},cancel:function(){assert(this.animation_);this.animation_.cancel()},queueDispatch_:function(e){setTimeout(()=>{this.dispatchEvent(e);this.animation_=undefined})}};return{Animation:Animation,Timing:Timing}});
|
|
// Copyright 2017 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-fade-in-animation",behaviors:[Polymer.NeonAnimationBehavior],configure:function(config){const node=config.node;this._effect=new KeyframeEffect(node,[{opacity:"0"},{opacity:"1"}],{duration:settings.animation.Timing.DURATION,easing:settings.animation.Timing.EASING,fill:"both"});return this._effect}});Polymer({is:"settings-fade-out-animation",behaviors:[Polymer.NeonAnimationBehavior],configure:function(config){const node=config.node;this._effect=new KeyframeEffect(node,[{opacity:"1"},{opacity:"0"}],{duration:settings.animation.Timing.DURATION,easing:settings.animation.Timing.EASING,fill:"both"});return this._effect}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-animated-pages",behaviors:[settings.RouteObserverBehavior],properties:{section:String,focusConfig:Object},previousRoute_:null,created:function(){this.lightDomObserver_=Polymer.dom(this).observeNodes(this.lightDomChanged_.bind(this))},onIronSelect_:function(e){if(!this.focusConfig||!this.previousRoute_)return;if(!settings.lastRouteChangeWasPopstate()){let subPage=this.querySelector("settings-subpage.iron-selected");if(subPage)subPage.initialFocus();return}let whitelist="settings-subpage#site-settings";if(settings.routes.SITE_SETTINGS_COOKIES){whitelist+=', settings-subpage[route-path="'+settings.routes.SITE_SETTINGS_COOKIES.path+'"]'}if(!e.detail.item.matches("neon-animatable, "+whitelist))return;const selector=this.focusConfig.get(this.previousRoute_.path);if(selector){cr.ui.focusWithoutInk(assert(this.querySelector(selector)))}},lightDomChanged_:function(){if(this.lightDomReady_)return;this.lightDomReady_=true;Polymer.dom(this).unobserveNodes(this.lightDomObserver_);this.runQueuedRouteChange_()},runQueuedRouteChange_:function(){if(!this.queuedRouteChange_)return;this.async(this.currentRouteChanged.bind(this,this.queuedRouteChange_.newRoute,this.queuedRouteChange_.oldRoute))},currentRouteChanged:function(newRoute,oldRoute){this.previousRoute_=oldRoute;if(newRoute.section==this.section&&newRoute.isSubpage()){this.switchToSubpage_(newRoute,oldRoute)}else{this.$.animatedPages.exitAnimation="settings-fade-out-animation";this.$.animatedPages.entryAnimation="settings-fade-in-animation";this.$.animatedPages.selected="default"}},switchToSubpage_:function(newRoute,oldRoute){if(!this.lightDomReady_){this.queuedRouteChange_=this.queuedRouteChange_||{oldRoute:oldRoute};this.queuedRouteChange_.newRoute=newRoute;return}this.ensureSubpageInstance_();if(oldRoute){if(oldRoute.isSubpage()&&newRoute.depth>oldRoute.depth){const isRtl=loadTimeData.getString("textdirection")=="rtl";const exit=isRtl?"right":"left";const entry=isRtl?"left":"right";this.$.animatedPages.exitAnimation="slide-"+exit+"-animation";this.$.animatedPages.entryAnimation="slide-from-"+entry+"-animation"}else if(oldRoute.depth>newRoute.depth){const isRtl=loadTimeData.getString("textdirection")=="rtl";const exit=isRtl?"left":"right";const entry=isRtl?"right":"left";this.$.animatedPages.exitAnimation="slide-"+exit+"-animation";this.$.animatedPages.entryAnimation="slide-from-"+entry+"-animation"}else{this.$.animatedPages.exitAnimation="settings-fade-out-animation";this.$.animatedPages.entryAnimation="settings-fade-in-animation";if(!oldRoute.isSubpage()){this.style.height=this.clientHeight+"px";this.async(function(){this.style.height=""})}}}this.$.animatedPages.selected=newRoute.path},ensureSubpageInstance_:function(){const routePath=settings.getCurrentRoute().path;const template=Polymer.dom(this).querySelector('template[route-path="'+routePath+'"]');if(!template||template.if)return;const subpage=template._content.querySelector("settings-subpage");subpage.setAttribute("route-path",routePath);if(template.hasAttribute("no-search"))subpage.setAttribute("no-search","");template.if=true;template.render()}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
let SettingsSectionElement=Polymer({is:"settings-section",properties:{section:String,pageTitle:{type:String,value:""},hiddenBySearch:{type:Boolean,value:false,reflectToAttribute:true},collapsedHeight_:{type:Number,value:NaN}},setFrozen:function(frozen){const card=this.$.card;if(frozen){this.style.height=this.clientHeight+"px";const cardHeight=card.offsetHeight;const cardWidth=card.offsetWidth;if(cardHeight&&cardWidth){card.style.height=cardHeight+"px";card.style.width=cardWidth+"px"}card.style.top=card.getBoundingClientRect().top+"px";this.classList.add("frozen")}else{if(!this.classList.contains("frozen"))return;this.classList.remove("frozen");this.$.card.style.top="";this.$.card.style.height="";this.$.card.style.width="";this.style.height=""}},setExpanded_:function(){this.classList.add("expanded");this.fire("settings-section-expanded")},canAnimateExpand:function(){return!this.classList.contains("expanding")&&!this.classList.contains("expanded")&&this.$.card.clientHeight>0},immediateExpand:function(container){const containerTop=container.getBoundingClientRect().top;this.$.card.position="fixed";this.$.card.top=containerTop+"px";this.$.card.height="calc(100% - "+containerTop+"px)";this.setExpanded_()},animateExpand:function(container){this.collapsedHeight_=this.clientHeight;this.style.height=this.collapsedHeight_+"px";this.classList.add("expanding");const startTop=this.$.card.getBoundingClientRect().top+"px";const startHeight=this.$.card.clientHeight+"px";const containerTop=container.getBoundingClientRect().top;const endTop=containerTop+"px";const endHeight="calc(100% - "+containerTop+"px)";const animation=this.animateCard_("fixed",startTop,endTop,startHeight,endHeight);animation.finished.then(this.setExpanded_.bind(this),()=>{}).then(()=>{this.classList.remove("expanding");this.style.height=""});return animation},canAnimateCollapse:function(){return this.classList.contains("expanded")&&this.clientHeight>0&&!Number.isNaN(this.collapsedHeight_)},setUpAnimateCollapse:function(container){this.$.card.style.width=this.$.card.clientWidth+"px";this.$.card.style.height=this.$.card.clientHeight+"px";this.$.card.style.top=container.getBoundingClientRect().top+"px";this.$.card.style.position="fixed";this.classList.remove("expanded");this.classList.add("collapsing");this.style.height=this.collapsedHeight_+"px"},animateCollapse:function(container){const fixedCardTop=this.$.card.getBoundingClientRect().top;const fixedSectionTop=this.getBoundingClientRect().top;const distance=fixedCardTop-fixedSectionTop;const headerStyle=getComputedStyle(this.$.header);const cardTargetTop=this.$.header.offsetHeight+parseFloat(headerStyle.marginBottom)+parseFloat(headerStyle.marginTop);const startTop=distance+"px";const startHeight=this.$.card.style.height;const endTop=cardTargetTop+"px";const endHeight=this.collapsedHeight_-cardTargetTop+"px";this.$.card.style.position="";const animation=this.animateCard_("absolute",startTop,endTop,startHeight,endHeight);this.$.card.style.width="";this.$.card.style.height="";this.$.card.style.top="";animation.finished.then(()=>{this.classList.remove("expanded")},function(){}).then(()=>{this.style.height="";this.classList.remove("collapsing")});return animation},animateCard_:function(position,startTop,endTop,startHeight,endHeight){const width=this.$.card.clientWidth+"px";const startFrame={position:position,width:width,top:startTop,height:startHeight};const endFrame={position:position,width:width,top:endTop,height:endHeight};const options={duration:settings.animation.Timing.DURATION,easing:settings.animation.Timing.EASING};return new settings.animation.Animation(this.$.card,[startFrame,endFrame],options)},getTitleHiddenStatus_:function(){return this.pageTitle?false:"true"}});
|
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
var parseHtmlSubset=function(){"use strict";var allowedAttributes={href:function(node,value){return node.tagName=="A"&&(value.startsWith("chrome://")||value.startsWith("https://"))},target:function(node,value){return node.tagName=="A"&&value=="_blank"}};var allowedTags=["A","B","SPAN","STRONG"];function merge(var_args){var clone={};for(var i=0;i<arguments.length;++i){if(typeof arguments[i]=="object"){for(var key in arguments[i]){if(arguments[i].hasOwnProperty(key))clone[key]=arguments[i][key]}}}return clone}function walk(n,f){f(n);for(var i=0;i<n.childNodes.length;i++){walk(n.childNodes[i],f)}}function assertElement(tags,node){if(tags.indexOf(node.tagName)==-1)throw Error(node.tagName+" is not supported")}function assertAttribute(attrs,attrNode,node){var n=attrNode.nodeName;var v=attrNode.nodeValue;if(!attrs.hasOwnProperty(n)||!attrs[n](node,v))throw Error(node.tagName+"["+n+'="'+v+'"] is not supported')}return function(s,opt_extraTags,opt_extraAttrs){var extraTags=(opt_extraTags||[]).map(function(str){return str.toUpperCase()});var tags=allowedTags.concat(extraTags);var attrs=merge(allowedAttributes,opt_extraAttrs||{});var doc=document.implementation.createHTMLDocument("");var r=doc.createRange();r.selectNode(doc.body);var df=r.createContextualFragment(s);walk(df,function(node){switch(node.nodeType){case Node.ELEMENT_NODE:assertElement(tags,node);var nodeAttrs=node.attributes;for(var i=0;i<nodeAttrs.length;++i){assertAttribute(attrs,nodeAttrs[i],node)}break;case Node.COMMENT_NODE:case Node.DOCUMENT_FRAGMENT_NODE:case Node.TEXT_NODE:break;default:throw Error("Node type "+node.nodeType+" is not supported")}});return df}}();
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
var I18nBehavior={properties:{locale:{type:String,value:""}},i18nRaw_:function(id,var_args){return arguments.length==1?loadTimeData.getString(id):loadTimeData.getStringF.apply(loadTimeData,arguments)},i18n:function(id,var_args){var rawString=this.i18nRaw_.apply(this,arguments);return parseHtmlSubset("<b>"+rawString+"</b>").firstChild.textContent},i18nAdvanced:function(id,opts){opts=opts||{};var args=[id].concat(opts.substitutions||[]);var rawString=this.i18nRaw_.apply(this,args);return loadTimeData.sanitizeInnerHtml(rawString,opts)},i18nDynamic:function(locale,id,var_args){return this.i18n.apply(this,Array.prototype.slice.call(arguments,1))},i18nExists:function(id){return loadTimeData.valueExists(id)},i18nUpdateLocale:function(){this.locale=loadTimeData.getString("language")}};I18nBehavior.Proto;
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
var WebUIListenerBehavior={properties:{webUIListeners_:{type:Array,value:function(){return[]}}},addWebUIListener:function(eventName,callback){this.webUIListeners_.push(cr.addWebUIListener(eventName,callback))},detached:function(){while(this.webUIListeners_.length>0){cr.removeWebUIListener(this.webUIListeners_.pop())}}};
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-about-page",behaviors:[WebUIListenerBehavior,MainPageBehavior,I18nBehavior],properties:{currentUpdateStatusEvent_:{type:Object,value:{message:"",progress:0,status:UpdateStatus.DISABLED}},obsoleteSystemInfo_:{type:Object,value:function(){return{obsolete:loadTimeData.getBoolean("aboutObsoleteNowOrSoon"),endOfLine:loadTimeData.getBoolean("aboutObsoleteEndOfTheLine")}}},showUpdateStatus_:Boolean,showButtonContainer_:Boolean,showRelaunch_:Boolean},observers:["updateShowUpdateStatus_("+"obsoleteSystemInfo_, currentUpdateStatusEvent_)","updateShowRelaunch_(currentUpdateStatusEvent_)","updateShowButtonContainer_(showRelaunch_)"],aboutBrowserProxy_:null,lifetimeBrowserProxy_:null,attached:function(){this.aboutBrowserProxy_=settings.AboutPageBrowserProxyImpl.getInstance();this.aboutBrowserProxy_.pageReady();this.lifetimeBrowserProxy_=settings.LifetimeBrowserProxyImpl.getInstance();this.startListening_();if(settings.getQueryParameters().get("checkForUpdate")=="true"){this.onCheckUpdatesTap_()}},startListening_:function(){this.addWebUIListener("update-status-changed",this.onUpdateStatusChanged_.bind(this));this.aboutBrowserProxy_.refreshUpdateStatus()},onUpdateStatusChanged_:function(event){this.currentUpdateStatusEvent_=event},onLearnMoreTap_:function(event){event.stopPropagation()},onHelpTap_:function(){this.aboutBrowserProxy_.openHelpPage()},onRelaunchTap_:function(){this.lifetimeBrowserProxy_.relaunch()},updateShowUpdateStatus_:function(){if(this.obsoleteSystemInfo_.endOfLine){this.showUpdateStatus_=false;return}this.showUpdateStatus_=this.currentUpdateStatusEvent_.status!=UpdateStatus.DISABLED},updateShowButtonContainer_:function(){this.showButtonContainer_=this.showRelaunch_},updateShowRelaunch_:function(){this.showRelaunch_=this.checkStatus_(UpdateStatus.NEARLY_UPDATED)},shouldShowLearnMoreLink_:function(){return this.currentUpdateStatusEvent_.status==UpdateStatus.FAILED},getUpdateStatusMessage_:function(){switch(this.currentUpdateStatusEvent_.status){case UpdateStatus.CHECKING:case UpdateStatus.NEED_PERMISSION_TO_UPDATE:return this.i18nAdvanced("aboutUpgradeCheckStarted");case UpdateStatus.NEARLY_UPDATED:return this.i18nAdvanced("aboutUpgradeRelaunch");case UpdateStatus.UPDATED:return this.i18nAdvanced("aboutUpgradeUpToDate");case UpdateStatus.UPDATING:assert(typeof this.currentUpdateStatusEvent_.progress=="number");const progressPercent=this.currentUpdateStatusEvent_.progress+"%";if(this.currentUpdateStatusEvent_.progress>0){return this.i18nAdvanced("aboutUpgradeUpdatingPercent",{substitutions:[progressPercent]})}return this.i18nAdvanced("aboutUpgradeUpdating");default:function formatMessage(msg){return parseHtmlSubset("<b>"+msg+"</b>",["br","pre"]).firstChild.innerHTML}let result="";const message=this.currentUpdateStatusEvent_.message;if(message)result+=formatMessage(message);const connectMessage=this.currentUpdateStatusEvent_.connectionTypes;if(connectMessage)result+="<div>"+formatMessage(connectMessage)+"</div>";return result}},getUpdateStatusIcon_:function(){if(this.obsoleteSystemInfo_.endOfLine)return"settings:error";switch(this.currentUpdateStatusEvent_.status){case UpdateStatus.DISABLED_BY_ADMIN:return"cr20:domain";case UpdateStatus.FAILED:return"settings:error";case UpdateStatus.UPDATED:case UpdateStatus.NEARLY_UPDATED:return"settings:check-circle";default:return null}},getThrobberSrcIfUpdating_:function(){if(this.obsoleteSystemInfo_.endOfLine)return null;switch(this.currentUpdateStatusEvent_.status){case UpdateStatus.CHECKING:case UpdateStatus.UPDATING:return"chrome://resources/images/throbber_small.svg";default:return null}},checkStatus_:function(status){return this.currentUpdateStatusEvent_.status==status},onProductLogoTap_:function(){this.$["product-logo"].animate({transform:["none","rotate(-10turn)"]},{duration:500,easing:"cubic-bezier(1, 0, 0, 1)"})},shouldShowIcons_:function(){if(this.obsoleteSystemInfo_.endOfLine)return true;return this.showUpdateStatus_}});
|
|
// Copyright 2017 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"cr-link-row",behaviors:[Polymer.PaperRippleBehavior],properties:{iconClass:String,label:String,subLabel:{type:String,value:""},disabled:{type:Boolean,reflectToAttribute:true}},listeners:{down:"_rippleDown",up:"_rippleUp",focus:"_rippleDown",blur:"_rippleUp"},_rippleDown:function(){this.getRipple().uiDownAction()},_rippleUp:function(){this.getRipple().uiUpAction()},_createRipple:function(){this._rippleContainer=this.$.icon;var ripple=Polymer.PaperRippleBehavior._createRipple();ripple.id="ink";ripple.setAttribute("recenters","");ripple.classList.add("circle");return ripple}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.define("settings",function(){class AppearanceBrowserProxy{getDefaultZoom(){}getThemeInfo(themeId){}isSupervised(){}isWallpaperSettingVisible(){}isWallpaperPolicyControlled(){}useDefaultTheme(){}useSystemTheme(){}validateStartupPage(url){}}class AppearanceBrowserProxyImpl{getDefaultZoom(){return new Promise(function(resolve){chrome.settingsPrivate.getDefaultZoom(resolve)})}getThemeInfo(themeId){return new Promise(function(resolve){chrome.management.get(themeId,resolve)})}isSupervised(){return loadTimeData.getBoolean("isSupervised")}useDefaultTheme(){chrome.send("useDefaultTheme")}useSystemTheme(){chrome.send("useSystemTheme")}validateStartupPage(url){return cr.sendWithPromise("validateStartupPage",url)}}cr.addSingletonGetter(AppearanceBrowserProxyImpl);return{AppearanceBrowserProxy:AppearanceBrowserProxy,AppearanceBrowserProxyImpl:AppearanceBrowserProxyImpl}});
|
|
// Copyright 2018 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
var CrRadioButtonBehaviorImpl={properties:{checked:{type:Boolean,value:false,reflectToAttribute:true,observer:"checkedChanged_"},disabled:{type:Boolean,value:false,reflectToAttribute:true,observer:"disabledChanged_"},label:{type:String,value:""}},listeners:{blur:"cancelRipple_",click:"onClick_",focus:"onFocus_",keyup:"onKeyUp_",pointerup:"cancelRipple_"},hostAttributes:{"aria-disabled":"false","aria-checked":"false",role:"radio",tabindex:0},checkedChanged_:function(){this.setAttribute("aria-checked",this.checked?"true":"false")},disabledChanged_:function(current,previous){if(previous===undefined&&!this.disabled)return;this.setAttribute("tabindex",this.disabled?-1:0);this.setAttribute("aria-disabled",this.disabled?"true":"false")},onFocus_:function(){this.ensureRipple();this.$$("paper-ripple").holdDown=true},onClick_:function(e){if(this.disabled||e.target.tagName=="A")e.stopPropagation()},onKeyUp_:function(e){if(e.key!=" "&&e.key!="Enter")return;e.target.click()},cancelRipple_:function(){this.ensureRipple();this.$$("paper-ripple").holdDown=false},_createRipple:function(){this._rippleContainer=this.$$(".disc-wrapper");let ripple=Polymer.PaperRippleBehavior._createRipple();ripple.id="ink";ripple.setAttribute("recenters","");ripple.classList.add("circle","toggle-ink");return ripple}};const CrRadioButtonBehavior=[Polymer.PaperRippleBehavior,CrRadioButtonBehaviorImpl];
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
var CrPolicyStrings;var CrPolicyIndicatorType={DEVICE_POLICY:"devicePolicy",EXTENSION:"extension",NONE:"none",OWNER:"owner",PRIMARY_USER:"primary_user",RECOMMENDED:"recommended",USER_POLICY:"userPolicy"};var CrPolicyIndicatorBehavior={properties:{indicatorType:{type:String,value:CrPolicyIndicatorType.NONE},indicatorSourceName:{type:String,value:""},indicatorVisible:{type:Boolean,computed:"getIndicatorVisible_(indicatorType)"},indicatorIcon:{type:String,computed:"getIndicatorIcon_(indicatorType)"},indicatorTooltip:{type:String,computed:"getIndicatorTooltip(indicatorType, indicatorSourceName)"}},getIndicatorVisible_:function(type){return type!=CrPolicyIndicatorType.NONE},getIndicatorIcon_:function(type){switch(type){case CrPolicyIndicatorType.EXTENSION:return"cr:extension";case CrPolicyIndicatorType.NONE:return"";case CrPolicyIndicatorType.PRIMARY_USER:return"cr:group";case CrPolicyIndicatorType.OWNER:return"cr:person";case CrPolicyIndicatorType.USER_POLICY:case CrPolicyIndicatorType.DEVICE_POLICY:case CrPolicyIndicatorType.RECOMMENDED:return"cr20:domain";default:assertNotReached()}},getIndicatorTooltip:function(type,name,opt_matches){if(!CrPolicyStrings)return"";switch(type){case CrPolicyIndicatorType.EXTENSION:return name.length>0?CrPolicyStrings.controlledSettingExtension.replace("$1",name):CrPolicyStrings.controlledSettingExtensionWithoutName;case CrPolicyIndicatorType.PRIMARY_USER:return CrPolicyStrings.controlledSettingShared.replace("$1",name);case CrPolicyIndicatorType.OWNER:return CrPolicyStrings.controlledSettingOwner.replace("$1",name);case CrPolicyIndicatorType.USER_POLICY:case CrPolicyIndicatorType.DEVICE_POLICY:return CrPolicyStrings.controlledSettingPolicy;case CrPolicyIndicatorType.RECOMMENDED:return opt_matches?CrPolicyStrings.controlledSettingRecommendedMatches:CrPolicyStrings.controlledSettingRecommendedDiffers}return""}};Polymer({is:"fade-in-animation",behaviors:[Polymer.NeonAnimationBehavior],configure:function(config){var node=config.node;this._effect=new KeyframeEffect(node,[{opacity:"0"},{opacity:"1"}],this.timingFromConfig(config));return this._effect}});Polymer({is:"fade-out-animation",behaviors:[Polymer.NeonAnimationBehavior],configure:function(config){var node=config.node;this._effect=new KeyframeEffect(node,[{opacity:"1"},{opacity:"0"}],this.timingFromConfig(config));return this._effect}});Polymer({is:"paper-tooltip",hostAttributes:{role:"tooltip",tabindex:-1},behaviors:[Polymer.NeonAnimationRunnerBehavior],properties:{for:{type:String,observer:"_findTarget"},manualMode:{type:Boolean,value:false,observer:"_manualModeChanged"},position:{type:String,value:"bottom"},fitToVisibleBounds:{type:Boolean,value:false},offset:{type:Number,value:14},marginTop:{type:Number,value:14},animationDelay:{type:Number,value:500},animationConfig:{type:Object,value:function(){return{entry:[{name:"fade-in-animation",node:this,timing:{delay:0}}],exit:[{name:"fade-out-animation",node:this}]}}},_showing:{type:Boolean,value:false}},listeners:{"neon-animation-finish":"_onAnimationFinish"},get target(){var parentNode=Polymer.dom(this).parentNode;var ownerRoot=Polymer.dom(this).getOwnerRoot();var target;if(this.for){target=Polymer.dom(ownerRoot).querySelector("#"+this.for)}else{target=parentNode.nodeType==Node.DOCUMENT_FRAGMENT_NODE?ownerRoot.host:parentNode}return target},attached:function(){this._findTarget()},detached:function(){if(!this.manualMode)this._removeListeners()},show:function(){if(this._showing)return;if(Polymer.dom(this).textContent.trim()===""){var allChildrenEmpty=true;var effectiveChildren=Polymer.dom(this).getEffectiveChildNodes();for(var i=0;i<effectiveChildren.length;i++){if(effectiveChildren[i].textContent.trim()!==""){allChildrenEmpty=false;break}}if(allChildrenEmpty){return}}this.cancelAnimation();this._showing=true;this.toggleClass("hidden",false,this.$.tooltip);this.updatePosition();this.animationConfig.entry[0].timing=this.animationConfig.entry[0].timing||{};this.animationConfig.entry[0].timing.delay=this.animationDelay;this._animationPlaying=true;this.playAnimation("entry")},hide:function(){if(!this._showing){return}if(this._animationPlaying){this.cancelAnimation();this._showing=false;this._onAnimationFinish();return}this._showing=false;this._animationPlaying=true;this.playAnimation("exit")},updatePosition:function(){if(!this._target||!this.offsetParent)return;var offset=this.offset;if(this.marginTop!=14&&this.offset==14)offset=this.marginTop;var parentRect=this.offsetParent.getBoundingClientRect();var targetRect=this._target.getBoundingClientRect();var thisRect=this.getBoundingClientRect();var horizontalCenterOffset=(targetRect.width-thisRect.width)/2;var verticalCenterOffset=(targetRect.height-thisRect.height)/2;var targetLeft=targetRect.left-parentRect.left;var targetTop=targetRect.top-parentRect.top;var tooltipLeft,tooltipTop;switch(this.position){case"top":tooltipLeft=targetLeft+horizontalCenterOffset;tooltipTop=targetTop-thisRect.height-offset;break;case"bottom":tooltipLeft=targetLeft+horizontalCenterOffset;tooltipTop=targetTop+targetRect.height+offset;break;case"left":tooltipLeft=targetLeft-thisRect.width-offset;tooltipTop=targetTop+verticalCenterOffset;break;case"right":tooltipLeft=targetLeft+targetRect.width+offset;tooltipTop=targetTop+verticalCenterOffset;break}if(this.fitToVisibleBounds){if(parentRect.left+tooltipLeft+thisRect.width>window.innerWidth){this.style.right="0px";this.style.left="auto"}else{this.style.left=Math.max(0,tooltipLeft)+"px";this.style.right="auto"}if(parentRect.top+tooltipTop+thisRect.height>window.innerHeight){this.style.bottom=parentRect.height+"px";this.style.top="auto"}else{this.style.top=Math.max(-parentRect.top,tooltipTop)+"px";this.style.bottom="auto"}}else{this.style.left=tooltipLeft+"px";this.style.top=tooltipTop+"px"}},_addListeners:function(){if(this._target){this.listen(this._target,"mouseenter","show");this.listen(this._target,"focus","show");this.listen(this._target,"mouseleave","hide");this.listen(this._target,"blur","hide");this.listen(this._target,"tap","hide")}this.listen(this,"mouseenter","hide")},_findTarget:function(){if(!this.manualMode)this._removeListeners();this._target=this.target;if(!this.manualMode)this._addListeners()},_manualModeChanged:function(){if(this.manualMode)this._removeListeners();else this._addListeners()},_onAnimationFinish:function(){this._animationPlaying=false;if(!this._showing){this.toggleClass("hidden",true,this.$.tooltip)}},_removeListeners:function(){if(this._target){this.unlisten(this._target,"mouseenter","show");this.unlisten(this._target,"focus","show");this.unlisten(this._target,"mouseleave","hide");this.unlisten(this._target,"blur","hide");this.unlisten(this._target,"tap","hide")}this.unlisten(this,"mouseenter","hide")}});
|
|
// Copyright 2017 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"cr-tooltip-icon",properties:{iconAriaLabel:String,iconClass:String,tooltipText:String}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"cr-policy-pref-indicator",behaviors:[CrPolicyIndicatorBehavior],properties:{iconAriaLabel:String,indicatorType:{type:String,value:CrPolicyIndicatorType.NONE,computed:"getIndicatorTypeForPref_(pref.controlledBy, pref.enforcement)"},indicatorTooltip:{type:String,computed:"getIndicatorTooltipForPref_(indicatorType, pref.*)"},pref:Object},getIndicatorTypeForPref_:function(controlledBy,enforcement){if(enforcement==chrome.settingsPrivate.Enforcement.RECOMMENDED)return CrPolicyIndicatorType.RECOMMENDED;if(enforcement==chrome.settingsPrivate.Enforcement.ENFORCED){switch(controlledBy){case chrome.settingsPrivate.ControlledBy.EXTENSION:return CrPolicyIndicatorType.EXTENSION;case chrome.settingsPrivate.ControlledBy.PRIMARY_USER:return CrPolicyIndicatorType.PRIMARY_USER;case chrome.settingsPrivate.ControlledBy.OWNER:return CrPolicyIndicatorType.OWNER;case chrome.settingsPrivate.ControlledBy.USER_POLICY:return CrPolicyIndicatorType.USER_POLICY;case chrome.settingsPrivate.ControlledBy.DEVICE_POLICY:return CrPolicyIndicatorType.DEVICE_POLICY}}return CrPolicyIndicatorType.NONE},getIndicatorTooltipForPref_:function(indicatorType){var matches=this.pref&&this.pref.value==this.pref.recommendedValue;return this.getIndicatorTooltip(indicatorType,this.pref.controlledByName||"",matches)}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
const CrSettingsPrefs=function(){const CrSettingsPrefsInternal={setInitialized:function(){CrSettingsPrefsInternal.isInitialized=true;CrSettingsPrefsInternal.resolve_()},resetForTesting:function(){CrSettingsPrefsInternal.setup_()},deferInitialization:false,setup_:function(){CrSettingsPrefsInternal.isInitialized=false;CrSettingsPrefsInternal.initialized=new Promise(function(resolve){CrSettingsPrefsInternal.resolve_=resolve})}};CrSettingsPrefsInternal.setup_();return CrSettingsPrefsInternal}();
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
const PrefControlBehavior={properties:{pref:{type:Object,notify:true,observer:"validatePref_"}},ready:function(){this.validatePref_()},validatePref_:function(){CrSettingsPrefs.initialized.then(()=>{if(!this.pref){let error="Pref not found for element "+this.tagName;if(this.id)error+="#"+this.id;error+=" in "+this.domHost.tagName;console.error(error)}})}};
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.define("Settings.PrefUtil",function(){function stringToPrefValue(value,pref){switch(pref.type){case chrome.settingsPrivate.PrefType.BOOLEAN:return value=="true";case chrome.settingsPrivate.PrefType.NUMBER:const n=parseFloat(value);if(isNaN(n)){console.error("Argument to stringToPrefValue for number pref "+"was unparsable: "+value);return undefined}return n;case chrome.settingsPrivate.PrefType.STRING:case chrome.settingsPrivate.PrefType.URL:return value;default:assertNotReached("No conversion from string to "+pref.type+" pref")}}function prefToString(pref){switch(pref.type){case chrome.settingsPrivate.PrefType.BOOLEAN:case chrome.settingsPrivate.PrefType.NUMBER:return pref.value.toString();case chrome.settingsPrivate.PrefType.STRING:case chrome.settingsPrivate.PrefType.URL:return pref.value;default:assertNotReached("No conversion from "+pref.type+" pref to string")}}return{stringToPrefValue:stringToPrefValue,prefToString:prefToString}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"controlled-radio-button",behaviors:[PrefControlBehavior,CrRadioButtonBehavior],properties:{disabled:{type:Boolean,computed:"computeDisabled_(pref.*)",reflectToAttribute:true,observer:"disabledChanged_"},name:{type:String,notify:true}},computeDisabled_:function(){return this.pref.enforcement==chrome.settingsPrivate.Enforcement.ENFORCED},disabledChanged_:function(current,previous){if(previous===undefined&&!this.disabled)return;this.setAttribute("tabindex",this.disabled?-1:0);this.setAttribute("aria-disabled",this.disabled?"true":"false")},showIndicator_:function(){return this.disabled&&this.name==Settings.PrefUtil.prefToString(assert(this.pref))},onIndicatorTap_:function(e){e.preventDefault();e.stopPropagation()}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.define("settings",function(){class ExtensionControlBrowserProxy{disableExtension(extensionId){}manageExtension(extensionId){}}class ExtensionControlBrowserProxyImpl{disableExtension(extensionId){chrome.send("disableExtension",[extensionId])}manageExtension(extensionId){window.open("chrome://extensions?id="+extensionId)}}cr.addSingletonGetter(ExtensionControlBrowserProxyImpl);return{ExtensionControlBrowserProxy:ExtensionControlBrowserProxy,ExtensionControlBrowserProxyImpl:ExtensionControlBrowserProxyImpl}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"extension-controlled-indicator",behaviors:[I18nBehavior],properties:{extensionCanBeDisabled:Boolean,extensionId:String,extensionName:String},getLabel_:function(extensionId,extensionName){const manageUrl="chrome://extensions/?id="+assert(this.extensionId);return this.i18nAdvanced("controlledByExtension",{substitutions:['<a href="'+manageUrl+'" target="_blank">'+assert(this.extensionName)+"</a>"]})},onDisableTap_:function(){assert(this.extensionCanBeDisabled);settings.ExtensionControlBrowserProxyImpl.getInstance().disableExtension(assert(this.extensionId));this.fire("extension-disable")}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
var CrPolicyPrefBehavior={properties:{noExtensionIndicator:Boolean},isPrefEnforced:function(){return this.pref.enforcement==chrome.settingsPrivate.Enforcement.ENFORCED},hasPrefPolicyIndicator:function(){if(this.noExtensionIndicator&&this.pref.controlledBy==chrome.settingsPrivate.ControlledBy.EXTENSION){return false}return this.isPrefEnforced()||this.pref.enforcement==chrome.settingsPrivate.Enforcement.RECOMMENDED}};
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
let DropdownMenuOption;let DropdownMenuOptionList;Polymer({is:"settings-dropdown-menu",behaviors:[CrPolicyPrefBehavior,PrefControlBehavior],properties:{menuOptions:{type:Array,value:null},disabled:{type:Boolean,reflectToAttribute:true,value:false},prefKey:{type:String,value:null},notFoundValue_:{type:String,value:"SETTINGS_DROPDOWN_NOT_FOUND_ITEM",readOnly:true},label:String},observers:["updateSelected_(menuOptions, pref.value.*, prefKey)"],onChange_:function(){const selected=this.$.dropdownMenu.value;if(selected==this.notFoundValue_)return;if(this.prefKey){assert(this.pref);this.set(`pref.value.${this.prefKey}`,selected)}else{const prefValue=Settings.PrefUtil.stringToPrefValue(selected,assert(this.pref));if(prefValue!==undefined)this.set("pref.value",prefValue)}},updateSelected_:function(){if(this.menuOptions===null||!this.menuOptions.length)return;const prefValue=this.prefStringValue_();const option=this.menuOptions.find(function(menuItem){return menuItem.value==prefValue});this.async(()=>{this.$.dropdownMenu.value=option==undefined?this.notFoundValue_:prefValue})},prefStringValue_:function(){if(this.prefKey){return this.pref.value[this.prefKey]}else{return Settings.PrefUtil.prefToString(assert(this.pref))}},showNotFoundValue_:function(menuOptions,prefValue){if(!menuOptions||!menuOptions.length)return false;const option=menuOptions.find(menuItem=>{return menuItem.value==this.prefStringValue_()});return!option},shouldDisableMenu_:function(){return this.disabled||this.isPrefEnforced()||this.menuOptions===null||this.menuOptions.length==0}});
|
|
// Copyright 2018 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"cr-radio-button",behaviors:[CrRadioButtonBehavior]});Polymer.IronMultiSelectableBehaviorImpl={properties:{multi:{type:Boolean,value:false,observer:"multiChanged"},selectedValues:{type:Array,notify:true,value:function(){return[]}},selectedItems:{type:Array,readOnly:true,notify:true,value:function(){return[]}}},observers:["_updateSelected(selectedValues.splices)"],select:function(value){if(this.multi){this._toggleSelected(value)}else{this.selected=value}},multiChanged:function(multi){this._selection.multi=multi;this._updateSelected()},get _shouldUpdateSelection(){return this.selected!=null||this.selectedValues!=null&&this.selectedValues.length},_updateAttrForSelected:function(){if(!this.multi){Polymer.IronSelectableBehavior._updateAttrForSelected.apply(this)}else if(this.selectedItems&&this.selectedItems.length>0){this.selectedValues=this.selectedItems.map(function(selectedItem){return this._indexToValue(this.indexOf(selectedItem))},this).filter(function(unfilteredValue){return unfilteredValue!=null},this)}},_updateSelected:function(){if(this.multi){this._selectMulti(this.selectedValues)}else{this._selectSelected(this.selected)}},_selectMulti:function(values){values=values||[];var selectedItems=(this._valuesToItems(values)||[]).filter(function(item){return item!==null&&item!==undefined});this._selection.clear(selectedItems);for(var i=0;i<selectedItems.length;i++){this._selection.setItemSelected(selectedItems[i],true)}if(this.fallbackSelection&&!this._selection.get().length){var fallback=this._valueToItem(this.fallbackSelection);if(fallback){this.select(this.fallbackSelection)}}},_selectionChange:function(){var s=this._selection.get();if(this.multi){this._setSelectedItems(s);this._setSelectedItem(s.length?s[0]:null)}else{if(s!==null&&s!==undefined){this._setSelectedItems([s]);this._setSelectedItem(s)}else{this._setSelectedItems([]);this._setSelectedItem(null)}}},_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(function(value){return this._valueToItem(value)},this)}};Polymer.IronMultiSelectableBehavior=[Polymer.IronSelectableBehavior,Polymer.IronMultiSelectableBehaviorImpl];Polymer.IronMenuBehaviorImpl={properties:{focusedItem:{observer:"_focusedItemChanged",readOnly:true,type:Object},attrForItemTitle:{type:String},disabled:{type:Boolean,value:false,observer:"_disabledChanged"}},_MODIFIER_KEYS:["Alt","AltGraph","CapsLock","Control","Fn","FnLock","Hyper","Meta","NumLock","OS","ScrollLock","Shift","Super","Symbol","SymbolLock"],_SEARCH_RESET_TIMEOUT_MS:1e3,_previousTabIndex:0,hostAttributes:{role:"menu"},observers:["_updateMultiselectable(multi)"],listeners:{focus:"_onFocus",keydown:"_onKeydown","iron-items-changed":"_onIronItemsChanged"},keyBindings:{up:"_onUpKey",down:"_onDownKey",esc:"_onEscKey","shift+tab:keydown":"_onShiftTabDown"},attached:function(){this._resetTabindices()},select:function(value){if(this._defaultFocusAsync){this.cancelAsync(this._defaultFocusAsync);this._defaultFocusAsync=null}var item=this._valueToItem(value);if(item&&item.hasAttribute("disabled"))return;this._setFocusedItem(item);Polymer.IronMultiSelectableBehaviorImpl.select.apply(this,arguments)},_resetTabindices:function(){var selectedItem=this.multi?this.selectedItems&&this.selectedItems[0]:this.selectedItem;this.items.forEach(function(item){item.setAttribute("tabindex",item===selectedItem?"0":"-1")},this)},_updateMultiselectable:function(multi){if(multi){this.setAttribute("aria-multiselectable","true")}else{this.removeAttribute("aria-multiselectable")}},_focusWithKeyboardEvent:function(event){if(this._MODIFIER_KEYS.indexOf(event.key)!==-1)return;this.cancelDebouncer("_clearSearchText");var searchText=this._searchText||"";var key=event.key&&event.key.length==1?event.key:String.fromCharCode(event.keyCode);searchText+=key.toLocaleLowerCase();var searchLength=searchText.length;for(var i=0,item;item=this.items[i];i++){if(item.hasAttribute("disabled")){continue}var attr=this.attrForItemTitle||"textContent";var title=(item[attr]||item.getAttribute(attr)||"").trim();if(title.length<searchLength){continue}if(title.slice(0,searchLength).toLocaleLowerCase()==searchText){this._setFocusedItem(item);break}}this._searchText=searchText;this.debounce("_clearSearchText",this._clearSearchText,this._SEARCH_RESET_TIMEOUT_MS)},_clearSearchText:function(){this._searchText=""},_focusPrevious:function(){var length=this.items.length;var curFocusIndex=Number(this.indexOf(this.focusedItem));for(var i=1;i<length+1;i++){var item=this.items[(curFocusIndex-i+length)%length];if(!item.hasAttribute("disabled")){var owner=Polymer.dom(item).getOwnerRoot()||document;this._setFocusedItem(item);if(Polymer.dom(owner).activeElement==item){return}}}},_focusNext:function(){var length=this.items.length;var curFocusIndex=Number(this.indexOf(this.focusedItem));for(var i=1;i<length+1;i++){var item=this.items[(curFocusIndex+i)%length];if(!item.hasAttribute("disabled")){var owner=Polymer.dom(item).getOwnerRoot()||document;this._setFocusedItem(item);if(Polymer.dom(owner).activeElement==item){return}}}},_applySelection:function(item,isSelected){if(isSelected){item.setAttribute("aria-selected","true")}else{item.removeAttribute("aria-selected")}Polymer.IronSelectableBehavior._applySelection.apply(this,arguments)},_focusedItemChanged:function(focusedItem,old){old&&old.setAttribute("tabindex","-1");if(focusedItem&&!focusedItem.hasAttribute("disabled")&&!this.disabled){focusedItem.setAttribute("tabindex","0");focusedItem.focus()}},_onIronItemsChanged:function(event){if(event.detail.addedNodes.length){this._resetTabindices()}},_onShiftTabDown:function(event){var oldTabIndex=this.getAttribute("tabindex");Polymer.IronMenuBehaviorImpl._shiftTabPressed=true;this._setFocusedItem(null);this.setAttribute("tabindex","-1");this.async(function(){this.setAttribute("tabindex",oldTabIndex);Polymer.IronMenuBehaviorImpl._shiftTabPressed=false},1)},_onFocus:function(event){if(Polymer.IronMenuBehaviorImpl._shiftTabPressed){return}var rootTarget=Polymer.dom(event).rootTarget;if(rootTarget!==this&&typeof rootTarget.tabIndex!=="undefined"&&!this.isLightDescendant(rootTarget)){return}this._defaultFocusAsync=this.async(function(){var selectedItem=this.multi?this.selectedItems&&this.selectedItems[0]:this.selectedItem;this._setFocusedItem(null);if(selectedItem){this._setFocusedItem(selectedItem)}else if(this.items[0]){this._focusNext()}})},_onUpKey:function(event){this._focusPrevious();event.detail.keyboardEvent.preventDefault()},_onDownKey:function(event){this._focusNext();event.detail.keyboardEvent.preventDefault()},_onEscKey:function(event){var focusedItem=this.focusedItem;if(focusedItem){focusedItem.blur()}},_onKeydown:function(event){if(!this.keyboardEventMatchesKeys(event,"up down esc")){this._focusWithKeyboardEvent(event)}event.stopPropagation()},_activateHandler:function(event){Polymer.IronSelectableBehavior._activateHandler.call(this,event);event.stopPropagation()},_disabledChanged:function(disabled){if(disabled){this._previousTabIndex=this.hasAttribute("tabindex")?this.tabIndex:0;this.removeAttribute("tabindex")}else if(!this.hasAttribute("tabindex")){this.setAttribute("tabindex",this._previousTabIndex)}}};Polymer.IronMenuBehaviorImpl._shiftTabPressed=false;Polymer.IronMenuBehavior=[Polymer.IronMultiSelectableBehavior,Polymer.IronA11yKeysBehavior,Polymer.IronMenuBehaviorImpl];Polymer.IronMenubarBehaviorImpl={hostAttributes:{role:"menubar"},keyBindings:{left:"_onLeftKey",right:"_onRightKey"},_onUpKey:function(event){this.focusedItem.click();event.detail.keyboardEvent.preventDefault()},_onDownKey:function(event){this.focusedItem.click();event.detail.keyboardEvent.preventDefault()},get _isRTL(){return window.getComputedStyle(this)["direction"]==="rtl"},_onLeftKey:function(event){if(this._isRTL){this._focusNext()}else{this._focusPrevious()}event.detail.keyboardEvent.preventDefault()},_onRightKey:function(event){if(this._isRTL){this._focusPrevious()}else{this._focusNext()}event.detail.keyboardEvent.preventDefault()},_onKeydown:function(event){if(this.keyboardEventMatchesKeys(event,"up down left right esc")){return}this._focusWithKeyboardEvent(event)}};Polymer.IronMenubarBehavior=[Polymer.IronMenuBehavior,Polymer.IronMenubarBehaviorImpl];Polymer({is:"paper-radio-group",behaviors:[Polymer.IronMenubarBehavior],hostAttributes:{role:"radiogroup"},properties:{attrForSelected:{type:String,value:"name"},selectedAttribute:{type:String,value:"checked"},selectable:{type:String,value:"paper-radio-button"},allowEmptySelection:{type:Boolean,value:false}},select:function(value){var newItem=this._valueToItem(value);if(newItem&&newItem.hasAttribute("disabled")){return}if(this.selected){var oldItem=this._valueToItem(this.selected);if(this.selected==value){if(this.allowEmptySelection){value=""}else{if(oldItem)oldItem.checked=true;return}}if(oldItem)oldItem.checked=false}Polymer.IronSelectableBehavior.select.apply(this,[value]);this.fire("paper-radio-group-changed")},_activateFocusedItem:function(){this._itemActivate(this._valueForItem(this.focusedItem),this.focusedItem)},_onUpKey:function(event){this._focusPrevious();event.preventDefault();this._activateFocusedItem()},_onDownKey:function(event){this._focusNext();event.preventDefault();this._activateFocusedItem()},_onLeftKey:function(event){Polymer.IronMenubarBehaviorImpl._onLeftKey.apply(this,arguments);this._activateFocusedItem()},_onRightKey:function(event){Polymer.IronMenubarBehaviorImpl._onRightKey.apply(this,arguments);this._activateFocusedItem()}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-radio-group",behaviors:[PrefControlBehavior],properties:{selected:{type:String,notify:true,observer:"selectedChanged_"}},hostAttributes:{role:"none"},observers:["prefChanged_(pref.*)"],prefChanged_:function(){const pref=this.pref;this.selected=Settings.PrefUtil.prefToString(pref)},selectedChanged_:function(selected){if(!this.pref)return;this.set("pref.value",Settings.PrefUtil.stringToPrefValue(selected,this.pref))}});
|
|
// Copyright 2017 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"cr-toggle",behaviors:[Polymer.PaperRippleBehavior],properties:{checked:{type:Boolean,value:false,reflectToAttribute:true,observer:"checkedChanged_",notify:true},disabled:{type:Boolean,value:false,reflectToAttribute:true,observer:"disabledChanged_"}},hostAttributes:{"aria-disabled":"false","aria-pressed":"false",role:"button",tabindex:0},listeners:{pointerdown:"onPointerDown_",pointerup:"onPointerUp_",click:"onTap_",keypress:"onKeyPress_",focus:"onFocus_",blur:"onBlur_"},boundPointerMove_:null,MOVE_THRESHOLD_PX:5,handledInPointerMove_:false,attached:function(){let direction=this.matches(":host-context([dir=rtl]) cr-toggle")?-1:1;this.boundPointerMove_=(e=>{e.preventDefault();let diff=e.clientX-this.pointerDownX_;if(Math.abs(diff)<this.MOVE_THRESHOLD_PX)return;this.handledInPointerMove_=true;let shouldToggle=diff*direction<0&&this.checked||diff*direction>0&&!this.checked;if(shouldToggle)this.toggleState_(false)})},checkedChanged_:function(){this.setAttribute("aria-pressed",this.checked?"true":"false")},disabledChanged_:function(){this.setAttribute("tabindex",this.disabled?-1:0);this.setAttribute("aria-disabled",this.disabled?"true":"false")},onFocus_:function(){this.ensureRipple();this.$$("paper-ripple").holdDown=true},onBlur_:function(){this.ensureRipple();this.$$("paper-ripple").holdDown=false},onPointerUp_:function(e){this.removeEventListener("pointermove",this.boundPointerMove_)},onPointerDown_:function(e){if(e.button!=0)return;this.setPointerCapture(e.pointerId);this.pointerDownX_=e.clientX;this.handledInPointerMove_=false;this.addEventListener("pointermove",this.boundPointerMove_)},onTap_:function(e){e.stopPropagation();e.preventDefault();if(this.handledInPointerMove_)return;this.toggleState_(false)},toggleState_:function(fromKeyboard){this.checked=!this.checked;if(!fromKeyboard){this.ensureRipple();this.$$("paper-ripple").holdDown=false}this.fire("change",this.checked)},onKeyPress_:function(e){if(e.key==" "||e.key=="Enter"){e.preventDefault();this.toggleState_(true)}},onButtonFocus_:function(){this.focus()},_createRipple:function(){this._rippleContainer=this.$.knob;let ripple=Polymer.PaperRippleBehavior._createRipple();ripple.id="ink";ripple.setAttribute("recenters","");ripple.classList.add("circle","toggle-ink");return ripple}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
const SettingsBooleanControlBehaviorImpl={properties:{inverted:{type:Boolean,value:false},checked:{type:Boolean,value:false,notify:true,reflectToAttribute:true},disabled:{type:Boolean,value:false,notify:true,reflectToAttribute:true},noSetPref:{type:Boolean,value:false},label:{type:String,value:""},subLabel:{type:String,value:""},numericUncheckedValue:{type:Number,value:0}},observers:["prefValueChanged_(pref.value)"],notifyChangedByUserInteraction:function(){this.fire("settings-boolean-control-change");if(!this.pref||this.noSetPref)return;this.sendPrefChange()},resetToPrefValue:function(){this.checked=this.getNewValue_(this.pref.value)},sendPrefChange:function(){if(this.pref.type==chrome.settingsPrivate.PrefType.NUMBER){assert(!this.inverted);this.set("pref.value",this.checked?1:this.numericUncheckedValue);return}this.set("pref.value",this.inverted?!this.checked:this.checked)},prefValueChanged_:function(prefValue){this.checked=this.getNewValue_(prefValue)},getNewValue_:function(value){if(this.pref.type==chrome.settingsPrivate.PrefType.NUMBER){assert(!this.inverted);return value!=this.numericUncheckedValue}return this.inverted?!value:!!value},controlDisabled:function(){return this.disabled||this.isPrefEnforced()}};const SettingsBooleanControlBehavior=[CrPolicyPrefBehavior,PrefControlBehavior,SettingsBooleanControlBehaviorImpl];
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-toggle-button",behaviors:[SettingsBooleanControlBehavior],properties:{ariaLabel:{type:String,reflectToAttribute:false,observer:"onAriaLabelSet_",value:""},elideLabel:{type:Boolean,reflectToAttribute:true}},listeners:{click:"onHostTap_"},observers:["onDisableOrPrefChange_(disabled, pref.*)"],focus:function(){this.$.control.focus()},onAriaLabelSet_:function(){if(this.hasAttribute("aria-label")){let ariaLabel=this.ariaLabel;this.removeAttribute("aria-label");this.ariaLabel=ariaLabel}},getAriaLabel_:function(){return this.label||this.ariaLabel},onDisableOrPrefChange_:function(){if(this.controlDisabled()){this.removeAttribute("actionable")}else{this.setAttribute("actionable","")}},onHostTap_:function(e){e.stopPropagation();if(this.controlDisabled())return;this.checked=!this.checked;this.notifyChangedByUserInteraction();this.fire("change")},onChange_:function(e){this.checked=e.detail;this.notifyChangedByUserInteraction()}});Polymer({is:"paper-input-container",properties:{noLabelFloat:{type:Boolean,value:false},alwaysFloatLabel:{type:Boolean,value:false},attrForValue:{type:String,value:"bind-value"},autoValidate:{type:Boolean,value:false},invalid:{observer:"_invalidChanged",type:Boolean,value:false},focused:{readOnly:true,type:Boolean,value:false,notify:true},_addons:{type:Array},_inputHasContent:{type:Boolean,value:false},_inputSelector:{type:String,value:"input,iron-input,textarea,.paper-input-input"},_boundOnFocus:{type:Function,value:function(){return this._onFocus.bind(this)}},_boundOnBlur:{type:Function,value:function(){return this._onBlur.bind(this)}},_boundOnInput:{type:Function,value:function(){return this._onInput.bind(this)}},_boundValueChanged:{type:Function,value:function(){return this._onValueChanged.bind(this)}}},listeners:{"addon-attached":"_onAddonAttached","iron-input-validate":"_onIronInputValidate"},get _valueChangedEvent(){return this.attrForValue+"-changed"},get _propertyForValue(){return Polymer.CaseMap.dashToCamelCase(this.attrForValue)},get _inputElement(){return Polymer.dom(this).querySelector(this._inputSelector)},get _inputElementValue(){return this._inputElement[this._propertyForValue]||this._inputElement.value},ready:function(){this.__isFirstValueUpdate=true;if(!this._addons){this._addons=[]}this.addEventListener("focus",this._boundOnFocus,true);this.addEventListener("blur",this._boundOnBlur,true)},attached:function(){if(this.attrForValue){this._inputElement.addEventListener(this._valueChangedEvent,this._boundValueChanged)}else{this.addEventListener("input",this._onInput)}if(this._inputElementValue&&this._inputElementValue!=""){this._handleValueAndAutoValidate(this._inputElement)}else{this._handleValue(this._inputElement)}},_onAddonAttached:function(event){if(!this._addons){this._addons=[]}var target=event.target;if(this._addons.indexOf(target)===-1){this._addons.push(target);if(this.isAttached){this._handleValue(this._inputElement)}}},_onFocus:function(){this._setFocused(true)},_onBlur:function(){this._setFocused(false);this._handleValueAndAutoValidate(this._inputElement)},_onInput:function(event){this._handleValueAndAutoValidate(event.target)},_onValueChanged:function(event){var input=event.target;if(this.__isFirstValueUpdate){this.__isFirstValueUpdate=false;if(input.value===undefined){return}}this._handleValueAndAutoValidate(event.target)},_handleValue:function(inputElement){var value=this._inputElementValue;if(value||value===0||inputElement.type==="number"&&!inputElement.checkValidity()){this._inputHasContent=true}else{this._inputHasContent=false}this.updateAddons({inputElement:inputElement,value:value,invalid:this.invalid})},_handleValueAndAutoValidate:function(inputElement){if(this.autoValidate&&inputElement){var valid;if(inputElement.validate){valid=inputElement.validate(this._inputElementValue)}else{valid=inputElement.checkValidity()}this.invalid=!valid}this._handleValue(inputElement)},_onIronInputValidate:function(event){this.invalid=this._inputElement.invalid},_invalidChanged:function(){if(this._addons){this.updateAddons({invalid:this.invalid})}},updateAddons:function(state){for(var addon,index=0;addon=this._addons[index];index++){addon.update(state)}},_computeInputContentClass:function(noLabelFloat,alwaysFloatLabel,focused,invalid,_inputHasContent){var cls="input-content";if(!noLabelFloat){var label=this.querySelector("label");if(alwaysFloatLabel||_inputHasContent){cls+=" label-is-floating";this.$.labelAndInputContainer.style.position="static";if(invalid){cls+=" is-invalid"}else if(focused){cls+=" label-is-highlighted"}}else{if(label){this.$.labelAndInputContainer.style.position="relative"}if(invalid){cls+=" is-invalid"}}}else{if(_inputHasContent){cls+=" label-is-hidden"}if(invalid){cls+=" is-invalid"}}if(focused){cls+=" focused"}return cls},_computeUnderlineClass:function(focused,invalid){var cls="underline";if(invalid){cls+=" is-invalid"}else if(focused){cls+=" is-highlighted"}return cls},_computeAddOnContentClass:function(focused,invalid){var cls="add-on-content";if(invalid){cls+=" is-invalid"}else if(focused){cls+=" is-highlighted"}return cls}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-subpage-search",behaviors:[CrSearchFieldBehavior],properties:{autofocus:Boolean},getSearchInput:function(){return this.$.searchInput},onTapClear_:function(){this.setValue("");this.$.searchInput.focus()}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-subpage",behaviors:[Polymer.NeonAnimatableBehavior,Polymer.IronResizableBehavior],properties:{pageTitle:String,learnMoreUrl:String,searchLabel:String,searchTerm:{type:String,notify:true,value:""},showSpinner:{type:Boolean,value:false},associatedControl:{type:Object,value:null}},attached:function(){if(!!this.searchLabel){this.listen(this,"clear-subpage-search","onClearSubpageSearch_")}},detached:function(){if(!!this.searchLabel){this.unlisten(this,"clear-subpage-search","onClearSubpageSearch_")}},initialFocus:function(){Polymer.RenderStatus.afterNextRender(this,()=>cr.ui.focusWithoutInk(this.$.closeButton))},onClearSubpageSearch_:function(e){e.stopPropagation();this.$$("settings-subpage-search").setValue("")},onTapBack_:function(){settings.navigateToPreviousRoute()},onSearchChanged_:function(e){this.searchTerm=e.detail}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
let FontsData;cr.define("settings",function(){class FontsBrowserProxy{fetchFontsData(){}observeAdvancedFontExtensionAvailable(){}openAdvancedFontSettings(){}}class FontsBrowserProxyImpl{fetchFontsData(){return cr.sendWithPromise("fetchFontsData")}observeAdvancedFontExtensionAvailable(){chrome.send("observeAdvancedFontExtensionAvailable")}openAdvancedFontSettings(){chrome.send("openAdvancedFontSettings")}}cr.addSingletonGetter(FontsBrowserProxyImpl);return{FontsBrowserProxy:FontsBrowserProxy,FontsBrowserProxyImpl:FontsBrowserProxyImpl}});Polymer.IronFormElementBehavior={properties:{name:{type:String},value:{notify:true,type:String},required:{type:Boolean,value:false},_parentForm:{type:Object}},attached(){if(!Polymer.Element){this.fire("iron-form-element-register")}},detached(){if(!Polymer.Element&&this._parentForm){this._parentForm.fire("iron-form-element-unregister",{target:this})}}};Polymer.IronRangeBehavior={properties:{value:{type:Number,value:0,notify:true,reflectToAttribute:true},min:{type:Number,value:0,notify:true},max:{type:Number,value:100,notify:true},step:{type:Number,value:1,notify:true},ratio:{type:Number,value:0,readOnly:true,notify:true}},observers:["_update(value, min, max, step)"],_calcRatio:function(value){return(this._clampValue(value)-this.min)/(this.max-this.min)},_clampValue:function(value){return Math.min(this.max,Math.max(this.min,this._calcStep(value)))},_calcStep:function(value){value=parseFloat(value);if(!this.step){return value}var numSteps=Math.round((value-this.min)/this.step);if(this.step<1){return numSteps/(1/this.step)+this.min}else{return numSteps*this.step+this.min}},_validateValue:function(){var v=this._clampValue(this.value);this.value=this.oldValue=isNaN(v)?this.oldValue:v;return this.value!==v},_update:function(){this._validateValue();this._setRatio(this._calcRatio(this.value)*100)}};Polymer.IronValidatableBehaviorMeta=null;Polymer.IronValidatableBehavior={properties:{validator:{type:String},invalid:{notify:true,reflectToAttribute:true,type:Boolean,value:false,observer:"_invalidChanged"}},registered:function(){Polymer.IronValidatableBehaviorMeta=new Polymer.IronMeta({type:"validator"})},_invalidChanged:function(){if(this.invalid){this.setAttribute("aria-invalid","true")}else{this.removeAttribute("aria-invalid")}},get _validator(){return Polymer.IronValidatableBehaviorMeta&&Polymer.IronValidatableBehaviorMeta.byKey(this.validator)},hasValidator:function(){return this._validator!=null},validate:function(value){if(value===undefined&&this.value!==undefined)this.invalid=!this._getValidity(this.value);else this.invalid=!this._getValidity(value);return!this.invalid},_getValidity:function(value){if(this.hasValidator()){return this._validator.validate(value)}return true}};Polymer({is:"iron-input",behaviors:[Polymer.IronValidatableBehavior],properties:{bindValue:{type:String,value:""},value:{type:String,computed:"_computeValue(bindValue)"},allowedPattern:{type:String},autoValidate:{type:Boolean,value:false},_inputElement:Object},observers:["_bindValueChanged(bindValue, _inputElement)"],listeners:{input:"_onInput",keypress:"_onKeypress"},created:function(){Polymer.IronA11yAnnouncer.requestAvailability();this._previousValidInput="";this._patternAlreadyChecked=false},attached:function(){this._observer=Polymer.dom(this).observeNodes(function(info){this._initSlottedInput()}.bind(this))},detached:function(){if(this._observer){Polymer.dom(this).unobserveNodes(this._observer);this._observer=null}},get inputElement(){return this._inputElement},_initSlottedInput:function(){this._inputElement=this.getEffectiveChildren()[0];if(this.inputElement&&this.inputElement.value){this.bindValue=this.inputElement.value}this.fire("iron-input-ready")},get _patternRegExp(){var pattern;if(this.allowedPattern){pattern=new RegExp(this.allowedPattern)}else{switch(this.inputElement.type){case"number":pattern=/[0-9.,e-]/;break}}return pattern},_bindValueChanged:function(bindValue,inputElement){if(!inputElement){return}if(bindValue===undefined){inputElement.value=null}else if(bindValue!==inputElement.value){this.inputElement.value=bindValue}if(this.autoValidate){this.validate()}this.fire("bind-value-changed",{value:bindValue})},_onInput:function(){if(this.allowedPattern&&!this._patternAlreadyChecked){var valid=this._checkPatternValidity();if(!valid){this._announceInvalidCharacter("Invalid string of characters not entered.");this.inputElement.value=this._previousValidInput}}this.bindValue=this._previousValidInput=this.inputElement.value;this._patternAlreadyChecked=false},_isPrintable:function(event){var anyNonPrintable=event.keyCode==8||event.keyCode==9||event.keyCode==13||event.keyCode==27;var mozNonPrintable=event.keyCode==19||event.keyCode==20||event.keyCode==45||event.keyCode==46||event.keyCode==144||event.keyCode==145||event.keyCode>32&&event.keyCode<41||event.keyCode>111&&event.keyCode<124;return!anyNonPrintable&&!(event.charCode==0&&mozNonPrintable)},_onKeypress:function(event){if(!this.allowedPattern&&this.inputElement.type!=="number"){return}var regexp=this._patternRegExp;if(!regexp){return}if(event.metaKey||event.ctrlKey||event.altKey){return}this._patternAlreadyChecked=true;var thisChar=String.fromCharCode(event.charCode);if(this._isPrintable(event)&&!regexp.test(thisChar)){event.preventDefault();this._announceInvalidCharacter("Invalid character "+thisChar+" not entered.")}},_checkPatternValidity:function(){var regexp=this._patternRegExp;if(!regexp){return true}for(var i=0;i<this.inputElement.value.length;i++){if(!regexp.test(this.inputElement.value[i])){return false}}return true},validate:function(){if(!this.inputElement){this.invalid=false;return true}var valid=this.inputElement.checkValidity();if(valid){if(this.required&&this.bindValue===""){valid=false}else if(this.hasValidator()){valid=Polymer.IronValidatableBehavior.validate.call(this,this.bindValue)}}this.invalid=!valid;this.fire("iron-input-validate");return valid},_announceInvalidCharacter:function(message){this.fire("iron-announce",{text:message})},_computeValue:function(bindValue){return bindValue}});Polymer.PaperInputHelper={};Polymer.PaperInputHelper.NextLabelID=1;Polymer.PaperInputHelper.NextAddonID=1;Polymer.PaperInputHelper.NextInputID=1;Polymer.PaperInputBehaviorImpl={properties:{label:{type:String},value:{notify:true,type:String},disabled:{type:Boolean,value:false},invalid:{type:Boolean,value:false,notify:true},allowedPattern:{type:String},type:{type:String},list:{type:String},pattern:{type:String},required:{type:Boolean,value:false},errorMessage:{type:String},charCounter:{type:Boolean,value:false},noLabelFloat:{type:Boolean,value:false},alwaysFloatLabel:{type:Boolean,value:false},autoValidate:{type:Boolean,value:false},validator:{type:String},autocomplete:{type:String,value:"off"},autofocus:{type:Boolean,observer:"_autofocusChanged"},inputmode:{type:String},minlength:{type:Number},maxlength:{type:Number},min:{type:String},max:{type:String},step:{type:String},name:{type:String},placeholder:{type:String,value:""},readonly:{type:Boolean,value:false},size:{type:Number},autocapitalize:{type:String,value:"none"},autocorrect:{type:String,value:"off"},autosave:{type:String},results:{type:Number},accept:{type:String},multiple:{type:Boolean},_ariaDescribedBy:{type:String,value:""},_ariaLabelledBy:{type:String,value:""},_inputId:{type:String,value:""}},listeners:{"addon-attached":"_onAddonAttached"},keyBindings:{"shift+tab:keydown":"_onShiftTabDown"},hostAttributes:{tabindex:0},get inputElement(){if(!this.$){this.$={}}if(!this.$.input){this._generateInputId();this.$.input=this.$$("#"+this._inputId)}return this.$.input},get _focusableElement(){return this.inputElement},created:function(){this._typesThatHaveText=["date","datetime","datetime-local","month","time","week","file"]},attached:function(){this._updateAriaLabelledBy();if(!Polymer.Element&&this.inputElement&&this._typesThatHaveText.indexOf(this.inputElement.type)!==-1){this.alwaysFloatLabel=true}},_appendStringWithSpace:function(str,more){if(str){str=str+" "+more}else{str=more}return str},_onAddonAttached:function(event){var target=Polymer.dom(event).rootTarget;if(target.id){this._ariaDescribedBy=this._appendStringWithSpace(this._ariaDescribedBy,target.id)}else{var id="paper-input-add-on-"+Polymer.PaperInputHelper.NextAddonID++;target.id=id;this._ariaDescribedBy=this._appendStringWithSpace(this._ariaDescribedBy,id)}},validate:function(){return this.inputElement.validate()},_focusBlurHandler:function(event){Polymer.IronControlState._focusBlurHandler.call(this,event);if(this.focused&&!this._shiftTabPressed&&this._focusableElement){this._focusableElement.focus()}},_onShiftTabDown:function(event){var oldTabIndex=this.getAttribute("tabindex");this._shiftTabPressed=true;this.setAttribute("tabindex","-1");this.async(function(){this.setAttribute("tabindex",oldTabIndex);this._shiftTabPressed=false},1)},_handleAutoValidate:function(){if(this.autoValidate)this.validate()},updateValueAndPreserveCaret:function(newValue){try{var start=this.inputElement.selectionStart;this.value=newValue;this.inputElement.selectionStart=start;this.inputElement.selectionEnd=start}catch(e){this.value=newValue}},_computeAlwaysFloatLabel:function(alwaysFloatLabel,placeholder){return placeholder||alwaysFloatLabel},_updateAriaLabelledBy:function(){var label=Polymer.dom(this.root).querySelector("label");if(!label){this._ariaLabelledBy="";return}var labelledBy;if(label.id){labelledBy=label.id}else{labelledBy="paper-input-label-"+Polymer.PaperInputHelper.NextLabelID++;label.id=labelledBy}this._ariaLabelledBy=labelledBy},_generateInputId:function(){if(!this._inputId||this._inputId===""){this._inputId="input-"+Polymer.PaperInputHelper.NextInputID++}},_onChange:function(event){if(this.shadowRoot){this.fire(event.type,{sourceEvent:event},{node:this,bubbles:event.bubbles,cancelable:event.cancelable})}},_autofocusChanged:function(){if(this.autofocus&&this._focusableElement){var activeElement=document.activeElement;var isActiveElementValid=activeElement instanceof HTMLElement;var isSomeElementActive=isActiveElementValid&&activeElement!==document.body&&activeElement!==document.documentElement;if(!isSomeElementActive){this._focusableElement.focus()}}}};Polymer.PaperInputBehavior=[Polymer.IronControlState,Polymer.IronA11yKeysBehavior,Polymer.PaperInputBehaviorImpl];Polymer.PaperInputAddonBehavior={attached:function(){Polymer.dom.flush();this.fire("addon-attached")},update:function(state){}};Polymer({is:"paper-input-char-counter",behaviors:[Polymer.PaperInputAddonBehavior],properties:{_charCounterStr:{type:String,value:"0"}},update:function(state){if(!state.inputElement){return}state.value=state.value||"";var counter=state.value.toString().length.toString();if(state.inputElement.hasAttribute("maxlength")){counter+="/"+state.inputElement.getAttribute("maxlength")}this._charCounterStr=counter}});Polymer({is:"paper-input-error",behaviors:[Polymer.PaperInputAddonBehavior],properties:{invalid:{readOnly:true,reflectToAttribute:true,type:Boolean}},update:function(state){this._setInvalid(state.invalid)}});Polymer({is:"paper-input",behaviors:[Polymer.PaperInputBehavior,Polymer.IronFormElementBehavior],beforeRegister:function(){var version="v1";var template=Polymer.DomModule.import("paper-input","template");var inputTemplate=Polymer.DomModule.import("paper-input","template#"+version);var inputPlaceholder=template.content.querySelector("#template-placeholder");if(inputPlaceholder){inputPlaceholder.parentNode.replaceChild(inputTemplate.content,inputPlaceholder)}},get _focusableElement(){return this.inputElement._inputElement},listeners:{"iron-input-ready":"_onIronInputReady"},_onIronInputReady:function(){if(!this.$.nativeInput){this.$.nativeInput=this.$$("input")}if(this.inputElement&&this._typesThatHaveText.indexOf(this.$.nativeInput.type)!==-1){this.alwaysFloatLabel=true}if(!!this.inputElement.bindValue){this.$.container._handleValueAndAutoValidate(this.inputElement)}}});Polymer({is:"paper-progress",behaviors:[Polymer.IronRangeBehavior],properties:{secondaryProgress:{type:Number,value:0},secondaryRatio:{type:Number,value:0,readOnly:true},indeterminate:{type:Boolean,value:false,observer:"_toggleIndeterminate"},disabled:{type:Boolean,value:false,reflectToAttribute:true,observer:"_disabledChanged"}},observers:["_progressChanged(secondaryProgress, value, min, max, indeterminate)"],hostAttributes:{role:"progressbar"},_toggleIndeterminate:function(indeterminate){this.toggleClass("indeterminate",indeterminate,this.$.primaryProgress)},_transformProgress:function(progress,ratio){var transform="scaleX("+ratio/100+")";progress.style.transform=progress.style.webkitTransform=transform},_mainRatioChanged:function(ratio){this._transformProgress(this.$.primaryProgress,ratio)},_progressChanged:function(secondaryProgress,value,min,max,indeterminate){secondaryProgress=this._clampValue(secondaryProgress);value=this._clampValue(value);var secondaryRatio=this._calcRatio(secondaryProgress)*100;var mainRatio=this._calcRatio(value)*100;this._setSecondaryRatio(secondaryRatio);this._transformProgress(this.$.secondaryProgress,secondaryRatio);this._transformProgress(this.$.primaryProgress,mainRatio);this.secondaryProgress=secondaryProgress;if(indeterminate){this.removeAttribute("aria-valuenow")}else{this.setAttribute("aria-valuenow",value)}this.setAttribute("aria-valuemin",min);this.setAttribute("aria-valuemax",max)},_disabledChanged:function(disabled){this.setAttribute("aria-disabled",disabled?"true":"false")},_hideSecondaryProgress:function(secondaryRatio){return secondaryRatio===0}});Polymer({is:"paper-slider",behaviors:[Polymer.IronA11yKeysBehavior,Polymer.IronFormElementBehavior,Polymer.PaperInkyFocusBehavior,Polymer.IronRangeBehavior],properties:{snaps:{type:Boolean,value:false,notify:true},pin:{type:Boolean,value:false,notify:true},secondaryProgress:{type:Number,value:0,notify:true,observer:"_secondaryProgressChanged"},editable:{type:Boolean,value:false},immediateValue:{type:Number,value:0,readOnly:true,notify:true},maxMarkers:{type:Number,value:0,notify:true},expand:{type:Boolean,value:false,readOnly:true},dragging:{type:Boolean,value:false,readOnly:true},transiting:{type:Boolean,value:false,readOnly:true},markers:{type:Array,readOnly:true,value:function(){return[]}}},observers:["_updateKnob(value, min, max, snaps, step)","_valueChanged(value)","_immediateValueChanged(immediateValue)","_updateMarkers(maxMarkers, min, max, snaps)"],hostAttributes:{role:"slider",tabindex:0},keyBindings:{left:"_leftKey",right:"_rightKey","down pagedown home":"_decrementKey","up pageup end":"_incrementKey"},increment:function(){this.value=this._clampValue(this.value+this.step)},decrement:function(){this.value=this._clampValue(this.value-this.step)},_updateKnob:function(value,min,max,snaps,step){this.setAttribute("aria-valuemin",min);this.setAttribute("aria-valuemax",max);this.setAttribute("aria-valuenow",value);this._positionKnob(this._calcRatio(value)*100)},_valueChanged:function(){this.fire("value-change",{composed:true})},_immediateValueChanged:function(){if(this.dragging){this.fire("immediate-value-change",{composed:true})}else{this.value=this.immediateValue}},_secondaryProgressChanged:function(){this.secondaryProgress=this._clampValue(this.secondaryProgress)},_expandKnob:function(){this._setExpand(true)},_resetKnob:function(){this.cancelDebouncer("expandKnob");this._setExpand(false)},_positionKnob:function(ratio){this._setImmediateValue(this._calcStep(this._calcKnobPosition(ratio)));this._setRatio(this._calcRatio(this.immediateValue)*100);this.$.sliderKnob.style.left=this.ratio+"%";if(this.dragging){this._knobstartx=this.ratio*this._w/100;this.translate3d(0,0,0,this.$.sliderKnob)}},_calcKnobPosition:function(ratio){return(this.max-this.min)*ratio/100+this.min},_onTrack:function(event){event.stopPropagation();switch(event.detail.state){case"start":this._trackStart(event);break;case"track":this._trackX(event);break;case"end":this._trackEnd();break}},_trackStart:function(event){this._setTransiting(false);this._w=this.$.sliderBar.offsetWidth;this._x=this.ratio*this._w/100;this._startx=this._x;this._knobstartx=this._startx;this._minx=-this._startx;this._maxx=this._w-this._startx;this.$.sliderKnob.classList.add("dragging");this._setDragging(true)},_trackX:function(event){if(!this.dragging){this._trackStart(event)}var direction=this._isRTL?-1:1;var dx=Math.min(this._maxx,Math.max(this._minx,event.detail.dx*direction));this._x=this._startx+dx;var immediateValue=this._calcStep(this._calcKnobPosition(this._x/this._w*100));this._setImmediateValue(immediateValue);var translateX=this._calcRatio(this.immediateValue)*this._w-this._knobstartx;this.translate3d(translateX+"px",0,0,this.$.sliderKnob)},_trackEnd:function(){var s=this.$.sliderKnob.style;this.$.sliderKnob.classList.remove("dragging");this._setDragging(false);this._resetKnob();this.value=this.immediateValue;s.transform=s.webkitTransform="";this.fire("change",{composed:true})},_knobdown:function(event){this._expandKnob();event.preventDefault();this.focus()},_bardown:function(event){this._w=this.$.sliderBar.offsetWidth;var rect=this.$.sliderBar.getBoundingClientRect();var ratio=(event.detail.x-rect.left)/this._w*100;if(this._isRTL){ratio=100-ratio}var prevRatio=this.ratio;this._setTransiting(true);this._positionKnob(ratio);this.debounce("expandKnob",this._expandKnob,60);if(prevRatio===this.ratio){this._setTransiting(false)}this.async(function(){this.fire("change",{composed:true})});event.preventDefault();this.focus()},_knobTransitionEnd:function(event){if(event.target===this.$.sliderKnob){this._setTransiting(false)}},_updateMarkers:function(maxMarkers,min,max,snaps){if(!snaps){this._setMarkers([])}var steps=Math.round((max-min)/this.step);if(steps>maxMarkers){steps=maxMarkers}if(steps<0||!isFinite(steps)){steps=0}this._setMarkers(new Array(steps))},_mergeClasses:function(classes){return Object.keys(classes).filter(function(className){return classes[className]}).join(" ")},_getClassNames:function(){return this._mergeClasses({disabled:this.disabled,pin:this.pin,snaps:this.snaps,ring:this.immediateValue<=this.min,expand:this.expand,dragging:this.dragging,transiting:this.transiting,editable:this.editable})},get _isRTL(){if(this.__isRTL===undefined){this.__isRTL=window.getComputedStyle(this)["direction"]==="rtl"}return this.__isRTL},_leftKey:function(event){if(this._isRTL)this._incrementKey(event);else this._decrementKey(event)},_rightKey:function(event){if(this._isRTL)this._decrementKey(event);else this._incrementKey(event)},_incrementKey:function(event){if(!this.disabled){if(event.detail.key==="end"){this.value=this.max}else{this.increment()}this.fire("change");event.preventDefault()}},_decrementKey:function(event){if(!this.disabled){if(event.detail.key==="home"){this.value=this.min}else{this.decrement()}this.fire("change");event.preventDefault()}},_changeValue:function(event){this.value=event.target.value;this.fire("change",{composed:true})},_inputKeyDown:function(event){event.stopPropagation()},_createRipple:function(){this._rippleContainer=this.$.sliderKnob;return Polymer.PaperInkyFocusBehaviorImpl._createRipple.call(this)},_focusedChanged:function(receivedFocusFromKeyboard){if(receivedFocusFromKeyboard){this.ensureRipple()}if(this.hasRipple()){if(receivedFocusFromKeyboard){this._ripple.style.display=""}else{this._ripple.style.display="none"}this._ripple.holdDown=receivedFocusFromKeyboard}}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-slider",behaviors:[CrPolicyPrefBehavior],properties:{pref:Object,tickValues:{type:Array,value:[]},scale:{type:Number,value:1},min:Number,max:Number,labelMin:String,labelMax:String,disabled:Boolean,disableSlider_:{computed:"computeDisableSlider_(pref.*, disabled)",type:Boolean}},observers:["valueChanged_(pref.*, tickValues.*)"],onSliderChanged_:function(){const sliderValue=isNaN(this.$.slider.immediateValue)?this.$.slider.value:this.$.slider.immediateValue;let newValue;if(this.tickValues&&this.tickValues.length>0)newValue=this.tickValues[sliderValue];else newValue=sliderValue/this.scale;this.set("pref.value",newValue)},computeDisableSlider_:function(){return this.disabled||this.isPrefEnforced()},valueChanged_:function(){if(this.tickValues.length==0){this.$.slider.value=this.pref.value*this.scale;return}assert(this.scale==1);const numTicks=Math.max(1,this.tickValues.length);this.$.slider.max=numTicks-1;const MAX_TICKS=10;this.$.slider.snaps=numTicks<MAX_TICKS;this.$.slider.maxMarkers=numTicks<MAX_TICKS?numTicks:0;if(this.$.slider.dragging&&this.tickValues.length>0&&this.pref.value!=this.tickValues[this.$.slider.immediateValue]){this.async(function(){const newValue=this.tickValues[this.$.slider.immediateValue];this.set("pref.value",newValue)});return}let sliderIndex=this.tickValues.length>0?this.tickValues.indexOf(this.pref.value):0;if(sliderIndex==-1){sliderIndex=this.findNearestIndex_(this.tickValues,this.pref.value)}this.$.slider.value=sliderIndex},findNearestIndex_:function(arr,value){let closestIndex;let minDifference=Number.MAX_VALUE;for(let i=0;i<arr.length;i++){const difference=Math.abs(arr[i]-value);if(difference<minDifference){closestIndex=i;minDifference=difference}}assert(typeof closestIndex!="undefined");return closestIndex},resetTrackLock_:function(){Polymer.Gestures.gestures.tap.reset()}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
(function(){"use strict";const FONT_SIZE_RANGE=[9,10,11,12,13,14,15,16,17,18,20,22,24,26,28,30,32,34,36,40,44,48,56,64,72];const MINIMUM_FONT_SIZE_RANGE=[6,7,8,9,10,11,12,13,14,15,16,17,18,20,22,24];Polymer({is:"settings-appearance-fonts-page",behaviors:[I18nBehavior,WebUIListenerBehavior],properties:{advancedExtensionSublabel_:String,fontOptions_:Object,isGuest_:{type:Boolean,value:function(){return loadTimeData.getBoolean("isGuest")}},fontSizeRange_:{readOnly:true,type:Array,value:FONT_SIZE_RANGE},minimumFontSizeRange_:{readOnly:true,type:Array,value:MINIMUM_FONT_SIZE_RANGE},prefs:{type:Object,notify:true}},browserProxy_:null,advancedExtensionInstalled_:false,advancedExtensionUrl_:null,created:function(){this.browserProxy_=settings.FontsBrowserProxyImpl.getInstance()},ready:function(){this.addWebUIListener("advanced-font-settings-installed",this.setAdvancedExtensionInstalled_.bind(this));this.browserProxy_.observeAdvancedFontExtensionAvailable();this.browserProxy_.fetchFontsData().then(this.setFontsData_.bind(this))},openAdvancedExtension_:function(){if(this.advancedExtensionInstalled_)this.browserProxy_.openAdvancedFontSettings();else window.open(this.advancedExtensionUrl_)},setAdvancedExtensionInstalled_:function(isInstalled){this.advancedExtensionInstalled_=isInstalled;this.advancedExtensionSublabel_=this.i18n(isInstalled?"openAdvancedFontSettings":"requiresWebStoreExtension")},setFontsData_:function(response){const fontMenuOptions=[];for(const fontData of response.fontList){fontMenuOptions.push({value:fontData[0],name:fontData[1]})}this.fontOptions_=fontMenuOptions;this.advancedExtensionUrl_=response.extensionUrl},computeMinimumFontSize_:function(){return this.get("prefs.webkit.webprefs.minimum_font_size.value")||MINIMUM_FONT_SIZE_RANGE[0]}})})();
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"home-url-input",behaviors:[CrPolicyPrefBehavior,PrefControlBehavior],properties:{pref:{observer:"prefChanged_"},disabled:{type:Boolean,value:false,reflectToAttribute:true},canTab:Boolean,invalid:{type:Boolean,value:false},value:{type:String,value:"",notify:true}},browserProxy_:null,created:function(){this.browserProxy_=settings.AppearanceBrowserProxyImpl.getInstance();this.noExtensionIndicator=true},focus:function(){this.$.input.focus()},prefChanged_:function(){if(!this.pref)return;if(this.$.input.focused)return;this.setInputValueFromPref_()},setInputValueFromPref_:function(){assert(this.pref.type==chrome.settingsPrivate.PrefType.URL);this.value=this.pref.value},getTabindex_:function(canTab){return canTab?0:-1},onChange_:function(){if(this.invalid){this.resetValue_();return}assert(this.pref.type==chrome.settingsPrivate.PrefType.URL);this.set("pref.value",this.value)},resetValue_:function(){this.invalid=false;this.setInputValueFromPref_();this.$.input.blur()},onKeydown_:function(event){if(event.key=="Enter"&&this.invalid)event.preventDefault();else if(event.key=="Escape")this.resetValue_()},isDisabled_:function(disabled){return disabled||this.isPrefEnforced()},validate_:function(){if(this.value==""){this.invalid=false;return}this.browserProxy_.validateStartupPage(this.value).then(isValid=>{this.invalid=!isValid})}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
(function(){"use strict";const SIZE_DIFFERENCE_FIXED_STANDARD=3;Polymer({is:"settings-appearance-page",behaviors:[I18nBehavior],properties:{pageVisibility:Object,prefs:{type:Object,notify:true},defaultZoom_:Number,isWallpaperPolicyControlled_:{type:Boolean,value:true},fontSizeOptions_:{readOnly:true,type:Array,value:function(){return[{value:9,name:loadTimeData.getString("verySmall")},{value:12,name:loadTimeData.getString("small")},{value:16,name:loadTimeData.getString("medium")},{value:20,name:loadTimeData.getString("large")},{value:24,name:loadTimeData.getString("veryLarge")}]}},pageZoomLevels_:{readOnly:true,type:Array,value:[1/4,1/3,1/2,2/3,3/4,4/5,9/10,1,11/10,5/4,3/2,7/4,2,5/2,3,4,5]},themeSublabel_:String,themeUrl_:String,useSystemTheme_:{type:Boolean,value:false},focusConfig_:{type:Object,value:function(){const map=new Map;if(settings.routes.FONTS){map.set(settings.routes.FONTS.path,"#customize-fonts-subpage-trigger")}return map}}},browserProxy_:null,observers:["defaultFontSizeChanged_(prefs.webkit.webprefs.default_font_size.value)","themeChanged_(prefs.extensions.theme.id.value, useSystemTheme_)","useSystemThemePrefChanged_(prefs.extensions.theme.use_system.value)"],created:function(){this.browserProxy_=settings.AppearanceBrowserProxyImpl.getInstance()},ready:function(){this.$.defaultFontSize.menuOptions=this.fontSizeOptions_;this.browserProxy_.getDefaultZoom().then(zoom=>{this.defaultZoom_=zoom})},formatZoom_:function(zoom){return Math.round(zoom*100)},getShowHomeSubLabel_:function(showHomepage,isNtp,homepageValue){if(!showHomepage)return this.i18n("homeButtonDisabled");if(isNtp)return this.i18n("homePageNtp");return homepageValue||this.i18n("customWebAddress")},onCustomizeFontsTap_:function(){settings.navigateTo(settings.routes.FONTS)},onDisableExtension_:function(){this.fire("refresh-pref","homepage")},defaultFontSizeChanged_:function(value){this.set("prefs.webkit.webprefs.default_fixed_font_size.value",value-SIZE_DIFFERENCE_FIXED_STANDARD)},openThemeUrl_:function(){window.open(this.themeUrl_||loadTimeData.getString("themesGalleryUrl"))},onUseDefaultTap_:function(){this.browserProxy_.useDefaultTheme()},useSystemThemePrefChanged_:function(useSystemTheme){this.useSystemTheme_=useSystemTheme},showUseClassic_:function(themeId,useSystemTheme){return!!themeId||useSystemTheme},showUseSystem_:function(themeId,useSystemTheme){return(!!themeId||!useSystemTheme)&&!this.browserProxy_.isSupervised()},showThemesSecondary_:function(themeId,useSystemTheme){return this.showUseClassic_(themeId,useSystemTheme)||this.showUseSystem_(themeId,useSystemTheme)},onUseSystemTap_:function(){this.browserProxy_.useSystemTheme()},themeChanged_:function(themeId,useSystemTheme){if(themeId.length>0){assert(!useSystemTheme);this.browserProxy_.getThemeInfo(themeId).then(info=>{this.themeSublabel_=info.name});this.themeUrl_="https://chrome.google.com/webstore/detail/"+themeId;return}let i18nId;i18nId=useSystemTheme?"systemTheme":"classicTheme";this.themeSublabel_=this.i18n(i18nId);this.themeUrl_=""},onZoomLevelChange_:function(){chrome.settingsPrivate.setDefaultZoom(parseFloat(this.$.zoomLevel.value))},getFirst_:function(bookmarksBarVisible){return!bookmarksBarVisible?"first":""},zoomValuesEqual_:function(zoom1,zoom2){return Math.abs(zoom1-zoom2)<=.001}})})();
|
|
// Copyright 2017 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.define("settings",function(){class ChangePasswordBrowserProxy{initializeChangePasswordHandler(){}changePassword(){}}class ChangePasswordBrowserProxyImpl{initializeChangePasswordHandler(){chrome.send("initializeChangePasswordHandler")}changePassword(){chrome.send("changePassword")}}cr.addSingletonGetter(ChangePasswordBrowserProxyImpl);return{ChangePasswordBrowserProxy:ChangePasswordBrowserProxy,ChangePasswordBrowserProxyImpl:ChangePasswordBrowserProxyImpl}});
|
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
function $(id){var el=document.getElementById(id);return el?assertInstanceof(el,HTMLElement):null}function getSVGElement(id){var el=document.getElementById(id);return el?assertInstanceof(el,Element):null}function announceAccessibleMessage(msg){var element=document.createElement("div");element.setAttribute("aria-live","polite");element.style.position="fixed";element.style.left="-9999px";element.style.height="0px";element.innerText=msg;document.body.appendChild(element);window.setTimeout(function(){document.body.removeChild(element)},0)}function getUrlForCss(s){var s2=s.replace(/(\(|\)|\,|\s|\'|\"|\\)/g,"\\$1");if(/\\\\$/.test(s2)){s2+=" "}return'url("'+s2+'")'}function parseQueryParams(location){var params={};var query=unescape(location.search.substring(1));var vars=query.split("&");for(var i=0;i<vars.length;i++){var pair=vars[i].split("=");params[pair[0]]=pair[1]}return params}function setQueryParam(location,key,value){var query=parseQueryParams(location);query[encodeURIComponent(key)]=encodeURIComponent(value);var newQuery="";for(var q in query){newQuery+=(newQuery?"&":"?")+q+"="+query[q]}return location.origin+location.pathname+newQuery+location.hash}function findAncestorByClass(el,className){return findAncestor(el,function(el){return el.classList&&el.classList.contains(className)})}function findAncestor(node,predicate){var last=false;while(node!=null&&!(last=predicate(node))){node=node.parentNode}return last?node:null}function swapDomNodes(a,b){var afterA=a.nextSibling;if(afterA==b){swapDomNodes(b,a);return}var aParent=a.parentNode;b.parentNode.replaceChild(a,b);aParent.insertBefore(b,afterA)}function disableTextSelectAndDrag(opt_allowSelectStart,opt_allowDragStart){document.onselectstart=function(e){if(!(opt_allowSelectStart&&opt_allowSelectStart.call(this,e)))e.preventDefault()};document.ondragstart=function(e){if(!(opt_allowDragStart&&opt_allowDragStart.call(this,e)))e.preventDefault()}}function isRTL(){return document.documentElement.dir=="rtl"}function getRequiredElement(id){return assertInstanceof($(id),HTMLElement,"Missing required element: "+id)}function queryRequiredElement(selectors,opt_context){var element=(opt_context||document).querySelector(selectors);return assertInstanceof(element,HTMLElement,"Missing required element: "+selectors)}["click","auxclick"].forEach(function(eventName){document.addEventListener(eventName,function(e){if(e.button>1)return;if(e.defaultPrevented)return;var eventPath=e.path;var anchor=null;if(eventPath){for(var i=0;i<eventPath.length;i++){var element=eventPath[i];if(element.tagName==="A"&&element.href){anchor=element;break}}}var el=e.target;if(!anchor&&el.nodeType==Node.ELEMENT_NODE&&el.webkitMatchesSelector("A, A *")){while(el.tagName!="A"){el=el.parentElement}anchor=el}if(!anchor)return;anchor=anchor;if((anchor.protocol=="file:"||anchor.protocol=="about:")&&(e.button==0||e.button==1)){chrome.send("navigateToUrl",[anchor.href,anchor.target,e.button,e.altKey,e.ctrlKey,e.metaKey,e.shiftKey]);e.preventDefault()}})});function appendParam(url,key,value){var param=encodeURIComponent(key)+"="+encodeURIComponent(value);if(url.indexOf("?")==-1)return url+"?"+param;return url+"&"+param}function createElementWithClassName(type,className){var elm=document.createElement(type);elm.className=className;return elm}function ensureTransitionEndEvent(el,opt_timeOut){if(opt_timeOut===undefined){var style=getComputedStyle(el);opt_timeOut=parseFloat(style.transitionDuration)*1e3;opt_timeOut+=50}var fired=false;el.addEventListener("transitionend",function f(e){el.removeEventListener("transitionend",f);fired=true});window.setTimeout(function(){if(!fired)cr.dispatchSimpleEvent(el,"transitionend",true)},opt_timeOut)}function scrollTopForDocument(doc){return doc.documentElement.scrollTop||doc.body.scrollTop}function setScrollTopForDocument(doc,value){doc.documentElement.scrollTop=doc.body.scrollTop=value}function scrollLeftForDocument(doc){return doc.documentElement.scrollLeft||doc.body.scrollLeft}function setScrollLeftForDocument(doc,value){doc.documentElement.scrollLeft=doc.body.scrollLeft=value}function HTMLEscape(original){return original.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function elide(original,maxLength){if(original.length<=maxLength)return original;return original.substring(0,maxLength-1)+"…"}function quoteString(str){return str.replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g,"\\$1")}function listenOnce(target,eventNames,callback){if(!Array.isArray(eventNames))eventNames=eventNames.split(/ +/);var removeAllAndCallCallback=function(event){eventNames.forEach(function(eventName){target.removeEventListener(eventName,removeAllAndCallCallback,false)});return callback(event)};eventNames.forEach(function(eventName){target.addEventListener(eventName,removeAllAndCallCallback,false)})}
|
|
// <if expr="is_ios">
|
|
if(!("key"in KeyboardEvent.prototype)){Object.defineProperty(KeyboardEvent.prototype,"key",{get:function(){if(this.keyCode>=48&&this.keyCode<=57)return String.fromCharCode(this.keyCode);if(this.keyCode>=65&&this.keyCode<=90){var result=String.fromCharCode(this.keyCode).toLowerCase();if(this.shiftKey)result=result.toUpperCase();return result}switch(this.keyCode){case 8:return"Backspace";case 9:return"Tab";case 13:return"Enter";case 16:return"Shift";case 17:return"Control";case 18:return"Alt";case 27:return"Escape";case 32:return" ";case 33:return"PageUp";case 34:return"PageDown";case 35:return"End";case 36:return"Home";case 37:return"ArrowLeft";case 38:return"ArrowUp";case 39:return"ArrowRight";case 40:return"ArrowDown";case 45:return"Insert";case 46:return"Delete";case 91:return"Meta";case 112:return"F1";case 113:return"F2";case 114:return"F3";case 115:return"F4";case 116:return"F5";case 117:return"F6";case 118:return"F7";case 119:return"F8";case 120:return"F9";case 121:return"F10";case 122:return"F11";case 123:return"F12";case 187:return"=";case 189:return"-";case 219:return"[";case 221:return"]"}return"Unidentified"}})}else{window.console.log("KeyboardEvent.Key polyfill not required")}
|
|
// </if> /* is_ios */
|
|
function hasKeyModifiers(e){return!!(e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)}
|
|
// Copyright 2017 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-change-password-page",changePassword_:function(){listenOnce(this,"transitionend",()=>{settings.ChangePasswordBrowserProxyImpl.getInstance().changePassword()})}});
|
|
// Copyright 2017 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-idle-load",extends:"template",behaviors:[Polymer.Templatizer],properties:{url:String},child_:null,idleCallback_:0,attached:function(){this.idleCallback_=requestIdleCallback(this.get.bind(this))},detached:function(){cancelIdleCallback(this.idleCallback_)},get:function(){if(this.loading_)return this.loading_;this.loading_=new Promise((resolve,reject)=>{this.importHref(this.url,()=>{assert(!this.ctor);this.templatize(this);assert(this.ctor);const instance=this.stamp({});assert(!this.child_);this.child_=instance.root.firstElementChild;this.parentNode.insertBefore(instance.root,this);resolve(this.child_);this.fire("lazy-loaded")},reject,true)});return this.loading_},_forwardParentProp:function(prop,value){if(this.child_)this.child_._templateInstance[prop]=value},_forwardParentPath:function(path,value){if(this.child_)this.child_._templateInstance.notifyPath(path,value,true)}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
let NtpExtension;cr.define("settings",function(){class OnStartupBrowserProxy{getNtpExtension(){}}class OnStartupBrowserProxyImpl{getNtpExtension(){return cr.sendWithPromise("getNtpExtension")}}cr.addSingletonGetter(OnStartupBrowserProxyImpl);return{OnStartupBrowserProxy:OnStartupBrowserProxy,OnStartupBrowserProxyImpl:OnStartupBrowserProxyImpl}});
|
|
// Copyright 2014 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
var ActionLink=document.registerElement("action-link",{prototype:{__proto__:HTMLAnchorElement.prototype,createdCallback:function(){this.tabIndex=this.disabled?-1:0;if(!this.hasAttribute("role"))this.setAttribute("role","link");this.addEventListener("keydown",function(e){if(!this.disabled&&e.key=="Enter"&&!this.href){window.setTimeout(this.click.bind(this),0)}});function preventDefault(e){e.preventDefault()}function removePreventDefault(){document.removeEventListener("selectstart",preventDefault);document.removeEventListener("mouseup",removePreventDefault)}this.addEventListener("mousedown",function(){document.addEventListener("selectstart",preventDefault);document.addEventListener("mouseup",removePreventDefault);if(document.activeElement!=this)this.classList.add("no-outline")});this.addEventListener("blur",function(){this.classList.remove("no-outline")})},set disabled(disabled){if(disabled)HTMLAnchorElement.prototype.setAttribute.call(this,"disabled","");else HTMLAnchorElement.prototype.removeAttribute.call(this,"disabled");this.tabIndex=disabled?-1:0},get disabled(){return this.hasAttribute("disabled")},setAttribute:function(attr,val){if(attr.toLowerCase()=="disabled")this.disabled=true;else HTMLAnchorElement.prototype.setAttribute.apply(this,arguments)},removeAttribute:function(attr){if(attr.toLowerCase()=="disabled")this.disabled=false;else HTMLAnchorElement.prototype.removeAttribute.apply(this,arguments)}},extends:"a"});Polymer.IronScrollTargetBehavior={properties:{scrollTarget:{type:HTMLElement,value:function(){return this._defaultScrollTarget}}},observers:["_scrollTargetChanged(scrollTarget, isAttached)"],_shouldHaveListener:true,_scrollTargetChanged:function(scrollTarget,isAttached){var eventTarget;if(this._oldScrollTarget){this._toggleScrollListener(false,this._oldScrollTarget);this._oldScrollTarget=null}if(!isAttached){return}if(scrollTarget==="document"){this.scrollTarget=this._doc}else if(typeof scrollTarget==="string"){var domHost=this.domHost;this.scrollTarget=domHost&&domHost.$?domHost.$[scrollTarget]:Polymer.dom(this.ownerDocument).querySelector("#"+scrollTarget)}else if(this._isValidScrollTarget()){this._oldScrollTarget=scrollTarget;this._toggleScrollListener(this._shouldHaveListener,scrollTarget)}},_scrollHandler:function scrollHandler(){},get _defaultScrollTarget(){return this._doc},get _doc(){return this.ownerDocument.documentElement},get _scrollTop(){if(this._isValidScrollTarget()){return this.scrollTarget===this._doc?window.pageYOffset:this.scrollTarget.scrollTop}return 0},get _scrollLeft(){if(this._isValidScrollTarget()){return this.scrollTarget===this._doc?window.pageXOffset:this.scrollTarget.scrollLeft}return 0},set _scrollTop(top){if(this.scrollTarget===this._doc){window.scrollTo(window.pageXOffset,top)}else if(this._isValidScrollTarget()){this.scrollTarget.scrollTop=top}},set _scrollLeft(left){if(this.scrollTarget===this._doc){window.scrollTo(left,window.pageYOffset)}else if(this._isValidScrollTarget()){this.scrollTarget.scrollLeft=left}},scroll:function(leftOrOptions,top){var left;if(typeof leftOrOptions==="object"){left=leftOrOptions.left;top=leftOrOptions.top}else{left=leftOrOptions}left=left||0;top=top||0;if(this.scrollTarget===this._doc){window.scrollTo(left,top)}else if(this._isValidScrollTarget()){this.scrollTarget.scrollLeft=left;this.scrollTarget.scrollTop=top}},get _scrollTargetWidth(){if(this._isValidScrollTarget()){return this.scrollTarget===this._doc?window.innerWidth:this.scrollTarget.offsetWidth}return 0},get _scrollTargetHeight(){if(this._isValidScrollTarget()){return this.scrollTarget===this._doc?window.innerHeight:this.scrollTarget.offsetHeight}return 0},_isValidScrollTarget:function(){return this.scrollTarget instanceof HTMLElement},_toggleScrollListener:function(yes,scrollTarget){var eventTarget=scrollTarget===this._doc?window:scrollTarget;if(yes){if(!this._boundScrollHandler){this._boundScrollHandler=this._scrollHandler.bind(this);eventTarget.addEventListener("scroll",this._boundScrollHandler)}}else{if(this._boundScrollHandler){eventTarget.removeEventListener("scroll",this._boundScrollHandler);this._boundScrollHandler=null}}},toggleScrollListener:function(yes){this._shouldHaveListener=yes;this._toggleScrollListener(yes,this.scrollTarget)}};(function(){var IOS=navigator.userAgent.match(/iP(?:hone|ad;(?: U;)? CPU) OS (\d+)/);var IOS_TOUCH_SCROLLING=IOS&&IOS[1]>=8;var DEFAULT_PHYSICAL_COUNT=3;var HIDDEN_Y="-10000px";var ITEM_WIDTH=0;var ITEM_HEIGHT=1;var SECRET_TABINDEX=-100;var IS_V2=Polymer.flush!=null;var ANIMATION_FRAME=IS_V2?Polymer.Async.animationFrame:0;var IDLE_TIME=IS_V2?Polymer.Async.idlePeriod:1;var MICRO_TASK=IS_V2?Polymer.Async.microTask:2;if(!Polymer.OptionalMutableDataBehavior){Polymer.OptionalMutableDataBehavior={}}Polymer({is:"iron-list",properties:{items:{type:Array},as:{type:String,value:"item"},indexAs:{type:String,value:"index"},selectedAs:{type:String,value:"selected"},grid:{type:Boolean,value:false,reflectToAttribute:true,observer:"_gridChanged"},selectionEnabled:{type:Boolean,value:false},selectedItem:{type:Object,notify:true},selectedItems:{type:Object,notify:true},multiSelection:{type:Boolean,value:false},scrollOffset:{type:Number,value:0},preserveFocus:{type:Boolean,value:false}},observers:["_itemsChanged(items.*)","_selectionEnabledChanged(selectionEnabled)","_multiSelectionChanged(multiSelection)","_setOverflow(scrollTarget, scrollOffset)"],behaviors:[Polymer.Templatizer,Polymer.IronResizableBehavior,Polymer.IronScrollTargetBehavior,Polymer.OptionalMutableDataBehavior],_ratio:.5,_scrollerPaddingTop:0,_scrollPosition:0,_physicalSize:0,_physicalAverage:0,_physicalAverageCount:0,_physicalTop:0,_virtualCount:0,_estScrollHeight:0,_scrollHeight:0,_viewportHeight:0,_viewportWidth:0,_physicalItems:null,_physicalSizes:null,_firstVisibleIndexVal:null,_collection:null,_lastVisibleIndexVal:null,_maxPages:2,_focusedItem:null,_focusedVirtualIndex:-1,_focusedPhysicalIndex:-1,_offscreenFocusedItem:null,_focusBackfillItem:null,_itemsPerRow:1,_itemWidth:0,_rowHeight:0,_templateCost:0,_parentModel:true,get _physicalBottom(){return this._physicalTop+this._physicalSize},get _scrollBottom(){return this._scrollPosition+this._viewportHeight},get _virtualEnd(){return this._virtualStart+this._physicalCount-1},get _hiddenContentSize(){var size=this.grid?this._physicalRows*this._rowHeight:this._physicalSize;return size-this._viewportHeight},get _itemsParent(){return Polymer.dom(Polymer.dom(this._userTemplate).parentNode)},get _maxScrollTop(){return this._estScrollHeight-this._viewportHeight+this._scrollOffset},get _maxVirtualStart(){var virtualCount=this._convertIndexToCompleteRow(this._virtualCount);return Math.max(0,virtualCount-this._physicalCount)},set _virtualStart(val){val=this._clamp(val,0,this._maxVirtualStart);if(this.grid){val=val-val%this._itemsPerRow}this._virtualStartVal=val},get _virtualStart(){return this._virtualStartVal||0},set _physicalStart(val){val=val%this._physicalCount;if(val<0){val=this._physicalCount+val}if(this.grid){val=val-val%this._itemsPerRow}this._physicalStartVal=val},get _physicalStart(){return this._physicalStartVal||0},get _physicalEnd(){return(this._physicalStart+this._physicalCount-1)%this._physicalCount},set _physicalCount(val){this._physicalCountVal=val},get _physicalCount(){return this._physicalCountVal||0},get _optPhysicalSize(){return this._viewportHeight===0?Infinity:this._viewportHeight*this._maxPages},get _isVisible(){return Boolean(this.offsetWidth||this.offsetHeight)},get firstVisibleIndex(){var idx=this._firstVisibleIndexVal;if(idx==null){var physicalOffset=this._physicalTop+this._scrollOffset;idx=this._iterateItems(function(pidx,vidx){physicalOffset+=this._getPhysicalSizeIncrement(pidx);if(physicalOffset>this._scrollPosition){return this.grid?vidx-vidx%this._itemsPerRow:vidx}if(this.grid&&this._virtualCount-1===vidx){return vidx-vidx%this._itemsPerRow}})||0;this._firstVisibleIndexVal=idx}return idx},get lastVisibleIndex(){var idx=this._lastVisibleIndexVal;if(idx==null){if(this.grid){idx=Math.min(this._virtualCount,this.firstVisibleIndex+this._estRowsInView*this._itemsPerRow-1)}else{var physicalOffset=this._physicalTop+this._scrollOffset;this._iterateItems(function(pidx,vidx){if(physicalOffset<this._scrollBottom){idx=vidx}physicalOffset+=this._getPhysicalSizeIncrement(pidx)})}this._lastVisibleIndexVal=idx}return idx},get _defaultScrollTarget(){return this},get _virtualRowCount(){return Math.ceil(this._virtualCount/this._itemsPerRow)},get _estRowsInView(){return Math.ceil(this._viewportHeight/this._rowHeight)},get _physicalRows(){return Math.ceil(this._physicalCount/this._itemsPerRow)},get _scrollOffset(){return this._scrollerPaddingTop+this.scrollOffset},ready:function(){this.addEventListener("focus",this._didFocus.bind(this),true)},attached:function(){this._debounce("_render",this._render,ANIMATION_FRAME);this.listen(this,"iron-resize","_resizeHandler");this.listen(this,"keydown","_keydownHandler")},detached:function(){this.unlisten(this,"iron-resize","_resizeHandler");this.unlisten(this,"keydown","_keydownHandler")},_setOverflow:function(scrollTarget){this.style.webkitOverflowScrolling=scrollTarget===this?"touch":"";this.style.overflowY=scrollTarget===this?"auto":"";this._lastVisibleIndexVal=null;this._firstVisibleIndexVal=null;this._debounce("_render",this._render,ANIMATION_FRAME)},updateViewportBoundaries:function(){var styles=window.getComputedStyle(this);this._scrollerPaddingTop=this.scrollTarget===this?0:parseInt(styles["padding-top"],10);this._isRTL=Boolean(styles.direction==="rtl");this._viewportWidth=this.$.items.offsetWidth;this._viewportHeight=this._scrollTargetHeight;this.grid&&this._updateGridMetrics()},_scrollHandler:function(){var scrollTop=Math.max(0,Math.min(this._maxScrollTop,this._scrollTop));var delta=scrollTop-this._scrollPosition;var isScrollingDown=delta>=0;this._scrollPosition=scrollTop;this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null;if(Math.abs(delta)>this._physicalSize&&this._physicalSize>0){delta=delta-this._scrollOffset;var idxAdjustment=Math.round(delta/this._physicalAverage)*this._itemsPerRow;this._virtualStart=this._virtualStart+idxAdjustment;this._physicalStart=this._physicalStart+idxAdjustment;this._physicalTop=Math.floor(this._virtualStart/this._itemsPerRow)*this._physicalAverage;this._update()}else if(this._physicalCount>0){var reusables=this._getReusables(isScrollingDown);if(isScrollingDown){this._physicalTop=reusables.physicalTop;this._virtualStart=this._virtualStart+reusables.indexes.length;this._physicalStart=this._physicalStart+reusables.indexes.length}else{this._virtualStart=this._virtualStart-reusables.indexes.length;this._physicalStart=this._physicalStart-reusables.indexes.length}this._update(reusables.indexes,isScrollingDown?null:reusables.indexes);this._debounce("_increasePoolIfNeeded",this._increasePoolIfNeeded.bind(this,0),MICRO_TASK)}},_getReusables:function(fromTop){var ith,lastIth,offsetContent,physicalItemHeight;var idxs=[];var protectedOffsetContent=this._hiddenContentSize*this._ratio;var virtualStart=this._virtualStart;var virtualEnd=this._virtualEnd;var physicalCount=this._physicalCount;var top=this._physicalTop+this._scrollOffset;var bottom=this._physicalBottom+this._scrollOffset;var scrollTop=this._scrollTop;var scrollBottom=this._scrollBottom;if(fromTop){ith=this._physicalStart;lastIth=this._physicalEnd;offsetContent=scrollTop-top}else{ith=this._physicalEnd;lastIth=this._physicalStart;offsetContent=bottom-scrollBottom}while(true){physicalItemHeight=this._getPhysicalSizeIncrement(ith);offsetContent=offsetContent-physicalItemHeight;if(idxs.length>=physicalCount||offsetContent<=protectedOffsetContent){break}if(fromTop){if(virtualEnd+idxs.length+1>=this._virtualCount){break}if(top+physicalItemHeight>=scrollTop-this._scrollOffset){break}idxs.push(ith);top=top+physicalItemHeight;ith=(ith+1)%physicalCount}else{if(virtualStart-idxs.length<=0){break}if(top+this._physicalSize-physicalItemHeight<=scrollBottom){break}idxs.push(ith);top=top-physicalItemHeight;ith=ith===0?physicalCount-1:ith-1}}return{indexes:idxs,physicalTop:top-this._scrollOffset}},_update:function(itemSet,movingUp){if(itemSet&&itemSet.length===0||this._physicalCount===0){return}this._manageFocus();this._assignModels(itemSet);this._updateMetrics(itemSet);if(movingUp){while(movingUp.length){var idx=movingUp.pop();this._physicalTop-=this._getPhysicalSizeIncrement(idx)}}this._positionItems();this._updateScrollerSize()},_createPool:function(size){this._ensureTemplatized();var i,inst;var physicalItems=new Array(size);for(i=0;i<size;i++){inst=this.stamp(null);physicalItems[i]=inst.root.querySelector("*");this._itemsParent.appendChild(inst.root)}return physicalItems},_isClientFull:function(){return this._scrollBottom!=0&&this._physicalBottom-1>=this._scrollBottom&&this._physicalTop<=this._scrollPosition},_increasePoolIfNeeded:function(count){var nextPhysicalCount=this._clamp(this._physicalCount+count,DEFAULT_PHYSICAL_COUNT,this._virtualCount-this._virtualStart);nextPhysicalCount=this._convertIndexToCompleteRow(nextPhysicalCount);if(this.grid){var correction=nextPhysicalCount%this._itemsPerRow;if(correction&&nextPhysicalCount-correction<=this._physicalCount){nextPhysicalCount+=this._itemsPerRow}nextPhysicalCount-=correction}var delta=nextPhysicalCount-this._physicalCount;var nextIncrease=Math.round(this._physicalCount*.5);if(delta<0){return}if(delta>0){var ts=window.performance.now();[].push.apply(this._physicalItems,this._createPool(delta));for(var i=0;i<delta;i++){this._physicalSizes.push(0)}this._physicalCount=this._physicalCount+delta;if(this._physicalStart>this._physicalEnd&&this._isIndexRendered(this._focusedVirtualIndex)&&this._getPhysicalIndex(this._focusedVirtualIndex)<this._physicalEnd){this._physicalStart=this._physicalStart+delta}this._update();this._templateCost=(window.performance.now()-ts)/delta;nextIncrease=Math.round(this._physicalCount*.5)}if(this._virtualEnd>=this._virtualCount-1||nextIncrease===0){}else if(!this._isClientFull()){this._debounce("_increasePoolIfNeeded",this._increasePoolIfNeeded.bind(this,nextIncrease),MICRO_TASK)}else if(this._physicalSize<this._optPhysicalSize){this._debounce("_increasePoolIfNeeded",this._increasePoolIfNeeded.bind(this,this._clamp(Math.round(50/this._templateCost),1,nextIncrease)),IDLE_TIME)}},_render:function(){if(!this.isAttached||!this._isVisible){return}if(this._physicalCount!==0){var reusables=this._getReusables(true);this._physicalTop=reusables.physicalTop;this._virtualStart=this._virtualStart+reusables.indexes.length;this._physicalStart=this._physicalStart+reusables.indexes.length;this._update(reusables.indexes);this._update();this._increasePoolIfNeeded(0)}else if(this._virtualCount>0){this.updateViewportBoundaries();this._increasePoolIfNeeded(DEFAULT_PHYSICAL_COUNT)}},_ensureTemplatized:function(){if(this.ctor){return}this._userTemplate=this.queryEffectiveChildren("template");if(!this._userTemplate){console.warn("iron-list requires a template to be provided in light-dom")}var instanceProps={};instanceProps.__key__=true;instanceProps[this.as]=true;instanceProps[this.indexAs]=true;instanceProps[this.selectedAs]=true;instanceProps.tabIndex=true;this._instanceProps=instanceProps;this.templatize(this._userTemplate,this.mutableData)},_gridChanged:function(newGrid,oldGrid){if(typeof oldGrid==="undefined")return;this.notifyResize();Polymer.flush?Polymer.flush():Polymer.dom.flush();newGrid&&this._updateGridMetrics()},_itemsChanged:function(change){var rendering=/^items(\.splices){0,1}$/.test(change.path);var lastFocusedIndex,focusedElement;if(rendering&&this.preserveFocus){lastFocusedIndex=this._focusedVirtualIndex;focusedElement=this.querySelector("* /deep/ *:focus")}var preservingFocus=rendering&&this.preserveFocus&&focusedElement;if(change.path==="items"){this._virtualStart=0;this._physicalTop=0;this._virtualCount=this.items?this.items.length:0;this._collection=this.items&&Polymer.Collection?Polymer.Collection.get(this.items):null;this._physicalIndexForKey={};this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null;this._physicalCount=this._physicalCount||0;this._physicalItems=this._physicalItems||[];this._physicalSizes=this._physicalSizes||[];this._physicalStart=0;if(this._scrollTop>this._scrollOffset&&!preservingFocus){this._resetScrollPosition(0)}this._removeFocusedItem();this._debounce("_render",this._render,ANIMATION_FRAME)}else if(change.path==="items.splices"){this._adjustVirtualIndex(change.value.indexSplices);this._virtualCount=this.items?this.items.length:0;var itemAddedOrRemoved=change.value.indexSplices.some(function(splice){return splice.addedCount>0||splice.removed.length>0});if(itemAddedOrRemoved){var activeElement=this._getActiveElement();if(this.contains(activeElement)){activeElement.blur()}}var affectedIndexRendered=change.value.indexSplices.some(function(splice){return splice.index+splice.addedCount>=this._virtualStart&&splice.index<=this._virtualEnd},this);if(!this._isClientFull()||affectedIndexRendered){this._debounce("_render",this._render,ANIMATION_FRAME)}}else if(change.path!=="items.length"){this._forwardItemPath(change.path,change.value)}if(preservingFocus){Polymer.dom.flush();focusedElement.blur();this._focusPhysicalItem(Math.min(this.items.length-1,lastFocusedIndex));if(!this._isIndexVisible(this._focusedVirtualIndex)){this.scrollToIndex(this._focusedVirtualIndex)}}},_forwardItemPath:function(path,value){path=path.slice(6);var dot=path.indexOf(".");if(dot===-1){dot=path.length}var isIndexRendered;var pidx;var inst;var offscreenInstance=this.modelForElement(this._offscreenFocusedItem);if(IS_V2){var vidx=parseInt(path.substring(0,dot),10);isIndexRendered=this._isIndexRendered(vidx);if(isIndexRendered){pidx=this._getPhysicalIndex(vidx);inst=this.modelForElement(this._physicalItems[pidx])}else if(offscreenInstance){inst=offscreenInstance}if(!inst||inst[this.indexAs]!==vidx){return}}else{var key=path.substring(0,dot);if(offscreenInstance&&offscreenInstance.__key__===key){inst=offscreenInstance}else{pidx=this._physicalIndexForKey[key];inst=this.modelForElement(this._physicalItems[pidx]);if(!inst||inst.__key__!==key){return}}}path=path.substring(dot+1);path=this.as+(path?"."+path:"");IS_V2?inst._setPendingPropertyOrPath(path,value,false,true):inst.notifyPath(path,value,true);inst._flushProperties&&inst._flushProperties(true);if(isIndexRendered){this._updateMetrics([pidx]);this._positionItems();this._updateScrollerSize()}},_adjustVirtualIndex:function(splices){splices.forEach(function(splice){splice.removed.forEach(this._removeItem,this);if(splice.index<this._virtualStart){var delta=Math.max(splice.addedCount-splice.removed.length,splice.index-this._virtualStart);this._virtualStart=this._virtualStart+delta;if(this._focusedVirtualIndex>=0){this._focusedVirtualIndex=this._focusedVirtualIndex+delta}}},this)},_removeItem:function(item){this.$.selector.deselect(item);if(this._focusedItem&&this.modelForElement(this._focusedItem)[this.as]===item){this._removeFocusedItem()}},_iterateItems:function(fn,itemSet){var pidx,vidx,rtn,i;if(arguments.length===2&&itemSet){for(i=0;i<itemSet.length;i++){pidx=itemSet[i];vidx=this._computeVidx(pidx);if((rtn=fn.call(this,pidx,vidx))!=null){return rtn}}}else{pidx=this._physicalStart;vidx=this._virtualStart;for(;pidx<this._physicalCount;pidx++,vidx++){if((rtn=fn.call(this,pidx,vidx))!=null){return rtn}}for(pidx=0;pidx<this._physicalStart;pidx++,vidx++){if((rtn=fn.call(this,pidx,vidx))!=null){return rtn}}}},_computeVidx:function(pidx){if(pidx>=this._physicalStart){return this._virtualStart+(pidx-this._physicalStart)}return this._virtualStart+(this._physicalCount-this._physicalStart)+pidx},_assignModels:function(itemSet){this._iterateItems(function(pidx,vidx){var el=this._physicalItems[pidx];var item=this.items&&this.items[vidx];if(item!=null){var inst=this.modelForElement(el);inst.__key__=this._collection?this._collection.getKey(item):null;this._forwardProperty(inst,this.as,item);this._forwardProperty(inst,this.selectedAs,this.$.selector.isSelected(item));this._forwardProperty(inst,this.indexAs,vidx);this._forwardProperty(inst,"tabIndex",this._focusedVirtualIndex===vidx?0:-1);this._physicalIndexForKey[inst.__key__]=pidx;inst._flushProperties&&inst._flushProperties(true);el.removeAttribute("hidden")}else{el.setAttribute("hidden","")}},itemSet)},_updateMetrics:function(itemSet){Polymer.flush?Polymer.flush():Polymer.dom.flush();var newPhysicalSize=0;var oldPhysicalSize=0;var prevAvgCount=this._physicalAverageCount;var prevPhysicalAvg=this._physicalAverage;this._iterateItems(function(pidx,vidx){oldPhysicalSize+=this._physicalSizes[pidx];this._physicalSizes[pidx]=this._physicalItems[pidx].offsetHeight;newPhysicalSize+=this._physicalSizes[pidx];this._physicalAverageCount+=this._physicalSizes[pidx]?1:0},itemSet);if(this.grid){this._updateGridMetrics();this._physicalSize=Math.ceil(this._physicalCount/this._itemsPerRow)*this._rowHeight}else{oldPhysicalSize=this._itemsPerRow===1?oldPhysicalSize:Math.ceil(this._physicalCount/this._itemsPerRow)*this._rowHeight;this._physicalSize=this._physicalSize+newPhysicalSize-oldPhysicalSize;this._itemsPerRow=1}if(this._physicalAverageCount!==prevAvgCount){this._physicalAverage=Math.round((prevPhysicalAvg*prevAvgCount+newPhysicalSize)/this._physicalAverageCount)}},_updateGridMetrics:function(){this._itemWidth=this._physicalCount>0?this._physicalItems[0].getBoundingClientRect().width:200;this._rowHeight=this._physicalCount>0?this._physicalItems[0].offsetHeight:200;this._itemsPerRow=this._itemWidth?Math.floor(this._viewportWidth/this._itemWidth):this._itemsPerRow},_positionItems:function(){this._adjustScrollPosition();var y=this._physicalTop;if(this.grid){var totalItemWidth=this._itemsPerRow*this._itemWidth;var rowOffset=(this._viewportWidth-totalItemWidth)/2;this._iterateItems(function(pidx,vidx){var modulus=vidx%this._itemsPerRow;var x=Math.floor(modulus*this._itemWidth+rowOffset);if(this._isRTL){x=x*-1}this.translate3d(x+"px",y+"px",0,this._physicalItems[pidx]);if(this._shouldRenderNextRow(vidx)){y+=this._rowHeight}})}else{this._iterateItems(function(pidx,vidx){this.translate3d(0,y+"px",0,this._physicalItems[pidx]);y+=this._physicalSizes[pidx]})}},_getPhysicalSizeIncrement:function(pidx){if(!this.grid){return this._physicalSizes[pidx]}if(this._computeVidx(pidx)%this._itemsPerRow!==this._itemsPerRow-1){return 0}return this._rowHeight},_shouldRenderNextRow:function(vidx){return vidx%this._itemsPerRow===this._itemsPerRow-1},_adjustScrollPosition:function(){var deltaHeight=this._virtualStart===0?this._physicalTop:Math.min(this._scrollPosition+this._physicalTop,0);if(deltaHeight!==0){this._physicalTop=this._physicalTop-deltaHeight;var scrollTop=this._scrollTop;if(!IOS_TOUCH_SCROLLING&&scrollTop>0){this._resetScrollPosition(scrollTop-deltaHeight)}}},_resetScrollPosition:function(pos){if(this.scrollTarget&&pos>=0){this._scrollTop=pos;this._scrollPosition=this._scrollTop}},_updateScrollerSize:function(forceUpdate){if(this.grid){this._estScrollHeight=this._virtualRowCount*this._rowHeight}else{this._estScrollHeight=this._physicalBottom+Math.max(this._virtualCount-this._physicalCount-this._virtualStart,0)*this._physicalAverage}forceUpdate=forceUpdate||this._scrollHeight===0;forceUpdate=forceUpdate||this._scrollPosition>=this._estScrollHeight-this._physicalSize;forceUpdate=forceUpdate||this.grid&&this.$.items.style.height<this._estScrollHeight;if(forceUpdate||Math.abs(this._estScrollHeight-this._scrollHeight)>=this._viewportHeight){this.$.items.style.height=this._estScrollHeight+"px";this._scrollHeight=this._estScrollHeight}},scrollToItem:function(item){return this.scrollToIndex(this.items.indexOf(item))},scrollToIndex:function(idx){if(typeof idx!=="number"||idx<0||idx>this.items.length-1){return}Polymer.flush?Polymer.flush():Polymer.dom.flush();if(this._physicalCount===0){return}idx=this._clamp(idx,0,this._virtualCount-1);if(!this._isIndexRendered(idx)||idx>=this._maxVirtualStart){this._virtualStart=this.grid?idx-this._itemsPerRow*2:idx-1}this._manageFocus();this._assignModels();this._updateMetrics();this._physicalTop=Math.floor(this._virtualStart/this._itemsPerRow)*this._physicalAverage;var currentTopItem=this._physicalStart;var currentVirtualItem=this._virtualStart;var targetOffsetTop=0;var hiddenContentSize=this._hiddenContentSize;while(currentVirtualItem<idx&&targetOffsetTop<=hiddenContentSize){targetOffsetTop=targetOffsetTop+this._getPhysicalSizeIncrement(currentTopItem);currentTopItem=(currentTopItem+1)%this._physicalCount;currentVirtualItem++}this._updateScrollerSize(true);this._positionItems();this._resetScrollPosition(this._physicalTop+this._scrollOffset+targetOffsetTop);this._increasePoolIfNeeded(0);this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null},_resetAverage:function(){this._physicalAverage=0;this._physicalAverageCount=0},_resizeHandler:function(){this._debounce("_render",function(){this._firstVisibleIndexVal=null;this._lastVisibleIndexVal=null;var delta=Math.abs(this._viewportHeight-this._scrollTargetHeight);this.updateViewportBoundaries();if(this._isVisible){this.toggleScrollListener(true);this._resetAverage();this._render()}else{this.toggleScrollListener(false)}},ANIMATION_FRAME)},selectItem:function(item){return this.selectIndex(this.items.indexOf(item))},selectIndex:function(index){if(index<0||index>=this._virtualCount){return}if(!this.multiSelection&&this.selectedItem){this.clearSelection()}if(this._isIndexRendered(index)){var model=this.modelForElement(this._physicalItems[this._getPhysicalIndex(index)]);if(model){model[this.selectedAs]=true}this.updateSizeForIndex(index)}if(this.$.selector.selectIndex){this.$.selector.selectIndex(index)}else{this.$.selector.select(this.items[index])}},deselectItem:function(item){return this.deselectIndex(this.items.indexOf(item))},deselectIndex:function(index){if(index<0||index>=this._virtualCount){return}if(this._isIndexRendered(index)){var model=this.modelForElement(this._physicalItems[this._getPhysicalIndex(index)]);model[this.selectedAs]=false;this.updateSizeForIndex(index)}if(this.$.selector.deselectIndex){this.$.selector.deselectIndex(index)}else{this.$.selector.deselect(this.items[index])}},toggleSelectionForItem:function(item){return this.toggleSelectionForIndex(this.items.indexOf(item))},toggleSelectionForIndex:function(index){var isSelected=this.$.selector.isIndexSelected?this.$.selector.isIndexSelected(index):this.$.selector.isSelected(this.items[index]);isSelected?this.deselectIndex(index):this.selectIndex(index)},clearSelection:function(){this._iterateItems(function(pidx,vidx){this.modelForElement(this._physicalItems[pidx])[this.selectedAs]=false});this.$.selector.clearSelection()},_selectionEnabledChanged:function(selectionEnabled){var handler=selectionEnabled?this.listen:this.unlisten;handler.call(this,this,"tap","_selectionHandler")},_selectionHandler:function(e){var model=this.modelForElement(e.target);if(!model){return}var modelTabIndex,activeElTabIndex;var target=Polymer.dom(e).path[0];var activeEl=this._getActiveElement();var physicalItem=this._physicalItems[this._getPhysicalIndex(model[this.indexAs])];if(target.localName==="input"||target.localName==="button"||target.localName==="select"){return}modelTabIndex=model.tabIndex;model.tabIndex=SECRET_TABINDEX;activeElTabIndex=activeEl?activeEl.tabIndex:-1;model.tabIndex=modelTabIndex;if(activeEl&&physicalItem!==activeEl&&physicalItem.contains(activeEl)&&activeElTabIndex!==SECRET_TABINDEX){return}this.toggleSelectionForItem(model[this.as])},_multiSelectionChanged:function(multiSelection){this.clearSelection();this.$.selector.multi=multiSelection},updateSizeForItem:function(item){return this.updateSizeForIndex(this.items.indexOf(item))},updateSizeForIndex:function(index){if(!this._isIndexRendered(index)){return null}this._updateMetrics([this._getPhysicalIndex(index)]);this._positionItems();return null},_manageFocus:function(){var fidx=this._focusedVirtualIndex;if(fidx>=0&&fidx<this._virtualCount){if(this._isIndexRendered(fidx)){this._restoreFocusedItem()}else{this._createFocusBackfillItem()}}else if(this._virtualCount>0&&this._physicalCount>0){this._focusedPhysicalIndex=this._physicalStart;this._focusedVirtualIndex=this._virtualStart;this._focusedItem=this._physicalItems[this._physicalStart]}},_convertIndexToCompleteRow:function(idx){this._itemsPerRow=this._itemsPerRow||1;return this.grid?Math.ceil(idx/this._itemsPerRow)*this._itemsPerRow:idx},_isIndexRendered:function(idx){return idx>=this._virtualStart&&idx<=this._virtualEnd},_isIndexVisible:function(idx){return idx>=this.firstVisibleIndex&&idx<=this.lastVisibleIndex},_getPhysicalIndex:function(vidx){return IS_V2?(this._physicalStart+(vidx-this._virtualStart))%this._physicalCount:this._physicalIndexForKey[this._collection.getKey(this.items[vidx])]},focusItem:function(idx){this._focusPhysicalItem(idx)},_focusPhysicalItem:function(idx){if(idx<0||idx>=this._virtualCount){return}this._restoreFocusedItem();if(!this._isIndexRendered(idx)){this.scrollToIndex(idx)}var physicalItem=this._physicalItems[this._getPhysicalIndex(idx)];var model=this.modelForElement(physicalItem);var focusable;model.tabIndex=SECRET_TABINDEX;if(physicalItem.tabIndex===SECRET_TABINDEX){focusable=physicalItem}if(!focusable){focusable=Polymer.dom(physicalItem).querySelector('[tabindex="'+SECRET_TABINDEX+'"]')}model.tabIndex=0;this._focusedVirtualIndex=idx;focusable&&focusable.focus()},_removeFocusedItem:function(){if(this._offscreenFocusedItem){this._itemsParent.removeChild(this._offscreenFocusedItem)}this._offscreenFocusedItem=null;this._focusBackfillItem=null;this._focusedItem=null;this._focusedVirtualIndex=-1;this._focusedPhysicalIndex=-1},_createFocusBackfillItem:function(){var fpidx=this._focusedPhysicalIndex;if(this._offscreenFocusedItem||this._focusedVirtualIndex<0){return}if(!this._focusBackfillItem){var inst=this.stamp(null);this._focusBackfillItem=inst.root.querySelector("*");this._itemsParent.appendChild(inst.root)}this._offscreenFocusedItem=this._physicalItems[fpidx];this.modelForElement(this._offscreenFocusedItem).tabIndex=0;this._physicalItems[fpidx]=this._focusBackfillItem;this._focusedPhysicalIndex=fpidx;this.translate3d(0,HIDDEN_Y,0,this._offscreenFocusedItem)},_restoreFocusedItem:function(){if(!this._offscreenFocusedItem||this._focusedVirtualIndex<0){return}this._assignModels();var fpidx=this._focusedPhysicalIndex;var onScreenItem=this._physicalItems[fpidx];if(!onScreenItem){return}var onScreenInstance=this.modelForElement(onScreenItem);var offScreenInstance=this.modelForElement(this._offscreenFocusedItem);if(onScreenInstance[this.as]===offScreenInstance[this.as]){this._focusBackfillItem=onScreenItem;onScreenInstance.tabIndex=-1;this._physicalItems[fpidx]=this._offscreenFocusedItem;this.translate3d(0,HIDDEN_Y,0,this._focusBackfillItem)}else{this._removeFocusedItem();this._focusBackfillItem=null}this._offscreenFocusedItem=null},_didFocus:function(e){var targetModel=this.modelForElement(e.target);var focusedModel=this.modelForElement(this._focusedItem);var hasOffscreenFocusedItem=this._offscreenFocusedItem!==null;var fidx=this._focusedVirtualIndex;if(!targetModel){return}if(focusedModel===targetModel){if(!this._isIndexVisible(fidx)){this.scrollToIndex(fidx)}}else{this._restoreFocusedItem();if(focusedModel){focusedModel.tabIndex=-1}targetModel.tabIndex=0;fidx=targetModel[this.indexAs];this._focusedVirtualIndex=fidx;this._focusedPhysicalIndex=this._getPhysicalIndex(fidx);this._focusedItem=this._physicalItems[this._focusedPhysicalIndex];if(hasOffscreenFocusedItem&&!this._offscreenFocusedItem){this._update()}}},_keydownHandler:function(e){switch(e.keyCode){case 40:e.preventDefault();this._focusPhysicalItem(this._focusedVirtualIndex+(this.grid?this._itemsPerRow:1));break;case 39:if(this.grid)this._focusPhysicalItem(this._focusedVirtualIndex+(this._isRTL?-1:1));break;case 38:this._focusPhysicalItem(this._focusedVirtualIndex-(this.grid?this._itemsPerRow:1));break;case 37:if(this.grid)this._focusPhysicalItem(this._focusedVirtualIndex+(this._isRTL?1:-1));break;case 13:this._focusPhysicalItem(this._focusedVirtualIndex);this._selectionHandler(e);break}},_clamp:function(v,min,max){return Math.min(max,Math.max(min,v))},_debounce:function(name,cb,asyncModule){if(IS_V2){this._debouncers=this._debouncers||{};this._debouncers[name]=Polymer.Debouncer.debounce(this._debouncers[name],asyncModule,cb.bind(this));Polymer.enqueueDebouncer(this._debouncers[name])}else{Polymer.dom.addDebouncer(this.debounce(name,cb))}},_forwardProperty:function(inst,name,value){if(IS_V2){inst._setPendingProperty(name,value)}else{inst[name]=value}},_forwardHostPropV2:function(prop,value){(this._physicalItems||[]).concat([this._offscreenFocusedItem,this._focusBackfillItem]).forEach(function(item){if(item){this.modelForElement(item).forwardHostProp(prop,value)}},this)},_notifyInstancePropV2:function(inst,prop,value){if(Polymer.Path.matches(this.as,prop)){var idx=inst[this.indexAs];if(prop==this.as){this.items[idx]=value}this.notifyPath(Polymer.Path.translate(this.as,"items."+idx,prop),value)}},_getStampedChildren:function(){return this._physicalItems},_forwardInstancePath:function(inst,path,value){if(path.indexOf(this.as+".")===0){this.notifyPath("items."+inst.__key__+"."+path.slice(this.as.length+1),value)}},_forwardParentPath:function(path,value){(this._physicalItems||[]).concat([this._offscreenFocusedItem,this._focusBackfillItem]).forEach(function(item){if(item){this.modelForElement(item).notifyPath(path,value,true)}},this)},_forwardParentProp:function(prop,value){(this._physicalItems||[]).concat([this._offscreenFocusedItem,this._focusBackfillItem]).forEach(function(item){if(item){this.modelForElement(item)[prop]=value}},this)},_getActiveElement:function(){var itemsHost=this._itemsParent.node.domHost;return Polymer.dom(itemsHost?itemsHost.root:document).activeElement}})})();
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
var CrScrollableBehavior={intervalId_:null,ready:function(){this.requestUpdateScroll();var scrollableElements=this.root.querySelectorAll("[scrollable]");for(var i=0;i<scrollableElements.length;i++){scrollableElements[i].addEventListener("scroll",this.updateScrollEvent_.bind(this))}},detached:function(){if(this.intervalId_!==null)clearInterval(this.intervalId_)},updateScrollableContents:function(){if(this.intervalId_!==null)return;this.requestUpdateScroll();var nodeList=this.root.querySelectorAll("[scrollable] iron-list");if(!nodeList.length)return;this.intervalId_=window.setInterval(function(){var unreadyNodes=[];for(var i=0;i<nodeList.length;i++){var node=nodeList[i];if(node.parentNode.scrollHeight==0){unreadyNodes.push(node);continue}var ironList=node;ironList.notifyResize()}if(unreadyNodes.length==0){window.clearInterval(this.intervalId_);this.intervalId_=null}else{nodeList=unreadyNodes}}.bind(this),10)},requestUpdateScroll:function(){requestAnimationFrame(function(){var scrollableElements=this.root.querySelectorAll("[scrollable]");for(var i=0;i<scrollableElements.length;i++)this.updateScroll_(scrollableElements[i])}.bind(this))},saveScroll:function(list){list.savedScrollTops=list.savedScrollTops||[];list.savedScrollTops.push(list.scrollTarget.scrollTop)},restoreScroll:function(list){this.async(function(){var scrollTop=list.savedScrollTops.shift();if(scrollTop!=0)list.scroll(0,scrollTop)})},updateScrollEvent_:function(event){var scrollable=event.target;this.updateScroll_(scrollable)},updateScroll_:function(scrollable){scrollable.classList.toggle("can-scroll",scrollable.clientHeight<scrollable.scrollHeight);scrollable.classList.toggle("is-scrolled",scrollable.scrollTop>0);scrollable.classList.toggle("scrolled-to-bottom",scrollable.scrollTop+scrollable.clientHeight>=scrollable.scrollHeight)}};
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"cr-dialog",properties:{open:{type:Boolean,value:false,reflectToAttribute:true},closeText:String,ignorePopstate:{type:Boolean,value:false},ignoreEnterKey:{type:Boolean,value:false},noCancel:{type:Boolean,value:false},showCloseButton:{type:Boolean,value:false}},listeners:{pointerdown:"onPointerdown_"},intersectionObserver_:null,mutationObserver_:null,ready:function(){window.addEventListener("popstate",function(){if(!this.ignorePopstate&&this.$.dialog.open)this.cancel()}.bind(this));if(!this.ignoreEnterKey)this.addEventListener("keypress",this.onKeypress_.bind(this));if(this.noCancel)this.addEventListener("cancel",this.onCancel_.bind(this))},attached:function(){var mutationObserverCallback=function(){if(this.$.dialog.open)this.addIntersectionObserver_();else this.removeIntersectionObserver_()}.bind(this);this.mutationObserver_=new MutationObserver(mutationObserverCallback);this.mutationObserver_.observe(this.$.dialog,{attributes:true,attributeFilter:["open"]});mutationObserverCallback()},detached:function(){this.removeIntersectionObserver_();if(this.mutationObserver_){this.mutationObserver_.disconnect();this.mutationObserver_=null}},addIntersectionObserver_:function(){if(this.intersectionObserver_)return;var bodyContainer=this.$$(".body-container");var bottomMarker=this.$.bodyBottomMarker;var topMarker=this.$.bodyTopMarker;var callback=function(entries){for(var i=0;i<entries.length;i++){var target=entries[i].target;assert(target==bottomMarker||target==topMarker);var classToToggle=target==bottomMarker?"bottom-scrollable":"top-scrollable";bodyContainer.classList.toggle(classToToggle,entries[i].intersectionRatio==0)}};this.intersectionObserver_=new IntersectionObserver(callback,{root:bodyContainer,threshold:0});this.intersectionObserver_.observe(bottomMarker);this.intersectionObserver_.observe(topMarker)},removeIntersectionObserver_:function(){if(this.intersectionObserver_){this.intersectionObserver_.disconnect();this.intersectionObserver_=null}},showModal:function(){this.$.dialog.showModal();this.open=this.$.dialog.open},cancel:function(){this.fire("cancel");this.$.dialog.close();this.open=this.$.dialog.open},close:function(){this.$.dialog.close("success");this.open=this.$.dialog.open},onCloseKeypress_:function(e){e.stopPropagation()},getNative:function(){return this.$.dialog},getCloseButton:function(){return this.$.close},onKeypress_:function(e){if(e.key!="Enter")return;if(e.target!=this&&e.target.tagName!="PAPER-INPUT")return;var actionButton=this.querySelector(".action-button:not([disabled]):not([hidden])");if(actionButton){actionButton.click();e.preventDefault()}},onCancel_:function(e){if(this.noCancel)e.preventDefault()},onPointerdown_:function(e){if(e.button!=0||e.composedPath()[0].tagName!=="DIALOG")return;this.$.dialog.animate([{transform:"scale(1)",offset:0},{transform:"scale(1.02)",offset:.4},{transform:"scale(1.02)",offset:.6},{transform:"scale(1)",offset:1}],{duration:180,easing:"ease-in-out",iterations:1});e.preventDefault()}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
let StartupPageInfo;cr.define("settings",function(){class StartupUrlsPageBrowserProxy{loadStartupPages(){}useCurrentPages(){}validateStartupPage(url){}addStartupPage(url){}editStartupPage(modelIndex,url){}removeStartupPage(index){}}class StartupUrlsPageBrowserProxyImpl{loadStartupPages(){chrome.send("onStartupPrefsPageLoad")}useCurrentPages(){chrome.send("setStartupPagesToCurrentPages")}validateStartupPage(url){return cr.sendWithPromise("validateStartupPage",url)}addStartupPage(url){return cr.sendWithPromise("addStartupPage",url)}editStartupPage(modelIndex,url){return cr.sendWithPromise("editStartupPage",modelIndex,url)}removeStartupPage(index){chrome.send("removeStartupPage",[index])}}cr.addSingletonGetter(StartupUrlsPageBrowserProxyImpl);return{StartupUrlsPageBrowserProxy:StartupUrlsPageBrowserProxy,StartupUrlsPageBrowserProxyImpl:StartupUrlsPageBrowserProxyImpl}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
(function(){let UrlInputError={NONE:0,INVALID_URL:1,TOO_LONG:2};Polymer({is:"settings-startup-url-dialog",properties:{error_:{type:Number,value:UrlInputError.NONE},url_:String,urlLimit_:{readOnly:true,type:Number,value:100*1024},model:Object,dialogTitle_:String,actionButtonText_:String},browserProxy_:null,attached:function(){this.browserProxy_=settings.StartupUrlsPageBrowserProxyImpl.getInstance();if(this.model){this.dialogTitle_=loadTimeData.getString("onStartupEditPage");this.actionButtonText_=loadTimeData.getString("save");this.$.actionButton.disabled=false;this.url_=this.model.url}else{this.dialogTitle_=loadTimeData.getString("onStartupAddNewPage");this.actionButtonText_=loadTimeData.getString("add");this.$.actionButton.disabled=true}this.$.dialog.showModal()},errorMessage_:function(invalidUrl,tooLong){return["",invalidUrl,tooLong][this.error_]},onCancelTap_:function(){this.$.dialog.close()},onActionButtonTap_:function(){const whenDone=this.model?this.browserProxy_.editStartupPage(this.model.modelIndex,this.url_):this.browserProxy_.addStartupPage(this.url_);whenDone.then(success=>{if(success)this.$.dialog.close()})},showCharCounter_:function(){return this.error_==UrlInputError.TOO_LONG},validate_:function(){if(this.url_.length==0){this.$.actionButton.disabled=true;this.error_=UrlInputError.NONE;return}if(this.url_.length>=this.urlLimit_){this.$.actionButton.disabled=true;this.error_=UrlInputError.TOO_LONG;return}this.browserProxy_.validateStartupPage(this.url_).then(isValid=>{this.$.actionButton.disabled=!isValid;this.error_=isValid?UrlInputError.NONE:UrlInputError.INVALID_URL})}})})();
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
var ShowAtConfig;var ShowAtPositionConfig;var AnchorAlignment={BEFORE_START:-2,AFTER_START:-1,CENTER:0,BEFORE_END:1,AFTER_END:2};var DROPDOWN_ITEM_CLASS="dropdown-item";(function(){function getStartPointWithAnchor(start,end,menuLength,anchorAlignment,min,max){var startPoint=0;switch(anchorAlignment){case AnchorAlignment.BEFORE_START:startPoint=-menuLength;break;case AnchorAlignment.AFTER_START:startPoint=start;break;case AnchorAlignment.CENTER:startPoint=(start+end-menuLength)/2;break;case AnchorAlignment.BEFORE_END:startPoint=end-menuLength;break;case AnchorAlignment.AFTER_END:startPoint=end;break}if(startPoint+menuLength>max)startPoint=end-menuLength;if(startPoint<min)startPoint=start;startPoint=Math.max(min,Math.min(startPoint,max-menuLength));return startPoint}function getDefaultShowConfig(){var doc=document.scrollingElement;return{top:0,left:0,height:0,width:0,anchorAlignmentX:AnchorAlignment.AFTER_START,anchorAlignmentY:AnchorAlignment.AFTER_START,minX:0,minY:0,maxX:0,maxY:0}}Polymer({is:"cr-action-menu",anchorElement_:null,boundClose_:null,hasMousemoveListener_:false,contentObserver_:null,resizeObserver_:null,lastConfig_:null,properties:{autoReposition:{type:Boolean,value:false},open:{type:Boolean,value:false}},listeners:{keydown:"onKeyDown_",mouseover:"onMouseover_",tap:"onTap_"},detached:function(){this.removeListeners_()},getDialog:function(){return this.$.dialog},removeListeners_:function(){window.removeEventListener("resize",this.boundClose_);window.removeEventListener("popstate",this.boundClose_);if(this.contentObserver_){Polymer.dom(this.$.contentNode).unobserveNodes(this.contentObserver_);this.contentObserver_=null}if(this.resizeObserver_){this.resizeObserver_.disconnect();this.resizeObserver_=null}},onTap_:function(e){if(e.target==this){this.close();e.stopPropagation()}},onKeyDown_:function(e){e.stopPropagation();if(e.key=="Tab"||e.key=="Escape"){this.close();e.preventDefault();return}if(e.key!=="ArrowDown"&&e.key!=="ArrowUp")return;var nextOption=this.getNextOption_(e.key=="ArrowDown"?1:-1);if(nextOption){if(!this.hasMousemoveListener_){this.hasMousemoveListener_=true;listenOnce(this,"mousemove",e=>{this.onMouseover_(e);this.hasMousemoveListener_=false})}nextOption.focus()}e.preventDefault()},onMouseover_:function(e){var i=0;do{var target=e.path[i++];if(target.classList&&target.classList.contains("dropdown-item")&&!target.disabled){target.focus();return}}while(this!=target);this.$.dialog.focus()},getNextOption_:function(step){var counter=0;var nextOption=null;var options=this.querySelectorAll(".dropdown-item");var numOptions=options.length;var focusedIndex=Array.prototype.indexOf.call(options,this.root.activeElement);if(focusedIndex===-1&&step===-1)focusedIndex=0;do{focusedIndex=(numOptions+focusedIndex+step)%numOptions;nextOption=options[focusedIndex];if(nextOption.disabled||nextOption.hidden)nextOption=null;counter++}while(!nextOption&&counter<numOptions);return nextOption},close:function(){this.removeListeners_();this.$.dialog.close();this.open=false;if(this.anchorElement_){cr.ui.focusWithoutInk(assert(this.anchorElement_));this.anchorElement_=null}if(this.lastConfig_){this.lastConfig_=null}},showAt:function(anchorElement,opt_config){this.anchorElement_=anchorElement;this.anchorElement_.scrollIntoViewIfNeeded();var rect=this.anchorElement_.getBoundingClientRect();this.showAtPosition(Object.assign({top:rect.top,left:rect.left,height:rect.height,width:rect.width,anchorAlignmentX:AnchorAlignment.BEFORE_END},opt_config))},showAtPosition:function(config){var doc=document.scrollingElement;var scrollLeft=doc.scrollLeft;var scrollTop=doc.scrollTop;this.resetStyle_();this.$.dialog.showModal();this.open=true;config.top+=scrollTop;config.left+=scrollLeft;this.positionDialog_(Object.assign({minX:scrollLeft,minY:scrollTop,maxX:scrollLeft+doc.clientWidth,maxY:scrollTop+doc.clientHeight},config));doc.scrollTop=scrollTop;doc.scrollLeft=scrollLeft;this.addListeners_()},resetStyle_:function(){this.$.dialog.style.left="";this.$.dialog.style.right="";this.$.dialog.style.top="0"},positionDialog_:function(config){this.lastConfig_=config;var c=Object.assign(getDefaultShowConfig(),config);var top=c.top;var left=c.left;var bottom=top+c.height;var right=left+c.width;var rtl=getComputedStyle(this).direction=="rtl";if(rtl)c.anchorAlignmentX*=-1;const offsetWidth=this.$.dialog.offsetWidth;var menuLeft=getStartPointWithAnchor(left,right,offsetWidth,c.anchorAlignmentX,c.minX,c.maxX);if(rtl){var menuRight=document.scrollingElement.clientWidth-menuLeft-offsetWidth;this.$.dialog.style.right=menuRight+"px"}else{this.$.dialog.style.left=menuLeft+"px"}var menuTop=getStartPointWithAnchor(top,bottom,this.$.dialog.offsetHeight,c.anchorAlignmentY,c.minY,c.maxY);this.$.dialog.style.top=menuTop+"px"},addListeners_:function(){this.boundClose_=this.boundClose_||function(){if(this.$.dialog.open)this.close()}.bind(this);window.addEventListener("resize",this.boundClose_);window.addEventListener("popstate",this.boundClose_);this.contentObserver_=Polymer.dom(this.$.contentNode).observeNodes(info=>{info.addedNodes.forEach(node=>{if(node.classList&&node.classList.contains(DROPDOWN_ITEM_CLASS)&&!node.getAttribute("role")){node.setAttribute("role","menuitem")}})});if(this.autoReposition){this.resizeObserver_=new ResizeObserver(()=>{if(this.lastConfig_){this.positionDialog_(this.lastConfig_);this.fire("cr-action-menu-repositioned")}});this.resizeObserver_.observe(this.$.dialog)}}})})();
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"cr-lazy-render",behaviors:[Polymer.Templatizer],child_:null,get:function(){if(!this.child_)this.render_();return this.child_},getIfExists:function(){return this.child_},render_:function(){var template=this.getContentChildren()[0];if(!template.ctor)this.templatize(template);var parentNode=this.parentNode;if(parentNode&&!this.child_){var instance=this.stamp({});this.child_=instance.root.firstElementChild;parentNode.insertBefore(instance.root,this)}},_forwardParentProp:function(prop,value){if(this.child_)this.child_._templateInstance[prop]=value},_forwardParentPath:function(path,value){if(this.child_)this.child_._templateInstance.notifyPath(path,value,true)}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.define("cr.icon",function(){function getSupportedScaleFactors(){var supportedScaleFactors=[];if(!cr.isIOS){supportedScaleFactors.push(1)}if(cr.isMac||cr.isChromeOS||cr.isWindows||cr.isLinux){supportedScaleFactors.push(2)}else{supportedScaleFactors.push(window.devicePixelRatio)}return supportedScaleFactors}function getImageSet(path){var supportedScaleFactors=getSupportedScaleFactors();var replaceStartIndex=path.indexOf("scalefactor");if(replaceStartIndex<0)return getUrlForCss(path);var s="";for(var i=0;i<supportedScaleFactors.length;++i){var scaleFactor=supportedScaleFactors[i];var pathWithScaleFactor=path.substr(0,replaceStartIndex)+scaleFactor+path.substr(replaceStartIndex+"scalefactor".length);s+=getUrlForCss(pathWithScaleFactor)+" "+scaleFactor+"x";if(i!=supportedScaleFactors.length-1)s+=", "}return"-webkit-image-set("+s+")"}function getImage(path){var chromeThemePath="chrome://theme";var isChromeThemeUrl=path.slice(0,chromeThemePath.length)==chromeThemePath;return isChromeThemeUrl?getImageSet(path+"@scalefactorx"):getUrlForCss(path)}var FAVICON_URL_REGEX=/\.ico$/i;function getFavicon(url){return getImageSet("chrome://favicon/size/16@scalefactorx/"+(FAVICON_URL_REGEX.test(url)?"iconurl/":"")+url)}return{getImage:getImage,getFavicon:getFavicon}});
|
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
var EventTrackerEntry;function EventTracker(){this.listeners_=[]}EventTracker.prototype={add:function(target,eventType,listener,opt_capture){var capture=!!opt_capture;var h={target:target,eventType:eventType,listener:listener,capture:capture};this.listeners_.push(h);target.addEventListener(eventType,listener,capture)},remove:function(target,eventType){this.listeners_=this.listeners_.filter(function(h){if(h.target==target&&(!eventType||h.eventType==eventType)){EventTracker.removeEventListener_(h);return false}return true})},removeAll:function(){this.listeners_.forEach(EventTracker.removeEventListener_);this.listeners_=[]}};EventTracker.removeEventListener_=function(h){h.target.removeEventListener(h.eventType,h.listener,h.capture)};
|
|
// Copyright 2014 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.define("cr.ui",function(){function FocusRow(root,boundary,opt_delegate){this.root=root;this.boundary_=boundary||document.documentElement;this.delegate=opt_delegate;this.eventTracker=new EventTracker}FocusRow.Delegate=function(){};FocusRow.Delegate.prototype={onKeydown:assertNotReached,onFocus:assertNotReached};FocusRow.ACTIVE_CLASS="focus-row-active";FocusRow.isFocusable=function(element){if(!element||element.disabled)return false;function isVisible(element){assertInstanceof(element,Element);var style=window.getComputedStyle(element);if(style.visibility=="hidden"||style.display=="none")return false;var parent=element.parentNode;if(!parent)return false;if(parent==element.ownerDocument||parent instanceof DocumentFragment)return true;return isVisible(parent)}return isVisible(element)};FocusRow.prototype={addItem:function(type,selectorOrElement){assert(type);var element;if(typeof selectorOrElement=="string")element=this.root.querySelector(selectorOrElement);else element=selectorOrElement;if(!element)return false;element.setAttribute("focus-type",type);element.tabIndex=this.isActive()?0:-1;this.eventTracker.add(element,"blur",this.onBlur_.bind(this));this.eventTracker.add(element,"focus",this.onFocus_.bind(this));this.eventTracker.add(element,"keydown",this.onKeydown_.bind(this));this.eventTracker.add(element,"mousedown",this.onMousedown_.bind(this));return true},destroy:function(){this.eventTracker.removeAll()},getCustomEquivalent:function(sampleElement){return assert(this.getFirstFocusable())},getElements:function(){var elements=this.root.querySelectorAll("[focus-type]");return Array.prototype.slice.call(elements)},getEquivalentElement:function(sampleElement){if(this.getFocusableElements().indexOf(sampleElement)>=0)return sampleElement;var sampleFocusType=this.getTypeForElement(sampleElement);if(sampleFocusType){var sameType=this.getFirstFocusable(sampleFocusType);if(sameType)return sameType}return this.getCustomEquivalent(sampleElement)},getFirstFocusable:function(opt_type){var filter=opt_type?'="'+opt_type+'"':"";var elements=this.root.querySelectorAll("[focus-type"+filter+"]");for(var i=0;i<elements.length;++i){if(cr.ui.FocusRow.isFocusable(elements[i]))return elements[i]}return null},getFocusableElements:function(){return this.getElements().filter(cr.ui.FocusRow.isFocusable)},getTypeForElement:function(element){return element.getAttribute("focus-type")||""},isActive:function(){return this.root.classList.contains(FocusRow.ACTIVE_CLASS)},makeActive:function(active){if(active==this.isActive())return;this.getElements().forEach(function(element){element.tabIndex=active?0:-1});this.root.classList.toggle(FocusRow.ACTIVE_CLASS,active)},onBlur_:function(e){if(!this.boundary_.contains(e.relatedTarget))return;var currentTarget=e.currentTarget;if(this.getFocusableElements().indexOf(currentTarget)>=0)this.makeActive(false)},onFocus_:function(e){if(this.delegate)this.delegate.onFocus(this,e)},onMousedown_:function(e){if(e.button)return;if(!e.currentTarget.disabled)e.currentTarget.tabIndex=0},onKeydown_:function(e){var elements=this.getFocusableElements();var currentElement=e.currentTarget;var elementIndex=elements.indexOf(currentElement);assert(elementIndex>=0);if(this.delegate&&this.delegate.onKeydown(this,e))return;if(hasKeyModifiers(e))return;var index=-1;if(e.key=="ArrowLeft")index=elementIndex+(isRTL()?1:-1);else if(e.key=="ArrowRight")index=elementIndex+(isRTL()?-1:1);else if(e.key=="Home")index=0;else if(e.key=="End")index=elements.length-1;var elementToFocus=elements[index];if(elementToFocus){this.getEquivalentElement(elementToFocus).focus();e.preventDefault()}}};return{FocusRow:FocusRow}});
|
|
// Copyright 2017 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
function FocusRowDelegate(listItem){this.listItem_=listItem}FocusRowDelegate.prototype={onFocus:function(row,e){this.listItem_.lastFocused=e.path[0];this.listItem_.tabIndex=-1},onKeydown:function(row,e){if(e.key=="Enter")e.stopPropagation();return false}};function VirtualFocusRow(root,delegate){cr.ui.FocusRow.call(this,root,null,delegate)}VirtualFocusRow.prototype={__proto__:cr.ui.FocusRow.prototype};const FocusRowBehavior={properties:{row_:Object,mouseFocused_:Boolean,lastFocused:{type:Object,notify:true},ironListTabIndex:{type:Number,observer:"ironListTabIndexChanged_"}},attached:function(){this.classList.add("no-outline");Polymer.RenderStatus.afterNextRender(this,function(){const rowContainer=this.root.querySelector("[focus-row-container]");assert(!!rowContainer);this.row_=new VirtualFocusRow(rowContainer,new FocusRowDelegate(this));this.ironListTabIndexChanged_();this.addItems_();this.listen(this,"focus","onFocus_");this.listen(this,"dom-change","addItems_");this.listen(this,"mousedown","onMouseDown_");this.listen(this,"blur","onBlur_")})},detached:function(){this.unlisten(this,"focus","onFocus_");this.unlisten(this,"dom-change","addItems_");this.unlisten(this,"mousedown","onMouseDown_");this.unlisten(this,"blur","onBlur_");if(this.row_)this.row_.destroy()},addItems_:function(){if(this.row_){this.row_.destroy();const controls=this.root.querySelectorAll("[focus-row-control]");for(let i=0;i<controls.length;i++){this.row_.addItem(controls[i].getAttribute("focus-type"),controls[i])}}},onFocus_:function(){if(this.mouseFocused_){this.mouseFocused_=false;return}if(this.lastFocused){this.row_.getEquivalentElement(this.lastFocused).focus()}else{const firstFocusable=assert(this.row_.getFirstFocusable());firstFocusable.focus()}this.tabIndex=-1},ironListTabIndexChanged_:function(){if(this.row_)this.row_.makeActive(this.ironListTabIndex==0)},onMouseDown_:function(){this.mouseFocused_=true},onBlur_:function(){this.mouseFocused_=false}};
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.exportPath("settings");settings.EDIT_STARTUP_URL_EVENT="edit-startup-url";Polymer({is:"settings-startup-url-entry",behaviors:[FocusRowBehavior],properties:{editable:{type:Boolean,reflectToAttribute:true},model:Object},getIconSet_:function(url){return cr.icon.getFavicon(url)},onRemoveTap_:function(){this.$$("cr-action-menu").close();settings.StartupUrlsPageBrowserProxyImpl.getInstance().removeStartupPage(this.model.modelIndex)},onEditTap_:function(e){e.preventDefault();this.$$("cr-action-menu").close();this.fire(settings.EDIT_STARTUP_URL_EVENT,{model:this.model,anchor:this.$$("#dots")})},onDotsTap_:function(){const actionMenu=this.$$("#menu").get();actionMenu.showAt(assert(this.$$("#dots")))}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-startup-urls-page",behaviors:[CrScrollableBehavior,WebUIListenerBehavior],properties:{prefs:Object,startupPages_:Array,showStartupUrlDialog_:Boolean,startupUrlDialogModel_:Object,lastFocused_:Object},browserProxy_:null,startupUrlDialogAnchor_:null,attached:function(){this.browserProxy_=settings.StartupUrlsPageBrowserProxyImpl.getInstance();this.addWebUIListener("update-startup-pages",startupPages=>{if(this.startupUrlDialogModel_)this.destroyUrlDialog_();this.startupPages_=startupPages;this.updateScrollableContents()});this.browserProxy_.loadStartupPages();this.addEventListener(settings.EDIT_STARTUP_URL_EVENT,event=>{this.startupUrlDialogModel_=event.detail.model;this.startupUrlDialogAnchor_=event.detail.anchor;this.showStartupUrlDialog_=true;event.stopPropagation()})},onAddPageTap_:function(e){e.preventDefault();this.showStartupUrlDialog_=true;this.startupUrlDialogAnchor_=this.$$("#addPage a[is=action-link]")},destroyUrlDialog_:function(){this.showStartupUrlDialog_=false;this.startupUrlDialogModel_=null;if(this.startupUrlDialogAnchor_){cr.ui.focusWithoutInk(assert(this.startupUrlDialogAnchor_));this.startupUrlDialogAnchor_=null}},onUseCurrentPagesTap_:function(){this.browserProxy_.useCurrentPages()},shouldAllowUrlsEdit_:function(){return this.get("prefs.session.startup_urls.enforcement")!=chrome.settingsPrivate.Enforcement.ENFORCED}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-on-startup-page",behaviors:[WebUIListenerBehavior],properties:{prefs:{type:Object,notify:true},ntpExtension_:Object,prefValues_:{readOnly:true,type:Object,value:{CONTINUE:1,OPEN_NEW_TAB:5,OPEN_SPECIFIC:4}}},attached:function(){const updateNtpExtension=ntpExtension=>{this.ntpExtension_=ntpExtension};settings.OnStartupBrowserProxyImpl.getInstance().getNtpExtension().then(updateNtpExtension);this.addWebUIListener("update-ntp-extension",updateNtpExtension)},showStartupUrls_:function(restoreOnStartup){return restoreOnStartup==this.prefValues_.OPEN_SPECIFIC}});
|
|
// Copyright 2018 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"cr-checkbox",behaviors:[Polymer.PaperRippleBehavior],properties:{checked:{type:Boolean,value:false,reflectToAttribute:true,observer:"checkedChanged_",notify:true},disabled:{type:Boolean,value:false,reflectToAttribute:true,observer:"disabledChanged_"}},hostAttributes:{"aria-disabled":"false","aria-checked":"false",role:"checkbox",tabindex:0},listeners:{click:"onClick_",keypress:"onKeyPress_",focus:"onFocus_",blur:"onBlur_"},ready:function(){this.removeAttribute("unresolved")},checkedChanged_:function(){this.setAttribute("aria-checked",this.checked?"true":"false")},disabledChanged_:function(current,previous){if(previous===undefined&&!this.disabled)return;this.setAttribute("tabindex",this.disabled?-1:0);this.setAttribute("aria-disabled",this.disabled?"true":"false")},onFocus_:function(){this.ensureRipple();this.$$("paper-ripple").holdDown=true},onBlur_:function(){this.ensureRipple();this.$$("paper-ripple").holdDown=false},shouldHandleEvent_:function(e){return!this.disabled&&e.target.tagName!="A"},onClick_:function(e){if(!this.shouldHandleEvent_(e))return;e.stopPropagation();e.preventDefault();this.toggleState_(false)},toggleState_:function(fromKeyboard){this.checked=!this.checked;if(!fromKeyboard){this.ensureRipple();this.$$("paper-ripple").holdDown=false}this.fire("change",this.checked)},onKeyPress_:function(e){if(!this.shouldHandleEvent_(e)||e.key!=" "&&e.key!="Enter")return;e.preventDefault();this.toggleState_(true)},onButtonFocus_:function(){this.focus()},_createRipple:function(){this._rippleContainer=this.$.checkbox;let ripple=Polymer.PaperRippleBehavior._createRipple();ripple.id="ink";ripple.setAttribute("recenters","");ripple.classList.add("circle","toggle-ink");return ripple}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"cr-expand-button",properties:{expanded:{type:Boolean,value:false,notify:true},disabled:{type:Boolean,value:false,reflectToAttribute:true},alt:String,tabIndex:{type:Number,value:0}},iconName_:function(expanded){return expanded?"icon-expand-less":"icon-expand-more"},toggleExpand_:function(event){this.expanded=!this.expanded;event.stopPropagation()},getAriaPressed_:function(expanded){return expanded?"true":"false"}});Polymer({is:"iron-collapse",behaviors:[Polymer.IronResizableBehavior],properties:{horizontal:{type:Boolean,value:false,observer:"_horizontalChanged"},opened:{type:Boolean,value:false,notify:true,observer:"_openedChanged"},transitioning:{type:Boolean,notify:true,readOnly:true},noAnimation:{type:Boolean},_desiredSize:{type:String,value:""}},get dimension(){return this.horizontal?"width":"height"},get _dimensionMax(){return this.horizontal?"maxWidth":"maxHeight"},get _dimensionMaxCss(){return this.horizontal?"max-width":"max-height"},hostAttributes:{role:"group","aria-hidden":"true"},listeners:{transitionend:"_onTransitionEnd"},toggle:function(){this.opened=!this.opened},show:function(){this.opened=true},hide:function(){this.opened=false},updateSize:function(size,animated){size=size==="auto"?"":size;var willAnimate=animated&&!this.noAnimation&&this.isAttached&&this._desiredSize!==size;this._desiredSize=size;this._updateTransition(false);if(willAnimate){var startSize=this._calcSize();if(size===""){this.style[this._dimensionMax]="";size=this._calcSize()}this.style[this._dimensionMax]=startSize;this.scrollTop=this.scrollTop;this._updateTransition(true);willAnimate=size!==startSize}this.style[this._dimensionMax]=size;if(!willAnimate){this._transitionEnd()}},enableTransition:function(enabled){Polymer.Base._warn("`enableTransition()` is deprecated, use `noAnimation` instead.");this.noAnimation=!enabled},_updateTransition:function(enabled){this.style.transitionDuration=enabled&&!this.noAnimation?"":"0s"},_horizontalChanged:function(){this.style.transitionProperty=this._dimensionMaxCss;var otherDimension=this._dimensionMax==="maxWidth"?"maxHeight":"maxWidth";this.style[otherDimension]="";this.updateSize(this.opened?"auto":"0px",false)},_openedChanged:function(){this.setAttribute("aria-hidden",!this.opened);this._setTransitioning(true);this.toggleClass("iron-collapse-closed",false);this.toggleClass("iron-collapse-opened",false);this.updateSize(this.opened?"auto":"0px",true);if(this.opened){this.focus()}},_transitionEnd:function(){this.style[this._dimensionMax]=this._desiredSize;this.toggleClass("iron-collapse-closed",!this.opened);this.toggleClass("iron-collapse-opened",this.opened);this._updateTransition(false);this.notifyResize();this._setTransitioning(false)},_onTransitionEnd:function(event){if(Polymer.dom(event).rootTarget===this){this._transitionEnd()}},_calcSize:function(){return this.getBoundingClientRect()[this.dimension]+"px"}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.exportPath("settings");settings.StoredAccount;settings.SyncStatus;settings.StatusAction={NO_ACTION:"noAction",REAUTHENTICATE:"reauthenticate",SIGNOUT_AND_SIGNIN:"signOutAndSignIn",UPGRADE_CLIENT:"upgradeClient",ENTER_PASSPHRASE:"enterPassphrase",CONFIRM_SYNC_SETTINGS:"confirmSyncSettings"};settings.SyncPrefs;settings.PageStatus={SPINNER:"spinner",CONFIGURE:"configure",TIMEOUT:"timeout",DONE:"done",PASSPHRASE_FAILED:"passphraseFailed"};cr.define("settings",function(){const PROMO_IMPRESSION_COUNT_KEY="signin-promo-count";class SyncBrowserProxy{startSignIn(){}signOut(deleteProfile){}manageOtherPeople(){}getPromoImpressionCount(){}incrementPromoImpressionCount(){}getSyncStatus(){}getStoredAccounts(){}didNavigateToSyncPage(){}didNavigateAwayFromSyncPage(didAbort){}setSyncDatatypes(syncPrefs){}setSyncEncryption(syncPrefs){}startSyncingWithEmail(email,isDefaultPromoAccount){}openActivityControlsUrl(){}}class SyncBrowserProxyImpl{startSignIn(){chrome.send("SyncSetupStartSignIn")}signOut(deleteProfile){chrome.send("SyncSetupStopSyncing",[deleteProfile])}manageOtherPeople(){chrome.send("SyncSetupManageOtherPeople")}getPromoImpressionCount(){return parseInt(window.localStorage.getItem(PROMO_IMPRESSION_COUNT_KEY),10)||0}incrementPromoImpressionCount(){window.localStorage.setItem(PROMO_IMPRESSION_COUNT_KEY,(this.getPromoImpressionCount()+1).toString())}getSyncStatus(){return cr.sendWithPromise("SyncSetupGetSyncStatus")}getStoredAccounts(){return cr.sendWithPromise("SyncSetupGetStoredAccounts")}didNavigateToSyncPage(){chrome.send("SyncSetupShowSetupUI")}didNavigateAwayFromSyncPage(didAbort){chrome.send("SyncSetupDidClosePage",[didAbort])}setSyncDatatypes(syncPrefs){return cr.sendWithPromise("SyncSetupSetDatatypes",JSON.stringify(syncPrefs))}setSyncEncryption(syncPrefs){return cr.sendWithPromise("SyncSetupSetEncryption",JSON.stringify(syncPrefs))}startSyncingWithEmail(email,isDefaultPromoAccount){chrome.send("SyncSetupStartSyncingWithEmail",[email,isDefaultPromoAccount])}openActivityControlsUrl(){chrome.metricsPrivate.recordUserAction("Signin_AccountSettings_GoogleActivityControlsClicked")}}cr.addSingletonGetter(SyncBrowserProxyImpl);return{SyncBrowserProxy:SyncBrowserProxy,SyncBrowserProxyImpl:SyncBrowserProxyImpl}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
let MetricsReporting;let SberPrefState;cr.define("settings",function(){class PrivacyPageBrowserProxy{getSafeBrowsingExtendedReporting(){}setSafeBrowsingExtendedReportingEnabled(enabled){}}class PrivacyPageBrowserProxyImpl{getSafeBrowsingExtendedReporting(){return cr.sendWithPromise("getSafeBrowsingExtendedReporting")}setSafeBrowsingExtendedReportingEnabled(enabled){chrome.send("setSafeBrowsingExtendedReportingEnabled",[enabled])}}cr.addSingletonGetter(PrivacyPageBrowserProxyImpl);return{PrivacyPageBrowserProxy:PrivacyPageBrowserProxy,PrivacyPageBrowserProxyImpl:PrivacyPageBrowserProxyImpl}});
|
|
// Copyright 2018 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
(function(){const NetworkPredictionOptions={ALWAYS:0,WIFI_ONLY:1,NEVER:2,DEFAULT:1};Polymer({is:"settings-personalization-options",behaviors:[WebUIListenerBehavior],properties:{prefs:{type:Object,notify:true},pageVisibility:Object,safeBrowsingExtendedReportingPref_:{type:Object,value:function(){return{}}},networkPredictionEnum_:{type:Object,value:NetworkPredictionOptions},unifiedConsentEnabled:Boolean},ready:function(){this.browserProxy_=settings.PrivacyPageBrowserProxyImpl.getInstance();const setSber=this.setSafeBrowsingExtendedReporting_.bind(this);this.addWebUIListener("safe-browsing-extended-reporting-change",setSber);this.browserProxy_.getSafeBrowsingExtendedReporting().then(setSber)},onSberChange_:function(){const enabled=this.$.safeBrowsingExtendedReportingControl.checked;this.browserProxy_.setSafeBrowsingExtendedReportingEnabled(enabled)},onLanguageLinkBoxClick_:function(e){if(e.target.tagName==="A"){e.preventDefault();settings.navigateTo(settings.routes.LANGUAGES)}},setSafeBrowsingExtendedReporting_:function(sberPrefState){const pref={key:"",type:chrome.settingsPrivate.PrefType.BOOLEAN,value:sberPrefState.enabled};if(sberPrefState.managed){pref.enforcement=chrome.settingsPrivate.Enforcement.ENFORCED;pref.controlledBy=chrome.settingsPrivate.ControlledBy.USER_POLICY}this.safeBrowsingExtendedReportingPref_=pref}})})();
|
|
// Copyright 2017 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"cr-toast",properties:{duration:{type:Number,value:0},open:{type:Boolean,value:false,reflectToAttribute:true}},observers:["resetAutoHide_(duration, open)"],hideTimeoutId_:null,resetAutoHide_:function(){if(this.hideTimeoutId_!=null){window.clearTimeout(this.hideTimeoutId_);this.hideTimeoutId_=null}if(this.open&&this.duration!=0){this.hideTimeoutId_=window.setTimeout(()=>{this.open=false},this.duration)}},show:function(duration){let shouldResetAutoHide=true;if(typeof duration!="undefined"&&duration>=0&&this.duration!=duration){this.duration=duration;shouldResetAutoHide=false}if(!this.open){this.open=true;shouldResetAutoHide=false}if(shouldResetAutoHide)this.resetAutoHide_()},hide:function(){this.open=false}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
(function(){const RadioButtonNames={ENCRYPT_WITH_GOOGLE:"encrypt-with-google",ENCRYPT_WITH_PASSPHRASE:"encrypt-with-passphrase"};const SyncPrefsIndividualDataTypes=["appsSynced","extensionsSynced","preferencesSynced","autofillSynced","typedUrlsSynced","themesSynced","bookmarksSynced","passwordsSynced","tabsSynced","paymentsIntegrationEnabled"];Polymer({is:"settings-sync-page",behaviors:[WebUIListenerBehavior,settings.RouteObserverBehavior],properties:{prefs:{type:Object,notify:true},pages_:{type:Object,value:settings.PageStatus,readOnly:true},pageStatus_:{type:String,value:settings.PageStatus.CONFIGURE},pageVisibility:Object,syncPrefs:{type:Object},syncStatus:{type:Object,observer:"onSyncStatusChanged_"},creatingNewPassphrase_:{type:Boolean,value:false},passphrase_:{type:String,value:""},confirmation_:{type:String,value:""},existingPassphrase_:{type:String,value:""},syncSectionDisabled_:{type:Boolean,value:false,computed:"computeSyncSectionDisabled_("+"unifiedConsentEnabled, syncStatus.signedIn)"},personalizeSectionOpened_:{type:Boolean,value:true},syncSectionOpened_:{type:Boolean,value:true},diceEnabled:Boolean,unifiedConsentEnabled:Boolean},browserProxy_:null,beforeunloadCallback_:null,didAbort_:false,cachedSyncPrefs_:null,created:function(){this.browserProxy_=settings.SyncBrowserProxyImpl.getInstance()},attached:function(){this.addWebUIListener("page-status-changed",this.handlePageStatusChanged_.bind(this));this.addWebUIListener("sync-prefs-changed",this.handleSyncPrefsChanged_.bind(this));if(settings.getCurrentRoute()==settings.routes.SYNC)this.onNavigateToPage_()},detached:function(){if(settings.getCurrentRoute()==settings.routes.SYNC)this.onNavigateAwayFromPage_();if(this.beforeunloadCallback_){window.removeEventListener("beforeunload",this.beforeunloadCallback_);this.beforeunloadCallback_=null}},computeSyncSectionDisabled_(){return this.unifiedConsentEnabled&&!this.syncStatus.signedIn},currentRouteChanged:function(){if(settings.getCurrentRoute()==settings.routes.SYNC)this.onNavigateToPage_();else this.onNavigateAwayFromPage_()},isStatus_:function(expectedPageStatus){return expectedPageStatus==this.pageStatus_},onNavigateToPage_:function(){assert(settings.getCurrentRoute()==settings.routes.SYNC);if(this.beforeunloadCallback_)return;this.pageStatus_=settings.PageStatus.SPINNER;this.browserProxy_.didNavigateToSyncPage();this.beforeunloadCallback_=this.onNavigateAwayFromPage_.bind(this);window.addEventListener("beforeunload",this.beforeunloadCallback_)},onNavigateAwayFromPage_:function(){if(!this.beforeunloadCallback_)return;this.pageStatus_=settings.PageStatus.CONFIGURE;this.browserProxy_.didNavigateAwayFromSyncPage(this.didAbort_);this.didAbort_=false;window.removeEventListener("beforeunload",this.beforeunloadCallback_);this.beforeunloadCallback_=null},handleSyncPrefsChanged_:function(syncPrefs){this.syncPrefs=syncPrefs;this.pageStatus_=settings.PageStatus.CONFIGURE;if(!this.syncPrefs.autofillRegistered||!this.syncPrefs.autofillSynced)this.set("syncPrefs.paymentsIntegrationEnabled",false);if(this.syncPrefs.encryptAllData)this.creatingNewPassphrase_=false;if(this.syncPrefs.passphraseRequired){listenOnce(document,"show-container",()=>{const input=this.$$("#existingPassphraseInput");input.focus()})}},onSyncAllDataTypesChanged_:function(event){if(event.target.checked){this.set("syncPrefs.syncAllDataTypes",true);this.cachedSyncPrefs_={};for(const dataType of SyncPrefsIndividualDataTypes){this.cachedSyncPrefs_[dataType]=this.syncPrefs[dataType];this.set(["syncPrefs",dataType],true)}}else if(this.cachedSyncPrefs_){for(const dataType of SyncPrefsIndividualDataTypes){this.set(["syncPrefs",dataType],this.cachedSyncPrefs_[dataType])}}this.onSingleSyncDataTypeChanged_()},onSingleSyncDataTypeChanged_:function(){assert(this.syncPrefs);this.browserProxy_.setSyncDatatypes(this.syncPrefs).then(this.handlePageStatusChanged_.bind(this))},onActivityControlsTap_:function(){this.browserProxy_.openActivityControlsUrl()},onAutofillDataTypeChanged_:function(){this.set("syncPrefs.paymentsIntegrationEnabled",this.syncPrefs.autofillSynced);this.onSingleSyncDataTypeChanged_()},isSaveNewPassphraseEnabled_:function(passphrase,confirmation){return passphrase!==""&&confirmation!==""},onSaveNewPassphraseTap_:function(e){assert(this.creatingNewPassphrase_);if(e.target.tagName!="PAPER-BUTTON"&&e.target.tagName!="PAPER-INPUT")return;if(e.type=="keypress"&&e.key!="Enter")return;if(!this.validateCreatedPassphrases_())return;this.syncPrefs.encryptAllData=true;this.syncPrefs.setNewPassphrase=true;this.syncPrefs.passphrase=this.passphrase_;this.browserProxy_.setSyncEncryption(this.syncPrefs).then(this.handlePageStatusChanged_.bind(this))},onSubmitExistingPassphraseTap_:function(e){if(e.type=="keypress"&&e.key!="Enter")return;assert(!this.creatingNewPassphrase_);this.syncPrefs.setNewPassphrase=false;this.syncPrefs.passphrase=this.existingPassphrase_;this.existingPassphrase_="";this.browserProxy_.setSyncEncryption(this.syncPrefs).then(this.handlePageStatusChanged_.bind(this))},handlePageStatusChanged_:function(pageStatus){switch(pageStatus){case settings.PageStatus.SPINNER:case settings.PageStatus.TIMEOUT:case settings.PageStatus.CONFIGURE:this.pageStatus_=pageStatus;return;case settings.PageStatus.DONE:if(settings.getCurrentRoute()==settings.routes.SYNC)settings.navigateTo(settings.routes.PEOPLE);return;case settings.PageStatus.PASSPHRASE_FAILED:if(this.pageStatus_==this.pages_.CONFIGURE&&this.syncPrefs&&this.syncPrefs.passphraseRequired){this.$$("#existingPassphraseInput").invalid=true}return}assertNotReached()},onEncryptionRadioSelectionChanged_:function(event){this.creatingNewPassphrase_=event.target.selected==RadioButtonNames.ENCRYPT_WITH_PASSPHRASE},selectedEncryptionRadio_:function(){return this.syncPrefs.encryptAllData||this.creatingNewPassphrase_?RadioButtonNames.ENCRYPT_WITH_PASSPHRASE:RadioButtonNames.ENCRYPT_WITH_GOOGLE},enterPassphrasePrompt_:function(){if(this.syncPrefs&&this.syncPrefs.passphraseTypeIsCustom)return this.syncPrefs.enterPassphraseBody;return this.syncPrefs.enterGooglePassphraseBody},shouldSyncCheckboxBeDisabled_:function(syncAllDataTypes,enforced){return syncAllDataTypes||enforced},shouldPaymentsCheckboxBeDisabled_:function(syncAllDataTypes,autofillSynced){return syncAllDataTypes||!autofillSynced},validateCreatedPassphrases_:function(){const emptyPassphrase=!this.passphrase_;const mismatchedPassphrase=this.passphrase_!=this.confirmation_;this.$$("#passphraseInput").invalid=emptyPassphrase;this.$$("#passphraseConfirmationInput").invalid=!emptyPassphrase&&mismatchedPassphrase;return!emptyPassphrase&&!mismatchedPassphrase},onLearnMoreTap_:function(event){if(event.target.tagName=="A"){event.stopPropagation()}},onCancelSyncClick_:function(){this.didAbort_=true;settings.navigateTo(settings.routes.BASIC)},onSyncStatusChanged_:function(){this.syncSectionOpened_=!!this.syncStatus.signedIn},toggleExpandButton_:function(e){const expandButtonTag="CR-EXPAND-BUTTON";if(e.target.tagName==expandButtonTag)return;if(!e.currentTarget.hasAttribute("actionable"))return;const expandButton=e.currentTarget.querySelector(expandButtonTag);assert(expandButton);expandButton.expanded=!expandButton.expanded},getListFrameClass_:function(){return this.unifiedConsentEnabled?"list-frame":""},getListItemClass_:function(){return this.unifiedConsentEnabled?"list-item":"settings-box"},shouldShowSyncAccountControl_:function(){return!!this.diceEnabled&&!!this.unifiedConsentEnabled&&!!this.syncStatus.syncSystemEnabled&&!!this.syncStatus.signinAllowed}})})();
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.exportPath("settings");settings.ProfileInfo;cr.define("settings",function(){class ProfileInfoBrowserProxy{getProfileInfo(){}getProfileStatsCount(){}}class ProfileInfoBrowserProxyImpl{getProfileInfo(){return cr.sendWithPromise("getProfileInfo")}getProfileStatsCount(){chrome.send("getProfileStatsCount")}}cr.addSingletonGetter(ProfileInfoBrowserProxyImpl);return{ProfileInfoBrowserProxyImpl:ProfileInfoBrowserProxyImpl}});
|
|
// Copyright 2018 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.exportPath("settings");settings.MAX_SIGNIN_PROMO_IMPRESSION=10;Polymer({is:"settings-sync-account-control",behaviors:[WebUIListenerBehavior],properties:{syncStatus:Object,promoLabelWithAccount:String,promoLabelWithNoAccount:String,promoSecondaryLabelWithAccount:String,promoSecondaryLabelWithNoAccount:String,signedIn_:{type:Boolean,computed:"computeSignedIn_(syncStatus.signedIn)",observer:"onSignedInChanged_"},storedAccounts_:Object,shownAccount_:Object,showingPromo:{type:Boolean,value:false,reflectToAttribute:true},alwaysShowPromo:{type:Boolean,reflectToAttribute:true},shouldShowAvatarRow_:{type:Boolean,value:false,computed:"computeShouldShowAvatarRow_(storedAccounts_, syncStatus,"+"storedAccounts_.length, syncStatus.signedIn)",observer:"onShouldShowAvatarRowChange_"}},observers:["onShownAccountShouldChange_(storedAccounts_, syncStatus)"],syncBrowserProxy_:null,created:function(){this.syncBrowserProxy_=settings.SyncBrowserProxyImpl.getInstance()},attached:function(){this.syncBrowserProxy_.getStoredAccounts().then(this.handleStoredAccounts_.bind(this));this.addWebUIListener("stored-accounts-updated",this.handleStoredAccounts_.bind(this))},recordImpressionUserActions_:function(){assert(!this.syncStatus.signedIn);assert(this.shownAccount_!==undefined);chrome.metricsPrivate.recordUserAction("Signin_Impression_FromSettings");if(this.shownAccount_){chrome.metricsPrivate.recordUserAction("Signin_ImpressionWithAccount_FromSettings")}else{chrome.metricsPrivate.recordUserAction("Signin_ImpressionWithNoAccount_FromSettings")}},computeSignedIn_:function(){return!!this.syncStatus.signedIn},onSignedInChanged_:function(){if(this.alwaysShowPromo){this.showingPromo=true;return}if(!this.showingPromo&&!this.syncStatus.signedIn&&this.syncBrowserProxy_.getPromoImpressionCount()<settings.MAX_SIGNIN_PROMO_IMPRESSION){this.showingPromo=true;this.syncBrowserProxy_.incrementPromoImpressionCount()}else{this.showingPromo=false}if(!this.syncStatus.signedIn&&this.shownAccount_!==undefined)this.recordImpressionUserActions_()},getLabel_:function(labelWithAccount,labelWithNoAccount){return this.shownAccount_?labelWithAccount:labelWithNoAccount},getSubstituteLabel_:function(label,name){return loadTimeData.substituteString(label,name)},getErrorLabel_:function(syncErrorLabel,authErrorLabel){if(this.syncStatus.hasError){return this.syncStatus.statusAction==settings.StatusAction.REAUTHENTICATE?authErrorLabel:syncErrorLabel}return""},getAccountLabel_:function(label,account){return this.syncStatus.signedIn&&!this.syncStatus.hasError?loadTimeData.substituteString(label,account):account},getAccountImageSrc_:function(image){return image||"chrome://theme/IDR_PROFILE_AVATAR_PLACEHOLDER_LARGE"},getSyncIcon_:function(){if(this.syncStatus.hasError){return this.syncStatus.statusAction==settings.StatusAction.REAUTHENTICATE?"sync-disabled":"sync-problem"}return"sync"},handleStoredAccounts_:function(accounts){this.storedAccounts_=accounts},computeShouldShowAvatarRow_:function(){return this.syncStatus.signedIn||this.storedAccounts_.length>0},onSigninTap_:function(){this.syncBrowserProxy_.startSignIn();if(this.$$("#menu")){this.$$("#menu").close()}},onSyncButtonTap_:function(){assert(this.shownAccount_);assert(this.storedAccounts_.length>0);const isDefaultPromoAccount=this.shownAccount_.email==this.storedAccounts_[0].email;this.syncBrowserProxy_.startSyncingWithEmail(this.shownAccount_.email,isDefaultPromoAccount)},onTurnOffButtonTap_:function(){settings.navigateTo(settings.routes.SIGN_OUT)},onMenuButtonTap_:function(){const actionMenu=this.$$("#menu");actionMenu.showAt(assert(this.$$("#dropdown-arrow")))},onShouldShowAvatarRowChange_:function(){const actionMenu=this.$$("#menu");if(!this.shouldShowAvatarRow_&&actionMenu&&actionMenu.open)actionMenu.close()},onAccountTap_:function(e){this.shownAccount_=e.model.item;this.$$("#menu").close()},onShownAccountShouldChange_:function(){if(this.syncStatus.signedIn){for(let i=0;i<this.storedAccounts_.length;i++){if(this.storedAccounts_[i].email==this.syncStatus.signedInUsername){this.shownAccount_=this.storedAccounts_[i];return}}}else{const firstStoredAccount=this.storedAccounts_.length>0?this.storedAccounts_[0]:null;const shouldRecordImpression=this.shownAccount_===undefined||!this.shownAccount_&&firstStoredAccount||this.shownAccount_&&!firstStoredAccount;this.shownAccount_=firstStoredAccount;if(shouldRecordImpression)this.recordImpressionUserActions_()}}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-checkbox",behaviors:[SettingsBooleanControlBehavior],properties:{subLabelHtml:{type:String,value:""}},observers:["subLabelHtmlChanged_(subLabelHtml)"],subLabelHtmlChanged_:function(){const links=this.root.querySelectorAll(".secondary.label a");links.forEach(link=>{link.addEventListener("click",this.stopPropagation)})},stopPropagation:function(event){event.stopPropagation()},hasSubLabel_:function(subLabel,subLabelHtml){return!!subLabel||!!subLabelHtml}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.exportPath("settings");settings.BrowserProfile;settings.ImportDataStatus={INITIAL:"initial",IN_PROGRESS:"inProgress",SUCCEEDED:"succeeded",FAILED:"failed"};cr.define("settings",function(){class ImportDataBrowserProxy{initializeImportDialog(){}importData(sourceBrowserProfileIndex){}importFromBookmarksFile(){}}class ImportDataBrowserProxyImpl{initializeImportDialog(){return cr.sendWithPromise("initializeImportDialog")}importData(sourceBrowserProfileIndex){chrome.send("importData",[sourceBrowserProfileIndex])}importFromBookmarksFile(){chrome.send("importFromBookmarksFile")}}cr.addSingletonGetter(ImportDataBrowserProxyImpl);return{ImportDataBrowserProxy:ImportDataBrowserProxy,ImportDataBrowserProxyImpl:ImportDataBrowserProxyImpl}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
const PrefsBehavior={properties:{prefs:{type:Object,notify:true}},getPref:function(prefPath){const pref=this.get(prefPath,this.prefs);assert(typeof pref!="undefined","Pref is missing: "+prefPath);return pref},setPrefValue:function(prefPath,value){this.getPref(prefPath);this.set("prefs."+prefPath+".value",value)},appendPrefListItem:function(key,item){const pref=this.getPref(key);assert(pref&&pref.type==chrome.settingsPrivate.PrefType.LIST);if(pref.value.indexOf(item)==-1)this.push("prefs."+key+".value",item)},deletePrefListItem:function(key,item){assert(this.getPref(key).type==chrome.settingsPrivate.PrefType.LIST);this.arrayDelete("prefs."+key+".value",item)}};
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-import-data-dialog",behaviors:[I18nBehavior,WebUIListenerBehavior,PrefsBehavior],properties:{browserProfiles_:Array,selected_:Object,noImportDataTypeSelected_:{type:Boolean,value:false},importStatus_:{type:String,value:settings.ImportDataStatus.INITIAL},importStatusEnum_:{type:Object,value:settings.ImportDataStatus}},observers:["prefsChanged_(selected_, prefs.*)"],browserProxy_:null,attached:function(){this.browserProxy_=settings.ImportDataBrowserProxyImpl.getInstance();this.browserProxy_.initializeImportDialog().then(data=>{this.browserProfiles_=data;this.selected_=this.browserProfiles_[0];this.$.dialog.showModal()});this.addWebUIListener("import-data-status-changed",importStatus=>{this.importStatus_=importStatus;if(this.hasImportStatus_(settings.ImportDataStatus.FAILED))this.closeDialog_()})},prefsChanged_:function(){this.noImportDataTypeSelected_=!(this.getPref("import_dialog_history").value&&this.selected_.history)&&!(this.getPref("import_dialog_bookmarks").value&&this.selected_.favorites)&&!(this.getPref("import_dialog_saved_passwords").value&&this.selected_.passwords)&&!(this.getPref("import_dialog_search_engine").value&&this.selected_.search)&&!(this.getPref("import_dialog_autofill_form_data").value&&this.selected_.autofillFormData)},hasImportStatus_:function(status){return this.importStatus_==status},isImportFromFileSelected_:function(){return this.selected_.index==this.browserProfiles_.length-1},getActionButtonText_:function(){return this.i18n(this.isImportFromFileSelected_()?"importChooseFile":"importCommit")},onBrowserProfileSelectionChange_:function(){this.selected_=this.browserProfiles_[this.$.browserSelect.selectedIndex]},onActionButtonTap_:function(){if(this.isImportFromFileSelected_())this.browserProxy_.importFromBookmarksFile();else this.browserProxy_.importData(this.$.browserSelect.selectedIndex)},closeDialog_:function(){this.$.dialog.close()},shouldDisableImport_:function(){return this.hasImportStatus_(settings.ImportDataStatus.IN_PROGRESS)||this.noImportDataTypeSelected_}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"cr-profile-avatar-selector-grid",properties:{ignoreModifiedKeyEvents:{type:Boolean,value:false}},listeners:{keydown:"onKeyDown_"},onKeyDown_:function(e){var items=this.querySelectorAll(".avatar");switch(e.key){case"ArrowDown":case"ArrowUp":this.moveFocusRow_(items,e.key);e.preventDefault();return;case"ArrowLeft":case"ArrowRight":if(this.ignoreModifiedKeyEvents&&hasKeyModifiers(e))return;this.moveFocusRow_(items,e.key);e.preventDefault();return}},moveFocusRow_:function(items,direction){var offset=direction=="ArrowDown"||direction=="ArrowRight"?1:-1;var style=getComputedStyle(this);var avatarSpacing=parseInt(style.getPropertyValue("--avatar-spacing"),10);var avatarSize=parseInt(style.getPropertyValue("--avatar-size"),10);var rowSize=Math.floor(this.clientWidth/(avatarSpacing+avatarSize));var rows=Math.ceil(items.length/rowSize);var gridSize=rows*rowSize;var focusIndex=Array.prototype.slice.call(items).findIndex(function(item){return Polymer.dom(item).getOwnerRoot().activeElement==item});var nextItem=null;if(direction=="ArrowDown"||direction=="ArrowUp"){for(var i=offset;Math.abs(i)<=rows;i+=offset){nextItem=items[(focusIndex+i*rowSize+gridSize)%gridSize];if(nextItem)break}}else{if(style.direction=="rtl")offset*=-1;var nextIndex=(focusIndex+offset)%items.length;if(nextIndex<0)nextIndex=items.length-1;nextItem=items[nextIndex]}nextItem.focus();assert(Polymer.dom(nextItem).getOwnerRoot().activeElement==nextItem)}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
let AvatarIcon;Polymer({is:"cr-profile-avatar-selector",properties:{avatars:{type:Array,value:function(){return[]}},selectedAvatar:{type:Object,notify:true},selectedAvatarElement_:Object,ignoreModifiedKeyEvents:{type:Boolean,value:false}},getSelectedClass_:function(isSelected){return isSelected?"iron-selected":""},getIconImageSet_:function(iconUrl){return cr.icon.getImage(iconUrl)},onAvatarTap_:function(e){if(this.selectedAvatarElement_)this.selectedAvatarElement_.classList.remove("iron-selected");this.selectedAvatarElement_=e.target;this.selectedAvatarElement_.classList.add("iron-selected");this.selectedAvatar=e.model.item}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
const ProfileShortcutStatus={PROFILE_SHORTCUT_SETTING_HIDDEN:"profileShortcutSettingHidden",PROFILE_SHORTCUT_NOT_FOUND:"profileShortcutNotFound",PROFILE_SHORTCUT_FOUND:"profileShortcutFound"};cr.define("settings",function(){class ManageProfileBrowserProxy{getAvailableIcons(){}setProfileIconToGaiaAvatar(){}setProfileIconToDefaultAvatar(iconUrl){}setProfileName(name){}getProfileShortcutStatus(){}addProfileShortcut(){}removeProfileShortcut(){}}class ManageProfileBrowserProxyImpl{getAvailableIcons(){return cr.sendWithPromise("getAvailableIcons")}setProfileIconToGaiaAvatar(){chrome.send("setProfileIconToGaiaAvatar")}setProfileIconToDefaultAvatar(iconUrl){chrome.send("setProfileIconToDefaultAvatar",[iconUrl])}setProfileName(name){chrome.send("setProfileName",[name])}getProfileShortcutStatus(){return cr.sendWithPromise("requestProfileShortcutStatus")}addProfileShortcut(){chrome.send("addProfileShortcut")}removeProfileShortcut(){chrome.send("removeProfileShortcut")}}cr.addSingletonGetter(ManageProfileBrowserProxyImpl);return{ManageProfileBrowserProxy:ManageProfileBrowserProxy,ManageProfileBrowserProxyImpl:ManageProfileBrowserProxyImpl}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-manage-profile",behaviors:[WebUIListenerBehavior,settings.RouteObserverBehavior],properties:{profileAvatar_:{type:Object,observer:"profileAvatarChanged_"},profileName:String,hasProfileShortcut_:Boolean,availableIcons:{type:Array,value:function(){return[]}},syncStatus:Object,isProfileShortcutSettingVisible_:Boolean},browserProxy_:null,created:function(){this.browserProxy_=settings.ManageProfileBrowserProxyImpl.getInstance()},attached:function(){const setIcons=icons=>{this.availableIcons=icons};this.addWebUIListener("available-icons-changed",setIcons);this.browserProxy_.getAvailableIcons().then(setIcons)},currentRouteChanged:function(){if(settings.getCurrentRoute()==settings.routes.MANAGE_PROFILE){this.$.name.value=this.profileName;if(loadTimeData.getBoolean("profileShortcutsEnabled")){this.browserProxy_.getProfileShortcutStatus().then(status=>{if(status==ProfileShortcutStatus.PROFILE_SHORTCUT_SETTING_HIDDEN){this.isProfileShortcutSettingVisible_=false;return}this.isProfileShortcutSettingVisible_=true;this.hasProfileShortcut_=status==ProfileShortcutStatus.PROFILE_SHORTCUT_FOUND})}}},onProfileNameChanged_:function(event){if(event.target.invalid)return;this.browserProxy_.setProfileName(event.target.value)},onProfileNameKeydown_:function(event){if(event.key=="Escape"){event.target.value=this.profileName;event.target.blur()}},profileAvatarChanged_:function(){if(this.profileAvatar_.isGaiaAvatar)this.browserProxy_.setProfileIconToGaiaAvatar();else this.browserProxy_.setProfileIconToDefaultAvatar(this.profileAvatar_.url)},isProfileNameDisabled_:function(syncStatus){return!!syncStatus.supervisedUser&&!syncStatus.childUser},onHasProfileShortcutChange_:function(event){if(this.hasProfileShortcut_){this.browserProxy_.addProfileShortcut()}else{this.browserProxy_.removeProfileShortcut()}}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-people-page",behaviors:[settings.RouteObserverBehavior,I18nBehavior,WebUIListenerBehavior],properties:{prefs:{type:Object,notify:true},diceEnabled_:{type:Boolean,value:function(){return loadTimeData.getBoolean("diceEnabled")}},unifiedConsentEnabled_:{type:Boolean,value:function(){return loadTimeData.getBoolean("unifiedConsentEnabled")}},syncStatus:Object,pageVisibility:Object,profileIconUrl_:String,profileName_:String,deleteProfileWarning_:String,deleteProfileWarningVisible_:Boolean,deleteProfile_:Boolean,showImportDataDialog_:{type:Boolean,value:false},showDisconnectDialog_:Boolean,focusConfig_:{type:Object,value:function(){const map=new Map;if(settings.routes.SYNC)map.set(settings.routes.SYNC.path,"#sync-status .subpage-arrow");if(settings.routes.MANAGE_PROFILE){map.set(settings.routes.MANAGE_PROFILE.path,"#picture-subpage-trigger .subpage-arrow")}return map}}},syncBrowserProxy_:null,attached:function(){const profileInfoProxy=settings.ProfileInfoBrowserProxyImpl.getInstance();profileInfoProxy.getProfileInfo().then(this.handleProfileInfo_.bind(this));this.addWebUIListener("profile-info-changed",this.handleProfileInfo_.bind(this));this.addWebUIListener("profile-stats-count-ready",this.handleProfileStatsCount_.bind(this));this.syncBrowserProxy_=settings.SyncBrowserProxyImpl.getInstance();this.syncBrowserProxy_.getSyncStatus().then(this.handleSyncStatus_.bind(this));this.addWebUIListener("sync-status-changed",this.handleSyncStatus_.bind(this));this.addWebUIListener("sync-settings-saved",()=>{this.$.toast.show()})},currentRouteChanged:function(){this.showImportDataDialog_=settings.getCurrentRoute()==settings.routes.IMPORT_DATA;if(settings.getCurrentRoute()==settings.routes.SIGN_OUT){settings.ProfileInfoBrowserProxyImpl.getInstance().getProfileStatsCount();if(this.syncStatus&&!this.syncStatus.signedIn){settings.navigateToPreviousRoute()}else{this.showDisconnectDialog_=true;this.async(()=>{this.$$("#disconnectDialog").showModal()})}}else if(this.showDisconnectDialog_){this.$$("#disconnectDialog").close()}},handleProfileInfo_:function(info){this.profileName_=info.name;this.profileIconUrl_=info.iconUrl},handleProfileStatsCount_:function(count){this.deleteProfileWarning_=count>0?count==1?loadTimeData.getStringF("deleteProfileWarningWithCountsSingular",this.syncStatus.signedInUsername):loadTimeData.getStringF("deleteProfileWarningWithCountsPlural",count,this.syncStatus.signedInUsername):loadTimeData.getStringF("deleteProfileWarningWithoutCounts",this.syncStatus.signedInUsername)},handleSyncStatus_:function(syncStatus){const shouldRecordSigninImpression=!this.syncStatus&&syncStatus&&this.showSignin_(syncStatus);if(!syncStatus.signedIn&&this.showDisconnectDialog_)this.$$("#disconnectDialog").close();this.syncStatus=syncStatus;if(shouldRecordSigninImpression&&!this.shouldShowSyncAccountControl_()){chrome.metricsPrivate.recordUserAction("Signin_Impression_FromSettings")}},onProfileTap_:function(){settings.navigateTo(settings.routes.MANAGE_PROFILE)},onSigninTap_:function(){this.syncBrowserProxy_.startSignIn()},onDisconnectClosed_:function(){this.showDisconnectDialog_=false;if(!this.diceEnabled_){cr.ui.focusWithoutInk(assert(this.$$("#disconnectButton")))}if(settings.getCurrentRoute()==settings.routes.SIGN_OUT)settings.navigateToPreviousRoute();this.fire("signout-dialog-closed")},onDisconnectTap_:function(){settings.navigateTo(settings.routes.SIGN_OUT)},onDisconnectCancel_:function(){this.$$("#disconnectDialog").close()},onDisconnectConfirm_:function(){const deleteProfile=!!this.syncStatus.domain||this.deleteProfile_;listenOnce(this,"signout-dialog-closed",()=>{this.syncBrowserProxy_.signOut(deleteProfile)});this.$$("#disconnectDialog").close()},onSyncTap_:function(){if(this.unifiedConsentEnabled_){settings.navigateTo(settings.routes.SYNC);return}assert(this.syncStatus.signedIn);assert(this.syncStatus.syncSystemEnabled);if(!this.isSyncStatusActionable_(this.syncStatus))return;switch(this.syncStatus.statusAction){case settings.StatusAction.REAUTHENTICATE:this.syncBrowserProxy_.startSignIn();break;case settings.StatusAction.SIGNOUT_AND_SIGNIN:if(this.syncStatus.domain)settings.navigateTo(settings.routes.SIGN_OUT);else{this.syncBrowserProxy_.signOut(false);this.syncBrowserProxy_.startSignIn()}break;case settings.StatusAction.UPGRADE_CLIENT:settings.navigateTo(settings.routes.ABOUT);break;case settings.StatusAction.ENTER_PASSPHRASE:case settings.StatusAction.CONFIRM_SYNC_SETTINGS:case settings.StatusAction.NO_ACTION:default:settings.navigateTo(settings.routes.SYNC)}},onManageOtherPeople_:function(){this.syncBrowserProxy_.manageOtherPeople()},getDomainHtml_:function(domain){const innerSpan='<span id="managed-by-domain-name">'+domain+"</span>";return loadTimeData.getStringF("domainManagedProfile",innerSpan)},onImportDataTap_:function(){settings.navigateTo(settings.routes.IMPORT_DATA)},onImportDataDialogClosed_:function(){settings.navigateToPreviousRoute();cr.ui.focusWithoutInk(assert(this.$.importDataDialogTrigger))},shouldShowSyncAccountControl_:function(){return!!this.diceEnabled_&&!!this.syncStatus.syncSystemEnabled&&!!this.syncStatus.signinAllowed},getDisconnectExplanationHtml_:function(domain){if(domain){return loadTimeData.getStringF("syncDisconnectManagedProfileExplanation",'<span id="managed-by-domain-name">'+domain+"</span>")}return loadTimeData.getString("syncDisconnectExplanation")},isAdvancedSyncSettingsVisible_:function(syncStatus){return!!syncStatus&&!!syncStatus.signedIn&&!!syncStatus.syncSystemEnabled&&!this.unifiedConsentEnabled_},isSyncStatusActionable_:function(syncStatus){return!!syncStatus&&!syncStatus.managed&&(!syncStatus.hasError||syncStatus.statusAction!=settings.StatusAction.NO_ACTION)},getSyncIcon_:function(syncStatus){if(!syncStatus)return"";let syncIcon="settings:sync";if(syncStatus.hasError)syncIcon="settings:sync-problem";if(syncStatus.managed||syncStatus.statusAction==settings.StatusAction.REAUTHENTICATE)syncIcon="settings:sync-disabled";return syncIcon},getSyncStatusClass_:function(syncStatus){if(syncStatus&&syncStatus.hasError){return syncStatus.statusAction==settings.StatusAction.REAUTHENTICATE?"auth-error":"sync-error"}return""},getIconImageSet_:function(iconUrl){return cr.icon.getImage(iconUrl)},showSignin_:function(syncStatus){return!!syncStatus.signinAllowed&&!syncStatus.signedIn}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.define("settings",function(){class ResetBrowserProxy{performResetProfileSettings(sendSettings,requestOrigin){}onHideResetProfileDialog(){}onHideResetProfileBanner(){}onShowResetProfileDialog(){}showReportedSettings(){}getTriggeredResetToolName(){}}class ResetBrowserProxyImpl{performResetProfileSettings(sendSettings,requestOrigin){return cr.sendWithPromise("performResetProfileSettings",sendSettings,requestOrigin)}onHideResetProfileDialog(){chrome.send("onHideResetProfileDialog")}onHideResetProfileBanner(){chrome.send("onHideResetProfileBanner")}onShowResetProfileDialog(){chrome.send("onShowResetProfileDialog")}showReportedSettings(){cr.sendWithPromise("getReportedSettings").then(function(settings){const output=settings.map(function(entry){return entry.key+": "+entry.value.replace(/\n/g,", ")});const win=window.open("about:blank");const div=win.document.createElement("div");div.textContent=output.join("\n");div.style.whiteSpace="pre";win.document.body.appendChild(div)})}getTriggeredResetToolName(){return cr.sendWithPromise("getTriggeredResetToolName")}}cr.addSingletonGetter(ResetBrowserProxyImpl);return{ResetBrowserProxy:ResetBrowserProxy,ResetBrowserProxyImpl:ResetBrowserProxyImpl}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-reset-profile-banner",listeners:{cancel:"onCancel_"},attached:function(){this.$.dialog.showModal()},onOkTap_:function(){this.$.dialog.cancel()},onCancel_:function(){settings.ResetBrowserProxyImpl.getInstance().onHideResetProfileBanner()},onResetTap_:function(){this.$.dialog.close();settings.navigateTo(settings.routes.RESET_DIALOG)}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
let SearchEngine;let SearchEnginesInfo;cr.define("settings",function(){class SearchEnginesBrowserProxy{setDefaultSearchEngine(modelIndex){}removeSearchEngine(modelIndex){}searchEngineEditStarted(modelIndex){}searchEngineEditCancelled(){}searchEngineEditCompleted(searchEngine,keyword,queryUrl){}getSearchEnginesList(){}validateSearchEngineInput(fieldName,fieldValue){}turnOnGoogleAssistant(){}}class SearchEnginesBrowserProxyImpl{setDefaultSearchEngine(modelIndex){chrome.send("setDefaultSearchEngine",[modelIndex])}removeSearchEngine(modelIndex){chrome.send("removeSearchEngine",[modelIndex])}searchEngineEditStarted(modelIndex){chrome.send("searchEngineEditStarted",[modelIndex])}searchEngineEditCancelled(){chrome.send("searchEngineEditCancelled")}searchEngineEditCompleted(searchEngine,keyword,queryUrl){chrome.send("searchEngineEditCompleted",[searchEngine,keyword,queryUrl])}getSearchEnginesList(){return cr.sendWithPromise("getSearchEnginesList")}validateSearchEngineInput(fieldName,fieldValue){return cr.sendWithPromise("validateSearchEngineInput",fieldName,fieldValue)}turnOnGoogleAssistant(){chrome.send("turnOnGoogleAssistant")}}cr.addSingletonGetter(SearchEnginesBrowserProxyImpl);return{SearchEnginesBrowserProxy:SearchEnginesBrowserProxy,SearchEnginesBrowserProxyImpl:SearchEnginesBrowserProxyImpl}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-search-engine-dialog",behaviors:[WebUIListenerBehavior],properties:{model:Object,searchEngine_:String,keyword_:String,queryUrl_:String,dialogTitle_:String,actionButtonText_:String},browserProxy_:null,DEFAULT_MODEL_INDEX:-1,created:function(){this.browserProxy_=settings.SearchEnginesBrowserProxyImpl.getInstance()},ready:function(){if(this.model){this.dialogTitle_=loadTimeData.getString("searchEnginesEditSearchEngine");this.actionButtonText_=loadTimeData.getString("save");this.searchEngine_=this.model.name;this.keyword_=this.model.keyword;this.queryUrl_=this.model.url}else{this.dialogTitle_=loadTimeData.getString("searchEnginesAddSearchEngine");this.actionButtonText_=loadTimeData.getString("add")}this.addEventListener("cancel",()=>{this.browserProxy_.searchEngineEditCancelled()});this.addWebUIListener("search-engines-changed",this.enginesChanged_.bind(this))},attached:function(){this.async(this.updateActionButtonState_.bind(this));this.browserProxy_.searchEngineEditStarted(this.model?this.model.modelIndex:this.DEFAULT_MODEL_INDEX);this.$.dialog.showModal()},enginesChanged_:function(searchEnginesInfo){if(this.model){const engineWasRemoved=["defaults","others","extensions"].every(engineType=>searchEnginesInfo[engineType].every(e=>e.id!=this.model.id));if(engineWasRemoved){this.cancel_();return}}[this.$.searchEngine,this.$.keyword,this.$.queryUrl].forEach(element=>this.validateElement_(element))},cancel_:function(){this.$.dialog.cancel()},onActionButtonTap_:function(){this.browserProxy_.searchEngineEditCompleted(this.searchEngine_,this.keyword_,this.queryUrl_);this.$.dialog.close()},validateElement_:function(inputElement){if(inputElement.value==""){inputElement.invalid=false;this.updateActionButtonState_();return}this.browserProxy_.validateSearchEngineInput(inputElement.id,inputElement.value).then(isValid=>{inputElement.invalid=!isValid;this.updateActionButtonState_()})},validate_:function(event){const inputElement=event.target;this.validateElement_(inputElement)},updateActionButtonState_:function(){const allValid=[this.$.searchEngine,this.$.keyword,this.$.queryUrl].every(function(inputElement){return!inputElement.invalid&&inputElement.value.length>0});this.$.actionButton.disabled=!allValid}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-search-engine-entry",behaviors:[FocusRowBehavior],properties:{engine:Object,isDefault:{reflectToAttribute:true,type:Boolean,computed:"computeIsDefault_(engine)"},showDots_:{reflectToAttribute:true,type:Boolean,computed:"computeShowDots_(engine.canBeDefault,"+"engine.canBeEdited,"+"engine.canBeRemoved)"}},browserProxy_:null,created:function(){this.browserProxy_=settings.SearchEnginesBrowserProxyImpl.getInstance()},closePopupMenu_:function(){this.$$("cr-action-menu").close()},computeIsDefault_:function(){return this.engine.default},computeShowDots_:function(canBeDefault,canBeEdited,canBeRemoved){return canBeDefault||canBeEdited||canBeRemoved},getIconSet_:function(url){return cr.icon.getFavicon(url||"")},onDeleteTap_:function(){this.browserProxy_.removeSearchEngine(this.engine.modelIndex);this.closePopupMenu_()},onDotsTap_:function(){this.$$("cr-action-menu").showAt(assert(this.$$("paper-icon-button-light button")))},onEditTap_:function(e){e.preventDefault();this.closePopupMenu_();this.fire("edit-search-engine",{engine:this.engine,anchorElement:assert(this.$$("paper-icon-button-light button"))})},onMakeDefaultTap_:function(){this.closePopupMenu_();this.browserProxy_.setDefaultSearchEngine(this.engine.modelIndex)}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-search-engines-list",properties:{engines:Array,scrollTarget:Object,scrollOffset:Number,lastFocused_:Object,fixedHeight:{type:Boolean,value:false,reflectToAttribute:true}}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-omnibox-extension-entry",properties:{engine:Object},behaviors:[FocusRowBehavior],browserProxy_:null,created:function(){this.browserProxy_=settings.ExtensionControlBrowserProxyImpl.getInstance()},onManageTap_:function(){this.closePopupMenu_();this.browserProxy_.manageExtension(this.engine.extension.id)},onDisableTap_:function(){this.closePopupMenu_();this.browserProxy_.disableExtension(this.engine.extension.id)},closePopupMenu_:function(){this.$$("cr-action-menu").close()},getIconSet_:function(url){return cr.icon.getFavicon(url)},onDotsTap_:function(){this.$$("cr-action-menu").showAt(assert(this.$$("paper-icon-button-light button")))}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-search-engines-page",behaviors:[settings.GlobalScrollTargetBehavior,WebUIListenerBehavior],properties:{defaultEngines:Array,otherEngines:Array,extensions:Array,subpageRoute:{type:Object,value:settings.routes.SEARCH_ENGINES},showExtensionsList_:{type:Boolean,computed:"computeShowExtensionsList_(extensions)"},filter:{type:String,value:""},matchingDefaultEngines_:{type:Array,computed:"computeMatchingEngines_(defaultEngines, filter)"},matchingOtherEngines_:{type:Array,computed:"computeMatchingEngines_(otherEngines, filter)"},matchingExtensions_:{type:Array,computed:"computeMatchingEngines_(extensions, filter)"},omniboxExtensionlastFocused_:Object,dialogModel_:{type:Object,value:null},dialogAnchorElement_:{type:Object,value:null},showDialog_:{type:Boolean,value:false}},observers:["extensionsChanged_(extensions, showExtensionsList_)"],listeners:{"edit-search-engine":"onEditSearchEngine_"},ready:function(){settings.SearchEnginesBrowserProxyImpl.getInstance().getSearchEnginesList().then(this.enginesChanged_.bind(this));this.addWebUIListener("search-engines-changed",this.enginesChanged_.bind(this));Polymer.RenderStatus.afterNextRender(this,function(){this.$.otherEngines.scrollOffset=this.$.otherEngines.offsetTop})},openDialog_:function(searchEngine,anchorElement){this.dialogModel_=searchEngine;this.dialogAnchorElement_=anchorElement;this.showDialog_=true},onCloseDialog_:function(){this.showDialog_=false;const anchor=this.dialogAnchorElement_;cr.ui.focusWithoutInk(anchor);this.dialogModel_=null;this.dialogAnchorElement_=null},onEditSearchEngine_:function(e){const params=e.detail;this.openDialog_(params.engine,params.anchorElement)},extensionsChanged_:function(){if(this.showExtensionsList_&&this.$.extensions)this.$.extensions.notifyResize()},enginesChanged_:function(searchEnginesInfo){this.defaultEngines=searchEnginesInfo.defaults;this.otherEngines=searchEnginesInfo.others.sort((a,b)=>a.name.toLocaleLowerCase().localeCompare(b.name.toLocaleLowerCase()));this.extensions=searchEnginesInfo.extensions},onAddSearchEngineTap_:function(e){e.preventDefault();this.openDialog_(null,assert(this.$.addSearchEngine))},computeShowExtensionsList_:function(){return this.extensions.length>0},computeMatchingEngines_:function(list){if(this.filter=="")return list;const filter=this.filter.toLowerCase();return list.filter(e=>{return[e.displayName,e.name,e.keyword,e.url].some(term=>term.toLowerCase().includes(filter))})},showNoResultsMessage_:function(list,filteredList){return list.length>0&&filteredList.length==0}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-search-page",behaviors:[I18nBehavior],properties:{prefs:Object,searchEngines_:{type:Array,value:function(){return[]}},searchEnginesFilter_:String,focusConfig_:Object},browserProxy_:null,created:function(){this.browserProxy_=settings.SearchEnginesBrowserProxyImpl.getInstance()},ready:function(){const updateSearchEngines=searchEngines=>{this.set("searchEngines_",searchEngines.defaults)};this.browserProxy_.getSearchEnginesList().then(updateSearchEngines);cr.addWebUIListener("search-engines-changed",updateSearchEngines);this.focusConfig_=new Map;if(settings.routes.SEARCH_ENGINES){this.focusConfig_.set(settings.routes.SEARCH_ENGINES.path,"#engines-subpage-trigger .subpage-arrow")}},onChange_:function(){const select=this.$$("select");const searchEngine=this.searchEngines_[select.selectedIndex];this.browserProxy_.setDefaultSearchEngine(searchEngine.modelIndex)},onDisableExtension_:function(){this.fire("refresh-pref","default_search_provider.enabled")},onManageSearchEnginesTap_:function(){settings.navigateTo(settings.routes.SEARCH_ENGINES)},doNothing_:function(event){event.stopPropagation()},isDefaultSearchControlledByPolicy_:function(pref){return pref.controlledBy==chrome.settingsPrivate.ControlledBy.USER_POLICY},isDefaultSearchEngineEnforced_:function(pref){return pref.enforcement==chrome.settingsPrivate.Enforcement.ENFORCED}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
let DefaultBrowserInfo;cr.define("settings",function(){class DefaultBrowserBrowserProxy{requestDefaultBrowserState(){}setAsDefaultBrowser(){}}class DefaultBrowserBrowserProxyImpl{requestDefaultBrowserState(){return cr.sendWithPromise("SettingsDefaultBrowser.requestDefaultBrowserState")}setAsDefaultBrowser(){chrome.send("SettingsDefaultBrowser.setAsDefaultBrowser")}}cr.addSingletonGetter(DefaultBrowserBrowserProxyImpl);return{DefaultBrowserBrowserProxy:DefaultBrowserBrowserProxy,DefaultBrowserBrowserProxyImpl:DefaultBrowserBrowserProxyImpl}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-default-browser-page",behaviors:[WebUIListenerBehavior],properties:{isDefault_:Boolean,isSecondaryInstall_:Boolean,isUnknownError_:Boolean,maySetDefaultBrowser_:Boolean},browserProxy_:null,created:function(){this.browserProxy_=settings.DefaultBrowserBrowserProxyImpl.getInstance()},ready:function(){this.addWebUIListener("settings.updateDefaultBrowserState",this.updateDefaultBrowserState_.bind(this));this.browserProxy_.requestDefaultBrowserState().then(this.updateDefaultBrowserState_.bind(this))},updateDefaultBrowserState_:function(defaultBrowserState){this.isDefault_=false;this.isSecondaryInstall_=false;this.isUnknownError_=false;this.maySetDefaultBrowser_=false;if(defaultBrowserState.isDefault)this.isDefault_=true;else if(!defaultBrowserState.canBeDefault)this.isSecondaryInstall_=true;else if(!defaultBrowserState.isDisabledByPolicy&&!defaultBrowserState.isUnknownError)this.maySetDefaultBrowser_=true;else this.isUnknownError_=true},onSetDefaultBrowserTap_:function(){this.browserProxy_.setAsDefaultBrowser()}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-basic-page",behaviors:[MainPageBehavior,WebUIListenerBehavior],properties:{prefs:{type:Object,notify:true},androidAppsInfo:Object,showChangePassword:{type:Boolean,value:false},pageVisibility:{type:Object,value:function(){return{}}},advancedToggleExpanded:{type:Boolean,notify:true,observer:"advancedToggleExpandedChanged_"},hasExpandedSection_:{type:Boolean,value:false},showResetProfileBanner_:{type:Boolean,value:function(){return loadTimeData.getBoolean("showResetProfileBanner")}},currentRoute_:Object},hostAttributes:{role:"main"},listeners:{"subpage-expand":"onSubpageExpanded_"},attached:function(){this.currentRoute_=settings.getCurrentRoute();this.addWebUIListener("change-password-visibility",visibility=>{this.showChangePassword=visibility});if(loadTimeData.getBoolean("passwordProtectionAvailable")){settings.ChangePasswordBrowserProxyImpl.getInstance().initializeChangePasswordHandler()}if(settings.AndroidAppsBrowserProxyImpl){this.addWebUIListener("android-apps-info-update",this.androidAppsInfoUpdate_.bind(this));settings.AndroidAppsBrowserProxyImpl.getInstance().requestAndroidAppsInfo()}},currentRouteChanged:function(newRoute,oldRoute){this.currentRoute_=newRoute;if(settings.routes.ADVANCED&&settings.routes.ADVANCED.contains(newRoute))this.advancedToggleExpanded=true;if(oldRoute&&oldRoute.isSubpage()){if(!newRoute.isSubpage()||newRoute.section!=oldRoute.section)this.hasExpandedSection_=false}else{assert(!this.hasExpandedSection_)}MainPageBehaviorImpl.currentRouteChanged.call(this,newRoute,oldRoute)},showPage_:function(visibility){return visibility!==false},searchContents:function(query){const whenSearchDone=[settings.getSearchManager().search(query,assert(this.$$("#basicPage")))];if(this.pageVisibility.advancedSettings!==false){whenSearchDone.push(this.$$("#advancedPageTemplate").get().then(function(advancedPage){return settings.getSearchManager().search(query,advancedPage)}))}return Promise.all(whenSearchDone).then(function(requests){return{canceled:requests.some(function(r){return r.canceled}),didFindMatches:requests.some(function(r){return r.didFindMatches()}),wasClearSearch:requests[0].isSame("")}})},onResetProfileBannerClosed_:function(){this.showResetProfileBanner_=false},androidAppsInfoUpdate_:function(info){this.androidAppsInfo=info},shouldShowAndroidApps_:function(){const visibility=this.get("pageVisibility.androidApps");if(!this.showAndroidApps||!this.showPage_(visibility)){return false}if(!this.havePlayStoreApp&&(!this.androidAppsInfo||!this.androidAppsInfo.settingsAppAvailable)){return false}return true},shouldShowMultidevice_:function(){const visibility=this.get("pageVisibility.multidevice");return this.showMultidevice&&this.showPage_(visibility)},onSubpageExpanded_:function(){this.hasExpandedSection_=true},advancedToggleExpandedChanged_:function(){if(this.advancedToggleExpanded){this.async(()=>{this.$$("#advancedPageTemplate").get()})}},showAdvancedToggle_:function(inSearchMode,hasExpandedSection){return!inSearchMode&&!hasExpandedSection},showBasicPage_:function(currentRoute,inSearchMode,hasExpandedSection){return!hasExpandedSection||settings.routes.BASIC.contains(currentRoute)},showAdvancedPage_:function(currentRoute,inSearchMode,hasExpandedSection,advancedToggleExpanded){return hasExpandedSection?settings.routes.ADVANCED&&settings.routes.ADVANCED.contains(currentRoute):advancedToggleExpanded||inSearchMode},showAdvancedSettings_:function(visibility){return visibility!==false},getArrowIcon_:function(opened){return opened?"cr:arrow-drop-up":"cr:arrow-drop-down"}});/* Copyright 2015 The Chromium Authors. All rights reserved.
|
|
* Use of this source code is governed by a BSD-style license that can be
|
|
* found in the LICENSE file. */
|
|
(function(){"use strict";function deepEqual(val1,val2){if(val1===val2)return true;if(Array.isArray(val1)||Array.isArray(val2)){if(!Array.isArray(val1)||!Array.isArray(val2))return false;return arraysEqual(val1,val2)}if(val1 instanceof Object&&val2 instanceof Object)return objectsEqual(val1,val2);return false}function arraysEqual(arr1,arr2){if(arr1.length!=arr2.length)return false;for(let i=0;i<arr1.length;i++){if(!deepEqual(arr1[i],arr2[i]))return false}return true}function objectsEqual(obj1,obj2){const keys1=Object.keys(obj1);const keys2=Object.keys(obj2);if(keys1.length!=keys2.length)return false;for(let i=0;i<keys1.length;i++){const key=keys1[i];if(!deepEqual(obj1[key],obj2[key]))return false}return true}function deepCopy(val){if(!(val instanceof Object))return val;return Array.isArray(val)?deepCopyArray(val):deepCopyObject(val)}function deepCopyArray(arr){const copy=[];for(let i=0;i<arr.length;i++)copy.push(deepCopy(arr[i]));return copy}function deepCopyObject(obj){const copy={};const keys=Object.keys(obj);for(let i=0;i<keys.length;i++){const key=keys[i];copy[key]=deepCopy(obj[key])}return copy}Polymer({is:"settings-prefs",properties:{prefs:{type:Object,notify:true},lastPrefValues_:{type:Object,value:function(){return{}}}},observers:["prefsChanged_(prefs.*)"],settingsApi_:chrome.settingsPrivate,created:function(){if(!CrSettingsPrefs.deferInitialization)this.initialize()},detached:function(){CrSettingsPrefs.resetForTesting()},initialize:function(opt_settingsApi){if(this.initialized_)return;this.initialized_=true;if(opt_settingsApi)this.settingsApi_=opt_settingsApi;this.boundPrefsChanged_=this.onSettingsPrivatePrefsChanged_.bind(this);this.settingsApi_.onPrefsChanged.addListener(this.boundPrefsChanged_);this.settingsApi_.getAllPrefs(this.onSettingsPrivatePrefsFetched_.bind(this))},prefsChanged_:function(e){if(!CrSettingsPrefs.isInitialized||e.path=="prefs")return;const key=this.getPrefKeyFromPath_(e.path);const prefStoreValue=this.lastPrefValues_[key];const prefObj=this.get(key,this.prefs);if(!deepEqual(prefStoreValue,prefObj.value)){this.settingsApi_.setPref(key,prefObj.value,"",this.setPrefCallback_.bind(this,key))}},onSettingsPrivatePrefsChanged_:function(prefs){if(CrSettingsPrefs.isInitialized)this.updatePrefs_(prefs)},onSettingsPrivatePrefsFetched_:function(prefs){this.updatePrefs_(prefs);CrSettingsPrefs.setInitialized()},setPrefCallback_:function(key,success){if(!success)this.refresh(key)},refresh:function(key){this.settingsApi_.getPref(key,pref=>{this.updatePrefs_([pref])})},updatePrefs_:function(newPrefs){const prefs=this.prefs||{};newPrefs.forEach(function(newPrefObj){this.lastPrefValues_[newPrefObj.key]=deepCopy(newPrefObj.value);if(!deepEqual(this.get(newPrefObj.key,prefs),newPrefObj)){cr.exportPath(newPrefObj.key,newPrefObj,prefs);if(prefs==this.prefs)this.notifyPath("prefs."+newPrefObj.key,newPrefObj)}},this);if(!this.prefs)this.prefs=prefs},getPrefKeyFromPath_:function(path){const parts=path.split(".");assert(parts.shift()=="prefs","Path doesn't begin with 'prefs'");for(let i=1;i<=parts.length;i++){const key=parts.slice(0,i).join(".");if(this.lastPrefValues_.hasOwnProperty(key))return key}return""},resetForTesting:function(){if(!this.initialized_)return;this.prefs=undefined;this.lastPrefValues_={};this.initialized_=false;this.settingsApi_.onPrefsChanged.removeListener(this.boundPrefsChanged_);this.settingsApi_=chrome.settingsPrivate}})})();
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
let MainPageVisibility;Polymer({is:"settings-main",behaviors:[settings.RouteObserverBehavior],properties:{prefs:{type:Object,notify:true},advancedToggleExpanded:{type:Boolean,notify:true},overscroll_:{type:Number,observer:"overscrollChanged_"},showPages_:{type:Object,value:function(){return{about:false,settings:false}}},inSearchMode_:{type:Boolean,value:false},showNoResultsFound_:{type:Boolean,value:false},toolbarSpinnerActive:{type:Boolean,value:false,notify:true},pageVisibility:Object,showAndroidApps:Boolean,showMultidevice:Boolean,havePlayStoreApp:Boolean},attached:function(){this.listen(this,"freeze-scroll","onFreezeScroll_");this.listen(this,"lazy-loaded","onLazyLoaded_")},onLazyLoaded_:function(){Polymer.dom.flush();this.updateOverscrollForPage_()},detached:function(){this.unlisten(this,"freeze-scroll","onFreezeScroll_")},overscrollChanged_:function(){if(!this.overscroll_&&this.boundScroll_){this.offsetParent.removeEventListener("scroll",this.boundScroll_);window.removeEventListener("resize",this.boundScroll_);this.boundScroll_=null}else if(this.overscroll_&&!this.boundScroll_){this.boundScroll_=(()=>{if(!this.ignoreScroll_)this.setOverscroll_(0)});this.offsetParent.addEventListener("scroll",this.boundScroll_);window.addEventListener("resize",this.boundScroll_)}},setOverscroll_:function(opt_minHeight){const scroller=this.offsetParent;if(!scroller)return;const overscroll=this.$.overscroll;const visibleBottom=scroller.scrollTop+scroller.clientHeight;const overscrollBottom=overscroll.offsetTop+overscroll.scrollHeight;const visibleOverscroll=overscroll.scrollHeight-(overscrollBottom-visibleBottom);this.overscroll_=Math.max(opt_minHeight||0,Math.ceil(visibleOverscroll))},onFreezeScroll_:function(e){if(e.detail){this.setOverscroll_(this.overscrollHeight_());this.ignoreScroll_=true;const scrollerWidth=this.offsetParent.clientWidth;this.offsetParent.style.overflow="hidden";const scrollbarWidth=this.offsetParent.clientWidth-scrollerWidth;this.offsetParent.style.width="calc(100% - "+scrollbarWidth+"px)"}else{this.ignoreScroll_=false;this.offsetParent.style.overflow="";this.offsetParent.style.width=""}},currentRouteChanged:function(newRoute){this.updatePagesShown_()},onSubpageExpand_:function(){this.updatePagesShown_()},updatePagesShown_:function(){const inAbout=settings.routes.ABOUT.contains(settings.getCurrentRoute());this.showPages_={about:inAbout,settings:!inAbout};this.updateOverscrollForPage_();setTimeout(()=>{Polymer.dom.flush();this.updateOverscrollForPage_()})},updateOverscrollForPage_:function(){if(this.showPages_.about||this.inSearchMode_){this.overscroll_=0;return}this.setOverscroll_(this.overscrollHeight_())},overscrollHeight_:function(){const route=settings.getCurrentRoute();if(!route.section||route.isSubpage()||this.showPages_.about)return 0;const page=this.getPage_(route);const section=page&&page.getSection(route.section);if(!section||!section.offsetParent)return 0;const sectionTop=section.offsetParent.offsetTop+section.offsetTop;const distance=this.$.overscroll.offsetTop-sectionTop;return Math.max(0,this.offsetParent.clientHeight-distance)},getPage_:function(route){if(settings.routes.ABOUT.contains(route)){return this.$$("settings-about-page")}if(settings.routes.BASIC.contains(route)||settings.routes.ADVANCED&&settings.routes.ADVANCED.contains(route)){return this.$$("settings-basic-page")}assertNotReached()},searchContents:function(query){this.inSearchMode_=true;this.toolbarSpinnerActive=true;return new Promise((resolve,reject)=>{setTimeout(()=>{const whenSearchDone=assert(this.getPage_(settings.routes.BASIC)).searchContents(query);whenSearchDone.then(result=>{resolve();if(result.canceled){return}this.toolbarSpinnerActive=false;this.inSearchMode_=!result.wasClearSearch;this.showNoResultsFound_=this.inSearchMode_&&!result.didFindMatches;if(this.inSearchMode_){Polymer.IronA11yAnnouncer.requestAvailability();this.fire("iron-announce",{text:this.showNoResultsFound_?loadTimeData.getString("searchNoResults"):loadTimeData.getStringF("searchResults",query)})}})},0)})}});
|
|
// Copyright 2016 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.exportPath("settings");settings.SearchResult;cr.define("settings",function(){const SKIP_SEARCH_CSS_ATTRIBUTE="no-search";const IGNORED_ELEMENTS=new Set(["CONTENT","CR-EVENTS","DIALOG","IMG","IRON-ICON","IRON-LIST","PAPER-ICON-BUTTON","PAPER-RIPPLE","PAPER-SLIDER","PAPER-SPINNER-LITE","STYLE","TEMPLATE"]);function findAndRemoveHighlights_(node){cr.search_highlight_utils.findAndRemoveHighlights(node);cr.search_highlight_utils.findAndRemoveBubbles(node)}function findAndHighlightMatches_(request,root){let foundMatches=false;function doSearch(node){if(node.nodeName=="TEMPLATE"&&node.hasAttribute("route-path")&&!node.if&&!node.hasAttribute(SKIP_SEARCH_CSS_ATTRIBUTE)){request.queue_.addRenderTask(new RenderTask(request,node));return}if(IGNORED_ELEMENTS.has(node.nodeName))return;if(node instanceof HTMLElement){const element=node;if(element.hasAttribute(SKIP_SEARCH_CSS_ATTRIBUTE)||element.hasAttribute("hidden")||element.style.display=="none"){return}}if(node.nodeType==Node.TEXT_NODE){const textContent=node.nodeValue.trim();if(textContent.length==0)return;if(request.regExp.test(textContent)){foundMatches=true;revealParentSection_(node,request.rawQuery_);if(node.parentNode.nodeName!="OPTION"){request.addTextObserver(node);cr.search_highlight_utils.highlight(node,textContent.split(request.regExp))}}return}let child=node.firstChild;while(child!==null){const nextSibling=child.nextSibling;doSearch(child);child=nextSibling}const shadowRoot=node.shadowRoot;if(shadowRoot)doSearch(shadowRoot)}doSearch(root);return foundMatches}function revealParentSection_(node,rawQuery){let associatedControl=null;let parent=node;while(parent&&parent.nodeName!=="SETTINGS-SECTION"){parent=parent.nodeType==Node.DOCUMENT_FRAGMENT_NODE?parent.host:parent.parentNode;if(parent.nodeName=="SETTINGS-SUBPAGE"){associatedControl=assert(parent.associatedControl,"An associated control was expected for SETTINGS-SUBPAGE "+parent.pageTitle+", but was not found.")}}if(parent)parent.hiddenBySearch=false;if(associatedControl){cr.search_highlight_utils.highlightControlWithBubble(associatedControl,rawQuery)}}class Task{constructor(request,node){this.request=request;this.node=node}exec(){}}class RenderTask extends Task{constructor(request,node){super(request,node)}exec(){const routePath=this.node.getAttribute("route-path");const subpageTemplate=this.node["_content"].querySelector("settings-subpage");subpageTemplate.setAttribute("route-path",routePath);assert(!this.node.if);this.node.if=true;return new Promise((resolve,reject)=>{const parent=this.node.parentNode;parent.async(()=>{const renderedNode=parent.querySelector('[route-path="'+routePath+'"]');this.request.queue_.addSearchAndHighlightTask(new SearchAndHighlightTask(this.request,assert(renderedNode)));resolve()})})}}class SearchAndHighlightTask extends Task{constructor(request,node){super(request,node)}exec(){const foundMatches=findAndHighlightMatches_(this.request,this.node);this.request.updateMatches(foundMatches);return Promise.resolve()}}class TopLevelSearchTask extends Task{constructor(request,page){super(request,page)}exec(){findAndRemoveHighlights_(this.node);const shouldSearch=this.request.regExp!==null;this.setSectionsVisibility_(!shouldSearch);if(shouldSearch){const foundMatches=findAndHighlightMatches_(this.request,this.node);this.request.updateMatches(foundMatches)}return Promise.resolve()}setSectionsVisibility_(visible){const sections=this.node.querySelectorAll("settings-section");for(let i=0;i<sections.length;i++)sections[i].hiddenBySearch=!visible}}class TaskQueue{constructor(request){this.request_=request;this.queues_;this.reset();this.onEmptyCallback_=null;this.running_=false}reset(){this.queues_={high:[],middle:[],low:[]}}addTopLevelSearchTask(task){this.queues_.high.push(task);this.consumePending_()}addSearchAndHighlightTask(task){this.queues_.middle.push(task);this.consumePending_()}addRenderTask(task){this.queues_.low.push(task);this.consumePending_()}onEmpty(onEmptyCallback){this.onEmptyCallback_=onEmptyCallback}popNextTask_(){return this.queues_.high.shift()||this.queues_.middle.shift()||this.queues_.low.shift()}consumePending_(){if(this.running_)return;const task=this.popNextTask_();if(!task){this.running_=false;if(this.onEmptyCallback_)this.onEmptyCallback_();return}this.running_=true;window.requestIdleCallback(()=>{if(!this.request_.canceled){task.exec().then(()=>{this.running_=false;this.consumePending_()})}})}}class SearchRequest{constructor(rawQuery,root){this.rawQuery_=rawQuery;this.root_=root;this.regExp=this.generateRegExp_();this.canceled=false;this.foundMatches_=false;this.resolver=new PromiseResolver;this.queue_=new TaskQueue(this);this.queue_.onEmpty(()=>{this.resolver.resolve(this)});this.textObservers_=new Set}removeAllTextObservers(){this.textObservers_.forEach(observer=>{observer.disconnect()});this.textObservers_.clear()}addTextObserver(textNode){const originalParentNode=textNode.parentNode;const observer=new MutationObserver(mutations=>{const oldValue=mutations[0].oldValue.trim();const newValue=textNode.nodeValue.trim();if(oldValue!=newValue){observer.disconnect();this.textObservers_.delete(observer);cr.search_highlight_utils.findAndRemoveHighlights(originalParentNode)}});observer.observe(textNode,{characterData:true,characterDataOldValue:true});this.textObservers_.add(observer)}start(){this.queue_.addTopLevelSearchTask(new TopLevelSearchTask(this,this.root_))}generateRegExp_(){let regExp=null;const searchText=this.rawQuery_.trim().replace(SANITIZE_REGEX,"\\$&");if(searchText.length>0)regExp=new RegExp(`(${searchText})`,"i");return regExp}isSame(rawQuery){return this.rawQuery_==rawQuery}updateMatches(found){this.foundMatches_=this.foundMatches_||found}didFindMatches(){return this.foundMatches_}}const SANITIZE_REGEX=/[-[\]{}()*+?.,\\^$|#\s]/g;class SearchManager{search(text,page){}}class SearchManagerImpl{constructor(){this.activeRequests_=new Set;this.completedRequests_=new Set;this.lastSearchedText_=null}search(text,page){if(text!=this.lastSearchedText_){this.activeRequests_.forEach(function(request){request.removeAllTextObservers();request.canceled=true;request.resolver.resolve(request)});this.activeRequests_.clear();this.completedRequests_.forEach(request=>{request.removeAllTextObservers()});this.completedRequests_.clear()}this.lastSearchedText_=text;const request=new SearchRequest(text,page);this.activeRequests_.add(request);request.start();return request.resolver.promise.then(()=>{this.activeRequests_.delete(request);this.completedRequests_.add(request);return request})}}cr.addSingletonGetter(SearchManagerImpl);function getSearchManager(){return SearchManagerImpl.getInstance()}function setSearchManagerForTesting(searchManager){SearchManagerImpl.instance_=searchManager}return{getSearchManager:getSearchManager,setSearchManagerForTesting:setSearchManagerForTesting,SearchRequest:SearchRequest}});Polymer({is:"iron-selector",behaviors:[Polymer.IronMultiSelectableBehavior]});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
Polymer({is:"settings-menu",behaviors:[settings.RouteObserverBehavior],properties:{advancedOpened:{type:Boolean,notify:true},pageVisibility:Object},listeners:{"topMenu.click":"onLinkTap_","subMenu.click":"onLinkTap_"},currentRouteChanged:function(newRoute){const currentPath=newRoute.path;const anchors=this.root.querySelectorAll("a");for(let i=0;i<anchors.length;++i){if(anchors[i].getAttribute("href")==currentPath){this.setSelectedUrl_(anchors[i].href);return}}this.setSelectedUrl_("")},onLinkTap_:function(event){if(event.target.matches("a:not(#extensionsLink)"))event.preventDefault()},setSelectedUrl_:function(url){this.$.topMenu.selected=this.$.subMenu.selected=url},onSelectorActivate_:function(event){this.setSelectedUrl_(event.detail.selected);const path=new URL(event.detail.selected).pathname;const route=settings.getRouteForPath(path);assert(route,"settings-menu has an entry with an invalid route.");settings.navigateTo(route,null,true)},arrowState_:function(opened){return opened?"cr:arrow-drop-up":"cr:arrow-drop-down"},onExtensionsLinkClick_:function(){chrome.metricsPrivate.recordUserAction("SettingsMenu_ExtensionsLinkClicked")}});
|
|
// Copyright 2015 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
cr.exportPath("settings");assert(!settings.defaultResourceLoaded,"settings_ui.js run twice. You probably have an invalid import.");settings.defaultResourceLoaded=true;Polymer({is:"settings-ui",behaviors:[settings.RouteObserverBehavior,CrContainerShadowBehavior,settings.FindShortcutBehavior],properties:{prefs:Object,advancedOpened_:{type:Boolean,value:false,notify:true},toolbarSpinnerActive_:{type:Boolean,value:false},pageVisibility_:{type:Object,value:settings.pageVisibility},showCrostini_:Boolean,showAndroidApps_:Boolean,showMultidevice_:Boolean,havePlayStoreApp_:Boolean,lastSearchQuery_:{type:String,value:""}},listeners:{"refresh-pref":"onRefreshPref_"},created:function(){settings.initializeRouteFromUrl()},ready:function(){listenOnce(this.$.drawer,"open-changed",()=>{this.$.drawerTemplate.if=true});window.addEventListener("popstate",e=>{this.$.drawer.closeDrawer()});CrPolicyStrings={controlledSettingExtension:loadTimeData.getString("controlledSettingExtension"),controlledSettingExtensionWithoutName:loadTimeData.getString("controlledSettingExtensionWithoutName"),controlledSettingPolicy:loadTimeData.getString("controlledSettingPolicy"),controlledSettingRecommendedMatches:loadTimeData.getString("controlledSettingRecommendedMatches"),controlledSettingRecommendedDiffers:loadTimeData.getString("controlledSettingRecommendedDiffers")};this.showCrostini_=loadTimeData.valueExists("showCrostini")&&loadTimeData.getBoolean("showCrostini");this.showAndroidApps_=loadTimeData.valueExists("androidAppsVisible")&&loadTimeData.getBoolean("androidAppsVisible");this.showMultidevice_=this.showAndroidApps_&&loadTimeData.valueExists("enableMultideviceSettings")&&loadTimeData.getBoolean("enableMultideviceSettings");this.havePlayStoreApp_=loadTimeData.valueExists("havePlayStoreApp")&&loadTimeData.getBoolean("havePlayStoreApp");this.addEventListener("show-container",()=>{this.$.container.style.visibility="visible"});this.addEventListener("hide-container",()=>{this.$.container.style.visibility="hidden"})},attached:function(){document.documentElement.classList.remove("loading");setTimeout(function(){chrome.send("metricsHandler:recordTime",["Settings.TimeUntilInteractive",window.performance.now()])});document.fonts.load("bold 12px Roboto");settings.setGlobalScrollTarget(this.$.container)},detached:function(){settings.resetRouteForTesting()},currentRouteChanged:function(route){const urlSearchQuery=settings.getQueryParameters().get("search")||"";if(urlSearchQuery==this.lastSearchQuery_)return;this.lastSearchQuery_=urlSearchQuery;const toolbar=this.$$("cr-toolbar");const searchField=toolbar.getSearchField();if(urlSearchQuery!=searchField.getValue()){searchField.setValue(urlSearchQuery,true)}this.$.main.searchContents(urlSearchQuery)},canHandleFindShortcut:function(){return!this.$.drawer.open&&!document.querySelector("* /deep/ cr-dialog[open]")},handleFindShortcut:function(){this.$$("cr-toolbar").getSearchField().showAndFocus()},onRefreshPref_:function(e){const prefName=e.detail;return this.$.prefs.refresh(prefName)},onSearchChanged_:function(e){const query=e.detail.replace(/^\s+/,"");if(query==this.lastSearchQuery_)return;settings.navigateTo(settings.routes.BASIC,query.length>0?new URLSearchParams("search="+encodeURIComponent(query)):undefined,true)},onIronActivate_:function(event){if(event.detail.item.id!="advancedSubmenu")this.$.drawer.closeDrawer()},onMenuButtonTap_:function(){this.$.drawer.toggle()},onMenuClosed_:function(){this.$.container.setAttribute("tabindex","-1");this.$.container.focus();listenOnce(this.$.container,["blur","pointerdown"],()=>{this.$.container.removeAttribute("tabindex")})}}); |