import{ObjectWrapper,Color,Linkifier as Linkifier$1}from'../common/common.js';import{SDKModel,CSSModel,DOMModel}from'../sdk/sdk.js';import{Widget,UIUtils,Fragment,Toolbar,Panel,SplitWidget,TabbedPane}from'../ui/ui.js';import{Linkifier}from'../components/components.js';import{SortableDataGrid,DataGrid}from'../data_grid/data_grid.js';import{TextRange}from'../text_utils/text_utils.js';class OverviewController extends ObjectWrapper.ObjectWrapper{constructor(){super();this.currentUrl=SDKModel.TargetManager.instance().inspectedURL();SDKModel.TargetManager.instance().addEventListener(SDKModel.Events.InspectedURLChanged,this._checkUrlAndResetIfChanged,this);}
_checkUrlAndResetIfChanged(){if(this.currentUrl===SDKModel.TargetManager.instance().inspectedURL()){return;}
this.currentUrl=SDKModel.TargetManager.instance().inspectedURL();this.dispatchEventToListeners(Events.Reset);}}
const Events={RequestOverviewStart:Symbol('RequestOverviewStart'),RequestNodeHighlight:Symbol('RequestNodeHighlight'),PopulateNodes:Symbol('PopulateNodes'),RequestOverviewCancel:Symbol('RequestOverviewCancel'),OverviewCompleted:Symbol('OverviewCompleted'),Reset:Symbol('Reset'),};var CSSOverviewController=Object.freeze({__proto__:null,OverviewController:OverviewController,Events:Events});class CSSOverviewUnusedDeclarations{static _add(target,key,item){const values=target.get(key)||[];values.push(item);target.set(key,values);}
static checkForUnusedPositionValues(unusedDeclarations,nodeId,strings,positionIdx,topIdx,leftIdx,rightIdx,bottomIdx){if(strings[positionIdx]!=='static'){return;}
if(strings[topIdx]!=='auto'){const reason=ls`Top applied to a statically positioned element`;this._add(unusedDeclarations,reason,{declaration:`top: ${strings[topIdx]}`,nodeId,});}
if(strings[leftIdx]!=='auto'){const reason=ls`Left applied to a statically positioned element`;this._add(unusedDeclarations,reason,{declaration:`left: ${strings[leftIdx]}`,nodeId,});}
if(strings[rightIdx]!=='auto'){const reason=ls`Right applied to a statically positioned element`;this._add(unusedDeclarations,reason,{declaration:`right: ${strings[rightIdx]}`,nodeId,});}
if(strings[bottomIdx]!=='auto'){const reason=ls`Bottom applied to a statically positioned element`;this._add(unusedDeclarations,reason,{declaration:`bottom: ${strings[bottomIdx]}`,nodeId,});}}
static checkForUnusedWidthAndHeightValues(unusedDeclarations,nodeId,strings,displayIdx,widthIdx,heightIdx){if(strings[displayIdx]!=='inline'){return;}
if(strings[widthIdx]!=='auto'){const reason=ls`Width applied to an inline element`;this._add(unusedDeclarations,reason,{declaration:`width: ${strings[widthIdx]}`,nodeId,});}
if(strings[heightIdx]!=='auto'){const reason=ls`Height applied to an inline element`;this._add(unusedDeclarations,reason,{declaration:`height: ${strings[heightIdx]}`,nodeId,});}}
static checkForInvalidVerticalAlignment(unusedDeclarations,nodeId,strings,displayIdx,verticalAlignIdx){if(strings[displayIdx]==='inline'||strings[displayIdx].startsWith('table')){return;}
if(strings[verticalAlignIdx]!=='baseline'){const reason=ls`Vertical alignment applied to element which is neither inline nor table-cell`;this._add(unusedDeclarations,reason,{declaration:`vertical-align: ${strings[verticalAlignIdx]}`,nodeId,});}}}
var CSSOverviewUnusedDeclarations$1=Object.freeze({__proto__:null,CSSOverviewUnusedDeclarations:CSSOverviewUnusedDeclarations});class CSSOverviewModel extends SDKModel.SDKModel{constructor(target){super(target);this._runtimeAgent=target.runtimeAgent();this._cssAgent=target.cssAgent();this._domAgent=target.domAgent();this._domSnapshotAgent=target.domsnapshotAgent();this._overlayAgent=target.overlayAgent();}
highlightNode(node){const highlightConfig={contentColor:Color.PageHighlight.Content.toProtocolRGBA(),showInfo:true};this._overlayAgent.invoke_hideHighlight({});this._overlayAgent.invoke_highlightNode({backendNodeId:node,highlightConfig});}
async getNodeStyleStats(){const backgroundColors=new Map();const textColors=new Map();const fillColors=new Map();const borderColors=new Map();const fontInfo=new Map();const unusedDeclarations=new Map();const snapshotConfig={computedStyles:['background-color','color','fill','border-top-width','border-top-color','border-bottom-width','border-bottom-color','border-left-width','border-left-color','border-right-width','border-right-color','font-family','font-size','font-weight','line-height','position','top','right','bottom','left','display','width','height','vertical-align']};const storeColor=(id,nodeId,target)=>{if(id===-1){return;}
const colorText=strings[id];const color=Color.Color.parse(colorText);if(!color||color.rgba()[3]===0){return;}
const colorFormatted=color.hasAlpha()?color.asString(Color.Format.HEXA):color.asString(Color.Format.HEX);const colorValues=target.get(colorFormatted)||new Set();colorValues.add(nodeId);target.set(colorFormatted,colorValues);};const isSVGNode=nodeName=>{const validNodes=new Set(['altglyph','circle','ellipse','path','polygon','polyline','rect','svg','text','textpath','tref','tspan']);return validNodes.has(nodeName.toLowerCase());};const isReplacedContent=nodeName=>{const validNodes=new Set(['iframe','video','embed','img']);return validNodes.has(nodeName.toLowerCase());};const isTableElementWithDefaultStyles=(nodeName,display)=>{const validNodes=new Set(['tr','td','thead','tbody']);return validNodes.has(nodeName.toLowerCase())&&display.startsWith('table');};let elementCount=0;const{documents,strings}=await this._domSnapshotAgent.invoke_captureSnapshot(snapshotConfig);for(const{nodes,layout}of documents){elementCount+=layout.nodeIndex.length;for(let idx=0;idx<layout.styles.length;idx++){const styles=layout.styles[idx];const nodeIdx=layout.nodeIndex[idx];const nodeId=nodes.backendNodeId[nodeIdx];const nodeName=nodes.nodeName[nodeIdx];const[backgroundColorIdx,textColorIdx,fillIdx,borderTopWidthIdx,borderTopColorIdx,borderBottomWidthIdx,borderBottomColorIdx,borderLeftWidthIdx,borderLeftColorIdx,borderRightWidthIdx,borderRightColorIdx,fontFamilyIdx,fontSizeIdx,fontWeightIdx,lineHeightIdx,positionIdx,topIdx,rightIdx,bottomIdx,leftIdx,displayIdx,widthIdx,heightIdx,verticalAlignIdx]=styles;storeColor(backgroundColorIdx,nodeId,backgroundColors);storeColor(textColorIdx,nodeId,textColors);if(isSVGNode(strings[nodeName])){storeColor(fillIdx,nodeId,fillColors);}
if(strings[borderTopWidthIdx]!=='0px'){storeColor(borderTopColorIdx,nodeId,borderColors);}
if(strings[borderBottomWidthIdx]!=='0px'){storeColor(borderBottomColorIdx,nodeId,borderColors);}
if(strings[borderLeftWidthIdx]!=='0px'){storeColor(borderLeftColorIdx,nodeId,borderColors);}
if(strings[borderRightWidthIdx]!=='0px'){storeColor(borderRightColorIdx,nodeId,borderColors);}
if(fontFamilyIdx!==-1){const fontFamily=strings[fontFamilyIdx];const fontFamilyInfo=fontInfo.get(fontFamily)||new Map();const sizeLabel='font-size';const weightLabel='font-weight';const lineHeightLabel='line-height';const size=fontFamilyInfo.get(sizeLabel)||new Map();const weight=fontFamilyInfo.get(weightLabel)||new Map();const lineHeight=fontFamilyInfo.get(lineHeightLabel)||new Map();if(fontSizeIdx!==-1){const fontSizeValue=strings[fontSizeIdx];const nodes=size.get(fontSizeValue)||[];nodes.push(nodeId);size.set(fontSizeValue,nodes);}
if(fontWeightIdx!==-1){const fontWeightValue=strings[fontWeightIdx];const nodes=weight.get(fontWeightValue)||[];nodes.push(nodeId);weight.set(fontWeightValue,nodes);}
if(lineHeightIdx!==-1){const lineHeightValue=strings[lineHeightIdx];const nodes=lineHeight.get(lineHeightValue)||[];nodes.push(nodeId);lineHeight.set(lineHeightValue,nodes);}
fontFamilyInfo.set(sizeLabel,size);fontFamilyInfo.set(weightLabel,weight);fontFamilyInfo.set(lineHeightLabel,lineHeight);fontInfo.set(fontFamily,fontFamilyInfo);}
CSSOverviewUnusedDeclarations.checkForUnusedPositionValues(unusedDeclarations,nodeId,strings,positionIdx,topIdx,leftIdx,rightIdx,bottomIdx);if(!isSVGNode(strings[nodeName])&&!isReplacedContent(strings[nodeName])){CSSOverviewUnusedDeclarations.checkForUnusedWidthAndHeightValues(unusedDeclarations,nodeId,strings,displayIdx,widthIdx,heightIdx);}
if(verticalAlignIdx!==-1&&!isTableElementWithDefaultStyles(strings[nodeName],strings[displayIdx])){CSSOverviewUnusedDeclarations.checkForInvalidVerticalAlignment(unusedDeclarations,nodeId,strings,displayIdx,verticalAlignIdx);}}}
return{backgroundColors,textColors,fillColors,borderColors,fontInfo,unusedDeclarations,elementCount};}
getComputedStyleForNode(nodeId){return this._cssAgent.getComputedStyleForNode(nodeId);}
async getMediaQueries(){const queries=await this._cssAgent.getMediaQueries();const queryMap=new Map();if(!queries){return queryMap;}
for(const query of queries){if(query.source==='linkedSheet'){continue;}
const entries=queryMap.get(query.text)||[];entries.push(query);queryMap.set(query.text,entries);}
return queryMap;}
async getGlobalStylesheetStats(){const expression=`(function() {
      let styleRules = 0;
      let inlineStyles = 0;
      let externalSheets = 0;
      const stats = {
        // Simple.
        type: new Set(),
        class: new Set(),
        id: new Set(),
        universal: new Set(),
        attribute: new Set(),

        // Non-simple.
        nonSimple: new Set()
      };

      for (const styleSheet of document.styleSheets) {
        if (styleSheet.href) {
          externalSheets++;
        } else {
          inlineStyles++;
        }

        // Attempting to grab rules can trigger a DOMException.
        // Try it and if it fails skip to the next stylesheet.
        let rules;
        try {
          rules = styleSheet.rules;
        } catch (err) {
          continue;
        }

        for (const rule of rules) {
          if ('selectorText' in rule) {
            styleRules++;

            // Each group that was used.
            for (const selectorGroup of rule.selectorText.split(',')) {
              // Each selector in the group.
              for (const selector of selectorGroup.split(\/[\\t\\n\\f\\r ]+\/g)) {
                if (selector.startsWith('.')) {
                  // Class.
                  stats.class.add(selector);
                } else if (selector.startsWith('#')) {
                  // Id.
                  stats.id.add(selector);
                } else if (selector.startsWith('*')) {
                  // Universal.
                  stats.universal.add(selector);
                } else if (selector.startsWith('[')) {
                  // Attribute.
                  stats.attribute.add(selector);
                } else {
                  // Type or non-simple selector.
                  const specialChars = \/[#\.:\\[\\]|\\+>~]\/;
                  if (specialChars.test(selector)) {
                    stats.nonSimple.add(selector);
                  } else {
                    stats.type.add(selector);
                  }
                }
              }
            }
          }
        }
      }

      return {
        styleRules,
        inlineStyles,
        externalSheets,
        stats: {
          // Simple.
          type: stats.type.size,
          class: stats.class.size,
          id: stats.id.size,
          universal: stats.universal.size,
          attribute: stats.attribute.size,

          // Non-simple.
          nonSimple: stats.nonSimple.size
        }
      }
    })()`;const{result}=await this._runtimeAgent.invoke_evaluate({expression,returnByValue:true});if(result.type!=='object'){return;}
return result.value;}}
SDKModel.SDKModel.register(CSSOverviewModel,SDKModel.Capability.DOM,false);var CSSOverviewModel$1=Object.freeze({__proto__:null,CSSOverviewModel:CSSOverviewModel});class CSSOverviewStartView extends Widget.Widget{constructor(controller){super();this.registerRequiredCSS('css_overview/cssOverviewStartView.css');this._controller=controller;this._render();}
_render(){const startButton=UIUtils.createTextButton(ls`Capture overview`,()=>this._controller.dispatchEventToListeners(Events.RequestOverviewStart),'',true);this.setDefaultFocusedElement(startButton);const fragment=Fragment.Fragment.build`
      <div class="vbox overview-start-view">
        <h1>${ls`CSS Overview`}</h1>
        <div>${startButton}</div>
      </div>
    `;this.contentElement.appendChild(fragment.element());this.contentElement.style.overflow='auto';}}
var CSSOverviewStartView$1=Object.freeze({__proto__:null,CSSOverviewStartView:CSSOverviewStartView});class CSSOverviewProcessingView extends Widget.Widget{constructor(controller){super();this.registerRequiredCSS('css_overview/cssOverviewProcessingView.css');this._formatter=new Intl.NumberFormat('en-US');this._controller=controller;this._render();}
_render(){const cancelButton=UIUtils.createTextButton(ls`Cancel`,()=>this._controller.dispatchEventToListeners(Events.RequestOverviewCancel),'',true);this.setDefaultFocusedElement(cancelButton);this.fragment=Fragment.Fragment.build`
      <div class="vbox overview-processing-view">
        <h1>Processing page</h1>
        <div>${cancelButton}</div>
      </div>
    `;this.contentElement.appendChild(this.fragment.element());this.contentElement.style.overflow='auto';}}
var CSSOverviewProcessingView$1=Object.freeze({__proto__:null,CSSOverviewProcessingView:CSSOverviewProcessingView});class CSSOverviewSidebarPanel extends Widget.VBox{static get ITEM_CLASS_NAME(){return'overview-sidebar-panel-item';}
static get SELECTED(){return'selected';}
constructor(){super(true);this.registerRequiredCSS('css_overview/cssOverviewSidebarPanel.css');this.contentElement.classList.add('overview-sidebar-panel');this.contentElement.addEventListener('click',this._onItemClick.bind(this));const clearResultsButton=new Toolbar.ToolbarButton(ls`Clear overview`,'largeicon-clear');clearResultsButton.addEventListener(Toolbar.ToolbarButton.Events.Click,this._reset,this);const toolbarElement=this.contentElement.createChild('div','overview-toolbar');const toolbar=new Toolbar.Toolbar('',toolbarElement);toolbar.appendToolbarItem(clearResultsButton);}
addItem(name,id){const item=this.contentElement.createChild('div',CSSOverviewSidebarPanel.ITEM_CLASS_NAME);item.textContent=name;item.dataset.id=id;}
_reset(){this.dispatchEventToListeners(SidebarEvents.Reset);}
_deselectAllItems(){const items=this.contentElement.querySelectorAll(`.${CSSOverviewSidebarPanel.ITEM_CLASS_NAME}`);for(const item of items){item.classList.remove(CSSOverviewSidebarPanel.SELECTED);}}
_onItemClick(event){const target=event.path[0];if(!target.classList.contains(CSSOverviewSidebarPanel.ITEM_CLASS_NAME)){return;}
const{id}=target.dataset;this.select(id);this.dispatchEventToListeners(SidebarEvents.ItemSelected,id);}
select(id){const target=this.contentElement.querySelector(`[data-id=${CSS.escape(id)}]`);if(!target){return;}
if(target.classList.contains(CSSOverviewSidebarPanel.SELECTED)){return;}
this._deselectAllItems();target.classList.add(CSSOverviewSidebarPanel.SELECTED);}}
const SidebarEvents={ItemSelected:Symbol('ItemSelected'),Reset:Symbol('Reset')};var CSSOverviewSidebarPanel$1=Object.freeze({__proto__:null,CSSOverviewSidebarPanel:CSSOverviewSidebarPanel,SidebarEvents:SidebarEvents});class CSSOverviewCompletedView extends Panel.PanelWithSidebar{constructor(controller,target){super('css_overview_completed_view');this.registerRequiredCSS('css_overview/cssOverviewCompletedView.css');this._controller=controller;this._formatter=new Intl.NumberFormat('en-US');this._mainContainer=new SplitWidget.SplitWidget(true,true);this._resultsContainer=new Widget.VBox();this._elementContainer=new DetailsView();this._elementContainer.addEventListener(TabbedPane.Events.TabClosed,evt=>{if(evt.data===0){this._mainContainer.setSidebarMinimized(true);}});this._mainContainer.registerRequiredCSS('css_overview/cssOverviewCompletedView.css');this._mainContainer.setMainWidget(this._resultsContainer);this._mainContainer.setSidebarWidget(this._elementContainer);this._mainContainer.setVertical(false);this._mainContainer.setSecondIsSidebar(true);this._mainContainer.setSidebarMinimized(true);this._sideBar=new CSSOverviewSidebarPanel();this.splitWidget().setSidebarWidget(this._sideBar);this.splitWidget().setMainWidget(this._mainContainer);this._cssModel=target.model(CSSModel.CSSModel);this._domModel=target.model(DOMModel.DOMModel);this._domAgent=target.domAgent();this._linkifier=new Linkifier.Linkifier(20,true);this._viewMap=new Map();this._sideBar.addItem(ls`Overview summary`,'summary');this._sideBar.addItem(ls`Colors`,'colors');this._sideBar.addItem(ls`Font info`,'font-info');this._sideBar.addItem(ls`Unused declarations`,'unused-declarations');this._sideBar.addItem(ls`Media queries`,'media-queries');this._sideBar.select('summary');this._sideBar.addEventListener(SidebarEvents.ItemSelected,this._sideBarItemSelected,this);this._sideBar.addEventListener(SidebarEvents.Reset,this._sideBarReset,this);this._controller.addEventListener(Events.Reset,this._reset,this);this._controller.addEventListener(Events.PopulateNodes,this._createElementsView,this);this._resultsContainer.element.addEventListener('click',this._onClick.bind(this));this._data=null;}
wasShown(){super.wasShown();}
_sideBarItemSelected(event){const section=this._fragment.$(event.data);if(!section){return;}
section.scrollIntoView();}
_sideBarReset(){this._controller.dispatchEventToListeners(Events.Reset);}
_reset(){this._resultsContainer.element.removeChildren();this._mainContainer.setSidebarMinimized(true);this._elementContainer.closeTabs();this._viewMap=new Map();}
_onClick(evt){const type=evt.target.dataset.type;if(!type){return;}
let payload;switch(type){case'color':{const color=evt.target.dataset.color;const section=evt.target.dataset.section;if(!color){return;}
let nodes;switch(section){case'text':nodes=this._data.textColors.get(color);break;case'background':nodes=this._data.backgroundColors.get(color);break;case'fill':nodes=this._data.fillColors.get(color);break;case'border':nodes=this._data.borderColors.get(color);break;}
if(!nodes){return;}
nodes=Array.from(nodes).map(nodeId=>({nodeId}));payload={type,color,nodes,section};break;}
case'unused-declarations':{const declaration=evt.target.dataset.declaration;const nodes=this._data.unusedDeclarations.get(declaration);if(!nodes){return;}
payload={type,declaration,nodes};break;}
case'media-queries':{const text=evt.target.dataset.text;const nodes=this._data.mediaQueries.get(text);if(!nodes){return;}
payload={type,text,nodes};break;}
case'font-info':{const value=evt.target.dataset.value;const[fontFamily,fontMetric]=evt.target.dataset.path.split('/');const nodesIds=this._data.fontInfo.get(fontFamily).get(fontMetric).get(value);if(!nodesIds){return;}
const nodes=nodesIds.map(nodeId=>({nodeId}));const name=`${value} (${fontFamily}, ${fontMetric})`;payload={type,name,nodes};break;}
default:return;}
evt.consume();this._controller.dispatchEventToListeners(Events.PopulateNodes,payload);this._mainContainer.setSidebarMinimized(false);}
_onMouseOver(evt){const node=evt.path.find(el=>el.dataset&&el.dataset.backendNodeId);if(!node){return;}
const backendNodeId=Number(node.dataset.backendNodeId);this._controller.dispatchEventToListeners(Events.RequestNodeHighlight,backendNodeId);}
async _render(data){if(!data||!('backgroundColors'in data)||!('textColors'in data)){return;}
this._data=data;const{elementCount,backgroundColors,textColors,fillColors,borderColors,globalStyleStats,mediaQueries,unusedDeclarations,fontInfo}=this._data;const sortedBackgroundColors=this._sortColorsByLuminance(backgroundColors);const sortedTextColors=this._sortColorsByLuminance(textColors);const sortedFillColors=this._sortColorsByLuminance(fillColors);const sortedBorderColors=this._sortColorsByLuminance(borderColors);this._fragment=Fragment.Fragment.build`
    <div class="vbox overview-completed-view">
      <div $="summary" class="results-section horizontally-padded summary">
        <h1>${ls`Overview summary`}</h1>

        <ul>
          <li>
            <div class="label">${ls`Elements`}</div>
            <div class="value">${this._formatter.format(elementCount)}</div>
          </li>
          <li>
            <div class="label">${ls`External stylesheets`}</div>
            <div class="value">${this._formatter.format(globalStyleStats.externalSheets)}</div>
          </li>
          <li>
            <div class="label">${ls`Inline style elements`}</div>
            <div class="value">${this._formatter.format(globalStyleStats.inlineStyles)}</div>
          </li>
          <li>
            <div class="label">${ls`Style rules`}</div>
            <div class="value">${this._formatter.format(globalStyleStats.styleRules)}</div>
          </li>
          <li>
            <div class="label">${ls`Media queries`}</div>
            <div class="value">${this._formatter.format(mediaQueries.size)}</div>
          </li>
          <li>
            <div class="label">${ls`Type selectors`}</div>
            <div class="value">${this._formatter.format(globalStyleStats.stats.type)}</div>
          </li>
          <li>
            <div class="label">${ls`ID selectors`}</div>
            <div class="value">${this._formatter.format(globalStyleStats.stats.id)}</div>
          </li>
          <li>
            <div class="label">${ls`Class selectors`}</div>
            <div class="value">${this._formatter.format(globalStyleStats.stats.class)}</div>
          </li>
          <li>
            <div class="label">${ls`Universal selectors`}</div>
            <div class="value">${this._formatter.format(globalStyleStats.stats.universal)}</div>
          </li>
          <li>
            <div class="label">${ls`Attribute selectors`}</div>
            <div class="value">${this._formatter.format(globalStyleStats.stats.attribute)}</div>
          </li>
          <li>
            <div class="label">${ls`Non-simple selectors`}</div>
            <div class="value">${this._formatter.format(globalStyleStats.stats.nonSimple)}</div>
          </li>
        </ul>
      </div>

      <div $="colors" class="results-section horizontally-padded colors">
        <h1>${ls`Colors`}</h1>
        <h2>${ls`Background colors:${sortedBackgroundColors.length}`}</h2>
        <ul>
          ${sortedBackgroundColors.map(this._colorsToFragment.bind(this, 'background'))}
        </ul>

        <h2>${ls`Text colors:${sortedTextColors.length}`}</h2>
        <ul>
          ${sortedTextColors.map(this._colorsToFragment.bind(this, 'text'))}
        </ul>

        <h2>${ls`Fill colors:${sortedFillColors.length}`}</h2>
        <ul>
          ${sortedFillColors.map(this._colorsToFragment.bind(this, 'fill'))}
        </ul>

        <h2>${ls`Border colors:${sortedBorderColors.length}`}</h2>
        <ul>
          ${sortedBorderColors.map(this._colorsToFragment.bind(this, 'border'))}
        </ul>
      </div>

      <div $="font-info" class="results-section font-info">
        <h1>${ls`Font info`}</h1>
        ${
        fontInfo.size > 0 ? this._fontInfoToFragment(fontInfo) :
                            Fragment.Fragment.build`<div>${ls`There are no fonts.`}</div>`}
      </div>

      <div $="unused-declarations" class="results-section unused-declarations">
        <h1>${ls`Unused declarations`}</h1>
        ${
        unusedDeclarations.size > 0 ?
            this._groupToFragment(unusedDeclarations, 'unused-declarations', 'declaration') :
            Fragment.Fragment.build`<div class="horizontally-padded">${ls`There are no unused declarations.`}</div>`}
      </div>

      <div $="media-queries" class="results-section media-queries">
        <h1>${ls`Media queries`}</h1>
        ${
        mediaQueries.size > 0 ?
            this._groupToFragment(mediaQueries, 'media-queries', 'text') :
            Fragment.Fragment.build`<div class="horizontally-padded">${ls`There are no media queries.`}</div>`}
      </div>
    </div>`;this._resultsContainer.element.appendChild(this._fragment.element());}
_createElementsView(evt){const{type,nodes}=evt.data;let id='';let tabTitle='';switch(type){case'color':{const{section,color}=evt.data;id=`${section}-${color}`;tabTitle=`${color.toUpperCase()} (${section})`;break;}
case'unused-declarations':{const{declaration}=evt.data;id=`${declaration}`;tabTitle=`${declaration}`;break;}
case'media-queries':{const{text}=evt.data;id=`${text}`;tabTitle=`${text}`;break;}
case'font-info':{const{name}=evt.data;id=`${name}`;tabTitle=`${name}`;break;}}
let view=this._viewMap.get(id);if(!view){view=new ElementDetailsView(this._controller,this._domModel,this._cssModel,this._linkifier);view.populateNodes(nodes);this._viewMap.set(id,view);}
this._elementContainer.appendTab(id,tabTitle,view,true);}
_fontInfoToFragment(fontInfo){const fonts=Array.from(fontInfo.entries());return Fragment.Fragment.build`
      ${fonts.map(([font, fontMetrics]) => {
      return Fragment.Fragment.build
      `<section class="font-family"><h2>${font}</h2>${this._fontMetricsToFragment(font,fontMetrics)}</section>`;
    })}
    `;}
_fontMetricsToFragment(font,fontMetrics){const fontMetricInfo=Array.from(fontMetrics.entries());return Fragment.Fragment.build`
      <div class="font-metric">
      ${fontMetricInfo.map(([label, values]) => {
      const sanitizedPath = `${font}/${label}`;
      return Fragment.Fragment.build`<div><h3>${label}</h3>${this._groupToFragment(values,'font-info','value',sanitizedPath)}</div>`;
    })}
      </div>`;}
_groupToFragment(items,type,dataLabel,path=''){const values=Array.from(items.entries()).sort((d1,d2)=>{const v1Nodes=d1[1];const v2Nodes=d2[1];return v2Nodes.length-v1Nodes.length;});const total=values.reduce((prev,curr)=>prev+curr[1].length,0);return Fragment.Fragment.build`<ul>
    ${values.map(([title, nodes]) => {
      const width = 100 * nodes.length / total;
      const itemLabel = nodes.length === 1 ? ls`occurrence` : ls`occurrences`;

      return Fragment.Fragment.build`<li><div class="title">${title}</div><button data-type="${type}"data-path="${path}"data-${dataLabel}="${title}"><div class="details">${ls`${nodes.length} ${itemLabel}`}</div><div class="bar-container"><div class="bar"style="width: ${width}%"></div></div></button></li>`;
    })}
    </ul>`;}
_colorsToFragment(section,color){const blockFragment=Fragment.Fragment.build`<li>
      <button data-type="color" data-color="${color}" data-section="${section}" class="block" $="color"></button>
      <div class="block-title">${color}</div>
    </li>`;const block=blockFragment.$('color');block.style.backgroundColor=color;const borderColor=Color.Color.parse(color);let[h,s,l]=borderColor.hsla();h=Math.round(h*360);s=Math.round(s*100);l=Math.round(l*100);l=Math.max(0,l-15);const borderString=`1px solid hsl(${h}, ${s}%, ${l}%)`;block.style.border=borderString;return blockFragment;}
_sortColorsByLuminance(srcColors){return Array.from(srcColors.keys()).sort((colA,colB)=>{const colorA=Color.Color.parse(colA);const colorB=Color.Color.parse(colB);return Color.Color.luminance(colorB.rgba())-Color.Color.luminance(colorA.rgba());});}
setOverviewData(data){this._render(data);}}
CSSOverviewCompletedView.pushedNodes=new Set();class DetailsView extends Widget.VBox{constructor(){super();this._tabbedPane=new TabbedPane.TabbedPane();this._tabbedPane.show(this.element);this._tabbedPane.addEventListener(TabbedPane.Events.TabClosed,()=>{this.dispatchEventToListeners(TabbedPane.Events.TabClosed,this._tabbedPane.tabIds().length);});}
appendTab(id,tabTitle,view,isCloseable){if(!this._tabbedPane.hasTab(id)){this._tabbedPane.appendTab(id,tabTitle,view,undefined,undefined,isCloseable);}
this._tabbedPane.selectTab(id);}
closeTabs(){this._tabbedPane.closeTabs(this._tabbedPane.tabIds());}}
class ElementDetailsView extends Widget.Widget{constructor(controller,domModel,cssModel,linkifier){super();this._controller=controller;this._domModel=domModel;this._cssModel=cssModel;this._linkifier=linkifier;this._elementGridColumns=[{id:'nodeId',title:ls`Element`,visible:false,sortable:true,hideable:true,weight:50},{id:'declaration',title:ls`Declaration`,visible:false,sortable:true,hideable:true,weight:50},{id:'sourceURL',title:ls`Source`,visible:true,sortable:false,hideable:true,weight:100}];this._elementGrid=new SortableDataGrid.SortableDataGrid({displayName:ls`CSS Overview Elements`,columns:this._elementGridColumns});this._elementGrid.element.classList.add('element-grid');this._elementGrid.element.addEventListener('mouseover',this._onMouseOver.bind(this));this._elementGrid.setStriped(true);this._elementGrid.addEventListener(DataGrid.Events.SortingChanged,this._sortMediaQueryDataGrid.bind(this));this.element.appendChild(this._elementGrid.element);}
_sortMediaQueryDataGrid(){const sortColumnId=this._elementGrid.sortColumnId();if(!sortColumnId){return;}
const comparator=SortableDataGrid.SortableDataGrid.StringComparator.bind(null,sortColumnId);this._elementGrid.sortNodes(comparator,!this._elementGrid.isSortOrderAscending());}
_onMouseOver(evt){const node=evt.path.find(el=>el.dataset&&el.dataset.backendNodeId);if(!node){return;}
const backendNodeId=Number(node.dataset.backendNodeId);this._controller.dispatchEventToListeners(Events.RequestNodeHighlight,backendNodeId);}
async populateNodes(data){this._elementGrid.rootNode().removeChildren();if(!data.length){return;}
const[firstItem]=data;const visibility={'nodeId':!!firstItem.nodeId,'declaration':!!firstItem.declaration,'sourceURL':!!firstItem.sourceURL};let relatedNodesMap;if(visibility.nodeId){const nodeIds=data.reduce((prev,curr)=>{if(CSSOverviewCompletedView.pushedNodes.has(curr.nodeId)){return prev;}
CSSOverviewCompletedView.pushedNodes.add(curr.nodeId);return prev.add(curr.nodeId);},new Set());relatedNodesMap=await this._domModel.pushNodesByBackendIdsToFrontend(nodeIds);}
for(const item of data){if(visibility.nodeId){const frontendNode=relatedNodesMap.get(item.nodeId);if(!frontendNode){continue;}
item.node=frontendNode;}
const node=new ElementNode(this._elementGrid,item,this._linkifier,this._cssModel);node.selectable=false;this._elementGrid.insertChild(node);}
this._elementGrid.setColumnsVisiblity(visibility);this._elementGrid.renderInline();this._elementGrid.wasShown();}}
class ElementNode extends SortableDataGrid.SortableDataGridNode{constructor(dataGrid,data,linkifier,cssModel){super(dataGrid,data.hasChildren);this.data=data;this._linkifier=linkifier;this._cssModel=cssModel;}
createCell(columnId){if(columnId==='nodeId'){const cell=this.createTD(columnId);cell.textContent='...';Linkifier$1.Linkifier.linkify(this.data.node).then(link=>{cell.textContent='';link.dataset.backendNodeId=this.data.node.backendNodeId();cell.appendChild(link);});return cell;}
if(columnId==='sourceURL'){const cell=this.createTD(columnId);if(this.data.range){const link=this._linkifyRuleLocation(this._cssModel,this._linkifier,this.data.styleSheetId,TextRange.TextRange.fromObject(this.data.range));if(link.textContent!==''){cell.appendChild(link);}else{cell.textContent='(unable to link)';}}else{cell.textContent='(unable to link to inlined styles)';}
return cell;}
return super.createCell(columnId);}
_linkifyRuleLocation(cssModel,linkifier,styleSheetId,ruleLocation){const styleSheetHeader=cssModel.styleSheetHeaderForId(styleSheetId);const lineNumber=styleSheetHeader.lineNumberInSource(ruleLocation.startLine);const columnNumber=styleSheetHeader.columnNumberInSource(ruleLocation.startLine,ruleLocation.startColumn);const matchingSelectorLocation=new CSSModel.CSSLocation(styleSheetHeader,lineNumber,columnNumber);return linkifier.linkifyCSSLocation(matchingSelectorLocation);}}
var CSSOverviewCompletedView$1=Object.freeze({__proto__:null,CSSOverviewCompletedView:CSSOverviewCompletedView,DetailsView:DetailsView,ElementDetailsView:ElementDetailsView,ElementNode:ElementNode});class CSSOverviewPanel extends Panel.Panel{constructor(){super('css_overview');this.registerRequiredCSS('css_overview/cssOverview.css');this.element.classList.add('css-overview-panel');const[model]=SDKModel.TargetManager.instance().models(CSSOverviewModel);this._model=model;this._controller=new OverviewController();this._startView=new CSSOverviewStartView(this._controller);this._processingView=new CSSOverviewProcessingView(this._controller);this._completedView=new CSSOverviewCompletedView(this._controller,model.target());this._controller.addEventListener(Events.RequestOverviewStart,event=>{this._startOverview();},this);this._controller.addEventListener(Events.RequestOverviewCancel,this._cancelOverview,this);this._controller.addEventListener(Events.OverviewCompleted,this._overviewCompleted,this);this._controller.addEventListener(Events.Reset,this._reset,this);this._controller.addEventListener(Events.RequestNodeHighlight,this._requestNodeHighlight,this);this._reset();}
_reset(){this._backgroundColors=new Map();this._textColors=new Map();this._fillColors=new Map();this._borderColors=new Map();this._fontInfo=new Map();this._mediaQueries=[];this._unusedDeclarations=new Map();this._elementCount=0;this._cancelled=false;this._globalStyleStats={styleRules:0,inlineStyles:0,externalSheets:0,stats:{type:0,class:0,id:0,universal:0,attribute:0,nonSimple:0}};this._renderInitialView();}
_requestNodeHighlight(evt){this._model.highlightNode(evt.data);}
_renderInitialView(){this._processingView.hideWidget();this._completedView.hideWidget();this._startView.show(this.contentElement);}
_renderOverviewStartedView(){this._startView.hideWidget();this._completedView.hideWidget();this._processingView.show(this.contentElement);}
_renderOverviewCompletedView(){this._startView.hideWidget();this._processingView.hideWidget();this._completedView.show(this.contentElement);this._completedView.setOverviewData({backgroundColors:this._backgroundColors,textColors:this._textColors,fillColors:this._fillColors,borderColors:this._borderColors,globalStyleStats:this._globalStyleStats,fontInfo:this._fontInfo,elementCount:this._elementCount,mediaQueries:this._mediaQueries,unusedDeclarations:this._unusedDeclarations,});}
async _startOverview(){this._renderOverviewStartedView();const[globalStyleStats,{elementCount,backgroundColors,textColors,fillColors,borderColors,fontInfo,unusedDeclarations},mediaQueries]=await Promise.all([this._model.getGlobalStylesheetStats(),this._model.getNodeStyleStats(),this._model.getMediaQueries()]);if(elementCount){this._elementCount=elementCount;}
if(globalStyleStats){this._globalStyleStats=globalStyleStats;}
if(mediaQueries){this._mediaQueries=mediaQueries;}
if(backgroundColors){this._backgroundColors=backgroundColors;}
if(textColors){this._textColors=textColors;}
if(fillColors){this._fillColors=fillColors;}
if(borderColors){this._borderColors=borderColors;}
if(fontInfo){this._fontInfo=fontInfo;}
if(unusedDeclarations){this._unusedDeclarations=unusedDeclarations;}
this._controller.dispatchEventToListeners(Events.OverviewCompleted);}
_getStyleValue(styles,name){const item=styles.filter(style=>style.name===name);if(!item.length){return;}
return item[0].value;}
_cancelOverview(){this._cancelled=true;}
_overviewCompleted(){this._renderOverviewCompletedView();}}
var CSSOverviewPanel$1=Object.freeze({__proto__:null,CSSOverviewPanel:CSSOverviewPanel});export{CSSOverviewCompletedView$1 as CSSOverviewCompletedView,CSSOverviewController,CSSOverviewModel$1 as CSSOverviewModel,CSSOverviewPanel$1 as CSSOverviewPanel,CSSOverviewProcessingView$1 as CSSOverviewProcessingView,CSSOverviewSidebarPanel$1 as CSSOverviewSidebarPanel,CSSOverviewStartView$1 as CSSOverviewStartView,CSSOverviewUnusedDeclarations$1 as CSSOverviewUnusedDeclarations};