import{ObjectWrapper,Color,UIString,Throttler,Settings}from'../common/common.js';import{InspectorFrontendHost,InspectorFrontendHostAPI}from'../host/host.js';import{Icon,Toolbar,ARIAUtils,UIUtils,Widget,ContextMenu}from'../ui/ui.js';import{NumberUtilities,StringUtilities}from'../platform/platform.js';import{SDKModel,CSSModel}from'../sdk/sdk.js';class ContrastInfo extends ObjectWrapper.ObjectWrapper{constructor(contrastInfo){super();this._isNull=true;this._contrastRatio=null;this._contrastRatioThresholds=null;this._fgColor=null;this._bgColor=null;if(!contrastInfo){return;}
if(!contrastInfo.computedFontSize||!contrastInfo.computedFontWeight||!contrastInfo.backgroundColors||contrastInfo.backgroundColors.length!==1){return;}
this._isNull=false;const isLargeFont=ContrastInfo.computeIsLargeFont(contrastInfo.computedFontSize,contrastInfo.computedFontWeight);this._contrastRatioThresholds=_ContrastThresholds[(isLargeFont?'largeFont':'normalFont')];const bgColorText=contrastInfo.backgroundColors[0];const bgColor=Color.Color.parse(bgColorText);if(bgColor){this._setBgColorInternal(bgColor);}}
isNull(){return this._isNull;}
setColor(fgColor){this._fgColor=fgColor;this._updateContrastRatio();this.dispatchEventToListeners(Events.ContrastInfoUpdated);}
color(){return this._fgColor;}
contrastRatio(){return this._contrastRatio;}
setBgColor(bgColor){this._setBgColorInternal(bgColor);this.dispatchEventToListeners(Events.ContrastInfoUpdated);}
_setBgColorInternal(bgColor){this._bgColor=bgColor;if(!this._fgColor){return;}
const fgRGBA=this._fgColor.rgba();if(bgColor.hasAlpha()){const blendedRGBA=[];Color.Color.blendColors(bgColor.rgba(),fgRGBA,blendedRGBA);this._bgColor=new Color.Color(blendedRGBA,Color.Format.RGBA);}
this._contrastRatio=Color.Color.calculateContrastRatio(fgRGBA,this._bgColor.rgba());}
bgColor(){return this._bgColor;}
_updateContrastRatio(){if(!this._bgColor||!this._fgColor){return;}
this._contrastRatio=Color.Color.calculateContrastRatio(this._fgColor.rgba(),this._bgColor.rgba());}
contrastRatioThreshold(level){if(!this._contrastRatioThresholds){return null;}
return this._contrastRatioThresholds[level];}
static computeIsLargeFont(fontSize,fontWeight){const boldWeights=['bold','bolder','600','700','800','900'];const fontSizePx=parseFloat(fontSize.replace('px',''));const isBold=(boldWeights.indexOf(fontWeight)!==-1);const fontSizePt=fontSizePx*72/96;if(isBold){return fontSizePt>=14;}
return fontSizePt>=18;}}
const Events={ContrastInfoUpdated:Symbol('ContrastInfoUpdated')};const _ContrastThresholds={largeFont:{aa:3.0,aaa:4.5},normalFont:{aa:4.5,aaa:7.0}};let ContrastInfoType;var ContrastInfo$1=Object.freeze({__proto__:null,ContrastInfo:ContrastInfo,Events:Events,ContrastInfoType:ContrastInfoType});class ContrastDetails extends ObjectWrapper.ObjectWrapper{constructor(contrastInfo,contentElement,toggleMainColorPickerCallback,expandedChangedCallback){super();this._contrastInfo=contrastInfo;this._element=contentElement.createChild('div','spectrum-contrast-details collapsed');this._toggleMainColorPicker=toggleMainColorPickerCallback;this._expandedChangedCallback=expandedChangedCallback;this._expanded=false;this._passesAA=true;this._contrastUnknown=false;this._visible=false;this._noContrastInfoAvailable=contentElement.createChild('div','no-contrast-info-available');this._noContrastInfoAvailable.textContent=ls`No contrast information available`;this._noContrastInfoAvailable.classList.add('hidden');const contrastValueRow=this._element.createChild('div');contrastValueRow.addEventListener('click',this._topRowClicked.bind(this));const contrastValueRowContents=contrastValueRow.createChild('div','container');contrastValueRowContents.createTextChild(UIString.UIString('Contrast ratio'));this._contrastValueBubble=contrastValueRowContents.createChild('span','contrast-details-value');this._contrastValue=this._contrastValueBubble.createChild('span');this._contrastValueBubbleIcons=[];this._contrastValueBubbleIcons.push(this._contrastValueBubble.appendChild(Icon.Icon.create('smallicon-checkmark-square')));this._contrastValueBubbleIcons.push(this._contrastValueBubble.appendChild(Icon.Icon.create('smallicon-checkmark-behind')));this._contrastValueBubbleIcons.push(this._contrastValueBubble.appendChild(Icon.Icon.create('smallicon-no')));this._contrastValueBubbleIcons.forEach(button=>button.addEventListener('click',event=>{ContrastDetails._showHelp();event.consume(false);}));const expandToolbar=new Toolbar.Toolbar('expand',contrastValueRowContents);this._expandButton=new Toolbar.ToolbarButton(UIString.UIString('Show more'),'smallicon-expand-more');this._expandButton.addEventListener(Toolbar.ToolbarButton.Events.Click,this._expandButtonClicked.bind(this));ARIAUtils.setExpanded(this._expandButton.element,false);expandToolbar.appendToolbarItem(this._expandButton);this._expandedDetails=this._element.createChild('div','expanded-details');ARIAUtils.setControls(this._expandButton.element,this._expandedDetails);this._contrastThresholds=this._expandedDetails.createChild('div','contrast-thresholds');this._contrastAA=this._contrastThresholds.createChild('div','contrast-threshold');this._contrastPassFailAA=this._contrastAA.createChild('span','contrast-pass-fail');this._contrastAAA=this._contrastThresholds.createChild('div','contrast-threshold');this._contrastPassFailAAA=this._contrastAAA.createChild('span','contrast-pass-fail');this._chooseBgColor=this._expandedDetails.createChild('div','contrast-choose-bg-color');this._chooseBgColor.textContent=UIString.UIString('Pick background color');const bgColorContainer=this._expandedDetails.createChild('div','background-color');const pickerToolbar=new Toolbar.Toolbar('spectrum-eye-dropper',bgColorContainer);this._bgColorPickerButton=new Toolbar.ToolbarToggle(UIString.UIString('Toggle background color picker'),'largeicon-eyedropper');this._bgColorPickerButton.addEventListener(Toolbar.ToolbarButton.Events.Click,this._toggleBackgroundColorPicker.bind(this,undefined,true));pickerToolbar.appendToolbarItem(this._bgColorPickerButton);this._bgColorPickedBound=this._bgColorPicked.bind(this);this._bgColorSwatch=new Swatch(bgColorContainer);this._contrastInfo.addEventListener(Events.ContrastInfoUpdated,this._update.bind(this));}
_showNoContrastInfoAvailableMessage(){this._noContrastInfoAvailable.classList.remove('hidden');}
_hideNoContrastInfoAvailableMessage(){this._noContrastInfoAvailable.classList.add('hidden');}
_update(){if(this._contrastInfo.isNull()){this._showNoContrastInfoAvailableMessage();this.setVisible(false);return;}
this.setVisible(true);this._hideNoContrastInfoAvailableMessage();const contrastRatio=this._contrastInfo.contrastRatio();const fgColor=this._contrastInfo.color();const bgColor=this._contrastInfo.bgColor();if(!contrastRatio||!bgColor||!fgColor){this._contrastUnknown=true;this._contrastValue.textContent='';this._contrastValueBubble.classList.add('contrast-unknown');this._chooseBgColor.classList.remove('hidden');this._contrastThresholds.classList.add('hidden');this._showNoContrastInfoAvailableMessage();return;}
this._contrastUnknown=false;this._chooseBgColor.classList.add('hidden');this._contrastThresholds.classList.remove('hidden');this._contrastValueBubble.classList.remove('contrast-unknown');this._contrastValue.textContent=contrastRatio.toFixed(2);this._bgColorSwatch.setColors(fgColor,bgColor);const aa=this._contrastInfo.contrastRatioThreshold('aa');this._passesAA=this._contrastInfo.contrastRatio()>=aa;this._contrastPassFailAA.removeChildren();const labelAA=this._contrastPassFailAA.createChild('span','contrast-link-label');labelAA.textContent=UIString.UIString('AA');this._contrastPassFailAA.createChild('span').textContent=UIString.UIString(': %s',aa.toFixed(1));if(this._passesAA){this._contrastPassFailAA.appendChild(Icon.Icon.create('smallicon-checkmark-square'));}else{this._contrastPassFailAA.appendChild(Icon.Icon.create('smallicon-no'));}
const aaa=this._contrastInfo.contrastRatioThreshold('aaa');const passesAAA=this._contrastInfo.contrastRatio()>=aaa;this._contrastPassFailAAA.removeChildren();const labelAAA=this._contrastPassFailAAA.createChild('span','contrast-link-label');labelAAA.textContent=UIString.UIString('AAA');this._contrastPassFailAAA.createChild('span').textContent=UIString.UIString(': %s',aaa.toFixed(1));if(passesAAA){this._contrastPassFailAAA.appendChild(Icon.Icon.create('smallicon-checkmark-square'));}else{this._contrastPassFailAAA.appendChild(Icon.Icon.create('smallicon-no'));}
[labelAA,labelAAA].forEach(e=>e.addEventListener('click',event=>ContrastDetails._showHelp()));this._element.classList.toggle('contrast-fail',!this._passesAA);this._contrastValueBubble.classList.toggle('contrast-aa',this._passesAA);this._contrastValueBubble.classList.toggle('contrast-aaa',passesAAA);}
static _showHelp(){InspectorFrontendHost.InspectorFrontendHostInstance.openInNewTab(UIUtils.addReferrerToURL('https://developers.google.com/web/fundamentals/accessibility/accessible-styles#color_and_contrast'));}
setVisible(visible){this._visible=visible;this._element.classList.toggle('hidden',!visible);}
visible(){return this._visible;}
element(){return this._element;}
_expandButtonClicked(event){this._contrastValueBubble.getComponentSelection().empty();this._toggleExpanded();}
_topRowClicked(event){this._contrastValueBubble.getComponentSelection().empty();this._toggleExpanded();event.consume(true);}
_toggleExpanded(){this._expanded=!this._expanded;ARIAUtils.setExpanded(this._expandButton.element,this._expanded);this._element.classList.toggle('collapsed',!this._expanded);if(this._expanded){this._toggleMainColorPicker(false);this._expandButton.setGlyph('smallicon-expand-less');this._expandButton.setTitle(UIString.UIString('Show less'));if(this._contrastUnknown){this._toggleBackgroundColorPicker(true);}}else{this._toggleBackgroundColorPicker(false);this._expandButton.setGlyph('smallicon-expand-more');this._expandButton.setTitle(UIString.UIString('Show more'));}
this._expandedChangedCallback();}
collapse(){this._element.classList.remove('expanded');this._toggleBackgroundColorPicker(false);this._toggleMainColorPicker(false);}
expanded(){return this._expanded;}
backgroundColorPickerEnabled(){return this._bgColorPickerButton.toggled();}
toggleBackgroundColorPicker(enabled){this._toggleBackgroundColorPicker(enabled,false);}
_toggleBackgroundColorPicker(enabled,shouldTriggerEvent=true){if(enabled===undefined){enabled=!this._bgColorPickerButton.toggled();}
this._bgColorPickerButton.setToggled(enabled);if(shouldTriggerEvent){this.dispatchEventToListeners(Events$1.BackgroundColorPickerWillBeToggled,enabled);}
InspectorFrontendHost.InspectorFrontendHostInstance.setEyeDropperActive(enabled);if(enabled){InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener(InspectorFrontendHostAPI.Events.EyeDropperPickedColor,this._bgColorPickedBound);}else{InspectorFrontendHost.InspectorFrontendHostInstance.events.removeEventListener(InspectorFrontendHostAPI.Events.EyeDropperPickedColor,this._bgColorPickedBound);}}
_bgColorPicked(event){const rgbColor=(event.data);const rgba=[rgbColor.r,rgbColor.g,rgbColor.b,(rgbColor.a/2.55|0)/100];const color=Color.Color.fromRGBA(rgba);this._contrastInfo.setBgColor(color);this._toggleBackgroundColorPicker(false);InspectorFrontendHost.InspectorFrontendHostInstance.bringToFront();}}
const Events$1={BackgroundColorPickerWillBeToggled:Symbol('BackgroundColorPickerWillBeToggled')};class Swatch{constructor(parentElement){this._parentElement=parentElement;this._swatchElement=parentElement.createChild('span','swatch contrast swatch-inner-white');this._swatchInnerElement=this._swatchElement.createChild('span','swatch-inner');this._textPreview=this._swatchElement.createChild('div','text-preview');this._textPreview.textContent='Aa';}
setColors(fgColor,bgColor){this._textPreview.style.color=(fgColor.asString(Color.Format.RGBA));this._swatchInnerElement.style.backgroundColor=(bgColor.asString(Color.Format.RGBA));this._swatchElement.classList.toggle('swatch-inner-white',bgColor.hsla()[2]>0.9);}}
var ContrastDetails$1=Object.freeze({__proto__:null,ContrastDetails:ContrastDetails,Events:Events$1,Swatch:Swatch});class ContrastOverlay{constructor(contrastInfo,colorElement){this._contrastInfo=contrastInfo;this._visible=false;this._contrastRatioSVG=colorElement.createSVGChild('svg','spectrum-contrast-container fill');this._contrastRatioLines={aa:this._contrastRatioSVG.createSVGChild('path','spectrum-contrast-line'),aaa:this._contrastRatioSVG.createSVGChild('path','spectrum-contrast-line')};this._width=0;this._height=0;this._contrastRatioLineBuilder=new ContrastRatioLineBuilder(this._contrastInfo);this._contrastRatioLinesThrottler=new Throttler.Throttler(0);this._drawContrastRatioLinesBound=this._drawContrastRatioLines.bind(this);this._contrastInfo.addEventListener(Events.ContrastInfoUpdated,this._update.bind(this));}
_update(){if(!this._visible||this._contrastInfo.isNull()||!this._contrastInfo.contrastRatio()){return;}
this._contrastRatioLinesThrottler.schedule(this._drawContrastRatioLinesBound);}
setDimensions(width,height){this._width=width;this._height=height;this._update();}
setVisible(visible){this._visible=visible;this._contrastRatioSVG.classList.toggle('hidden',!visible);this._update();}
async _drawContrastRatioLines(){for(const level in this._contrastRatioLines){const path=this._contrastRatioLineBuilder.drawContrastRatioLine(this._width,this._height,level);if(path){this._contrastRatioLines[level].setAttribute('d',path);}else{this._contrastRatioLines[level].removeAttribute('d');}}}}
class ContrastRatioLineBuilder{constructor(contrastInfo){this._contrastInfo=contrastInfo;}
drawContrastRatioLine(width,height,level){const requiredContrast=this._contrastInfo.contrastRatioThreshold(level);if(!width||!height||!requiredContrast){return null;}
const dS=0.02;const epsilon=0.0002;const H=0;const S=1;const V=2;const A=3;const color=this._contrastInfo.color();const bgColor=this._contrastInfo.bgColor();if(!color||!bgColor){return null;}
const fgRGBA=color.rgba();const fgHSVA=color.hsva();const bgRGBA=bgColor.rgba();const bgLuminance=Color.Color.luminance(bgRGBA);const blendedRGBA=[];Color.Color.blendColors(fgRGBA,bgRGBA,blendedRGBA);const fgLuminance=Color.Color.luminance(blendedRGBA);const fgIsLighter=fgLuminance>bgLuminance;const desiredLuminance=Color.Color.desiredLuminance(bgLuminance,requiredContrast,fgIsLighter);let lastV=fgHSVA[V];let currentSlope=0;const candidateHSVA=[fgHSVA[H],0,0,fgHSVA[A]];let pathBuilder=[];const candidateRGBA=[];Color.Color.hsva2rgba(candidateHSVA,candidateRGBA);Color.Color.blendColors(candidateRGBA,bgRGBA,blendedRGBA);function updateCandidateAndComputeDelta(index,x){candidateHSVA[index]=x;Color.Color.hsva2rgba(candidateHSVA,candidateRGBA);Color.Color.blendColors(candidateRGBA,bgRGBA,blendedRGBA);return Color.Color.luminance(blendedRGBA)-desiredLuminance;}
function approach(index){let x=candidateHSVA[index];let multiplier=1;let dLuminance=updateCandidateAndComputeDelta(index,x);let previousSign=Math.sign(dLuminance);for(let guard=100;guard;guard--){if(Math.abs(dLuminance)<epsilon){return x;}
const sign=Math.sign(dLuminance);if(sign!==previousSign){multiplier/=2;previousSign=sign;}else if(x<0||x>1){return null;}
x+=multiplier*(index===V?-dLuminance:dLuminance);dLuminance=updateCandidateAndComputeDelta(index,x);}
console.error('Loop exited unexpectedly');return null;}
let s;for(s=0;s<1+dS;s+=dS){s=Math.min(1,s);candidateHSVA[S]=s;candidateHSVA[V]=lastV+currentSlope*dS;const v=approach(V);if(v===null){break;}
currentSlope=s===0?0:(v-lastV)/dS;lastV=v;pathBuilder.push(pathBuilder.length?'L':'M');pathBuilder.push((s*width).toFixed(2));pathBuilder.push(((1-v)*height).toFixed(2));}
if(s<1+dS){s-=dS;candidateHSVA[V]=1;s=approach(S);if(s!==null){pathBuilder=pathBuilder.concat(['L',(s*width).toFixed(2),'-0.1']);}}
if(pathBuilder.length===0){return null;}
return pathBuilder.join(' ');}}
var ContrastOverlay$1=Object.freeze({__proto__:null,ContrastOverlay:ContrastOverlay,ContrastRatioLineBuilder:ContrastRatioLineBuilder});class Spectrum extends Widget.VBox{constructor(contrastInfo){function appendSwitcherIcon(parentElement){const icon=parentElement.createSVGChild('svg');icon.setAttribute('height',16);icon.setAttribute('width',16);const path=icon.createSVGChild('path');path.setAttribute('d','M5,6 L11,6 L8,2 Z M5,10 L11,10 L8,14 Z');return icon;}
super(true);this.registerRequiredCSS('color_picker/spectrum.css');this._colorElement=this.contentElement.createChild('div','spectrum-color');this._colorElement.tabIndex=0;this.setDefaultFocusedElement(this._colorElement);this._colorElement.addEventListener('keydown',this._onSliderKeydown.bind(this,positionColor.bind(this)));const swatchAriaText=ls`Press arrow keys with or without modifiers to move swatch position. Arrow key with Shift key moves position largely, with Ctrl key it is less and with Alt key it is even less`;ARIAUtils.setAccessibleName(this._colorElement,swatchAriaText);ARIAUtils.markAsApplication(this._colorElement);this._colorDragElement=this._colorElement.createChild('div','spectrum-sat fill').createChild('div','spectrum-val fill').createChild('div','spectrum-dragger');this._dragX=0;this._dragY=0;const toolsContainer=this.contentElement.createChild('div','spectrum-tools');const toolbar=new Toolbar.Toolbar('spectrum-eye-dropper',toolsContainer);this._colorPickerButton=new Toolbar.ToolbarToggle(UIString.UIString('Toggle color picker'),'largeicon-eyedropper');this._colorPickerButton.setToggled(true);this._colorPickerButton.addEventListener(Toolbar.ToolbarButton.Events.Click,this._toggleColorPicker.bind(this,undefined));toolbar.appendToolbarItem(this._colorPickerButton);this._swatch=new Swatch$1(toolsContainer);this._hueElement=toolsContainer.createChild('div','spectrum-hue');this._hueElement.tabIndex=0;this._hueElement.addEventListener('keydown',this._onSliderKeydown.bind(this,positionHue.bind(this)));ARIAUtils.setAccessibleName(this._hueElement,ls`Change hue`);ARIAUtils.markAsSlider(this._hueElement,0,360);this._hueSlider=this._hueElement.createChild('div','spectrum-slider');this._alphaElement=toolsContainer.createChild('div','spectrum-alpha');this._alphaElement.tabIndex=0;this._alphaElement.addEventListener('keydown',this._onSliderKeydown.bind(this,positionAlpha.bind(this)));ARIAUtils.setAccessibleName(this._alphaElement,ls`Change alpha`);ARIAUtils.markAsSlider(this._alphaElement,0,1);this._alphaElementBackground=this._alphaElement.createChild('div','spectrum-alpha-background');this._alphaSlider=this._alphaElement.createChild('div','spectrum-slider');this._displayContainer=toolsContainer.createChild('div','spectrum-text source-code');ARIAUtils.markAsPoliteLiveRegion(this._displayContainer,true);this._textValues=[];for(let i=0;i<4;++i){const inputValue=UIUtils.createInput('spectrum-text-value');this._displayContainer.appendChild(inputValue);inputValue.maxLength=4;this._textValues.push(inputValue);inputValue.addEventListener('keydown',this._inputChanged.bind(this),false);inputValue.addEventListener('input',this._inputChanged.bind(this),false);inputValue.addEventListener('mousewheel',this._inputChanged.bind(this),false);inputValue.addEventListener('paste',this._pasted.bind(this),false);}
this._textLabels=this._displayContainer.createChild('div','spectrum-text-label');this._hexContainer=toolsContainer.createChild('div','spectrum-text spectrum-text-hex source-code');ARIAUtils.markAsPoliteLiveRegion(this._hexContainer,true);this._hexValue=UIUtils.createInput('spectrum-text-value');this._hexContainer.appendChild(this._hexValue);this._hexValue.maxLength=9;this._hexValue.addEventListener('keydown',this._inputChanged.bind(this),false);this._hexValue.addEventListener('input',this._inputChanged.bind(this),false);this._hexValue.addEventListener('mousewheel',this._inputChanged.bind(this),false);this._hexValue.addEventListener('paste',this._pasted.bind(this),false);const label=this._hexContainer.createChild('div','spectrum-text-label');label.textContent=ls`HEX`;ARIAUtils.setAccessibleName(this._hexValue,label.textContent);const displaySwitcher=toolsContainer.createChild('div','spectrum-display-switcher spectrum-switcher');appendSwitcherIcon(displaySwitcher);displaySwitcher.tabIndex=0;self.onInvokeElement(displaySwitcher,event=>{this._formatViewSwitch();event.consume(true);});ARIAUtils.setAccessibleName(displaySwitcher,ls`Change color format`);ARIAUtils.markAsButton(displaySwitcher);UIUtils.installDragHandle(this._hueElement,dragStart.bind(this,positionHue.bind(this)),positionHue.bind(this),null,'pointer','default');UIUtils.installDragHandle(this._alphaElement,dragStart.bind(this,positionAlpha.bind(this)),positionAlpha.bind(this),null,'pointer','default');UIUtils.installDragHandle(this._colorElement,dragStart.bind(this,positionColor.bind(this)),positionColor.bind(this),null,'pointer','default');if(contrastInfo){this._contrastInfo=contrastInfo;this._contrastOverlay=new ContrastOverlay(this._contrastInfo,this._colorElement);this._contrastDetails=new ContrastDetails(this._contrastInfo,this.contentElement,this._toggleColorPicker.bind(this),this._contrastPanelExpanded.bind(this));this._contrastDetailsBackgroundColorPickedToggledBound=this._contrastDetailsBackgroundColorPickedToggled.bind(this);}
this.element.classList.add('flex-none');this._palettes=new Map();this._palettePanel=this.contentElement.createChild('div','palette-panel');this._palettePanelShowing=false;this._paletteSectionContainer=this.contentElement.createChild('div','spectrum-palette-container');this._paletteContainer=this._paletteSectionContainer.createChild('div','spectrum-palette');this._paletteContainer.addEventListener('contextmenu',this._showPaletteColorContextMenu.bind(this,-1));this._shadesContainer=this.contentElement.createChild('div','palette-color-shades hidden');UIUtils.installDragHandle(this._paletteContainer,this._paletteDragStart.bind(this),this._paletteDrag.bind(this),this._paletteDragEnd.bind(this),'default');const paletteSwitcher=this._paletteSectionContainer.createChild('div','spectrum-palette-switcher spectrum-switcher');appendSwitcherIcon(paletteSwitcher);ARIAUtils.markAsButton(paletteSwitcher);ARIAUtils.setAccessibleName(paletteSwitcher,ls`Preview palettes`);paletteSwitcher.tabIndex=0;self.onInvokeElement(paletteSwitcher,event=>{this._togglePalettePanel(true);event.consume(true);});this._deleteIconToolbar=new Toolbar.Toolbar('delete-color-toolbar');this._deleteButton=new Toolbar.ToolbarButton('','largeicon-trash-bin');this._deleteIconToolbar.appendToolbarItem(this._deleteButton);const overlay=this.contentElement.createChild('div','spectrum-overlay fill');overlay.addEventListener('click',this._togglePalettePanel.bind(this,false));this._addColorToolbar=new Toolbar.Toolbar('add-color-toolbar');const addColorButton=new Toolbar.ToolbarButton(UIString.UIString('Add to palette'),'largeicon-add');addColorButton.addEventListener(Toolbar.ToolbarButton.Events.Click,this._onAddColorMousedown.bind(this));addColorButton.element.addEventListener('keydown',this._onAddColorKeydown.bind(this));this._addColorToolbar.appendToolbarItem(addColorButton);this._colorPickedBound=this._colorPicked.bind(this);this._loadPalettes();new PaletteGenerator(palette=>{if(palette.colors.length){this.addPalette(palette);}else if(this._selectedColorPalette.get()===palette.title){this._paletteSelected(MaterialPalette);}});function dragStart(callback,event){this._colorOffset=this._colorElement.totalOffset();callback(event);return true;}
function getUpdatedSliderPosition(element,event){const elementPosition=element.getBoundingClientRect();switch(event.key){case'ArrowLeft':case'ArrowDown':return elementPosition.left-1;case'ArrowRight':case'ArrowUp':return elementPosition.right+1;default:return event.x;}}
function positionHue(event){const hsva=this._hsv.slice();const sliderPosition=getUpdatedSliderPosition(this._hueSlider,event);const hueAlphaLeft=this._hueElement.getBoundingClientRect().left;const positionFraction=(sliderPosition-hueAlphaLeft)/this._hueAlphaWidth;const newHue=1-positionFraction;hsva[0]=NumberUtilities.clamp(newHue,0,1);this._innerSetColor(hsva,'',undefined,undefined,ChangeSource.Other);const colorValues=this._color().canonicalHSLA();ARIAUtils.setValueNow(this._hueElement,colorValues[0]);}
function positionAlpha(event){const hsva=this._hsv.slice();const sliderPosition=getUpdatedSliderPosition(this._alphaSlider,event);const hueAlphaLeft=this._hueElement.getBoundingClientRect().left;const positionFraction=(sliderPosition-hueAlphaLeft)/this._hueAlphaWidth;const newAlpha=Math.round(positionFraction*100)/100;hsva[3]=NumberUtilities.clamp(newAlpha,0,1);this._innerSetColor(hsva,'',undefined,undefined,ChangeSource.Other);const colorValues=this._color().canonicalHSLA();ARIAUtils.setValueText(this._alphaElement,colorValues[3]);}
function positionColor(event){const hsva=this._hsv.slice();const colorPosition=getUpdatedColorPosition(this._colorDragElement,event);this._colorOffset=this._colorElement.totalOffset();hsva[1]=NumberUtilities.clamp((colorPosition.x-this._colorOffset.left)/this.dragWidth,0,1);hsva[2]=NumberUtilities.clamp(1-(colorPosition.y-this._colorOffset.top)/this.dragHeight,0,1);this._innerSetColor(hsva,'',undefined,undefined,ChangeSource.Other);}
function getUpdatedColorPosition(dragElement,event){const elementPosition=dragElement.getBoundingClientRect();const verticalX=elementPosition.x+elementPosition.width/2;const horizontalY=elementPosition.y+elementPosition.width/2;const defaultUnit=elementPosition.width/4;const unit=getUnitToMove(defaultUnit,event);switch(event.key){case'ArrowLeft':return{x:elementPosition.left-unit,y:horizontalY};case'ArrowRight':return{x:elementPosition.right+unit,y:horizontalY};case'ArrowDown':return{x:verticalX,y:elementPosition.bottom+unit};case'ArrowUp':return{x:verticalX,y:elementPosition.top-unit};default:return{x:event.x,y:event.y};}}
function getUnitToMove(unit,event){if(event.altKey){unit=1;}else if(event.ctrlKey){unit=10;}else if(event.shiftKey){unit=20;}
return unit;}}
_contrastDetailsBackgroundColorPickedToggled({data:enabled}){if(enabled){this._toggleColorPicker(false);}}
_contrastPanelExpanded(){this._contrastOverlay.setVisible(this._contrastDetails.expanded());this._resizeForSelectedPalette(true);}
_updatePalettePanel(){this._palettePanel.removeChildren();const title=this._palettePanel.createChild('div','palette-title');title.textContent=UIString.UIString('Color Palettes');const toolbar=new Toolbar.Toolbar('',this._palettePanel);this._closeButton=new Toolbar.ToolbarButton(ls`Return to color picker`,'largeicon-delete');this._closeButton.addEventListener(Toolbar.ToolbarButton.Events.Click,this._togglePalettePanel.bind(this,false));this._closeButton.element.addEventListener('keydown',this._onCloseBtnKeydown.bind(this));toolbar.appendToolbarItem(this._closeButton);for(const palette of this._palettes.values()){this._palettePanel.appendChild(this._createPreviewPaletteElement(palette));}}
_togglePalettePanel(show){if(this._palettePanelShowing===show){return;}
if(show){this._updatePalettePanel();}
this._palettePanelShowing=show;this.contentElement.classList.toggle('palette-panel-showing',show);this._focus();}
_onCloseBtnKeydown(event){if(isEscKey(event)||isEnterOrSpaceKey(event)){this._togglePalettePanel(false);event.consume(true);}}
_onSliderKeydown(sliderNewPosition,event){switch(event.key){case'ArrowLeft':case'ArrowRight':case'ArrowDown':case'ArrowUp':sliderNewPosition(event);event.consume(true);}}
_focus(){if(!this.isShowing()){return;}
if(this._palettePanelShowing){this._closeButton.element.focus({preventScroll:true});}else{this.contentElement.focus();}}
_createPaletteColor(colorText,colorName,animationDelay){const element=document.createElement('div');element.classList.add('spectrum-palette-color');element.style.background=StringUtilities.sprintf('linear-gradient(%s, %s), url(Images/checker.png)',colorText,colorText);if(animationDelay){element.animate([{opacity:0},{opacity:1}],{duration:100,delay:animationDelay,fill:'backwards'});}
element.title=colorName||colorText;return element;}
_showPalette(palette,animate,event){this._resizeForSelectedPalette();this._paletteContainer.removeChildren();for(let i=0;i<palette.colors.length;i++){const animationDelay=animate?i*100/palette.colors.length:0;const colorElement=this._createPaletteColor(palette.colors[i],palette.colorNames[i],animationDelay);ARIAUtils.markAsButton(colorElement);ARIAUtils.setAccessibleName(colorElement,ls`Color ${palette.colors[i]}`);colorElement.tabIndex=-1;colorElement.addEventListener('mousedown',this._paletteColorSelected.bind(this,palette.colors[i],palette.colorNames[i],palette.matchUserFormat));colorElement.addEventListener('focus',this._paletteColorSelected.bind(this,palette.colors[i],palette.colorNames[i],palette.matchUserFormat));colorElement.addEventListener('keydown',this._onPaletteColorKeydown.bind(this,i));if(palette.mutable){colorElement.__mutable=true;colorElement.__color=palette.colors[i];colorElement.addEventListener('contextmenu',this._showPaletteColorContextMenu.bind(this,i));}else if(palette===MaterialPalette){colorElement.classList.add('has-material-shades');let shadow=colorElement.createChild('div','spectrum-palette-color spectrum-palette-color-shadow');shadow.style.background=palette.colors[i];shadow=colorElement.createChild('div','spectrum-palette-color spectrum-palette-color-shadow');shadow.style.background=palette.colors[i];colorElement.title=ls`Long-click or long-press space to show alternate shades of ${palette.colors[i]}`;ARIAUtils.setAccessibleName(colorElement,colorElement.title);new UIUtils.LongClickController(colorElement,this._showLightnessShades.bind(this,colorElement,palette.colors[i]));}
this._paletteContainer.appendChild(colorElement);}
if(this._paletteContainer.childNodes.length>0){this._paletteContainer.childNodes[0].tabIndex=0;}
this._paletteContainerMutable=palette.mutable;if(palette.mutable){this._paletteContainer.appendChild(this._addColorToolbar.element);this._paletteContainer.appendChild(this._deleteIconToolbar.element);}else{this._addColorToolbar.element.remove();this._deleteIconToolbar.element.remove();}
this._togglePalettePanel(false);this._focus();}
_showLightnessShades(colorElement,colorText,event){function closeLightnessShades(element){this._shadesContainer.classList.add('hidden');element.classList.remove('spectrum-shades-shown');this._shadesContainer.ownerDocument.removeEventListener('mousedown',this._shadesCloseHandler,true);delete this._shadesCloseHandler;}
if(this._shadesCloseHandler){this._shadesCloseHandler();}
this._shadesContainer.classList.remove('hidden');this._shadesContainer.removeChildren();this._shadesContainer.animate([{transform:'scaleY(0)',opacity:'0'},{transform:'scaleY(1)',opacity:'1'}],{duration:200,easing:'cubic-bezier(0.4, 0, 0.2, 1)'});let shadesTop=this._paletteContainer.offsetTop+colorElement.offsetTop+colorElement.parentElement.offsetTop;if(this._contrastDetails){shadesTop+=this._contrastDetails.element().offsetHeight;}
this._shadesContainer.style.top=shadesTop+'px';this._shadesContainer.style.left=colorElement.offsetLeft+'px';colorElement.classList.add('spectrum-shades-shown');const shades=MaterialPaletteShades[colorText];for(let i=shades.length-1;i>=0;i--){const shadeElement=this._createPaletteColor(shades[i],undefined,i*200/shades.length+100);ARIAUtils.markAsButton(shadeElement);ARIAUtils.setAccessibleName(shadeElement,ls`Color ${shades[i]}`);shadeElement.tabIndex=-1;shadeElement.addEventListener('mousedown',this._paletteColorSelected.bind(this,shades[i],shades[i],false));shadeElement.addEventListener('focus',this._paletteColorSelected.bind(this,shades[i],shades[i],false));shadeElement.addEventListener('keydown',this._onShadeColorKeydown.bind(this,colorElement));this._shadesContainer.appendChild(shadeElement);}
if(this._shadesContainer.childNodes.length>0){this._shadesContainer.childNodes[this._shadesContainer.childNodes.length-1].focus();}
this._shadesCloseHandler=closeLightnessShades.bind(this,colorElement);this._shadesContainer.ownerDocument.addEventListener('mousedown',this._shadesCloseHandler,true);}
_slotIndexForEvent(e){const localX=e.pageX-this._paletteContainer.totalOffsetLeft();const localY=e.pageY-this._paletteContainer.totalOffsetTop();const col=Math.min(localX/_colorChipSize|0,_itemsPerPaletteRow-1);const row=(localY/_colorChipSize)|0;return Math.min(row*_itemsPerPaletteRow+col,this._customPaletteSetting.get().colors.length-1);}
_isDraggingToBin(e){return e.pageX>this._deleteIconToolbar.element.totalOffsetLeft();}
_paletteDragStart(e){const element=e.deepElementFromPoint();if(!element||!element.__mutable){return false;}
const index=this._slotIndexForEvent(e);this._dragElement=element;this._dragHotSpotX=e.pageX-(index%_itemsPerPaletteRow)*_colorChipSize;this._dragHotSpotY=e.pageY-(index/_itemsPerPaletteRow|0)*_colorChipSize;return true;}
_paletteDrag(e){if(e.pageX<this._paletteContainer.totalOffsetLeft()||e.pageY<this._paletteContainer.totalOffsetTop()){return;}
const newIndex=this._slotIndexForEvent(e);const offsetX=e.pageX-(newIndex%_itemsPerPaletteRow)*_colorChipSize;const offsetY=e.pageY-(newIndex/_itemsPerPaletteRow|0)*_colorChipSize;const isDeleting=this._isDraggingToBin(e);this._deleteIconToolbar.element.classList.add('dragging');this._deleteIconToolbar.element.classList.toggle('delete-color-toolbar-active',isDeleting);const dragElementTransform='translateX('+(offsetX-this._dragHotSpotX)+'px) translateY('+(offsetY-this._dragHotSpotY)+'px)';this._dragElement.style.transform=isDeleting?dragElementTransform+' scale(0.8)':dragElementTransform;const children=Array.prototype.slice.call(this._paletteContainer.children);const index=children.indexOf(this._dragElement);const swatchOffsets=new Map();for(const swatch of children){swatchOffsets.set(swatch,swatch.totalOffset());}
if(index!==newIndex){this._paletteContainer.insertBefore(this._dragElement,children[newIndex>index?newIndex+1:newIndex]);}
for(const swatch of children){if(swatch===this._dragElement){continue;}
const before=swatchOffsets.get(swatch);const after=swatch.totalOffset();if(before.left!==after.left||before.top!==after.top){swatch.animate([{transform:'translateX('+(before.left-after.left)+'px) translateY('+(before.top-after.top)+'px)'},{transform:'none'}],{duration:100,easing:'cubic-bezier(0, 0, 0.2, 1)'});}}}
_paletteDragEnd(e){if(this._isDraggingToBin(e)){this._dragElement.remove();}
this._dragElement.style.removeProperty('transform');const children=this._paletteContainer.children;const colors=[];for(let i=0;i<children.length;++i){if(children[i].__color){colors.push(children[i].__color);}}
const palette=this._customPaletteSetting.get();palette.colors=colors;this._customPaletteSetting.set(palette);this._showPalette(this._customPaletteSetting.get(),false);this._deleteIconToolbar.element.classList.remove('dragging');this._deleteIconToolbar.element.classList.remove('delete-color-toolbar-active');}
_loadPalettes(){this._palettes.set(MaterialPalette.title,MaterialPalette);const defaultCustomPalette={title:'Custom',colors:[],colorNames:[],mutable:true};this._customPaletteSetting=Settings.Settings.instance().createSetting('customColorPalette',defaultCustomPalette);const customPalette=this._customPaletteSetting.get();customPalette.colorNames=customPalette.colorNames||[];this._palettes.set(customPalette.title,customPalette);this._selectedColorPalette=Settings.Settings.instance().createSetting('selectedColorPalette',GeneratedPaletteTitle);const palette=this._palettes.get(this._selectedColorPalette.get());if(palette){this._showPalette(palette,true);}}
addPalette(palette){this._palettes.set(palette.title,palette);if(this._selectedColorPalette.get()===palette.title){this._showPalette(palette,true);}}
_createPreviewPaletteElement(palette){const colorsPerPreviewRow=5;const previewElement=document.createElement('div');previewElement.classList.add('palette-preview');ARIAUtils.markAsButton(previewElement);previewElement.tabIndex=0;const titleElement=previewElement.createChild('div','palette-preview-title');titleElement.textContent=palette.title;let i;for(i=0;i<colorsPerPreviewRow&&i<palette.colors.length;i++){previewElement.appendChild(this._createPaletteColor(palette.colors[i],palette.colorNames[i]));}
for(;i<colorsPerPreviewRow;i++){previewElement.createChild('div','spectrum-palette-color empty-color');}
self.onInvokeElement(previewElement,event=>{this._paletteSelected(palette);event.consume(true);});return previewElement;}
_paletteSelected(palette){this._selectedColorPalette.set(palette.title);this._showPalette(palette,true);}
_resizeForSelectedPalette(force){const palette=this._palettes.get(this._selectedColorPalette.get());if(!palette){return;}
let numColors=palette.colors.length;if(palette===this._customPaletteSetting.get()){numColors++;}
const rowsNeeded=Math.max(1,Math.ceil(numColors/_itemsPerPaletteRow));if(this._numPaletteRowsShown===rowsNeeded&&!force){return;}
this._numPaletteRowsShown=rowsNeeded;const paletteColorHeight=12;const paletteMargin=12;let paletteTop=236;if(this._contrastDetails){if(this._contrastDetails.expanded()){paletteTop+=78;}else{paletteTop+=36;}}
this.element.style.height=(paletteTop+paletteMargin+(paletteColorHeight+paletteMargin)*rowsNeeded)+'px';this.dispatchEventToListeners(Events$2.SizeChanged);}
_paletteColorSelected(colorText,colorName,matchUserFormat){const color=Color.Color.parse(colorText);if(!color){return;}
this._innerSetColor(color.hsva(),colorText,colorName,matchUserFormat?this._colorFormat:color.format(),ChangeSource.Other);}
_onPaletteColorKeydown(colorIndex,event){let nextColorIndex;switch(event.key){case'ArrowLeft':nextColorIndex=colorIndex-1;break;case'ArrowRight':nextColorIndex=colorIndex+1;break;case'ArrowUp':nextColorIndex=colorIndex-_itemsPerPaletteRow;break;case'ArrowDown':nextColorIndex=colorIndex+_itemsPerPaletteRow;break;}
if(nextColorIndex>-1&&nextColorIndex<this._paletteContainer.childNodes.length){this._paletteContainer.childNodes[nextColorIndex].focus();}}
_onShadeColorKeydown(colorElement,event){if(isEscKey(event)||event.key==='Tab'){colorElement.focus();this._shadesCloseHandler();event.consume(true);}else if(event.key==='ArrowUp'&&event.target.previousElementSibling){event.target.previousElementSibling.focus();event.consume(true);}else if(event.key==='ArrowDown'&&event.target.nextElementSibling){event.target.nextElementSibling.focus();event.consume(true);}}
_onAddColorMousedown(){this._addColorToCustomPalette();}
_onAddColorKeydown(event){if(isEnterOrSpaceKey(event)){this._addColorToCustomPalette();event.consume(true);}}
_addColorToCustomPalette(){const palette=this._customPaletteSetting.get();palette.colors.push(this.colorString());this._customPaletteSetting.set(palette);this._showPalette(this._customPaletteSetting.get(),false);const colorElements=this._paletteContainer.querySelectorAll('.spectrum-palette-color');colorElements[colorElements.length-1].focus();}
_showPaletteColorContextMenu(colorIndex,event){if(!this._paletteContainerMutable){return;}
const contextMenu=new ContextMenu.ContextMenu(event);if(colorIndex!==-1){contextMenu.defaultSection().appendItem(UIString.UIString('Remove color'),this._deletePaletteColors.bind(this,colorIndex,false));contextMenu.defaultSection().appendItem(UIString.UIString('Remove all to the right'),this._deletePaletteColors.bind(this,colorIndex,true));}
contextMenu.defaultSection().appendItem(UIString.UIString('Clear palette'),this._deletePaletteColors.bind(this,-1,true));contextMenu.show();}
_deletePaletteColors(colorIndex,toRight){const palette=this._customPaletteSetting.get();if(toRight){palette.colors.splice(colorIndex+1,palette.colors.length-colorIndex-1);}else{palette.colors.splice(colorIndex,1);}
this._customPaletteSetting.set(palette);this._showPalette(this._customPaletteSetting.get(),false);}
setColor(color,colorFormat){this._originalFormat=colorFormat;this._innerSetColor(color.hsva(),'',undefined,colorFormat,ChangeSource.Model);const colorValues=this._color().canonicalHSLA();ARIAUtils.setValueNow(this._hueElement,colorValues[0]);ARIAUtils.setValueText(this._alphaElement,colorValues[3]);}
_innerSetColor(hsva,colorString,colorName,colorFormat,changeSource){if(hsva!==undefined){this._hsv=hsva;}
this._colorName=colorName;if(colorString!==undefined){this._colorString=colorString;}
if(colorFormat!==undefined){const cf=Color.Format;console.assert(colorFormat!==cf.Original,'Spectrum\'s color format cannot be Original');if(colorFormat===cf.RGBA){colorFormat=cf.RGB;}else if(colorFormat===cf.HSLA){colorFormat=cf.HSL;}else if(colorFormat===cf.HEXA){colorFormat=cf.HEX;}else if(colorFormat===cf.ShortHEXA){colorFormat=cf.ShortHEX;}
this._colorFormat=colorFormat;}
if(hsva&&this._contrastInfo){this._contrastInfo.setColor(Color.Color.fromHSVA(hsva));}
this._updateHelperLocations();this._updateUI();if(changeSource!==ChangeSource.Input){this._updateInput();}
if(changeSource!==ChangeSource.Model){this.dispatchEventToListeners(Events$2.ColorChanged,this.colorString());}}
_color(){return Color.Color.fromHSVA(this._hsv);}
colorName(){return this._colorName;}
colorString(){if(this._colorString){return this._colorString;}
const cf=Color.Format;const color=this._color();let colorString=color.asString(this._colorFormat);if(colorString){return colorString;}
if(this._colorFormat===cf.Nickname){colorString=color.asString(color.hasAlpha()?cf.HEXA:cf.HEX);}else if(this._colorFormat===cf.ShortHEX){colorString=color.asString(color.detectHEXFormat());}else if(this._colorFormat===cf.HEX){colorString=color.asString(cf.HEXA);}else if(this._colorFormat===cf.HSL){colorString=color.asString(cf.HSLA);}else{colorString=color.asString(cf.RGBA);}
console.assert(colorString);return colorString||'';}
_updateHelperLocations(){const h=this._hsv[0];const s=this._hsv[1];const v=this._hsv[2];const alpha=this._hsv[3];this._dragX=s*this.dragWidth;this._dragY=this.dragHeight-(v*this.dragHeight);const dragX=Math.max(-this._colorDragElementHeight,Math.min(this.dragWidth-this._colorDragElementHeight,this._dragX-this._colorDragElementHeight));const dragY=Math.max(-this._colorDragElementHeight,Math.min(this.dragHeight-this._colorDragElementHeight,this._dragY-this._colorDragElementHeight));this._colorDragElement.positionAt(dragX,dragY);const hueSlideX=(1-h)*this._hueAlphaWidth-this.slideHelperWidth;this._hueSlider.style.left=hueSlideX+'px';const alphaSlideX=alpha*this._hueAlphaWidth-this.slideHelperWidth;this._alphaSlider.style.left=alphaSlideX+'px';}
_updateInput(){const cf=Color.Format;if(this._colorFormat===cf.HEX||this._colorFormat===cf.ShortHEX||this._colorFormat===cf.Nickname){this._hexContainer.hidden=false;this._displayContainer.hidden=true;if(this._colorFormat===cf.ShortHEX){this._hexValue.value=this._color().asString(this._color().detectHEXFormat());}else{this._hexValue.value=this._color().asString(this._color().hasAlpha()?cf.HEXA:cf.HEX);}}else{this._hexContainer.hidden=true;this._displayContainer.hidden=false;const isRgb=this._colorFormat===cf.RGB;this._textLabels.textContent=isRgb?'RGBA':'HSLA';const colorValues=isRgb?this._color().canonicalRGBA():this._color().canonicalHSLA();for(let i=0;i<3;++i){ARIAUtils.setAccessibleName(this._textValues[i],ls`${this._textLabels.textContent.charAt(i)} in ${this._textLabels.textContent}`);this._textValues[i].value=colorValues[i];if(!isRgb&&(i===1||i===2)){this._textValues[i].value+='%';}}
ARIAUtils.setAccessibleName(this._textValues[3],ls`${this._textLabels.textContent.charAt(3)} in ${this._textLabels.textContent}`);this._textValues[3].value=Math.round(colorValues[3]*100)/100;}}
_updateUI(){const h=Color.Color.fromHSVA([this._hsv[0],1,1,1]);this._colorElement.style.backgroundColor=(h.asString(Color.Format.RGB));if(this._contrastOverlay){this._contrastOverlay.setDimensions(this.dragWidth,this.dragHeight);}
this._swatch.setColor(this._color(),this.colorString());this._colorDragElement.style.backgroundColor=(this._color().asString(Color.Format.RGBA));const noAlpha=Color.Color.fromHSVA(this._hsv.slice(0,3).concat(1));this._alphaElementBackground.style.backgroundImage=StringUtilities.sprintf('linear-gradient(to right, rgba(0,0,0,0), %s)',noAlpha.asString(Color.Format.RGB));}
_formatViewSwitch(){const cf=Color.Format;let format=cf.RGB;if(this._colorFormat===cf.RGB){format=cf.HSL;}else if(this._colorFormat===cf.HSL){format=(this._originalFormat===cf.ShortHEX||this._originalFormat===cf.ShortHEXA)?cf.ShortHEX:cf.HEX;}
this._innerSetColor(undefined,'',undefined,format,ChangeSource.Other);}
_pasted(event){if(!event.clipboardData){return;}
const text=event.clipboardData.getData('text');const color=Color.Color.parse(text);if(!color){return;}
this._innerSetColor(color.hsva(),text,undefined,undefined,ChangeSource.Other);event.preventDefault();}
_inputChanged(event){function elementValue(element){return element.value;}
const inputElement=(event.currentTarget);const newValue=UIUtils.createReplacementString(inputElement.value,event);if(newValue){inputElement.value=newValue;inputElement.selectionStart=0;inputElement.selectionEnd=newValue.length;event.consume(true);}
const cf=Color.Format;let colorString;if(this._colorFormat===cf.Nickname||this._colorFormat===cf.HEX||this._colorFormat===cf.ShortHEX){colorString=this._hexValue.value;}else{const format=this._colorFormat===cf.RGB?'rgb':'hsl';const values=this._textValues.slice(0,-1).map(elementValue).join(' ');const alpha=this._textValues.slice(-1).map(elementValue).join(' ');colorString=StringUtilities.sprintf('%s(%s)',format,[values,alpha].join(' / '));}
const color=Color.Color.parse(colorString);if(!color){return;}
let colorFormat=undefined;if(this._colorFormat===cf.HEX||this._colorFormat===cf.ShortHEX){colorFormat=color.detectHEXFormat();}
this._innerSetColor(color.hsva(),colorString,undefined,colorFormat,ChangeSource.Input);}
wasShown(){this._hueAlphaWidth=this._hueElement.offsetWidth;this.slideHelperWidth=this._hueSlider.offsetWidth/2;this.dragWidth=this._colorElement.offsetWidth;this.dragHeight=this._colorElement.offsetHeight;this._colorDragElementHeight=this._colorDragElement.offsetHeight/2;this._innerSetColor(undefined,undefined,undefined,undefined,ChangeSource.Model);this._toggleColorPicker(true);if(this._contrastDetails){this._contrastDetails.addEventListener(Events$1.BackgroundColorPickerWillBeToggled,this._contrastDetailsBackgroundColorPickedToggledBound);}}
willHide(){this._toggleColorPicker(false);if(this._contrastDetails){this._contrastDetails.removeEventListener(Events$1.BackgroundColorPickerWillBeToggled,this._contrastDetailsBackgroundColorPickedToggledBound);}}
_toggleColorPicker(enabled,event){if(enabled===undefined){enabled=!this._colorPickerButton.toggled();}
this._colorPickerButton.setToggled(enabled);if(this._contrastDetails&&enabled&&this._contrastDetails.backgroundColorPickerEnabled()){this._contrastDetails.toggleBackgroundColorPicker(false);}
InspectorFrontendHost.InspectorFrontendHostInstance.setEyeDropperActive(enabled);if(enabled){InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener(InspectorFrontendHostAPI.Events.EyeDropperPickedColor,this._colorPickedBound);}else{InspectorFrontendHost.InspectorFrontendHostInstance.events.removeEventListener(InspectorFrontendHostAPI.Events.EyeDropperPickedColor,this._colorPickedBound);}}
_colorPicked(event){const rgbColor=(event.data);const rgba=[rgbColor.r,rgbColor.g,rgbColor.b,(rgbColor.a/2.55|0)/100];const color=Color.Color.fromRGBA(rgba);this._innerSetColor(color.hsva(),'',undefined,undefined,ChangeSource.Other);InspectorFrontendHost.InspectorFrontendHostInstance.bringToFront();}}
const ChangeSource={Input:'Input',Model:'Model',Other:'Other'};const Events$2={ColorChanged:Symbol('ColorChanged'),SizeChanged:Symbol('SizeChanged')};const _colorChipSize=24;const _itemsPerPaletteRow=8;const GeneratedPaletteTitle='Page colors';class PaletteGenerator{constructor(callback){this._callback=callback;this._frequencyMap=new Map();const stylesheetPromises=[];for(const cssModel of SDKModel.TargetManager.instance().models(CSSModel.CSSModel)){for(const stylesheet of cssModel.allStyleSheets()){stylesheetPromises.push(this._processStylesheet(stylesheet));}}
Promise.all(stylesheetPromises).catch(error=>{console.error(error);}).then(this._finish.bind(this));}
_frequencyComparator(a,b){return this._frequencyMap.get(b)-this._frequencyMap.get(a);}
_finish(){function hueComparator(a,b){const hsva=paletteColors.get(a).hsva();const hsvb=paletteColors.get(b).hsva();if(hsvb[1]<0.12&&hsva[1]<0.12){return hsvb[2]*hsvb[3]-hsva[2]*hsva[3];}
if(hsvb[1]<0.12){return-1;}
if(hsva[1]<0.12){return 1;}
if(hsvb[0]===hsva[0]){return hsvb[1]*hsvb[3]-hsva[1]*hsva[3];}
return(hsvb[0]+0.94)%1-(hsva[0]+0.94)%1;}
let colors=[...this._frequencyMap.keys()];colors=colors.sort(this._frequencyComparator.bind(this));const paletteColors=new Map();const colorsPerRow=24;while(paletteColors.size<colorsPerRow&&colors.length){const colorText=colors.shift();const color=Color.Color.parse(colorText);if(!color||color.nickname()==='white'||color.nickname()==='black'){continue;}
paletteColors.set(colorText,color);}
this._callback({title:GeneratedPaletteTitle,colors:[...paletteColors.keys()].sort(hueComparator),colorNames:[],mutable:false});}
async _processStylesheet(stylesheet){let text=(await stylesheet.requestContent()).content||'';text=text.toLowerCase();const regexResult=text.match(/((?:rgb|hsl)a?\([^)]+\)|#[0-9a-f]{6}|#[0-9a-f]{3})/g)||[];for(const c of regexResult){let frequency=this._frequencyMap.get(c)||0;this._frequencyMap.set(c,++frequency);}}}
const MaterialPaletteShades={'#F44336':['#FFEBEE','#FFCDD2','#EF9A9A','#E57373','#EF5350','#F44336','#E53935','#D32F2F','#C62828','#B71C1C'],'#E91E63':['#FCE4EC','#F8BBD0','#F48FB1','#F06292','#EC407A','#E91E63','#D81B60','#C2185B','#AD1457','#880E4F'],'#9C27B0':['#F3E5F5','#E1BEE7','#CE93D8','#BA68C8','#AB47BC','#9C27B0','#8E24AA','#7B1FA2','#6A1B9A','#4A148C'],'#673AB7':['#EDE7F6','#D1C4E9','#B39DDB','#9575CD','#7E57C2','#673AB7','#5E35B1','#512DA8','#4527A0','#311B92'],'#3F51B5':['#E8EAF6','#C5CAE9','#9FA8DA','#7986CB','#5C6BC0','#3F51B5','#3949AB','#303F9F','#283593','#1A237E'],'#2196F3':['#E3F2FD','#BBDEFB','#90CAF9','#64B5F6','#42A5F5','#2196F3','#1E88E5','#1976D2','#1565C0','#0D47A1'],'#03A9F4':['#E1F5FE','#B3E5FC','#81D4FA','#4FC3F7','#29B6F6','#03A9F4','#039BE5','#0288D1','#0277BD','#01579B'],'#00BCD4':['#E0F7FA','#B2EBF2','#80DEEA','#4DD0E1','#26C6DA','#00BCD4','#00ACC1','#0097A7','#00838F','#006064'],'#009688':['#E0F2F1','#B2DFDB','#80CBC4','#4DB6AC','#26A69A','#009688','#00897B','#00796B','#00695C','#004D40'],'#4CAF50':['#E8F5E9','#C8E6C9','#A5D6A7','#81C784','#66BB6A','#4CAF50','#43A047','#388E3C','#2E7D32','#1B5E20'],'#8BC34A':['#F1F8E9','#DCEDC8','#C5E1A5','#AED581','#9CCC65','#8BC34A','#7CB342','#689F38','#558B2F','#33691E'],'#CDDC39':['#F9FBE7','#F0F4C3','#E6EE9C','#DCE775','#D4E157','#CDDC39','#C0CA33','#AFB42B','#9E9D24','#827717'],'#FFEB3B':['#FFFDE7','#FFF9C4','#FFF59D','#FFF176','#FFEE58','#FFEB3B','#FDD835','#FBC02D','#F9A825','#F57F17'],'#FFC107':['#FFF8E1','#FFECB3','#FFE082','#FFD54F','#FFCA28','#FFC107','#FFB300','#FFA000','#FF8F00','#FF6F00'],'#FF9800':['#FFF3E0','#FFE0B2','#FFCC80','#FFB74D','#FFA726','#FF9800','#FB8C00','#F57C00','#EF6C00','#E65100'],'#FF5722':['#FBE9E7','#FFCCBC','#FFAB91','#FF8A65','#FF7043','#FF5722','#F4511E','#E64A19','#D84315','#BF360C'],'#795548':['#EFEBE9','#D7CCC8','#BCAAA4','#A1887F','#8D6E63','#795548','#6D4C41','#5D4037','#4E342E','#3E2723'],'#9E9E9E':['#FAFAFA','#F5F5F5','#EEEEEE','#E0E0E0','#BDBDBD','#9E9E9E','#757575','#616161','#424242','#212121'],'#607D8B':['#ECEFF1','#CFD8DC','#B0BEC5','#90A4AE','#78909C','#607D8B','#546E7A','#455A64','#37474F','#263238']};const MaterialPalette={title:'Material',mutable:false,matchUserFormat:true,colors:Object.keys(MaterialPaletteShades),colorNames:[]};class Swatch$1{constructor(parentElement){this._colorString;const swatchElement=parentElement.createChild('span','swatch');this._swatchInnerElement=swatchElement.createChild('span','swatch-inner');this._swatchOverlayElement=swatchElement.createChild('span','swatch-overlay');ARIAUtils.markAsButton(this._swatchOverlayElement);ARIAUtils.setPressed(this._swatchOverlayElement,false);this._swatchOverlayElement.tabIndex=0;self.onInvokeElement(this._swatchOverlayElement,this._onCopyText.bind(this));this._swatchOverlayElement.addEventListener('mouseout',this._onCopyIconMouseout.bind(this));this._swatchOverlayElement.addEventListener('blur',this._onCopyIconMouseout.bind(this));this._swatchCopyIcon=Icon.Icon.create('largeicon-copy','copy-color-icon');this._swatchCopyIcon.title=ls`Copy color to clipboard`;this._swatchOverlayElement.appendChild(this._swatchCopyIcon);ARIAUtils.setAccessibleName(this._swatchOverlayElement,this._swatchCopyIcon.title);}
setColor(color,colorString){this._swatchInnerElement.style.backgroundColor=(color.asString(Color.Format.RGBA));this._swatchInnerElement.classList.toggle('swatch-inner-white',color.hsla()[2]>0.9);this._colorString=colorString||null;if(colorString){this._swatchOverlayElement.hidden=false;}else{this._swatchOverlayElement.hidden=true;}}
_onCopyText(event){this._swatchCopyIcon.setIconType('largeicon-checkmark');InspectorFrontendHost.InspectorFrontendHostInstance.copyText(this._colorString);ARIAUtils.setPressed(this._swatchOverlayElement,true);event.consume();}
_onCopyIconMouseout(){this._swatchCopyIcon.setIconType('largeicon-copy');ARIAUtils.setPressed(this._swatchOverlayElement,false);}}
let Palette;var Spectrum$1=Object.freeze({__proto__:null,Spectrum:Spectrum,ChangeSource:ChangeSource,Events:Events$2,PaletteGenerator:PaletteGenerator,MaterialPaletteShades:MaterialPaletteShades,MaterialPalette:MaterialPalette,Swatch:Swatch$1,Palette:Palette});export{ContrastDetails$1 as ContrastDetails,ContrastInfo$1 as ContrastInfo,ContrastOverlay$1 as ContrastOverlay,Spectrum$1 as Spectrum};