import{render as e,html as t,nothing as o,Directives as r,directive as i,AttributePart as n}from"../../third_party/lit-html/lit-html.js";import*as s from"../../common/common.js";import{ls as l,UIString as a}from"../../common/common.js";import{SetCSSProperty as c}from"../../component_helpers/component_helpers.js";import{Platform as d}from"../../host/host.js";import{assertNever as h,KeyboardUtilities as u,NumberUtilities as p}from"../../platform/platform.js";import{RenderCoordinator as m}from"../../render_coordinator/render_coordinator.js";import{ContextMenu as f,Widget as w}from"../ui.js";import{ResourceUtils as g}from"../../bindings/bindings.js";class b extends HTMLElement{constructor(){super(...arguments),this.shadow=this.attachShadow({mode:"open"}),this.clickHandler=()=>{},this.counters=[]}set data(e){this.counters=e.counters,this.clickHandler=e.clickHandler,this.render()}setCounts(e){if(e.length!==this.counters.length)throw new Error(`Wrong number of texts, expected ${this.counters.length} but got ${e.length}`);for(let t=0;t<e.length;++t)this.counters[t].count=e[t];this.render()}onClickHandler(e){e.preventDefault(),this.clickHandler()}render(){return e(t`
      <style>
        :host {
          white-space: normal;
        }

        .counter-button {
          cursor: pointer;
          background-color: var(--toolbar-bg-color);
          border: 1px solid var(--divider-color);
          border-radius: 2px;
          color: var(--tab-selected-fg-color);
          margin-right: 2px;
          display: inline-flex;
          align-items: center;
        }

        .counter-button:hover,
        .counter-button:focus-visible {
          background-color: var(--toolbar-hover-bg-color);
        }

        .counter-button-title {
          margin-left: 0.5ex;
        }

        .status-icon {
          margin-left: 1ex;
        }

        .status-icon:first-child {
          margin-left: inherit;
        }
      </style>
      <button class="counter-button" @click=${this.onClickHandler}>
      ${this.counters.filter((e=>Boolean(e.count))).map((e=>t`
      <devtools-icon class="status-icon"
      .data=${{iconName:e.iconName,color:e.iconColor||"",width:"1.5ex",height:"1.5ex"}}>
      </devtools-icon>
      <span class="counter-button-title">${e.count}</span>
      </button>`))}
    `,this.shadow,{eventContext:this})}}customElements.define("counter-button",b);var v=Object.freeze({__proto__:null,CounterButton:b});const x=e=>t`${e}`;var y=Object.freeze({__proto__:null,primitiveRenderer:x,codeBlockRenderer:e=>{if(!e)return o;const r=String(e),i=r.length>13?r.substring(0,10)+"...":r;return t`<code>${i}</code>`}});function C(e,t){const o=e.cells.find((e=>e.columnId===t));if(void 0===o)throw new Error(`Found a row that was missing an entry for column ${t}.`);return o}function k(e){return e.renderer?e.renderer(e.value):x(e.value)}function S(e,t){const o=e.filter((e=>e.visible)).reduce(((e,t)=>e+t.widthWeighting),0),r=e.find((e=>e.id===t));if(!r)throw new Error("Could not find column with ID "+t);if(r.widthWeighting<1)throw new Error(`Error with column ${t}: width weightings must be >= 1.`);return r.visible?Math.round(r.widthWeighting/o*100):0}function R(e){const{key:t,currentFocusedCell:o,columns:r,rows:i}=e,[n,s]=o;switch(t){case"ArrowLeft":{if(n===r.findIndex((e=>e.visible)))return[n,s];let e=n;for(let t=e-1;t>=0;t--){if(r[t].visible){e=t;break}}return[e,s]}case"ArrowRight":{let e=n;for(let t=e+1;t<r.length;t++){if(r[t].visible){e=t;break}}return[e,s]}case"ArrowUp":{const e=r.some((e=>!0===e.sortable))?0:1;if(s===e)return[n,s];let t=s;for(let o=s-1;o>=e;o--){if(0===o){t=0;break}if(!i[o-1].hidden){t=o;break}}return[n,t]}case"ArrowDown":{if(0===s){const e=i.findIndex((e=>!e.hidden));return e>-1?[n,e+1]:[n,s]}let e=s;for(let t=e+1;t<i.length+1;t++){if(!i[t-1].hidden){e=t;break}}return[n,e]}default:return h(t,"Unknown arrow key: "+t)}}const E=e=>{const{columns:t,rows:o}=e,r=t.some((e=>!0===e.sortable))?0:o.findIndex((e=>!e.hidden))+1;return[t.findIndex((e=>e.visible)),r]};class M extends Event{constructor(e){super("context-menu-column-sort-click"),this.data={column:e}}}class $ extends Event{constructor(){super("context-menu-header-reset-click")}}var T=Object.freeze({__proto__:null,getRowEntryForColumnId:C,renderCellValue:k,calculateColumnWidthPercentageFromWeighting:S,handleArrowKeyNavigation:R,calculateFirstFocusableCell:E,ContextMenuColumnSortClickEvent:M,ContextMenuHeaderResetClickEvent:$});function N(e,t){const o=!t.visible,r=e.data.columns.map((e=>(e===t&&(e.visible=o),e)));e.data={...e.data,columns:r}}function I(e,t){const{columns:o}=e.data;for(const r of o)r.hideable&&t.defaultSection().appendCheckboxItem(r.title,(()=>{N(e,r)}),r.visible)}function z(e,t){const o=e.data.columns.filter((e=>!0===e.sortable));if(o.length>0)for(const r of o)t.defaultSection().appendItem(r.title,(()=>{e.dispatchEvent(new M(r))}))}const{ls:L}=s,_=m.RenderCoordinator.instance();class H extends Event{constructor(e,t){super("column-header-click"),this.data={column:e,columnIndex:t}}}class O extends Event{constructor(e){super("new-user-filter-text",{composed:!0}),this.data={filterText:e}}}class A extends Event{constructor(e,t){super("cell-focused",{composed:!0}),this.data={cell:e,row:t}}}const D=new Set([" ","Enter"]);class F extends HTMLElement{constructor(){super(...arguments),this.shadow=this.attachShadow({mode:"open"}),this.columns=[],this.rows=[],this.sortState=null,this.scheduledRender=!1,this.contextMenus=void 0,this.currentResize=null,this.rowIndexMap=new WeakMap,this.resizeObserver=new ResizeObserver((()=>{this.alignScrollHandlers()})),this.boundOnResizePointerUp=this.onResizePointerUp.bind(this),this.boundOnResizePointerMove=this.onResizePointerMove.bind(this),this.boundOnResizePointerDown=this.onResizePointerDown.bind(this),this.focusableCell=[0,1],this.hasRenderedAtLeastOnce=!1,this.userHasFocused=!1,this.userHasScrolled=!1,this.enqueuedRender=!1}connectedCallback(){c.set(this,"--table-row-height","18px")}get data(){return{columns:this.columns,rows:this.rows,activeSort:this.sortState,contextMenus:this.contextMenus}}set data(e){if(this.columns=e.columns,this.rows=e.rows,this.rows.forEach(((e,t)=>{this.rowIndexMap.set(e,t)})),this.sortState=e.activeSort,this.contextMenus=e.contextMenus,this.hasRenderedAtLeastOnce||(this.focusableCell=E({columns:this.columns,rows:this.rows})),this.hasRenderedAtLeastOnce){const[e,t]=this.focusableCell,o=e>this.columns.length,r=t>this.rows.length;(o||r)&&(this.focusableCell=[o?this.columns.length:e,r?this.rows.length:t])}this.render()}scrollToBottomIfRequired(){if(!1===this.hasRenderedAtLeastOnce||this.userHasFocused||this.userHasScrolled)return;const e=this.getCurrentlyFocusableCell();e&&e===this.shadow.activeElement||_.read((()=>{const e=this.shadow.querySelector(".wrapping-container");if(!e)return;const t=e.scrollHeight;_.scroll((()=>{e.scrollTo(0,t)}))}))}engageResizeObserver(){this.hasRenderedAtLeastOnce||this.resizeObserver.observe(this.shadow.host)}getCurrentlyFocusableCell(){const[e,t]=this.focusableCell;return this.shadow.querySelector(`[data-row-index="${t}"][data-col-index="${e}"]`)}focusCell([e,t]){this.userHasFocused=!0;const[o,r]=this.focusableCell;o===e&&r===t||(this.focusableCell=[e,t],this.render());const i=this.getCurrentlyFocusableCell();i&&_.write((()=>{i.focus()}))}onTableKeyDown(e){const t=e.key;if(D.has(t)){const e=this.getCurrentlyFocusableCell(),[t,o]=this.focusableCell,r=this.columns[t];e&&0===o&&r&&r.sortable&&this.onColumnHeaderClick(r,t)}if(!u.keyIsArrowKey(t))return;const o=R({key:t,currentFocusedCell:this.focusableCell,columns:this.columns,rows:this.rows});e.preventDefault(),this.focusCell(o)}onColumnHeaderClick(e,t){this.dispatchEvent(new H(e,t))}ariaSortForHeader(e){return!e.sortable||this.sortState&&this.sortState.columnId===e.id?this.sortState&&this.sortState.columnId===e.id?"ASC"===this.sortState.direction?"ascending":"descending":void 0:"none"}renderEmptyFillerRow(){const e=this.columns.map(((e,i)=>{if(!e.visible)return o;const n=r.classMap({firstVisibleColumn:0===i});return t`<td tabindex="-1" class=${n} data-filler-row-column-index=${i}></td>`}));return t`<tr tabindex="-1" class="filler-row padding-row">${e}</tr>`}cleanUpAfterResizeColumnComplete(){this.currentResize&&(this.currentResize.documentForCursorChange.body.style.cursor=this.currentResize.cursorToRestore,this.currentResize=null,this.alignScrollHandlers())}onResizePointerDown(e){if(1!==e.buttons||d.isMac()&&e.ctrlKey)return;e.preventDefault();const t=e.target;if(!t)return;const o=t.dataset.columnIndex;if(!o)return;const r=globalThis.parseInt(o,10),i=this.columns.findIndex(((e,t)=>t>r&&!0===e.visible)),n=this.shadow.querySelector(`td[data-filler-row-column-index="${r}"]`),s=this.shadow.querySelector(`td[data-filler-row-column-index="${i}"]`);if(!n||!s)return;const l=this.shadow.querySelector(`col[data-col-column-index="${r}"]`),a=this.shadow.querySelector(`col[data-col-column-index="${i}"]`);if(!l||!a)return;const c=e.target.ownerDocument;c&&(this.currentResize={leftCellCol:l,rightCellCol:a,leftCellColInitialPercentageWidth:globalThis.parseInt(l.style.width,10),rightCellColInitialPercentageWidth:globalThis.parseInt(a.style.width,10),initialLeftCellWidth:n.clientWidth,initialRightCellWidth:s.clientWidth,initialMouseX:e.x,documentForCursorChange:c,cursorToRestore:t.style.cursor},c.body.style.cursor="col-resize",t.setPointerCapture(e.pointerId),t.addEventListener("pointermove",this.boundOnResizePointerMove))}onResizePointerMove(e){if(e.preventDefault(),!this.currentResize)return;const t=this.currentResize.leftCellColInitialPercentageWidth+this.currentResize.rightCellColInitialPercentageWidth-10,o=e.x-this.currentResize.initialMouseX,r=Math.abs(o)/(this.currentResize.initialLeftCellWidth+this.currentResize.initialRightCellWidth)*100;let i,n;o>0?(i=p.clamp(this.currentResize.leftCellColInitialPercentageWidth+r,10,t),n=p.clamp(this.currentResize.rightCellColInitialPercentageWidth-r,10,t)):o<0&&(i=p.clamp(this.currentResize.leftCellColInitialPercentageWidth-r,10,t),n=p.clamp(this.currentResize.rightCellColInitialPercentageWidth+r,10,t)),i&&n&&(this.currentResize.leftCellCol.style.width=i.toFixed(2)+"%",this.currentResize.rightCellCol.style.width=n.toFixed(2)+"%")}onResizePointerUp(e){e.preventDefault();const t=e.target;t&&(t.releasePointerCapture(e.pointerId),t.removeEventListener("pointermove",this.boundOnResizePointerMove),this.cleanUpAfterResizeColumnComplete())}renderResizeForCell(e,r){const[i]=r;return i!==this.getIndexOfLastVisibleColumn()&&e.visible?t`<span class="cell-resize-handle"
     @pointerdown=${this.boundOnResizePointerDown}
     @pointerup=${this.boundOnResizePointerUp}
     data-column-index=${i}
    ></span>`:o}getIndexOfLastVisibleColumn(){let e=this.columns.length-1;for(;e>-1;e--){if(this.columns[e].visible)break}return e}onHeaderContextMenu(e){if(2!==e.button)return;const t=new f.ContextMenu(e);I(this,t);z(this,t.defaultSection().appendSubMenuItem(L`Sort By`)),t.defaultSection().appendItem(L`Reset Columns`,(()=>{this.dispatchEvent(new $)})),this.contextMenus&&this.contextMenus.headerRow&&this.contextMenus.headerRow(t,this.columns),t.show()}onBodyRowContextMenu(e){if(2!==e.button)return;if(!(e.target&&e.target instanceof HTMLElement))return;const t=e.target.dataset.rowIndex;if(!t)return;const o=parseInt(t,10),r=this.rows[o-1],i=new f.ContextMenu(e);z(this,i.defaultSection().appendSubMenuItem(L`Sort By`));const n=i.defaultSection().appendSubMenuItem(L`Header Options`);I(this,n),n.defaultSection().appendItem(L`Reset Columns`,(()=>{this.dispatchEvent(new $)})),this.contextMenus&&this.contextMenus.bodyRow&&this.contextMenus.bodyRow(i,this.columns,r),i.show()}onScroll(){this.render()}onWheel(){this.userHasScrolled=!0}alignScrollHandlers(){return _.read((()=>{const e=this.shadow.querySelectorAll("th:not(.hidden)"),t=this.shadow.querySelectorAll(".cell-resize-handle");this.shadow.querySelector("table")&&e.forEach((async(e,o)=>{const{right:r}=e.getBoundingClientRect();t[o]&&_.write((()=>{t[o].style.left=r-40+"px"}))}))}))}calculateTopAndBottomRowIndexes(){return _.read((()=>{const e=this.shadow.querySelector(".wrapping-container");let t=0,o=window.innerHeight;e&&(t=e.scrollTop,o=e.clientHeight);let r=Math.floor((t-180)/18),i=Math.ceil((t+o+180)/18);return r=Math.max(0,r),i=Math.min(this.rows.length,i),{topVisibleRow:r,bottomVisibleRow:i}}))}render(){this.scheduledRender?this.enqueuedRender=!0:(this.scheduledRender=!0,_.read((async()=>{const{topVisibleRow:i,bottomVisibleRow:n}=await this.calculateTopAndBottomRowIndexes(),s=this.rows.filter(((e,t)=>t>=i&&t<=n)),l=this.columns.findIndex((e=>e.visible)),a=this.columns.some((e=>!0===e.sortable));await _.write((()=>{e(t`
        <style>
          :host {
            --table-divider-color: var(--color-details-hairline);
            --toolbar-bg-color: var(--color-background-elevation-1);
            --selected-row-color: var(--color-background-elevation-1);

            height: 100%;
            display: block;
            position: relative;
          }
          /* Ensure that vertically we don't overflow */
          .wrapping-container {
            overflow-y: scroll;
            /* Use max-height instead of height to ensure that the
              table does not use more space than necessary. */
            height: 100%;
          }

          table {
            border-spacing: 0;
            width: 100%;
            height: 100%;
            /* To make sure that we properly hide overflowing text
              when horizontal space is too narrow. */
            table-layout: fixed;
          }

          tr {
            outline: none;
          }

          tbody tr {
            background-color: var(--color-background);
          }

          tbody tr.selected {
            background-color: var(--selected-row-color); /* stylelint-disable-line plugin/use_theme_colors */
            /* See: crbug.com/1152736 for color variable migration. */
          }

          td,
          th {
            padding: 1px 4px;
            /* Divider between each cell, except the first one (see below) */
            border-left: 1px solid var(--table-divider-color); /* stylelint-disable-line plugin/use_theme_colors */
            /*See: crbug.com/1152736 for color variable migration.*/
            color: var(--color-text-primary);
            line-height: var(--table-row-height);
            height: var(--table-row-height);
            user-select: text;
            /* Ensure that text properly cuts off if horizontal space is too narrow */
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
          }

          .cell-resize-handle {
            top: 0;
            height: 100%;
            z-index: 3;
            width: 20px;
            cursor: col-resize;
            position: absolute;
          }
          /* There is no divider before the first cell */
          td.firstVisibleColumn,
          th.firstVisibleColumn {
            border-left: none;
          }

          th {
            font-weight: normal;
            text-align: left;
            border-bottom: 1px solid var(--table-divider-color); /* stylelint-disable-line plugin/use_theme_colors */
            /*See: crbug.com/1152736 for color variable migration.*/
            position: sticky;
            top: 0;
            z-index: 2;
            background-color: var(--toolbar-bg-color);
          }

          .hidden {
            display: none;
          }

          .filler-row td {
            /* By making the filler row cells 100% they take up any extra height,
            * leaving the cells with content to be the regular height, and the
            * final filler row to be as high as it needs to be to fill the empty
            * space.
            */
            height: 100%;
            pointer-events: none;
          }

          [aria-sort]:hover {
            cursor: pointer;
          }

          [aria-sort="descending"]::after {
            content: " ";
            border-left: 0.3em solid transparent;
            border-right: 0.3em solid transparent;
            border-top: 0.3em solid #000; /* stylelint-disable-line plugin/use_theme_colors */
            /*See: crbug.com/1152736 for color variable migration.*/
            position: absolute;
            right: 0.5em;
            top: 0.6em;
          }

          [aria-sort="ascending"]::after {
            content: " ";
            border-bottom: 0.3em solid #000; /* stylelint-disable-line plugin/use_theme_colors */
            /*See: crbug.com/1152736 for color variable migration.*/
            border-left: 0.3em solid transparent;
            border-right: 0.3em solid transparent;
            position: absolute;
            right: 0.5em;
            top: 0.6em;
          }
        </style>
        ${this.columns.map(((e,t)=>this.renderResizeForCell(e,[t,0])))}
        <div class="wrapping-container" @scroll=${this.onScroll} @wheel=${this.onWheel}>
          <table
            aria-rowcount=${this.rows.length}
            aria-colcount=${this.columns.length}
            @keydown=${this.onTableKeyDown}
          >
            <colgroup>
              ${this.columns.map(((e,r)=>{const i=`width: ${S(this.columns,e.id)}%`;return e.visible?t`<col style=${i} data-col-column-index=${r}>`:o}))}
            </colgroup>
            <thead>
              <tr @contextmenu=${this.onHeaderContextMenu}>
                ${this.columns.map(((e,o)=>{const i=r.classMap({hidden:!e.visible,firstVisibleColumn:o===l}),n=a&&o===this.focusableCell[0]&&0===this.focusableCell[1];return t`<th class=${i}
                    data-grid-header-cell=${e.id}
                    @click=${()=>{this.focusCell([o,0]),this.onColumnHeaderClick(e,o)}}
                    title=${e.title}
                    aria-sort=${r.ifDefined(this.ariaSortForHeader(e))}
                    aria-colindex=${o+1}
                    data-row-index='0'
                    data-col-index=${o}
                    tabindex=${r.ifDefined(a?n?"0":"-1":void 0)}
                  >${e.title}</th>`}))}
              </tr>
            </thead>
            <tbody>
              <tr class="filler-row-top padding-row" style=${r.styleMap({height:18*i+"px"})}></tr>
              ${r.repeat(s,(e=>this.rowIndexMap.get(e)),(e=>{const o=this.rowIndexMap.get(e);if(void 0===o)throw new Error("Trying to render a row that has no index in the rowIndexMap");const i=this.getCurrentlyFocusableCell(),[,n]=this.focusableCell,s=o+1,a=!!i&&(i===this.shadow.activeElement&&s===n),c=r.classMap({selected:a,hidden:!0===e.hidden});return t`
                  <tr
                    aria-rowindex=${o+1}
                    class=${c}
                    @contextmenu=${this.onBodyRowContextMenu}
                  >${this.columns.map(((o,i)=>{const n=C(e,o.id),a=r.classMap({hidden:!o.visible,firstVisibleColumn:i===l}),c=i===this.focusableCell[0]&&s===this.focusableCell[1],d=o.visible?k(n):null;return t`<td
                      class=${a}
                      tabindex=${c?"0":"-1"}
                      aria-colindex=${i+1}
                      title=${n.title||String(n.value).substr(0,20)}
                      data-row-index=${s}
                      data-col-index=${i}
                      data-grid-value-cell-for-column=${o.id}
                      @focus=${()=>{this.dispatchEvent(new A(n,e))}}
                      @click=${()=>{this.focusCell([i,s])}}
                    >${d}</td>`}))}
                `}))}
              ${this.renderEmptyFillerRow()}
              <tr class="filler-row-bottom padding-row" style=${r.styleMap({height:18*(this.rows.length-n)+"px"})}></tr>
            </tbody>
          </table>
        </div>
        `,this.shadow,{eventContext:this})}));const c=this.focusableCell[1];this.userHasFocused&&c>0&&this.focusCell(this.focusableCell),this.scrollToBottomIfRequired(),this.engageResizeObserver(),this.scheduledRender=!1,this.hasRenderedAtLeastOnce=!0,this.enqueuedRender&&(this.enqueuedRender=!1,this.render())})))}}customElements.define("devtools-data-grid",F);var P=Object.freeze({__proto__:null,ColumnHeaderClickEvent:H,NewUserFilterTextEvent:O,BodyCellFocusedEvent:A,DataGrid:F});class W extends HTMLElement{constructor(){super(...arguments),this.shadow=this.attachShadow({mode:"open"}),this.hasRenderedAtLeastOnce=!1,this.columns=[],this.rows=[],this.contextMenus=void 0,this.originalColumns=[],this.originalRows=[],this.sortState=null,this.filters=[]}get data(){return{columns:this.originalColumns,rows:this.originalRows,filters:this.filters,contextMenus:this.contextMenus}}set data(e){this.originalColumns=e.columns,this.originalRows=e.rows,this.contextMenus=e.contextMenus,this.filters=e.filters||[],this.contextMenus=e.contextMenus,this.columns=[...this.originalColumns],this.rows=this.cloneAndFilterRows(e.rows,this.filters),!this.hasRenderedAtLeastOnce&&e.initialSort&&(this.sortState=e.initialSort),this.sortState&&this.sortRows(this.sortState),this.render()}testRowWithFilter(e,t){let o=!1;const{key:r,text:i,negative:n,regex:s}=t;let l;if(r){const t=C(e,r);l=JSON.stringify(t.value).toLowerCase()}else l=JSON.stringify(e.cells.map((e=>e.value))).toLowerCase();return s?o=s.test(l):i&&(o=l.includes(i.toLowerCase())),n?!o:o}cloneAndFilterRows(e,t){return 0===t.length?[...e]:e.map((e=>{let o=!0;for(const r of t){if(!this.testRowWithFilter(e,r)){o=!1;break}}return{...e,hidden:!o}}))}sortRows(e){const{columnId:t,direction:o}=e;this.rows.sort(((e,r)=>{const i=C(e,t),n=C(r,t),s="number"==typeof i.value?i.value:String(i.value).toUpperCase(),l="number"==typeof n.value?n.value:String(n.value).toUpperCase();return s<l?"ASC"===o?-1:1:s>l?"ASC"===o?1:-1:0})),this.render()}onColumnHeaderClick(e){const{column:t}=e.data;this.applySortOnColumn(t)}applySortOnColumn(e){if(this.sortState&&this.sortState.columnId===e.id){const{columnId:e,direction:t}=this.sortState;this.sortState="DESC"===t?null:{columnId:e,direction:"DESC"}}else this.sortState={columnId:e.id,direction:"ASC"};this.sortState?this.sortRows(this.sortState):(this.rows=[...this.originalRows],this.render())}onContextMenuColumnSortClick(e){this.applySortOnColumn(e.data.column)}onContextMenuHeaderResetClick(){this.sortState=null,this.rows=[...this.originalRows],this.render()}render(){e(t`
      <style>
        :host {
          display: block;
          height: 100%;
          overflow: hidden;
        }
      </style>
      <devtools-data-grid .data=${{columns:this.columns,rows:this.rows,activeSort:this.sortState,contextMenus:this.contextMenus}}
        @column-header-click=${this.onColumnHeaderClick}
        @context-menu-column-sort-click=${this.onContextMenuColumnSortClick}
        @context-menu-header-reset-click=${this.onContextMenuHeaderResetClick}
     ></devtools-data-grid>
    `,this.shadow,{eventContext:this}),this.hasRenderedAtLeastOnce=!0}}customElements.define("devtools-data-grid-controller",W);var j=Object.freeze({__proto__:null,DataGridController:W});class q extends w.VBox{constructor(e){super(!0,!0),this.dataGrid=new W,this.dataGrid.data=e,this.contentElement.appendChild(this.dataGrid)}data(){return this.dataGrid.data}update(e){this.dataGrid.data=e}}var B=Object.freeze({__proto__:null,DataGridControllerIntegrator:q});const U=e=>void 0!==e;class K extends HTMLElement{constructor(){super(...arguments),this.shadow=this.attachShadow({mode:"open"}),this.iconPath="",this.color="rgb(110 110 110)",this.width="100%",this.height="100%"}set data(e){const{width:t,height:o}=e;this.color=e.color,this.width=U(t)?t:U(o)?o:this.width,this.height=U(o)?o:U(t)?t:this.height,this.iconPath="iconPath"in e?e.iconPath:`Images/${e.iconName}.svg`,"iconName"in e&&(this.iconName=e.iconName),this.render()}get data(){const e={color:this.color,width:this.width,height:this.height};return this.iconName?{...e,iconName:this.iconName}:{...e,iconPath:this.iconPath}}getStyles(){const{iconPath:e,width:t,height:o,color:r}=this,i={width:t,height:o,display:"block"};return r?{...i,webkitMaskImage:`url(${e})`,webkitMaskPosition:"center",webkitMaskRepeat:"no-repeat",webkitMaskSize:"100%",backgroundColor:`var(--icon-color, ${r})`}:{...i,backgroundImage:`url(${e})`,backgroundPosition:"center",backgroundRepeat:"no-repeat",backgroundSize:"100%"}}render(){e(t`
      <style>
        :host {
          display: inline-block;
          white-space: nowrap;
        }
      </style>
      <div class="icon-basic" style=${r.styleMap(this.getStyles())}></div>
    `,this.shadow)}}customElements.get("devtools-icon")||customElements.define("devtools-icon",K);var V=Object.freeze({__proto__:null,Icon:K});class G extends Event{constructor(e){super("linkifier-activated",{bubbles:!0,composed:!0}),this.data=e}}class J extends HTMLElement{constructor(){super(...arguments),this.shadow=this.attachShadow({mode:"open"}),this.url=""}set data(e){this.url=e.url,this.lineNumber=e.lineNumber,this.columnNumber=e.columnNumber,this.render()}onLinkActivation(e){e.preventDefault();const t=new G({url:this.url,lineNumber:this.lineNumber,columnNumber:this.columnNumber});this.dispatchEvent(t)}render(){if(!this.url)throw new Error("Cannot construct a Linkifier without providing a valid string URL.");return e(t`
      <style>
          .link:link,
          .link:visited {
            color: var(--color-link);
            text-decoration: underline;
            cursor: pointer;
          }
      </style>
      <a class="link" href=${this.url} @click=${this.onLinkActivation}>${function(e,t){if(e){let o=""+g.displayNameForURL(e);return void 0!==t&&(o+=":"+(t+1)),o}throw new Error("New linkifier component error: don't know how to generate link text for given arguments")}(this.url,this.lineNumber)}</a>
    `,this.shadow,{eventContext:this})}}customElements.define("devtools-linkifier",J);var X=Object.freeze({__proto__:null,LinkifierClick:G,Linkifier:J});class Q extends HTMLElement{constructor(){super(...arguments),this.shadow=this.attachShadow({mode:"open"}),this.reportTitle=""}set data({reportTitle:e}){this.reportTitle=e,this.render()}connectedCallback(){this.render()}render(){e(t`
      <style>
        .content {
          background-color: var(--color-background);
          display: grid;
          grid-template-columns: min-content 1fr;
        }

        .report-title {
          padding: 12px 24px;
          font-size: 15px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          border-bottom: 1px solid var(--color-details-hairline);
          color: var(--color-text-primary);
          background-color: var(--color-background);
          grid-column-start: span 2;
        }
      </style>

      <div class="content">
        ${this.reportTitle?t`<div class="report-title">${this.reportTitle}</div>`:o}
        <slot></slot>
      </div>
    `,this.shadow)}}class Y extends HTMLElement{constructor(){super(...arguments),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}render(){e(t`
      <style>
        :host {
          grid-column-start: span 2;
        }

        .section-header {
          padding: 12px;
          margin-left: 18px;
          display: flex;
          flex-direction: row;
          align-items: center;
          flex: auto;
          text-overflow: ellipsis;
          overflow: hidden;
          font-weight: bold;
          color: var(--color-text-primary);
        }
      </style>
      <div class="section-header">
        <slot></slot>
      </div>
    `,this.shadow)}}class Z extends HTMLElement{constructor(){super(...arguments),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}render(){e(t`
      <style>
        :host {
          grid-column-start: span 2;
        }

        .section-divider {
          border-bottom: 1px solid var(--color-details-hairline);
        }
      </style>
      <div class="section-divider">
      </div>
    `,this.shadow)}}class ee extends HTMLElement{constructor(){super(...arguments),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}render(){e(t`
      <style>
        :host {
          line-height: 28px;
          margin: 0 0 8px 0;
        }

        .key {
          color: var(--color-text-secondary);
          padding: 0 6px;
          text-align: right;
          white-space: pre;
        }
      </style>
      <div class="key"><slot></slot></div>
    `,this.shadow)}}class te extends HTMLElement{constructor(){super(...arguments),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}render(){e(t`
      <style>
        :host {
          line-height: 28px;
          margin: 0 0 8px 0;
          min-width: 150px;
        }

        .value {
          color: var(--color-text-primary);
          margin-inline-start: 0;
          padding: 0 6px;
        }
      </style>
      <div class="value"><slot></slot></div>
    `,this.shadow)}}customElements.define("devtools-report",Q),customElements.define("devtools-report-section-header",Y),customElements.define("devtools-report-key",ee),customElements.define("devtools-report-value",te),customElements.define("devtools-report-divider",Z);var oe=Object.freeze({__proto__:null,Report:Q,ReportSectionHeader:Y,ReportSectionDivider:Z,ReportKey:ee,ReportValue:te});const re=l;class ie extends HTMLElement{constructor(){super(...arguments),this.shadow=this.attachShadow({mode:"open"}),this.trigger="",this.promptText=a.LocalizedEmptyString,this.canShowSurvey=()=>{},this.showSurvey=()=>{},this.state="Checking"}set data(e){this.trigger=e.trigger,this.promptText=e.promptText,this.canShowSurvey=e.canShowSurvey,this.showSurvey=e.showSurvey,this.checkSurvey()}checkSurvey(){this.state="Checking",this.canShowSurvey(this.trigger,(({canShowSurvey:e})=>{this.state=e?"ShowLink":"DontShowLink",this.render()}))}sendSurvey(){this.state="Sending",this.render(),this.showSurvey(this.trigger,(({surveyShown:e})=>{this.state=e?"SurveyShown":"Failed",this.render()}))}render(){if("Checking"===this.state||"DontShowLink"===this.state)return;let o=this.promptText;"Sending"===this.state?o=re`Opening survey …`:"SurveyShown"===this.state?o=re`Thank you for your feedback`:"Failed"===this.state&&(o=re`An error occurred with the survey`);let r="";"Sending"===this.state?r="pending-link":"Failed"!==this.state&&"SurveyShown"!==this.state||(r="disabled-link");const i="ShowLink"!==this.state,n=t`
      <style>
        .link-icon {
          vertical-align: sub;
          margin-right: 0.5ch;
        }

        .link {
          padding: var(--issue-link-padding, 4px 0 0 0);
          text-decoration: var(--issue-link-text-decoration, underline);
          cursor: pointer;
          font-size: var(--issue-link-font-size, 14px);
          color: var(--issue-link); /* stylelint-disable-line plugin/use_theme_colors */
          /* See: crbug.com/1152736 for color variable migration. */
          border: none;
          background: none;
          font-family: inherit;
        }

        .link:focus:not(:focus-visible) {
          outline: none;
        }

        .pending-link {
          opacity: 75%;
          pointer-events: none;
          cursor: default;
          text-decoration: none;
        }

        .disabled-link {
          pointer-events: none;
          cursor: default;
          text-decoration: none;
        }
      </style>
      <button class="link ${r}" tabindex=${i?"-1":"0"} aria-disabled=${i} @click=${this.sendSurvey}>
        <devtools-icon class="link-icon" .data=${{iconName:"feedback_thin_16x16_icon",color:"var(--issue-link)",width:"var(--issue-link-icon-size, 16px)",height:"var(--issue-link-icon-size, 16px)"}}></devtools-icon><!--
      -->${o}
      </button>
    `;e(n,this.shadow,{eventContext:this})}}customElements.define("devtools-survey-link",ie);var ne=Object.freeze({__proto__:null,SurveyLink:ie});function se(e){return"children"in e}const le=i(((e,t)=>o=>{if(!(o instanceof n))throw new Error("Ref directive must be used as an attribute.");const r=o.committer.element;if(!(r instanceof HTMLLIElement))throw new Error("trackTreeNodeToDOMNode must be used on <li> elements.");e.set(r,t)})),ae=e=>{const t=e.parentElement?.parentElement;if(t&&t instanceof HTMLLIElement){const e=t.nextElementSibling;return e&&e instanceof HTMLLIElement?e:ae(t)}return null},ce=e=>{const t=e.querySelector(':scope > [role="group"] > [role="treeitem"]:first-child');if(!t)throw new Error("Could not find child of expanded node.");return t},de=e=>null!==e.getAttribute("aria-expanded"),he=e=>de(e)&&"true"===e.getAttribute("aria-expanded"),ue=e=>{const t=e.querySelector(':scope > [role="group"] > [role="treeitem"]:last-child');if(!t)throw new Error("Could not find child of expanded node.");return he(t)?ue(t):t},pe=e=>{let t=e.parentElement;if(!t)return null;for(;t&&"treeitem"!==t.getAttribute("role")&&t instanceof HTMLLIElement==!1;)t=t.parentElement;return t},me=e=>{const{currentDOMNode:t,currentTreeNode:o,direction:r,setNodeExpandedState:i}=e;if(!o)return t;if("ArrowDown"===r){if(he(t))return ce(t);const e=(e=>{const t=e.nextElementSibling;return t&&t instanceof HTMLLIElement?t:null})(t);if(e)return e;const o=ae(t);if(o)return o}else{if("ArrowRight"===r)return de(t)?he(t)?ce(t):(i(o,!0),t):t;if("ArrowUp"===r){const e=(e=>{const t=e.previousElementSibling;return t&&t instanceof HTMLLIElement?t:null})(t);if(e)return he(e)?ue(e):e;const o=pe(t);if(o&&o instanceof HTMLLIElement)return o}else if("ArrowLeft"===r){if(he(t))return i(o,!1),t;const e=pe(t);if(e&&e instanceof HTMLLIElement)return e}}return t};var fe=Object.freeze({__proto__:null,isExpandableNode:se,trackDOMNodeToTreeNode:le,findNextNodeForTreeOutlineKeyboardNavigation:me});const we=m.RenderCoordinator.instance();class ge extends HTMLElement{constructor(){super(...arguments),this.shadow=this.attachShadow({mode:"open"}),this.treeData=[],this.nodeExpandedMap=new WeakMap,this.domNodeToTreeNodeMap=new WeakMap,this.hasRenderedAtLeastOnce=!1,this.focusableTreeNode=null}get data(){return{tree:this.treeData}}set data(e){this.treeData=e.tree,this.hasRenderedAtLeastOnce||(this.focusableTreeNode=this.treeData[0]),this.render()}expandRecursively(e=2){for(const t of this.treeData)this.expandAndRecurse(t,0,e);this.render()}collapseChildrenOfNode(e){const t=this.domNodeToTreeNodeMap.get(e);t&&(this.recursivelyCollapseTreeNodeChildren(t),this.render())}recursivelyCollapseTreeNodeChildren(e){if(se(e)&&this.nodeIsExpanded(e)){for(const t of e.children)this.recursivelyCollapseTreeNodeChildren(t);this.setNodeExpandedState(e,!1)}}getFocusableTreeNode(){if(!this.focusableTreeNode)throw new Error("getFocusableNode was called but focusableNode is null");return this.focusableTreeNode}setNodeExpandedState(e,t){this.nodeExpandedMap.set(e,t)}nodeIsExpanded(e){return this.nodeExpandedMap.get(e)||!1}expandAndRecurse(e,t,o){if(se(e)&&(this.setNodeExpandedState(e,!0),t!==o&&se(e)))for(const r of e.children)this.expandAndRecurse(r,t+1,o)}onArrowClick(e){return t=>{t.stopPropagation(),se(e)&&(this.setNodeExpandedState(e,!this.nodeIsExpanded(e)),this.render())}}onNodeClick(e){e.stopPropagation(),this.focusTreeNode(e.target)}async focusTreeNode(e){const t=this.domNodeToTreeNodeMap.get(e);t&&(this.focusableTreeNode=t,await we.write((()=>{this.render(),e.focus()})))}processHomeAndEndKeysNavigation(e){if("Home"===e){const e=this.shadow.querySelector('ul[role="tree"] > li[role="treeitem"]');e&&this.focusTreeNode(e)}else if("End"===e){const e=this.shadow.querySelectorAll('li[role="treeitem"]'),t=e[e.length-1];t&&this.focusTreeNode(t)}}async processArrowKeyNavigation(e,t){const o=this.domNodeToTreeNodeMap.get(t);if(!o)return;const r=me({currentDOMNode:t,currentTreeNode:o,direction:e,setNodeExpandedState:(e,t)=>this.setNodeExpandedState(e,t)});this.focusTreeNode(r)}processEnterOrSpaceNavigation(e){const t=this.domNodeToTreeNodeMap.get(e);if(t&&se(t)){const e=this.nodeIsExpanded(t);this.setNodeExpandedState(t,!e),this.render()}}async onTreeKeyDown(e){if(!(e.target instanceof HTMLLIElement))throw new Error("event.target was not an <li> element");"Home"===e.key||"End"===e.key?(e.preventDefault(),this.processHomeAndEndKeysNavigation(e.key)):u.keyIsArrowKey(e.key)?(e.preventDefault(),await this.processArrowKeyNavigation(e.key,e.target)):"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),this.processEnterOrSpaceNavigation(e.target))}renderNode(e,{depth:i,setSize:n,positionInSet:s}){let l;const a=this.nodeIsExpanded(e);if(se(e)&&a){const o=e.children.map(((t,o)=>this.renderNode(t,{depth:i+1,setSize:e.children.length,positionInSet:o})));l=t`<ul role="group">${o}</ul>`}else l=o;const c=this.getFocusableTreeNode()===e?0:-1,d=r.classMap({expanded:se(e)&&a,parent:se(e)}),h=r.ifDefined(se(e)?String(a):void 0);return t`
      <li role="treeitem"
        tabindex=${c}
        aria-setsize=${n}
        aria-expanded=${h}
        aria-level=${i+1}
        aria-posinset=${s+1}
        class=${d}
        @click=${this.onNodeClick}
        track-dom-node-to-tree-node=${le(this.domNodeToTreeNodeMap,e)}
      >
        <span class="arrow-and-key-wrapper">
          <span class="arrow-icon" @click=${this.onArrowClick(e)}>
          </span>
          <span class="tree-node-key" data-node-key>${e.key}</span>
        </span>
        ${l}
      </li>
    `}render(){e(t`
    <style>
      li {
        list-style: none;
      }

      .arrow-icon {
        display: inline-block;
        user-select: none;
        -webkit-mask-image: url(Images/treeoutlineTriangles.svg);
        -webkit-mask-size: 32px 24px;
        -webkit-mask-position: 0 0;
        background-color: var(--color-text-primary);
        content: "";
        text-shadow: none;
        margin-right: -2px;
        height: 12px;
        width: 13px;
        display: inline-block;
        overflow: hidden;
      }
      li:not(.parent) > .arrow-and-key-wrapper > .arrow-icon {
        -webkit-mask-size: 0;
      }
      li.parent.expanded > .arrow-and-key-wrapper > .arrow-icon {
        -webkit-mask-position: -16px 0;
      }

      .arrow-and-key-wrapper {
        border: 2px solid transparent;
      }
      [role="treeitem"]:focus {
        outline: 0;
      }
      [role="treeitem"]:focus > .arrow-and-key-wrapper {
       border-color: black;
      }
    </style>
    <div class="wrapping-container">
     <ul role="tree" @keydown=${this.onTreeKeyDown}>
       ${this.treeData.map(((e,t)=>this.renderNode(e,{depth:0,setSize:this.treeData.length,positionInSet:t})))}
     </ul>
    </div>
    `,this.shadow,{eventContext:this}),this.hasRenderedAtLeastOnce=!0}}customElements.define("devtools-tree-outline",ge);var be=Object.freeze({__proto__:null,TreeOutline:ge});export{v as CounterButton,P as DataGrid,j as DataGridController,B as DataGridControllerIntegrator,y as DataGridRenderers,T as DataGridUtils,V as Icon,X as Linkifier,oe as ReportView,ne as SurveyLink,be as TreeOutline,fe as TreeOutlineUtils};
