/* * Copyright (C) 2007-2021 Apple Inc. All rights reserved. * Copyright (C) 2008 Matt Lilek. All rights reserved. * Copyright (C) 2008-2009 Anthony Ricaud * Copyright (C) 2009-2010 Joseph Pecoraro. All rights reserved. * Copyright (C) 2009-2011 Google Inc. All rights reserved. * Copyright (C) 2009 280 North Inc. All Rights Reserved. * Copyright (C) 2010 Nikita Vasilyev. All rights reserved. * Copyright (C) 2011 Brian Grinstead All rights reserved. * Copyright (C) 2013 Matt Holden * Copyright (C) 2013 Samsung Electronics. All rights reserved. * Copyright (C) 2013 Seokju Kwon (seokju.kwon@gmail.com) * Copyright (C) 2013 Adobe Systems Inc. All rights reserved. * Copyright (C) 2013-2015 University of Washington. All rights reserved. * Copyright (C) 2014-2015 Saam Barati * Copyright (C) 2014 Antoine Quint * Copyright (C) 2015 Tobias Reiss * Copyright (C) 2015-2017 Devin Rousso . All rights reserved. * Copyright (C) 2017 The Chromium Authors * Copyright (C) 2017-2018 Sony Interactive Entertainment Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ var WI={};var WebKitAdditions={};WI.Platform={name:InspectorFrontendHost.platform,version:{name:InspectorFrontendHost.platformVersionName,}}; class Debouncer {constructor(callback) {this._callback=callback;this._lastArguments=[];this._timeoutIdentifier=undefined;this._animationFrameIdentifier=undefined;this._promiseIdentifier=undefined;} force() {this._lastArguments=arguments;this._execute();} delayForTime(time,...args) {this.cancel();this._lastArguments=args;this._timeoutIdentifier=setTimeout(()=>{this._execute();},time);} delayForFrame() {this.cancel();this._lastArguments=arguments;this._animationFrameIdentifier=requestAnimationFrame(()=>{this._execute();});} delayForMicrotask() {this.cancel();this._lastArguments=arguments;let promiseIdentifier=Symbol("next-microtask");this._promiseIdentifier=promiseIdentifier;queueMicrotask(()=>{if(this._promiseIdentifier===promiseIdentifier) this._execute();});} cancel() {this._lastArguments=[];if(this._timeoutIdentifier){clearTimeout(this._timeoutIdentifier);this._timeoutIdentifier=undefined;} if(this._animationFrameIdentifier){cancelAnimationFrame(this._animationFrameIdentifier);this._animationFrameIdentifier=undefined;} if(this._promiseIdentifier) this._promiseIdentifier=undefined;} _execute() {let args=this._lastArguments;this.cancel();this._callback.apply(undefined,args);}} WI.DebuggableType={ITML:"itml",JavaScript:"javascript",Page:"page",ServiceWorker:"service-worker",WebPage:"web-page",};WI.DebuggableType.fromString=function(type){switch(type){case"itml":return WI.DebuggableType.ITML;case"javascript":return WI.DebuggableType.JavaScript;case"page":return WI.DebuggableType.Page;case"service-worker":return WI.DebuggableType.ServiceWorker;case"web-page":return WI.DebuggableType.WebPage;} return null;};WI.DebuggableType.supportedTargetTypes=function(debuggableType){let targetTypes=new Set;switch(debuggableType){case WI.DebuggableType.ITML:targetTypes.add(WI.TargetType.ITML);break;case WI.DebuggableType.JavaScript:targetTypes.add(WI.TargetType.JavaScript);break;case WI.DebuggableType.Page:targetTypes.add(WI.TargetType.Page);targetTypes.add(WI.TargetType.Worker);break;case WI.DebuggableType.ServiceWorker:targetTypes.add(WI.TargetType.ServiceWorker);break;case WI.DebuggableType.WebPage:targetTypes.add(WI.TargetType.Page);targetTypes.add(WI.TargetType.WebPage);targetTypes.add(WI.TargetType.Worker);break;} return targetTypes;};class IterableWeakSet {constructor(items=[]) {this._wrappers=new Set;this._wrapperForItem=new WeakMap;for(let item of items) this.add(item);} get size() {let size=0;for(let wrapper of this._wrappers){if(wrapper.deref()) ++size;} return size;} has(item) {let result=this._wrapperForItem.has(item);return result;} add(item) {if(this.has(item)) return;let wrapper=new WeakRef(item);this._wrappers.add(wrapper);this._wrapperForItem.set(item,wrapper);this._finalizationRegistry.register(item,{weakThis:new WeakRef(this),wrapper},wrapper);} delete(item) {return!!this.take(item);} take(item) {let wrapper=this._wrapperForItem.get(item);if(!wrapper) return undefined;let itemDeleted=this._wrapperForItem.delete(item);let wrapperDeleted=this._wrappers.delete(wrapper);this._finalizationRegistry.unregister(wrapper);return item;} clear() {for(let wrapper of this._wrappers){this._wrapperForItem.delete(wrapper);this._finalizationRegistry.unregister(wrapper);} this._wrappers.clear();} keys() {return this.values();}*values() {for(let wrapper of this._wrappers){let item=wrapper.deref();if(item) yield item;}} [Symbol.iterator]() {return this.values();} copy() {return new IterableWeakSet(this.toJSON());} toJSON() {return Array.from(this);} get _finalizationRegistry() {return IterableWeakSet._finalizationRegistry??=new FinalizationRegistry(function(heldValue){heldValue.weakThis.deref()?._wrappers.delete(heldValue.wrapper);});}} class Multimap {constructor(items=[]) {this._map=new Map;for(let[key,value]of items) this.add(key,value);} get size() {return this._map.size;} has(key,value) {let valueSet=this._map.get(key);if(!valueSet) return false;return value===undefined||valueSet.has(value);} get(key) {return this._map.get(key);} add(key,value) {let valueSet=this._map.get(key);if(!valueSet){valueSet=new Set;this._map.set(key,valueSet);} valueSet.add(value);return this;} delete(key,value) {if(arguments.length===1) return this._map.delete(key);let valueSet=this._map.get(key);if(!valueSet) return false;let deleted=valueSet.delete(value);if(!valueSet.size) this._map.delete(key);return deleted;} take(key,value) {if(arguments.length===1) return this._map.take(key);let valueSet=this._map.get(key);if(!valueSet) return undefined;let result=valueSet.take(value);if(!valueSet.size) this._map.delete(key);return result;} clear() {this._map.clear();} keys() {return this._map.keys();}*values() {for(let valueSet of this._map.values()){for(let value of valueSet) yield value;}} sets() {return this._map.entries();}*[Symbol.iterator]() {for(let[key,valueSet]of this._map){for(let value of valueSet) yield[key,value];}} copy() {return new Multimap(this.toJSON());} toJSON() {return Array.from(this);}} WI.Object=class WebInspectorObject {constructor() {this._listeners=null;} static addEventListener(eventType,listener,thisObject) {thisObject??=this;let data={listener,thisObjectWeakRef:new WeakRef(thisObject),};WI.Object._listenerThisObjectFinalizationRegistry.register(thisObject,{eventTargetWeakRef:new WeakRef(this),eventType,data},data);this._listeners??=new Multimap;this._listeners.add(eventType,data);return listener;} static singleFireEventListener(eventType,listener,thisObject) {let eventTargetWeakRef=new WeakRef(this);return this.addEventListener(eventType,function wrappedCallback(){eventTargetWeakRef.deref()?.removeEventListener(eventType,wrappedCallback,this);listener.apply(this,arguments);},thisObject);} static awaitEvent(eventType,thisObject) {return new Promise((resolve,reject)=>{this.singleFireEventListener(eventType,resolve,thisObject);});} static removeEventListener(eventType,listener,thisObject) {if(!this._listeners) return;thisObject??=this;let listenersForEventType=this._listeners.get(eventType);if(!listenersForEventType) return;let didDelete=false;for(let data of listenersForEventType){let unwrapped=data.thisObjectWeakRef.deref();if(!unwrapped||unwrapped!==thisObject||data.listener!==listener) continue;if(this._listeners.delete(eventType,data)) didDelete=true;WI.Object._listenerThisObjectFinalizationRegistry.unregister(data);}} addEventListener(){return WI.Object.addEventListener.apply(this,arguments);} singleFireEventListener(){return WI.Object.singleFireEventListener.apply(this,arguments);} awaitEvent(){return WI.Object.awaitEvent.apply(this,arguments);} removeEventListener(){return WI.Object.removeEventListener.apply(this,arguments);} dispatchEventToListeners(eventType,eventData) {let event=new WI.Event(this,eventType,eventData);function dispatch(object) {if(!object||event._stoppedPropagation) return;let listeners=object._listeners;if(!listeners||!object.hasOwnProperty("_listeners")||!listeners.size) return;let listenersForEventType=listeners.get(eventType);if(!listenersForEventType) return;for(let data of Array.from(listenersForEventType)){let unwrapped=data.thisObjectWeakRef.deref();if(!unwrapped) continue;data.listener.call(unwrapped,event);if(event._stoppedPropagation) break;}} dispatch(this);event._stoppedPropagation=false;let constructor=this.constructor;while(constructor){dispatch(constructor);if(!constructor.prototype.__proto__) break;constructor=constructor.prototype.__proto__.constructor;} return event.defaultPrevented;} static hasEventListeners(eventType) {return this._listeners?.has(eventType);} static activelyListeningObjectsWithPrototype(proto) {let results=new Set;if(this._listeners){for(let data of this._listeners.values()){let unwrapped=data.thisObjectWeakRef.deref();if(unwrapped instanceof proto) results.add(unwrapped);}} return results;} hasEventListeners(){return WI.Object.hasEventListeners.apply(this,arguments);} activelyListeningObjectsWithPrototype(){return WI.Object.activelyListeningObjectsWithPrototype.apply(this,arguments);}};WI.Object._listenerThisObjectFinalizationRegistry=new FinalizationRegistry((heldValue)=>{heldValue.eventTargetWeakRef.deref()?._listeners.delete(heldValue.eventType,heldValue.data);});WI.Event=class Event {constructor(target,type,data) {this.target=target;this.type=type;this.data=data;this.defaultPrevented=false;this._stoppedPropagation=false;} stopPropagation() {this._stoppedPropagation=true;} preventDefault() {this.defaultPrevented=true;}};WI.notifications=new WI.Object;WI.Notification={GlobalModifierKeysDidChange:"global-modifiers-did-change",PageArchiveStarted:"page-archive-started",PageArchiveEnded:"page-archive-ended",ExtraDomainsActivated:"extra-domains-activated", VisibilityStateDidChange:"visibility-state-did-change",TransitionPageTarget:"transition-page-target",};WI.ReferencePage=class ReferencePage{constructor(page,{topic}={}) {if(page instanceof WI.ReferencePage) page=page.page;this._page=page;this._topic=topic||"";} get page(){return this._page;} get topic(){return this._topic;} createLinkElement() {let url="https://webkit.org/web-inspector/"+this._page+"/";if(this._topic) url+="#"+this._topic;let wrapper=document.createElement("span");wrapper.className="reference-page-link-container";let link=wrapper.appendChild(document.createElement("a"));link.className="reference-page-link";link.href=link.title=url;link.textContent="?";link.addEventListener("click",(event)=>{event.preventDefault();event.stopPropagation();WI.openURL(link.href,{alwaysOpenExternally:true});});return wrapper;}};WI.ReferencePage.AuditTab=new WI.ReferencePage("audit-tab");WI.ReferencePage.AuditTab.AuditResults=new WI.ReferencePage(WI.ReferencePage.AuditTab,{topic:"audit-results"});WI.ReferencePage.AuditTab.CreatingAudits=new WI.ReferencePage(WI.ReferencePage.AuditTab,{topic:"creating-audits"});WI.ReferencePage.AuditTab.EditingAudits=new WI.ReferencePage(WI.ReferencePage.AuditTab,{topic:"editing-audits"});WI.ReferencePage.AuditTab.RunningAudits=new WI.ReferencePage(WI.ReferencePage.AuditTab,{topic:"running-audits"});WI.ReferencePage.DOMBreakpoints=new WI.ReferencePage("dom-breakpoints");WI.ReferencePage.DOMBreakpoints.Configuration=new WI.ReferencePage(WI.ReferencePage.DOMBreakpoints,{topic:"configuration"});WI.ReferencePage.DeviceSettings=new WI.ReferencePage("device-settings");WI.ReferencePage.DeviceSettings.Configuration=new WI.ReferencePage(WI.ReferencePage.DeviceSettings,{topic:"configuration"});WI.ReferencePage.ElementsTab=new WI.ReferencePage("elements-tab");WI.ReferencePage.ElementsTab.DOMTree=new WI.ReferencePage(WI.ReferencePage.ElementsTab,{topic:"dom-tree"});WI.ReferencePage.EventBreakpoints=new WI.ReferencePage("event-breakpoints");WI.ReferencePage.EventBreakpoints.Configuration=new WI.ReferencePage(WI.ReferencePage.EventBreakpoints,{topic:"configuration"});WI.ReferencePage.JavaScriptBreakpoints=new WI.ReferencePage("javascript-breakpoints");WI.ReferencePage.JavaScriptBreakpoints.Configuration=new WI.ReferencePage(WI.ReferencePage.JavaScriptBreakpoints,{topic:"configuration"});WI.ReferencePage.LayersTab=new WI.ReferencePage("layers-tab");WI.ReferencePage.LocalOverrides=new WI.ReferencePage("local-overrides");WI.ReferencePage.LocalOverrides.ConfiguringLocalOverrides=new WI.ReferencePage(WI.ReferencePage.LocalOverrides,{topic:"configuring-local-overrides"});WI.ReferencePage.NetworkTab=new WI.ReferencePage("network-tab");WI.ReferencePage.NetworkTab.CookiesPane=new WI.ReferencePage(WI.ReferencePage.NetworkTab,{topic:"cookies-pane"});WI.ReferencePage.NetworkTab.HeadersPane=new WI.ReferencePage(WI.ReferencePage.NetworkTab,{topic:"headers-pane"});WI.ReferencePage.NetworkTab.PreviewPane=new WI.ReferencePage(WI.ReferencePage.NetworkTab,{topic:"preview-pane"});WI.ReferencePage.NetworkTab.SecurityPane=new WI.ReferencePage(WI.ReferencePage.NetworkTab,{topic:"security-pane"});WI.ReferencePage.NetworkTab.SizesPane=new WI.ReferencePage(WI.ReferencePage.NetworkTab,{topic:"sizes-pane"});WI.ReferencePage.NetworkTab.TimingPane=new WI.ReferencePage(WI.ReferencePage.NetworkTab,{topic:"timing-pane"});WI.ReferencePage.SymbolicBreakpoints=new WI.ReferencePage("symbolic-breakpoints");WI.ReferencePage.SymbolicBreakpoints.Configuration=new WI.ReferencePage(WI.ReferencePage.SymbolicBreakpoints,{topic:"configuration"});WI.ReferencePage.TimelinesTab=new WI.ReferencePage("timelines-tab");WI.ReferencePage.TimelinesTab.CPUTimeline=new WI.ReferencePage(WI.ReferencePage.TimelinesTab,{topic:"cpu-timeline"});WI.ReferencePage.TimelinesTab.EventsView=new WI.ReferencePage(WI.ReferencePage.TimelinesTab,{topic:"events-view"});WI.ReferencePage.TimelinesTab.FramesView=new WI.ReferencePage(WI.ReferencePage.TimelinesTab,{topic:"frames-view"});WI.ReferencePage.TimelinesTab.JavaScriptAllocationsTimeline=new WI.ReferencePage(WI.ReferencePage.TimelinesTab,{topic:"javascript-allocations-timeline"});WI.ReferencePage.TimelinesTab.JavaScriptAndEventsTimeline=new WI.ReferencePage(WI.ReferencePage.TimelinesTab,{topic:"javascript-events-timeline"});WI.ReferencePage.TimelinesTab.LayoutAndRenderingTimeline=new WI.ReferencePage(WI.ReferencePage.TimelinesTab,{topic:"layout-rendering-timeline"});WI.ReferencePage.TimelinesTab.MediaAndAnimationsTimeline=new WI.ReferencePage(WI.ReferencePage.TimelinesTab,{topic:"media-animations-timeline"});WI.ReferencePage.TimelinesTab.MemoryTimeline=new WI.ReferencePage(WI.ReferencePage.TimelinesTab,{topic:"memory-timeline"});WI.ReferencePage.TimelinesTab.NetworkRequestsTimeline=new WI.ReferencePage(WI.ReferencePage.TimelinesTab,{topic:"network-timeline"});WI.ReferencePage.TimelinesTab.ScreenshotsTimeline=new WI.ReferencePage(WI.ReferencePage.TimelinesTab,{topic:"screenshots-timeline"});WI.ReferencePage.URLBreakpoints=new WI.ReferencePage("url-breakpoints");WI.ReferencePage.URLBreakpoints.Configuration=new WI.ReferencePage(WI.ReferencePage.URLBreakpoints,{topic:"configuration"});WI.TargetType={ITML:"itml",JavaScript:"javascript",Page:"page",ServiceWorker:"service-worker",WebPage:"web-page",Worker:"worker",};WI.TargetType.all=Object.values(WI.TargetType); class Throttler {constructor(callback,delay) {this._callback=callback;this._delay=delay;this._lastArguments=[];this._timeoutIdentifier=undefined;this._lastFireTime=-this._delay;} force() {this._lastArguments=arguments;this._execute();} fire() {this._lastArguments=arguments;let remaining=this._delay-(Date.now()-this._lastFireTime);if(remaining<=0){this._execute();return;} if(this._timeoutIdentifier) return;this._timeoutIdentifier=setTimeout(()=>{this._execute();},remaining);} cancel() {this._lastArguments=[];if(this._timeoutIdentifier){clearTimeout(this._timeoutIdentifier);this._timeoutIdentifier=undefined;}} _execute() {this._lastFireTime=Date.now();let args=this._lastArguments;this.cancel();this._callback.apply(undefined,args);}} WI.BlobUtilities=class BlobUtilities{static blobForContent(content,base64Encoded,mimeType) {if(base64Encoded) return BlobUtilities.decodeBase64ToBlob(content,mimeType);return BlobUtilities.textToBlob(content,mimeType);} static decodeBase64ToBlob(base64Data,mimeType) {mimeType=mimeType||"";const sliceSize=1024;let byteCharacters=atob(base64Data);let bytesLength=byteCharacters.length;let slicesCount=Math.ceil(bytesLength/sliceSize);let byteArrays=new Array(slicesCount);for(let sliceIndex=0;sliceIndex{callback(fileReader.result);});fileReader.readAsText(blob);}};WI.roleSelectorForNode=function(node) { var title="";var role=node.computedRole();if(role) title=":role("+role+")";return title;};WI.linkifyAccessibilityNodeReference=function(node) {if(!node) return null;var link=WI.linkifyNodeReference(node);var tagIdSelector=link.title;var classSelectorIndex=tagIdSelector.indexOf(".");if(classSelectorIndex>-1) tagIdSelector=tagIdSelector.substring(0,classSelectorIndex);var roleSelector=WI.roleSelectorForNode(node);link.textContent=tagIdSelector+roleSelector;link.title+=roleSelector;return link;};WI.linkifyStyleable=function(styleable) {let displayName=styleable.displayName;let link=document.createElement("span");link.append(displayName);return WI.linkifyNodeReferenceElement(styleable.node,link,{displayName});};WI.linkifyNodeReference=function(node,options={}) {let displayName=node.displayName;if(!isNaN(options.maxLength)) displayName=displayName.truncate(options.maxLength);let link=document.createElement("span");link.append(displayName);return WI.linkifyNodeReferenceElement(node,link,{...options,displayName});};WI.linkifyNodeReferenceElement=function(node,element,options={}) {element.setAttribute("role","link");element.title=options.displayName||node.displayName;let nodeType=node.nodeType();if(!options.ignoreClick&&(nodeType!==Node.DOCUMENT_NODE||node.parentNode)&&nodeType!==Node.TEXT_NODE) element.classList.add("node-link");WI.bindInteractionsForNodeToElement(node,element,options);return element;};WI.bindInteractionsForNodeToElement=function(node,element,options={}){if(!options.ignoreClick){element.addEventListener("click",(event)=>{WI.domManager.inspectElement(node.id,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.LinkClick,});});} element.addEventListener("mouseover",(event)=>{node.highlight();});element.addEventListener("mouseout",(event)=>{WI.domManager.hideDOMNodeHighlight();});element.addEventListener("contextmenu",(event)=>{let contextMenu=WI.ContextMenu.createFromEvent(event);WI.appendContextMenuItemsForDOMNode(contextMenu,node,options);});};function createSVGElement(tagName) {return document.createElementNS("http://www.w3.org/2000/svg",tagName);} WI.cssPath=function(node,options={}) {if(node.nodeType()!==Node.ELEMENT_NODE) return"";let suffix="";if(node.isPseudoElement()){suffix="::"+node.pseudoType();node=node.parentNode;} let components=[];while(node){let component=WI.cssPathComponent(node,options);if(!component) break;components.push(component);if(component.done) break;node=node.parentNode;} components.reverse();return components.map((x)=>x.value).join(" > ")+suffix;};WI.cssPathComponent=function(node,options={}) {if(node.nodeType()!==Node.ELEMENT_NODE) return null;let nodeName=node.nodeNameInCorrectCase();if(!node.parentNode||node.parentNode.nodeType()===Node.DOCUMENT_NODE) return{value:nodeName,done:true};if(options.full){function getUniqueAttributes(domNode){let uniqueAttributes=new Map;for(let attribute of domNode.attributes()){let values=[attribute.value];if(attribute.name==="id"||attribute.name==="class") values=attribute.value.split(/\s+/);uniqueAttributes.set(attribute.name,new Set(values));} return uniqueAttributes;} let nodeIndex=0;let needsNthChild=false;let uniqueAttributes=getUniqueAttributes(node);node.parentNode.children.forEach((child,i)=>{if(child.nodeType()!==Node.ELEMENT_NODE) return;if(child===node){nodeIndex=i;return;} if(needsNthChild||child.nodeNameInCorrectCase()!==nodeName) return;let childUniqueAttributes=getUniqueAttributes(child);let subsetCount=0;for(let[name,values]of uniqueAttributes){let childValues=childUniqueAttributes.get(name);if(childValues&&values.size<=childValues.size&&values.isSubsetOf(childValues)) ++subsetCount;} if(subsetCount===uniqueAttributes.size) needsNthChild=true;});function selectorForAttribute(values,prefix="",shouldCSSEscape=false){if(!values||!values.size) return"";values=Array.from(values);values=values.filter((value)=>value&&value.length);if(!values.length) return"";values=values.map((value)=>shouldCSSEscape?CSS.escape(value):value.escapeCharacters("\""));return prefix+values.join(prefix);} let selector=nodeName;selector+=selectorForAttribute(uniqueAttributes.get("id"),"#",true);selector+=selectorForAttribute(uniqueAttributes.get("class"),".",true);for(let[attribute,values]of uniqueAttributes){if(attribute!=="id"&&attribute!=="class") selector+=`[${attribute}="${selectorForAttribute(values)}"]`;} if(needsNthChild) selector+=`:nth-child(${nodeIndex + 1})`;return{value:selector,done:false};} let lowerNodeName=node.nodeName().toLowerCase();if(lowerNodeName==="body"||lowerNodeName==="head"||lowerNodeName==="html") return{value:nodeName,done:true};let id=node.getAttribute("id");if(id) return{value:node.escapedIdSelector,done:true}; function classNames(node){let classAttribute=node.getAttribute("class");return classAttribute?classAttribute.trim().split(/\s+/):[];} let nthChildIndex=-1;let hasUniqueTagName=true;let uniqueClasses=new Set(classNames(node));let siblings=node.parentNode.children;let elementIndex=0;for(let sibling of siblings){if(sibling.nodeType()!==Node.ELEMENT_NODE) continue;elementIndex++;if(sibling===node){nthChildIndex=elementIndex;continue;} if(sibling.nodeNameInCorrectCase()===nodeName) hasUniqueTagName=false;if(uniqueClasses.size){let siblingClassNames=classNames(sibling);for(let className of siblingClassNames) uniqueClasses.delete(className);}} let selector=nodeName;if(lowerNodeName==="input"&&node.getAttribute("type")&&!uniqueClasses.size) selector+=`[type="${node.getAttribute("type")}"]`;if(!hasUniqueTagName){if(uniqueClasses.size) selector+=node.escapedClassSelector;else selector+=`:nth-child(${nthChildIndex})`;} return{value:selector,done:false};};WI.xpath=function(node) {if(node.nodeType()===Node.DOCUMENT_NODE) return"/";let components=[];while(node){let component=WI.xpathComponent(node);if(!component) break;components.push(component);if(component.done) break;node=node.parentNode;} components.reverse();let prefix=components.length&&components[0].done?"":"/";return prefix+components.map((x)=>x.value).join("/");};WI.xpathComponent=function(node) {let index=WI.xpathIndex(node);if(index===-1) return null;let value;switch(node.nodeType()){case Node.DOCUMENT_NODE:return{value:"",done:true};case Node.ELEMENT_NODE:var id=node.getAttribute("id");if(id) return{value:`//*[@id="${id}"]`,done:true};value=node.localName();break;case Node.ATTRIBUTE_NODE:value=`@${node.nodeName()}`;break;case Node.TEXT_NODE:case Node.CDATA_SECTION_NODE:value="text()";break;case Node.COMMENT_NODE:value="comment()";break;case Node.PROCESSING_INSTRUCTION_NODE:value="processing-instruction()";break;default:value="";break;} if(index>0) value+=`[${index}]`;return{value,done:false};};WI.xpathIndex=function(node) {if(!node.parentNode) return 0;let siblings=node.parentNode.children;if(siblings.length<=1) return 0; function isSimiliarNode(a,b){if(a===b) return true;let aType=a.nodeType();let bType=b.nodeType();if(aType===Node.ELEMENT_NODE&&bType===Node.ELEMENT_NODE) return a.localName()===b.localName();if(aType===Node.CDATA_SECTION_NODE) return aType===Node.TEXT_NODE;if(bType===Node.CDATA_SECTION_NODE) return bType===Node.TEXT_NODE;return aType===bType;} let unique=true;let xPathIndex=-1;let xPathIndexCounter=1;for(let sibling of siblings){if(!isSimiliarNode(node,sibling)) continue;if(node===sibling){xPathIndex=xPathIndexCounter;if(!unique) return xPathIndex;}else{unique=false;if(xPathIndex!==-1) return xPathIndex;} xPathIndexCounter++;} if(unique) return 0;return xPathIndex;};WI.FileUtilities=class FileUtilities{static screenshotString() {let date=new Date;let values=[date.getFullYear(),Number.zeroPad(date.getMonth()+1,2),Number.zeroPad(date.getDate(),2),Number.zeroPad(date.getHours(),2),Number.zeroPad(date.getMinutes(),2),Number.zeroPad(date.getSeconds(),2),];return WI.UIString("Screen Shot %s-%s-%s at %s.%s.%s").format(...values);} static sanitizeFilename(filename) {return filename.replace(/:+/g,"-");} static inspectorURLForFilename(filename) {return"web-inspector:///"+encodeURIComponent(FileUtilities.sanitizeFilename(filename));} static longestCommonPrefix(files,{directory}={}) {let longestCommonPrefix=files[0].getPath();for(let i=1;i1)&&!longestCommonPrefix.endsWith("/")){let lastSlashIndex=longestCommonPrefix.lastIndexOf("/");if(lastSlashIndex) longestCommonPrefix=longestCommonPrefix.substring(0,lastSlashIndex);longestCommonPrefix+="/";} return longestCommonPrefix;} static canSave(saveMode) {return InspectorFrontendHost.canSave(saveMode);} static async save(saveMode,fileVariants,forceSaveAs) {if(!fileVariants){InspectorFrontendHost.beep();return;} let isFileVariantsMode=saveMode===WI.FileUtilities.SaveMode.FileVariants;if(isFileVariantsMode) forceSaveAs=true;if(typeof fileVariants.customSaveHandler==="function"){fileVariants.customSaveHandler(forceSaveAs);return;} if(!isFileVariantsMode&&!Array.isArray(fileVariants)) fileVariants=[fileVariants];if(!Array.isArray(fileVariants)){InspectorFrontendHost.beep();return;} let promises=fileVariants.map((fileVariant)=>{let content=fileVariant.content;if(!content) return null;let displayType=fileVariant.displayType||"";if(!fileVariant.displayType&&isFileVariantsMode) return null;let suggestedName=fileVariant.suggestedName;if(!suggestedName){let url=fileVariant.url||"";suggestedName=parseURL(url).lastPathComponent;if(!suggestedName){suggestedName=WI.UIString("Untitled");let dataURLTypeMatch=/^data:([^;]+)/.exec(url);if(dataURLTypeMatch){let fileExtension=WI.fileExtensionForMIMEType(dataURLTypeMatch[1]);if(fileExtension) suggestedName+="."+fileExtension;}}} let url=WI.FileUtilities.inspectorURLForFilename(suggestedName);if(typeof content==="string"){return Promise.resolve({displayType,url,content,base64Encoded:!!fileVariant.base64Encoded,});} let wrappedPromise=new WI.WrappedPromise;let fileReader=new FileReader;fileReader.addEventListener("loadend",()=>{wrappedPromise.resolve({displayType,url,content:parseDataURL(fileReader.result).data,base64Encoded:true,});});fileReader.readAsDataURL(content);return wrappedPromise.promise;});if(promises.includes(null)){InspectorFrontendHost.beep();return;} let saveDatas=await Promise.all(promises);InspectorFrontendHost.save(saveDatas,!!forceSaveAs);} static import(callback,{multiple,directory}={}) {let inputElement=document.createElement("input");inputElement.type="file";inputElement.value=null;inputElement.multiple=!!multiple||!!directory;inputElement.webkitdirectory=!!directory;inputElement.addEventListener("change",(event)=>{callback(inputElement.files);});inputElement.click(); FileUtilities.importInputElement=inputElement;} static importText(callback,options={}) {FileUtilities.import((files)=>{FileUtilities.readText(files,callback);},options);} static importJSON(callback,options={}) {FileUtilities.import((files)=>{FileUtilities.readJSON(files,callback);},options);} static importData(callback,options={}) {FileUtilities.import((files)=>{FileUtilities.readData(files,callback);},options);} static async readText(fileOrList,callback) {await FileUtilities._read(fileOrList,async(file,result)=>{await new Promise((resolve,reject)=>{let reader=new FileReader;reader.addEventListener("loadend",(event)=>{result.text=reader.result;resolve(event);});reader.addEventListener("error",reject);reader.readAsText(file);});},callback);} static async readJSON(fileOrList,callback) {await WI.FileUtilities.readText(fileOrList,async(result)=>{if(result.text&&!result.error){try{result.json=JSON.parse(result.text);}catch(e){result.error=e;}} await callback(result);});} static async readData(fileOrList,callback) {await FileUtilities._read(fileOrList,async(file,result)=>{await new Promise((resolve,reject)=>{let reader=new FileReader;reader.addEventListener("loadend",(event)=>{let{mimeType,base64,data}=parseDataURL(reader.result);if(!mimeType||mimeType==="text/plain"){let extension=WI.fileExtensionForFilename(result.filename);if(extension) mimeType=WI.mimeTypeForFileExtension(extension);} result.mimeType=mimeType;result.base64Encoded=base64;result.content=data;resolve(event);});reader.addEventListener("error",reject);reader.readAsDataURL(file);});},callback);} static async _read(fileOrList,operation,callback) {let files=[];if(fileOrList instanceof File) files.push(fileOrList);else if(fileOrList instanceof FileList) files=Array.from(fileOrList);for(let file of files){let result={filename:file.name,};try{await operation(file,result);}catch(e){result.error=e;} await callback(result);}}};WI.FileUtilities.SaveMode={SingleFile:"single-file",FileVariants:"file-variants",};WI.HTTPUtilities=class HTTPUtilities{static statusTextForStatusCode(code) {switch(code){case 0:return"OK";case 100:return"Continue";case 101:return"Switching Protocols";case 200:return"OK";case 201:return"Created";case 202:return"Accepted";case 203:return"Non-Authoritative Information";case 204:return"No Content";case 205:return"Reset Content";case 206:return"Partial Content";case 207:return"Multi-Status";case 300:return"Multiple Choices";case 301:return"Moved Permanently";case 302:return"Found";case 303:return"See Other";case 304:return"Not Modified";case 305:return"Use Proxy";case 307:return"Temporary Redirect";case 308:return"Permanent Redirect";case 400:return"Bad Request";case 401:return"Unauthorized";case 402:return"Payment Required";case 403:return"Forbidden";case 404:return"Not Found";case 405:return"Method Not Allowed";case 406:return"Not Acceptable";case 407:return"Proxy Authentication Required";case 408:return"Request Time-out";case 409:return"Conflict";case 410:return"Gone";case 411:return"Length Required";case 412:return"Precondition Failed";case 413:return"Request Entity Too Large";case 414:return"Request-URI Too Large";case 415:return"Unsupported Media Type";case 416:return"Requested range not satisfiable";case 417:return"Expectation Failed";case 500:return"Internal Server Error";case 501:return"Not Implemented";case 502:return"Bad Gateway";case 503:return"Service Unavailable";case 504:return"Gateway Time-out";case 505:return"HTTP Version not supported";} if(code<200) return"Continue";if(code<300) return"OK";if(code<400) return"Multiple Choices";if(code<500) return"Bad Request";return"Internal Server Error";}};WI.HTTPUtilities.RequestMethod={CONNECT:"CONNECT",DELETE:"DELETE",GET:"GET",HEAD:"HEAD",OPTIONS:"OPTIONS",PATCH:"PATCH",POST:"POST",PUT:"PUT",TRACE:"TRACE",};WI.HTTPUtilities.RequestMethodsWithBody=new Set([WI.HTTPUtilities.RequestMethod.DELETE,WI.HTTPUtilities.RequestMethod.PATCH,WI.HTTPUtilities.RequestMethod.POST,WI.HTTPUtilities.RequestMethod.PUT,]);WI.ImageUtilities=class ImageUtilities{static useSVGSymbol(url,className,title) {const svgNamespace="http://www.w3.org/2000/svg";const xlinkNamespace="http://www.w3.org/1999/xlink";let svgElement=document.createElementNS(svgNamespace,"svg");svgElement.style.width="100%";svgElement.style.height="100%"; if(!url.includes("#")) url+="#root";let useElement=document.createElementNS(svgNamespace,"use");useElement.setAttributeNS(xlinkNamespace,"xlink:href",url);svgElement.appendChild(useElement);let wrapper=document.createElement("div");wrapper.appendChild(svgElement);if(className) wrapper.className=className;if(title) wrapper.title=title;return wrapper;} static promisifyLoad(src) {return new Promise((resolve,reject)=>{let image=new Image;let resolveWithImage=()=>{resolve(image);};image.addEventListener("load",resolveWithImage);image.addEventListener("error",resolveWithImage);image.src=src;});} static scratchCanvasContext2D(callback) {if(!WI.ImageUtilities._scratchContext2D) WI.ImageUtilities._scratchContext2D=document.createElement("canvas").getContext("2d");let context=WI.ImageUtilities._scratchContext2D;context.clearRect(0,0,context.canvas.width,context.canvas.height);context.save();callback(context);context.restore();} static imageFromImageBitmap(data) {let image=null;WI.ImageUtilities.scratchCanvasContext2D((context)=>{context.canvas.width=data.width;context.canvas.height=data.height;context.drawImage(data,0,0);image=new Image;image.src=context.canvas.toDataURL();});return image;} static imageFromImageData(data) {let image=null;WI.ImageUtilities.scratchCanvasContext2D((context)=>{context.canvas.width=data.width;context.canvas.height=data.height;context.putImageData(data,0,0);image=new Image;image.src=context.canvas.toDataURL();});return image;} static imageFromCanvasGradient(gradient,width,height) {let image=null;WI.ImageUtilities.scratchCanvasContext2D((context)=>{context.canvas.width=width;context.canvas.height=height;context.fillStyle=gradient;context.fillRect(0,0,width,height);image=new Image;image.src=context.canvas.toDataURL();});return image;}};WI.ImageUtilities._scratchContext2D=null;(function(){if(WI.dontLocalizeUserInterface) return;let localizedStringsURL=InspectorFrontendHost.localizedStringsURL;if(localizedStringsURL) document.write("");})();WI.unlocalizedString=function(string) { return string;};WI.UIString=function(string,key,comment) {"use strict";if(WI.dontLocalizeUserInterface) return string;if(arguments.length===2){comment=key;key=undefined;} key=key||string;if(window.localizedStrings&&key in window.localizedStrings) return window.localizedStrings[key];if(!window.localizedStrings) console.error(`Attempted to load localized string "${key}" before localizedStrings was initialized.`,comment);if(!this._missingLocalizedStrings) this._missingLocalizedStrings={};if(!(key in this._missingLocalizedStrings)){console.error(`Localized string "${key}" was not found.`,comment);this._missingLocalizedStrings[key]=true;} return"LOCALIZED STRING NOT FOUND";};WI.repeatedUIString={};WI.repeatedUIString.timelineRecordLayout=function(){return WI.UIString("Layout","Layout @ Timeline record","Layout phase timeline records");};WI.repeatedUIString.timelineRecordPaint=function(){return WI.UIString("Paint","Paint @ Timeline record","Paint (render) phase timeline records");};WI.repeatedUIString.timelineRecordComposite=function(){return WI.UIString("Composite","Composite @ Timeline record","Composite phase timeline records, where graphic layers are combined");};WI.repeatedUIString.debuggerStatements=function(){return WI.UIString("Debugger Statements","Debugger Statements @ JavaScript Breakpoint","Break (pause) on debugger statements");};WI.repeatedUIString.allExceptions=function(){return WI.UIString("All Exceptions","All Exceptions @ JavaScript Breakpoint","Break (pause) on all exceptions");};WI.repeatedUIString.uncaughtExceptions=function(){return WI.UIString("Uncaught Exceptions","Uncaught Exceptions @ JavaScript Breakpoint","Break (pause) on uncaught (unhandled) exceptions");};WI.repeatedUIString.assertionFailures=function(){return WI.UIString("Assertion Failures","Assertion Failures @ JavaScript Breakpoint","Break (pause) when console.assert() fails");};WI.repeatedUIString.allMicrotasks=function(){return WI.UIString("All Microtasks","All Microtasks @ JavaScript Breakpoint","Break (pause) on all microtasks");};WI.repeatedUIString.allAnimationFrames=function(){return WI.UIString("All Animation Frames","All Animation Frames @ Event Breakpoint","Break (pause) on All animation frames");};WI.repeatedUIString.allIntervals=function(){return WI.UIString("All Intervals","All Intervals @ Event Breakpoint","Break (pause) on all intervals");};WI.repeatedUIString.allEvents=function(){return WI.UIString("All Events","All Events @ Event Breakpoint","Break (pause) on all events");};WI.repeatedUIString.allTimeouts=function(){return WI.UIString("All Timeouts","All Timeouts @ Event Breakpoint","Break (pause) on all timeouts");};WI.repeatedUIString.allRequests=function(){return WI.UIString("All Requests","A submenu item of 'Break on' that breaks (pauses) before all network requests");};WI.repeatedUIString.fetch=function(){return WI.UIString("Fetch","Resource loaded via 'fetch' method");};WI.repeatedUIString.revealInDOMTree=function(){return WI.UIString("Reveal in DOM Tree","Open Elements tab and select this node in DOM tree");};WI.repeatedUIString.showTransparencyGridTooltip=function(){return WI.UIString("Show transparency grid","Show transparency grid (tooltip)","Tooltip for showing the checkered transparency grid under images and canvases")};WI.fileExtensionForFilename=function(filename) {if(!filename) return null;let index=filename.lastIndexOf(".");if(index===-1) return null;if(index===filename.length-1) return null;return filename.substr(index+1);};WI.fileExtensionForURL=function(url) {let lastPathComponent=parseURL(url).lastPathComponent;return WI.fileExtensionForFilename(lastPathComponent);};WI.mimeTypeForFileExtension=function(extension) {const extensionToMIMEType={"html":"text/html","xhtml":"application/xhtml+xml","xml":"text/xml","js":"text/javascript","mjs":"text/javascript","json":"application/json","clj":"text/x-clojure","coffee":"text/x-coffeescript","ls":"text/x-livescript","ts":"text/typescript","ps":"application/postscript","jsx":"text/jsx","css":"text/css","less":"text/x-less","sass":"text/x-sass","scss":"text/x-scss","avif":"image/avif","bmp":"image/bmp","gif":"image/gif","ico":"image/x-icon","jp2":"image/jp2","jpeg":"image/jpeg","jpg":"image/jpeg","jxl":"image/jxl","pdf":"application/pdf","png":"image/png","tif":"image/tiff","tiff":"image/tiff","webp":"image/webp","xbm":"image/x-xbitmap","ogx":"application/ogg","ogg":"audio/ogg","oga":"audio/ogg","ogv":"video/ogg","anx":"application/annodex","axa":"audio/annodex","axv":"video/annodex","spx":"audio/speex","webm":"video/webm","m1a":"audio/mpeg","m2a":"audio/mpeg","mpg":"video/mpeg","m15":"video/mpeg","m1s":"video/mpeg","m1v":"video/mpeg","m75":"video/mpeg","mpa":"video/mpeg","mpeg":"video/mpeg","mpm":"video/mpeg","mpv":"video/mpeg","m3u8":"application/x-mpegurl","m3url":"audio/x-mpegurl","m3u":"audio/x-mpegurl","m4v":"video/x-m4v","m4a":"audio/x-m4a","m4b":"audio/x-m4b","m4p":"audio/x-m4p","mp3":"audio/mp3","mp2":"video/x-mpeg2","vob":"video/mpeg2","mod":"video/mpeg2","m2ts":"video/m2ts","m2t":"video/x-m2ts","3gpp":"audio/3gpp","3g2":"audio/3gpp2","amc":"application/x-mpeg","aac":"audio/aac","adts":"audio/aac","m4r":"audio/x-aac","caf":"audio/x-caf","gsm":"audio/x-gsm","wav":"audio/x-wav","vtt":"text/vtt","woff":"font/woff","woff2":"font/woff2","otf":"font/otf","ttf":"font/ttf","sfnt":"font/sfnt","svg":"image/svg+xml","txt":"text/plain","xsl":"text/xsl"};return extensionToMIMEType[extension]||null;};WI.fileExtensionForMIMEType=function(mimeType) {if(!mimeType) return null;const mimeTypeToExtension={"text/html":"html","application/xhtml+xml":"xhtml","application/xml":"xml","text/xml":"xml","application/ecmascript":"js","application/javascript":"js","application/x-ecmascript":"js","application/x-javascript":"js","text/ecmascript":"js","text/javascript":"js","text/javascript1.0":"js","text/javascript1.1":"js","text/javascript1.2":"js","text/javascript1.3":"js","text/javascript1.4":"js","text/javascript1.5":"js","text/jscript":"js","text/x-ecmascript":"js","text/x-javascript":"js","application/json":"json","text/x-clojure":"clj","text/x-coffeescript":"coffee","text/livescript":"ls","text/x-livescript":"ls","text/typescript":"ts","application/postscript":"ps","text/jsx":"jsx","text/css":"css","text/x-less":"less","text/x-sass":"sass","text/x-scss":"scss","image/avif":"avif","image/bmp":"bmp","image/gif":"gif","image/vnd.microsoft.icon":"ico","image/x-icon":"ico","image/jp2":"jp2","image/jpeg":"jpg","image/jxl":"jxl","application/pdf":"pdf","text/pdf":"pdf","image/png":"png","image/tiff":"tiff","image/webp":"webp","image/x-xbitmap":"xbm","application/ogg":"ogx","audio/ogg":"ogg","application/annodex":"anx","audio/annodex":"axa","video/annodex":"axv","audio/speex":"spx","video/webm":"webm","audio/webm":"webm","video/mpeg":"mpeg","application/vnd.apple.mpegurl":"m3u8","application/mpegurl":"m3u8","application/x-mpegurl":"m3u8","audio/mpegurl":"m3u","audio/x-mpegurl":"m3u","video/x-m4v":"m4v","audio/x-m4a":"m4a","audio/x-m4b":"m4b","audio/x-m4p":"m4p","audio/mp4":"m4a","audio/mp3":"mp3","audio/x-mp3":"mp3","audio/x-mpeg":"mp3","video/x-mpeg2":"mp2","video/mpeg2":"vob","video/m2ts":"m2ts","video/x-m2ts":"m2t","audio/3gpp":"3gpp","audio/3gpp2":"3g2","application/x-mpeg":"amc","audio/aac":"aac","audio/x-aac":"m4r","audio/x-caf":"caf","audio/x-gsm":"gsm","audio/x-wav":"wav","audio/vnd.wave":"wav","text/vtt":"vtt","font/woff":"woff","font/woff2":"woff2","font/otf":"otf","font/ttf":"ttf","font/sfnt":"sfnt","image/svg+xml":"svg","text/plain":"txt","text/xsl":"xsl",};let extension=mimeTypeToExtension[mimeType];if(extension) return extension;if(mimeType.endsWith("+json")) return"json";if(mimeType.endsWith("+xml")) return"xml";return null;};WI.shouldTreatMIMETypeAsText=function(mimeType) {if(!mimeType) return false;if(mimeType.startsWith("text/")) return true;if(mimeType.endsWith("+json")||mimeType.endsWith("+xml")) return true;let extension=WI.fileExtensionForMIMEType(mimeType);if(extension==="xml") return true;if(extension==="js"||extension==="json") return true;if(extension==="m3u8"||extension==="m3u") return true;if(mimeType.startsWith("application/")) return mimeType.endsWith("script")||mimeType.endsWith("json")||mimeType.endsWith("xml");return false;};WI.ObjectStore=class ObjectStore {constructor(name,options={}) {this._name=name;this._options=options;} static supported() {return(!window.InspectorTest||WI.ObjectStore.__testObjectStore)&&window.indexedDB;} static async reset() {if(WI.ObjectStore._database) WI.ObjectStore._database.close();await window.indexedDB.deleteDatabase(ObjectStore._databaseName);} static get _databaseName() {let inspectionLevel=InspectorFrontendHost?InspectorFrontendHost.inspectionLevel:1;let levelString=(inspectionLevel>1)?"-"+inspectionLevel:"";return"com.apple.WebInspector"+levelString;} static _open(callback) {if(WI.ObjectStore._database){callback(WI.ObjectStore._database);return;} if(Array.isArray(WI.ObjectStore._databaseCallbacks)){WI.ObjectStore._databaseCallbacks.push(callback);return;} WI.ObjectStore._databaseCallbacks=[callback];const version=8;let databaseRequest=window.indexedDB.open(WI.ObjectStore._databaseName,version);databaseRequest.addEventListener("upgradeneeded",(event)=>{let database=databaseRequest.result;let objectStores=Object.values(WI.objectStores);if(WI.ObjectStore.__testObjectStore) objectStores.push(WI.ObjectStore.__testObjectStore);let existingNames=new Set;for(let objectStore of objectStores){if(!database.objectStoreNames.contains(objectStore._name)) database.createObjectStore(objectStore._name,objectStore._options);existingNames.add(objectStore._name);} for(let objectStoreName of database.objectStoreNames){if(!existingNames.has(objectStoreName)) database.deleteObjectStore(objectStoreName);}});databaseRequest.addEventListener("success",(successEvent)=>{WI.ObjectStore._database=databaseRequest.result;WI.ObjectStore._database.addEventListener("close",(closeEvent)=>{WI.ObjectStore._database=null;});for(let databaseCallback of WI.ObjectStore._databaseCallbacks) databaseCallback(WI.ObjectStore._database);WI.ObjectStore._databaseCallbacks=null;});} get keyPath() {return(this._options||{}).keyPath;} associateObject(object,key,value) {if(typeof value==="object") value=this._resolveKeyPath(value,key).value;let resolved=this._resolveKeyPath(object,key);resolved.object[resolved.key]=value;} async get(...args) {if(!WI.ObjectStore.supported()) return undefined;return this._operation("readonly",(objectStore)=>objectStore.get(...args));} async getAll(...args) {if(!WI.ObjectStore.supported()) return[];return this._operation("readonly",(objectStore)=>objectStore.getAll(...args));} async getAllKeys(...args) {if(!WI.ObjectStore.supported()) return[];return this._operation("readonly",(objectStore)=>objectStore.getAllKeys(...args));} async put(...args) {if(!WI.ObjectStore.supported()) return undefined;return this._operation("readwrite",(objectStore)=>objectStore.put(...args));} async putObject(object,...args) {if(!WI.ObjectStore.supported()) return undefined;let result=await this.put(object.toJSON(WI.ObjectStore.toJSONSymbol),...args);this.associateObject(object,args[0],result);return result;} async delete(...args) {if(!WI.ObjectStore.supported()) return undefined;return this._operation("readwrite",(objectStore)=>objectStore.delete(...args));} async deleteObject(object,...args) {if(!WI.ObjectStore.supported()) return undefined;return this.delete(this._resolveKeyPath(object).value,...args);} async clear(...args) {if(!WI.ObjectStore.supported()) return undefined;return this._operation("readwrite",(objectStore)=>objectStore.clear(...args));} _resolveKeyPath(object,keyPath) {keyPath=keyPath||this._options.keyPath||"";let parts=keyPath.split(".");let key=parts.splice(-1,1);while(parts.length){if(!object.hasOwnProperty(parts[0])) break;object=object[parts.shift()];} if(parts.length) key=parts.join(".")+"."+key;return{object,key,value:object[key],};} async _operation(mode,func) { return new Promise((resolve,reject)=>{WI.ObjectStore._open((database)=>{let transaction=database.transaction([this._name],mode);let objectStore=transaction.objectStore(this._name);let request=null;try{request=func(objectStore);}catch(e){reject(e);return;} function listener(event){transaction.removeEventListener("complete",listener);transaction.removeEventListener("error",listener);request.removeEventListener("success",listener);request.removeEventListener("error",listener);if(request.error){reject(request.error);return;} resolve(request.result);} transaction.addEventListener("complete",listener,{once:true});transaction.addEventListener("error",listener,{once:true});request.addEventListener("success",listener,{once:true});request.addEventListener("error",listener,{once:true});});});}};WI.ObjectStore._database=null;WI.ObjectStore._databaseCallbacks=null;WI.ObjectStore.toJSONSymbol=Symbol("ObjectStore-toJSON");WI.objectStores={ audits:new WI.ObjectStore("audit-manager-tests",{keyPath:"__id",autoIncrement:true}), breakpoints:new WI.ObjectStore("debugger-breakpoints",{keyPath:"__id"}), domBreakpoints:new WI.ObjectStore("dom-debugger-dom-breakpoints",{keyPath:"__id"}),eventBreakpoints:new WI.ObjectStore("dom-debugger-event-breakpoints",{keyPath:"__id"}),urlBreakpoints:new WI.ObjectStore("dom-debugger-url-breakpoints",{keyPath:"__id"}), localResourceOverrides:new WI.ObjectStore("local-resource-overrides",{keyPath:"__id"}), general:new WI.ObjectStore("general"), cssPropertyNameCounts:new WI.ObjectStore("css-property-name-counts"), symbolicBreakpoints:new WI.ObjectStore("debugger-symbolic-breakpoints",{keyPath:"__id"}), consoleSnippets:new WI.ObjectStore("console-snippets",{keyPath:"__id"}),};function removeURLFragment(url) {var hashIndex=url.indexOf("#");if(hashIndex>=0) return url.substring(0,hashIndex);return url;} function relativePath(path,basePath) {var pathComponents=path.split("/");var baseComponents=basePath.replace(/\/$/,"").split("/");var finalComponents=[];var index=1;for(;index[^:]+):\/\/(?[^\/:]*)(?::(?[\d]+))?$/i);if(!match) return{scheme:null,host:null,port:null};let scheme=match.groups.scheme.toLowerCase();let host=match.groups.host.toLowerCase();let port=Number(match.groups.port)||null;return{scheme,host,port};} function parseDataURL(url) {if(!url.startsWith("data:")) return null;let match=url.match(/^data:(?[^;,]*)?(?:;charset=(?[^;,]*?))?(?;base64)?,(?.*)$/);if(!match) return null;let scheme="data";let mimeType=match.groups.mime||"text/plain";let charset=match.groups.charset||"US-ASCII";let base64=!!match.groups.base64;let data=decodeURIComponent(match.groups.data);return{scheme,mimeType,charset,base64,data};} function parseURL(url) {let result={scheme:null,userinfo:null,host:null,port:null,origin:null,path:null,queryString:null,fragment:null,lastPathComponent:null,};if(url&&url.startsWith("data:")){result.scheme="data";return result;} if(isWebKitInternalScript(url)) return result;let parsed=null;try{parsed=new URL(url);}catch{return result;} result.scheme=parsed.protocol.slice(0,-1);if(parsed.username) result.userinfo=parsed.username;if(parsed.password) result.userinfo=(result.userinfo||"")+":"+parsed.password;if(parsed.hostname) result.host=parsed.hostname;if(parsed.port) result.port=Number(parsed.port);if(parsed.origin&&parsed.origin!=="null") result.origin=parsed.origin;else if(result.scheme&&result.host){result.origin=result.scheme+"://"+result.host;if(result.port) result.origin+=":"+result.port;} if(parsed.pathname) result.path=parsed.pathname;if(parsed.search) result.queryString=parsed.search.substring(1);if(parsed.hash) result.fragment=parsed.hash.substring(1);if(result.path&&result.path!=="/"){let endOffset=result.path.endsWith("/")?1:0;let lastSlashIndex=result.path.lastIndexOf("/",result.path.length-1-endOffset);if(lastSlashIndex!==-1) result.lastPathComponent=result.path.substring(lastSlashIndex+1,result.path.length-endOffset);} return result;} function absoluteURL(partialURL,baseURL) {partialURL=partialURL?partialURL.trim():"";if(partialURL.startsWith("data:")||partialURL.startsWith("javascript:")||partialURL.startsWith("mailto:")) return partialURL;if(parseURL(partialURL).scheme) return partialURL;if(!partialURL) return baseURL||null;var baseURLComponents=parseURL(baseURL);if(!baseURLComponents.scheme) return null;if(partialURL[0]==="/"&&partialURL[1]==="/") return baseURLComponents.scheme+":"+partialURL;if(!baseURLComponents.path) baseURLComponents.path="/";var baseURLPrefix=baseURLComponents.scheme+"://"+baseURLComponents.host+(baseURLComponents.port?(":"+baseURLComponents.port):"");if(partialURL[0]==="?") return baseURLPrefix+baseURLComponents.path+partialURL;if(partialURL[0]==="/") return baseURLPrefix+resolveDotsInPath(partialURL);if(partialURL[0]==="#"){let queryStringComponent=baseURLComponents.queryString?"?"+baseURLComponents.queryString:"";return baseURLPrefix+baseURLComponents.path+queryStringComponent+partialURL;} var basePath=baseURLComponents.path.substring(0,baseURLComponents.path.lastIndexOf("/"))+"/";return baseURLPrefix+resolveDotsInPath(basePath+partialURL);} function parseQueryString(queryString,arrayResult) {if(!queryString) return arrayResult?[]:{};function decode(string) {try{return decodeURIComponent(string.replace(/\+/g," "));}catch{return string;}} var parameters=arrayResult?[]:{};for(let parameterString of queryString.split("&")){let index=parameterString.indexOf("=");if(index===-1) index=parameterString.length;let name=decode(parameterString.substring(0,index));let value=decode(parameterString.substring(index+1));if(arrayResult) parameters.push({name,value});else parameters[name]=value;} return parameters;} WI.displayNameForURL=function(url,urlComponents,options={}) {if(url.startsWith("data:")) return WI.truncateURL(url);if(!urlComponents) urlComponents=parseURL(url);var displayName;try{displayName=decodeURIComponent(urlComponents.lastPathComponent||"");}catch{displayName=urlComponents.lastPathComponent;} if(options.allowDirectoryAsName&&(urlComponents.path==="/"||(displayName&&urlComponents.path.endsWith(displayName+"/")))) displayName="/";return displayName||WI.displayNameForHost(urlComponents.host)||url;};WI.truncateURL=function(url,multiline=false,dataURIMaxSize=6) {if(!url.startsWith("data:")) return url;const dataIndex=url.indexOf(",")+1;let header=url.slice(0,dataIndex);if(multiline) header+="\n";const data=url.slice(dataIndex);if(data.length=0;--i){if(stopCharacters.indexOf(node.nodeValue[i])!==-1){startNode=node;startOffset=i+1;break;}}} if(startNode) break;node=node.traversePreviousNode(stayWithinNode);} if(!startNode){startNode=stayWithinNode;startOffset=0;}}else{startNode=this;startOffset=offset;} if(!direction||direction==="forward"||direction==="both"){node=this;while(node){if(node===stayWithinNode){if(!endNode) endNode=stayWithinNode;break;} if(node.nodeType===Node.TEXT_NODE){let start=node===this?offset:0;for(var i=start;i{this[fontSymbol]||=window.getComputedStyle(this).font;context.font=this[fontSymbol];let textMetrics=context.measureText(this.value||this.placeholder);this.style.setProperty("width",(textMetrics.width+extra)+"px");});},});})();Object.defineProperty(HTMLCollection.prototype,"indexOf",{value(element) {let length=this.length;for(let i=0;ieditCount){break;} for(let j=0;jeditCount){break;} if(comparator(initialArray[i],currentArray[j])){if(newEditCount=0;--i){if(this[i]===value) this.splice(i,1);}}});Object.defineProperty(Array.prototype,"toggleIncludes",{value(value,force) {let exists=this.includes(value);if(force!==undefined&&exists===!!force) return;if(exists) this.remove(value);else this.push(value);}});Object.defineProperty(Array.prototype,"insertAtIndex",{value(value,index) {this.splice(index,0,value);}});Object.defineProperty(Array.prototype,"pushAll",{value(iterable) {for(let item of iterable) this.push(item);},});Object.defineProperty(Array.prototype,"partition",{value(callback) {let positive=[];let negative=[];for(let i=0;i>1;var rightHalf=maxLength-leftHalf-1;return this.substr(0,leftHalf)+ellipsis+this.substr(this.length-rightHalf,rightHalf);}});Object.defineProperty(String.prototype,"truncateEnd",{value(maxLength) {"use strict";if(this.length<=maxLength) return this;return this.substr(0,maxLength-1)+ellipsis;}});Object.defineProperty(String.prototype,"truncate",{value(maxLength) {"use strict";if(this.length<=maxLength) return this;let clipped=this.slice(0,maxLength);let indexOfLastWhitespace=clipped.search(/\s\S*$/);if(indexOfLastWhitespace>Math.floor(maxLength/2)) clipped=clipped.slice(0,indexOfLastWhitespace-1);return clipped+ellipsis;}});Object.defineProperty(String.prototype,"collapseWhitespace",{value() {return this.replace(/[\s\xA0]+/g," ");}});Object.defineProperty(String.prototype,"removeWhitespace",{value() {return this.replace(/[\s\xA0]+/g,"");}});Object.defineProperty(String.prototype,"escapeCharacters",{value(charactersToEscape) {if(!charactersToEscape) return this.valueOf();let charactersToEscapeSet=new Set(charactersToEscape);let foundCharacter=false;for(let c of this){if(!charactersToEscapeSet.has(c)) continue;foundCharacter=true;break;} if(!foundCharacter) return this.valueOf();let result="";for(let c of this){if(charactersToEscapeSet.has(c)) result+="\\";result+=c;} return result.valueOf();}});Object.defineProperty(String.prototype,"escapeForRegExp",{value() {return this.escapeCharacters("^[]{}()\\.$*+?|");}});Object.defineProperty(String.prototype,"capitalize",{value() {return this.charAt(0).toUpperCase()+this.slice(1);}});Object.defineProperty(String.prototype,"extendedLocaleCompare",{value(other) {return this.localeCompare(other,undefined,{numeric:true});}});Object.defineProperty(String,"tokenizeFormatString",{value(format) {var tokens=[];var substitutionIndex=0;function addStringToken(str) {tokens.push({type:"string",value:str});} function addSpecifierToken(specifier,precision,substitutionIndex) {tokens.push({type:"specifier",specifier,precision,substitutionIndex});} var index=0;for(var precentIndex=format.indexOf("%",index);precentIndex!==-1;precentIndex=format.indexOf("%",index)){addStringToken(format.substring(index,precentIndex));index=precentIndex+1;if(format[index]==="%"){addStringToken("%");++index;continue;} if(!isNaN(format[index])){var number=parseInt(format.substring(index),10);while(!isNaN(format[index])) ++index;if(number>0&&format[index]==="$"){substitutionIndex=(number-1);++index;}} const defaultPrecision=6;let precision=defaultPrecision;if(format[index]==="."){++index;precision=parseInt(format.substring(index),10);if(isNaN(precision)) precision=defaultPrecision;while(!isNaN(format[index])) ++index;} addSpecifierToken(format[index],precision,substitutionIndex);++substitutionIndex;++index;} addStringToken(format.substring(index));return tokens;}});Object.defineProperty(String.prototype,"lineCount",{get() {"use strict";let lineCount=1;let index=0;while(true){index=this.indexOf("\n",index);if(index===-1) return lineCount;index+="\n".length;lineCount++;}}});Object.defineProperty(String.prototype,"lastLine",{get() {"use strict";let index=this.lastIndexOf("\n");if(index===-1) return this;return this.slice(index+"\n".length);}});Object.defineProperty(String.prototype,"hash",{get() {const stringHashingStartValue=0x9e3779b9;var result=stringHashingStartValue;var pendingCharacter=null;for(var i=0;i>11;pendingCharacter=null;} if(pendingCharacter!==null){result+=pendingCharacter;result^=result<<11;result+=result>>17;} result^=result<<3;result+=result>>5;result^=result<<2;result+=result>>15;result^=result<<10;return(0xffffffff+result+1).toString(36);}});Object.defineProperty(String,"standardFormatters",{value:{d:function(substitution) {return parseInt(substitution).toLocaleString();},f:function(substitution,token) {let value=parseFloat(substitution);if(isNaN(value)) return NaN;let options={minimumFractionDigits:token.precision,maximumFractionDigits:token.precision,useGrouping:false};return value.toLocaleString(undefined,options);},s:function(substitution) {return substitution;}}});Object.defineProperty(String,"format",{value(format,substitutions,formatters,initialValue,append) {if(!format||!substitutions||!substitutions.length) return{formattedResult:append(initialValue,format),unusedSubstitutions:substitutions};function prettyFunctionName() {return"String.format(\""+format+"\", \""+Array.from(substitutions).join("\", \"")+"\")";} function warn(msg) {console.warn(prettyFunctionName()+": "+msg);} function error(msg) {console.error(prettyFunctionName()+": "+msg);} var result=initialValue;var tokens=String.tokenizeFormatString(format);var usedSubstitutionIndexes={};let ignoredUnknownSpecifierCount=0;for(var i=0;i=substitutions.length){ error("not enough substitution arguments. Had "+substitutions.length+" but needed "+(substitutionIndex+1)+", so substitution was skipped.");result=append(result,"%"+(token.precision>-1?token.precision:"")+token.specifier);continue;} if(!(token.specifier in formatters)){warn(`Unsupported format specifier "%${token.specifier}" will be ignored.`);result=append(result,"%"+token.specifier);++ignoredUnknownSpecifierCount;continue;} usedSubstitutionIndexes[substitutionIndex]=true;result=append(result,formatters[token.specifier](substitutions[substitutionIndex],token));} var unusedSubstitutions=[];for(var i=0;igroup.toUpperCase());}});Object.defineProperty(String.prototype,"hasMatchingEscapedQuotes",{value() {return/^\"(?:[^\"\\]|\\.)*\"$/.test(this) || /^\'(?:[^\'\\]|\\.)*\'$/.test(this); } }); Object.defineProperty(Math, "roundTo", { value(num, step) { return Math.round(num / step) * step; } }); // https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Matrix_math_for_the_web#Multiplying_a_matrix_and_a_point Object.defineProperty(Math, "multiplyMatrixByVector", { value(matrix, vector) { let height = matrix.length; let width = matrix[0].length; let result = Array(width).fill(0); for (let i = 0; i < width; ++i) { for (let rowIndex = 0; rowIndex < height; ++rowIndex) result[i] += vector[rowIndex] * matrix[i][rowIndex]; } return result; } }); Object.defineProperty(Number, "constrain", { value(num, min, max) { if (isNaN(num) || max < min) return min; if (num < min) num = min; else if (num > max) num = max; return num; } }); Object.defineProperty(Number, "percentageString", { value(fraction, precision = 1) { return fraction.toLocaleString(undefined, {minimumFractionDigits: precision, style: "percent"}); } }); Object.defineProperty(Number, "secondsToMillisecondsString", { value(seconds, higherResolution) { let ms = seconds * 1000; if (higherResolution) return WI.UIString("%.2fms").format(ms); return WI.UIString("%.1fms").format(ms); } }); Object.defineProperty(Number, "secondsToString", { value(seconds, higherResolution) { const epsilon = 0.0001; let ms = seconds * 1000; if (ms < epsilon) return WI.UIString("%.0fms").format(0); if (Math.abs(ms) < (10 + epsilon)) { if (higherResolution) return WI.UIString("%.3fms").format(ms); return WI.UIString("%.2fms").format(ms); } if (Math.abs(ms) < (100 + epsilon)) { if (higherResolution) return WI.UIString("%.2fms").format(ms); return WI.UIString("%.1fms").format(ms); } if (Math.abs(ms) < (1000 + epsilon)) { if (higherResolution) return WI.UIString("%.1fms").format(ms); return WI.UIString("%.0fms").format(ms); } // Do not go over seconds when in high resolution mode. if (higherResolution || Math.abs(seconds) < 60) return WI.UIString("%.2fs").format(seconds); let minutes = seconds / 60; if (Math.abs(minutes) < 60) return WI.UIString("%.1fmin").format(minutes); let hours = minutes / 60; if (Math.abs(hours) < 24) return WI.UIString("%.1fhrs").format(hours); let days = hours / 24; return WI.UIString("%.1f days").format(days); } }); Object.defineProperty(Number, "bytesToString", { value(bytes, higherResolution, bytesThreshold) { higherResolution ??= true; bytesThreshold ??= 1000; if (Math.abs(bytes) < bytesThreshold) return WI.UIString("%.0f B").format(bytes); let kilobytes = bytes / 1000; if (Math.abs(kilobytes) < 1000) { if (higherResolution || Math.abs(kilobytes) < 10) return WI.UIString("%.2f KB").format(kilobytes); return WI.UIString("%.1f KB").format(kilobytes); } let megabytes = kilobytes / 1000; if (Math.abs(megabytes) < 1000) { if (higherResolution || Math.abs(megabytes) < 10) return WI.UIString("%.2f MB").format(megabytes); return WI.UIString("%.1f MB").format(megabytes); } let gigabytes = megabytes / 1000; if (higherResolution || Math.abs(gigabytes) < 10) return WI.UIString("%.2f GB").format(gigabytes); return WI.UIString("%.1f GB").format(gigabytes); } }); Object.defineProperty(Number, "abbreviate", { value(num) { if (num < 1000) return num.toLocaleString(); if (num < 1_000_000) return WI.UIString("%.1fK").format(Math.round(num / 100) / 10); if (num < 1_000_000_000) return WI.UIString("%.1fM").format(Math.round(num / 100_000) / 10); return WI.UIString("%.1fB").format(Math.round(num / 100_000_000) / 10); } }); Object.defineProperty(Number, "zeroPad", { value(num, length) { let string = num.toLocaleString(); return string.padStart(length, "0"); }, }); Object.defineProperty(Number, "countDigits", { value(num) { if (num === 0) return 1; num = Math.abs(num); return Math.floor(Math.log(num) * Math.LOG10E) + 1; } }); Object.defineProperty(Number.prototype, "maxDecimals", { value(decimals) { let power = 10 ** decimals; return Math.round(this * power) / power; } }); Object.defineProperty(Uint32Array, "isLittleEndian", { value() { if ("_isLittleEndian" in this) return this._isLittleEndian; var buffer = new ArrayBuffer(4); var longData = new Uint32Array(buffer); var data = new Uint8Array(buffer); longData[0] = 0x0a0b0c0d; this._isLittleEndian = data[0] === 0x0d && data[1] === 0x0c && data[2] === 0x0b && data[3] === 0x0a; return this._isLittleEndian; } }); function isEmptyObject(object) { for (var property in object) return false; return true; } function isEnterKey(event) { // Check if this is an IME event. return event.keyCode !== 229 && event.keyIdentifier === "Enter"; } function resolveDotsInPath(path) { if (!path) return path; if (path.indexOf("./") === -1) return path; var result = []; var components = path.split("/"); for (var i = 0; i < components.length; ++i) { var component = components[i]; // Skip over "./". if (component === ".") continue; // Rewind one component for "../". if (component === "..") { if (result.length === 1) continue; result.pop(); continue; } result.push(component); } return result.join("/"); } function parseMIMEType(fullMimeType) { if (!fullMimeType) return {type: fullMimeType, boundary: null, encoding: null}; var typeParts = fullMimeType.split(/\s*;\s*/); var type = typeParts[0]; var boundary = null; var encoding = null; for (var i = 1; i < typeParts.length; ++i) { var subparts = typeParts[i].split(/\s*=\s*/); if (subparts.length !== 2) continue; if (subparts[0].toLowerCase() === "boundary") boundary = subparts[1]; else if (subparts[0].toLowerCase() === "charset") encoding = subparts[1].replace("^\"|\"$","");} return{type,boundary:boundary||null,encoding:encoding||null};} function simpleGlobStringToRegExp(globString,regExpFlags) {if(!globString) return null;var regexString=globString.escapeCharacters("^[]{}()\\.$+?|");regexString=regexString.replace(/\\\\\*/g,"\\*");var unescapedAsteriskRegex=/(^|[^\\])\*+/g;if(unescapedAsteriskRegex.test(globString)){regexString=regexString.replace(unescapedAsteriskRegex,"$1.*"); regexString="\\b"+regexString+"\\b";} return new RegExp(regexString,regExpFlags);} Object.defineProperty(Array.prototype,"min",{value(comparator) {return this[this.minIndex(comparator)];},});Object.defineProperty(Array.prototype,"minIndex",{value(comparator) {function defaultComparator(a,b) {return a-b;} comparator=comparator||defaultComparator;let minIndex=-1;for(let i=0;i0) minIndex=i;} return minIndex;},});Object.defineProperty(Array.prototype,"lowerBound",{ value(object,comparator) {function defaultComparator(a,b) {return a-b;} comparator=comparator||defaultComparator;var l=0;var r=this.length;while(l>1;if(comparator(object,this[m])>0) l=m+1;else r=m;} return r;}});Object.defineProperty(Array.prototype,"upperBound",{ value(object,comparator) {function defaultComparator(a,b) {return a-b;} comparator=comparator||defaultComparator;var l=0;var r=this.length;while(l>1;if(comparator(object,this[m])>=0) l=m+1;else r=m;} return r;}});Object.defineProperty(Array.prototype,"binaryIndexOf",{value(value,comparator) {function defaultComparator(a,b) {return a-b;} comparator=comparator||defaultComparator;var index=this.lowerBound(value,comparator);return indexsetTimeout(resolve,delay||0));}});function appendWebInspectorSourceURL(string) {if(string.includes("//# sourceURL")) return string;return"\n//# sourceURL=__WebInspectorInternal__\n"+string;} function appendWebInspectorConsoleEvaluationSourceURL(string) {if(string.includes("//# sourceURL")) return string;return"\n//# sourceURL=__WebInspectorConsoleEvaluation__\n"+string;} function isWebInspectorBootstrapScript(url) {return url===WI.NetworkManager.bootstrapScriptURL;} function isWebInspectorInternalScript(url) {return url==="__WebInspectorInternal__";} function isWebInspectorConsoleEvaluationScript(url) {return url==="__WebInspectorConsoleEvaluation__";} function isWebKitInjectedScript(url) {return url&&url.startsWith("__InjectedScript_")&&url.endsWith(".js");} function isWebKitInternalScript(url) {if(isWebInspectorConsoleEvaluationScript(url)) return false;if(isWebKitInjectedScript(url)) return true;return url&&url.startsWith("__Web")&&url.endsWith("__");} function isFunctionStringNativeCode(str) {return str.endsWith("{\n [native code]\n}");} function whitespaceRatio(content,start,end) {let whitespaceScore=0;let size=end-start;for(let i=start;i{if(settings.caseSensitive){contextMenu.appendCheckboxItem(WI.UIString("Case Sensitive","Case Sensitive @ Context Menu","Context menu label for whether searches should be case sensitive."),()=>{settings.caseSensitive.value=!settings.caseSensitive.value;},settings.caseSensitive.value);} if(settings.regularExpression){contextMenu.appendCheckboxItem(WI.UIString("Regular Expression","Regular Expression @ Context Menu","Context menu label for whether searches should be treated as regular expressions."),()=>{settings.regularExpression.value=!settings.regularExpression.value;},settings.regularExpression.value);}});button.appendChild(WI.ImageUtilities.useSVGSymbol("Images/Gear.svg","glyph"));function toggleActive(){button.classList.toggle("active",Object.values(settings).some((setting)=>!!setting.value));} settings.caseSensitive.addEventListener(WI.Setting.Event.Changed,toggleActive,button);settings.regularExpression.addEventListener(WI.Setting.Event.Changed,toggleActive,button);toggleActive();return button;} static _regExpForString(query,settings={},options={}) {function checkSetting(setting){return setting instanceof WI.Setting?setting.value:!!setting;} if(!checkSetting(settings.regularExpression)){try{query=simpleGlobStringToRegExp(String(query));}catch{return null;}} let flags="";if(options.global) flags+="g" if(!checkSetting(settings.caseSensitive)) flags+="i";try{return new RegExp(query,flags);}catch{return null;}}};WI.Setting=class Setting extends WI.Object {constructor(name,defaultValue) {super();this._name=name;this._defaultValue=defaultValue;} static migrateValue(key) {let localStorageKey=WI.Setting._localStorageKeyPrefix+key;let value=undefined;if(!window.InspectorTest&&window.localStorage){let item=window.localStorage.getItem(localStorageKey);if(item!==null){try{value=JSON.parse(item);}catch{} window.localStorage.removeItem(localStorageKey);}} return value;} static reset() {let prefix=WI.Setting._localStorageKeyPrefix;let keysToRemove=[];for(let i=0;i1?"-"+inspectionLevel:"";return`com.apple.WebInspector${levelString}.`;})();WI.Setting.isFirstLaunch=!!window.InspectorTest||(window.localStorage&&Object.keys(window.localStorage).every((key)=>!key.startsWith(WI.Setting._localStorageKeyPrefix)));WI.Setting.Event={Changed:"setting-changed"};WI.EngineeringSetting=class EngineeringSetting extends WI.Setting {get value() {if(WI.engineeringSettingsAllowed()) return super.value;return this.defaultValue;} set value(value) {if(WI.engineeringSettingsAllowed()) super.value=value;}};WI.DebugSetting=class DebugSetting extends WI.Setting {get value() {if(WI.isDebugUIEnabled()) return super.value;return this.defaultValue;} set value(value) {if(WI.isDebugUIEnabled()) super.value=value;}};WI.settings={blackboxBreakpointEvaluations:new WI.Setting("blackbox-breakpoint-evaluations",true),canvasRecordingAutoCaptureEnabled:new WI.Setting("canvas-recording-auto-capture-enabled",false),canvasRecordingAutoCaptureFrameCount:new WI.Setting("canvas-recording-auto-capture-frame-count",1),consoleAutoExpandTrace:new WI.Setting("console-auto-expand-trace",true),consoleSavedResultAlias:new WI.Setting("console-saved-result-alias",""),cssChangesPerNode:new WI.Setting("css-changes-per-node",false),clearLogOnNavigate:new WI.Setting("clear-log-on-navigate",true),clearNetworkOnNavigate:new WI.Setting("clear-network-on-navigate",true),cpuTimelineThreadDetailsExpanded:new WI.Setting("cpu-timeline-thread-details-expanded",false),domTreeDeemphasizesNodesThatAreNotRendered:new WI.Setting("dom-tree-deemphasizes-nodes-that-are-not-rendered",true),emulateInUserGesture:new WI.Setting("emulate-in-user-gesture",false),enableControlFlowProfiler:new WI.Setting("enable-control-flow-profiler",false),enableElementsTabIndependentStylesDetailsSidebarPanel:new WI.Setting("elements-tab-independent-styles-details-panel",true),enableLineWrapping:new WI.Setting("enable-line-wrapping",true),enableNarrowLayoutMode:new WI.Setting("enable-narrow-layout-mode",true),flexOverlayShowOrderNumbers:new WI.Setting("flex-overlay-show-order-numbers",false),frontendAppearance:new WI.Setting("frontend-appearance","system"),gridOverlayShowAreaNames:new WI.Setting("grid-overlay-show-area-names",false),gridOverlayShowExtendedGridLines:new WI.Setting("grid-overlay-show-extended-grid-lines",false),gridOverlayShowLineNames:new WI.Setting("grid-overlay-show-line-names",false),gridOverlayShowLineNumbers:new WI.Setting("grid-overlay-show-line-numbers",true),gridOverlayShowTrackSizes:new WI.Setting("grid-overlay-show-track-sizes",true),groupMediaRequestsByDOMNode:new WI.Setting("group-media-requests-by-dom-node",WI.Setting.migrateValue("group-by-dom-node")||false),indentUnit:new WI.Setting("indent-unit",4),indentWithTabs:new WI.Setting("indent-with-tabs",false),resourceCachingDisabled:new WI.Setting("disable-resource-caching",false),searchCaseSensitive:new WI.Setting("search-case-sensitive",false),searchFromSelection:new WI.Setting("search-from-selection",false),searchRegularExpression:new WI.Setting("search-regular-expression",false),selectedNetworkDetailContentViewIdentifier:new WI.Setting("network-detail-content-view-identifier","preview"),sourceMapsEnabled:new WI.Setting("source-maps-enabled",true),showConsoleMessageTimestamps:new WI.Setting("show-console-message-timestamps",false),showCSSPropertySyntaxInDocumentationPopover:new WI.Setting("show-css-property-syntax-in-documentation-popover",false),showCanvasPath:new WI.Setting("show-canvas-path",false),showFlexOverlayDuringElementSelection:new WI.Setting("show-grid-overlay-during-element-selection",true),showGridOverlayDuringElementSelection:new WI.Setting("show-flex-overlay-during-element-selection",true),showImageGrid:new WI.Setting("show-image-grid",true),showInvisibleCharacters:new WI.Setting("show-invisible-characters",!!WI.Setting.migrateValue("show-invalid-characters")),showJavaScriptTypeInformation:new WI.Setting("show-javascript-type-information",false),showRulers:new WI.Setting("show-rulers",false),showRulersDuringElementSelection:new WI.Setting("show-rulers-during-element-selection",true),showScopeChainOnPause:new WI.Setting("show-scope-chain-sidebar",true),showWhitespaceCharacters:new WI.Setting("show-whitespace-characters",false),tabSize:new WI.Setting("tab-size",4),timelinesAutoStop:new WI.Setting("timelines-auto-stop",true),timelineOverviewGroupBySourceCode:new WI.Setting("timeline-overview-group-by-source-code",true),zoomFactor:new WI.Setting("zoom-factor",1), experimentalEnableStylesJumpToEffective:new WI.Setting("experimental-styles-jump-to-effective",false),experimentalEnableStylesJumpToVariableDeclaration:new WI.Setting("experimental-styles-jump-to-variable-declaration",false),experimentalAllowInspectingInspector:new WI.Setting("experimental-allow-inspecting-inspector",false),experimentalCSSSortPropertyNameAutocompletionByUsage:new WI.Setting("experimental-css-sort-property-name-autocompletion-by-usage",true),experimentalEnableNetworkEmulatedCondition:new WI.Setting("experimental-enable-network-emulated-condition",false),experimentalGroupSourceMapErrors:new WI.Setting("experimental-group-source-map-errors",true),experimentalLimitSourceCodeHighlighting:new WI.Setting("engineering-limit-source-code-highlighting",false), protocolLogAsText:new WI.Setting("protocol-log-as-text",false),protocolAutoLogMessages:new WI.Setting("protocol-auto-log-messages",false),protocolAutoLogTimeStats:new WI.Setting("protocol-auto-log-time-stats",false),protocolFilterMultiplexingBackendMessages:new WI.Setting("protocol-filter-multiplexing-backend-messages",true), engineeringShowInternalExecutionContexts:new WI.EngineeringSetting("engineering-show-internal-execution-contexts",false),engineeringShowInternalScripts:new WI.EngineeringSetting("engineering-show-internal-scripts",false),engineeringPauseForInternalScripts:new WI.EngineeringSetting("engineering-pause-for-internal-scripts",false),engineeringShowInternalObjectsInHeapSnapshot:new WI.EngineeringSetting("engineering-show-internal-objects-in-heap-snapshot",false),engineeringShowPrivateSymbolsInHeapSnapshot:new WI.EngineeringSetting("engineering-show-private-symbols-in-heap-snapshot",false),engineeringAllowEditingUserAgentShadowTrees:new WI.EngineeringSetting("engineering-allow-editing-user-agent-shadow-trees",false), debugShowConsoleEvaluations:new WI.DebugSetting("debug-show-console-evaluations",false),debugOutlineFocusedElement:new WI.DebugSetting("debug-outline-focused-element",false),debugEnableLayoutFlashing:new WI.DebugSetting("debug-enable-layout-flashing",false),debugEnableStyleEditingDebugMode:new WI.DebugSetting("debug-enable-style-editing-debug-mode",false),debugEnableUncaughtExceptionReporter:new WI.DebugSetting("debug-enable-uncaught-exception-reporter",true),debugEnableDiagnosticLogging:new WI.DebugSetting("debug-enable-diagnostic-logging",true),debugAutoLogDiagnosticEvents:new WI.DebugSetting("debug-auto-log-diagnostic-events",false),debugLayoutDirection:new WI.DebugSetting("debug-layout-direction-override","system"),debugShowMockWebExtensionTab:new WI.DebugSetting("debug-show-mock-web-extension-tab",false),};WI.YieldableTask=class YieldableTask {constructor(delegate,items,options={}) {let{workInterval,idleInterval}=options;this._workInterval=workInterval||10;this._idleInterval=idleInterval||0;this._delegate=delegate;this._items=items;this._idleTimeoutIdentifier=undefined;this._processing=false;this._processing=false;this._cancelled=false;} get processing(){return this._processing;} get cancelled(){return this._cancelled;} get idleInterval(){return this._idleInterval;} get workInterval(){return this._workInterval;} start() {if(this._processing) return;if(this._cancelled) return;function*createIteratorForProcessingItems() {let startTime=Date.now();let processedItems=[];for(let item of this._items){if(this._cancelled) break;this._delegate.yieldableTaskWillProcessItem(this,item);processedItems.push(item);if(this._cancelled) break;let elapsedTime=Date.now()-startTime;if(elapsedTime>this._workInterval){let returnedItems=processedItems.slice();processedItems=[];this._willYield(returnedItems,elapsedTime);yield;startTime=Date.now();}} if(processedItems.length) this._willYield(processedItems,Date.now()-startTime);} this._processing=true;this._pendingItemsIterator=createIteratorForProcessingItems.call(this);this._processPendingItems();} cancel() {if(!this._processing) return;this._cancelled=true;} _processPendingItems() {if(this._cancelled) return;if(!this._pendingItemsIterator.next().done){this._idleTimeoutIdentifier=setTimeout(()=>{this._processPendingItems();},this._idleInterval);return;} this._didFinish();} _willYield(processedItems,elapsedTime) {if(typeof this._delegate.yieldableTaskDidYield==="function") this._delegate.yieldableTaskDidYield(this,processedItems,elapsedTime);} _didFinish() {this._processing=false;this._pendingItemsIterator=null;if(this._idleTimeoutIdentifier){clearTimeout(this._idleTimeoutIdentifier);this._idleTimeoutIdentifier=undefined;} if(typeof this._delegate.yieldableTaskDidFinish==="function") this._delegate.yieldableTaskDidFinish(this);}};Object.defineProperty(File.prototype,"getPath",{value(){return InspectorFrontendHost.getPath(this);},});Object.defineProperty(CanvasRenderingContext2D.prototype,"currentX",{get(){return InspectorFrontendHost.getCurrentX(this);},});Object.defineProperty(CanvasRenderingContext2D.prototype,"currentY",{get(){return InspectorFrontendHost.getCurrentY(this);},});Object.defineProperty(CanvasRenderingContext2D.prototype,"getPath",{value(){return InspectorFrontendHost.getPath(this);},});Object.defineProperty(CanvasRenderingContext2D.prototype,"setPath",{value(path){return InspectorFrontendHost.setPath(this,path);},});if(window.OffscreenCanvasRenderingContext2D){Object.defineProperty(OffscreenCanvasRenderingContext2D.prototype,"currentX",{get(){return InspectorFrontendHost.getCurrentX(this);},});Object.defineProperty(OffscreenCanvasRenderingContext2D.prototype,"currentY",{get(){return InspectorFrontendHost.getCurrentY(this);},});Object.defineProperty(OffscreenCanvasRenderingContext2D.prototype,"getPath",{value(){return InspectorFrontendHost.getPath(this);},});Object.defineProperty(OffscreenCanvasRenderingContext2D.prototype,"setPath",{value(path){return InspectorFrontendHost.setPath(this,path);},});} WI.ProtocolTracer=class ProtocolTracer { logStarted() {} logFrontendException(connection,message,exception) {} logFrontendRequest(connection,message) {} logWillHandleResponse(connection,message) {} logDidHandleResponse(connection,message,timings=null) {} logWillHandleEvent(connection,message) {} logDidHandleEvent(connection,message,timings=null) {} logFinished() {}};WI.LoggingProtocolTracer=class LoggingProtocolTracer extends WI.ProtocolTracer {constructor() {super();this._dumpMessagesToConsole=false;this._dumpTimingDataToConsole=false;this._filterMultiplexingBackend=true;this._logToConsole=window.InspectorTest?InspectorFrontendHost.unbufferedLog.bind(InspectorFrontendHost):console.log;} set dumpMessagesToConsole(value) {this._dumpMessagesToConsole=!!value;} get dumpMessagesToConsole() {return this._dumpMessagesToConsole;} set dumpTimingDataToConsole(value) {this._dumpTimingDataToConsole=!!value;} get dumpTimingDataToConsole() {return this._dumpTimingDataToConsole;} set filterMultiplexingBackend(value) {this._filterMultiplexingBackend=!!value;} get filterMultiplexingBackend() {return this._filterMultiplexingBackend;} logFrontendException(connection,message,exception) {this._processEntry({type:"exception",connection,message,exception});} logFrontendRequest(connection,message) {this._processEntry({type:"request",connection,message});} logWillHandleResponse(connection,message) {let entry={type:"response",connection,message};this._processEntry(entry);} logDidHandleResponse(connection,message,timings=null) {let entry={type:"response",connection,message};if(timings) entry.timings=Object.shallowCopy(timings);this._processEntry(entry);} logWillHandleEvent(connection,message) {let entry={type:"event",connection,message};this._processEntry(entry);} logDidHandleEvent(connection,message,timings=null) {let entry={type:"event",connection,message};if(timings) entry.timings=Object.shallowCopy(timings);this._processEntry(entry);} _processEntry(entry) {if(this._dumpTimingDataToConsole&&entry.timings){if(entry.timings.rtt&&entry.timings.dispatch) this._logToConsole(`time-stats: Handling: ${entry.timings.dispatch || NaN}ms; RTT: ${entry.timings.rtt}ms`);else if(entry.timings.dispatch) this._logToConsole(`time-stats: Handling: ${entry.timings.dispatch || NaN}ms`);}else if(this._dumpMessagesToConsole&&!entry.timings){let connection=entry.connection;let targetId=connection&&connection.target?connection.target.identifier:"unknown";if(this._filterMultiplexingBackend&&targetId==="multi") return;let prefix=`${entry.type} (${targetId})`;if(!window.InspectorTest&&InspectorFrontendHost.isBeingInspected()&&!WI.settings.protocolLogAsText.value){if(entry.type==="request"||entry.type==="exception") console.trace(prefix,entry.message);else this._logToConsole(prefix,entry.message);}else this._logToConsole(`${prefix}: ${JSON.stringify(entry.message)}`);if(entry.exception){this._logToConsole(entry.exception);if(entry.exception.stack) this._logToConsole(entry.exception.stack);}}}};InspectorBackendClass=class InspectorBackendClass {constructor() {this._registeredDomains={};this._activeDomains={};this._customTracer=null;this._defaultTracer=new WI.LoggingProtocolTracer;this._activeTracers=[this._defaultTracer]; this._supportedDomainsForTargetType=new Multimap;this._supportedCommandParameters=new Map;this._supportedEventParameters=new Map;WI.settings.protocolAutoLogMessages.addEventListener(WI.Setting.Event.Changed,this._startOrStopAutomaticTracing,this);WI.settings.protocolAutoLogTimeStats.addEventListener(WI.Setting.Event.Changed,this._startOrStopAutomaticTracing,this);this._startOrStopAutomaticTracing();this.currentDispatchState={event:null,request:null,response:null,};} get Enum() {return this._registeredDomains;} set dumpInspectorProtocolMessages(value) {WI.settings.protocolAutoLogMessages.value=value;this._defaultTracer.dumpMessagesToConsole=value;} get dumpInspectorProtocolMessages() {return WI.settings.protocolAutoLogMessages.value;} set dumpInspectorTimeStats(value) {WI.settings.protocolAutoLogTimeStats.value=value;if(!this.dumpInspectorProtocolMessages) this.dumpInspectorProtocolMessages=true;this._defaultTracer.dumpTimingDataToConsole=value;} get dumpInspectorTimeStats() {return WI.settings.protocolAutoLogTimeStats.value;} set filterMultiplexingBackendInspectorProtocolMessages(value) {WI.settings.protocolFilterMultiplexingBackendMessages.value=value;this._defaultTracer.filterMultiplexingBackend=value;} get filterMultiplexingBackendInspectorProtocolMessages() {return WI.settings.protocolFilterMultiplexingBackendMessages.value;} set customTracer(tracer) {if(!tracer&&!this._customTracer) return;if(tracer===this._customTracer) return;if(tracer===this._defaultTracer) return;if(this._customTracer) this._customTracer.logFinished();this._customTracer=tracer;this._activeTracers=[this._defaultTracer];if(this._customTracer){this._customTracer.logStarted();this._activeTracers.push(this._customTracer);}} get activeTracers() {return this._activeTracers;} registerDomain(domainName,targetTypes) {targetTypes=targetTypes||WI.TargetType.all;for(let targetType of targetTypes) this._supportedDomainsForTargetType.add(targetType,domainName);this._registeredDomains[domainName]=new InspectorBackend.Domain(domainName);} registerVersion(domainName,version) {let domain=this._registeredDomains[domainName];domain.VERSION=version;} registerEnum(qualifiedName,enumValues) {let[domainName,enumName]=qualifiedName.split(".");let domain=this._registeredDomains[domainName];domain._addEnum(enumName,enumValues);} registerCommand(qualifiedName,targetTypes,callSignature,replySignature) {let[domainName,commandName]=qualifiedName.split(".");let domain=this._registeredDomains[domainName];domain._addCommand(targetTypes,new InspectorBackend.Command(qualifiedName,commandName,callSignature,replySignature));} registerEvent(qualifiedName,targetTypes,signature) {let[domainName,eventName]=qualifiedName.split(".");let domain=this._registeredDomains[domainName];domain._addEvent(targetTypes,new InspectorBackend.Event(qualifiedName,eventName,signature));} registerDispatcher(domainName,dispatcher) {let domain=this._registeredDomains[domainName];domain._addDispatcher(dispatcher);} activateDomain(domainName,debuggableTypes) { let currentDebuggableType=WI.sharedApp?.debuggableType||InspectorFrontendHost.debuggableInfo.debuggableType;if(debuggableTypes&&!debuggableTypes.includes(currentDebuggableType)) return;let domain=this._registeredDomains[domainName];this._activeDomains[domainName]=domain;let supportedTargetTypes=WI.DebuggableType.supportedTargetTypes(currentDebuggableType);for(let[targetType,command]of domain._supportedCommandsForTargetType){if(!supportedTargetTypes.has(targetType)) continue;let parameters=this._supportedCommandParameters.get(command._qualifiedName);if(!parameters){parameters=new Set;this._supportedCommandParameters.set(command._qualifiedName,parameters);} parameters.addAll(command._callSignature.map((item)=>item.name));} for(let[targetType,event]of domain._supportedEventsForTargetType){if(!supportedTargetTypes.has(targetType)) continue;let parameters=this._supportedEventParameters.get(event._qualifiedName);if(!parameters){parameters=new Set;this._supportedEventParameters.set(event._qualifiedName,parameters);} parameters.addAll(event._parameterNames);}} dispatch(message) {InspectorBackend.backendConnection.dispatch(message);} runAfterPendingDispatches(callback) {if(!WI.mainTarget){callback();return;} WI.mainTarget.connection.runAfterPendingDispatches(callback);} supportedDomainsForTargetType(type) {return this._supportedDomainsForTargetType.get(type)||new Set;} hasDomain(domainName) {return domainName in this._activeDomains;} hasCommand(qualifiedName,parameterName) {let parameters=this._supportedCommandParameters.get(qualifiedName);if(!parameters) return false;return parameterName===undefined||parameters.has(parameterName);} hasEvent(qualifiedName,parameterName) {let parameters=this._supportedEventParameters.get(qualifiedName);if(!parameters) return false;return parameterName===undefined||parameters.has(parameterName);} getVersion(domainName) {let domain=this._activeDomains[domainName];if(domain&&"VERSION"in domain) return domain.VERSION;return-Infinity;} invokeCommand(qualifiedName,targetType,connection,commandArguments,callback) {let[domainName,commandName]=qualifiedName.split(".");let domain=this._activeDomains[domainName];return domain._invokeCommand(commandName,targetType,connection,commandArguments,callback);} _makeAgent(domainName,target) {let domain=this._activeDomains[domainName];return domain._makeAgent(target);} _startOrStopAutomaticTracing() {this._defaultTracer.dumpMessagesToConsole=this.dumpInspectorProtocolMessages;this._defaultTracer.dumpTimingDataToConsole=this.dumpTimingDataToConsole;this._defaultTracer.filterMultiplexingBackend=this.filterMultiplexingBackendInspectorProtocolMessages;}};InspectorBackend=new InspectorBackendClass;InspectorBackend.Domain=class InspectorBackendDomain {constructor(domainName) {this._domainName=domainName; this._dispatcher=null; this._supportedCommandsForTargetType=new Multimap;this._supportedEventsForTargetType=new Multimap;} _addEnum(enumName,enumValues) {this[enumName]=enumValues;} _addCommand(targetTypes,command) {targetTypes=targetTypes||WI.TargetType.all;for(let type of targetTypes) this._supportedCommandsForTargetType.add(type,command);} _addEvent(targetTypes,event) {targetTypes=targetTypes||WI.TargetType.all;for(let type of targetTypes) this._supportedEventsForTargetType.add(type,event);} _addDispatcher(dispatcher) {this._dispatcher=dispatcher;} _makeAgent(target) {let commands=this._supportedCommandsForTargetType.get(target.type)||new Set;let events=this._supportedEventsForTargetType.get(target.type)||new Set;return new InspectorBackend.Agent(target,commands,events,this._dispatcher);} _invokeCommand(commandName,targetType,connection,commandArguments,callback) {let commands=this._supportedCommandsForTargetType.get(targetType);for(let command of commands){if(command._commandName===commandName) return command._makeCallable(connection).invoke(commandArguments,callback);}}};InspectorBackend.Agent=class InspectorBackendAgent {constructor(target,commands,events,dispatcher) { for(let command of commands){this[command._commandName]=command._makeCallable(target.connection);target._supportedCommandParameters.set(command._qualifiedName,command);} this._events={};for(let event of events){this._events[event._eventName]=event;target._supportedEventParameters.set(event._qualifiedName,event);} this._dispatcher=dispatcher?new dispatcher(target):null;}};InspectorBackend.Dispatcher=class InspectorBackendDispatcher {constructor(target) {this._target=target;}};InspectorBackend.Command=class InspectorBackendCommand {constructor(qualifiedName,commandName,callSignature,replySignature) {this._qualifiedName=qualifiedName;this._commandName=commandName;this._callSignature=callSignature||[];this._replySignature=replySignature||[];} _hasParameter(parameterName) {return this._callSignature.some((item)=>item.name===parameterName);} _makeCallable(connection) {let instance=new InspectorBackend.Callable(this,connection);function callable(){return instance._invokeWithArguments.call(instance,Array.from(arguments));} callable._instance=instance;Object.setPrototypeOf(callable,InspectorBackend.Callable.prototype);return callable;}};InspectorBackend.Event=class InspectorBackendEvent {constructor(qualifiedName,eventName,parameterNames) {this._qualifiedName=qualifiedName;this._eventName=eventName;this._parameterNames=parameterNames||[];} _hasParameter(parameterName) {return this._parameterNames.includes(parameterName);}};InspectorBackend.Callable=function(command,connection) {"use strict";this._command=command;this._connection=connection;this._instance=this;};InspectorBackend.Callable.prototype={__proto__:Function.prototype, invoke(commandArguments,callback) {"use strict";let command=this._instance._command;let connection=this._instance._connection;function deliverFailure(message){console.error(`Protocol Error: ${message}`);if(callback) setTimeout(callback.bind(null,message),0);else return Promise.reject(new Error(message));} if(typeof commandArguments!=="object") return deliverFailure(`invoke expects an object for command arguments but its type is '${typeof commandArguments}'.`);let parameters={};for(let{name,type,optional}of command._callSignature){if(!(name in commandArguments)&&!optional) return deliverFailure(`Missing argument '${name}' for command '${command._qualifiedName}'.`);let value=commandArguments[name];if(optional&&value===undefined) continue;if(typeof value!==type) return deliverFailure(`Invalid type of argument '${name}' for command '${command._qualifiedName}' call. It must be '${type}' but it is '${typeof value}'.`);parameters[name]=value;} if(typeof callback==="function") connection._sendCommandToBackendWithCallback(command,parameters,callback);else return connection._sendCommandToBackendExpectingPromise(command,parameters);}, _invokeWithArguments(commandArguments) {"use strict";let command=this._instance._command;let connection=this._instance._connection;let callback=typeof commandArguments.lastValue==="function"?commandArguments.pop():null;function deliverFailure(message){console.error(`Protocol Error: ${message}`);if(callback) setTimeout(callback.bind(null,message),0);else return Promise.reject(new Error(message));} let parameters={};for(let{name,type,optional}of command._callSignature){if(!commandArguments.length&&!optional) return deliverFailure(`Invalid number of arguments for command '${command._qualifiedName}'.`);let value=commandArguments.shift();if(optional&&value===undefined) continue;if(typeof value!==type) return deliverFailure(`Invalid type of argument '${name}' for command '${command._qualifiedName}' call. It must be '${type}' but it is '${typeof value}'.`);parameters[name]=value;} if(!callback&&commandArguments.length===1&&commandArguments[0]!==undefined) return deliverFailure(`Protocol Error: Optional callback argument for command '${command._qualifiedName}' call must be a function but its type is '${typeof commandArguments[0]}'.`);if(callback) connection._sendCommandToBackendWithCallback(command,parameters,callback);else return connection._sendCommandToBackendExpectingPromise(command,parameters);}};InspectorBackend.globalSequenceId=1;InspectorBackend.Connection=class InspectorBackendConnection {constructor() {this._pendingResponses=new Map;this._deferredCallbacks=[];this._target=null;this._provisionalMessages=[];} get target() {return this._target;} set target(target) {this._target=target;} addProvisionalMessage(message) {this._provisionalMessages.push(message);} dispatchProvisionalMessages() {for(let message of this._provisionalMessages) this.dispatch(message);this._provisionalMessages=[];} dispatch(message) {let messageObject=typeof message==="string"?JSON.parse(message):message;if("id"in messageObject) this._dispatchResponse(messageObject);else this._dispatchEvent(messageObject);} runAfterPendingDispatches(callback) {if(!this._pendingResponses.size) callback.call(this);else this._deferredCallbacks.push(callback);} sendMessageToBackend(message) {throw new Error("Should be implemented by a InspectorBackend.Connection subclass");} _dispatchResponse(messageObject) {if(messageObject.error&&messageObject.error.code!==-32_000) console.error("Request with id = "+messageObject["id"]+" failed. "+JSON.stringify(messageObject.error));let sequenceId=messageObject["id"];let responseData=this._pendingResponses.take(sequenceId)||{};let{request,command,callback,promise}=responseData;let processingStartTimestamp=performance.now();for(let tracer of InspectorBackend.activeTracers) tracer.logWillHandleResponse(this,messageObject);InspectorBackend.currentDispatchState.request=request;InspectorBackend.currentDispatchState.response=messageObject;if(typeof callback==="function") this._dispatchResponseToCallback(command,request,messageObject,callback);else if(typeof promise==="object") this._dispatchResponseToPromise(command,messageObject,promise);else console.error("Received a command response without a corresponding callback or promise.",messageObject,command);InspectorBackend.currentDispatchState.request=null;InspectorBackend.currentDispatchState.response=null;let processingTime=(performance.now()-processingStartTimestamp).toFixed(3);let roundTripTime=(processingStartTimestamp-responseData.sendRequestTimestamp).toFixed(3);for(let tracer of InspectorBackend.activeTracers) tracer.logDidHandleResponse(this,messageObject,{rtt:roundTripTime,dispatch:processingTime});if(this._deferredCallbacks.length&&!this._pendingResponses.size) this._flushPendingScripts();} _dispatchResponseToCallback(command,requestObject,responseObject,callback) {let callbackArguments=[];callbackArguments.push(responseObject["error"]?responseObject["error"].message:null);if(responseObject["result"]){for(let parameterName of command._replySignature) callbackArguments.push(responseObject["result"][parameterName]);} try{callback.apply(null,callbackArguments);}catch(e){WI.reportInternalError(e,{"cause":`An uncaught exception was thrown while dispatching response callback for command ${command._qualifiedName}.`});}} _dispatchResponseToPromise(command,messageObject,promise) {let{resolve,reject}=promise;if(messageObject["error"]) reject(new Error(messageObject["error"].message));else resolve(messageObject["result"]);} _dispatchEvent(messageObject) {let qualifiedName=messageObject.method;let[domainName,eventName]=qualifiedName.split("."); if(!this._target&&this===InspectorBackend.backendConnection&&WI.sharedApp.debuggableType===WI.DebuggableType.WebPage&&qualifiedName==="Target.targetCreated") WI.targetManager.createMultiplexingBackendTarget();let agent=this._target._agents[domainName];if(!agent){console.error(`Protocol Error: Attempted to dispatch method '${qualifiedName}' for non-existing domain '${domainName}'`,messageObject);return;} let dispatcher=agent._dispatcher;if(!dispatcher){console.error(`Protocol Error: Missing dispatcher for domain '${domainName}', for event '${qualifiedName}'`,messageObject);return;} let event=agent._events[eventName];if(!event){console.error(`Protocol Error: Attempted to dispatch an unspecified method '${qualifiedName}'`,messageObject);return;} let handler=dispatcher[eventName];if(!handler){console.error(`Protocol Error: Attempted to dispatch an unimplemented method '${qualifiedName}'`,messageObject);return;} let processingStartTimestamp=performance.now();for(let tracer of InspectorBackend.activeTracers) tracer.logWillHandleEvent(this,messageObject);InspectorBackend.currentDispatchState.event=messageObject;try{let params=messageObject.params||{};handler.apply(dispatcher,event._parameterNames.map((name)=>params[name]));}catch(e){for(let tracer of InspectorBackend.activeTracers) tracer.logFrontendException(this,messageObject,e);WI.reportInternalError(e,{"cause":`An uncaught exception was thrown while handling event: ${qualifiedName}`});} InspectorBackend.currentDispatchState.event=null;let processingDuration=(performance.now()-processingStartTimestamp).toFixed(3);for(let tracer of InspectorBackend.activeTracers) tracer.logDidHandleEvent(this,messageObject,{dispatch:processingDuration});} _sendCommandToBackendWithCallback(command,parameters,callback) {let sequenceId=InspectorBackend.globalSequenceId++;let messageObject={"id":sequenceId,"method":command._qualifiedName,};if(!isEmptyObject(parameters)) messageObject["params"]=parameters;let responseData={command,request:messageObject,callback};if(InspectorBackend.activeTracer) responseData.sendRequestTimestamp=performance.now();this._pendingResponses.set(sequenceId,responseData);this._sendMessageToBackend(messageObject);} _sendCommandToBackendExpectingPromise(command,parameters) {let sequenceId=InspectorBackend.globalSequenceId++;let messageObject={"id":sequenceId,"method":command._qualifiedName,};if(!isEmptyObject(parameters)) messageObject["params"]=parameters;let responseData={command,request:messageObject};if(InspectorBackend.activeTracer) responseData.sendRequestTimestamp=performance.now();let responsePromise=new Promise(function(resolve,reject){responseData.promise={resolve,reject};});this._pendingResponses.set(sequenceId,responseData);this._sendMessageToBackend(messageObject);return responsePromise;} _sendMessageToBackend(messageObject) {for(let tracer of InspectorBackend.activeTracers) tracer.logFrontendRequest(this,messageObject);this.sendMessageToBackend(JSON.stringify(messageObject));} _flushPendingScripts() {let scriptsToRun=this._deferredCallbacks;this._deferredCallbacks=[];for(let script of scriptsToRun) script.call(this);}};InspectorBackend.BackendConnection=class InspectorBackendBackendConnection extends InspectorBackend.Connection {sendMessageToBackend(message) {InspectorFrontendHost.sendMessageToBackend(message);}};InspectorBackend.WorkerConnection=class InspectorBackendWorkerConnection extends InspectorBackend.Connection {sendMessageToBackend(message) {let workerId=this.target.identifier;this.target.parentTarget.WorkerAgent.sendMessageToWorker(workerId,message).catch((error)=>{if(this.target.isDestroyed) return;WI.reportInternalError(error);});}};InspectorBackend.TargetConnection=class InspectorBackendTargetConnection extends InspectorBackend.Connection {sendMessageToBackend(message) {let targetId=this.target.identifier;this.target.parentTarget.TargetAgent.sendMessageToTarget(targetId,message).catch((error)=>{if(this.target.isDestroyed) return;WI.reportInternalError(error);});}};InspectorBackend.backendConnection=new InspectorBackend.BackendConnection;InspectorFrontendAPI={_loaded:false,_pendingCommands:[],isTimelineProfilingEnabled:function() {return WI.timelineManager.isCapturing();},setTimelineProfilingEnabled:function(enabled) {if(!WI.targetsAvailable()){WI.whenTargetsAvailable().then(()=>{InspectorFrontendAPI.setTimelineProfilingEnabled(enabled);});return;} WI.showTimelineTab({initiatorHint:WI.TabBrowser.TabNavigationInitiator.FrontendAPI});if(WI.timelineManager.isCapturing()===enabled) return;if(enabled) WI.timelineManager.startCapturing();else WI.timelineManager.stopCapturing();},setElementSelectionEnabled:function(enabled) {if(!WI.targetsAvailable()){WI.whenTargetsAvailable().then(()=>{InspectorFrontendAPI.setElementSelectionEnabled(enabled);});return;} WI.domManager.inspectModeEnabled=enabled;},setDockingUnavailable:function(unavailable) {WI.updateDockingAvailability(!unavailable);},setDockSide:function(side) {WI.updateDockedState(side);},setIsVisible:function(visible) {WI.updateVisibilityState(visible);},updateFindString:function(findString) {WI.updateFindString(findString);},setDiagnosticLoggingAvailable:function(available) {if(WI.diagnosticController) WI.diagnosticController.diagnosticLoggingAvailable=available;},showConsole:function() {WI.showConsoleTab({initiatorHint:WI.TabBrowser.TabNavigationInitiator.FrontendAPI,});WI.quickConsole.prompt.focus();if(document.readyState!=="complete") document.addEventListener("readystatechange",this);if(document.visibilityState!=="visible") document.addEventListener("visibilitychange",this);},handleEvent:function(event) {if(document.readyState==="complete"&&document.visibilityState==="visible"){WI.quickConsole.prompt.focus();document.removeEventListener("readystatechange",this);document.removeEventListener("visibilitychange",this);}},showResources:function() {WI.showSourcesTab({initiatorHint:WI.TabBrowser.TabNavigationInitiator.FrontendAPI,});},showTimelines:function() {WI.showTimelineTab({initiatorHint:WI.TabBrowser.TabNavigationInitiator.FrontendAPI});},showMainResourceForFrame:function(frameIdentifier) {WI.showSourceCodeForFrame(frameIdentifier,{ignoreNetworkTab:true,ignoreSearchTab:true,initiatorHint:WI.TabBrowser.TabNavigationInitiator.FrontendAPI,});},contextMenuItemSelected:function(id) {WI.ContextMenu.contextMenuItemSelected(id);},contextMenuCleared:function() {WI.ContextMenu.contextMenuCleared();},dispatchMessageAsync:function(messageObject) {WI.dispatchMessageFromBackend(messageObject);},dispatchMessage:function(messageObject) {InspectorBackend.dispatch(messageObject);},dispatch:function(signature) {if(!InspectorFrontendAPI._loaded){InspectorFrontendAPI._pendingCommands.push(signature);return null;} var methodName=signature.shift();if(!InspectorFrontendAPI[methodName]) return null;return InspectorFrontendAPI[methodName].apply(InspectorFrontendAPI,signature);},loadCompleted:function() {InspectorFrontendAPI._loaded=true;for(var i=0;i");})();WI._messagesToDispatch=[];WI.dispatchNextQueuedMessageFromBackend=function() {const startCount=WI._messagesToDispatch.length;const startTimestamp=performance.now();const timeLimitPerRunLoop=10; let i=0;for(;itimeLimitPerRunLoop) break;InspectorBackend.dispatch(WI._messagesToDispatch[i]);} if(i===WI._messagesToDispatch.length){WI._messagesToDispatch=[];WI._dispatchTimeout=null;}else{WI._messagesToDispatch=WI._messagesToDispatch.slice(i);WI._dispatchTimeout=setTimeout(WI.dispatchNextQueuedMessageFromBackend,0);} if(InspectorBackend.dumpInspectorTimeStats){let messageDuration=(performance.now()-startTimestamp).toFixed(3);let dispatchedCount=startCount-WI._messagesToDispatch.length;let remainingCount=WI._messagesToDispatch.length;console.log(`time-stats: --- RunLoop duration: ${messageDuration}ms; dispatched: ${dispatchedCount}; remaining: ${remainingCount}`);}};WI.dispatchMessageFromBackend=function(message) {this._messagesToDispatch.push(message); if(window.__uncaughtExceptions&&window.__uncaughtExceptions.length) return;if(this._dispatchTimeout) return;this._dispatchTimeout=setTimeout(this.dispatchNextQueuedMessageFromBackend,0);};WI.RemoteObject=class RemoteObject {constructor(target,objectId,type,subtype,value,description,size,classPrototype,className,preview) {this._target=target||WI.mainTarget;this._type=type;this._subtype=subtype;if(objectId){this._objectId=objectId;this._description=description||"";this._hasChildren=type!=="symbol";this._size=size;this._classPrototype=classPrototype;this._preview=preview;if(subtype==="class"){this._functionDescription=this._description;this._description="class "+className;}}else{this._description=description||(value+"");this._hasChildren=false;this._value=value;if(type==="bigint"){if(window.BigInt) this._value=BigInt(description.substring(0,description.length-1));else this._value=`${description} [BigInt Not Enabled in Web Inspector]`;}}} static createFakeRemoteObject() {return new WI.RemoteObject(undefined,WI.RemoteObject.FakeRemoteObjectId,"object");} static fromPrimitiveValue(value) {return new WI.RemoteObject(undefined,undefined,typeof value,undefined,value,undefined,undefined,undefined,undefined);} static createBigIntFromDescriptionString(description) {return new WI.RemoteObject(undefined,undefined,"bigint",undefined,undefined,description,undefined,undefined,undefined);} static fromPayload(payload,target) {if(payload.classPrototype) payload.classPrototype=WI.RemoteObject.fromPayload(payload.classPrototype,target);if(payload.preview) payload.preview=WI.ObjectPreview.fromPayload(payload.preview);return new WI.RemoteObject(target,payload.objectId,payload.type,payload.subtype,payload.value,payload.description,payload.size,payload.classPrototype,payload.className,payload.preview);} static createCallArgument(valueOrObject) {if(valueOrObject instanceof WI.RemoteObject){if(valueOrObject.objectId) return{objectId:valueOrObject.objectId};return{value:valueOrObject.value};} return{value:valueOrObject};} static resolveNode(node,objectGroup) {if(node.destroyed) return Promise.reject("ERROR: node is destroyed");let target=WI.assumingMainTarget();return target.DOMAgent.resolveNode(node.id,objectGroup).then(({object})=>WI.RemoteObject.fromPayload(object,WI.mainTarget));} static resolveWebSocket(webSocketResource,objectGroup,callback) {let target=WI.assumingMainTarget();target.NetworkAgent.resolveWebSocket(webSocketResource.requestIdentifier,objectGroup,(error,object)=>{if(error||!object) callback(null);else callback(WI.RemoteObject.fromPayload(object,webSocketResource.target));});} static resolveCanvasContext(canvas,objectGroup) {let promise=null;if(!canvas.target.hasCommand("Canvas.resolveContext")) promise=canvas.target.CanvasAgent.resolveCanvasContext(canvas.identifier,objectGroup);else promise=canvas.target.CanvasAgent.resolveContext(canvas.identifier,objectGroup);return promise.then(({object})=>WI.RemoteObject.fromPayload(object,canvas.target));} static resolveAnimation(animation,objectGroup,callback) {function wrapCallback(error,object){if(error||!object) callback(null);else callback(WI.RemoteObject.fromPayload(object,WI.mainTarget));} let target=WI.assumingMainTarget();target.AnimationAgent.resolveAnimation(animation.animationId,objectGroup,wrapCallback);} get target() {return this._target;} get objectId() {return this._objectId;} get type() {return this._type;} get subtype() {return this._subtype;} get description() {return this._description;} get functionDescription() {return this._functionDescription||this._description;} get hasChildren() {return this._hasChildren;} get value() {return this._value;} get size() {return this._size||0;} get classPrototype() {return this._classPrototype;} get preview() {return this._preview;} hasSize() {return this.isArray()||this.isCollectionType();} hasValue() {return"_value"in this;} canLoadPreview() {if(this._failedToLoadPreview) return false;if(this._type!=="object") return false;if(!this._objectId||this._isSymbol()||this._isFakeObject()) return false;return true;} updatePreview(callback) {if(!this.canLoadPreview()){callback(null);return;} if(!this._target.hasCommand("Runtime.getPreview")){this._failedToLoadPreview=true;callback(null);return;} this._target.RuntimeAgent.getPreview(this._objectId,(error,payload)=>{if(error){this._failedToLoadPreview=true;callback(null);return;} this._preview=WI.ObjectPreview.fromPayload(payload);callback(this._preview);});} getPropertyDescriptors(callback,options={}) {if(!this._objectId||this._isSymbol()||this._isFakeObject()){callback([]);return;} this._getProperties(this._getPropertyDescriptorsResolver.bind(this,callback),options);} getDisplayablePropertyDescriptors(callback,options={}) {if(!this._objectId||this._isSymbol()||this._isFakeObject()){callback([]);return;} this._getDisplayableProperties(this._getPropertyDescriptorsResolver.bind(this,callback),options);} setPropertyValue(name,value,callback) {if(!this._objectId||this._isSymbol()||this._isFakeObject()){callback("Can't set a property of non-object.");return;} this._target.RuntimeAgent.evaluate.invoke({expression:appendWebInspectorSourceURL(value),doNotPauseOnExceptionsAndMuteConsole:true},evaluatedCallback.bind(this));function evaluatedCallback(error,result,wasThrown) {if(error||wasThrown){callback(error||result.description);return;} function setPropertyValue(propertyName,propertyValue) {this[propertyName]=propertyValue;} delete result.description;this._target.RuntimeAgent.callFunctionOn(this._objectId,appendWebInspectorSourceURL(setPropertyValue.toString()),[{value:name},result],true,undefined,propertySetCallback.bind(this));if(result._objectId) this._target.RuntimeAgent.releaseObject(result._objectId);} function propertySetCallback(error,result,wasThrown) {if(error||wasThrown){callback(error||result.description);return;} callback();}} isUndefined() {return this._type==="undefined";} isNode() {return this._subtype==="node";} isArray() {return this._subtype==="array";} isClass() {return this._subtype==="class";} isCollectionType() {return this._subtype==="map"||this._subtype==="set"||this._subtype==="weakmap"||this._subtype==="weakset";} isWeakCollection() {return this._subtype==="weakmap"||this._subtype==="weakset";} getCollectionEntries(callback,{fetchStart,fetchCount}={}) {let objectGroup=this.isWeakCollection()?this._weakCollectionObjectGroup():"";this._target.RuntimeAgent.getCollectionEntries(this._objectId,objectGroup,fetchStart,fetchCount,(error,entries)=>{callback(entries.map((x)=>WI.CollectionEntry.fromPayload(x,this._target)));});} releaseWeakCollectionEntries() {this._target.RuntimeAgent.releaseObjectGroup(this._weakCollectionObjectGroup());} pushNodeToFrontend(callback) {if(this._objectId&&InspectorBackend.hasCommand("DOM.requestNode")) WI.domManager.pushNodeToFrontend(this._objectId,callback);else callback(0);} async fetchProperties(propertyNames,resultObject={}) {let seenPropertyNames=new Set;let requestedValues=[];for(let propertyName of propertyNames){if(typeof propertyName!=="string"&&typeof propertyName!=="number") throw new Error(`Tried to get property using key is not a string or number: ${propertyName}`);if(seenPropertyNames.has(propertyName)) continue;seenPropertyNames.add(propertyName);requestedValues.push(this.getProperty(propertyName));} function maybeUnwrapValue(remoteObject){return remoteObject.hasValue()?remoteObject.value:remoteObject;} let fetchedKeys=Array.from(seenPropertyNames);let fetchedValues=await Promise.all(requestedValues);for(let i=0;iresult?WI.RemoteObject.fromPayload(result,this._target):null;if(args) args=args.map(WI.RemoteObject.createCallArgument);if(callback&&typeof callback==="function"){this._target.RuntimeAgent.callFunctionOn(this._objectId,appendWebInspectorSourceURL(functionDeclaration.toString()),args,true,undefined,!!generatePreview,(error,result,wasThrown)=>{callback(error,translateResult(result),wasThrown);});}else{return this._target.RuntimeAgent.callFunctionOn(this._objectId,appendWebInspectorSourceURL(functionDeclaration.toString()),args,true,undefined,!!generatePreview).then(({result,wasThrown})=>{result=translateResult(result);if(result&&wasThrown) return Promise.reject(result);return Promise.resolve(result);});}} callFunctionJSON(functionDeclaration,args,callback=null) {if(callback&&typeof callback==="function"){this._target.RuntimeAgent.callFunctionOn(this._objectId,appendWebInspectorSourceURL(functionDeclaration.toString()),args,true,true,(error,result,wasThrown)=>{callback((error||wasThrown)?null:result.value);});}else{return this._target.RuntimeAgent.callFunctionOn(this._objectId,appendWebInspectorSourceURL(functionDeclaration.toString()),args,true,true).then(({result,wasThrown})=>{return wasThrown?null:result.value;});}} invokeGetter(getterRemoteObject,callback) {function backendInvokeGetter(getter) {return getter?getter.call(this):undefined;} this.callFunction(backendInvokeGetter,[getterRemoteObject],true,callback);} getOwnPropertyDescriptor(propertyName,callback) {function backendGetOwnPropertyDescriptor(propertyName) {return this[propertyName];} function wrappedCallback(error,result,wasThrown) {if(error||wasThrown||!(result instanceof WI.RemoteObject)){callback(null);return;} var fakeDescriptor={name:propertyName,value:result,writable:true,configurable:true};var fakePropertyDescriptor=new WI.PropertyDescriptor(fakeDescriptor,null,true,false,false,false);callback(fakePropertyDescriptor);} this.callFunction(backendGetOwnPropertyDescriptor,[propertyName],false,wrappedCallback.bind(this));} release() {if(this._objectId&&!this._isFakeObject()) this._target.RuntimeAgent.releaseObject(this._objectId);} arrayLength() {if(this._subtype!=="array") return 0;var matches=this._description.match(/\[([0-9]+)\]/);if(!matches) return 0;return parseInt(matches[1],10);} asCallArgument() {return WI.RemoteObject.createCallArgument(this);} findFunctionSourceCodeLocation() {var result=new WI.WrappedPromise;if(!this._isFunction()||!this._objectId){result.resolve(WI.RemoteObject.SourceCodeLocationPromise.MissingObjectId);return result.promise;} this._target.DebuggerAgent.getFunctionDetails(this._objectId,(error,response)=>{if(error){result.resolve(WI.RemoteObject.SourceCodeLocationPromise.NoSourceFound);return;} var location=response.location;var sourceCode=WI.debuggerManager.scriptForIdentifier(location.scriptId,this._target);if(!sourceCode||(!WI.settings.engineeringShowInternalScripts.value&&isWebKitInternalScript(sourceCode.sourceURL))){result.resolve(WI.RemoteObject.SourceCodeLocationPromise.NoSourceFound);return;} var sourceCodeLocation=sourceCode.createSourceCodeLocation(location.lineNumber,location.columnNumber||0);result.resolve(sourceCodeLocation);});return result.promise;} _isFakeObject() {return this._objectId===WI.RemoteObject.FakeRemoteObjectId;} _isSymbol() {return this._type==="symbol";} _isFunction() {return this._type==="function";} _weakCollectionObjectGroup() {return JSON.stringify(this._objectId)+"-"+this._subtype;} _getProperties(callback,{ownProperties,fetchStart,fetchCount,generatePreview}={}) {this._target.RuntimeAgent.getProperties.invoke({objectId:this._objectId,ownProperties,fetchStart,fetchCount,generatePreview,},callback);} _getDisplayableProperties(callback,{fetchStart,fetchCount,generatePreview}={}) {this._target.RuntimeAgent.getDisplayableProperties.invoke({objectId:this._objectId,fetchStart,fetchCount,generatePreview,},callback);} _getPropertyDescriptorsResolver(callback,error,properties,internalProperties) {if(error){callback(null);return;} let descriptors=properties.map((payload)=>WI.PropertyDescriptor.fromPayload(payload,false,this._target));if(internalProperties){for(let payload of internalProperties) descriptors.push(WI.PropertyDescriptor.fromPayload(payload,true,this._target));} callback(descriptors);}};WI.RemoteObject.FakeRemoteObjectId="fake-remote-object";WI.RemoteObject.SourceCodeLocationPromise={NoSourceFound:"remote-object-source-code-location-promise-no-source-found",MissingObjectId:"remote-object-source-code-location-promise-missing-object-id"};WI.Target=class Target extends WI.Object {constructor(parentTarget,identifier,name,type,connection,{isPaused,isProvisional}={}) {super();this._parentTarget=parentTarget;this._identifier=identifier;this._name=name;this._type=type;this._connection=connection;this._isPaused=!!isPaused;this._isProvisional=!!isProvisional;this._executionContext=null;this._mainResource=null;this._resourceCollection=new WI.ResourceCollection;this._extraScriptCollection=new WI.ScriptCollection;this._supportedCommandParameters=new Map;this._supportedEventParameters=new Map; this._agents={};for(let domainName of InspectorBackend.supportedDomainsForTargetType(this._type)) this._agents[domainName]=InspectorBackend._makeAgent(domainName,this);this._connection.target=this;} initialize() {if(this.hasDomain("Inspector")) this.InspectorAgent.enable();for(let manager of WI.managers){if(manager.initializeTarget) manager.initializeTarget(this);} WI.initializeTarget(this); this.ConsoleAgent.enable();setTimeout(()=>{ WI.performOneTimeFrontendInitializationsUsingTarget(this);});Promise.all(Target._initializationPromises).then(()=>{ if(this.hasDomain("Inspector")) this.InspectorAgent.initialized();});this._resumeIfPaused();} _resumeIfPaused() {if(this._isPaused){this._parentTarget.TargetAgent.resume(this._identifier,(error)=>{if(error){if(!this.isDestroyed) WI.reportInternalError(error);return;} this._isPaused=false;});}} activateExtraDomain(domainName) { this._agents[domainName]=InspectorBackend._makeAgent(domainName,this);} get AnimationAgent(){return this._agents.Animation;} get ApplicationCacheAgent(){return this._agents.ApplicationCache;} get AuditAgent(){return this._agents.Audit;} get BrowserAgent(){return this._agents.Browser;} get CPUProfilerAgent(){return this._agents.CPUProfiler;} get CSSAgent(){return this._agents.CSS;} get CanvasAgent(){return this._agents.Canvas;} get ConsoleAgent(){return this._agents.Console;} get DOMAgent(){return this._agents.DOM;} get DOMDebuggerAgent(){return this._agents.DOMDebugger;} get DOMStorageAgent(){return this._agents.DOMStorage;} get DatabaseAgent(){return this._agents.Database;} get DebuggerAgent(){return this._agents.Debugger;} get HeapAgent(){return this._agents.Heap;} get IndexedDBAgent(){return this._agents.IndexedDB;} get InspectorAgent(){return this._agents.Inspector;} get LayerTreeAgent(){return this._agents.LayerTree;} get MemoryAgent(){return this._agents.Memory;} get NetworkAgent(){return this._agents.Network;} get PageAgent(){return this._agents.Page;} get RecordingAgent(){return this._agents.Recording;} get RuntimeAgent(){return this._agents.Runtime;} get ScriptProfilerAgent(){return this._agents.ScriptProfiler;} get ServiceWorkerAgent(){return this._agents.ServiceWorker;} get TargetAgent(){return this._agents.Target;} get TimelineAgent(){return this._agents.Timeline;} get WorkerAgent(){return this._agents.Worker;} static registerInitializationPromise(promise) {Target._initializationPromises.push(promise);promise.then(()=>{++Target._completedInitializationPromiseCount;Target._initializationPromises.remove(promise);});} get parentTarget(){return this._parentTarget;} get rootTarget() {if(this._type===WI.TargetType.Page) return this;if(this._parentTarget) return this._parentTarget.rootTarget;return this;} get identifier(){return this._identifier;} set identifier(identifier){this._identifier=identifier;} get name(){return this._name;} set name(name){this._name=name;} get type(){return this._type;} get connection(){return this._connection;} get executionContext(){return this._executionContext;} get resourceCollection(){return this._resourceCollection;} get extraScriptCollection(){return this._extraScriptCollection;} get isProvisional(){return this._isProvisional;} get isPaused(){return this._isPaused;} get isDestroyed(){return this._isDestroyed;} get displayName(){return this._name;} get mainResource() {return this._mainResource;} set mainResource(resource) {this._mainResource=resource;this.dispatchEventToListeners(WI.Target.Event.MainResourceAdded,{resource});} addResource(resource) {this._resourceCollection.add(resource);this.dispatchEventToListeners(WI.Target.Event.ResourceAdded,{resource});} adoptResource(resource) {resource._target=this;this.addResource(resource);} addScript(script) {this._extraScriptCollection.add(script);this.dispatchEventToListeners(WI.Target.Event.ScriptAdded,{script});} didCommitProvisionalTarget() {this._isProvisional=false;} destroy() {this._isDestroyed=true;} hasDomain(domainName) {return domainName in this._agents;} hasCommand(qualifiedName,parameterName) {let command=this._supportedCommandParameters.get(qualifiedName);if(!command) return false;return parameterName===undefined||command._hasParameter(parameterName);} hasEvent(qualifiedName,parameterName) {let event=this._supportedEventParameters.get(qualifiedName);if(!event) return false;return parameterName===undefined||event._hasParameter(parameterName);}};WI.Target.Event={MainResourceAdded:"target-main-resource-added",ResourceAdded:"target-resource-added",ScriptAdded:"target-script-added",};WI.Target._initializationPromises=[];WI.Target._completedInitializationPromiseCount=0;WI.DirectBackendTarget=class DirectBackendTarget extends WI.Target {constructor() {const parentTarget=null;const targetId="direct";let{type,displayName}=DirectBackendTarget.connectionInfoForDebuggable();super(parentTarget,targetId,displayName,type,InspectorBackend.backendConnection);this._executionContext=new WI.ExecutionContext(this,WI.RuntimeManager.TopLevelContextExecutionIdentifier,WI.ExecutionContext.Type.Normal,displayName);this._mainResource=null;} static connectionInfoForDebuggable() {switch(WI.sharedApp.debuggableType){case WI.DebuggableType.ITML:return{type:WI.TargetType.ITML,displayName:WI.UIString("ITML Context"),};case WI.DebuggableType.JavaScript:return{type:WI.TargetType.JavaScript,displayName:WI.UIString("JavaScript Context"),};case WI.DebuggableType.Page:return{type:WI.TargetType.Page,displayName:WI.UIString("Page"),};case WI.DebuggableType.ServiceWorker:return{type:WI.TargetType.ServiceWorker,displayName:WI.UIString("ServiceWorker"),};case WI.DebuggableType.WebPage:return{type:WI.TargetType.WebPage,displayName:WI.UIString("Page"),};default:console.error("Unexpected debuggable type: ",WI.sharedApp.debuggableType);return{type:WI.TargetType.JavaScript,displayName:WI.UIString("JavaScript Context"),};}} get mainResource() {if(this._mainResource) return this._mainResource;let mainFrame=WI.networkManager.mainFrame;return mainFrame?mainFrame.mainResource:null;} set mainResource(resource) {this._mainResource=resource;}};WI.MultiplexingBackendTarget=class MultiplexingBackendTarget extends WI.Target {constructor() {const parentTarget=null;const targetId="multi";super(parentTarget,targetId,WI.UIString("Web Page"),WI.TargetType.WebPage,InspectorBackend.backendConnection);} initialize() {WI.browserManager.initializeTarget(this);WI.targetManager.initializeTarget(this);} get name() {console.error("Called name on a MultiplexingBackendTarget");return WI.UIString("Page");} get executionContext() {console.error("Called executionContext on a MultiplexingBackendTarget");return null;} get mainResource() {console.error("Called mainResource on a MultiplexingBackendTarget");return null;}};WI.PageTarget=class PageTarget extends WI.Target {constructor(parentTarget,targetId,name,connection,options={}) {super(parentTarget,targetId,name,WI.TargetType.Page,connection,options);this._executionContext=new WI.ExecutionContext(this,WI.RuntimeManager.TopLevelContextExecutionIdentifier,WI.ExecutionContext.Type.Normal,this.displayName);}};WI.WorkerTarget=class WorkerTarget extends WI.Target {constructor(parentTarget,workerId,url,displayName,connection,options={}) {super(parentTarget,workerId,url,WI.TargetType.Worker,connection,options);this._displayName=displayName;this._executionContext=new WI.ExecutionContext(this,WI.RuntimeManager.TopLevelContextExecutionIdentifier,WI.ExecutionContext.Type.Normal,this.displayName);} get customName() {return this._displayName;} get displayName() {return this._displayName||this.displayURL;} get displayURL() {return WI.displayNameForURL(this._name);}};WI.AnimationObserver=class AnimationObserver extends InspectorBackend.Dispatcher {animationCreated(animation) {WI.animationManager.animationCreated(animation);} nameChanged(animationId,name) {WI.animationManager.nameChanged(animationId,name);} effectChanged(animationId,effect) {WI.animationManager.effectChanged(animationId,effect);} targetChanged(animationId) {WI.animationManager.targetChanged(animationId);} animationDestroyed(animationId) {WI.animationManager.animationDestroyed(animationId);} trackingStart(timestamp) {WI.timelineManager.animationTrackingStarted(timestamp);} trackingUpdate(timestamp,event) {WI.timelineManager.animationTrackingUpdated(timestamp,event);} trackingComplete(timestamp) {WI.timelineManager.animationTrackingCompleted(timestamp);}};WI.ApplicationCacheObserver=class ApplicationCacheObserver extends InspectorBackend.Dispatcher {applicationCacheStatusUpdated(frameId,manifestURL,status) {WI.applicationCacheManager.applicationCacheStatusUpdated(frameId,manifestURL,status);} networkStateUpdated(isNowOnline) {WI.applicationCacheManager.networkStateUpdated(isNowOnline);}};WI.BrowserObserver=class BrowserObserver extends InspectorBackend.Dispatcher {extensionsEnabled(extensions) {WI.browserManager.extensionsEnabled(extensions);} extensionsDisabled(extensionIds) {WI.browserManager.extensionsDisabled(extensionIds);}};WI.CPUProfilerObserver=class CPUProfilerObserver extends InspectorBackend.Dispatcher {trackingStart(timestamp) {WI.timelineManager.cpuProfilerTrackingStarted(timestamp);} trackingUpdate(event) {WI.timelineManager.cpuProfilerTrackingUpdated(event);} trackingComplete(timestamp) {WI.timelineManager.cpuProfilerTrackingCompleted(timestamp);}};WI.CSSObserver=class CSSObserver extends InspectorBackend.Dispatcher {mediaQueryResultChanged() {WI.cssManager.mediaQueryResultChanged();} styleSheetChanged(styleSheetId) {WI.cssManager.styleSheetChanged(styleSheetId);} styleSheetAdded(styleSheetInfo) {WI.cssManager.styleSheetAdded(styleSheetInfo);} styleSheetRemoved(id) {WI.cssManager.styleSheetRemoved(id);} nodeLayoutFlagsChanged(nodeId,layoutFlags) {WI.domManager.nodeLayoutFlagsChanged(nodeId,layoutFlags);} nodeLayoutContextTypeChanged(nodeId,layoutContextType) {WI.domManager.nodeLayoutFlagsChanged(nodeId,[WI.DOMNode.LayoutFlag.Rendered,layoutContextType]);}};WI.CanvasObserver=class CanvasObserver extends InspectorBackend.Dispatcher {canvasAdded(canvas) {WI.canvasManager.canvasAdded(this._target,canvas);} canvasRemoved(canvasId) {WI.canvasManager.canvasRemoved(this._target,canvasId);} canvasSizeChanged(canvasId,width,height) {WI.canvasManager.canvasSizeChanged(this._target,canvasId,width,height);} canvasMemoryChanged(canvasId,memoryCost) {WI.canvasManager.canvasMemoryChanged(this._target,canvasId,memoryCost);} clientNodesChanged(canvasId) {WI.canvasManager.clientNodesChanged(this._target,canvasId);} recordingStarted(canvasId,initiator) {WI.canvasManager.recordingStarted(this._target,canvasId,initiator);} recordingProgress(canvasId,frames,bufferUsed) {WI.canvasManager.recordingProgress(this._target,canvasId,frames,bufferUsed);} recordingFinished(canvasId,recording) {WI.canvasManager.recordingFinished(this._target,canvasId,recording);} extensionEnabled(canvasId,extension) {WI.canvasManager.extensionEnabled(this._target,canvasId,extension);} programCreated(shaderProgram) {if(arguments.length===2){shaderProgram={canvasId:arguments[0],programId:arguments[1],};} WI.canvasManager.programCreated(this._target,shaderProgram);} programDeleted(programId) {WI.canvasManager.programDeleted(this._target,programId);} cssCanvasClientNodesChanged(canvasId) {WI.canvasManager.clientNodesChanged(this._target,canvasId);}};WI.ConsoleObserver=class ConsoleObserver extends InspectorBackend.Dispatcher {messageAdded(message) {if(message.source==="console-api"&&message.type==="clear") return;if(message.type==="assert"&&!message.text) message.text=WI.UIString("Assertion");WI.consoleManager.messageWasAdded(this._target,message.source,message.level,message.text,message.type,message.url,message.line,message.column||0,message.repeatCount,message.parameters,message.stackTrace,message.networkRequestId,message.timestamp);} messageRepeatCountUpdated(count,timestamp) {WI.consoleManager.messageRepeatCountUpdated(count,timestamp);} messagesCleared(reason) {WI.consoleManager.messagesCleared(reason);} heapSnapshot(timestamp,snapshotStringData,title) {let workerProxy=WI.HeapSnapshotWorkerProxy.singleton();workerProxy.createSnapshot(snapshotStringData,title||null,({objectId,snapshot:serializedSnapshot})=>{let snapshot=WI.HeapSnapshotProxy.deserialize(objectId,serializedSnapshot);snapshot.snapshotStringData=snapshotStringData;WI.timelineManager.heapSnapshotAdded(timestamp,snapshot);});}};WI.DOMObserver=class DOMObserver extends InspectorBackend.Dispatcher {documentUpdated() {WI.domManager._documentUpdated();} inspect(nodeId) {WI.domManager.inspectElement(nodeId);} setChildNodes(parentId,nodes) {WI.domManager._setChildNodes(parentId,nodes);} attributeModified(nodeId,name,value) {WI.domManager._attributeModified(nodeId,name,value);} attributeRemoved(nodeId,name) {WI.domManager._attributeRemoved(nodeId,name);} inlineStyleInvalidated(nodeIds) {WI.domManager._inlineStyleInvalidated(nodeIds);} characterDataModified(nodeId,characterData) {WI.domManager._characterDataModified(nodeId,characterData);} childNodeCountUpdated(nodeId,childNodeCount) {WI.domManager._childNodeCountUpdated(nodeId,childNodeCount);} childNodeInserted(parentNodeId,previousNodeId,node) {WI.domManager._childNodeInserted(parentNodeId,previousNodeId,node);} childNodeRemoved(parentNodeId,nodeId) {WI.domManager._childNodeRemoved(parentNodeId,nodeId);} willDestroyDOMNode(nodeId) {WI.domManager.willDestroyDOMNode(nodeId);} shadowRootPushed(hostId,root) {WI.domManager._childNodeInserted(hostId,0,root);} shadowRootPopped(hostId,rootId) {WI.domManager._childNodeRemoved(hostId,rootId);} customElementStateChanged(nodeId,customElementState) {WI.domManager._customElementStateChanged(nodeId,customElementState);} pseudoElementAdded(parentNodeId,pseudoElement) {WI.domManager._pseudoElementAdded(parentNodeId,pseudoElement);} pseudoElementRemoved(parentNodeId,pseudoElementId) {WI.domManager._pseudoElementRemoved(parentNodeId,pseudoElementId);} didAddEventListener(nodeId) {WI.domManager.didAddEventListener(nodeId);} willRemoveEventListener(nodeId) {WI.domManager.willRemoveEventListener(nodeId);} didFireEvent(nodeId,eventName,timestamp,data) {WI.domManager.didFireEvent(nodeId,eventName,timestamp,data);} videoLowPowerChanged(nodeId,timestamp,isLowPower) {WI.domManager.powerEfficientPlaybackStateChanged(nodeId,timestamp,isLowPower);} powerEfficientPlaybackStateChanged(nodeId,timestamp,isPowerEfficient) {WI.domManager.powerEfficientPlaybackStateChanged(nodeId,timestamp,isPowerEfficient);}};WI.DOMStorageObserver=class DOMStorageObserver extends InspectorBackend.Dispatcher {domStorageItemsCleared(storageId) {WI.domStorageManager.itemsCleared(storageId);} domStorageItemRemoved(storageId,key) {WI.domStorageManager.itemRemoved(storageId,key);} domStorageItemAdded(storageId,key,value) {WI.domStorageManager.itemAdded(storageId,key,value);} domStorageItemUpdated(storageId,key,oldValue,newValue) {WI.domStorageManager.itemUpdated(storageId,key,oldValue,newValue);}};WI.DatabaseObserver=class DatabaseObserver extends InspectorBackend.Dispatcher {addDatabase(database) {WI.databaseManager.databaseWasAdded(database.id,database.domain,database.name,database.version);}};WI.DebuggerObserver=class DebuggerObserver extends InspectorBackend.Dispatcher {constructor(target) {super(target);this._legacyScriptParsed=this._target.hasEvent("Debugger.scriptParsed","hasSourceURL");} globalObjectCleared() {WI.debuggerManager.globalObjectCleared(this._target);} scriptParsed(scriptId,url,startLine,startColumn,endLine,endColumn,isContentScript,sourceURL,sourceMapURL,isModule) {WI.debuggerManager.scriptDidParse(this._target,scriptId,url,startLine,startColumn,endLine,endColumn,isModule,isContentScript,sourceURL,sourceMapURL);} scriptFailedToParse(url,scriptSource,startLine,errorLine,errorMessage) {WI.debuggerManager.scriptDidFail(this._target,url,scriptSource);} breakpointResolved(breakpointId,location) {WI.debuggerManager.breakpointResolved(this._target,breakpointId,location);} paused(callFrames,reason,data,asyncStackTrace) {WI.debuggerManager.debuggerDidPause(this._target,callFrames,reason,data,asyncStackTrace);} resumed() {WI.debuggerManager.debuggerDidResume(this._target);} playBreakpointActionSound(breakpointActionIdentifier) {WI.debuggerManager.playBreakpointActionSound(breakpointActionIdentifier);} didSampleProbe(sample) {WI.debuggerManager.didSampleProbe(this._target,sample);}};WI.HeapObserver=class HeapObserver extends InspectorBackend.Dispatcher {garbageCollected(collection) {WI.heapManager.garbageCollected(this._target,collection);} trackingStart(timestamp,snapshotStringData) {let workerProxy=WI.HeapSnapshotWorkerProxy.singleton();workerProxy.createSnapshot(snapshotStringData,({objectId,snapshot:serializedSnapshot})=>{let snapshot=WI.HeapSnapshotProxy.deserialize(objectId,serializedSnapshot);snapshot.snapshotStringData=snapshotStringData;WI.timelineManager.heapTrackingStarted(timestamp,snapshot);});} trackingComplete(timestamp,snapshotStringData) {let workerProxy=WI.HeapSnapshotWorkerProxy.singleton();workerProxy.createSnapshot(snapshotStringData,({objectId,snapshot:serializedSnapshot})=>{let snapshot=WI.HeapSnapshotProxy.deserialize(objectId,serializedSnapshot);snapshot.snapshotStringData=snapshotStringData;WI.timelineManager.heapTrackingCompleted(timestamp,snapshot);});}};WI.InspectorObserver=class InspectorObserver extends InspectorBackend.Dispatcher {evaluateForTestInFrontend(script) {if(!InspectorFrontendHost.isUnderTest()) return;InspectorBackend.runAfterPendingDispatches(function(){window.eval(script);});} inspect(payload,hints) {let remoteObject=WI.RemoteObject.fromPayload(payload,WI.mainTarget);if(remoteObject.subtype==="node"){WI.domManager.inspectNodeObject(remoteObject);return;} if(remoteObject.type==="function"){remoteObject.findFunctionSourceCodeLocation().then((sourceCodeLocation)=>{if(sourceCodeLocation instanceof WI.SourceCodeLocation){WI.showSourceCodeLocation(sourceCodeLocation,{ignoreNetworkTab:true,ignoreSearchTab:true,});}});remoteObject.release();return;} if(hints.databaseId) WI.databaseManager.inspectDatabase(hints.databaseId);else if(hints.domStorageId) WI.domStorageManager.inspectDOMStorage(hints.domStorageId);remoteObject.release();} activateExtraDomains(domains) { WI.sharedApp.activateExtraDomains(domains);}};WI.LayerTreeObserver=class LayerTreeObserver extends InspectorBackend.Dispatcher {layerTreeDidChange() {WI.layerTreeManager.layerTreeDidChange();}};WI.MemoryObserver=class MemoryObserver extends InspectorBackend.Dispatcher {memoryPressure(timestamp,severity) {WI.memoryManager.memoryPressure(timestamp,severity);} trackingStart(timestamp) {WI.timelineManager.memoryTrackingStarted(timestamp);} trackingUpdate(event) {WI.timelineManager.memoryTrackingUpdated(event);} trackingComplete(timestamp) {WI.timelineManager.memoryTrackingCompleted(timestamp);}};WI.NetworkObserver=class NetworkObserver extends InspectorBackend.Dispatcher {requestWillBeSent(requestId,frameId,loaderId,documentURL,request,timestamp,walltime,initiator,redirectResponse,type,targetId) {WI.networkManager.resourceRequestWillBeSent(requestId,frameId,loaderId,request,type,redirectResponse,timestamp,walltime,initiator,targetId);} responseReceived(requestId,frameId,loaderId,timestamp,type,response) {WI.networkManager.resourceRequestDidReceiveResponse(requestId,frameId,loaderId,type,response,timestamp);} dataReceived(requestId,timestamp,dataLength,encodedDataLength) {WI.networkManager.resourceRequestDidReceiveData(requestId,dataLength,encodedDataLength,timestamp);} loadingFinished(requestId,timestamp,sourceMapURL,metrics) {WI.networkManager.resourceRequestDidFinishLoading(requestId,timestamp,sourceMapURL,metrics);} loadingFailed(requestId,timestamp,errorText,canceled) {WI.networkManager.resourceRequestDidFailLoading(requestId,canceled,timestamp,errorText);} requestServedFromMemoryCache(requestId,frameId,loaderId,documentURL,timestamp,initiator,resource) {WI.networkManager.resourceRequestWasServedFromMemoryCache(requestId,frameId,loaderId,resource,timestamp,initiator);} webSocketCreated(requestId,url) {WI.networkManager.webSocketCreated(requestId,url);} webSocketWillSendHandshakeRequest(requestId,timestamp,walltime,request) {WI.networkManager.webSocketWillSendHandshakeRequest(requestId,timestamp,walltime,request);} webSocketHandshakeResponseReceived(requestId,timestamp,response) {WI.networkManager.webSocketHandshakeResponseReceived(requestId,timestamp,response);} webSocketClosed(requestId,timestamp) {WI.networkManager.webSocketClosed(requestId,timestamp);} webSocketFrameReceived(requestId,timestamp,response) {WI.networkManager.webSocketFrameReceived(requestId,timestamp,response);} webSocketFrameSent(requestId,timestamp,response) {WI.networkManager.webSocketFrameSent(requestId,timestamp,response);} webSocketFrameError(requestId,timestamp,errorMessage) {} requestIntercepted(requestId,request) {WI.networkManager.requestIntercepted(this._target,requestId,request);} responseIntercepted(requestId,response) {WI.networkManager.responseIntercepted(this._target,requestId,response);}};WI.PageObserver=class PageObserver extends InspectorBackend.Dispatcher {domContentEventFired(timestamp) {WI.timelineManager.pageDOMContentLoadedEventFired(timestamp);} loadEventFired(timestamp) {WI.timelineManager.pageLoadEventFired(timestamp);} frameNavigated(frame,loaderId) {WI.networkManager.frameDidNavigate(frame,loaderId);} frameDetached(frameId) {WI.networkManager.frameDidDetach(frameId);} defaultAppearanceDidChange(appearance) {WI.cssManager.defaultAppearanceDidChange(appearance);} defaultUserPreferencesDidChange(userPreferences) {WI.cssManager.defaultUserPreferencesDidChange(userPreferences);} frameStartedLoading(frameId) {} frameStoppedLoading(frameId) {} frameScheduledNavigation(frameId,delay) {} frameClearedScheduledNavigation(frameId) {}};WI.RuntimeObserver=class RuntimeObserver extends InspectorBackend.Dispatcher {executionContextCreated(contextPayload) {WI.networkManager.executionContextCreated(contextPayload);}};WI.ScriptProfilerObserver=class ScriptProfilerObserver extends InspectorBackend.Dispatcher {trackingStart(timestamp) {WI.timelineManager.scriptProfilerTrackingStarted(timestamp);} trackingUpdate(event) {WI.timelineManager.scriptProfilerTrackingUpdated(event);} trackingComplete(timestamp,samples) {WI.timelineManager.scriptProfilerTrackingCompleted(timestamp,samples);} programmaticCaptureStarted() {} programmaticCaptureStopped() {}};WI.TargetObserver=class TargetObserver extends InspectorBackend.Dispatcher {targetCreated(targetInfo) {WI.targetManager.targetCreated(this._target,targetInfo);} didCommitProvisionalTarget(oldTargetId,newTargetId) {WI.targetManager.didCommitProvisionalTarget(this._target,oldTargetId,newTargetId);} targetDestroyed(targetId) {WI.targetManager.targetDestroyed(targetId);} dispatchMessageFromTarget(targetId,message) {WI.targetManager.dispatchMessageFromTarget(targetId,message);}};WI.TimelineObserver=class TimelineObserver extends InspectorBackend.Dispatcher {eventRecorded(record) {WI.timelineManager.eventRecorded(record);} recordingStarted(startTime) {WI.timelineManager.capturingStarted(startTime);} recordingStopped(endTime) {WI.timelineManager.capturingStopped(endTime);} autoCaptureStarted() {WI.timelineManager.autoCaptureStarted();} programmaticCaptureStarted() {} programmaticCaptureStopped() {}};WI.WorkerObserver=class WorkerObserver extends InspectorBackend.Dispatcher {workerCreated(workerId,url,name) {WI.workerManager.workerCreated(this._target,workerId,url,name);} workerTerminated(workerId) {WI.workerManager.workerTerminated(workerId);} dispatchMessageFromWorker(workerId,message) {WI.workerManager.dispatchMessageFromWorker(workerId,message);}};WI.Breakpoint=class Breakpoint extends WI.Object {constructor({disabled,condition,actions,ignoreCount,autoContinue}={}) {super();this._disabled=disabled||false;this._condition=condition||"";this._ignoreCount=ignoreCount||0;this._autoContinue=autoContinue||false;this._actions=actions||[];for(let action of this._actions) action.addEventListener(WI.BreakpointAction.Event.Modified,this._handleBreakpointActionModified,this);} toJSON(key) {let json={};if(this._disabled) json.disabled=this._disabled;if(this.editable){if(this._condition) json.condition=this._condition;if(this._ignoreCount) json.ignoreCount=this._ignoreCount;if(this._actions.length) json.actions=this._actions.map((action)=>action.toJSON());if(this._autoContinue) json.autoContinue=this._autoContinue;} return json;} get displayName() {throw WI.NotImplementedError.subclassMustOverride();} get special() {return false;} get removable() {return true;} get editable() {return false;} get resolved() {return WI.debuggerManager.breakpointsEnabled;} get disabled() {return this._disabled;} set disabled(disabled) {if(this._disabled===disabled) return;this._disabled=disabled||false;this.dispatchEventToListeners(WI.Breakpoint.Event.DisabledStateDidChange);} get condition() {return this._condition;} set condition(condition) {if(this._condition===condition) return;this._condition=condition;this.dispatchEventToListeners(WI.Breakpoint.Event.ConditionDidChange);} get ignoreCount() {return this._ignoreCount;} set ignoreCount(ignoreCount) {if(ignoreCount<0) return;if(this._ignoreCount===ignoreCount) return;this._ignoreCount=ignoreCount;this.dispatchEventToListeners(WI.Breakpoint.Event.IgnoreCountDidChange);} get autoContinue() {return this._autoContinue;} set autoContinue(cont) {if(this._autoContinue===cont) return;this._autoContinue=cont;this.dispatchEventToListeners(WI.Breakpoint.Event.AutoContinueDidChange);} get actions() {return this._actions;} get probeActions() {return this._actions.filter(function(action){return action.type===WI.BreakpointAction.Type.Probe;});} addAction(action,{precedingAction}={}) {action.addEventListener(WI.BreakpointAction.Event.Modified,this._handleBreakpointActionModified,this);if(!precedingAction) this._actions.push(action);else{var index=this._actions.indexOf(precedingAction);if(index===-1) this._actions.push(action);else this._actions.splice(index+1,0,action);} this.dispatchEventToListeners(WI.Breakpoint.Event.ActionsDidChange);} removeAction(action) {var index=this._actions.indexOf(action);if(index===-1) return;this._actions.splice(index,1);action.removeEventListener(WI.BreakpointAction.Event.Modified,this._handleBreakpointActionModified,this);if(!this._actions.length) this.autoContinue=false;this.dispatchEventToListeners(WI.Breakpoint.Event.ActionsDidChange);} clearActions(type) {if(!type) this._actions=[];else this._actions=this._actions.filter(function(action){return action.type!==type;});this.dispatchEventToListeners(WI.Breakpoint.Event.ActionsDidChange);} reset() {this.condition="";this.ignoreCount=0;this.autoContinue=false;this.clearActions();} remove() {} optionsToProtocol() {let payload={};if(this._condition) payload.condition=this._condition;if(this._actions.length){payload.actions=this._actions.map((action)=>action.toProtocol()).filter((action)=>{if(action.type!==WI.BreakpointAction.Type.Log) return true;if(!/\$\{.*?\}/.test(action.data)) return true;let lexer=new WI.BreakpointLogMessageLexer;let tokens=lexer.tokenize(action.data);if(!tokens) return false;let templateLiteral=tokens.reduce((text,token)=>{if(token.type===WI.BreakpointLogMessageLexer.TokenType.PlainText) return text+token.data.escapeCharacters("`\\");if(token.type===WI.BreakpointLogMessageLexer.TokenType.Expression) return text+"${"+token.data+"}";return text;},"");action.data="console.log(`"+templateLiteral+"`)";action.type=WI.BreakpointAction.Type.Evaluate;return true;});} if(this._autoContinue) payload.autoContinue=this._autoContinue;if(this._ignoreCount) payload.ignoreCount=this._ignoreCount;return!isEmptyObject(payload)?payload:undefined;} _handleBreakpointActionModified(event) {this.dispatchEventToListeners(WI.Breakpoint.Event.ActionsDidChange);}};WI.Breakpoint.TypeIdentifier="breakpoint";WI.Breakpoint.Event={DisabledStateDidChange:"breakpoint-disabled-state-did-change",ConditionDidChange:"breakpoint-condition-did-change",IgnoreCountDidChange:"breakpoint-ignore-count-did-change",ActionsDidChange:"breakpoint-actions-did-change",AutoContinueDidChange:"breakpoint-auto-continue-did-change",};WI.BreakpointAction=class BreakpointAction extends WI.Object {constructor(type,{data,emulateUserGesture}={}) {super();this._type=type;this._data=data||null;this._id=WI.debuggerManager.nextBreakpointActionIdentifier();this._emulateUserGesture=!!emulateUserGesture;} static supportsEmulateUserAction() {return WI.sharedApp.isWebDebuggable()&&InspectorBackend.hasCommand("Debugger.setPauseOnExceptions","options");} static fromJSON(json) {return new WI.BreakpointAction(json.type,{data:json.data,emulateUserGesture:json.emulateUserGesture,});} toJSON() {let json={type:this._type,};if(this._data) json.data=this._data;if(this._emulateUserGesture) json.emulateUserGesture=this._emulateUserGesture;return json;} get id(){return this._id;} get type() {return this._type;} set type(type) {if(type===this._type) return;this._type=type;this.dispatchEventToListeners(WI.BreakpointAction.Event.Modified);} get data() {return this._data;} set data(data) {if(this._data===data) return;this._data=data;this.dispatchEventToListeners(WI.BreakpointAction.Event.Modified);} get emulateUserGesture() {return this._emulateUserGesture;} set emulateUserGesture(emulateUserGesture) {if(this._emulateUserGesture===emulateUserGesture) return;this._emulateUserGesture=emulateUserGesture;this.dispatchEventToListeners(WI.BreakpointAction.Event.Modified);} toProtocol() {let json=this.toJSON();json.id=this._id;return json;}};WI.BreakpointAction.Type={Log:"log",Evaluate:"evaluate",Sound:"sound",Probe:"probe"};WI.BreakpointAction.Event={Modified:"breakpoint-action-modified",};WI.Collection=class Collection extends WI.Object {constructor(items=[]) {super();this._items=new Set;for(let item of items) this.add(item);} get size() {return this._items.size;} get displayName() {throw WI.NotImplementedError.subclassMustOverride();} objectIsRequiredType(object) {throw WI.NotImplementedError.subclassMustOverride();} add(item) {let isValidType=this.objectIsRequiredType(item);if(!isValidType) return;this._items.add(item);this.itemAdded(item);this.dispatchEventToListeners(WI.Collection.Event.ItemAdded,{item});} remove(item) {let wasRemoved=this._items.delete(item);this.itemRemoved(item);this.dispatchEventToListeners(WI.Collection.Event.ItemRemoved,{item});} has(...args) {return this._items.has(...args);} clear() {let items=new Set(this._items);this._items.clear();this.itemsCleared(items);for(let item of items) this.dispatchEventToListeners(WI.Collection.Event.ItemRemoved,{item});} toJSON() {return Array.from(this);} [Symbol.iterator]() {return this._items[Symbol.iterator]();} itemAdded(item) {} itemRemoved(item) {} itemsCleared(items) {}};WI.Collection.Event={ItemAdded:"collection-item-added",ItemRemoved:"collection-item-removed",};WI.ConsoleMessage=class ConsoleMessage {constructor(target,source,level,message,type,url,line,column,repeatCount,parameters,stackTrace,request,timestamp) {this._target=target;this._source=source;this._level=level;this._messageText=message;this._type=type||WI.ConsoleMessage.MessageType.Log;this._url=url||null;this._line=line||0;this._column=column||0;this._sourceCodeLocation=undefined;this._repeatCount=repeatCount||0;this._parameters=parameters;this._stackTrace=stackTrace||null;this._request=request;this._timestamp=timestamp??NaN;} get target(){return this._target;} get source(){return this._source;} get level(){return this._level;} get messageText(){return this._messageText;} get type(){return this._type;} get url(){return this._url;} get line(){return this._line;} get column(){return this._column;} get repeatCount(){return this._repeatCount;} get parameters(){return this._parameters;} get stackTrace(){return this._stackTrace;} get request(){return this._request;} get timestamp(){return this._timestamp;} get sourceCodeLocation() {if(this._sourceCodeLocation!==undefined) return this._sourceCodeLocation;let topCallFrame=this._stackTrace?.callFrames[0];if(topCallFrame&&topCallFrame.sourceCodeLocation){this._sourceCodeLocation=topCallFrame.sourceCodeLocation;return this._sourceCodeLocation;} if(this._url&&this._url!=="undefined"){let sourceCode=WI.networkManager.resourcesForURL(this._url).firstValue;if(sourceCode){let lineNumber=this._line>0?this._line-1:0;let columnNumber=this._column>0?this._column-1:0;this._sourceCodeLocation=new WI.SourceCodeLocation(sourceCode,lineNumber,columnNumber);return this._sourceCodeLocation;}} this._sourceCodeLocation=null;return this._sourceCodeLocation;}};WI.ConsoleMessage.MessageSource={HTML:"html",XML:"xml",JS:"javascript",Network:"network",ConsoleAPI:"console-api",Storage:"storage",Appcache:"appcache",Rendering:"rendering",CSS:"css",Security:"security",Media:"media",MediaSource:"mediasource",WebRTC:"webrtc",ITPDebug:"itp-debug",PrivateClickMeasurement:"private-click-measurement",PaymentRequest:"payment-request",Other:"other",AdClickAttribution:"ad-click-attribution",};WI.ConsoleMessage.MessageType={Log:"log",Dir:"dir",DirXML:"dirxml",Table:"table",Trace:"trace",StartGroup:"startGroup",StartGroupCollapsed:"startGroupCollapsed",EndGroup:"endGroup",Assert:"assert",Timing:"timing",Profile:"profile",ProfileEnd:"profileEnd",Image:"image",Result:"result",};WI.ConsoleMessage.MessageLevel={Log:"log",Info:"info",Warning:"warning",Error:"error",Debug:"debug",};WI.Instrument=class Instrument { static createForTimelineType(type) {switch(type){case WI.TimelineRecord.Type.Network:return new WI.NetworkInstrument;case WI.TimelineRecord.Type.Layout:return new WI.LayoutInstrument;case WI.TimelineRecord.Type.Script:return new WI.ScriptInstrument;case WI.TimelineRecord.Type.RenderingFrame:return new WI.FPSInstrument;case WI.TimelineRecord.Type.CPU:return new WI.CPUInstrument;case WI.TimelineRecord.Type.Memory:return new WI.MemoryInstrument;case WI.TimelineRecord.Type.HeapAllocations:return new WI.HeapAllocationsInstrument;case WI.TimelineRecord.Type.Media:return new WI.MediaInstrument;case WI.TimelineRecord.Type.Screenshots:return new WI.ScreenshotsInstrument;default:console.error("Unknown TimelineRecord.Type: "+type);return null;}} static startLegacyTimelineAgent(initiatedByBackend) {if(WI.Instrument._legacyTimelineAgentStarted) return;WI.Instrument._legacyTimelineAgentStarted=true;if(initiatedByBackend) return;let target=WI.assumingMainTarget();target.TimelineAgent.start();} static stopLegacyTimelineAgent(initiatedByBackend) {if(!WI.Instrument._legacyTimelineAgentStarted) return;WI.Instrument._legacyTimelineAgentStarted=false;if(initiatedByBackend) return;let target=WI.assumingMainTarget();target.TimelineAgent.stop();} get timelineRecordType() {return null;} startInstrumentation(initiatedByBackend) {WI.Instrument.startLegacyTimelineAgent(initiatedByBackend);} stopInstrumentation(initiatedByBackend) {WI.Instrument.stopLegacyTimelineAgent(initiatedByBackend);}};WI.Instrument._legacyTimelineAgentStarted=false;WI.SourceCode=class SourceCode extends WI.Object {constructor(url) {super();this._url=url;this._urlComponents=null;this._originalRevision=new WI.SourceCodeRevision(this);this._currentRevision=this._originalRevision;this._sourceMaps=null;this._formatterSourceMap=null;this._requestContentPromise=null;} static generateSpecialContentForURL(url) {if(url==="about:blank"){return Promise.resolve({content:"",message:WI.unlocalizedString("about:blank")});} return null;} get displayName() {console.error("Needs to be implemented by a subclass.");return"";} get originalRevision() {return this._originalRevision;} get currentRevision() {return this._currentRevision;} set currentRevision(revision) {if(!(revision instanceof WI.SourceCodeRevision)) return;if(revision.sourceCode!==this) return;this._currentRevision=revision;this.dispatchEventToListeners(WI.SourceCode.Event.ContentDidChange);} get editableRevision() {if(this._currentRevision===this._originalRevision) this._currentRevision=this._originalRevision.copy();return this._currentRevision;} get content() {return this._currentRevision.content;} get base64Encoded() {return this._currentRevision.base64Encoded;} get url() {return this._url;} get urlComponents() {if(!this._urlComponents) this._urlComponents=parseURL(this._url);return this._urlComponents;} get contentIdentifier() { return this.url;} get isScript() {return false;} get supportsScriptBlackboxing() {if(!this.isScript) return false;if(!WI.DebuggerManager.supportsBlackboxingScripts()) return false;let contentIdentifier=this.contentIdentifier;return contentIdentifier&&!isWebKitInjectedScript(contentIdentifier);} get localResourceOverride() {return null;} get sourceMaps() {return this._sourceMaps||[];} addSourceMap(sourceMap) {if(!this._sourceMaps) this._sourceMaps=[];this._sourceMaps.push(sourceMap);this.dispatchEventToListeners(WI.SourceCode.Event.SourceMapAdded);} get formatterSourceMap() {return this._formatterSourceMap;} set formatterSourceMap(formatterSourceMap) {this._formatterSourceMap=formatterSourceMap;this.dispatchEventToListeners(WI.SourceCode.Event.FormatterDidChange);} requestContent() {this._requestContentPromise=this._requestContentPromise||this.requestContentFromBackend().then(this._processContent.bind(this));return this._requestContentPromise;} createSourceCodeLocation(lineNumber,columnNumber) {return new WI.SourceCodeLocation(this,lineNumber,columnNumber);} createLazySourceCodeLocation(lineNumber,columnNumber) {return new WI.LazySourceCodeLocation(this,lineNumber,columnNumber);} createSourceCodeTextRange(textRange) {return new WI.SourceCodeTextRange(this,textRange);} revisionContentDidChange(revision) {if(this._ignoreRevisionContentDidChangeEvent) return;if(revision!==this._currentRevision) return;this.handleCurrentRevisionContentChange();this.dispatchEventToListeners(WI.SourceCode.Event.ContentDidChange);} handleCurrentRevisionContentChange() {} get revisionForRequestedContent() {return this._originalRevision;} markContentAsStale() {this._requestContentPromise=null;this._contentReceived=false;} requestContentFromBackend() {console.error("Needs to be implemented by a subclass.");return Promise.reject(new Error("Needs to be implemented by a subclass."));} get mimeType() {console.error("Needs to be implemented by a subclass.");} _processContent(parameters) {let rawContent=parameters.content||parameters.body||parameters.text||parameters.scriptSource;let rawBase64Encoded=!!parameters.base64Encoded;let content=rawContent;let error=parameters.error;let message=parameters.message;if(parameters.base64Encoded) content=content?WI.BlobUtilities.decodeBase64ToBlob(content,this.mimeType):"";let revision=this.revisionForRequestedContent;this._ignoreRevisionContentDidChangeEvent=true;revision.updateRevisionContent(rawContent,{base64Encoded:rawBase64Encoded,mimeType:this.mimeType,blobContent:content instanceof Blob?content:null,});this._ignoreRevisionContentDidChangeEvent=false; return Promise.resolve({error,message,sourceCode:this,content,rawContent,rawBase64Encoded,});}};WI.SourceCode.Event={ContentDidChange:"source-code-content-did-change",SourceMapAdded:"source-code-source-map-added",FormatterDidChange:"source-code-formatter-did-change",LoadingDidFinish:"source-code-loading-did-finish",LoadingDidFail:"source-code-loading-did-fail"};WI.SourceCodeLocation=class SourceCodeLocation extends WI.Object {constructor(sourceCode,lineNumber,columnNumber) {super();this._sourceCode=sourceCode||null;this._lineNumber=lineNumber;this._columnNumber=columnNumber;this._resolveFormattedLocation();if(this._sourceCode){this._sourceCode.addEventListener(WI.SourceCode.Event.SourceMapAdded,this._sourceCodeSourceMapAdded,this);this._sourceCode.addEventListener(WI.SourceCode.Event.FormatterDidChange,this._sourceCodeFormatterDidChange,this);} this._resetMappedLocation();} static get specialBreakpointLocation() {return new WI.SourceCodeLocation(null,Infinity,Infinity);} isEqual(other) {if(!other) return false;if(this.lineNumber!==other.lineNumber) return false;if(this.columnNumber!==other.columnNumber) return false;function resolveSourceCode(sourceCode){if(sourceCode instanceof WI.Script) return sourceCode.resource;return sourceCode;} let thisSourceCode=resolveSourceCode(this.sourceCode);let otherSourceCode=resolveSourceCode(other.sourceCode);if(thisSourceCode!==otherSourceCode) return false;return true;} get sourceCode() {return this._sourceCode;} set sourceCode(sourceCode) {this.setSourceCode(sourceCode);} get lineNumber() {return this._lineNumber;} get columnNumber() {return this._columnNumber;} position() {return new WI.SourceCodePosition(this.lineNumber,this.columnNumber);} get formattedLineNumber() {return this._formattedLineNumber;} get formattedColumnNumber() {return this._formattedColumnNumber;} formattedPosition() {return new WI.SourceCodePosition(this.formattedLineNumber,this.formattedColumnNumber);} get displaySourceCode() {this.resolveMappedLocation();return this._mappedResource||this._sourceCode;} get displayLineNumber() {this.resolveMappedLocation();return isNaN(this._mappedLineNumber)?this._formattedLineNumber:this._mappedLineNumber;} get displayColumnNumber() {this.resolveMappedLocation();return isNaN(this._mappedColumnNumber)?this._formattedColumnNumber:this._mappedColumnNumber;} displayPosition() {return new WI.SourceCodePosition(this.displayLineNumber,this.displayColumnNumber);} originalLocationString(columnStyle,nameStyle,prefix) {return this._locationString(this.sourceCode,this.lineNumber,this.columnNumber,columnStyle,nameStyle,prefix);} formattedLocationString(columnStyle,nameStyle,prefix) {return this._locationString(this.sourceCode,this.formattedLineNumber,this.formattedColumn,columnStyle,nameStyle,prefix);} displayLocationString(columnStyle,nameStyle,prefix) {return this._locationString(this.displaySourceCode,this.displayLineNumber,this.displayColumnNumber,columnStyle,nameStyle,prefix);} tooltipString() {if(!this.hasDifferentDisplayLocation()) return this.originalLocationString(WI.SourceCodeLocation.ColumnStyle.Shown,WI.SourceCodeLocation.NameStyle.Full);var tooltip=WI.UIString("Located at %s").format(this.displayLocationString(WI.SourceCodeLocation.ColumnStyle.Shown,WI.SourceCodeLocation.NameStyle.Full));tooltip+="\n"+WI.UIString("Originally %s").format(this.originalLocationString(WI.SourceCodeLocation.ColumnStyle.Shown,WI.SourceCodeLocation.NameStyle.Full));return tooltip;} hasMappedLocation() {this.resolveMappedLocation();return this._mappedResource!==null;} hasFormattedLocation() {return this._formattedLineNumber!==this._lineNumber||this._formattedColumnNumber!==this._columnNumber;} hasDifferentDisplayLocation() {return this.hasMappedLocation()||this.hasFormattedLocation();} update(sourceCode,lineNumber,columnNumber) {if(sourceCode===this._sourceCode&&lineNumber===this._lineNumber&&columnNumber===this._columnNumber) return;if(this._mappedResource&&sourceCode===this._mappedResource&&lineNumber===this._mappedLineNumber&&columnNumber===this._mappedColumnNumber) return;var newSourceCodeLocation=sourceCode.createSourceCodeLocation(lineNumber,columnNumber);this._makeChangeAndDispatchChangeEventIfNeeded(function(){this._lineNumber=newSourceCodeLocation._lineNumber;this._columnNumber=newSourceCodeLocation._columnNumber;if(newSourceCodeLocation._mappedLocationIsResolved){this._mappedLocationIsResolved=true;this._mappedResource=newSourceCodeLocation._mappedResource;this._mappedLineNumber=newSourceCodeLocation._mappedLineNumber;this._mappedColumnNumber=newSourceCodeLocation._mappedColumnNumber;}});} populateLiveDisplayLocationTooltip(element,prefix,suffix) {prefix=prefix||"";suffix=suffix||"";element.title=prefix+this.tooltipString()+suffix;this.addEventListener(WI.SourceCodeLocation.Event.DisplayLocationChanged,function(event){if(this.sourceCode) element.title=prefix+this.tooltipString()+suffix;},this);} populateLiveDisplayLocationString(element,propertyName,columnStyle,nameStyle,prefix) {var currentDisplay;function updateDisplayString(showAlternativeLocation,forceUpdate) {if(!forceUpdate&¤tDisplay===showAlternativeLocation) return;currentDisplay=showAlternativeLocation;if(!showAlternativeLocation){element[propertyName]=this.displayLocationString(columnStyle,nameStyle,prefix);element.classList.toggle(WI.SourceCodeLocation.DisplayLocationClassName,this.hasDifferentDisplayLocation());}else if(this.hasDifferentDisplayLocation()){element[propertyName]=this.originalLocationString(columnStyle,nameStyle,prefix);element.classList.remove(WI.SourceCodeLocation.DisplayLocationClassName);}} function mouseOverOrMove(event) {updateDisplayString.call(this,event.metaKey&&!event.altKey&&!event.shiftKey);} updateDisplayString.call(this,false);this.addEventListener(WI.SourceCodeLocation.Event.DisplayLocationChanged,function(event){if(this.sourceCode) updateDisplayString.call(this,currentDisplay,true);},this);var boundMouseOverOrMove=mouseOverOrMove.bind(this);element.addEventListener("mouseover",boundMouseOverOrMove);element.addEventListener("mousemove",boundMouseOverOrMove);element.addEventListener("mouseout",(event)=>{updateDisplayString.call(this,false);});} setSourceCode(sourceCode) {if(sourceCode===this._sourceCode) return;this._makeChangeAndDispatchChangeEventIfNeeded(function(){if(this._sourceCode){this._sourceCode.removeEventListener(WI.SourceCode.Event.SourceMapAdded,this._sourceCodeSourceMapAdded,this);this._sourceCode.removeEventListener(WI.SourceCode.Event.FormatterDidChange,this._sourceCodeFormatterDidChange,this);} this._sourceCode=sourceCode;if(this._sourceCode){this._sourceCode.addEventListener(WI.SourceCode.Event.SourceMapAdded,this._sourceCodeSourceMapAdded,this);this._sourceCode.addEventListener(WI.SourceCode.Event.FormatterDidChange,this._sourceCodeFormatterDidChange,this);}});} resolveMappedLocation() {if(this._mappedLocationIsResolved) return;this._mappedLocationIsResolved=true;if(!this._sourceCode) return;var sourceMaps=this._sourceCode.sourceMaps;if(!sourceMaps.length) return;for(var i=0;i0) lineString+=":"+(columnNumber+1);else if(columnStyle===WI.SourceCodeLocation.ColumnStyle.OnlyIfLarge&&columnNumber>WI.SourceCodeLocation.LargeColumnNumber) lineString+=":"+(columnNumber+1);else if(columnStyle===WI.SourceCodeLocation.ColumnStyle.Hidden) lineString="";switch(nameStyle){case WI.SourceCodeLocation.NameStyle.None:return prefix+lineString;case WI.SourceCodeLocation.NameStyle.Short:case WI.SourceCodeLocation.NameStyle.Full:var displayURL=sourceCode.displayURL;var name=nameStyle===WI.SourceCodeLocation.NameStyle.Full&&displayURL?displayURL:sourceCode.displayName;if(columnStyle===WI.SourceCodeLocation.ColumnStyle.Hidden) return prefix+name;var lineSuffix=displayURL?":"+lineString:WI.UIString(" (line %s)").format(lineString);return prefix+name+lineSuffix;default:console.error("Unknown nameStyle: "+nameStyle);return prefix+lineString;}} _resetMappedLocation() {this._mappedLocationIsResolved=false;this._mappedResource=null;this._mappedLineNumber=NaN;this._mappedColumnNumber=NaN;} _setMappedLocation(mappedResource,mappedLineNumber,mappedColumnNumber) {this._mappedLocationIsResolved=true;this._mappedResource=mappedResource;this._mappedLineNumber=mappedLineNumber;this._mappedColumnNumber=mappedColumnNumber;} _resolveFormattedLocation() {if(this._sourceCode&&this._sourceCode.formatterSourceMap){var formattedLocation=this._sourceCode.formatterSourceMap.originalToFormatted(this._lineNumber,this._columnNumber);this._formattedLineNumber=formattedLocation.lineNumber;this._formattedColumnNumber=formattedLocation.columnNumber;}else{this._formattedLineNumber=this._lineNumber;this._formattedColumnNumber=this._columnNumber;}} _makeChangeAndDispatchChangeEventIfNeeded(changeFunction) {var oldSourceCode=this._sourceCode;var oldLineNumber=this._lineNumber;var oldColumnNumber=this._columnNumber;var oldFormattedLineNumber=this._formattedLineNumber;var oldFormattedColumnNumber=this._formattedColumnNumber;var oldDisplaySourceCode=this.displaySourceCode;var oldDisplayLineNumber=this.displayLineNumber;var oldDisplayColumnNumber=this.displayColumnNumber;this._resetMappedLocation();if(changeFunction) changeFunction.call(this);this.resolveMappedLocation();this._resolveFormattedLocation();var displayLocationChanged=false;var newDisplaySourceCode=this.displaySourceCode;if(oldDisplaySourceCode!==newDisplaySourceCode) displayLocationChanged=true;else if(newDisplaySourceCode&&(oldDisplayLineNumber!==this.displayLineNumber||oldDisplayColumnNumber!==this.displayColumnNumber)) displayLocationChanged=true;var anyLocationChanged=false;if(displayLocationChanged) anyLocationChanged=true;else if(oldSourceCode!==this._sourceCode) anyLocationChanged=true;else if(this._sourceCode&&(oldLineNumber!==this._lineNumber||oldColumnNumber!==this._columnNumber)) anyLocationChanged=true;else if(this._sourceCode&&(oldFormattedLineNumber!==this._formattedLineNumber||oldFormattedColumnNumber!==this._formattedColumnNumber)) anyLocationChanged=true;if(displayLocationChanged||anyLocationChanged){var oldData={oldSourceCode,oldLineNumber,oldColumnNumber,oldFormattedLineNumber,oldFormattedColumnNumber,oldDisplaySourceCode,oldDisplayLineNumber,oldDisplayColumnNumber};if(displayLocationChanged) this.dispatchEventToListeners(WI.SourceCodeLocation.Event.DisplayLocationChanged,oldData);if(anyLocationChanged) this.dispatchEventToListeners(WI.SourceCodeLocation.Event.LocationChanged,oldData);}} _sourceCodeSourceMapAdded() {this._makeChangeAndDispatchChangeEventIfNeeded(null);} _sourceCodeFormatterDidChange() {this._makeChangeAndDispatchChangeEventIfNeeded(null);}};WI.SourceCodeLocation.DisplayLocationClassName="display-location";WI.SourceCodeLocation.LargeColumnNumber=80;WI.SourceCodeLocation.NameStyle={None:"none",Short:"short",Full:"full"};WI.SourceCodeLocation.ColumnStyle={Hidden:"hidden",OnlyIfLarge:"only-if-large",Shown:"shown"};WI.SourceCodeLocation.Event={LocationChanged:"source-code-location-location-changed",DisplayLocationChanged:"source-code-location-display-location-changed"};WI.Timeline=class Timeline extends WI.Object {constructor(type) {super();this._type=type;this.reset(true);} static create(type) {if(type===WI.TimelineRecord.Type.Network) return new WI.NetworkTimeline(type);if(type===WI.TimelineRecord.Type.CPU) return new WI.CPUTimeline(type);if(type===WI.TimelineRecord.Type.Memory) return new WI.MemoryTimeline(type);if(type===WI.TimelineRecord.Type.Media) return new WI.MediaTimeline(type);return new WI.Timeline(type);} get type(){return this._type;} get startTime(){return this._startTime;} get endTime(){return this._endTime;} get records(){return this._records;} reset(suppressEvents) {this._records=[];this._startTime=NaN;this._endTime=NaN;if(!suppressEvents){this.dispatchEventToListeners(WI.Timeline.Event.TimesUpdated);this.dispatchEventToListeners(WI.Timeline.Event.Reset);}} addRecord(record,options={}) {if(record.updatesDynamically) record.addEventListener(WI.TimelineRecord.Event.Updated,this._recordUpdated,this); this._tryInsertingRecordInSortedOrder(record);this._updateTimesIfNeeded(record);this.dispatchEventToListeners(WI.Timeline.Event.RecordAdded,{record});} saveIdentityToCookie(cookie) {cookie[WI.Timeline.TimelineTypeCookieKey]=this._type;} refresh() {this.dispatchEventToListeners(WI.Timeline.Event.Refreshed);} closestRecordTo(timestamp) {let lowerIndex=this._records.lowerBound(timestamp,(time,record)=>time-record.endTime);let recordBefore=this._records[lowerIndex-1];let recordAfter=this._records[lowerIndex];if(!recordBefore&&!recordAfter) return null;if(!recordBefore&&recordAfter) return recordAfter;if(!recordAfter&&recordBefore) return recordBefore;let before=Math.abs(recordBefore.endTime-timestamp);let after=Math.abs(recordAfter.startTime-timestamp);return(beforetime-record.endTime);if(includeRecordBeforeStart&&lowerIndex>0){lowerIndex--;let recordBefore=this._records[lowerIndex];if(recordBefore.parent&&recordBefore.parent.type===recordBefore.type){lowerIndex--;while(this._records[lowerIndex]!==recordBefore.parent) lowerIndex--;}} let upperIndex=this._records.upperBound(endTime,(time,record)=>time-record.startTime);if(includeRecordAfterEnd&&upperIndex=end;--i){if(this._records[i].startTime!localResourceOverride.disabled)[0];let isOverride=!!resource.localResourceOverride;let wasOverridden=resource.responseSource===WI.Resource.ResponseSource.InspectorOverride;let shouldBeOverridden=resource.isLoading()&&localResourceOverride;let shouldBeBlocked=(resource.failed||isOverride)&&localResourceOverride?.type===WI.LocalResourceOverride.InterceptType.Block;if(isOverride||wasOverridden||shouldBeOverridden||shouldBeBlocked){classes.push("override");if(shouldBeBlocked||localResourceOverride?.type===WI.LocalResourceOverride.InterceptType.ResponseSkippingNetwork) classes.push("skip-network");if(localResourceOverride?.localResource.mappedFilePath) classes.push("mapped-file");} if(resource.type===WI.Resource.Type.Other){if(resource.requestedByteRange) classes.push("resource-type-range");}else classes.push(resource.type);return classes;} static displayNameForProtocol(protocol) {switch(protocol){case"h2":return"HTTP/2";case"http/1.0":return"HTTP/1.0";case"http/1.1":return"HTTP/1.1";case"spdy/2":return"SPDY/2";case"spdy/3":return"SPDY/3";case"spdy/3.1":return"SPDY/3.1";default:return null;}} static comparePriority(a,b) {const map={[WI.Resource.NetworkPriority.Unknown]:0,[WI.Resource.NetworkPriority.Low]:1,[WI.Resource.NetworkPriority.Medium]:2,[WI.Resource.NetworkPriority.High]:3,};let aNum=map[a]||0;let bNum=map[b]||0;return aNum-bNum;} static displayNameForPriority(priority) {switch(priority){case WI.Resource.NetworkPriority.Low:return WI.UIString("Low","Low @ Network Priority","Low network request priority");case WI.Resource.NetworkPriority.Medium:return WI.UIString("Medium","Medium @ Network Priority","Medium network request priority");case WI.Resource.NetworkPriority.High:return WI.UIString("High","High @ Network Priority","High network request priority");default:return null;}} static responseSourceFromPayload(source) {if(!source) return WI.Resource.ResponseSource.Unknown;switch(source){case InspectorBackend.Enum.Network.ResponseSource.Unknown:return WI.Resource.ResponseSource.Unknown;case InspectorBackend.Enum.Network.ResponseSource.Network:return WI.Resource.ResponseSource.Network;case InspectorBackend.Enum.Network.ResponseSource.MemoryCache:return WI.Resource.ResponseSource.MemoryCache;case InspectorBackend.Enum.Network.ResponseSource.DiskCache:return WI.Resource.ResponseSource.DiskCache;case InspectorBackend.Enum.Network.ResponseSource.ServiceWorker:return WI.Resource.ResponseSource.ServiceWorker;case InspectorBackend.Enum.Network.ResponseSource.InspectorOverride:return WI.Resource.ResponseSource.InspectorOverride;default:console.error("Unknown response source type",source);return WI.Resource.ResponseSource.Unknown;}} static networkPriorityFromPayload(priority) {switch(priority){case InspectorBackend.Enum.Network.MetricsPriority.Low:return WI.Resource.NetworkPriority.Low;case InspectorBackend.Enum.Network.MetricsPriority.Medium:return WI.Resource.NetworkPriority.Medium;case InspectorBackend.Enum.Network.MetricsPriority.High:return WI.Resource.NetworkPriority.High;default:console.error("Unknown metrics priority",priority);return WI.Resource.NetworkPriority.Unknown;}} static connectionIdentifierFromPayload(connectionIdentifier) {if(!WI.Resource.connectionIdentifierMap){WI.Resource.connectionIdentifierMap=new Map;WI.Resource.nextConnectionIdentifier=1;} let id=WI.Resource.connectionIdentifierMap.get(connectionIdentifier);if(id) return id;id=WI.Resource.nextConnectionIdentifier++;WI.Resource.connectionIdentifierMap.set(connectionIdentifier,id);return id;} get mimeType(){return this._mimeType;} get target(){return this._target;} get type(){return this._type;} get loaderIdentifier(){return this._loaderIdentifier;} get requestIdentifier(){return this._requestIdentifier;} get requestMethod(){return this._requestMethod;} get requestData(){return this._requestData;} get initiatorStackTrace(){return this._initiatorStackTrace;} get initiatorSourceCodeLocation(){return this._initiatorSourceCodeLocation;} get initiatorNode(){return this._initiatorNode;} get initiatedResources(){return this._initiatedResources;} get statusCode(){return this._statusCode;} get statusText(){return this._statusText;} get responseSource(){return this._responseSource;} get security(){return this._security;} get timingData(){return this._timingData;} get protocol(){return this._protocol;} get priority(){return this._priority;} get remoteAddress(){return this._remoteAddress;} get connectionIdentifier(){return this._connectionIdentifier;} get parentFrame(){return this._parentFrame;} get finished(){return this._finished;} get failed(){return this._failed;} get canceled(){return this._canceled;} get failureReasonText(){return this._failureReasonText;} get requestHeaders(){return this._requestHeaders;} get responseHeaders(){return this._responseHeaders;} get requestSentTimestamp(){return this._requestSentTimestamp;} get requestSentWalltime(){return this._requestSentWalltime;} get responseReceivedTimestamp(){return this._responseReceivedTimestamp;} get lastDataReceivedTimestamp(){return this._lastDataReceivedTimestamp;} get finishedOrFailedTimestamp(){return this._finishedOrFailedTimestamp;} get cached(){return this._cached;} get requestHeadersTransferSize(){return this._requestHeadersTransferSize;} get requestBodyTransferSize(){return this._requestBodyTransferSize;} get responseHeadersTransferSize(){return this._responseHeadersTransferSize;} get responseBodyTransferSize(){return this._responseBodyTransferSize;} get cachedResponseBodySize(){return this._cachedResponseBodySize;} get redirects(){return this._redirects;} get referrerPolicy(){return this._referrerPolicy;} get integrity(){return this._integrity;} get loadedSecurely() {if(this.urlComponents.scheme!=="https"&&this.urlComponents.scheme!=="wss"&&this.urlComponents.scheme!=="sftp") return false;if(isNaN(this._timingData.secureConnectionStart)&&!isNaN(this._timingData.connectionStart)) return false;return true;} get isScript() {return this._type===Resource.Type.Script;} get supportsScriptBlackboxing() {if(this.localResourceOverride) return false;if(!this.finished||this.failed) return false;return super.supportsScriptBlackboxing;} get displayName() {return WI.displayNameForURL(this._url,this.urlComponents);} get displayURL() {const isMultiLine=true;const dataURIMaxSize=64;return WI.truncateURL(this._url,isMultiLine,dataURIMaxSize);} get displayRemoteAddress() {if(this._isProxyConnection) return WI.UIString("%s (Proxy)","%s (Proxy) @ Resource Remote Address","Label for the IP address of a proxy server used to retrieve a network resource.").format(this._remoteAddress);return this._remoteAddress;} get mimeTypeComponents() {if(!this._mimeTypeComponents) this._mimeTypeComponents=parseMIMEType(this._mimeType);return this._mimeTypeComponents;} get syntheticMIMEType() { if(this._type===WI.Resource.typeFromMIMEType(this._mimeType)) return this._mimeType; switch(this._type){case WI.Resource.Type.StyleSheet:return"text/css";case WI.Resource.Type.Script:return"text/javascript";} return this._mimeType;} get hasMetadata() {return!!this._requestIdentifier;} createObjectURL() {let revision=this.currentRevision;let blobContent=revision.blobContent;if(blobContent) return URL.createObjectURL(blobContent) return this._url;} isMainResource() {return this._parentFrame?this._parentFrame.mainResource===this:false;} addInitiatedResource(resource) {if(!(resource instanceof WI.Resource)) return;this._initiatedResources.push(resource);this.dispatchEventToListeners(WI.Resource.Event.InitiatedResourcesDidChange);} get queryStringParameters() {if(this._queryStringParameters===undefined) this._queryStringParameters=parseQueryString(this.urlComponents.queryString,true);return this._queryStringParameters;} get requestFormParameters() {if(this._requestFormParameters===undefined) this._requestFormParameters=this.hasRequestFormParameters()?parseQueryString(this.requestData,true):null;return this._requestFormParameters;} get requestDataContentType() {return this._requestHeaders.valueForCaseInsensitiveKey("Content-Type")||null;} get requestCookies() {if(!this._requestCookies) this._requestCookies=WI.Cookie.parseCookieRequestHeader(this._requestHeaders.valueForCaseInsensitiveKey("Cookie"));return this._requestCookies;} get responseCookies() {if(!this._responseCookies){ let rawCombinedHeader=this._responseHeaders.valueForCaseInsensitiveKey("Set-Cookie")||"";let setCookieHeaders=rawCombinedHeader.split(/, (?![0-9])/);let cookies=[];for(let header of setCookieHeaders){let cookie=WI.Cookie.parseSetCookieResponseHeader(header);if(cookie) cookies.push(cookie);} this._responseCookies=cookies;} return this._responseCookies;} get requestSentDate() {return isNaN(this._requestSentWalltime)?null:new Date(this._requestSentWalltime*1000);} get lastRedirectReceivedTimestamp() {return this._redirects.length?this._redirects.lastValue.timestamp:NaN;} get firstTimestamp() {return this.timingData.startTime||this.lastRedirectReceivedTimestamp||this.responseReceivedTimestamp||this.lastDataReceivedTimestamp||this.finishedOrFailedTimestamp;} get lastTimestamp() {return this.timingData.responseEnd||this.lastDataReceivedTimestamp||this.responseReceivedTimestamp||this.lastRedirectReceivedTimestamp||this.requestSentTimestamp;} get latency() {return this.timingData.responseStart-this.timingData.requestStart;} get receiveDuration() {return this.timingData.responseEnd-this.timingData.responseStart;} get totalDuration() {return this.timingData.responseEnd-this.timingData.startTime;} get size() {if(!isNaN(this._cachedResponseBodySize)) return this._cachedResponseBodySize;if(!isNaN(this._responseBodySize)&&this._responseBodySize!==0) return this._responseBodySize;return this._estimatedSize;} get networkEncodedSize() {return this._responseBodyTransferSize;} get networkDecodedSize() {return this._responseBodySize;} get networkTotalTransferSize() {return this._responseHeadersTransferSize+this._responseBodyTransferSize;} get estimatedNetworkEncodedSize() {let exact=this.networkEncodedSize;if(!isNaN(exact)) return exact;if(this._cached) return 0; if(WI.Platform.name==="mac"){let contentLength=Number(this._responseHeaders.valueForCaseInsensitiveKey("Content-Length"));if(!isNaN(contentLength)) return contentLength;} if(!isNaN(this._estimatedTransferSize)) return this._estimatedTransferSize; return Number(this._responseHeaders.valueForCaseInsensitiveKey("Content-Length")||this._estimatedSize);} get estimatedTotalTransferSize() {let exact=this.networkTotalTransferSize;if(!isNaN(exact)) return exact;if(this.statusCode===304) return this._estimatedResponseHeadersSize;if(this._cached) return 0;return this._estimatedResponseHeadersSize+this.estimatedNetworkEncodedSize;} get compressed() {let contentEncoding=this._responseHeaders.valueForCaseInsensitiveKey("Content-Encoding");return!!(contentEncoding&&/\b(?:gzip|deflate|br)\b/.test(contentEncoding));} get requestedByteRange() {let range=this._requestHeaders.valueForCaseInsensitiveKey("Range");if(!range) return null;let rangeValues=range.match(/bytes=(\d+)-(\d+)/);if(!rangeValues) return null;let start=parseInt(rangeValues[1]);if(isNaN(start)) return null;let end=parseInt(rangeValues[2]);if(isNaN(end)) return null;return{start,end};} get scripts() {return this._scripts||[];} get serverTiming() {if(!this._serverTimingEntries) this._serverTimingEntries=WI.ServerTimingEntry.parseHeaders(this._responseHeaders.valueForCaseInsensitiveKey("Server-Timing"));return this._serverTimingEntries;} scriptForLocation(sourceCodeLocation) {if(sourceCodeLocation.sourceCode!==this) return null;var lineNumber=sourceCodeLocation.lineNumber;var columnNumber=sourceCodeLocation.columnNumber;for(var i=0;i=lineNumber){if(script.range.startLine===lineNumber&&columnNumberscript.range.endColumn) continue;return script;}} return null;} updateForRedirectResponse(request,response,elapsedTime,walltime) {let oldURL=this._url;let oldHeaders=this._requestHeaders;let oldMethod=this._requestMethod;if(request.url) this._url=request.url;this._requestHeaders=request.headers||{};this._requestCookies=null;this._requestMethod=request.method||null;this._redirects.push(new WI.Redirect(oldURL,oldMethod,oldHeaders,response.status,response.statusText,response.headers,elapsedTime));this._referrerPolicy=request.referrerPolicy??null;this._integrity=request.integrity??null;if(oldURL!==request.url){this._urlComponents=null;this.dispatchEventToListeners(WI.Resource.Event.URLDidChange,{oldURL});} this.dispatchEventToListeners(WI.Resource.Event.RequestHeadersDidChange);this.dispatchEventToListeners(WI.Resource.Event.TimestampsDidChange);} hasResponse() {return!isNaN(this._statusCode)||this._finished||this._failed;} hasRequestFormParameters() {let requestDataContentType=this.requestDataContentType;return requestDataContentType&&requestDataContentType.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i);} updateForResponse(url,mimeType,type,responseHeaders,statusCode,statusText,elapsedTime,timingData,source,security) {let oldURL=this._url;let oldMIMEType=this._mimeType;let oldType=this._type;if(type in WI.Resource.Type) type=WI.Resource.Type[type];else if(type==="Stylesheet"){type=WI.Resource.Type.StyleSheet;} if(url) this._url=url;this._mimeType=mimeType;this._type=Resource.resolvedType(type,mimeType);this._statusCode=statusCode;this._statusText=statusText;this._responseHeaders=responseHeaders||{};this._responseCookies=null;this._serverTimingEntries=null;this._responseReceivedTimestamp=elapsedTime||NaN;this._timingData=WI.ResourceTimingData.fromPayload(timingData,this);if(source) this._responseSource=WI.Resource.responseSourceFromPayload(source);this._security=security||{};const headerBaseSize=12;const headerPad=4;this._estimatedResponseHeadersSize=String(this._statusCode).length+this._statusText.length+headerBaseSize;for(let name in this._responseHeaders) this._estimatedResponseHeadersSize+=name.length+this._responseHeaders[name].length+headerPad;if(!this._cached){if(statusCode===304||(this._responseSource===WI.Resource.ResponseSource.MemoryCache||this._responseSource===WI.Resource.ResponseSource.DiskCache)) this.markAsCached();} if(oldURL!==url){this._urlComponents=null;this.dispatchEventToListeners(WI.Resource.Event.URLDidChange,{oldURL});} if(oldMIMEType!==mimeType){this._mimeTypeComponents=null;this.dispatchEventToListeners(WI.Resource.Event.MIMETypeDidChange,{oldMIMEType});} if(oldType!==type) this.dispatchEventToListeners(WI.Resource.Event.TypeDidChange,{oldType}); if(statusCode===304||this._responseHeaders.valueForCaseInsensitiveKey("Content-Length")) this.dispatchEventToListeners(WI.Resource.Event.TransferSizeDidChange);this.dispatchEventToListeners(WI.Resource.Event.ResponseReceived);this.dispatchEventToListeners(WI.Resource.Event.TimestampsDidChange);} updateWithMetrics(metrics) {this._receivedNetworkLoadMetrics=true;if(metrics.protocol) this._protocol=metrics.protocol;if(metrics.priority) this._priority=WI.Resource.networkPriorityFromPayload(metrics.priority);if(metrics.remoteAddress) this._remoteAddress=metrics.remoteAddress;if(metrics.connectionIdentifier) this._connectionIdentifier=WI.Resource.connectionIdentifierFromPayload(metrics.connectionIdentifier);if(metrics.requestHeaders){this._requestHeaders=metrics.requestHeaders;this._requestCookies=null;this.dispatchEventToListeners(WI.Resource.Event.RequestHeadersDidChange);} if("requestHeaderBytesSent"in metrics){this._requestHeadersTransferSize=metrics.requestHeaderBytesSent;this._requestBodyTransferSize=metrics.requestBodyBytesSent;this._responseHeadersTransferSize=metrics.responseHeaderBytesReceived;this._responseBodyTransferSize=metrics.responseBodyBytesReceived;this._responseBodySize=metrics.responseBodyDecodedSize;if(isNaN(this._estimatedSize)) this._estimatedSize=0;this.dispatchEventToListeners(WI.Resource.Event.SizeDidChange,{previousSize:this._estimatedSize});this.dispatchEventToListeners(WI.Resource.Event.TransferSizeDidChange);} if(metrics.securityConnection){if(!this._security) this._security={};this._security.connection=metrics.securityConnection;} this._isProxyConnection=!!metrics.isProxyConnection;this.dispatchEventToListeners(WI.Resource.Event.MetricsDidChange);} setCachedResponseBodySize(size) {this._cachedResponseBodySize=size;} requestContentFromBackend() {let specialContentPromise=WI.SourceCode.generateSpecialContentForURL(this._url);if(specialContentPromise) return specialContentPromise;if(this._target.type===WI.TargetType.Worker){let scriptForTarget=this.scripts.find((script)=>script.target===this._target);if(scriptForTarget) return scriptForTarget.requestContentFromBackend();}else{if(this._requestIdentifier) return this._target.NetworkAgent.getResponseBody(this._requestIdentifier);if(this._parentFrame) return this._target.PageAgent.getResourceContent(this._parentFrame.id,this._url);} return Promise.reject(new Error("Content request failed."));} increaseSize(dataLength,elapsedTime) {if(isNaN(this._estimatedSize)) this._estimatedSize=0;let previousSize=this._estimatedSize;this._estimatedSize+=dataLength;this._lastDataReceivedTimestamp=elapsedTime||NaN;this.dispatchEventToListeners(WI.Resource.Event.SizeDidChange,{previousSize});if(isNaN(this._estimatedTransferSize)&&this._statusCode!==304&&!this._responseHeaders.valueForCaseInsensitiveKey("Content-Length")) this.dispatchEventToListeners(WI.Resource.Event.TransferSizeDidChange);} increaseTransferSize(encodedDataLength) {if(isNaN(this._estimatedTransferSize)) this._estimatedTransferSize=0;this._estimatedTransferSize+=encodedDataLength;this.dispatchEventToListeners(WI.Resource.Event.TransferSizeDidChange);} markAsCached() {this._cached=true;this.dispatchEventToListeners(WI.Resource.Event.CacheStatusDidChange);if(this._statusCode!==304) this.dispatchEventToListeners(WI.Resource.Event.TransferSizeDidChange);} markAsFinished(elapsedTime) {this._finished=true;this._finishedOrFailedTimestamp=elapsedTime||NaN;this._timingData.markResponseEndTime(elapsedTime||NaN);if(this._finishThenRequestContentPromise) this._finishThenRequestContentPromise=null;this.dispatchEventToListeners(WI.Resource.Event.LoadingDidFinish);this.dispatchEventToListeners(WI.Resource.Event.TimestampsDidChange);} markAsFailed(canceled,elapsedTime,errorText) {this._failed=true;this._canceled=canceled;this._finishedOrFailedTimestamp=elapsedTime||NaN;if(!this._failureReasonText) this._failureReasonText=errorText||null;this.dispatchEventToListeners(WI.Resource.Event.LoadingDidFail);this.dispatchEventToListeners(WI.Resource.Event.TimestampsDidChange);} revertMarkAsFinished() {this._finished=false;this._finishedOrFailedTimestamp=NaN;} isLoading() {return!this._finished&&!this._failed;} hadLoadingError() {return this._failed||this._canceled||this._statusCode>=400;} getImageSize(callback) {if(this.type!==WI.Resource.Type.Image) throw"Resource is not an image.";if(this._imageSize!==undefined){callback(this._imageSize);return;} var objectURL=null;function imageDidLoad(){URL.revokeObjectURL(objectURL);this._imageSize={width:image.width,height:image.height};callback(this._imageSize);} function requestContentFailure(){this._imageSize=null;callback(this._imageSize);} var image=new Image;image.addEventListener("load",imageDidLoad.bind(this),false);this.requestContent().then((content)=>{objectURL=image.src=content.sourceCode.createObjectURL();if(!objectURL) requestContentFailure.call(this);},requestContentFailure.bind(this));} requestContent() {if(this._finished) return super.requestContent().catch(this._requestContentFailure.bind(this));if(this._failed) return this._requestContentFailure();if(!this._finishThenRequestContentPromise){this._finishThenRequestContentPromise=new Promise((resolve,reject)=>{this.singleFireEventListener(WI.Resource.Event.LoadingDidFinish,resolve,this);this.singleFireEventListener(WI.Resource.Event.LoadingDidFail,reject,this);}).then(this.requestContent.bind(this));} return this._finishThenRequestContentPromise;} associateWithScript(script) {if(!this._scripts) this._scripts=[];this._scripts.push(script);if(this._type===WI.Resource.Type.Other||this._type===WI.Resource.Type.XHR){let oldType=this._type;this._type=WI.Resource.Type.Script;this.dispatchEventToListeners(WI.Resource.Event.TypeDidChange,{oldType});}} saveIdentityToCookie(cookie) {cookie[WI.Resource.URLCookieKey]=this.url.hash;cookie[WI.Resource.MainResourceCookieKey]=this.isMainResource();} async createLocalResourceOverride(type,{mimeType,base64Encoded,content}={}) {let resourceData={requestURL:this.url,};switch(type){case WI.LocalResourceOverride.InterceptType.Request:resourceData.requestMethod=this.requestMethod??WI.HTTPUtilities.RequestMethod.GET;resourceData.requestHeaders=Object.shallowCopy(this.requestHeaders);resourceData.requestData=this.requestData??"";break;case WI.LocalResourceOverride.InterceptType.Response:case WI.LocalResourceOverride.InterceptType.ResponseSkippingNetwork:resourceData.responseMIMEType=this.mimeType??WI.mimeTypeForFileExtension(WI.fileExtensionForFilename(this.urlComponents.lastPathComponent));resourceData.responseStatusCode=this.statusCode;resourceData.responseStatusText=this.statusText;if(!resourceData.responseStatusCode){resourceData.responseStatusCode=200;resourceData.responseStatusText=null;} resourceData.responseStatusText||=WI.HTTPUtilities.statusTextForStatusCode(resourceData.responseStatusCode);if(base64Encoded===undefined||content===undefined){try{let{rawContent,rawBase64Encoded}=await this.requestContent();content??=rawContent;base64Encoded??=rawBase64Encoded;}catch{content??="";base64Encoded??=!WI.shouldTreatMIMETypeAsText(resourceData.mimeType);}} resourceData.responseContent=content;resourceData.responseBase64Encoded=base64Encoded;resourceData.responseHeaders=Object.shallowCopy(this.responseHeaders);break;} return WI.LocalResourceOverride.create(this.url,type,resourceData);} updateLocalResourceOverrideRequestData(data) {if(data===this._requestData) return;this._requestData=data;this.dispatchEventToListeners(WI.Resource.Event.RequestDataDidChange);} generateFetchCode() {let options={};if(this.requestData) options.body=this.requestData;options.cache="default";options.credentials=(this.requestCookies.length||this._requestHeaders.valueForCaseInsensitiveKey("Authorization"))?"include":"omit"; const forbiddenHeaders=new Set(["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via",]);let headers=Object.entries(this.requestHeaders).filter((header)=>{let key=header[0].toLowerCase();if(forbiddenHeaders.has(key)) return false;if(key.startsWith("proxy-")||key.startsWith("sec-")) return false;return true;}).sort((a,b)=>a[0].extendedLocaleCompare(b[0])).reduce((accumulator,current)=>{accumulator[current[0]]=current[1];return accumulator;},{});if(!isEmptyObject(headers)) options.headers=headers;if(this._integrity) options.integrity=this._integrity;if(this.requestMethod) options.method=this.requestMethod;options.mode="cors";options.redirect="follow";let referrer=this.requestHeaders.valueForCaseInsensitiveKey("Referer");if(referrer) options.referrer=referrer;if(this._referrerPolicy) options.referrerPolicy=this._referrerPolicy;return`fetch(${JSON.stringify(this.url)}, ${JSON.stringify(options, null, WI.indentString())})`;} generateCURLCommand() {function escapeStringPosix(str){function escapeCharacter(x){let code=x.charCodeAt(0);let hex=code.toString(16);if(code<256) return"\\x"+hex.padStart(2,"0");return"\\u"+hex.padStart(4,"0");} if(/[^\x20-\x7E]|'/.test(str)){return"$'"+str.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/!/g,"\\041").replace(/[^\x20-\x7E]/g,escapeCharacter)+"'";} return`'${str}'`;} let command=["curl "+escapeStringPosix(this.url).replace(/[[{}\]]/g,"\\$&")];command.push("-X "+escapeStringPosix(this.requestMethod));for(let key in this.requestHeaders) command.push("-H "+escapeStringPosix(`${key}: ${this.requestHeaders[key]}`));if(this.requestDataContentType&&this.requestMethod!=="GET"&&this.requestData){if(this.requestDataContentType.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i)) command.push("--data "+escapeStringPosix(this.requestData));else command.push("--data-binary "+escapeStringPosix(this.requestData));} return command.join(" \\\n");} stringifyHTTPRequest() {let lines=[];let protocol=this.protocol||"";if(protocol==="h2"){ lines.push(`:method: ${this.requestMethod}`);lines.push(`:scheme: ${this.urlComponents.scheme}`);lines.push(`:authority: ${WI.h2Authority(this.urlComponents)}`);lines.push(`:path: ${WI.h2Path(this.urlComponents)}`);}else{ lines.push(`${this.requestMethod} ${this.urlComponents.path}${protocol ? " " + protocol.toUpperCase() : ""}`);} for(let key in this.requestHeaders) lines.push(`${key}: ${this.requestHeaders[key]}`);return lines.join("\n")+"\n";} stringifyHTTPResponse() {let lines=[];let protocol=this.protocol||"";if(protocol==="h2"){ lines.push(`:status: ${this.statusCode}`);}else{ lines.push(`${protocol ? protocol.toUpperCase() + " " : ""}${this.statusCode} ${this.statusText}`);} for(let key in this.responseHeaders) lines.push(`${key}: ${this.responseHeaders[key]}`);return lines.join("\n")+"\n";} async showCertificate() {let errorString=WI.UIString("Unable to show certificate for \u201C%s\u201D").format(this.url);try{let{serializedCertificate}=await this._target.NetworkAgent.getSerializedCertificate(this._requestIdentifier);if(InspectorFrontendHost.showCertificate(serializedCertificate)) return;}catch(e){console.error(e);throw errorString;} let consoleMessage=new WI.ConsoleMessage(this._target,WI.ConsoleMessage.MessageSource.Other,WI.ConsoleMessage.MessageLevel.Error,errorString);consoleMessage.shouldRevealConsole=true;WI.consoleLogViewController.appendConsoleMessage(consoleMessage);throw errorString;} _requestContentFailure(error) {return Promise.resolve({error:WI.UIString("An error occurred trying to load the resource."),reason:error?.message||this._failureReasonText,sourceCode:this,});}};WI.Resource.TypeIdentifier="resource";WI.Resource.URLCookieKey="resource-url";WI.Resource.MainResourceCookieKey="resource-is-main-resource";WI.Resource.Event={URLDidChange:"resource-url-did-change",MIMETypeDidChange:"resource-mime-type-did-change",TypeDidChange:"resource-type-did-change",RequestHeadersDidChange:"resource-request-headers-did-change",RequestDataDidChange:"resource-request-data-did-change",ResponseReceived:"resource-response-received",LoadingDidFinish:"resource-loading-did-finish",LoadingDidFail:"resource-loading-did-fail",TimestampsDidChange:"resource-timestamps-did-change",SizeDidChange:"resource-size-did-change",TransferSizeDidChange:"resource-transfer-size-did-change",CacheStatusDidChange:"resource-cached-did-change",MetricsDidChange:"resource-metrics-did-change",InitiatedResourcesDidChange:"resource-initiated-resources-did-change",};WI.Resource.Type={Document:"resource-type-document",StyleSheet:"resource-type-style-sheet",Image:"resource-type-image",Font:"resource-type-font",Script:"resource-type-script",XHR:"resource-type-xhr",Fetch:"resource-type-fetch",Ping:"resource-type-ping",Beacon:"resource-type-beacon",WebSocket:"resource-type-websocket",EventSource:"resource-type-eventsource",Other:"resource-type-other",};WI.Resource.ResponseSource={Unknown:Symbol("unknown"),Network:Symbol("network"),MemoryCache:Symbol("memory-cache"),DiskCache:Symbol("disk-cache"),ServiceWorker:Symbol("service-worker"),InspectorOverride:Symbol("inspector-override"),};WI.Resource.NetworkPriority={Unknown:Symbol("unknown"),Low:Symbol("low"),Medium:Symbol("medium"),High:Symbol("high"),};WI.Resource.GroupingMode={Path:"group-resource-by-path",Type:"group-resource-by-type",};WI.settings.resourceGroupingMode=new WI.Setting("resource-grouping-mode",WI.Resource.GroupingMode.Type);WI.Resource._mimeTypeMap={"text/html":WI.Resource.Type.Document,"text/xml":WI.Resource.Type.Document,"application/xhtml+xml":WI.Resource.Type.Document,"text/plain":WI.Resource.Type.Other,"text/css":WI.Resource.Type.StyleSheet,"text/xsl":WI.Resource.Type.StyleSheet,"text/x-less":WI.Resource.Type.StyleSheet,"text/x-sass":WI.Resource.Type.StyleSheet,"text/x-scss":WI.Resource.Type.StyleSheet,"application/pdf":WI.Resource.Type.Image,"image/svg+xml":WI.Resource.Type.Image,"application/x-font-type1":WI.Resource.Type.Font,"application/x-font-ttf":WI.Resource.Type.Font,"application/x-font-woff":WI.Resource.Type.Font,"application/x-truetype-font":WI.Resource.Type.Font,"text/javascript":WI.Resource.Type.Script,"text/ecmascript":WI.Resource.Type.Script,"application/javascript":WI.Resource.Type.Script,"application/ecmascript":WI.Resource.Type.Script,"application/x-javascript":WI.Resource.Type.Script,"application/json":WI.Resource.Type.Script,"application/x-json":WI.Resource.Type.Script,"text/x-javascript":WI.Resource.Type.Script,"text/x-json":WI.Resource.Type.Script,"text/javascript1.1":WI.Resource.Type.Script,"text/javascript1.2":WI.Resource.Type.Script,"text/javascript1.3":WI.Resource.Type.Script,"text/jscript":WI.Resource.Type.Script,"text/livescript":WI.Resource.Type.Script,"text/x-livescript":WI.Resource.Type.Script,"text/typescript":WI.Resource.Type.Script,"text/typescript-jsx":WI.Resource.Type.Script,"text/jsx":WI.Resource.Type.Script,"text/x-clojure":WI.Resource.Type.Script,"text/x-coffeescript":WI.Resource.Type.Script,};WI.Script=class Script extends WI.SourceCode {constructor(target,id,range,url,sourceType,injected,sourceURL,sourceMapURL) {super(url);this._target=target;this._id=id||null;this._range=range||null;this._sourceType=sourceType||WI.Script.SourceType.Program;this._sourceURL=sourceURL||null;this._sourceMappingURL=sourceMapURL||null;this._injected=injected||false;this._dynamicallyAddedScriptElement=false;this._scriptSyntaxTree=null;this._resource=this._resolveResource(); if(this._resource&&this._resource.type===WI.Resource.Type.Document&&!this._range.startLine&&!this._range.startColumn){let documentResource=this._resource;this._resource=null;this._dynamicallyAddedScriptElement=true;documentResource.parentFrame.addExtraScript(this);this._dynamicallyAddedScriptElementNumber=documentResource.parentFrame.extraScriptCollection.size;}else if(this._resource) this._resource.associateWithScript(this);if(isWebInspectorConsoleEvaluationScript(this._sourceURL)){this._uniqueDisplayNameNumber=this._nextUniqueConsoleDisplayNameNumber();} if(this._sourceMappingURL) WI.networkManager.downloadSourceMap(this._sourceMappingURL,this._url,this);} static resetUniqueDisplayNameNumbers(target) {if(WI.Script._uniqueDisplayNameNumbersForRootTargetMap) WI.Script._uniqueDisplayNameNumbersForRootTargetMap.delete(target);} get target(){return this._target;} get id(){return this._id;} get range(){return this._range;} get sourceType(){return this._sourceType;} get sourceURL(){return this._sourceURL;} get sourceMappingURL(){return this._sourceMappingURL;} get injected(){return this._injected;} get contentIdentifier() {if(this._url) return this._url;if(!this._sourceURL) return null; if(isWebInspectorConsoleEvaluationScript(this._sourceURL)) return null;if(isWebInspectorInternalScript(this._sourceURL)) return null;return this._sourceURL;} get mimeType() {return this._resource?this._resource.mimeType:"text/javascript";} get isScript() {return true;} get displayName() {if(isWebInspectorBootstrapScript(this._sourceURL||this._url)){return WI.UIString("Inspector Bootstrap Script");} if(this._url&&!this._dynamicallyAddedScriptElement) return WI.displayNameForURL(this._url,this.urlComponents);if(isWebInspectorConsoleEvaluationScript(this._sourceURL)){return WI.UIString("Console Evaluation %d").format(this._uniqueDisplayNameNumber);} if(this._sourceURL){if(!this._sourceURLComponents) this._sourceURLComponents=parseURL(this._sourceURL);return WI.displayNameForURL(this._sourceURL,this._sourceURLComponents);} if(this._dynamicallyAddedScriptElement) return WI.UIString("Script Element %d").format(this._dynamicallyAddedScriptElementNumber);if(!this._uniqueDisplayNameNumber) this._uniqueDisplayNameNumber=this._nextUniqueDisplayNameNumber();return WI.UIString("Anonymous Script %d").format(this._uniqueDisplayNameNumber);} get displayURL() {if(isWebInspectorBootstrapScript(this._sourceURL||this._url)){return WI.UIString("Inspector Bootstrap Script");} const isMultiLine=true;const dataURIMaxSize=64;if(this._url) return WI.truncateURL(this._url,isMultiLine,dataURIMaxSize);if(this._sourceURL) return WI.truncateURL(this._sourceURL,isMultiLine,dataURIMaxSize);return null;} get dynamicallyAddedScriptElement() {return this._dynamicallyAddedScriptElement;} get anonymous() {return!this._resource&&!this._url&&!this._sourceURL;} get resource() {return this._resource;} get scriptSyntaxTree() {return this._scriptSyntaxTree;} isMainResource() {return this._target&&this._target.mainResource===this;} requestContentFromBackend() {let specialContentPromise=WI.SourceCode.generateSpecialContentForURL(this._url);if(specialContentPromise) return specialContentPromise;if(!this._id){ return Promise.reject(new Error("There is no identifier to request content with."));} return this._target.DebuggerAgent.getScriptSource(this._id);} saveIdentityToCookie(cookie) {cookie[WI.Script.URLCookieKey]=this.url;cookie[WI.Script.DisplayNameCookieKey]=this.displayName;} requestScriptSyntaxTree(callback) {if(this._scriptSyntaxTree){setTimeout(()=>{callback(this._scriptSyntaxTree);},0);return;} var makeSyntaxTreeAndCallCallback=(content)=>{this._makeSyntaxTree(content);callback(this._scriptSyntaxTree);};var content=this.content;if(!content&&this._resource&&this._resource.type===WI.Resource.Type.Script&&this._resource.finished) content=this._resource.content;if(content){setTimeout(makeSyntaxTreeAndCallCallback,0,content);return;} this.requestContent().then(function(parameters){makeSyntaxTreeAndCallCallback(parameters.sourceCode.content);}).catch(function(error){makeSyntaxTreeAndCallCallback(null);});} async breakpointLocations(startPosition,endPosition) {if(!this._target.hasCommand("Debugger.getBreakpointLocations")) return[];let{locations}=await this._target.DebuggerAgent.getBreakpointLocations.invoke({start:{scriptId:this._id,lineNumber:startPosition.lineNumber,columnNumber:startPosition.columnNumber,},end:{scriptId:this._id,lineNumber:endPosition.lineNumber,columnNumber:endPosition.columnNumber,},});return locations.map((location)=>{let sourceCode=this._resource||this;return sourceCode.createLazySourceCodeLocation(location.lineNumber,location.columnNumber);});} _nextUniqueDisplayNameNumber() {let numbers=this._uniqueDisplayNameNumbersForRootTarget();return++numbers.lastUniqueDisplayNameNumber;} _nextUniqueConsoleDisplayNameNumber() {let numbers=this._uniqueDisplayNameNumbersForRootTarget();return++numbers.lastUniqueConsoleDisplayNameNumber;} _uniqueDisplayNameNumbersForRootTarget() {if(!WI.Script._uniqueDisplayNameNumbersForRootTargetMap) WI.Script._uniqueDisplayNameNumbersForRootTargetMap=new WeakMap();let key=this._target.rootTarget;let numbers=WI.Script._uniqueDisplayNameNumbersForRootTargetMap.get(key);if(!numbers){numbers={lastUniqueDisplayNameNumber:0,lastUniqueConsoleDisplayNameNumber:0};WI.Script._uniqueDisplayNameNumbersForRootTargetMap.set(key,numbers);} return numbers;} _resolveResource() { if(!this._url) return null;let resolver=WI.networkManager;if(this._target&&this._target!==WI.mainTarget) resolver=this._target.resourceCollection;function isScriptResource(item){return item.type===WI.Resource.Type.Document||item.type===WI.Resource.Type.Script;} try{let resource=resolver.resourcesForURL(this._url).find(isScriptResource);if(resource) return resource;let decodedURL=decodeURI(this._url);if(decodedURL!==this._url){resource=resolver.resourcesForURL(decodedURL).find(isScriptResource);if(resource) return resource;} let urlWithoutFragment=removeURLFragment(this._url);if(urlWithoutFragment!==this._url){resource=resolver.resourcesForURL(urlWithoutFragment).find(isScriptResource);if(resource) return resource;} let decodedURLWithoutFragment=removeURLFragment(decodedURL);if(decodedURLWithoutFragment!==decodedURL){resource=resolver.resourcesForURL(decodedURLWithoutFragment).find(isScriptResource);if(resource) return resource;}}catch{} if(!this.isMainResource()){for(let frame of WI.networkManager.frames){if(frame.mainResource.type===WI.Resource.Type.Document&&frame.mainResource.url.startsWith(this._url)) return frame.mainResource;}} return null;} _makeSyntaxTree(sourceText) {if(this._scriptSyntaxTree||!sourceText) return;this._scriptSyntaxTree=new WI.ScriptSyntaxTree(sourceText,this);}};WI.Script.SourceType={Program:"script-source-type-program",Module:"script-source-type-module",};WI.Script.TypeIdentifier="script";WI.Script.URLCookieKey="script-url";WI.Script.DisplayNameCookieKey="script-display-name";WI.LocalScript=class LocalScript extends WI.Script {constructor(target,url,sourceURL,sourceType,source,{injected,editable}={}) {const id=null;super(target,id,WI.TextRange.fromText(source),url,sourceType,injected,sourceURL);this._editable=!!editable;const base64Encoded=false;const mimeType="text/javascript";this._originalRevision=new WI.SourceCodeRevision(this,source,base64Encoded,mimeType);this._currentRevision=this._originalRevision;} get editable(){return this._editable;} get supportsScriptBlackboxing() {return false;} requestContentFromBackend() {return Promise.resolve({scriptSource:this._originalRevision.content,});} handleCurrentRevisionContentChange() {super.handleCurrentRevisionContentChange();this._range=WI.TextRange.fromText(this._currentRevision.content);}};WI.AlignmentData=class AlignmentData {constructor(propertyName,text) {this._type=WI.AlignmentData._propertyNameToType(propertyName);this._propertyName=propertyName;this._text=text;} static isAlignmentAwarePropertyName(propertyName) {return!!WI.AlignmentData._propertyNameToType(propertyName);} static _propertyNameToType(propertyName) {switch(propertyName){case"align-content":return WI.AlignmentData.Type.AlignContent;case"align-items":return WI.AlignmentData.Type.AlignItems;case"align-self":return WI.AlignmentData.Type.AlignSelf;case"justify-content":return WI.AlignmentData.Type.JustifyContent;case"justify-items":return WI.AlignmentData.Type.JustifyItems;case"justify-self":return WI.AlignmentData.Type.JustifySelf;} return null;} get type(){return this._type;} get text(){return this._text;} set text(text){this._text=text;} toString() {return this._text;}};WI.AlignmentData.Type={AlignContent:"align-content",AlignItems:"align-items",AlignSelf:"align-self",JustifyContent:"justify-content",JustifyItems:"justify-items",JustifySelf:"justify-self",};WI.Animation=class Animation extends WI.Object {constructor(animationId,{name,cssAnimationName,cssTransitionProperty,effect,stackTrace}={}) {super();this._animationId=animationId;this._name=name||null;this._cssAnimationName=cssAnimationName||null;this._cssTransitionProperty=cssTransitionProperty||null;this._updateEffect(effect);this._stackTrace=stackTrace||null;this._effectTarget=undefined;this._requestEffectTargetCallbacks=null;} static fromPayload(payload) {if(payload.backtrace) payload.stackTrace={callFrames:payload.backtrace};return new WI.Animation(payload.animationId,{name:payload.name,cssAnimationName:payload.cssAnimationName,cssTransitionProperty:payload.cssTransitionProperty,effect:payload.effect,stackTrace:WI.StackTrace.fromPayload(WI.assumingMainTarget(),payload.stackTrace),});} static displayNameForAnimationType(animationType,plural) {switch(animationType){case WI.Animation.Type.WebAnimation:return plural?WI.UIString("Web Animations"):WI.UIString("Web Animation");case WI.Animation.Type.CSSAnimation:return plural?WI.UIString("CSS Animations"):WI.UIString("CSS Animation");case WI.Animation.Type.CSSTransition:return plural?WI.UIString("CSS Transitions"):WI.UIString("CSS Transition");} return null;} static displayNameForPlaybackDirection(playbackDirection) {switch(playbackDirection){case WI.Animation.PlaybackDirection.Normal:return WI.UIString("Normal","Web Animation Playback Direction Normal","Indicates that the playback direction of this web animation is normal (e.g. forwards)");case WI.Animation.PlaybackDirection.Reverse:return WI.UIString("Reverse","Web Animation Playback Direction Reverse","Indicates that the playback direction of this web animation is reversed (e.g. backwards)");case WI.Animation.PlaybackDirection.Alternate:return WI.UIString("Alternate","Web Animation Playback Direction Alternate","Indicates that the playback direction of this web animation alternates between normal and reversed on each iteration");case WI.Animation.PlaybackDirection.AlternateReverse:return WI.UIString("Alternate Reverse","Web Animation Playback Direction Alternate Reverse","Indicates that the playback direction of this web animation alternates between reversed and normal on each iteration");} return null;} static displayNameForFillMode(fillMode) {switch(fillMode){case WI.Animation.FillMode.None:return WI.UIString("None","Web Animation Fill Mode None","Indicates that this web animation does not apply any styles before it begins and after it ends");case WI.Animation.FillMode.Forwards:return WI.UIString("Forwards","Web Animation Fill Mode Forwards","Indicates that this web animation also applies styles after it ends");case WI.Animation.FillMode.Backwards:return WI.UIString("Backwards","Web Animation Fill Mode Backwards","Indicates that this web animation also applies styles before it begins");case WI.Animation.FillMode.Both:return WI.UIString("Both","Web Animation Fill Mode Both","Indicates that this web animation also applies styles before it begins and after it ends");case WI.Animation.FillMode.Auto:return WI.UIString("Auto","Web Animation Fill Mode Auto","Indicates that this web animation either does not apply any styles before it begins and after it ends or that it applies to both, depending on it's configuration");} return null;} static resetUniqueDisplayNameNumbers() {WI.Animation._nextUniqueDisplayNameNumber=1;} get animationId(){return this._animationId;} get name(){return this._name;} get cssAnimationName(){return this._cssAnimationName;} get cssTransitionProperty(){return this._cssTransitionProperty;} get stackTrace(){return this._stackTrace;} get animationType() {if(this._cssAnimationName) return WI.Animation.Type.CSSAnimation;if(this._cssTransitionProperty) return WI.Animation.Type.CSSTransition;return WI.Animation.Type.WebAnimation;} get startDelay() {return"startDelay"in this._effect?this._effect.startDelay:NaN;} get endDelay() {return"endDelay"in this._effect?this._effect.endDelay:NaN;} get iterationCount() {return"iterationCount"in this._effect?this._effect.iterationCount:NaN;} get iterationStart() {return"iterationStart"in this._effect?this._effect.iterationStart:NaN;} get iterationDuration() {return"iterationDuration"in this._effect?this._effect.iterationDuration:NaN;} get timingFunction() {return"timingFunction"in this._effect?this._effect.timingFunction:null;} get playbackDirection() {return"playbackDirection"in this._effect?this._effect.playbackDirection:null;} get fillMode() {return"fillMode"in this._effect?this._effect.fillMode:null;} get keyframes() {return"keyframes"in this._effect?this._effect.keyframes:[];} get displayName() {if(this._name) return this._name;if(this._cssAnimationName) return this._cssAnimationName;if(this._cssTransitionProperty) return this._cssTransitionProperty;if(!this._uniqueDisplayNameNumber) this._uniqueDisplayNameNumber=WI.Animation._nextUniqueDisplayNameNumber++;return WI.UIString("Animation %d").format(this._uniqueDisplayNameNumber);} requestEffectTarget(callback) {if(this._effectTarget!==undefined){callback(this._effectTarget);return;} if(this._requestEffectTargetCallbacks){this._requestEffectTargetCallbacks.push(callback);return;} this._requestEffectTargetCallbacks=[callback];WI.domManager.ensureDocument();let target=WI.assumingMainTarget();target.AnimationAgent.requestEffectTarget(this._animationId,(error,effectTarget)=>{if(!isNaN(effectTarget)) effectTarget={nodeId:effectTarget};this._effectTarget=!error?WI.DOMStyleable.fromPayload(effectTarget):null;for(let requestEffectTargetCallback of this._requestEffectTargetCallbacks) requestEffectTargetCallback(this._effectTarget);this._requestEffectTargetCallbacks=null;});} nameChanged(name) {this._name=name||null;this.dispatchEventToListeners(WI.Animation.Event.NameChanged);} effectChanged(effect) {this._updateEffect(effect);} targetChanged() {this._effectTarget=undefined;this.dispatchEventToListeners(WI.Animation.Event.TargetChanged);} _updateEffect(effect) {this._effect=effect||{};if("iterationCount"in this._effect){if(this._effect.iterationCount===-1) this._effect.iterationCount=Infinity;else if(this._effect.iterationCount===null){this._effect.iterationCount=Infinity;}} if("timingFunction"in this._effect){let timingFunction=this._effect.timingFunction;this._effect.timingFunction=WI.CubicBezierTimingFunction.fromString(timingFunction)||WI.LinearTimingFunction.fromString(timingFunction)||WI.StepsTimingFunction.fromString(timingFunction)||WI.SpringTimingFunction.fromString(timingFunction);} if("keyframes"in this._effect){for(let keyframe of this._effect.keyframes){if(keyframe.easing){let easing=keyframe.easing;keyframe.easing=WI.CubicBezierTimingFunction.fromString(easing)||WI.LinearTimingFunction.fromString(easing)||WI.StepsTimingFunction.fromString(easing)||WI.SpringTimingFunction.fromString(easing);} if(keyframe.style) keyframe.style=keyframe.style.replaceAll(/;\s+/g,";\n");}} this.dispatchEventToListeners(WI.Animation.Event.EffectChanged);}};WI.Animation._nextUniqueDisplayNameNumber=1;WI.Animation.Type={WebAnimation:"web-animation",CSSAnimation:"css-animation",CSSTransition:"css-transition",};WI.Animation.PlaybackDirection={Normal:"normal",Reverse:"reverse",Alternate:"alternate",AlternateReverse:"alternate-reverse",};WI.Animation.FillMode={None:"none",Forwards:"forwards",Backwards:"backwards",Both:"both",Auto:"auto",};WI.Animation.Event={NameChanged:"animation-name-changed",EffectChanged:"animation-effect-changed",TargetChanged:"animation-target-changed",};WI.AnimationCollection=class AnimationCollection extends WI.Collection {constructor(animationType) {super();this._animationType=animationType||null;if(!this._animationType) this._animationCollectionForTypeMap=null;} get animationType(){return this._animationType;} get displayName() {if(this._animationType){const plural=true;return WI.Animation.displayNameForType(this._animationType,plural);} return WI.UIString("Web Animations");} objectIsRequiredType(object) {if(!(object instanceof WI.Animation)) return false;return!this._animationType||object.animationType===this._animationType;} animationCollectionForType(animationType) {if(this._animationType){return this;} if(!this._animationCollectionForTypeMap) this._animationCollectionForTypeMap=new Map;let animationCollectionForType=this._animationCollectionForTypeMap.get(animationType);if(!animationCollectionForType){animationCollectionForType=new WI.AnimationCollection(animationType);this._animationCollectionForTypeMap.set(animationType,animationCollectionForType);} return animationCollectionForType;} itemAdded(item) {super.itemAdded(item);if(!this._animationType){let animationCollectionForType=this.animationCollectionForType(item.animationType);animationCollectionForType.add(item);}} itemRemoved(item) {if(!this._animationType){let animationCollectionForType=this.animationCollectionForType(item.animationType);animationCollectionForType.remove(item);} super.itemRemoved(item);} itemsCleared(items) {if(this._animationCollectionForTypeMap){for(let animationCollectionForType of this._animationCollectionForTypeMap.values()) animationCollectionForType.clear();} super.itemsCleared(items);}};WI.ApplicationCacheFrame=class ApplicationCacheFrame {constructor(frame,manifest,status) {this._frame=frame;this._manifest=manifest;this._status=status;} get frame(){return this._frame;} get manifest(){return this._manifest;} get status(){return this._status;} set status(status){this._status=status;} saveIdentityToCookie(cookie) {cookie[WI.ApplicationCacheFrame.FrameURLCookieKey]=this.frame.url;cookie[WI.ApplicationCacheFrame.ManifestURLCookieKey]=this.manifest.manifestURL;}};WI.ApplicationCacheFrame.TypeIdentifier="application-cache-frame";WI.ApplicationCacheFrame.FrameURLCookieKey="application-cache-frame-url";WI.ApplicationCacheFrame.ManifestURLCookieKey="application-cache-frame-manifest-url";WI.ApplicationCacheManifest=class ApplicationCacheManifest {constructor(manifestURL) {this._manifestURL=manifestURL;} get manifestURL(){return this._manifestURL;}};WI.BackForwardEntry=class BackForwardEntry {constructor(contentView,cookie) {this._contentView=contentView; this._tombstone=false;this._cookie=cookie||{};this._scrollPositions=[];contentView.saveToCookie(this._cookie);} makeCopy(newCookie) {let copy=new WI.BackForwardEntry(this._contentView,newCookie||this.cookie);copy._tombstone=this._tombstone;copy._scrollPositions=this._scrollPositions.slice();return copy;} get contentView() {return this._contentView;} get cookie() {return Object.shallowCopy(this._cookie);} get tombstone() {return this._tombstone;} set tombstone(tombstone) {this._tombstone=tombstone;} prepareToShow() {this._restoreFromCookie();this.contentView.needsLayout();} prepareToHide() {this._saveScrollPositions();if(this._contentView.shouldSaveStateWhenHidden){this._cookie={};this._contentView.saveToCookie(this._cookie);}} isEqual(other) {if(!other) return false;return this._contentView===other._contentView&&Object.shallowEqual(this._cookie,other._cookie);} _restoreFromCookie() {this._restoreScrollPositions();this.contentView.restoreFromCookie(this.cookie);} _restoreScrollPositions() {if(!this._scrollPositions.length) return;var scrollableElements=this.contentView.scrollableElements||[];for(var i=0;i>1;if(this._values[middleIndex].startsWith(prefix)){foundIndex=middleIndex;break;} if(this._values[middleIndex]text.length) return{prefix:"",completions:[]};if(!text.length) return{prefix:"",completions:WI.CSSKeywordCompletions.forProperty(propertyName).values};let tokens=WI.tokenizeCSSValue(text);let indexOfTokenAtCaret=-1;let passedCharacters=0;for(let i=0;i=caretPosition){indexOfTokenAtCaret=i;break;}} let tokenAtCaret=tokens[indexOfTokenAtCaret];if(!tokenAtCaret) return{prefix:"",completions:[]};if(tokenAtCaret.type&&/\b(comment|string)\b/.test(tokenAtCaret.type)) return{prefix:"",completions:[]};let currentTokenValue=tokenAtCaret.value.trim();let caretIsInMiddleOfToken=caretPosition!==passedCharacters;let tokenAfterCaret=tokens[indexOfTokenAtCaret+1];if((caretIsInMiddleOfToken&¤tTokenValue.length)||(!caretIsInMiddleOfToken&&tokenAfterCaret&&/[a-zA-Z0-9-]/.test(tokenAfterCaret.value[0]))) return{prefix:"",completions:[]};if(currentTokenValue==="("||currentTokenValue===",") currentTokenValue="";let tokenBeforeCaret=tokens[indexOfTokenAtCaret-1];if(currentTokenValue===")"||tokenBeforeCaret?.value===")") return{prefix:"",completions:[]};if(currentTokenValue.length&&tokenBeforeCaret?.value==="-"){currentTokenValue=tokenBeforeCaret.value+currentTokenValue;} let functionName=null;let preceedingFunctionDepth=0;for(let i=indexOfTokenAtCaret;i>=0;--i){let value=tokens[i].value;if(value===")") ++preceedingFunctionDepth;else if(value==="("){if(preceedingFunctionDepth) --preceedingFunctionDepth;else{functionName=tokens[i-1]?.value;break;}}} let valueCompletions;if(functionName) valueCompletions=WI.CSSKeywordCompletions.forFunction(functionName,{additionalFunctionValueCompletionsProvider});else valueCompletions=WI.CSSKeywordCompletions.forProperty(propertyName);return{prefix:currentTokenValue,completions:valueCompletions.executeQuery(currentTokenValue)};};WI.CSSKeywordCompletions.forProperty=function(propertyName) {let acceptedKeywords=["initial","unset","revert","revert-layer","var()","env()"];function addKeywordsForName(name){let isNotPrefixed=name.charAt(0)!=="-";if(name in WI.CSSKeywordCompletions._propertyKeywordMap) acceptedKeywords.pushAll(WI.CSSKeywordCompletions._propertyKeywordMap[name]);else if(isNotPrefixed&&("-webkit-"+name)in WI.CSSKeywordCompletions._propertyKeywordMap) acceptedKeywords.pushAll(WI.CSSKeywordCompletions._propertyKeywordMap["-webkit-"+name]);if(WI.CSSKeywordCompletions.isColorAwareProperty(name)) acceptedKeywords.pushAll(WI.CSSKeywordCompletions._colors);if(WI.CSSKeywordCompletions.InheritedProperties.has(name)) acceptedKeywords.push("inherit");else if(isNotPrefixed&&WI.CSSKeywordCompletions.InheritedProperties.has("-webkit-"+name)) acceptedKeywords.push("inherit");} addKeywordsForName(propertyName);let unaliasedName=WI.CSSKeywordCompletions.PropertyNameForAlias.get(propertyName);if(unaliasedName) addKeywordsForName(unaliasedName);let longhandNames=WI.CSSKeywordCompletions.LonghandNamesForShorthandProperty.get(propertyName);if(longhandNames){for(let longhandName of longhandNames) addKeywordsForName(longhandName);} if(acceptedKeywords.includes(WI.CSSKeywordCompletions.AllPropertyNamesPlaceholder)&&WI.cssManager.propertyNameCompletions){acceptedKeywords.remove(WI.CSSKeywordCompletions.AllPropertyNamesPlaceholder);acceptedKeywords.pushAll(WI.cssManager.propertyNameCompletions.values);} return new WI.CSSCompletions(Array.from(new Set(acceptedKeywords)),{acceptEmptyPrefix:true});};WI.CSSKeywordCompletions.isColorAwareProperty=function(name) {if(WI.CSSKeywordCompletions._colorAwareProperties.has(name)) return true;let isNotPrefixed=name.charAt(0)!=="-";if(isNotPrefixed&&WI.CSSKeywordCompletions._colorAwareProperties.has("-webkit-"+name)) return true;if(name.endsWith("color")) return true;return false;};WI.CSSKeywordCompletions.isTimingFunctionAwareProperty=function(name) {if(WI.CSSKeywordCompletions._timingFunctionAwareProperties.has(name)) return true;let isNotPrefixed=name.charAt(0)!=="-";if(isNotPrefixed&&WI.CSSKeywordCompletions._timingFunctionAwareProperties.has("-webkit-"+name)) return true;return false;};WI.CSSKeywordCompletions.forFunction=function(functionName,{additionalFunctionValueCompletionsProvider}={}) {let suggestions=["var()"];if(functionName==="var") suggestions=[];else if(functionName==="calc"||functionName==="min"||functionName==="max") suggestions.push("calc()","min()","max()");else if(functionName==="env") suggestions.push("safe-area-inset-top","safe-area-inset-right","safe-area-inset-bottom","safe-area-inset-left");else if(functionName==="image-set") suggestions.push("url()");else if(functionName==="repeat") suggestions.push("auto","auto-fill","auto-fit","min-content","max-content");else if(functionName==="steps") suggestions.push("jump-none","jump-start","jump-end","jump-both","start","end");else if(functionName.endsWith("gradient")){suggestions.push("to","left","right","top","bottom");suggestions.pushAll(WI.CSSKeywordCompletions._colors);} if(additionalFunctionValueCompletionsProvider) suggestions.pushAll(additionalFunctionValueCompletionsProvider(functionName));return new WI.CSSCompletions(suggestions,{acceptEmptyPrefix:true});};WI.CSSKeywordCompletions.addCustomCompletions=function(properties) {for(var property of properties){if(property.aliases){for(let alias of property.aliases) WI.CSSKeywordCompletions.PropertyNameForAlias.set(alias,property.name);} if(property.values) WI.CSSKeywordCompletions.addPropertyCompletionValues(property.name,property.values);if(property.inherited) WI.CSSKeywordCompletions.InheritedProperties.add(property.name);if(property.longhands){WI.CSSKeywordCompletions.LonghandNamesForShorthandProperty.set(property.name,property.longhands);for(let longhand of property.longhands){let shorthands=WI.CSSKeywordCompletions.ShorthandNamesForLongHandProperty.getOrInitialize(longhand,[]);shorthands.push(property.name);}}}};WI.CSSKeywordCompletions.addPropertyCompletionValues=function(propertyName,newValues) {var existingValues=WI.CSSKeywordCompletions._propertyKeywordMap[propertyName];if(!existingValues){WI.CSSKeywordCompletions._propertyKeywordMap[propertyName]=newValues;return;} var union=new Set;for(var value of existingValues) union.add(value);for(var value of newValues) union.add(value);WI.CSSKeywordCompletions._propertyKeywordMap[propertyName]=[...union.values()];};WI.CSSKeywordCompletions.AllPropertyNamesPlaceholder="__all-properties__";WI.CSSKeywordCompletions.PropertyNameForAlias=new Map;WI.CSSKeywordCompletions.LonghandNamesForShorthandProperty=new Map;WI.CSSKeywordCompletions.ShorthandNamesForLongHandProperty=new Map;WI.CSSKeywordCompletions.InheritedProperties=new Set(["-apple-color-filter","-webkit-aspect-ratio","-webkit-border-horizontal-spacing","-webkit-border-vertical-spacing","-webkit-box-direction","-webkit-cursor-visibility","-webkit-font-kerning","-webkit-font-smoothing","-webkit-hyphenate-character","-webkit-hyphenate-limit-after","-webkit-hyphenate-limit-before","-webkit-hyphenate-limit-lines","-webkit-hyphens","-webkit-line-align","-webkit-line-break","-webkit-line-box-contain","-webkit-line-grid","-webkit-line-snap","-webkit-locale","-webkit-nbsp-mode","-webkit-overflow-scrolling","-webkit-rtl-ordering","-webkit-ruby-position","-webkit-text-combine","-webkit-text-decoration-skip","-webkit-text-decorations-in-effect","-webkit-text-emphasis","-webkit-text-emphasis-color","-webkit-text-emphasis-position","-webkit-text-emphasis-style","-webkit-text-fill-color","-webkit-text-orientation","-webkit-text-security","-webkit-text-size-adjust","-webkit-text-stroke","-webkit-text-stroke-color","-webkit-text-stroke-width","-webkit-text-underline-position","-webkit-text-zoom","-webkit-touch-callout","-webkit-user-modify","-webkit-user-select","border-collapse","border-spacing","caption-side","caret-color","clip-rule","color","color-interpolation","color-interpolation-filters","color-rendering","cursor","direction","empty-cells","fill","fill-opacity","fill-rule","font","font-family","font-feature-settings","font-optical-sizing","font-size","font-stretch","font-style","font-synthesis","font-synthesis-weight","font-synthesis-style","font-synthesis-small-caps","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","glyph-orientation-horizontal","glyph-orientation-vertical","hanging-punctuation","image-orientation","image-rendering","image-resolution","kerning","letter-spacing","line-break","line-height","list-style","list-style-image","list-style-position","list-style-type","marker","marker-end","marker-mid","marker-start","orphans","pointer-events","print-color-adjust","quotes","resize","shape-rendering","speak-as","stroke","stroke-color","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","text-align","text-align-last","text-anchor","text-indent","text-justify","text-rendering","text-shadow","text-transform","visibility","white-space","widows","word-break","word-spacing","word-wrap","writing-mode",]);WI.CSSKeywordCompletions._colors=["aqua","black","blue","fuchsia","gray","green","lime","maroon","navy","olive","orange","purple","red","silver","teal","white","yellow","transparent","currentcolor","grey","aliceblue","antiquewhite","aquamarine","azure","beige","bisque","blanchedalmond","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","gainsboro","ghostwhite","gold","goldenrod","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","limegreen","linen","magenta","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","oldlace","olivedrab","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","rebeccapurple","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","thistle","tomato","turquoise","violet","wheat","whitesmoke","yellowgreen","rgb()","rgba()","hsl()","hsla()","color()","hwb()","lch()","lab()","color-mix()","color-contrast()","light-dark()",];WI.CSSKeywordCompletions._colorAwareProperties=new Set(["background","background-color","background-image","border","border-color","border-bottom","border-bottom-color","border-left","border-left-color","border-right","border-right-color","border-top","border-top-color","box-shadow","-webkit-box-shadow","color","column-rule","-webkit-column-rule","column-rule-color","-webkit-column-rule-color","fill","outline","outline-color","stroke","text-decoration-color","-webkit-text-decoration-color","text-emphasis","-webkit-text-emphasis","text-emphasis-color","-webkit-text-emphasis-color","text-line-through","text-line-through-color","text-overline","text-overline-color","text-shadow","text-underline","text-underline-color","-webkit-text-fill-color","-webkit-text-stroke","-webkit-text-stroke-color","-webkit-tap-highlight-color",]);WI.CSSKeywordCompletions._timingFunctionAwareProperties=new Set(["animation","-webkit-animation","animation-timing-function","-webkit-animation-timing-function","transition","-webkit-transition","transition-timing-function","-webkit-transition-timing-function",]);WI.CSSKeywordCompletions._propertyKeywordMap={"content":["list-item","close-quote","no-close-quote","no-open-quote","open-quote","attr()","counter()","counters()","url()","linear-gradient()","radial-gradient()","repeating-linear-gradient()","repeating-radial-gradient()","-webkit-canvas()","cross-fade()","image-set()"],"list-style-image":["none","url()","linear-gradient()","radial-gradient()","repeating-linear-gradient()","repeating-radial-gradient()","-webkit-canvas()","cross-fade()","image-set()"],"baseline-shift":["baseline","sub","super"],"block-size":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()",],"border-block-end-width":["medium","thick","thin","calc()",],"border-block-start-width":["medium","thick","thin","calc()",],"border-bottom-width":["medium","thick","thin","calc()"],"border-inline-end-width":["medium","thick","thin","calc()",],"border-inline-start-width":["medium","thick","thin","calc()",],"font-stretch":["normal","wider","narrower","ultra-condensed","extra-condensed","condensed","semi-condensed","semi-expanded","expanded","extra-expanded","ultra-expanded"],"border-left-width":["medium","thick","thin","calc()"],"border-top-width":["medium","thick","thin","calc()"],"outline-color":["invert","-webkit-focus-ring-color"],"cursor":["auto","default","none","context-menu","help","pointer","progress","wait","cell","crosshair","text","vertical-text","alias","copy","move","no-drop","not-allowed","grab","grabbing","e-resize","n-resize","ne-resize","nw-resize","s-resize","se-resize","sw-resize","w-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","col-resize","row-resize","all-scroll","zoom-in","zoom-out","-webkit-grab","-webkit-grabbing","-webkit-zoom-in","-webkit-zoom-out","url()","image-set()"],"border-width":["medium","thick","thin","calc()"],"size":["a3","a4","a5","b4","b5","landscape","ledger","legal","letter","portrait"],"background":["none","url()","linear-gradient()","radial-gradient()","conic-gradient()","repeating-linear-gradient()","repeating-radial-gradient()","repeating-conic-gradient()","-webkit-canvas()","cross-fade()","image-set()","repeat","repeat-x","repeat-y","no-repeat","space","round","scroll","fixed","local","auto","contain","cover","top","right","left","bottom","center","border-box","padding-box","content-box"],"background-image":["none","url()","linear-gradient()","radial-gradient()","repeating-linear-gradient()","repeating-radial-gradient()","-webkit-canvas()","cross-fade()","image-set()"],"background-size":["auto","contain","cover"],"background-attachment":["scroll","fixed","local"],"background-repeat":["repeat","repeat-x","repeat-y","no-repeat","space","round"],"background-blend-mode":["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],"background-position":["top","right","left","bottom","center"],"background-origin":["border-box","padding-box","content-box"],"background-clip":["border-box","padding-box","content-box"],"enable-background":["accumulate","new"],"font-palette":["none","normal","light","dark"],"hanging-punctuation":["none","first","last","allow-end","force-end"],"inline-size":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()",],"overflow":["hidden","auto","visible","scroll","marquee","-webkit-paged-x","-webkit-paged-y"],"-webkit-box-reflect":["none","left","right","above","below"],"margin-block":["auto",],"margin-block-end":["auto",],"margin-block-start":["auto",],"margin-bottom":["auto"],"margin-inline":["auto",],"margin-inline-end":["auto",],"margin-inline-start":["auto",],"font-weight":["normal","bold","bolder","lighter","100","200","300","400","500","600","700","800","900"],"font-synthesis":["none","weight","style","small-caps"],"font-synthesis-weight":["none","auto"],"font-synthesis-style":["none","auto"],"font-synthesis-small-caps":["none","auto"],"font-style":["italic","oblique","normal"],"outline":["none","hidden","inset","groove","ridge","outset","dotted","dashed","solid","double"],"font":["caption","icon","menu","message-box","small-caption","-webkit-mini-control","-webkit-small-control","-webkit-control","status-bar","italic","oblique","small-caps","normal","bold","bolder","lighter","100","200","300","400","500","600","700","800","900","xx-small","x-small","small","medium","large","x-large","xx-large","xxx-large","smaller","larger","serif","sans-serif","cursive","fantasy","monospace","-webkit-body","-webkit-pictograph","-apple-system","-apple-system-headline","-apple-system-body","-apple-system-subheadline","-apple-system-footnote","-apple-system-caption1","-apple-system-caption2","-apple-system-short-headline","-apple-system-short-body","-apple-system-short-subheadline","-apple-system-short-footnote","-apple-system-short-caption1","-apple-system-tall-body","-apple-system-title0","-apple-system-title1","-apple-system-title2","-apple-system-title3","-apple-system-title4","system-ui"],"outline-width":["medium","thick","thin","calc()"],"box-shadow":["none"],"text-shadow":["none"],"-webkit-box-shadow":["none"],"border-right-width":["medium","thick","thin"],"line-height":["normal"],"counter-increment":["none"],"counter-reset":["none"],"page-break-after":["left","right","auto","always","avoid"],"page-break-before":["left","right","auto","always","avoid"],"page-break-inside":["auto","avoid"],"-webkit-column-break-after":["left","right","auto","always","avoid"],"-webkit-column-break-before":["left","right","auto","always","avoid"],"-webkit-column-break-inside":["auto","avoid"],"border-image":["repeat","stretch","url()","linear-gradient()","radial-gradient()","repeating-linear-gradient()","repeating-radial-gradient()","-webkit-canvas()","cross-fade()","image-set()"],"border-image-repeat":["repeat","stretch","space","round"],"-webkit-mask-box-image-repeat":["repeat","stretch","space","round"],"font-family":["serif","sans-serif","cursive","fantasy","monospace","-webkit-body","-webkit-pictograph","-apple-system","-apple-system-headline","-apple-system-body","-apple-system-subheadline","-apple-system-footnote","-apple-system-caption1","-apple-system-caption2","-apple-system-short-headline","-apple-system-short-body","-apple-system-short-subheadline","-apple-system-short-footnote","-apple-system-short-caption1","-apple-system-tall-body","-apple-system-title0","-apple-system-title1","-apple-system-title2","-apple-system-title3","-apple-system-title4","system-ui"],"margin-left":["auto"],"margin-top":["auto"],"zoom":["normal","document","reset"],"z-index":["auto"],"width":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()"],"height":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()"],"max-width":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","none","calc()"],"min-width":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()"],"max-block-size":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","none","calc()",],"max-height":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","none","calc()"],"max-inline-size":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","none","calc()",],"min-block-size":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()",],"min-height":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()"],"min-inline-size":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()",],"letter-spacing":["normal","calc()"],"word-spacing":["normal","calc()"],"border":["none","hidden","inset","groove","ridge","outset","dotted","dashed","solid","double"],"font-size":["xx-small","x-small","small","medium","large","x-large","xx-large","xxx-large","smaller","larger"],"font-variant":["small-caps","normal"],"font-variant-numeric":["normal","ordinal","slashed-zero","lining-nums","oldstyle-nums","proportional-nums","tabular-nums","diagonal-fractions","stacked-fractions"],"vertical-align":["baseline","middle","sub","super","text-top","text-bottom","top","bottom","-webkit-baseline-middle"],"text-indent":["each-line","hanging"],"clip":["auto","rect()"],"clip-path":["none","url()","circle()","ellipse()","inset()","polygon()","margin-box","border-box","padding-box","content-box"],"shape-outside":["none","url()","circle()","ellipse()","inset()","polygon()","margin-box","border-box","padding-box","content-box"],"orphans":["auto"],"widows":["auto"],"margin":["auto"],"page":["auto"],"perspective":["none"],"perspective-origin":["none","left","right","bottom","top","center"],"margin-right":["auto"],"-webkit-text-emphasis":["circle","filled","open","dot","double-circle","triangle","sesame"],"-webkit-text-emphasis-style":["circle","filled","open","dot","double-circle","triangle","sesame"],"-webkit-text-emphasis-position":["over","under","left","right"],"transform":["none","scale()","scaleX()","scaleY()","scale3d()","rotate()","rotateX()","rotateY()","rotateZ()","rotate3d()","skew()","skewX()","skewY()","translate()","translateX()","translateY()","translateZ()","translate3d()","matrix()","matrix3d()","perspective()"],"text-decoration":["none","underline","overline","line-through","blink"],"-webkit-text-decorations-in-effect":["none","underline","overline","line-through","blink"],"-webkit-text-decoration-line":["none","underline","overline","line-through","blink"],"-webkit-text-decoration-skip":["auto","none","objects","ink"],"-webkit-text-underline-position":["auto","alphabetic","under"],"transition":["none","ease","linear","ease-in","ease-out","ease-in-out","step-start","step-end","steps()","cubic-bezier()","linear()","spring()","all",WI.CSSKeywordCompletions.AllPropertyNamesPlaceholder],"transition-timing-function":["ease","linear","ease-in","ease-out","ease-in-out","step-start","step-end","steps()","cubic-bezier()","linear()","spring()"],"transition-property":["all","none",WI.CSSKeywordCompletions.AllPropertyNamesPlaceholder],"animation-direction":["normal","alternate","reverse","alternate-reverse"],"animation-fill-mode":["none","forwards","backwards","both"],"animation-iteration-count":["infinite"],"animation-play-state":["paused","running"],"animation-timeline":["auto","none","scroll()","view()"],"animation-timing-function":["ease","linear","ease-in","ease-out","ease-in-out","step-start","step-end","steps()","cubic-bezier()","linear()","spring()"],"align-content":["auto","baseline","last-baseline","space-between","space-around","space-evenly","stretch","center","start","end","flex-start","flex-end","left","right","true","safe"],"justify-content":["auto","baseline","last-baseline","space-between","space-around","space-evenly","stretch","center","start","end","flex-start","flex-end","left","right","true","safe"],"align-items":["auto","stretch","baseline","last-baseline","center","start","end","self-start","self-end","flex-start","flex-end","left","right","true","safe"],"align-self":["auto","stretch","baseline","last-baseline","center","start","end","self-start","self-end","flex-start","flex-end","left","right","true","safe"],"justify-items":["auto","stretch","baseline","last-baseline","center","start","end","self-start","self-end","flex-start","flex-end","left","right","true","safe"],"justify-self":["auto","stretch","baseline","last-baseline","center","start","end","self-start","self-end","flex-start","flex-end","left","right","true","safe"],"flex-flow":["row","row-reverse","column","column-reverse","nowrap","wrap","wrap-reverse"],"flex":["none"],"flex-basis":["auto"],"grid":["none"],"grid-area":["auto"],"grid-auto-columns":["auto","max-content","-webkit-max-content","min-content","-webkit-min-content","minmax()",],"grid-auto-flow":["row","column","dense"],"grid-auto-rows":["auto","max-content","-webkit-max-content","min-content","-webkit-min-content","minmax()",],"grid-column":["auto"],"grid-column-start":["auto"],"grid-column-end":["auto"],"grid-row":["auto"],"grid-row-start":["auto"],"grid-row-end":["auto"],"grid-template":["none"],"grid-template-areas":["none"],"grid-template-columns":["none","auto","max-content","-webkit-max-content","min-content","-webkit-min-content","minmax()","repeat()"],"grid-template-rows":["none","auto","max-content","-webkit-max-content","min-content","-webkit-min-content","minmax()","repeat()"],"scroll-snap-align":["none","start","center","end"],"scroll-snap-type":["none","mandatory","proximity","x","y","inline","block","both"],"-webkit-mask-composite":["clear","copy","source-over","source-in","source-out","source-atop","destination-over","destination-in","destination-out","destination-atop","xor","plus-darker","plus-lighter"],"-webkit-text-stroke-width":["medium","thick","thin","calc()"],"-webkit-aspect-ratio":["auto","from-dimensions","from-intrinsic","/"],"filter":["none","grayscale()","sepia()","saturate()","hue-rotate()","invert()","opacity()","brightness()","contrast()","blur()","drop-shadow()","custom()"],"-webkit-backdrop-filter":["none","grayscale()","sepia()","saturate()","hue-rotate()","invert()","opacity()","brightness()","contrast()","blur()","drop-shadow()","custom()"],"-webkit-hyphenate-character":["none"],"-webkit-hyphenate-limit-after":["auto"],"-webkit-hyphenate-limit-before":["auto"],"-webkit-hyphenate-limit-lines":["no-limit"],"-webkit-line-grid":["none"],"-webkit-locale":["auto"],"-webkit-line-box-contain":["block","inline","font","glyphs","replaced","inline-box","none"],"font-feature-settings":["normal"],"-webkit-text-size-adjust":["none","auto"],"-apple-pay-button-style":["black","white","white-outline",],"-apple-pay-button-type":["plain","buy","set-up","donate","check-out","book","subscribe",],"-webkit-alt":["attr()",],"-webkit-animation-direction":["normal","alternate","reverse","alternate-reverse",],"-webkit-animation-fill-mode":["none","forwards","backwards","both",],"-webkit-animation-iteration-count":["infinite",],"-webkit-animation-play-state":["paused","running",],"-webkit-animation-timing-function":["ease","linear","ease-in","ease-out","ease-in-out","step-start","step-end","steps()","cubic-bezier()","linear()","spring()",],"-webkit-appearance":["none","checkbox","radio","push-button","square-button","button","button-bevel","default-button","inner-spin-button","listbox","listitem","media-controls-background","media-controls-dark-bar-background","media-controls-fullscreen-background","media-controls-light-bar-background","media-current-time-display","media-enter-fullscreen-button","media-exit-fullscreen-button","media-fullscreen-volume-slider","media-fullscreen-volume-slider-thumb","media-mute-button","media-overlay-play-button","media-play-button","media-return-to-realtime-button","media-rewind-button","media-seek-back-button","media-seek-forward-button","media-slider","media-sliderthumb","media-time-remaining-display","media-toggle-closed-captions-button","media-volume-slider","media-volume-slider-container","media-volume-slider-mute-button","media-volume-sliderthumb","menulist","menulist-button","menulist-text","menulist-textfield","meter","progress-bar","progress-bar-value","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","caret","searchfield","searchfield-decoration","searchfield-results-decoration","searchfield-results-button","searchfield-cancel-button","snapshotted-plugin-overlay","textfield","relevancy-level-indicator","continuous-capacity-level-indicator","discrete-capacity-level-indicator","rating-level-indicator","-apple-pay-button","textarea","attachment","borderless-attachment","caps-lock-indicator",],"-webkit-backface-visibility":["hidden","visible",],"-webkit-border-after-width":["medium","thick","thin","calc()",],"-webkit-border-before-width":["medium","thick","thin","calc()",],"-webkit-border-end-width":["medium","thick","thin","calc()",],"-webkit-border-start-width":["medium","thick","thin","calc()",],"-webkit-box-align":["baseline","center","stretch","start","end",],"-webkit-box-decoration-break":["clone","slice",],"-webkit-box-direction":["normal","reverse",],"-webkit-box-lines":["single","multiple",],"-webkit-box-orient":["horizontal","vertical","inline-axis","block-axis",],"-webkit-box-pack":["center","justify","start","end",],"-webkit-column-axis":["auto","horizontal","vertical",],"-webkit-column-count":["auto","calc()",],"-webkit-column-fill":["auto","balance",],"-webkit-column-gap":["normal","calc()",],"-webkit-column-progression":["normal","reverse",],"-webkit-column-rule-width":["medium","thick","thin","calc()",],"-webkit-column-span":["all","none","calc()",],"-webkit-column-width":["auto","calc()",],"-webkit-cursor-visibility":["auto","auto-hide",],"-webkit-font-kerning":["none","normal","auto",],"-webkit-font-smoothing":["none","auto","antialiased","subpixel-antialiased",],"-webkit-hyphens":["none","auto","manual",],"-webkit-line-align":["none","edges",],"-webkit-line-break":["auto","loose","normal","strict","after-white-space",],"-webkit-line-snap":["none","baseline","contain",],"-webkit-logical-height":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()"],"-webkit-logical-width":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()"],"-webkit-max-logical-height":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","none","calc()"],"-webkit-max-logical-width":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","none","calc()"],"-webkit-min-logical-height":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()"],"-webkit-min-logical-width":["auto","intrinsic","min-intrinsic","min-content","-webkit-min-content","max-content","-webkit-max-content","-webkit-fill-available","fit-content","-webkit-fit-content","calc()"],"-webkit-nbsp-mode":["normal","space",],"-webkit-overflow-scrolling":["auto","touch",],"print-color-adjust":["economy","exact",],"-webkit-rtl-ordering":["logical","visual",],"-webkit-ruby-position":["after","before","inter-character",],"-webkit-text-combine":["none","horizontal",],"-webkit-text-decoration-style":["dotted","dashed","solid","double","wavy",],"-webkit-text-orientation":["sideways","sideways-right","upright","mixed",],"-webkit-text-security":["none","disc","circle","square",],"-webkit-text-zoom":["normal","reset",],"-webkit-transform-style":["flat","preserve-3d",],"-webkit-user-drag":["none","auto","element",],"-webkit-user-modify":["read-only","read-write","read-write-plaintext-only",],"-webkit-user-select":["none","all","auto","text",],"-webkit-writing-mode":["lr","rl","tb","lr-tb","rl-tb","tb-rl","horizontal-tb","vertical-rl","vertical-lr","horizontal-bt",],"alignment-baseline":["baseline","middle","auto","alphabetic","before-edge","after-edge","central","text-before-edge","text-after-edge","ideographic","hanging","mathematical",],"border-block-end-style":["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double",],"border-block-start-style":["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double",],"border-bottom-style":["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double",],"border-collapse":["collapse","separate",],"border-inline-end-style":["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double",],"border-inline-start-style":["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double",],"border-left-style":["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double",],"border-right-style":["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double",],"border-top-style":["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double",],"box-sizing":["border-box","content-box",],"break-after":["left","right","auto","avoid","column","avoid-column","avoid-page","page","recto","verso",],"break-before":["left","right","auto","avoid","column","avoid-column","avoid-page","page","recto","verso",],"break-inside":["auto","avoid","avoid-column","avoid-page",],"buffered-rendering":["auto","static","dynamic",],"caption-side":["top","bottom","left","right",],"clear":["none","left","right","both",],"clip-rule":["nonzero","evenodd",],"color-interpolation":["auto","sRGB","linearRGB",],"color-interpolation-filters":["auto","sRGB","linearRGB",],"color-rendering":["auto","optimizeSpeed","optimizeQuality",],"column-fill":["auto","balance",],"column-rule-style":["none","hidden","inset","groove","outset","ridge","dotted","dashed","solid","double",],"direction":["ltr","rtl",],"display":["none","inline","block","list-item","compact","inline-block","table","inline-table","table-row-group","table-header-group","table-footer-group","table-row","table-column-group","table-column","table-cell","table-caption","-webkit-box","-webkit-inline-box","flex","-webkit-flex","inline-flex","-webkit-inline-flex","contents","grid","inline-grid",],"dominant-baseline":["middle","auto","alphabetic","central","text-before-edge","text-after-edge","ideographic","hanging","mathematical","use-script","no-change","reset-size",],"empty-cells":["hide","show",],"fill-rule":["nonzero","evenodd",],"flex-direction":["row","row-reverse","column","column-reverse",],"flex-wrap":["nowrap","wrap-reverse","wrap",],"float":["none","left","right",],"font-optical-sizing":["none","auto",],"font-variant-alternates":["historical-forms","normal",],"font-variant-caps":["small-caps","all-small-caps","petite-caps","all-petite-caps","unicase","titling-caps","normal",],"font-variant-position":["normal","sub","super",],"image-rendering":["auto","optimizeSpeed","optimizeQuality","crisp-edges","pixelated","-webkit-crisp-edges","-webkit-optimize-contrast",],"image-resolution":["from-image","snap",],"isolation":["auto","isolate",],"line-break":["normal","auto","loose","strict","after-white-space",],"list-style-position":["outside","inside",],"list-style-type":["none","disc","circle","square","decimal","decimal-leading-zero","arabic-indic","binary","bengali","cambodian","khmer","devanagari","gujarati","gurmukhi","kannada","lower-hexadecimal","lao","malayalam","mongolian","myanmar","octal","oriya","persian","urdu","telugu","tibetan","thai","upper-hexadecimal","lower-roman","upper-roman","lower-greek","lower-alpha","lower-latin","upper-alpha","upper-latin","afar","ethiopic-halehame-aa-et","ethiopic-halehame-aa-er","amharic","ethiopic-halehame-am-et","amharic-abegede","ethiopic-abegede-am-et","cjk-earthly-branch","cjk-heavenly-stem","ethiopic","ethiopic-halehame-gez","ethiopic-abegede","ethiopic-abegede-gez","hangul-consonant","hangul","lower-norwegian","oromo","ethiopic-halehame-om-et","sidama","ethiopic-halehame-sid-et","somali","ethiopic-halehame-so-et","tigre","ethiopic-halehame-tig","tigrinya-er","ethiopic-halehame-ti-er","tigrinya-er-abegede","ethiopic-abegede-ti-er","tigrinya-et","ethiopic-halehame-ti-et","tigrinya-et-abegede","ethiopic-abegede-ti-et","upper-greek","upper-norwegian","asterisks","footnotes","hebrew","armenian","lower-armenian","upper-armenian","georgian","cjk-ideographic","hiragana","katakana","hiragana-iroha","katakana-iroha",],"mask-type":["alpha","luminance",],"max-zoom":["auto",],"min-zoom":["auto",],"mix-blend-mode":["normal","plus-darker","plus-lighter","overlay","multiply","screen","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity",],"object-fit":["none","contain","cover","fill","scale-down",],"orientation":["auto","portait","landscape",],"outline-style":["none","inset","groove","outset","ridge","dotted","dashed","solid","double","auto",],"overflow-wrap":["normal","break-word",],"overflow-x":["hidden","auto","visible","scroll",],"overflow-y":["hidden","auto","visible","scroll","-webkit-paged-x","-webkit-paged-y",],"pointer-events":["none","all","auto","visible","visiblePainted","visibleFill","visibleStroke","painted","fill","stroke",],"position":["absolute","fixed","relative","static","sticky","-webkit-sticky",],"resize":["none","auto","both","horizontal","vertical",],"shape-rendering":["auto","optimizeSpeed","geometricPrecision","crispedges",],"stroke-linecap":["square","round","butt",],"stroke-linejoin":["round","miter","bevel",],"table-layout":["auto","fixed",],"text-align":["-webkit-auto","left","right","center","justify","match-parent","-webkit-left","-webkit-right","-webkit-center","-webkit-match-parent","start","end",],"text-align-last":["auto","start","end","left","right","center","justify","match-parent",],"text-anchor":["middle","start","end",],"text-justify":["auto","none","inter-word","inter-character","distribute",],"text-line-through":["none","dotted","dashed","solid","double","dot-dash","dot-dot-dash","wave","continuous","skip-white-space",],"text-line-through-mode":["continuous","skip-white-space",],"text-line-through-style":["none","dotted","dashed","solid","double","dot-dash","dot-dot-dash","wave",],"text-line-through-width":["normal","medium","auto","thick","thin",],"text-overflow":["clip","ellipsis",],"text-overline-mode":["continuous","skip-white-space",],"text-overline-style":["none","dotted","dashed","solid","double","dot-dash","dot-dot-dash","wave",],"text-overline-width":["normal","medium","auto","thick","thin","calc()",],"text-rendering":["auto","optimizeSpeed","optimizeLegibility","geometricPrecision",],"text-transform":["none","capitalize","uppercase","lowercase",],"text-underline":["none","dotted","dashed","solid","double","dot-dash","dot-dot-dash","wave",],"text-underline-mode":["continuous","skip-white-space",],"text-underline-style":["none","dotted","dashed","solid","double","dot-dash","dot-dot-dash","wave",],"text-underline-width":["normal","medium","auto","thick","thin","calc()",],"transform-style":["flat","preserve-3d",],"unicode-bidi":["normal","bidi-override","embed","isolate-override","plaintext","-webkit-isolate","-webkit-isolate-override","-webkit-plaintext","isolate",],"user-zoom":["zoom","fixed",],"vector-effect":["none",],"visibility":["hidden","visible","collapse",],"white-space":["normal","nowrap","pre","pre-line","pre-wrap",],"word-break":["normal","break-all","keep-all","break-word",],"word-wrap":["normal","break-word",],"writing-mode":["lr","rl","tb","lr-tb","rl-tb","tb-rl","horizontal-tb","vertical-rl","vertical-lr","horizontal-bt",],};WI.CSSProperty=class CSSProperty extends WI.Object {constructor(index,text,name,value,priority,enabled,overridden,implicit,anonymous,valid,styleSheetTextRange) {WI.CSSProperty._initializePropertyNameCounts();super();this._ownerStyle=null;this._index=index;this._overridingProperty=null;this._initialState=null;this._modified=false;this._isUpdatingText=false;this._isNewProperty=false;this.update(text,name,value,priority,enabled,overridden,implicit,anonymous,valid,styleSheetTextRange,true);} static isVariable(name) {return name.startsWith("--")&&name.length>2;} static isInheritedPropertyName(name) {if(WI.CSSKeywordCompletions.InheritedProperties.has(name)) return true;return WI.CSSProperty.isVariable(name);} static findVariableNames(string) {const prefix="var(--";let prefixCursor=0;let cursor=0;let nameStartIndex=0;let names=[];function isTerminatingChar(char){return char===")"||char===","||char===" "||char==="\n"||char==="\t";} while(cursor=minimumCount;let validB=countB>=minimumCount;if(validA&&!validB) return-1;if(!validA&&validB) return 1;if(validA&&validB){if(countA!==countB) return countB-countA;let canonicalPropertyNameA=WI.cssManager.canonicalNameForPropertyName(propertyNameA);let canonicalPropertyNameB=WI.cssManager.canonicalNameForPropertyName(propertyNameB);if(canonicalPropertyNameA!==propertyNameA||canonicalPropertyNameB!==propertyNameB) return WI.CSSProperty.sortByPropertyNameUsageCount(canonicalPropertyNameA,canonicalPropertyNameB);} return 0;} static indexOfCompletionForMostUsedPropertyName(completions) {let highestRankCompletions=completions;if(highestRankCompletions.every((completion)=>completion instanceof WI.QueryResult)){let highestRankValue=-1;for(let completion of completions){if(completion.rank>highestRankValue){highestRankValue=completion.rank;highestRankCompletions=[];} if(completion.rank===highestRankValue) highestRankCompletions.push(completion);}} let mostUsedHighestRankCompletion=highestRankCompletions.min((a,b)=>WI.CSSProperty.sortByPropertyNameUsageCount(WI.CSSCompletions.getCompletionText(a),WI.CSSCompletions.getCompletionText(b)));return completions.indexOf(mostUsedHighestRankCompletion);} static _initializePropertyNameCounts() {if(WI.CSSProperty._cachedNameCounts) return;WI.CSSProperty._cachedNameCounts={};WI.CSSProperty._storedNameCountsQueue=new Promise((resolve,reject)=>{WI.objectStores.cssPropertyNameCounts.getAllKeys().then((propertyNames)=>{Promise.allSettled(propertyNames.map(async(propertyName)=>{let storedCount=await WI.objectStores.cssPropertyNameCounts.get(propertyName);WI.CSSProperty._cachedNameCounts[propertyName]=(WI.CSSProperty._cachedNameCounts[propertyName]||0)+storedCount;})).then(resolve,reject);});});} get ownerStyle() {return this._ownerStyle;} set ownerStyle(ownerStyle) {this._ownerStyle=ownerStyle||null;} get index() {return this._index;} set index(index) {this._index=index;} update(text,name,value,priority,enabled,overridden,implicit,anonymous,valid,styleSheetTextRange,dontFireEvents) {if(this._ownerStyle&&this._ownerStyle.locked&&text!==this._text) return;text=text||"";name=name||"";value=value||"";priority=priority||"";enabled=enabled||false;overridden=overridden||false;implicit=implicit||false;anonymous=anonymous||false;valid=valid||false;var changed=false;if(!dontFireEvents){changed=this._name!==name||this._rawValue!==value||this._priority!==priority||this._enabled!==enabled||this._implicit!==implicit||this._anonymous!==anonymous||this._valid!==valid;} if(!dontFireEvents) this.overridden=overridden;else this._overridden=overridden;if(!overridden) this._overridingProperty=null;this._text=text;this._rawValue=value;this._value=undefined;this._priority=priority;this._enabled=enabled;this._implicit=implicit;this._anonymous=anonymous;this._inherited=WI.CSSProperty.isInheritedPropertyName(name);this._valid=valid;this._isVariable=WI.CSSProperty.isVariable(name);this._styleSheetTextRange=styleSheetTextRange||null;this._rawValueNewlineIndent="";if(this._rawValue){let match=this._rawValue.match(/^[^\n]+\n(\s*)/);if(match) this._rawValueNewlineIndent=match[1];} this._rawValue=this._rawValue.replace(/\n\s+/g,"\n");this._isShorthand=undefined;this._shorthandPropertyNames=undefined;this._updateName(name);this._relatedShorthandProperty=null;this._relatedLonghandProperties=[];delete this._styleDeclarationTextRange;delete this._canonicalName;delete this._hasOtherVendorNameOrKeyword;if(changed) this.dispatchEventToListeners(WI.CSSProperty.Event.Changed);} remove() {this._markModified();this._updateName("");const forceRemove=true;this._updateStyleText(forceRemove);} commentOut(disabled) {if(this._enabled===!disabled) return;this._markModified();this._enabled=!disabled;if(disabled) this.text="/* "+this._text+" */";else this.text=this._text.slice(2,-2).trim();} get text() {return this._text;} set text(newText) {newText=newText.trim();if(this._text===newText) return;this._markModified();this._text=newText;this._isUpdatingText=true;this._updateOwnerStyleText();this._isUpdatingText=false;} get formattedText() {if(this._isUpdatingText) return this._text;if(!this._name) return"";let text=`${this._name}: ${this._rawValue};`;if(!this._enabled) text="/* "+text+" */";return text;} get modified() {return this._modified;} set modified(value) {if(this._modified===value) return;this._modified=value;this.dispatchEventToListeners(WI.CSSProperty.Event.ModifiedChanged);} get name() {return this._name;} set name(name) {if(name===this._name) return;if(!name){this._indexBeforeDetached=this._index;}else if(!isNaN(this._indexBeforeDetached)&&isNaN(this._index)){this._ownerStyle.insertProperty(this,this._indexBeforeDetached);this._indexBeforeDetached=NaN;} this._markModified();this._updateName(name);this._updateStyleText();} get canonicalName() {if(this._canonicalName) return this._canonicalName;this._canonicalName=WI.cssManager.canonicalNameForPropertyName(this.name);return this._canonicalName;} get value() {if(!this._value) this._value=this._rawValue.replace(/\s*!important\s*$/,"");return this._value;} get rawValue() {return this._rawValue;} set rawValue(value) {if(value===this._rawValue) return;this._markModified();let suffix=WI.CSSCompletions.completeUnbalancedValue(value);if(suffix) value+=suffix;this._rawValue=value;this._value=undefined;this._updateStyleText();} get important() {return this.priority==="important";} get priority(){return this._priority;} get attached() {return this._enabled&&this._ownerStyle&&(!isNaN(this._index)||this._ownerStyle.type===WI.CSSStyleDeclaration.Type.Computed);} get enabled(){return this._enabled;} get overridden(){return this._overridden;} set overridden(overridden) {overridden=overridden||false;if(this._overridden===overridden) return;if(!overridden) this._overridingProperty=null;var previousOverridden=this._overridden;this._overridden=overridden;if(this._overriddenStatusChangedTimeout) return;function delayed() {delete this._overriddenStatusChangedTimeout;if(this._overridden===previousOverridden) return;this.dispatchEventToListeners(WI.CSSProperty.Event.OverriddenStatusChanged);} this._overriddenStatusChangedTimeout=setTimeout(delayed.bind(this),0);} get overridingProperty() {return this._overridingProperty;} set overridingProperty(effectiveProperty) {if(!WI.settings.experimentalEnableStylesJumpToEffective.value) return;this._overridingProperty=effectiveProperty||null;} get implicit(){return this._implicit;} set implicit(implicit){this._implicit=implicit;} get anonymous(){return this._anonymous;} get inherited(){return this._inherited;} get valid(){return this._valid;} get isVariable(){return this._isVariable;} get styleSheetTextRange(){return this._styleSheetTextRange;} get initialState() {return this._initialState;} get editable() {return!!(this._styleSheetTextRange&&this._ownerStyle&&this._ownerStyle.styleSheetTextRange);} get styleDeclarationTextRange() {if("_styleDeclarationTextRange"in this) return this._styleDeclarationTextRange;if(!this._ownerStyle||!this._styleSheetTextRange) return null;var styleTextRange=this._ownerStyle.styleSheetTextRange;if(!styleTextRange) return null;var startLine=this._styleSheetTextRange.startLine-styleTextRange.startLine;var endLine=this._styleSheetTextRange.endLine-styleTextRange.startLine;var startColumn=this._styleSheetTextRange.startColumn;if(!startLine) startColumn-=styleTextRange.startColumn;var endColumn=this._styleSheetTextRange.endColumn;if(!endLine) endColumn-=styleTextRange.startColumn;this._styleDeclarationTextRange=new WI.TextRange(startLine,startColumn,endLine,endColumn);return this._styleDeclarationTextRange;} get relatedShorthandProperty(){return this._relatedShorthandProperty;} set relatedShorthandProperty(property) {this._relatedShorthandProperty=property||null;} get relatedLonghandProperties(){return this._relatedLonghandProperties;} addRelatedLonghandProperty(property) {this._relatedLonghandProperties.push(property);} clearRelatedLonghandProperties(property) {this._relatedLonghandProperties=[];} get isShorthand() {if(this._isShorthand===undefined){this._isShorthand=WI.CSSKeywordCompletions.LonghandNamesForShorthandProperty.has(this._name);if(this._isShorthand){let longhands=WI.CSSKeywordCompletions.LonghandNamesForShorthandProperty.get(this._name);if(longhands&&longhands.length===1) this._isShorthand=false;}} return this._isShorthand;} get shorthandPropertyNames() {if(!this._shorthandPropertyNames){this._shorthandPropertyNames=WI.CSSKeywordCompletions.ShorthandNamesForLongHandProperty.get(this._name)||[];this._shorthandPropertyNames.remove("all");} return this._shorthandPropertyNames;} get isNewProperty(){return this._isNewProperty;} set isNewProperty(value){this._isNewProperty=value;} hasOtherVendorNameOrKeyword() {if("_hasOtherVendorNameOrKeyword"in this) return this._hasOtherVendorNameOrKeyword;this._hasOtherVendorNameOrKeyword=WI.cssManager.propertyNameHasOtherVendorPrefix(this.name)||WI.cssManager.propertyValueHasOtherVendorKeyword(this.value);return this._hasOtherVendorNameOrKeyword;} equals(property) {if(property===this) return true;if(!property) return false;return this._name===property.name&&this._rawValue===property.rawValue&&this._enabled===property.enabled;} clone() {let cssProperty=new WI.CSSProperty(this._index,this._text,this._name,this._rawValue,this._priority,this._enabled,this._overridden,this._implicit,this._anonymous,this._valid,this._styleSheetTextRange);cssProperty.ownerStyle=this._ownerStyle;return cssProperty;} _updateName(name) {if(name===this._name) return;let changeCount=(propertyName,delta)=>{if(this._implicit||this._anonymous||!this._enabled) return;if(!propertyName||WI.CSSProperty.isVariable(propertyName)) return;let cachedCount=WI.CSSProperty._cachedNameCounts[propertyName];if(isNaN(cachedCount)&&!WI.cssManager.propertyNameCompletions.isValidPropertyName(propertyName)) return;WI.CSSProperty._cachedNameCounts[propertyName]=Math.max(0,(cachedCount||0)+delta);WI.CSSProperty._storedNameCountsQueue=WI.CSSProperty._storedNameCountsQueue.finally(async()=>{let storedCount=await WI.objectStores.cssPropertyNameCounts.get(propertyName);await WI.objectStores.cssPropertyNameCounts.put(Math.max(0,(storedCount||0)+delta),propertyName);});if(propertyName!==this.canonicalName) changeCount(this.canonicalName,delta);};changeCount(this._name,-1);this._name=name;changeCount(this._name,1);} _updateStyleText(forceRemove=false) {let text="";if(this._name&&this._rawValue){let value=this._rawValue.replace(/\n/g,"\n"+this._rawValueNewlineIndent);text=this._name+": "+value+";";} this._text=text;if(forceRemove) this._ownerStyle.removeProperty(this);this._updateOwnerStyleText();} _updateOwnerStyleText() {if(!this._ownerStyle) return;this._ownerStyle.text=this._ownerStyle.generateFormattedText({multiline:this._ownerStyle.type===WI.CSSStyleDeclaration.Type.Rule});this._ownerStyle.updatePropertiesModifiedState();} _markModified() {if(this._ownerStyle) this._ownerStyle.markModified();}};WI.CSSProperty._cachedNameCounts=null;WI.CSSProperty._storedNameCountsQueue=null;WI.CSSProperty.Event={Changed:"css-property-changed",ModifiedChanged:"css-property-modified-changed",OverriddenStatusChanged:"css-property-overridden-status-changed"};WI.CSSPropertyNameCompletions=class CSSPropertyNameCompletions extends WI.CSSCompletions {constructor(properties,options={}) {let values=[];for(let property of properties){values.push(property.name);if(Array.isArray(property.aliases)) values.pushAll(property.aliases);} super(values,options);this._cachedSortedPropertyNames=this.values.slice();this._needsVariablesFromInspectedNode=true;this._inspectedDOMNodeStyles=null;WI.domManager.addEventListener(WI.DOMManager.Event.InspectedNodeChanged,this._handleInspectedNodeChanged,this);} isValidPropertyName(name) {return this.values.includes(name);} executeQuery(query) {this._updateValuesWithLatestCSSVariablesIfNeeded();return super.executeQuery(query);} startsWith(prefix) {this._updateValuesWithLatestCSSVariablesIfNeeded();return super.startsWith(prefix);} _updateValuesWithLatestCSSVariablesIfNeeded() {if(!this._needsVariablesFromInspectedNode) return;if(!WI.domManager.inspectedNode){this._needsVariablesFromInspectedNode=false;return;} let values=Array.from(WI.cssManager.stylesForNode(WI.domManager.inspectedNode).allCSSVariables);values.pushAll(this._cachedSortedPropertyNames);this.replaceValues(values);this._needsVariablesFromInspectedNode=false;} _handleInspectedNodeChanged(event) {this._needsVariablesFromInspectedNode=true;this._inspectedDOMNodeStyles?.removeEventListener(WI.DOMNodeStyles.Event.NeedsRefresh,this._handleNodesStylesNeedsRefresh,this);this._inspectedDOMNodeStyles=WI.cssManager.stylesForNode(WI.domManager.inspectedNode);this._inspectedDOMNodeStyles.addEventListener(WI.DOMNodeStyles.Event.NeedsRefresh,this._handleNodesStylesNeedsRefresh,this);} _handleNodesStylesNeedsRefresh(event) {this._needsVariablesFromInspectedNode=true;}};WI.CSSRule=class CSSRule extends WI.Object {constructor(nodeStyles,ownerStyleSheet,id,type,sourceCodeLocation,selectorText,selectors,matchedSelectorIndices,style,groupings,isImplicitlyNested) {super();this._nodeStyles=nodeStyles;this._ownerStyleSheet=ownerStyleSheet||null;this._id=id||null;this._type=type||null;this._initialState=null;this._isImplicitlyNested=isImplicitlyNested||false;this.update(sourceCodeLocation,selectorText,selectors,matchedSelectorIndices,style,groupings,true);} get ownerStyleSheet(){return this._ownerStyleSheet;} get id(){return this._id;} get type(){return this._type;} get initialState(){return this._initialState;} get sourceCodeLocation(){return this._sourceCodeLocation;} get selectors(){return this._selectors;} get matchedSelectorIndices(){return this._matchedSelectorIndices;} get style(){return this._style;} get groupings(){return this._groupings;} get isImplicitlyNested(){return this._isImplicitlyNested;} get editable() {return!!this._id&&this._type!==WI.CSSStyleSheet.Type.UserAgent;} get selectorText() {return this._selectorText;} setSelectorText(selectorText) {if(!this.editable) return Promise.reject();return this._nodeStyles.changeRuleSelector(this,selectorText).then(this._selectorResolved.bind(this));} update(sourceCodeLocation,selectorText,selectors,matchedSelectorIndices,style,groupings) {sourceCodeLocation=sourceCodeLocation||null;selectorText=selectorText||"";selectors=selectors||[];matchedSelectorIndices=matchedSelectorIndices||[];style=style||null;groupings=groupings||[];if(this._style) this._style.ownerRule=null;this._sourceCodeLocation=sourceCodeLocation;this._selectorText=selectorText;this._selectors=selectors;this._matchedSelectorIndices=matchedSelectorIndices;this._style=style;this._groupings=groupings;if(this._style) this._style.ownerRule=this;} isEqualTo(rule) {if(!rule) return false;return Object.shallowEqual(this._id,rule.id);} get nodeStyles() {return this._nodeStyles;} _selectorResolved(rulePayload) {if(!rulePayload) return;let selectorText=rulePayload.selectorList.text;if(selectorText===this._selectorText) return;let selectors=WI.DOMNodeStyles.parseSelectorListPayload(rulePayload.selectorList);let sourceCodeLocation=null;let sourceRange=rulePayload.selectorList.range;if(sourceRange){sourceCodeLocation=WI.DOMNodeStyles.createSourceCodeLocation(rulePayload.sourceURL,{line:sourceRange.startLine,column:sourceRange.startColumn,documentNode:this._nodeStyles.node.ownerDocument,});} if(this._ownerStyleSheet){if(!sourceCodeLocation&&sourceRange) sourceCodeLocation=this._ownerStyleSheet.createSourceCodeLocation(sourceRange.startLine,sourceRange.startColumn);sourceCodeLocation=this._ownerStyleSheet.offsetSourceCodeLocation(sourceCodeLocation);} this.update(sourceCodeLocation,selectorText,selectors,[],this._style,this._groupings);}};WI.CSSSelector=class CSSSelector {constructor(text,specificity,dynamic) {this._text=text;this._specificity=specificity||null;this._dynamic=dynamic||false;} get text(){return this._text;} get specificity(){return this._specificity;} get dynamic(){return this._dynamic;} isPseudoSelector() {return Object.values(WI.CSSManager.PseudoSelectorNames).some((pseudoId)=>(new RegExp("(?:\\b|^):{1,2}(?:-webkit-)?"+pseudoId+"(?:\\b|$)")).test(this._text));}};WI.CSSStyleDeclaration=class CSSStyleDeclaration extends WI.Object {constructor(nodeStyles,ownerStyleSheet,id,type,node,inherited,text,properties,styleSheetTextRange) {super();this._nodeStyles=nodeStyles;this._ownerRule=null;this._ownerStyleSheet=ownerStyleSheet||null;this._id=id||null;this._type=type||null;this._node=node||null;this._inherited=inherited||false;this._initialState=null;this._updatesInProgressCount=0;this._pendingPropertiesChanged=false;this._locked=false;this._pendingProperties=[];this._propertyNameMap={};this._properties=[];this._enabledProperties=null;this._visibleProperties=null;this._variablesForType=new Map;this.update(text,properties,styleSheetTextRange,{dontFireEvents:true});} get initialState(){return this._initialState;} get id() {return this._id;} get stringId() {if(this._id) return this._id.styleSheetId+"/"+this._id.ordinal;else return"";} get ownerStyleSheet() {return this._ownerStyleSheet;} get type() {return this._type;} get inherited() {return this._inherited;} get node() {return this._node;} get editable() {if(!this._id) return false;if(this._type===WI.CSSStyleDeclaration.Type.Rule) return this._ownerRule&&this._ownerRule.editable;if(this._type===WI.CSSStyleDeclaration.Type.Inline) return!this._node.isInUserAgentShadowTree()||WI.DOMManager.supportsEditingUserAgentShadowTrees();return false;} get selectorEditable() {return this._ownerRule&&this._ownerRule.editable&&!this._ownerRule.isImplicitlyNested&&InspectorBackend.hasCommand("CSS.setRuleSelector");} get locked(){return this._locked;} set locked(value){this._locked=value;} variablesForType(type) {let variables=this._variablesForType.get(type);if(variables) return variables;const typeCheckFunctions=[{type:WI.CSSStyleDeclaration.VariablesGroupType.Colors,checker:(property)=>WI.Color.fromString(property.value),},{type:WI.CSSStyleDeclaration.VariablesGroupType.Dimensions,checker:(property)=>/^-?\d+(\.\d+)?\D+$/.test(property.value),},{type:WI.CSSStyleDeclaration.VariablesGroupType.Numbers,checker:(property)=>/^-?\d+(\.\d+)?$/.test(property.value),},{type:WI.CSSStyleDeclaration.VariablesGroupType.Other,checker:(property)=>true,},];for(let{type}of typeCheckFunctions) this._variablesForType.set(type,[]);for(let property of this._properties){if(!property.isVariable) continue;for(let{type,checker}of typeCheckFunctions){if(checker(property)){this._variablesForType.get(type).push(property);break;}}} return this._variablesForType.get(type);} update(text,properties,styleSheetTextRange,options={}) {let dontFireEvents=options.dontFireEvents||false; if(this._updatesInProgressCount>0&&!options.forceUpdate){if(WI.settings.debugEnableStyleEditingDebugMode.value&&text!==this._text) console.warn("Style modified while editing:",text);return;} if(this._locked&&!options.forceUpdate&&text!==this._text) return;text=text||"";properties=properties||[];let oldProperties=this._properties||[];let oldText=this._text;this._text=text;this._properties=properties;this._styleSheetTextRange=styleSheetTextRange;this._propertyNameMap={};this._variablesForType.clear();this._enabledProperties=null;this._visibleProperties=null;let editable=this.editable;for(let property of this._properties){property.ownerStyle=this; if(!editable) this._propertyNameMap[property.name]=property;else{this._pendingProperties.remove(property);}} for(let oldProperty of oldProperties){if(this._properties.includes(oldProperty)) continue;oldProperty.index=NaN; if(editable) this._pendingProperties.push(oldProperty);} if(dontFireEvents) return; if(oldText===this._text&&!this._pendingPropertiesChanged&&this._type!==WI.CSSStyleDeclaration.Type.Computed) return;this._pendingPropertiesChanged=false;function delayed() {this.dispatchEventToListeners(WI.CSSStyleDeclaration.Event.PropertiesChanged);} setTimeout(delayed.bind(this),0);} get ownerRule() {return this._ownerRule;} set ownerRule(rule) {this._ownerRule=rule||null;} get text() {return this._text;} set text(text) {if(this._text===text) return;let trimmedText=text.trim();if(this._text===trimmedText) return;if(!trimmedText.length||this._type===WI.CSSStyleDeclaration.Type.Inline) text=trimmedText;this._text=text;++this._updatesInProgressCount;let timeoutId=setTimeout(()=>{console.error("Timed out when setting style text:",text);styleTextDidChange();},2000);let styleTextDidChange=()=>{if(!timeoutId) return;clearTimeout(timeoutId);timeoutId=null;this._updatesInProgressCount=Math.max(0,this._updatesInProgressCount-1);this._pendingPropertiesChanged=true;};this._nodeStyles.changeStyleText(this,text,styleTextDidChange);} get enabledProperties() {if(!this._enabledProperties) this._enabledProperties=this._properties.filter((property)=>property.enabled);return this._enabledProperties;} get properties() {return this._properties;} set properties(properties) {if(properties===this._properties) return;this._properties=properties;this._enabledProperties=null;this._visibleProperties=null;} get visibleProperties() {if(!this._visibleProperties) this._visibleProperties=this._properties.filter((property)=>!!property.styleDeclarationTextRange);return this._visibleProperties;} get pendingProperties() {return this._pendingProperties;} get styleSheetTextRange() {return this._styleSheetTextRange;} get groupings() {if(this._ownerRule) return this._ownerRule.groupings;return[];} get selectorText() {if(this._ownerRule) return this._ownerRule.selectorText;return this._node.appropriateSelectorFor(true);} propertyForName(name) {if(!name) return null;if(!this.editable) return this._propertyNameMap[name]||null; let bestMatchProperty=null;for(let property of this.enabledProperties){if(property.canonicalName!==name&&property.name!==name) continue;if(bestMatchProperty&&!bestMatchProperty.overridden&&property.overridden) continue;bestMatchProperty=property;} return bestMatchProperty;} resolveVariableValue(text) {const invalid=Symbol("invalid");let checkTokens=(tokens)=>{let startIndex=NaN;let openParenthesis=0;for(let i=0;i0) continue;let variableTokens=tokens.slice(startIndex,i+1);startIndex=NaN;let variableNameIndex=variableTokens.findIndex((token)=>WI.CSSProperty.isVariable(token.value)&&/\bvariable-2\b/.test(token.type));if(variableNameIndex===-1) continue;let variableProperty=this.propertyForName(variableTokens[variableNameIndex].value);if(variableProperty) return variableProperty.value.trim();let fallbackStartIndex=variableTokens.findIndex((value,j)=>j>variableNameIndex+1&&/\bm-css\b/.test(value.type));if(fallbackStartIndex===-1) return invalid;let fallbackTokens=variableTokens.slice(fallbackStartIndex,i);return checkTokens(fallbackTokens)||fallbackTokens.reduce((accumulator,token)=>accumulator+token.value,"").trim();}} return null;};let resolved=checkTokens(WI.tokenizeCSSValue(text));return resolved===invalid?null:resolved;} newBlankProperty(propertyIndex) {let text,name,value,priority,overridden,implicit,anonymous;let enabled=true;let valid=false;let styleSheetTextRange=this._rangeAfterPropertyAtIndex(propertyIndex-1);this.markModified();let property=new WI.CSSProperty(propertyIndex,text,name,value,priority,enabled,overridden,implicit,anonymous,valid,styleSheetTextRange);property.isNewProperty=true;this.insertProperty(property,propertyIndex);this.update(this._text,this._properties,this._styleSheetTextRange,{dontFireEvents:true,forceUpdate:true});return property;} markModified() {if(!this._initialState){let visibleProperties=this.visibleProperties.map((property)=>{return property.clone();});this._initialState=new WI.CSSStyleDeclaration(this._nodeStyles,this._ownerStyleSheet,this._id,this._type,this._node,this._inherited,this._text,visibleProperties,this._styleSheetTextRange);} WI.cssManager.addModifiedStyle(this);} insertProperty(cssProperty,propertyIndex) {this._properties.insertAtIndex(cssProperty,propertyIndex);for(let index=propertyIndex+1;index!grouping.isMedia||grouping.text!=="all");let groupingsCount=groupings.length;if(options.includeGroupingsAndSelectors){for(let i=groupingsCount-1;i>=0;--i){if(options.multiline) styleText+=indentString.repeat(groupingsCount-i-1);let prefix=groupings[i].prefix;if(prefix) styleText+=prefix;if(groupings[i].text) styleText+=" "+groupings[i].text;styleText+=" {";if(options.multiline) styleText+="\n";} if(options.multiline) styleText+=indentString.repeat(groupingsCount);styleText+=this.selectorText+" {";} let properties=this._styleSheetTextRange?this.visibleProperties:this._properties;if(properties.length){if(options.multiline){let propertyIndent=indentString.repeat(groupingsCount+1);for(let property of properties) styleText+="\n"+propertyIndent+property.formattedText;styleText+="\n";if(!options.includeGroupingsAndSelectors){styleText+=indentString.repeat(groupingsCount);}}else styleText+=properties.map((property)=>property.formattedText).join(" ");} if(options.includeGroupingsAndSelectors){for(let i=groupingsCount;i>0;--i){if(options.multiline) styleText+=indentString.repeat(i);styleText+="}";if(options.multiline) styleText+="\n";} styleText+="}";} return styleText;} get nodeStyles() {return this._nodeStyles;} _rangeAfterPropertyAtIndex(index) {if(index<0) return this._styleSheetTextRange.collapseToStart();if(index>=this.visibleProperties.length) return this._styleSheetTextRange.collapseToEnd();let property=this.visibleProperties[index];return property.styleSheetTextRange.collapseToEnd();}};WI.CSSStyleDeclaration.Event={PropertiesChanged:"css-style-declaration-properties-changed",};WI.CSSStyleDeclaration.Type={Rule:"css-style-declaration-type-rule",Inline:"css-style-declaration-type-inline",Attribute:"css-style-declaration-type-attribute",Computed:"css-style-declaration-type-computed"};WI.CSSStyleDeclaration.VariablesGroupType={Ungrouped:"ungrouped",Colors:"colors",Dimensions:"dimensions",Numbers:"numbers",Other:"other",};WI.CSSStyleSheet=class CSSStyleSheet extends WI.SourceCode {constructor(id) {super();this._id=id||null;this._parentFrame=null;this._origin=null;this._startLineNumber=0;this._startColumnNumber=0;this._inlineStyleAttribute=false;this._inlineStyleTag=false;this._hasInfo=false;} static resetUniqueDisplayNameNumbers() {WI.CSSStyleSheet._nextUniqueDisplayNameNumber=1;} get id() {return this._id;} get parentFrame() {return this._parentFrame;} get origin() {return this._origin;} get injected() {return WI.browserManager.isExtensionScheme(this.urlComponents.scheme);} get anonymous() {return!this.isInspectorStyleSheet()&&!this._url;} get mimeType() {return"text/css";} get displayName() {if(this.isInspectorStyleSheet()) return WI.UIString("Inspector Style Sheet");if(this._url) return WI.displayNameForURL(this._url,this.urlComponents);if(!this._uniqueDisplayNameNumber) this._uniqueDisplayNameNumber=this.constructor._nextUniqueDisplayNameNumber++;return WI.UIString("Anonymous Style Sheet %d").format(this._uniqueDisplayNameNumber);} get startLineNumber() {return this._startLineNumber;} get startColumnNumber() {return this._startColumnNumber;} hasInfo() {return this._hasInfo;} isInspectorStyleSheet() {return this._origin===WI.CSSStyleSheet.Type.Inspector;} isInlineStyleTag() {return this._inlineStyleTag;} isInlineStyleAttributeStyleSheet() {return this._inlineStyleAttribute;} markAsInlineStyleAttributeStyleSheet() {this._inlineStyleAttribute=true;} offsetSourceCodeLocation(sourceCodeLocation) {if(!sourceCodeLocation) return null;if(!this._hasInfo) return sourceCodeLocation;let sourceCode=sourceCodeLocation.sourceCode;let lineNumber=this._startLineNumber+sourceCodeLocation.lineNumber;let columnNumber=this._startColumnNumber+sourceCodeLocation.columnNumber;return sourceCode.createSourceCodeLocation(lineNumber,columnNumber);} updateInfo(url,parentFrame,origin,inlineStyle,startLineNumber,startColumnNumber) {this._hasInfo=true;this._url=url||null;this._urlComponents=undefined;this._parentFrame=parentFrame||null;this._origin=origin;this._inlineStyleTag=inlineStyle;this._startLineNumber=startLineNumber;this._startColumnNumber=startColumnNumber;} get revisionForRequestedContent() {return this.currentRevision;} handleCurrentRevisionContentChange() {if(!this._id) return;let target=WI.assumingMainTarget();function contentDidChange(error) {if(error) return;if(target.hasCommand("DOM.markUndoableState")) target.DOMAgent.markUndoableState();this.dispatchEventToListeners(WI.CSSStyleSheet.Event.ContentDidChange);} this._ignoreNextContentDidChangeNotification=true;target.CSSAgent.setStyleSheetText(this._id,this.currentRevision.content,contentDidChange.bind(this));} requestContentFromBackend() {let specialContentPromise=WI.SourceCode.generateSpecialContentForURL(this._url);if(specialContentPromise) return specialContentPromise;if(!this._id){ return Promise.reject(new Error("There is no identifier to request content with."));} let target=WI.assumingMainTarget();return target.CSSAgent.getStyleSheetText(this._id);} noteContentDidChange() {if(this._ignoreNextContentDidChangeNotification){this._ignoreNextContentDidChangeNotification=false;return false;} this.markContentAsStale();this.dispatchEventToListeners(WI.CSSStyleSheet.Event.ContentDidChange);return true;}};WI.CSSStyleSheet._nextUniqueDisplayNameNumber=1;WI.CSSStyleSheet.Event={ContentDidChange:"css-style-sheet-content-did-change"};WI.CSSStyleSheet.Type={Author:"css-style-sheet-type-author",User:"css-style-sheet-type-user",UserAgent:"css-style-sheet-type-user-agent",Inspector:"css-style-sheet-type-inspector"};WI.CallFrame=class CallFrame {constructor(target,{id,sourceCodeLocation,functionName,thisObject,scopeChain,nativeCode,programCode,isTailDeleted,blackboxed}={}) {this._isConsoleEvaluation=sourceCodeLocation&&isWebInspectorConsoleEvaluationScript(sourceCodeLocation.sourceCode.sourceURL);if(this._isConsoleEvaluation){functionName=WI.UIString("Console Evaluation");programCode=true;} this._target=target;this._id=id||null;this._sourceCodeLocation=sourceCodeLocation||null;this._functionName=functionName||"";this._thisObject=thisObject||null;this._scopeChain=scopeChain||[];this._nativeCode=nativeCode||false;this._programCode=programCode||false;this._isTailDeleted=isTailDeleted||false;this._blackboxed=blackboxed||false;} get target(){return this._target;} get id(){return this._id;} get sourceCodeLocation(){return this._sourceCodeLocation;} get functionName(){return this._functionName;} get nativeCode(){return this._nativeCode;} get programCode(){return this._programCode;} get thisObject(){return this._thisObject;} get scopeChain(){return this._scopeChain;} get isTailDeleted(){return this._isTailDeleted;} get blackboxed(){return this._blackboxed;} get isConsoleEvaluation(){return this._isConsoleEvaluation;} get displayName() {return this._functionName||WI.UIString("(anonymous function)");} isEqual(other) {if(!other) return false;if(this._sourceCodeLocation&&other._sourceCodeLocation) return this._sourceCodeLocation.isEqual(other._sourceCodeLocation);return false;} saveIdentityToCookie() { } collectScopeChainVariableNames(callback) {let result=["this","__proto__"];var pendingRequests=this._scopeChain.length;function propertiesCollected(properties) {for(var i=0;properties&&i=0;--i){let scope=scopes[i];markAsBaseIfNeeded(scope);if(shouldMergeClosureScopes(scope,lastScope,lastMerge)){let type=WI.ScopeChainNode.Type.Closure;let objects=lastScope.objects.concat(scope.objects);let merged=new WI.ScopeChainNode(type,objects,scope.name,scope.location);merged.__baseClosureScope=true;mergedScopes.pop();mergedScopes.push(merged);lastMerge=merged;lastScope=null;}else{mergedScopes.push(scope);lastMerge=null;lastScope=scope;}} mergedScopes=mergedScopes.reverse();for(let scope of mergedScopes){if(scope.type===WI.ScopeChainNode.Type.Closure){if(scope.name===this._functionName) scope.convertToLocalScope();break;}} return mergedScopes;} static functionNameFromPayload(payload) {let functionName=payload.functionName;if(functionName==="global code") return WI.UIString("Global Code");if(functionName==="eval code") return WI.UIString("Eval Code");if(functionName==="module code") return WI.UIString("Module Code");return functionName;} static programCodeFromPayload(payload) {return payload.functionName.endsWith(" code");} static fromDebuggerPayload(target,payload,scopeChain,sourceCodeLocation) {return new WI.CallFrame(target,{id:payload.callFrameId,sourceCodeLocation,functionName:WI.CallFrame.functionNameFromPayload(payload),thisObject:WI.RemoteObject.fromPayload(payload.this,target),scopeChain,programCode:WI.CallFrame.programCodeFromPayload(payload),isTailDeleted:payload.isTailDeleted,blackboxed:sourceCodeLocation&&!!WI.debuggerManager.blackboxDataForSourceCode(sourceCodeLocation.sourceCode),});} static fromPayload(target,payload) {let{url,scriptId}=payload;let nativeCode=false;let sourceCodeLocation=null;if(url==="[native code]"){nativeCode=true;url=null;}else if(url||scriptId){let sourceCode=null;if(scriptId){sourceCode=WI.debuggerManager.scriptForIdentifier(scriptId,target);if(sourceCode&&sourceCode.resource) sourceCode=sourceCode.resource;} if(!sourceCode) sourceCode=WI.networkManager.resourcesForURL(url).firstValue;if(!sourceCode) sourceCode=WI.debuggerManager.scriptsForURL(url,target)[0];if(sourceCode){let lineNumber=payload.lineNumber-1;sourceCodeLocation=sourceCode.createLazySourceCodeLocation(lineNumber,payload.columnNumber);}else{nativeCode=true;url=null;}} return new WI.CallFrame(target,{sourceCodeLocation,functionName:WI.CallFrame.functionNameFromPayload(payload),nativeCode,programCode:WI.CallFrame.programCodeFromPayload(payload),blackboxed:sourceCodeLocation&&!!WI.debuggerManager.blackboxDataForSourceCode(sourceCodeLocation.sourceCode),});}};WI.CallingContextTree=class CallingContextTree {constructor(type) {this._type=type||WI.CallingContextTree.Type.TopDown;this.reset();} get type(){return this._type;} get totalNumberOfSamples(){return this._totalNumberOfSamples;} reset() {this._root=new WI.CallingContextTreeNode(-1,-1,-1,"",null);this._totalNumberOfSamples=0;} totalDurationInTimeRange(startTime,endTime) {return this._root.filteredTimestampsAndDuration(startTime,endTime).duration;} updateTreeWithStackTrace({timestamp,stackFrames},duration) {this._totalNumberOfSamples++;let node=this._root;node.addTimestampAndExpressionLocation(timestamp,duration,null);switch(this._type){case WI.CallingContextTree.Type.TopDown:for(let i=stackFrames.length;i--;){let stackFrame=stackFrames[i];node=node.findOrMakeChild(stackFrame);node.addTimestampAndExpressionLocation(timestamp,duration,stackFrame.expressionLocation||null,i===0);} break;case WI.CallingContextTree.Type.BottomUp:for(let i=0;i{if(child.hasStackTraceInTimeRange(startTime,endTime)) roots.push(child.toCPUProfileNode(numSamplesInTimeRange,startTime,endTime));});cpuProfile.rootNodes=roots;return cpuProfile;} forEachChild(callback) {this._root.forEachChild(callback);} forEachNode(callback) {this._root.forEachNode(callback);} static __test_makeTreeFromProtocolMessageObject(messageObject) {let tree=new WI.CallingContextTree;let stackTraces=messageObject.params.samples.stackTraces;for(let i=0;iendTime) return false;let timestamps=this._timestamps;let length=timestamps.length;if(!length) return false;let index=timestamps.lowerBound(startTime);if(index===length) return false;let hasTimestampInRange=timestamps[index]<=endTime;return hasTimestampInRange;} filteredTimestampsAndDuration(startTime,endTime) {let lowerIndex=this._timestamps.lowerBound(startTime);let upperIndex=this._timestamps.upperBound(endTime);let totalDuration=0;for(let i=lowerIndex;i{if(child.hasStackTraceInTimeRange(startTime,endTime)) children.push(child.toCPUProfileNode(numSamples,startTime,endTime));});let cpuProfileNode={id:this._uid,functionName:this._name,url:this._url,lineNumber:this._line,columnNumber:this._column,children:children};let timestamps=[];let frameStartTime=Number.MAX_VALUE;let frameEndTime=Number.MIN_VALUE;for(let i=0;i{child.__test_buildLeafLinkedLists(linkedListNode,result);});}else{result.push(linkedListNode);}}};WI.CallingContextTreeNode.__uid=0;WI.Canvas=class Canvas extends WI.Object {constructor(target,identifier,contextType,size,{domNode,cssCanvasName,contextAttributes,memoryCost,stackTrace}={}) {super();this._target=target;this._identifier=identifier;this._contextType=contextType;this._size=size||null;this._domNode=domNode||null;this._cssCanvasName=cssCanvasName||"";this._contextAttributes=contextAttributes||{};this._extensions=new Set;this._memoryCost=memoryCost||NaN;this._stackTrace=stackTrace||null;this._clientNodes=null;this._shaderProgramCollection=new WI.ShaderProgramCollection;this._recordingCollection=new WI.RecordingCollection;this._nextShaderProgramDisplayNumber=null;this._requestNodePromise=null;this._recordingState=WI.Canvas.RecordingState.Inactive;this._recordingFrames=[];this._recordingBufferUsed=0;if(!InspectorBackend.hasEvent("Canvas.canvasSizeChanged")){this.requestNode().then((node)=>{if(node){node.addEventListener(WI.DOMNode.Event.AttributeModified,this._calculateSize,this);node.addEventListener(WI.DOMNode.Event.AttributeRemoved,this._calculateSize,this);}});this._calculateSize();}} static fromPayload(target,payload) {let contextType=null;switch(payload.contextType){case InspectorBackend.Enum.Canvas.ContextType.Canvas2D:contextType=WI.Canvas.ContextType.Canvas2D;break;case InspectorBackend.Enum.Canvas.ContextType.OffscreenCanvas2D:contextType=WI.Canvas.ContextType.OffscreenCanvas2D;break;case InspectorBackend.Enum.Canvas.ContextType.BitmapRenderer:contextType=WI.Canvas.ContextType.BitmapRenderer;break;case InspectorBackend.Enum.Canvas.ContextType.OffscreenBitmapRenderer:contextType=WI.Canvas.ContextType.OffscreenBitmapRenderer;break;case InspectorBackend.Enum.Canvas.ContextType.WebGL:contextType=WI.Canvas.ContextType.WebGL;break;case InspectorBackend.Enum.Canvas.ContextType.OffscreenWebGL:contextType=WI.Canvas.ContextType.OffscreenWebGL;break;case InspectorBackend.Enum.Canvas.ContextType.WebGL2:contextType=WI.Canvas.ContextType.WebGL2;break;case InspectorBackend.Enum.Canvas.ContextType.OffscreenWebGL2:contextType=WI.Canvas.ContextType.OffscreenWebGL2;break;case InspectorBackend.Enum.Canvas.ContextType.WebGPU:contextType=WI.Canvas.ContextType.WebGPU;break;case InspectorBackend.Enum.Canvas.ContextType.WebMetal:contextType=WI.Canvas.ContextType.WebMetal;break;default:console.error("Invalid canvas context type",payload.contextType);} let size=("width"in payload&&"height"in payload)?new WI.Size(payload.width,payload.height):null;if(payload.backtrace) payload.stackTrace={callFrames:payload.backtrace};return new WI.Canvas(target,payload.canvasId,contextType,size,{height:payload.height,domNode:payload.nodeId?WI.domManager.nodeForId(payload.nodeId):null,cssCanvasName:payload.cssCanvasName,contextAttributes:payload.contextAttributes,memoryCost:payload.memoryCost,stackTrace:WI.StackTrace.fromPayload(target,payload.stackTrace),});} static displayNameForContextType(contextType) {switch(contextType){case WI.Canvas.ContextType.Canvas2D:return WI.UIString("2D","2D @ Canvas Context Type","2D is a type of rendering context associated with a element.");case WI.Canvas.ContextType.OffscreenCanvas2D:return WI.UIString("Offscreen2D","2D @ Offscreen Canvas Context Type","2D is a type of rendering context associated with a OffscreenCanvas.");case WI.Canvas.ContextType.BitmapRenderer:return WI.UIString("Bitmap Renderer","Bitmap Renderer @ Canvas Context Type","Bitmap Renderer is a type of rendering context associated with a element.");case WI.Canvas.ContextType.OffscreenBitmapRenderer:return WI.UIString("Bitmap Renderer (Offscreen)","Bitmap Renderer @ Offscreen Canvas Context Type","Bitmap Renderer is a type of rendering context associated with a OffscreenCanvas.");case WI.Canvas.ContextType.WebGL:return WI.UIString("WebGL","WebGL @ Canvas Context Type","WebGL is a type of rendering context associated with a element.");case WI.Canvas.ContextType.OffscreenWebGL:return WI.UIString("WebGL (Offscreen)","WebGL @ Offscreen Canvas Context Type","WebGL is a type of rendering context associated with a OffscreenCanvas.");case WI.Canvas.ContextType.WebGL2:return WI.UIString("WebGL2","WebGL2 @ Canvas Context Type","WebGL2 is a type of rendering context associated with a element.");case WI.Canvas.ContextType.OffscreenWebGL2:return WI.UIString("WebGL2 (Offscreen)","WebGL2 @ Offscreen Canvas Context Type","WebGL2 is a type of rendering context associated with a OffscreenCanvas.");case WI.Canvas.ContextType.WebGPU:return WI.UIString("WebGPU","WebGPU @ Canvas Context Type","WebGPU is a type of rendering context associated with a element.");case WI.Canvas.ContextType.WebMetal:return WI.UIString("WebMetal","WebMetal @ Canvas Context Type","WebMetal is a type of rendering context associated with a element.");} return null;} static displayNameForColorSpace(colorSpace) {switch(colorSpace){case WI.Canvas.ColorSpace.SRGB:return WI.UIString("sRGB","sRGB @ Color Space","Label for a canvas that uses the sRGB color space.");case WI.Canvas.ColorSpace.DisplayP3:return WI.UIString("Display P3","Display P3 @ Color Space","Label for a canvas that uses the Display P3 color space.");} return null;} static resetUniqueDisplayNameNumbers() {Canvas._nextContextUniqueDisplayNameNumber=1;Canvas._nextDeviceUniqueDisplayNameNumber=1;} static supportsRequestContentForContextType(contextType) {switch(contextType){case Canvas.ContextType.WebGPU:case Canvas.ContextType.WebMetal:return false;} return true;} get target(){return this._target;} get identifier(){return this._identifier;} get contextType(){return this._contextType;} get size(){return this._size;} get memoryCost(){return this._memoryCost;} get cssCanvasName(){return this._cssCanvasName;} get contextAttributes(){return this._contextAttributes;} get extensions(){return this._extensions;} get stackTrace(){return this._stackTrace;} get shaderProgramCollection(){return this._shaderProgramCollection;} get recordingCollection(){return this._recordingCollection;} get recordingFrameCount(){return this._recordingFrames.length;} get recordingBufferUsed(){return this._recordingBufferUsed;} get supportsRecording() {switch(this._contextType){case WI.Canvas.ContextType.Canvas2D:case WI.Canvas.ContextType.OffscreenCanvas2D:case WI.Canvas.ContextType.BitmapRenderer:case WI.Canvas.ContextType.OffscreenBitmapRenderer:case WI.Canvas.ContextType.WebGL:case WI.Canvas.ContextType.OffscreenWebGL:case WI.Canvas.ContextType.WebGL2:case WI.Canvas.ContextType.OffscreenWebGL2:return true;case WI.Canvas.ContextType.WebGPU:case WI.Canvas.ContextType.WebMetal:return false;} return false;} get recordingActive() {return this._recordingState!==WI.Canvas.RecordingState.Inactive;} get displayName() {if(this._cssCanvasName) return WI.UIString("CSS canvas \u201C%s\u201D").format(this._cssCanvasName);if(this._domNode){let idSelector=this._domNode.escapedIdSelector;if(idSelector) return WI.UIString("Canvas %s").format(idSelector);} if(this._contextType===Canvas.ContextType.WebGPU){if(!this._uniqueDisplayNameNumber) this._uniqueDisplayNameNumber=Canvas._nextDeviceUniqueDisplayNameNumber++;return WI.UIString("Device %d").format(this._uniqueDisplayNameNumber);} if(!this._uniqueDisplayNameNumber) this._uniqueDisplayNameNumber=Canvas._nextContextUniqueDisplayNameNumber++;return WI.UIString("Canvas %d").format(this._uniqueDisplayNameNumber);} get is2D() {return this._contextType===Canvas.ContextType.Canvas2D||this._contextType===Canvas.ContextType.OffscreenCanvas2D;} get isBitmapRender() {return this._contextType===Canvas.ContextType.BitmapRenderer||this._contextType===Canvas.ContextType.OffscreenBitmapRenderer;} get isWebGL() {return this._contextType===Canvas.ContextType.WebGL||this._contextType===Canvas.ContextType.OffscreenWebGL;} get isWebGL2() {return this._contextType===Canvas.ContextType.WebGL2||this._contextType===Canvas.ContextType.OffscreenWebGL2;} requestNode() {if(!this._requestNodePromise){this._requestNodePromise=new Promise((resolve,reject)=>{WI.domManager.ensureDocument();if(!this._target.hasCommand("Canvas.requestNode")){resolve(null);return;} this._target.CanvasAgent.requestNode(this._identifier,(error,nodeId)=>{if(error){resolve(null);return;} this._domNode=WI.domManager.nodeForId(nodeId);if(!this._domNode){resolve(null);return;} resolve(this._domNode);});});} return this._requestNodePromise;} requestContent() {if(!Canvas.supportsRequestContentForContextType(this._contextType)) return Promise.resolve(null);return this._target.CanvasAgent.requestContent(this._identifier).then((result)=>result.content).catch((error)=>console.error(error));} requestClientNodes(callback) {if(this._clientNodes){callback(this._clientNodes);return;} WI.domManager.ensureDocument();let wrappedCallback=(error,clientNodeIds)=>{if(error){callback([]);return;} clientNodeIds=Array.isArray(clientNodeIds)?clientNodeIds:[];this._clientNodes=clientNodeIds.map((clientNodeId)=>WI.domManager.nodeForId(clientNodeId));callback(this._clientNodes);};if(this._target.hasCommand("Canvas.requestClientNodes")){this._target.CanvasAgent.requestClientNodes(this._identifier,wrappedCallback);return;} if(this._target.hasCommand("Canvas.requestCSSCanvasClientNodes")){this._target.CanvasAgent.requestCSSCanvasClientNodes(this._identifier,wrappedCallback);return;} wrappedCallback(null,[]);} startRecording(singleFrame) {let handleStartRecording=(error)=>{if(error){console.error(error);return;} this._recordingState=WI.Canvas.RecordingState.ActiveFrontend; if(this._target.hasEvent("Canvas.recordingStarted")) return;this._recordingFrames=[];this._recordingBufferUsed=0;this.dispatchEventToListeners(WI.Canvas.Event.RecordingStarted);};if(this._target.hasCommand("Canvas.startRecording","singleFrame")){this._target.CanvasAgent.startRecording(this._identifier,singleFrame,handleStartRecording);return;} if(singleFrame){const frameCount=1;this._target.CanvasAgent.startRecording(this._identifier,frameCount,handleStartRecording);}else this._target.CanvasAgent.startRecording(this._identifier,handleStartRecording);} stopRecording() {this._target.CanvasAgent.stopRecording(this._identifier);} saveIdentityToCookie(cookie) {if(this._cssCanvasName) cookie[WI.Canvas.CSSCanvasNameCookieKey]=this._cssCanvasName;else if(this._domNode) cookie[WI.Canvas.NodePathCookieKey]=this._domNode.path;} sizeChanged(size) {if(this._size?.equals(size)) return;this._size=size;this.dispatchEventToListeners(WI.Canvas.Event.SizeChanged);} memoryChanged(memoryCost) {if(memoryCost===this._memoryCost) return;this._memoryCost=memoryCost;this.dispatchEventToListeners(WI.Canvas.Event.MemoryChanged);} enableExtension(extension) {this._extensions.add(extension);this.dispatchEventToListeners(WI.Canvas.Event.ExtensionEnabled,{extension});} clientNodesChanged() {this._clientNodes=null;this.dispatchEventToListeners(Canvas.Event.ClientNodesChanged);} recordingStarted(initiator) {if(initiator===InspectorBackend.Enum.Recording.Initiator.Console) this._recordingState=WI.Canvas.RecordingState.ActiveConsole;else if(initiator===InspectorBackend.Enum.Recording.Initiator.AutoCapture) this._recordingState=WI.Canvas.RecordingState.ActiveAutoCapture;else{this._recordingState=WI.Canvas.RecordingState.ActiveFrontend;} this._recordingFrames=[];this._recordingBufferUsed=0;this.dispatchEventToListeners(WI.Canvas.Event.RecordingStarted);} recordingProgress(framesPayload,bufferUsed) {this._recordingFrames.pushAll(framesPayload.map(WI.RecordingFrame.fromPayload));this._recordingBufferUsed=bufferUsed;this.dispatchEventToListeners(WI.Canvas.Event.RecordingProgress);} recordingFinished(recordingPayload) {let initiatedByUser=this._recordingState===WI.Canvas.RecordingState.ActiveFrontend; if(!initiatedByUser&&!InspectorBackend.hasEvent("Canvas.recordingStarted")) initiatedByUser=!!this.recordingActive;let recording=recordingPayload?WI.Recording.fromPayload(recordingPayload,this._recordingFrames):null;if(recording){recording.source=this;recording.createDisplayName(recordingPayload.name);this._recordingCollection.add(recording);} this._recordingState=WI.Canvas.RecordingState.Inactive;this._recordingFrames=[];this._recordingBufferUsed=0;this.dispatchEventToListeners(WI.Canvas.Event.RecordingStopped,{recording,initiatedByUser});} nextShaderProgramDisplayNumberForProgramType(programType) {if(!this._nextShaderProgramDisplayNumber) this._nextShaderProgramDisplayNumber={};this._nextShaderProgramDisplayNumber[programType]=(this._nextShaderProgramDisplayNumber[programType]||0)+1;return this._nextShaderProgramDisplayNumber[programType];} async _calculateSize() {let remoteObject=await WI.RemoteObject.resolveCanvasContext(this);if(!remoteObject) return;function inspectedPage_context_getCanvasSize(){return{width:this.canvas.width,height:this.canvas.height,};} let size=await remoteObject.callFunctionJSON(inspectedPage_context_getCanvasSize);remoteObject.release();this.sizeChanged(WI.Size.fromJSON(size));}};WI.Canvas._nextContextUniqueDisplayNameNumber=1;WI.Canvas._nextDeviceUniqueDisplayNameNumber=1;WI.Canvas.FrameURLCookieKey="canvas-frame-url";WI.Canvas.CSSCanvasNameCookieKey="canvas-css-canvas-name";WI.Canvas.ContextType={Canvas2D:"canvas-2d",OffscreenCanvas2D:"offscreen-canvas-2d",BitmapRenderer:"bitmaprenderer",OffscreenBitmapRenderer:"offscreen-bitmaprenderer",WebGL:"webgl",OffscreenWebGL:"offscreen-webgl",WebGL2:"webgl2",OffscreenWebGL2:"offscreen-webgl2",WebGPU:"webgpu",WebMetal:"webmetal",};WI.Canvas.ColorSpace={SRGB:"srgb",DisplayP3:"display-p3",};WI.Canvas.RecordingState={Inactive:"canvas-recording-state-inactive",ActiveFrontend:"canvas-recording-state-active-frontend",ActiveConsole:"canvas-recording-state-active-console",ActiveAutoCapture:"canvas-recording-state-active-auto-capture",};WI.Canvas.Event={SizeChanged:"canvas-size-changed",MemoryChanged:"canvas-memory-changed",ExtensionEnabled:"canvas-extension-enabled",ClientNodesChanged:"canvas-client-nodes-changed",RecordingStarted:"canvas-recording-started",RecordingProgress:"canvas-recording-progress",RecordingStopped:"canvas-recording-stopped",};WI.CollectionEntry=class CollectionEntry {constructor(key,value) {this._key=key;this._value=value;} static fromPayload(payload,target) {if(payload.key) payload.key=WI.RemoteObject.fromPayload(payload.key,target);if(payload.value) payload.value=WI.RemoteObject.fromPayload(payload.value,target);return new WI.CollectionEntry(payload.key,payload.value);} get key(){return this._key;} get value(){return this._value;}};WI.CollectionEntryPreview=class CollectionEntryPreview {constructor(keyPreview,valuePreview) {this._key=keyPreview;this._value=valuePreview;} static fromPayload(payload) {if(payload.key) payload.key=WI.ObjectPreview.fromPayload(payload.key);if(payload.value) payload.value=WI.ObjectPreview.fromPayload(payload.value);return new WI.CollectionEntryPreview(payload.key,payload.value);} get keyPreview(){return this._key;} get valuePreview(){return this._value;}};WI.FrameCollection=class FrameCollection extends WI.Collection { get displayName() {return WI.UIString("Frames");} objectIsRequiredType(object) {return object instanceof WI.Frame;}};WI.ScriptCollection=class ScriptCollection extends WI.Collection { get displayName() {return WI.UIString("Scripts");} objectIsRequiredType(object) {return object instanceof WI.Script;}};WI.CSSStyleSheetCollection=class CSSStyleSheetCollection extends WI.Collection { get displayName() {return WI.UIString("Style Sheets");} objectIsRequiredType(object) {return object instanceof WI.CSSStyleSheet;}};WI.CanvasCollection=class CanvasCollection extends WI.Collection { get displayName() {return WI.UIString("Canvases");} objectIsRequiredType(object) {return object instanceof WI.Canvas;}};WI.ShaderProgramCollection=class ShaderProgramCollection extends WI.Collection { get displayName() {return WI.UIString("Shader Programs");} objectIsRequiredType(object) {return object instanceof WI.ShaderProgram;}};WI.RecordingCollection=class RecordingCollection extends WI.Collection { get displayName() {return WI.UIString("Recordings");} objectIsRequiredType(object) {return object instanceof WI.Recording;}};WI.Color=class Color {constructor(format,components,gamut) {this.format=format;this._gamut=gamut||WI.Color.Gamut.SRGB;this.alpha=components.length===4?components[3]:1;this._rgb=null;this._normalizedRGB=null;this._hsl=null;if(format===WI.Color.Format.HSL||format===WI.Color.Format.HSLA) this._hsl=components.slice(0,3);else if(format===WI.Color.Format.ColorFunction) this._normalizedRGB=components.slice(0,3);else this._rgb=components.slice(0,3);this.valid=!components.some(isNaN);} static fromString(colorString) {const matchRegExp=/^(?:#(?[0-9a-f]{3,8})|rgba?\((?[^)]+)\)|(?\w+)|color\((?[^)]+)\)|hsla?\((?[^)]+)\))$/i;let match=colorString.match(matchRegExp);if(!match) return null;if(match.groups.hex){let hex=match.groups.hex.toUpperCase();switch(hex.length){case 3:return new WI.Color(WI.Color.Format.ShortHEX,[parseInt(hex.charAt(0)+hex.charAt(0),16),parseInt(hex.charAt(1)+hex.charAt(1),16),parseInt(hex.charAt(2)+hex.charAt(2),16),1]);case 6:return new WI.Color(WI.Color.Format.HEX,[parseInt(hex.substring(0,2),16),parseInt(hex.substring(2,4),16),parseInt(hex.substring(4,6),16),1]);case 4:return new WI.Color(WI.Color.Format.ShortHEXAlpha,[parseInt(hex.charAt(0)+hex.charAt(0),16),parseInt(hex.charAt(1)+hex.charAt(1),16),parseInt(hex.charAt(2)+hex.charAt(2),16),parseInt(hex.charAt(3)+hex.charAt(3),16)/255]);case 8:return new WI.Color(WI.Color.Format.HEXAlpha,[parseInt(hex.substring(0,2),16),parseInt(hex.substring(2,4),16),parseInt(hex.substring(4,6),16),parseInt(hex.substring(6,8),16)/255]);} return null;} if(match.groups.keyword){let keyword=match.groups.keyword.toLowerCase();if(!WI.Color.Keywords.hasOwnProperty(keyword)) return null;let color=new WI.Color(WI.Color.Format.Keyword,WI.Color.Keywords[keyword].slice());color.keyword=keyword;color.original=colorString;return color;} function splitFunctionString(string){return string.trim().replace(/(\s*(,|\/)\s*|\s+)/g,"|").split("|");} function parseFunctionAlpha(alpha){let value=parseFloat(alpha);if(alpha.includes("%")) value/=100;return Number.constrain(value,0,1);} if(match.groups.rgb){let rgb=splitFunctionString(match.groups.rgb);if(rgb.length!==3&&rgb.length!==4) return null;function parseFunctionComponent(component){let value=parseFloat(component);if(component.includes("%")) value=value*255/100;return Number.constrain(value,0,255);} let alpha=1;if(rgb.length===4) alpha=parseFunctionAlpha(rgb[3]);return new WI.Color(rgb.length===4?WI.Color.Format.RGBA:WI.Color.Format.RGB,[parseFunctionComponent(rgb[0]),parseFunctionComponent(rgb[1]),parseFunctionComponent(rgb[2]),alpha,]);} if(match.groups.hsl){let hsl=splitFunctionString(match.groups.hsl);if(hsl.length!==3&&hsl.length!==4) return null;let alpha=1;if(hsl.length===4) alpha=parseFunctionAlpha(hsl[3]);function parseHueComponent(hue){let value=parseFloat(hue);if(/(\b|\d)rad\b/.test(hue)) value=value*180/Math.PI;else if(/(\b|\d)grad\b/.test(hue)) value=value*360/400;else if(/(\b|\d)turn\b/.test(hue)) value=value*360;return Number.constrain(value,0,360);} function parsePercentageComponent(component){let value=parseFloat(component);return Number.constrain(value,0,100);} return new WI.Color(hsl.length===4?WI.Color.Format.HSLA:WI.Color.Format.HSL,[parseHueComponent(hsl[0]),parsePercentageComponent(hsl[1]),parsePercentageComponent(hsl[2]),alpha,]);} if(match.groups.color){let colorString=match.groups.color.trim();let components=splitFunctionString(colorString);if(components.length!==4&&components.length!==5) return null;let gamut=components[0].toLowerCase();if(!Object.values(WI.Color.Gamut).includes(gamut)) return null;let alpha=1;if(components.length===5) alpha=parseFunctionAlpha(components[4]);function parseFunctionComponent(component){let value=parseFloat(component);return Number.constrain(value,0,1);} return new WI.Color(WI.Color.Format.ColorFunction,[parseFunctionComponent(components[1]),parseFunctionComponent(components[2]),parseFunctionComponent(components[3]),alpha,],gamut);} return null;} static fromStringBestMatchingSuggestedFormatAndGamut(colorString,{suggestedFormat,suggestedGamut,forceSuggestedFormatAndGamut}={}) {let newColor=WI.Color.fromString(colorString);if(forceSuggestedFormatAndGamut){newColor.format=suggestedFormat;newColor.gamut=suggestedGamut;return newColor;} if(suggestedGamut===WI.Color.Gamut.DisplayP3&&newColor.gamut!==WI.Color.Gamut.DisplayP3) newColor.gamut=WI.Color.Gamut.DisplayP3;else if(suggestedGamut!==WI.Color.Gamut.DisplayP3&&newColor.gamut===WI.Color.Gamut.DisplayP3&&!newColor.isOutsideSRGB()) newColor.gamut=WI.Color.Gamut.SRGB;if(newColor.gamut!==WI.Color.Gamut.SRGB) return newColor; switch(suggestedFormat){case WI.Color.Format.Original:break;case WI.Color.Format.Keyword:break;case WI.Color.Format.HEX:newColor.format=newColor.simple?WI.Color.Format.HEX:WI.Color.Format.HEXAlpha;break;case WI.Color.Format.ShortHEX:if(newColor.canBeSerializedAsShortHEX()) newColor.format=newColor.simple?WI.Color.Format.ShortHEX:WI.Color.Format.ShortHEXAlpha;else newColor.format=newColor.simple?WI.Color.Format.HEX:WI.Color.Format.HEXAlpha;break;case WI.Color.Format.ShortHEXAlpha:newColor.format=newColor.canBeSerializedAsShortHEX()?WI.Color.Format.ShortHEXAlpha:WI.Color.Format.HEXAlpha;break;case WI.Color.Format.RGB:newColor.format=newColor.simple?WI.Color.Format.RGB:WI.Color.Format.RGBA;break;case WI.Color.Format.HSL:newColor.format=newColor.simple?WI.Color.Format.HSL:WI.Color.Format.HSLA;break;case WI.Color.Format.HEXAlpha:case WI.Color.Format.RGBA:case WI.Color.Format.HSLA:case WI.Color.Format.ColorFunction:newColor.format=suggestedFormat;break;default:break;} return newColor;} static rgb2hsl(r,g,b) {r=WI.Color._eightBitChannel(r)/255;g=WI.Color._eightBitChannel(g)/255;b=WI.Color._eightBitChannel(b)/255;let min=Math.min(r,g,b);let max=Math.max(r,g,b);let delta=max-min;let h=0;let s=0;let l=(max+min)/2;if(delta===0) h=0;else if(max===r) h=(60*((g-b)/delta))%360;else if(max===g) h=60*((b-r)/delta)+120;else if(max===b) h=60*((r-g)/delta)+240;if(h<0) h+=360; if(delta===0) s=0;else s=delta/(1-Math.abs((2*l)-1));return[h,s*100,l*100,];} static hsl2rgb(h,s,l) {h=Number.constrain(h,0,360)%360;s=Number.constrain(s,0,100)/100;l=Number.constrain(l,0,100)/100;let c=(1-Math.abs((2*l)-1))*s;let x=c*(1-Math.abs(((h/60)%2)-1));let m=l-(c/2);let r=0;let g=0;let b=0;if(h<60){r=c;g=x;}else if(h<120){r=x;g=c;}else if(h<180){g=c;b=x;}else if(h<240){g=x;b=c;}else if(h<300){r=x;b=c;}else if(h<360){r=c;b=x;} return[(r+m)*255,(g+m)*255,(b+m)*255,];} static hsv2hsl(h,s,v) {h=Number.constrain(h,0,360);s=Number.constrain(s,0,100)/100;v=Number.constrain(v,0,100)/100;let l=v-v*s/2;let saturation;if(l===0||l===1) saturation=0;else saturation=(v-l)/Math.min(l,1-l);return[h,saturation*100,l*100];} static rgb2hsv(r,g,b) {r=Number.constrain(r,0,1);g=Number.constrain(g,0,1);b=Number.constrain(b,0,1);let max=Math.max(r,g,b);let min=Math.min(r,g,b);let h=0;let delta=max-min;let s=max===0?0:delta/max;let v=max;if(max===min) h=0;else{switch(max){case r:h=((g-b)/delta)+((gx.maxDecimals(4));} static srgbToDisplayP3(r,g,b) {r=Number.constrain(r,0,1);g=Number.constrain(g,0,1);b=Number.constrain(b,0,1);let linearSRGB=WI.Color._toLinearLight([r,g,b]); const linearSRGBtoXYZMatrix=[[0.4124564,0.3575761,0.1804375],[0.2126729,0.7151522,0.0721750],[0.0193339,0.1191920,0.9503041],];let xyz=Math.multiplyMatrixByVector(linearSRGBtoXYZMatrix,linearSRGB);const xyzToLinearP3Matrix=[[2.493496911941425,-0.9313836179191239,-0.40271078445071684],[-0.8294889695615747,1.7626640603183463,0.023624685841943577],[0.03584583024378447,-0.07617238926804182,0.9568845240076872],];let linearP3=Math.multiplyMatrixByVector(xyzToLinearP3Matrix,xyz);let p3=WI.Color._gammaCorrect(linearP3);return p3.map((x)=>x.maxDecimals(4));} static _toLinearLight(rgb) {return rgb.map(function(value){if(value<0.04045) return value/12.92;return Math.pow((value+0.055)/1.055,2.4);});} static _gammaCorrect(rgb) {return rgb.map(function(value){if(value>0.0031308) return 1.055*Math.pow(value,1/2.4)-0.055;return 12.92*value;});} static cmyk2rgb(c,m,y,k) {c=Number.constrain(c,0,1);m=Number.constrain(m,0,1);y=Number.constrain(y,0,1);k=Number.constrain(k,0,1);return[255*(1-c)*(1-k),255*(1-m)*(1-k),255*(1-y)*(1-k),];} static normalized2rgb(r,g,b) {return[WI.Color._eightBitChannel(r*255),WI.Color._eightBitChannel(g*255),WI.Color._eightBitChannel(b*255)];} static _eightBitChannel(value) {return Number.constrain(Math.round(value),0,255);} nextFormat(format) {format=format||this.format;switch(format){case WI.Color.Format.Original:case WI.Color.Format.HEX:case WI.Color.Format.HEXAlpha:return this.simple?WI.Color.Format.RGB:WI.Color.Format.RGBA;case WI.Color.Format.RGB:case WI.Color.Format.RGBA:return WI.Color.Format.ColorFunction;case WI.Color.Format.ColorFunction:if(this.simple) return WI.Color.Format.HSL;return WI.Color.Format.HSLA;case WI.Color.Format.HSL:case WI.Color.Format.HSLA:if(this.isKeyword()) return WI.Color.Format.Keyword;if(this.simple) return this.canBeSerializedAsShortHEX()?WI.Color.Format.ShortHEX:WI.Color.Format.HEX;return this.canBeSerializedAsShortHEX()?WI.Color.Format.ShortHEXAlpha:WI.Color.Format.HEXAlpha;case WI.Color.Format.ShortHEX:return WI.Color.Format.HEX;case WI.Color.Format.ShortHEXAlpha:return WI.Color.Format.HEXAlpha;case WI.Color.Format.Keyword:if(this.simple) return this.canBeSerializedAsShortHEX()?WI.Color.Format.ShortHEX:WI.Color.Format.HEX;return this.canBeSerializedAsShortHEX()?WI.Color.Format.ShortHEXAlpha:WI.Color.Format.HEXAlpha;default:console.error("Unknown color format.");return null;}} get simple() {return this.alpha===1;} get rgb() {if(!this._rgb){if(this._hsl) this._rgb=WI.Color.hsl2rgb(...this._hsl);else if(this._normalizedRGB) this._rgb=this._normalizedRGB.map((component)=>WI.Color._eightBitChannel(component*255));} return this._rgb;} get hsl() {if(!this._hsl) this._hsl=WI.Color.rgb2hsl(...this.rgb);return this._hsl;} get normalizedRGB() {if(!this._normalizedRGB) this._normalizedRGB=this.rgb.map((component)=>component/255);return this._normalizedRGB;} get rgba() {return[...this.rgb,this.alpha];} get hsla() {return[...this.hsl,this.alpha];} get normalizedRGBA() {return[...this.normalizedRGB,this.alpha];} get gamut() {return this._gamut;} set gamut(gamut) {if(this._gamut===WI.Color.Gamut.DisplayP3&&gamut===WI.Color.Gamut.SRGB){this._normalizedRGB=WI.Color.displayP3toSRGB(...this.normalizedRGB).map((x)=>Number.constrain(x,0,1));this._hsl=null;this._rgb=null;}else if(this._gamut===WI.Color.Gamut.SRGB&&gamut===WI.Color.Gamut.DisplayP3){this._normalizedRGB=WI.Color.srgbToDisplayP3(...this.normalizedRGB);this._hsl=null;this._rgb=null;this.format=WI.Color.Format.ColorFunction;} this._gamut=gamut;} copy() {switch(this.format){case WI.Color.Format.RGB:case WI.Color.Format.HEX:case WI.Color.Format.ShortHEX:case WI.Color.Format.HEXAlpha:case WI.Color.Format.ShortHEXAlpha:case WI.Color.Format.Keyword:case WI.Color.Format.RGBA:return new WI.Color(this.format,this.rgba,this._gamut);case WI.Color.Format.HSL:case WI.Color.Format.HSLA:return new WI.Color(this.format,this.hsla,this._gamut);case WI.Color.Format.ColorFunction:return new WI.Color(this.format,this.normalizedRGBA,this._gamut);} console.error("Invalid color format: "+this.format);} toString(format) {if(!format) format=this.format;switch(format){case WI.Color.Format.Original:return this._toOriginalString();case WI.Color.Format.RGB:return this._toRGBString();case WI.Color.Format.RGBA:return this._toRGBAString();case WI.Color.Format.ColorFunction:return this._toFunctionString();case WI.Color.Format.HSL:return this._toHSLString();case WI.Color.Format.HSLA:return this._toHSLAString();case WI.Color.Format.HEX:return this._toHEXString();case WI.Color.Format.ShortHEX:return this._toShortHEXString();case WI.Color.Format.HEXAlpha:return this._toHEXAlphaString();case WI.Color.Format.ShortHEXAlpha:return this._toShortHEXAlphaString();case WI.Color.Format.Keyword:return this._toKeywordString();} console.error("Invalid color format: "+format);return"";} toProtocol() {let[r,g,b,a]=this.rgba;return{r,g,b,a};} isKeyword() {if(this.keyword) return true;if(this._gamut!==WI.Color.Gamut.SRGB) return false;if(!this.simple) return Array.shallowEqual(this.rgba,[0,0,0,0]);return Object.keys(WI.Color.Keywords).some(key=>Array.shallowEqual(WI.Color.Keywords[key],this.rgb));} isOutsideSRGB() {if(this._gamut!==WI.Color.Gamut.DisplayP3) return false;let rgb=WI.Color.displayP3toSRGB(...this.normalizedRGB);const epsilon=(1/255)/2;return rgb.some((x)=>x<=-epsilon||x>=1+epsilon);} canBeSerializedAsShortHEX() {let rgb=this.rgb;let r=this._componentToHexValue(rgb[0]);if(r[0]!==r[1]) return false;let g=this._componentToHexValue(rgb[1]);if(g[0]!==g[1]) return false;let b=this._componentToHexValue(rgb[2]);if(b[0]!==b[1]) return false;if(!this.simple){let a=this._componentToHexValue(Math.round(this.alpha*255));if(a[0]!==a[1]) return false;} return true;} _toOriginalString() {return this.original||this._toKeywordString();} _toKeywordString() {if(this.keyword) return this.keyword;let rgba=this.rgba;if(!this.simple){if(Array.shallowEqual(rgba,[0,0,0,0])) return"transparent";return this._toRGBAString();} let keywords=WI.Color.Keywords;for(let keyword in keywords){if(!keywords.hasOwnProperty(keyword)) continue;let keywordRGB=keywords[keyword];if(keywordRGB[0]===rgba[0]&&keywordRGB[1]===rgba[1]&&keywordRGB[2]===rgba[2]) return keyword;} return this._toRGBString();} _toShortHEXString() {if(!this.simple) return this._toRGBAString();let[r,g,b]=this.rgb.map(this._componentToHexValue);if(r[0]===r[1]&&g[0]===g[1]&&b[0]===b[1]) return"#"+r[0]+g[0]+b[0];return"#"+r+g+b;} _toHEXString() {if(!this.simple) return this._toRGBAString();let[r,g,b]=this.rgb.map(this._componentToHexValue);return"#"+r+g+b;} _toShortHEXAlphaString() {let[r,g,b]=this.rgb.map(this._componentToHexValue);let a=this._componentToHexValue(Math.round(this.alpha*255));if(r[0]===r[1]&&g[0]===g[1]&&b[0]===b[1]&&a[0]===a[1]) return"#"+r[0]+g[0]+b[0]+a[0];return"#"+r+g+b+a;} _toHEXAlphaString() {let[r,g,b]=this.rgb.map(this._componentToHexValue);let a=this._componentToHexValue(Math.round(this.alpha*255));return"#"+r+g+b+a;} _toRGBString() {if(!this.simple) return this._toRGBAString();let[r,g,b]=this.rgb.map(WI.Color._eightBitChannel);return`rgb(${r}, ${g}, ${b})`;} _toRGBAString() {let[r,g,b]=this.rgb.map(WI.Color._eightBitChannel);return`rgba(${r}, ${g}, ${b}, ${this.alpha})`;} _toFunctionString() {let[r,g,b]=this.normalizedRGB.map((x)=>x.maxDecimals(4));if(this.alpha===1) return`color(${this._gamut} ${r} ${g} ${b})`;return`color(${this._gamut} ${r} ${g} ${b} / ${this.alpha})`;} _toHSLString() {if(!this.simple) return this._toHSLAString();let[h,s,l]=this.hsl.map((x)=>x.maxDecimals(2));return`hsl(${h}, ${s}%, ${l}%)`;} _toHSLAString() {let[h,s,l]=this.hsl.map((x)=>x.maxDecimals(2));return`hsla(${h}, ${s}%, ${l}%, ${this.alpha})`;} _componentToHexValue(value) {let hex=WI.Color._eightBitChannel(value).toString(16);if(hex.length===1) hex="0"+hex;return hex;}};WI.Color.Format={Original:"color-format-original",Keyword:"color-format-keyword",HEX:"color-format-hex",ShortHEX:"color-format-short-hex",HEXAlpha:"color-format-hex-alpha",ShortHEXAlpha:"color-format-short-hex-alpha",RGB:"color-format-rgb",RGBA:"color-format-rgba",HSL:"color-format-hsl",HSLA:"color-format-hsla",ColorFunction:"color-format-color-function",};WI.Color.Gamut={SRGB:"srgb",DisplayP3:"display-p3",};WI.Color.FunctionNames=new Set(["rgb","rgba","hsl","hsla","color","color-mix",]);WI.Color.Keywords={"aliceblue":[240,248,255,1],"antiquewhite":[250,235,215,1],"aqua":[0,255,255,1],"aquamarine":[127,255,212,1],"azure":[240,255,255,1],"beige":[245,245,220,1],"bisque":[255,228,196,1],"black":[0,0,0,1],"blanchedalmond":[255,235,205,1],"blue":[0,0,255,1],"blueviolet":[138,43,226,1],"brown":[165,42,42,1],"burlywood":[222,184,135,1],"cadetblue":[95,158,160,1],"chartreuse":[127,255,0,1],"chocolate":[210,105,30,1],"coral":[255,127,80,1],"cornflowerblue":[100,149,237,1],"cornsilk":[255,248,220,1],"crimson":[237,164,61,1],"cyan":[0,255,255,1],"darkblue":[0,0,139,1],"darkcyan":[0,139,139,1],"darkgoldenrod":[184,134,11,1],"darkgray":[169,169,169,1],"darkgreen":[0,100,0,1],"darkgrey":[169,169,169,1],"darkkhaki":[189,183,107,1],"darkmagenta":[139,0,139,1],"darkolivegreen":[85,107,47,1],"darkorange":[255,140,0,1],"darkorchid":[153,50,204,1],"darkred":[139,0,0,1],"darksalmon":[233,150,122,1],"darkseagreen":[143,188,143,1],"darkslateblue":[72,61,139,1],"darkslategray":[47,79,79,1],"darkslategrey":[47,79,79,1],"darkturquoise":[0,206,209,1],"darkviolet":[148,0,211,1],"deeppink":[255,20,147,1],"deepskyblue":[0,191,255,1],"dimgray":[105,105,105,1],"dimgrey":[105,105,105,1],"dodgerblue":[30,144,255,1],"firebrick":[178,34,34,1],"floralwhite":[255,250,240,1],"forestgreen":[34,139,34,1],"fuchsia":[255,0,255,1],"gainsboro":[220,220,220,1],"ghostwhite":[248,248,255,1],"gold":[255,215,0,1],"goldenrod":[218,165,32,1],"gray":[128,128,128,1],"green":[0,128,0,1],"greenyellow":[173,255,47,1],"grey":[128,128,128,1],"honeydew":[240,255,240,1],"hotpink":[255,105,180,1],"indianred":[205,92,92,1],"indigo":[75,0,130,1],"ivory":[255,255,240,1],"khaki":[240,230,140,1],"lavender":[230,230,250,1],"lavenderblush":[255,240,245,1],"lawngreen":[124,252,0,1],"lemonchiffon":[255,250,205,1],"lightblue":[173,216,230,1],"lightcoral":[240,128,128,1],"lightcyan":[224,255,255,1],"lightgoldenrodyellow":[250,250,210,1],"lightgray":[211,211,211,1],"lightgreen":[144,238,144,1],"lightgrey":[211,211,211,1],"lightpink":[255,182,193,1],"lightsalmon":[255,160,122,1],"lightseagreen":[32,178,170,1],"lightskyblue":[135,206,250,1],"lightslategray":[119,136,153,1],"lightslategrey":[119,136,153,1],"lightsteelblue":[176,196,222,1],"lightyellow":[255,255,224,1],"lime":[0,255,0,1],"limegreen":[50,205,50,1],"linen":[250,240,230,1],"magenta":[255,0,255,1],"maroon":[128,0,0,1],"mediumaquamarine":[102,205,170,1],"mediumblue":[0,0,205,1],"mediumorchid":[186,85,211,1],"mediumpurple":[147,112,219,1],"mediumseagreen":[60,179,113,1],"mediumslateblue":[123,104,238,1],"mediumspringgreen":[0,250,154,1],"mediumturquoise":[72,209,204,1],"mediumvioletred":[199,21,133,1],"midnightblue":[25,25,112,1],"mintcream":[245,255,250,1],"mistyrose":[255,228,225,1],"moccasin":[255,228,181,1],"navajowhite":[255,222,173,1],"navy":[0,0,128,1],"oldlace":[253,245,230,1],"olive":[128,128,0,1],"olivedrab":[107,142,35,1],"orange":[255,165,0,1],"orangered":[255,69,0,1],"orchid":[218,112,214,1],"palegoldenrod":[238,232,170,1],"palegreen":[152,251,152,1],"paleturquoise":[175,238,238,1],"palevioletred":[219,112,147,1],"papayawhip":[255,239,213,1],"peachpuff":[255,218,185,1],"peru":[205,133,63,1],"pink":[255,192,203,1],"plum":[221,160,221,1],"powderblue":[176,224,230,1],"purple":[128,0,128,1],"rebeccapurple":[102,51,153,1],"red":[255,0,0,1],"rosybrown":[188,143,143,1],"royalblue":[65,105,225,1],"saddlebrown":[139,69,19,1],"salmon":[250,128,114,1],"sandybrown":[244,164,96,1],"seagreen":[46,139,87,1],"seashell":[255,245,238,1],"sienna":[160,82,45,1],"silver":[192,192,192,1],"skyblue":[135,206,235,1],"slateblue":[106,90,205,1],"slategray":[112,128,144,1],"slategrey":[112,128,144,1],"snow":[255,250,250,1],"springgreen":[0,255,127,1],"steelblue":[70,130,180,1],"tan":[210,180,140,1],"teal":[0,128,128,1],"thistle":[216,191,216,1],"tomato":[255,99,71,1],"transparent":[0,0,0,0],"turquoise":[64,224,208,1],"violet":[238,130,238,1],"wheat":[245,222,179,1],"white":[255,255,255,1],"whitesmoke":[245,245,245,1],"yellow":[255,255,0,1],"yellowgreen":[154,205,50,1],};WI.ConsoleCommandResultMessage=class ConsoleCommandResult extends WI.ConsoleMessage {constructor(target,result,wasThrown,savedResultIndex,{shouldRevealConsole}={}) {let source=WI.ConsoleMessage.MessageSource.JS;let level=wasThrown?WI.ConsoleMessage.MessageLevel.Error:WI.ConsoleMessage.MessageLevel.Log;let type=WI.ConsoleMessage.MessageType.Result;super(target,source,level,"",type,undefined,undefined,undefined,0,[result],undefined,undefined);this._savedResultIndex=savedResultIndex;this._shouldRevealConsole=!!shouldRevealConsole;if(this._savedResultIndex&&this._savedResultIndex>WI.ConsoleCommandResultMessage.maximumSavedResultIndex) WI.ConsoleCommandResultMessage.maximumSavedResultIndex=this._savedResultIndex;} static clearMaximumSavedResultIndex() {WI.ConsoleCommandResultMessage.maximumSavedResultIndex=0;} get savedResultIndex() {return this._savedResultIndex;} get shouldRevealConsole() {return this._shouldRevealConsole;}};WI.ConsoleCommandResultMessage.maximumSavedResultIndex=0;WI.ConsoleSnippet=class ConsoleSnippet extends WI.LocalScript {constructor(title,source) {const target=null;const sourceURL=null;super(target,title,sourceURL,WI.Script.SourceType.Program,source,{editable:true});} static createDefaultWithTitle(title) {const source=` /* * ${WI.UIString("Console Snippets are an easy way to save and evaluate JavaScript in the Console.")} * * ${WI.UIString("As such, the contents will be run as though it was typed into the Console.")} * ${WI.UIString("This means all of the Console Command Line API is available .")} * * ${WI.UIString("Modifications are saved automatically and will apply the next time the Console Snippet is run.")} * ${WI.UIString("The contents will be preserved across Web Inspector sessions.")} * * ${WI.UIString("More information is available at .")} */ "Hello World!" `.trimStart();return new WI.ConsoleSnippet(title,source);} get title() {return this.url;} run() {WI.runtimeManager.evaluateInInspectedWindow(this.content,{objectGroup:WI.RuntimeManager.ConsoleObjectGroup,includeCommandLineAPI:true,doNotPauseOnExceptionsAndMuteConsole:true,generatePreview:true,saveResult:true,},(result,wasThrown)=>{WI.consoleLogViewController.appendImmediateExecutionWithResult(this.title,result,{addSpecialUserLogClass:true,shouldRevealConsole:true,handleClick:(event)=>{if(!WI.consoleManager.snippets.has(this)) return;const cookie=null;WI.showRepresentedObject(this,cookie,{ignoreNetworkTab:true,ignoreSearchTab:true,});},});});} static fromJSON(json) {return new WI.ConsoleSnippet(json.title,json.source);} toJSON(key) {let json={title:this.title,source:this.content,};if(key===WI.ObjectStore.toJSONSymbol) json[WI.objectStores.breakpoints.keyPath]=this.title;return json;}};WI.Cookie=class Cookie {constructor(type,name,value,{header,expires,session,maxAge,path,domain,secure,httpOnly,sameSite}={}) {this._type=type;this._name=name;this._value=value;this._size=this._name.length+this._value.length;if(this._type===WI.Cookie.Type.Response){this._header=header||"";this._expires=(!session&&expires)||null;this._session=session||false;this._maxAge=maxAge||null;this._path=path||null;this._domain=domain||null;this._secure=secure||false;this._httpOnly=httpOnly||false;this._sameSite=sameSite||WI.Cookie.SameSiteType.None;}} static fromPayload(payload) {let{name,value,...options}=payload;options.expires=options.expires?new Date(options.expires.maxDecimals(-3)):null;return new WI.Cookie(WI.Cookie.Type.Response,name,value,options);} static parseCookieRequestHeader(header) {if(!header) return[];header=header.trim();if(!header) return[];let cookies=[];let pairs=header.split(/; /);for(let pair of pairs){let match=pair.match(/^(?[^\s=]+)[ \t]*=[ \t]*(?.*)$/);if(!match){WI.reportInternalError("Failed to parse Cookie pair",{header,pair});continue;} let{name,value}=match.groups;cookies.push(new WI.Cookie(WI.Cookie.Type.Request,name,value));} return cookies;} static displayNameForSameSiteType(sameSiteType) {switch(sameSiteType){case WI.Cookie.SameSiteType.None:return WI.unlocalizedString("None");case WI.Cookie.SameSiteType.Lax:return WI.unlocalizedString("Lax");case WI.Cookie.SameSiteType.Strict:return WI.unlocalizedString("Strict");default:console.error("Invalid SameSite type",sameSiteType);return sameSiteType;}} static parseSameSiteAttributeValue(attributeValue) {if(!attributeValue) return WI.Cookie.SameSiteType.None;switch(attributeValue.toLowerCase()){case"lax":return WI.Cookie.SameSiteType.Lax;case"strict":return WI.Cookie.SameSiteType.Strict;} return WI.Cookie.SameSiteType.None;} static parseSetCookieResponseHeader(header) {if(!header) return null; let nameValueMatch=header.match(/^(?[^\s=]+)[ \t]*=[ \t]*(?[^;]*)/);if(!nameValueMatch){WI.reportInternalError("Failed to parse Set-Cookie header",{header});return null;} let{name,value}=nameValueMatch.groups;let expires=null;let session=false;let maxAge=null;let path=null;let domain=null;let secure=false;let httpOnly=false;let sameSite=WI.Cookie.SameSiteType.None; let remaining=header.substr(nameValueMatch[0].length);let attributes=remaining.split(/; ?/);for(let attribute of attributes){if(!attribute) continue;let match=attribute.match(/^(?[^\s=]+)(?:=(?.*))?$/);if(!match){console.error("Failed to parse Set-Cookie attribute:",attribute);continue;} let attributeName=match.groups.name;let attributeValue=match.groups.value;switch(attributeName.toLowerCase()){case"expires":expires=new Date(attributeValue);if(isNaN(expires.getTime())){console.warn("Invalid Expires date:",attributeValue);expires=null;} break;case"max-age":maxAge=parseInt(attributeValue,10);if(isNaN(maxAge)||!/^\d+$/.test(attributeValue)){console.warn("Invalid MaxAge value:",attributeValue);maxAge=null;} break;case"path":path=attributeValue;break;case"domain":domain=attributeValue;break;case"secure":secure=true;break;case"httponly":httpOnly=true;break;case"samesite":sameSite=WI.Cookie.parseSameSiteAttributeValue(attributeValue);break;default:console.warn("Unknown Cookie attribute:",attribute);break;}} if(!expires) session=true;return new WI.Cookie(WI.Cookie.Type.Response,name,value,{header,expires,session,maxAge,path,domain,secure,httpOnly,sameSite});} get type(){return this._type;} get name(){return this._name;} get value(){return this._value;} get header(){return this._header;} get expires(){return this._expires;} get session(){return this._session;} get maxAge(){return this._maxAge;} get path(){return this._path;} get domain(){return this._domain;} get secure(){return this._secure;} get httpOnly(){return this._httpOnly;} get sameSite(){return this._sameSite;} get size(){return this._size;} get url() {let url=this._secure?"https://":"http://";url+=this._domain||"";url+=this._path||"";return url;} expirationDate(requestSentDate) {if(this._session) return null;if(this._maxAge){let startDate=requestSentDate||new Date;return new Date(startDate.getTime()+(this._maxAge*1000));} return this._expires;} equals(other) {return this._type===other.type&&this._name===other.name&&this._value===other.value&&this._header===other.header&&this._expires?.getTime()===other.expires?.getTime()&&this._session===other.session&&this._maxAge===other.maxAge&&this._path===other.path&&this._domain===other.domain&&this._secure===other.secure&&this._httpOnly===other.httpOnly&&this._sameSite===other.sameSite;} toProtocol() {if(typeof this._name!=="string") return null;if(typeof this._value!=="string") return null;if(typeof this._domain!=="string") return null;if(typeof this._path!=="string") return null;if(!this._session&&!this._expires) return null;if(!Object.values(WI.Cookie.SameSiteType).includes(this._sameSite)) return null;let json={name:this._name,value:this._value,domain:this._domain,path:this._path,expires:this._expires?.getTime(),session:this._session,httpOnly:!!this._httpOnly,secure:!!this._secure,sameSite:this._sameSite,};return json;}};WI.Cookie.Type={Request:"request",Response:"response",};WI.Cookie.SameSiteType={None:"None",Lax:"Lax",Strict:"Strict",};WI.CookieStorageObject=class CookieStorageObject {constructor(host) {this._host=host;} static cookieMatchesResourceURL(cookie,resourceURL) {var parsedURL=parseURL(resourceURL);if(!parsedURL||!WI.CookieStorageObject.cookieDomainMatchesResourceDomain(cookie.domain,parsedURL.host)) return false;return parsedURL.path.startsWith(cookie.path)&&(!cookie.port||parsedURL.port===cookie.port)&&(!cookie.secure||parsedURL.scheme==="https");} static cookieDomainMatchesResourceDomain(cookieDomain,resourceDomain) {if(cookieDomain.charAt(0)!==".") return resourceDomain===cookieDomain;return!!resourceDomain.match(new RegExp("^(?:[^\\.]+\\.)*"+cookieDomain.substring(1).escapeForRegExp()+"$"),"i");} get host() {return this._host;} saveIdentityToCookie(cookie) {cookie[WI.CookieStorageObject.CookieHostCookieKey]=this.host;}};WI.CookieStorageObject.TypeIdentifier="cookie-storage";WI.CookieStorageObject.CookieHostCookieKey="cookie-storage-host";WI.CubicBezierTimingFunction=class CubicBezierTimingFunction {constructor(x1,y1,x2,y2) {this._inPoint=new WI.Point(x1,y1);this._outPoint=new WI.Point(x2,y2);this._curveInfo={x:{c:3.0*x1},y:{c:3.0*y1}};this._curveInfo.x.b=3.0*(x2-x1)-this._curveInfo.x.c;this._curveInfo.x.a=1.0-this._curveInfo.x.c-this._curveInfo.x.b;this._curveInfo.y.b=3.0*(y2-y1)-this._curveInfo.y.c;this._curveInfo.y.a=1.0-this._curveInfo.y.c-this._curveInfo.y.b;} static fromCoordinates(coordinates) {if(!coordinates||coordinates.length<4) return null;coordinates=coordinates.map(Number);if(coordinates.includes(NaN)) return null;return new WI.CubicBezierTimingFunction(coordinates[0],coordinates[1],coordinates[2],coordinates[3]);} static fromString(text) {if(!text||!text.length) return null;var trimmedText=text.toLowerCase().replace(/\s/g,"");if(!trimmedText.length) return null;if(Object.keys(WI.CubicBezierTimingFunction.keywordValues).includes(trimmedText)) return WI.CubicBezierTimingFunction.fromCoordinates(WI.CubicBezierTimingFunction.keywordValues[trimmedText]);var matches=trimmedText.match(/^cubic-bezier\(([-\d.]+),([-\d.]+),([-\d.]+),([-\d.]+)\)$/);if(!matches) return null;matches.splice(0,1);return WI.CubicBezierTimingFunction.fromCoordinates(matches);} get inPoint() {return this._inPoint;} get outPoint() {return this._outPoint;} copy() {return new WI.CubicBezierTimingFunction(this._inPoint.x,this._inPoint.y,this._outPoint.x,this._outPoint.y);} toString() {var values=[this._inPoint.x,this._inPoint.y,this._outPoint.x,this._outPoint.y];for(var key in WI.CubicBezierTimingFunction.keywordValues){if(Array.shallowEqual(WI.CubicBezierTimingFunction.keywordValues[key],values)) return key;} return"cubic-bezier("+values.join(", ")+")";} solve(x,epsilon) {return this._sampleCurveY(this._solveCurveX(x,epsilon));} _sampleCurveX(t) {return((this._curveInfo.x.a*t+this._curveInfo.x.b)*t+this._curveInfo.x.c)*t;} _sampleCurveY(t) {return((this._curveInfo.y.a*t+this._curveInfo.y.b)*t+this._curveInfo.y.c)*t;} _sampleCurveDerivativeX(t) {return(3.0*this._curveInfo.x.a*t+2.0*this._curveInfo.x.b)*t+this._curveInfo.x.c;} _solveCurveX(x,epsilon) {var t0,t1,t2,x2,d2,i;for(t2=x,i=0;i<8;i++){x2=this._sampleCurveX(t2)-x;if(Math.abs(x2)t1) return t1;while(t0x2) t0=t2;else t1=t2;t2=(t1-t0)*0.5+t0;} return t2;}};WI.CubicBezierTimingFunction.keywordValues={"ease":[0.25,0.1,0.25,1],"ease-in":[0.42,0,1,1],"ease-out":[0,0,0.58,1],"ease-in-out":[0.42,0,0.58,1],"linear":[0,0,1,1]};WI.DOMBreakpoint=class DOMBreakpoint extends WI.Breakpoint {constructor(domNodeOrInfo,type,{disabled,actions,condition,ignoreCount,autoContinue}={}) {super({disabled,actions,condition,ignoreCount,autoContinue});if(domNodeOrInfo instanceof WI.DOMNode){this._domNode=domNodeOrInfo;this._path=domNodeOrInfo.path();this._url=WI.networkManager.mainFrame.url;}else if(domNodeOrInfo&&typeof domNodeOrInfo==="object"){this._domNode=null;this._path=domNodeOrInfo.path;this._url=domNodeOrInfo.url;} this._type=type;} static displayNameForType(type) {switch(type){case WI.DOMBreakpoint.Type.SubtreeModified:return WI.UIString("Subtree Modified","Subtree Modified @ DOM Breakpoint","A submenu item of 'Break On' that breaks (pauses) before child DOM node is modified");case WI.DOMBreakpoint.Type.AttributeModified:return WI.UIString("Attribute Modified","Attribute Modified @ DOM Breakpoint","A submenu item of 'Break On' that breaks (pauses) before DOM attribute is modified");case WI.DOMBreakpoint.Type.NodeRemoved:return WI.UIString("Node Removed","Node Removed @ DOM Breakpoint","A submenu item of 'Break On' that breaks (pauses) before DOM node is removed");} return WI.UIString("DOM");} static fromJSON(json) {return new WI.DOMBreakpoint(json,json.type,{disabled:json.disabled,condition:json.condition,actions:json.actions?.map((actionJSON)=>WI.BreakpointAction.fromJSON(actionJSON))||[],ignoreCount:json.ignoreCount,autoContinue:json.autoContinue,});} get type(){return this._type;} get url(){return this._url;} get path(){return this._path;} get displayName() {return WI.DOMBreakpoint.displayNameForType(this._type);} get editable() {return InspectorBackend.hasCommand("DOMDebugger.setDOMBreakpoint","options");} get domNode() {return this._domNode;} set domNode(domNode) {if(!xor(domNode,this._domNode)) return;this.dispatchEventToListeners(WI.DOMBreakpoint.Event.DOMNodeWillChange);this._domNode=domNode;this.dispatchEventToListeners(WI.DOMBreakpoint.Event.DOMNodeDidChange);} remove() {super.remove();WI.domDebuggerManager.removeDOMBreakpoint(this);} saveIdentityToCookie(cookie) {cookie["dom-breakpoint-url"]=this._url;cookie["dom-breakpoint-path"]=this._path;cookie["dom-breakpoint-type"]=this._type;} toJSON(key) {let json=super.toJSON(key);json.url=this._url;json.path=this._path;json.type=this._type;if(key===WI.ObjectStore.toJSONSymbol) json[WI.objectStores.domBreakpoints.keyPath]=this._url+":"+this._path+":"+this._type;return json;}};WI.DOMBreakpoint.Type={SubtreeModified:"subtree-modified",AttributeModified:"attribute-modified",NodeRemoved:"node-removed",};WI.DOMBreakpoint.Event={DOMNodeDidChange:"dom-breakpoint-dom-node-did-change",DOMNodeWillChange:"dom-breakpoint-dom-node-will-change",};WI.DOMBreakpoint.ReferencePage=WI.ReferencePage.DOMBreakpoints;WI.DOMNode=class DOMNode extends WI.Object {constructor(domManager,doc,isInShadowTree,payload) {super();this._destroyed=false;this._domManager=domManager;this._isInShadowTree=isInShadowTree;this.id=payload.nodeId;this._domManager._idToDOMNode[this.id]=this;this._nodeType=payload.nodeType;this._nodeName=payload.nodeName;this._localName=payload.localName;this._nodeValue=payload.nodeValue;this._pseudoType=payload.pseudoType;this._shadowRootType=payload.shadowRootType;this._computedRole=null;this._contentSecurityPolicyHash=payload.contentSecurityPolicyHash;this._layoutFlags=[];this._layoutOverlayShowing=false;this._layoutOverlayColorSetting=null;if(this._nodeType===Node.DOCUMENT_NODE) this.ownerDocument=this;else this.ownerDocument=doc;this._frame=null;if(InspectorBackend.hasDomain("Audit")){if(payload.frameId) this._frame=WI.networkManager.frameForIdentifier(payload.frameId);} if(!this._frame&&this.ownerDocument) this._frame=WI.networkManager.frameForIdentifier(this.ownerDocument.frameIdentifier);this._attributes=[];this._attributesMap=new Map;if(payload.attributes) this._setAttributesPayload(payload.attributes);this._childNodeCount=payload.childNodeCount;this._children=null;this._nextSibling=null;this._previousSibling=null;this.parentNode=null;this._enabledPseudoClasses=[]; this._shadowRoots=[];if(payload.shadowRoots){for(var i=0;i{if(current.eventName==="webkitfullscreenchange"&¤t.data&&(!accumulator.length||accumulator.lastValue.data.enabled!==current.data.enabled)) accumulator.push(current);return accumulator;},[]);} static isPlayEvent(eventName) {return eventName==="play"||eventName==="playing";} static isPauseEvent(eventName) {return eventName==="pause"||eventName==="stall";} static isStopEvent(eventName) {return eventName==="emptied"||eventName==="ended"||eventName==="suspend";} get destroyed(){return this._destroyed;} get frame(){return this._frame;} get nextSibling(){return this._nextSibling;} get previousSibling(){return this._previousSibling;} get children(){return this._children;} get domEvents(){return this._domEvents;} get powerEfficientPlaybackRanges(){return this._powerEfficientPlaybackRanges;} get layoutOverlayShowing(){return this._layoutOverlayShowing;} get attached() {if(this._destroyed) return false;for(let node=this;node;node=node.parentNode){if(node.ownerDocument===node) return true;} return false;} get firstChild() {var children=this.children;if(children&&children.length>0) return children[0];return null;} get lastChild() {var children=this.children;if(children&&children.length>0) return children.lastValue;return null;} get childNodeCount() {var children=this.children;if(children) return children.length;return this._childNodeCount+this._shadowRoots.length;} set childNodeCount(count) {this._childNodeCount=count;} get layoutFlags() {return this._layoutFlags;} set layoutFlags(layoutFlags) {layoutFlags||=[];let oldLayoutContextType=this.layoutContextType;this._layoutFlags=layoutFlags;this.dispatchEventToListeners(WI.DOMNode.Event.LayoutFlagsChanged);if(!this._layoutOverlayShowing) return;this.dispatchEventToListeners(WI.DOMNode.Event.LayoutOverlayHidden);switch(oldLayoutContextType){case WI.DOMNode.LayoutFlag.Flex:WI.settings.flexOverlayShowOrderNumbers.removeEventListener(WI.Setting.Event.Changed,this._handleLayoutOverlaySettingChanged,this);break;case WI.DOMNode.LayoutFlag.Grid:WI.settings.gridOverlayShowExtendedGridLines.removeEventListener(WI.Setting.Event.Changed,this._handleLayoutOverlaySettingChanged,this);WI.settings.gridOverlayShowLineNames.removeEventListener(WI.Setting.Event.Changed,this._handleLayoutOverlaySettingChanged,this);WI.settings.gridOverlayShowLineNumbers.removeEventListener(WI.Setting.Event.Changed,this._handleLayoutOverlaySettingChanged,this);WI.settings.gridOverlayShowTrackSizes.removeEventListener(WI.Setting.Event.Changed,this._handleLayoutOverlaySettingChanged,this);WI.settings.gridOverlayShowAreaNames.removeEventListener(WI.Setting.Event.Changed,this._handleLayoutOverlaySettingChanged,this);break;}} get layoutContextType() {return this._layoutFlags.find((layoutFlag)=>WI.DOMNode._LayoutContextTypes.includes(layoutFlag))||null;} markDestroyed() {this._destroyed=true;this.layoutFlags=[];} computedRole() {return this._computedRole;} contentSecurityPolicyHash() {return this._contentSecurityPolicyHash;} hasAttributes() {return this._attributes.length>0;} hasChildNodes() {return this.childNodeCount>0;} hasShadowRoots() {return!!this._shadowRoots.length;} isInShadowTree() {return this._isInShadowTree;} isInUserAgentShadowTree() {return this._isInShadowTree&&this.ancestorShadowRoot().isUserAgentShadowRoot();} isCustomElement() {return this._customElementState===WI.DOMNode.CustomElementState.Custom;} customElementState() {return this._customElementState;} isShadowRoot() {return!!this._shadowRootType;} isUserAgentShadowRoot() {return this._shadowRootType===WI.DOMNode.ShadowRootType.UserAgent;} ancestorShadowRoot() {if(!this._isInShadowTree) return null;let node=this;while(node&&!node.isShadowRoot()) node=node.parentNode;return node;} ancestorShadowHost() {let shadowRoot=this.ancestorShadowRoot();return shadowRoot?shadowRoot.parentNode:null;} isPseudoElement() {return this._pseudoType!==undefined;} nodeType() {return this._nodeType;} nodeName() {return this._nodeName;} nodeNameInCorrectCase() {return this.isXMLNode()?this.nodeName():this.nodeName().toLowerCase();} setNodeName(name,callback) {if(this._destroyed){callback("ERROR: node is destroyed");return;} let target=WI.assumingMainTarget();target.DOMAgent.setNodeName(this.id,name,this._makeUndoableCallback(callback));} localName() {return this._localName;} templateContent() {return this._templateContent||null;} pseudoType() {return this._pseudoType;} hasPseudoElements() {return this._pseudoElements.size>0;} pseudoElements() {return this._pseudoElements;} beforePseudoElement() {return this._pseudoElements.get(WI.DOMNode.PseudoElementType.Before)||null;} afterPseudoElement() {return this._pseudoElements.get(WI.DOMNode.PseudoElementType.After)||null;} shadowRoots() {return this._shadowRoots;} shadowRootType() {return this._shadowRootType;} nodeValue() {return this._nodeValue;} setNodeValue(value,callback) {if(this._destroyed){callback("ERROR: node is destroyed");return;} let target=WI.assumingMainTarget();target.DOMAgent.setNodeValue(this.id,value,this._makeUndoableCallback(callback));} getAttribute(name) {let attr=this._attributesMap.get(name);return attr?attr.value:undefined;} setAttribute(name,text,callback) {if(this._destroyed){callback("ERROR: node is destroyed");return;} let target=WI.assumingMainTarget();target.DOMAgent.setAttributesAsText(this.id,text,name,this._makeUndoableCallback(callback));} setAttributeValue(name,value,callback) {if(this._destroyed){if(!callback) return Promise.reject("ERROR: node is destroyed");callback("ERROR: node is destroyed");return;} let target=WI.assumingMainTarget();if(!callback){return target.DOMAgent.setAttributeValue(this.id,name,value).then(()=>{this._markUndoableState();});} target.DOMAgent.setAttributeValue(this.id,name,value,this._makeUndoableCallback(callback));} attributes() {return this._attributes;} removeAttribute(name,callback) {if(this._destroyed){callback("ERROR: node is destroyed");return;} function mycallback(error,success) {if(!error){this._attributesMap.delete(name);for(var i=0;i{function inspectedPage_node_toggleClass(className,flag){this.classList.toggle(className,flag);} object.callFunction(inspectedPage_node_toggleClass,[className,flag]);object.release();});} querySelector(selector,callback) {let target=WI.assumingMainTarget();if(typeof callback!=="function"){if(this._destroyed) return Promise.reject("ERROR: node is destroyed");return target.DOMAgent.querySelector(this.id,selector).then(({nodeId})=>nodeId);} if(this._destroyed){callback("ERROR: node is destroyed");return;} target.DOMAgent.querySelector(this.id,selector,WI.DOMManager.wrapClientCallback(callback));} querySelectorAll(selector,callback) {let target=WI.assumingMainTarget();if(typeof callback!=="function"){if(this._destroyed) return Promise.reject("ERROR: node is destroyed");return target.DOMAgent.querySelectorAll(this.id,selector).then(({nodeIds})=>nodeIds);} if(this._destroyed){callback("ERROR: node is destroyed");return;} target.DOMAgent.querySelectorAll(this.id,selector,WI.DOMManager.wrapClientCallback(callback));} highlight(mode) {if(this._destroyed) return;if(this._hideDOMNodeHighlightTimeout){clearTimeout(this._hideDOMNodeHighlightTimeout);this._hideDOMNodeHighlightTimeout=undefined;} let target=WI.assumingMainTarget();target.DOMAgent.highlightNode.invoke({nodeId:this.id,...WI.DOMManager.buildHighlightConfigs(mode),});} showLayoutOverlay({color}={}) {if(this._destroyed) return Promise.reject("ERROR: node is destroyed");color||=this.layoutOverlayColor;let target=WI.assumingMainTarget();let agentCommandFunction=null;let agentCommandArguments={nodeId:this.id};switch(this.layoutContextType){case WI.DOMNode.LayoutFlag.Grid:agentCommandArguments.gridOverlayConfig={gridColor:color.toProtocol(),showLineNames:WI.settings.gridOverlayShowLineNames.value,showLineNumbers:WI.settings.gridOverlayShowLineNumbers.value,showExtendedGridLines:WI.settings.gridOverlayShowExtendedGridLines.value,showTrackSizes:WI.settings.gridOverlayShowTrackSizes.value,showAreaNames:WI.settings.gridOverlayShowAreaNames.value,};if(!target.hasCommand("DOM.showGridOverlay","gridOverlayConfig")){for(let[key,value]in Object.entries(agentCommandArguments.gridOverlayConfig)) agentCommandArguments[key]=value;} agentCommandFunction=target.DOMAgent.showGridOverlay;if(!this._layoutOverlayShowing){WI.settings.gridOverlayShowExtendedGridLines.addEventListener(WI.Setting.Event.Changed,this._handleLayoutOverlaySettingChanged,this);WI.settings.gridOverlayShowLineNames.addEventListener(WI.Setting.Event.Changed,this._handleLayoutOverlaySettingChanged,this);WI.settings.gridOverlayShowLineNumbers.addEventListener(WI.Setting.Event.Changed,this._handleLayoutOverlaySettingChanged,this);WI.settings.gridOverlayShowTrackSizes.addEventListener(WI.Setting.Event.Changed,this._handleLayoutOverlaySettingChanged,this);WI.settings.gridOverlayShowAreaNames.addEventListener(WI.Setting.Event.Changed,this._handleLayoutOverlaySettingChanged,this);} break;case WI.DOMNode.LayoutFlag.Flex:agentCommandArguments.flexOverlayConfig={flexColor:color.toProtocol(),showOrderNumbers:WI.settings.flexOverlayShowOrderNumbers.value,};if(!target.hasCommand("DOM.showFlexOverlay","flexOverlayConfig")){for(let[key,value]in Object.entries(agentCommandArguments.flexOverlayConfig)) agentCommandArguments[key]=value;} agentCommandFunction=target.DOMAgent.showFlexOverlay;if(!this._layoutOverlayShowing) WI.settings.flexOverlayShowOrderNumbers.addEventListener(WI.Setting.Event.Changed,this._handleLayoutOverlaySettingChanged,this);break;} this._layoutOverlayShowing=true;this.dispatchEventToListeners(WI.DOMNode.Event.LayoutOverlayShown);return agentCommandFunction.invoke(agentCommandArguments);} hideLayoutOverlay() {if(this._destroyed) return Promise.reject("ERROR: node is destroyed");let target=WI.assumingMainTarget();let agentCommandFunction;let agentCommandArguments={nodeId:this.id};switch(this.layoutContextType){case WI.DOMNode.LayoutFlag.Grid:WI.settings.gridOverlayShowExtendedGridLines.removeEventListener(WI.Setting.Event.Changed,this._handleLayoutOverlaySettingChanged,this);WI.settings.gridOverlayShowLineNames.removeEventListener(WI.Setting.Event.Changed,this._handleLayoutOverlaySettingChanged,this);WI.settings.gridOverlayShowLineNumbers.removeEventListener(WI.Setting.Event.Changed,this._handleLayoutOverlaySettingChanged,this);WI.settings.gridOverlayShowTrackSizes.removeEventListener(WI.Setting.Event.Changed,this._handleLayoutOverlaySettingChanged,this);WI.settings.gridOverlayShowAreaNames.removeEventListener(WI.Setting.Event.Changed,this._handleLayoutOverlaySettingChanged,this);agentCommandFunction=target.DOMAgent.hideGridOverlay;break;case WI.DOMNode.LayoutFlag.Flex:WI.settings.flexOverlayShowOrderNumbers.removeEventListener(WI.Setting.Event.Changed,this._handleLayoutOverlaySettingChanged,this);agentCommandFunction=target.DOMAgent.hideFlexOverlay;break;} this._layoutOverlayShowing=false;this.dispatchEventToListeners(WI.DOMNode.Event.LayoutOverlayHidden);return agentCommandFunction.invoke(agentCommandArguments);} get layoutOverlayColor() {this._createLayoutOverlayColorSettingIfNeeded();return new WI.Color(WI.Color.Format.HSL,this._layoutOverlayColorSetting.value);} set layoutOverlayColor(color) {this._createLayoutOverlayColorSettingIfNeeded();this._layoutOverlayColorSetting.value=color.hsl;if(this._layoutOverlayShowing) this.showLayoutOverlay({color});} scrollIntoView() {WI.RemoteObject.resolveNode(this).then((object)=>{function inspectedPage_node_scrollIntoView(){this.scrollIntoViewIfNeeded(true);} object.callFunction(inspectedPage_node_scrollIntoView);object.release();});} getChildNodes(callback) {if(this.children){if(callback) callback(this.children);return;} if(this._destroyed){callback(this.children);return;} function mycallback(error){if(!error&&callback) callback(this.children);} let target=WI.assumingMainTarget();target.DOMAgent.requestChildNodes(this.id,mycallback.bind(this));} getSubtree(depth,callback) {if(this._destroyed){callback(this.children);return;} function mycallback(error) {if(callback) callback(error?null:this.children);} let target=WI.assumingMainTarget();target.DOMAgent.requestChildNodes(this.id,depth,mycallback.bind(this));} getOuterHTML(callback) {let target=WI.assumingMainTarget();if(typeof callback!=="function"){if(this._destroyed) return Promise.reject("ERROR: node is destroyed");return target.DOMAgent.getOuterHTML(this.id).then(({outerHTML})=>outerHTML);} if(this._destroyed){callback("ERROR: node is destroyed");return;} target.DOMAgent.getOuterHTML(this.id,callback);} setOuterHTML(html,callback) {if(this._destroyed){callback("ERROR: node is destroyed");return;} let target=WI.assumingMainTarget();target.DOMAgent.setOuterHTML(this.id,html,this._makeUndoableCallback(callback));} insertAdjacentHTML(position,html) {if(this._destroyed) return;if(this.nodeType()!==Node.ELEMENT_NODE) return;let target=WI.assumingMainTarget();target.DOMAgent.insertAdjacentHTML(this.id,position,html,this._makeUndoableCallback());} removeNode(callback) {if(this._destroyed){callback("ERROR: node is destroyed");return;} let target=WI.assumingMainTarget();target.DOMAgent.removeNode(this.id,this._makeUndoableCallback(callback));} getEventListeners({includeAncestors}={}) {if(this._destroyed) return Promise.reject("ERROR: node is destroyed");includeAncestors??=true;let target=WI.assumingMainTarget();return target.DOMAgent.getEventListenersForNode.invoke({nodeId:this.id,includeAncestors,});} accessibilityProperties(callback) {if(this._destroyed){callback({});return;} function accessibilityPropertiesCallback(error,accessibilityProperties) {if(!error&&callback&&accessibilityProperties){this._computedRole=accessibilityProperties.role;callback({activeDescendantNodeId:accessibilityProperties.activeDescendantNodeId,busy:accessibilityProperties.busy,checked:accessibilityProperties.checked,childNodeIds:accessibilityProperties.childNodeIds,controlledNodeIds:accessibilityProperties.controlledNodeIds,current:accessibilityProperties.current,disabled:accessibilityProperties.disabled,exists:accessibilityProperties.exists,expanded:accessibilityProperties.expanded,flowedNodeIds:accessibilityProperties.flowedNodeIds,focused:accessibilityProperties.focused,ignored:accessibilityProperties.ignored,ignoredByDefault:accessibilityProperties.ignoredByDefault,invalid:accessibilityProperties.invalid,isPopupButton:accessibilityProperties.isPopUpButton,headingLevel:accessibilityProperties.headingLevel,hierarchyLevel:accessibilityProperties.hierarchyLevel,hidden:accessibilityProperties.hidden,label:accessibilityProperties.label,liveRegionAtomic:accessibilityProperties.liveRegionAtomic,liveRegionRelevant:accessibilityProperties.liveRegionRelevant,liveRegionStatus:accessibilityProperties.liveRegionStatus,mouseEventNodeId:accessibilityProperties.mouseEventNodeId,nodeId:accessibilityProperties.nodeId,ownedNodeIds:accessibilityProperties.ownedNodeIds,parentNodeId:accessibilityProperties.parentNodeId,pressed:accessibilityProperties.pressed,readonly:accessibilityProperties.readonly,required:accessibilityProperties.required,role:accessibilityProperties.role,selected:accessibilityProperties.selected,selectedChildNodeIds:accessibilityProperties.selectedChildNodeIds});}} let target=WI.assumingMainTarget();target.DOMAgent.getAccessibilityPropertiesForNode(this.id,accessibilityPropertiesCallback.bind(this));} path() {var path=[];var node=this;while(node&&"index"in node&&node._nodeName.length){path.push([node.index,node._nodeName]);node=node.parentNode;} path.reverse();return path.join(",");} get escapedIdSelector() {return this._idSelector(true);} get escapedClassSelector() {return this._classSelector(true);} get displayName() {if(this.isPseudoElement()) return"::"+this._pseudoType;return this.nodeNameInCorrectCase()+this.escapedIdSelector+this.escapedClassSelector;} get unescapedSelector() {if(this.isPseudoElement()) return"::"+this._pseudoType;const shouldEscape=false;return this.nodeNameInCorrectCase()+this._idSelector(shouldEscape)+this._classSelector(shouldEscape);} appropriateSelectorFor(justSelector) {if(this.isPseudoElement()) return this.parentNode.appropriateSelectorFor()+"::"+this._pseudoType;let lowerCaseName=this.localName()||this.nodeName().toLowerCase();let id=this.escapedIdSelector;if(id.length) return justSelector?id:lowerCaseName+id;let classes=this.escapedClassSelector;if(classes.length) return justSelector?classes:lowerCaseName+classes;if(lowerCaseName==="input"&&this.getAttribute("type")) return lowerCaseName+"[type=\""+this.getAttribute("type")+"\"]";return lowerCaseName;} isAncestor(node) {if(!node) return false;var currentNode=node.parentNode;while(currentNode){if(this===currentNode) return true;currentNode=currentNode.parentNode;} return false;} isDescendant(descendant) {return descendant!==null&&descendant.isAncestor(this);} get ownerSVGElement() {if(this._nodeName==="svg") return this;if(!this.parentNode) return null;return this.parentNode.ownerSVGElement;} isSVGElement() {return!!this.ownerSVGElement;} isMediaElement() {let lowerCaseName=this.localName()||this.nodeName().toLowerCase();return lowerCaseName==="video"||lowerCaseName==="audio";} didFireEvent(eventName,timestamp,data) {this._addDOMEvent({eventName,timestamp:WI.timelineManager.computeElapsedTime(timestamp),data,});} powerEfficientPlaybackStateChanged(timestamp,isPowerEfficient) {let lastValue=this._powerEfficientPlaybackRanges.lastValue;if(isPowerEfficient){if(!lastValue||lastValue.endTimestamp) this._powerEfficientPlaybackRanges.push({startTimestamp:timestamp});}else{if(!lastValue) this._powerEfficientPlaybackRanges.push({endTimestamp:timestamp});else if(lastValue.startTimestamp) lastValue.endTimestamp=timestamp;} this.dispatchEventToListeners(DOMNode.Event.PowerEfficientPlaybackStateChanged,{isPowerEfficient,timestamp});} canEnterPowerEfficientPlaybackState() {return this.localName()==="video"||this.nodeName().toLowerCase()==="video";} _handleDOMNodeDidFireEvent(event) {if(event.target===this||!event.target.isAncestor(this)) return;let domEvent=Object.shallowCopy(event.data.domEvent);domEvent.originator=event.target;this._addDOMEvent(domEvent);} _addDOMEvent(domEvent) {this._domEvents.push(domEvent);this.dispatchEventToListeners(WI.DOMNode.Event.DidFireEvent,{domEvent});} _setAttributesPayload(attrs) {this._attributes=[];this._attributesMap=new Map;for(var i=0;i=0?this._children[i-1]:null;child.parentNode=this;}} _addAttribute(name,value) {let attr={name,value,_node:this};this._attributesMap.set(name,attr);this._attributes.push(attr);} _setAttribute(name,value) {let attr=this._attributesMap.get(name);if(attr) attr.value=value;else this._addAttribute(name,value);} _removeAttribute(name) {let attr=this._attributesMap.get(name);if(attr){this._attributes.remove(attr);this._attributesMap.delete(name);}} moveTo(targetNode,anchorNode,callback) {if(this._destroyed){callback("ERROR: node is destroyed");return;} let target=WI.assumingMainTarget();target.DOMAgent.moveTo(this.id,targetNode.id,anchorNode?anchorNode.id:undefined,this._makeUndoableCallback(callback));} isXMLNode() {return!!this.ownerDocument&&!!this.ownerDocument.xmlVersion;} get enabledPseudoClasses() {return this._enabledPseudoClasses;} setPseudoClassEnabled(pseudoClass,enabled) {var pseudoClasses=this._enabledPseudoClasses;if(enabled){if(pseudoClasses.includes(pseudoClass)) return;pseudoClasses.push(pseudoClass);}else{if(!pseudoClasses.includes(pseudoClass)) return;pseudoClasses.remove(pseudoClass);} function changed(error) {if(!error) this.dispatchEventToListeners(WI.DOMNode.Event.EnabledPseudoClassesChanged);} let target=WI.assumingMainTarget();target.CSSAgent.forcePseudoState(this.id,pseudoClasses,changed.bind(this));} _markUndoableState() {let target=WI.assumingMainTarget();if(target.hasCommand("DOM.markUndoableState")) target.DOMAgent.markUndoableState();} _makeUndoableCallback(callback) {return(...args)=>{if(!args[0]) this._markUndoableState();if(callback) callback.apply(null,args);};} _idSelector(shouldEscape) {let id=this.getAttribute("id");if(!id) return"";id=id.trim();if(!id.length) return"";if(shouldEscape) id=CSS.escape(id);if(/[\s'"]/.test(id)) return`[id="${id}"]`;return`#${id}`;} _classSelector(shouldEscape){let classes=this.getAttribute("class");if(!classes) return"";classes=classes.trim();if(!classes.length) return"";let foundClasses=new Set;return classes.split(/\s+/).reduce((selector,className)=>{if(!className.length||foundClasses.has(className)) return selector;foundClasses.add(className);return`${selector}.${(shouldEscape ? CSS.escape(className) : className)}`;},"");} _createLayoutOverlayColorSettingIfNeeded() {if(this._layoutOverlayColorSetting) return;let defaultConfiguration=WI.DOMNode._defaultLayoutOverlayConfiguration;let url=this.ownerDocument.documentURL||WI.networkManager.mainFrame.url;let nextColorIndex;switch(this.layoutContextType){case WI.DOMNode.LayoutFlag.Grid:nextColorIndex=defaultConfiguration.nextGridColorIndex;defaultConfiguration.nextGridColorIndex=(nextColorIndex+1)%defaultConfiguration.colors.length;break;case WI.DOMNode.LayoutFlag.Flex:nextColorIndex=defaultConfiguration.nextFlexColorIndex;defaultConfiguration.nextFlexColorIndex=(nextColorIndex+1)%defaultConfiguration.colors.length;break;} this._layoutOverlayColorSetting=new WI.Setting(`overlay-color-${url.hash}-${this.path().hash}`,defaultConfiguration.colors[nextColorIndex]);} _handleLayoutOverlaySettingChanged(event) {if(this._layoutOverlayShowing) this.showLayoutOverlay();} async getMediaStats() {let target=WI.assumingMainTarget();let{mediaStats}=await target.DOMAgent.getMediaStats(this.id);return mediaStats;}};WI.DOMNode._defaultLayoutOverlayConfiguration={colors:[[329,91,70],[207,96,69],[92,90,64],[291,73,68],[40,97,57],],nextFlexColorIndex:0,nextGridColorIndex:0,};WI.DOMNode.Event={EnabledPseudoClassesChanged:"dom-node-enabled-pseudo-classes-did-change",AttributeModified:"dom-node-attribute-modified",AttributeRemoved:"dom-node-attribute-removed",EventListenersChanged:"dom-node-event-listeners-changed",DidFireEvent:"dom-node-did-fire-event",PowerEfficientPlaybackStateChanged:"dom-node-power-efficient-playback-state-changed",LayoutFlagsChanged:"dom-node-layout-flags-changed",LayoutOverlayShown:"dom-node-layout-overlay-shown",LayoutOverlayHidden:"dom-node-layout-overlay-hidden",};WI.DOMNode.PseudoElementType={Before:"before",After:"after",};WI.DOMNode.ShadowRootType={UserAgent:"user-agent",Closed:"closed",Open:"open",};WI.DOMNode.CustomElementState={Builtin:"builtin",Custom:"custom",Waiting:"waiting",Failed:"failed",};WI.DOMNode.LayoutFlag={Rendered:"rendered",Event:"event",Scrollable:"scrollable",Flex:"flex",Grid:"grid",};WI.DOMNode._LayoutContextTypes=[WI.DOMNode.LayoutFlag.Flex,WI.DOMNode.LayoutFlag.Grid,];WI.DOMNodeStyles=class DOMNodeStyles extends WI.Object {constructor(node) {super();this._node=node||null;this._rulesMap=new Map;this._stylesMap=new Multimap;this._groupingsMap=new Map;this._matchedRules=[];this._inheritedRules=[];this._pseudoElements=new Map;this._inlineStyle=null;this._attributesStyle=null;this._computedStyle=null;this._orderedStyles=[];this._computedPrimaryFont=null;this._propertyNameToEffectivePropertyMap={};this._usedCSSVariables=new Set;this._allCSSVariables=new Set;this._pendingRefreshTask=null;this.refresh();this._trackedStyleSheets=new WeakSet;WI.CSSStyleSheet.addEventListener(WI.CSSStyleSheet.Event.ContentDidChange,this._handleCSSStyleSheetContentDidChange,this);} static parseSelectorListPayload(selectorList) {let selectors=selectorList.selectors;if(!selectors.length) return[];return selectors.map(function(selectorPayload){return new WI.CSSSelector(selectorPayload.text,selectorPayload.specificity,selectorPayload.dynamic);});} static createSourceCodeLocation(sourceURL,{line,column,documentNode}={}) {if(!sourceURL) return null;let sourceCode=null;if(documentNode){let mainResource=WI.networkManager.resourcesForURL(documentNode.documentURL).firstValue;if(mainResource){let parentFrame=mainResource.parentFrame;sourceCode=parentFrame.resourcesForURL(sourceURL).firstValue;}} if(!sourceCode) sourceCode=WI.networkManager.resourcesForURL(sourceURL).firstValue;if(!sourceCode) return null;return sourceCode.createSourceCodeLocation(line||0,column||0);} static uniqueOrderedStyles(orderedStyles) {let uniqueOrderedStyles=[];for(let style of orderedStyles){let rule=style.ownerRule;if(!rule){uniqueOrderedStyles.push(style);continue;} let found=false;for(let existingStyle of uniqueOrderedStyles){if(rule.isEqualTo(existingStyle.ownerRule)){found=true;break;}} if(!found) uniqueOrderedStyles.push(style);} return uniqueOrderedStyles;} get node(){return this._node;} get matchedRules(){return this._matchedRules;} get inheritedRules(){return this._inheritedRules;} get inlineStyle(){return this._inlineStyle;} get attributesStyle(){return this._attributesStyle;} get pseudoElements(){return this._pseudoElements;} get computedStyle(){return this._computedStyle;} get orderedStyles(){return this._orderedStyles;} get computedPrimaryFont(){return this._computedPrimaryFont;} get usedCSSVariables(){return this._usedCSSVariables;} get allCSSVariables(){return this._allCSSVariables;} set ignoreNextContentDidChangeForStyleSheet(ignoreNextContentDidChangeForStyleSheet){this._ignoreNextContentDidChangeForStyleSheet=ignoreNextContentDidChangeForStyleSheet;} get needsRefresh() {return this._pendingRefreshTask||this._needsRefresh;} get uniqueOrderedStyles() {return WI.DOMNodeStyles.uniqueOrderedStyles(this._orderedStyles);} refreshIfNeeded() {if(this._pendingRefreshTask) return this._pendingRefreshTask;if(!this._needsRefresh) return Promise.resolve(this);return this.refresh();} refresh() {if(this._pendingRefreshTask) return this._pendingRefreshTask;this._needsRefresh=false;let fetchedMatchedStylesPromise=new WI.WrappedPromise;let fetchedInlineStylesPromise=new WI.WrappedPromise;let fetchedComputedStylesPromise=new WI.WrappedPromise;let fetchedFontDataPromise=new WI.WrappedPromise;function wrap(func,promise){return(...args)=>{try{func.apply(this,args);}catch(e){console.error(e);promise.resolve();}};} let parseRuleMatchArrayPayload=(matchArray,node,inherited,pseudoId)=>{var result=[];var ruleOccurrences={};for(var i=matchArray.length-1;i>=0;--i){var rule=this._parseRulePayload(matchArray[i].rule,matchArray[i].matchingSelectors,node,inherited,pseudoId,ruleOccurrences);if(!rule) continue;result.push(rule);} return result;};function fetchedMatchedStyles(error,matchedRulesPayload,pseudoElementRulesPayload,inheritedRulesPayload) {matchedRulesPayload=matchedRulesPayload||[];pseudoElementRulesPayload=pseudoElementRulesPayload||[];inheritedRulesPayload=inheritedRulesPayload||[];this._previousStylesMap=this._stylesMap;this._stylesMap=new Multimap;this._groupingsMap=new Map;this._matchedRules=parseRuleMatchArrayPayload(matchedRulesPayload,this._node);this._pseudoElements.clear();for(let{pseudoId,matches}of pseudoElementRulesPayload){let pseudoElementRules=parseRuleMatchArrayPayload(matches,this._node,false,pseudoId);this._pseudoElements.set(pseudoId,{matchedRules:pseudoElementRules});} this._inheritedRules=[];var i=0;var currentNode=this._node.parentNode;while(currentNode&&i{this._pendingRefreshTask=null;this.dispatchEventToListeners(WI.DOMNodeStyles.Event.Refreshed,{significantChange:fetchComputedStylesResult.significantChange,});return this;});return this._pendingRefreshTask;} addRule(selector,text,styleSheetId) {selector=selector||this._node.appropriateSelectorFor(true);let result=new WI.WrappedPromise;let target=WI.assumingMainTarget();function completed() {target.DOMAgent.markUndoableState(); if(this._pendingRefreshTask) this._pendingRefreshTask.then(this.refresh.bind(this));else this.refresh();} function styleChanged(error,stylePayload) {if(error) return;completed.call(this);} function addedRule(error,rulePayload) {if(error){result.reject(error);return;} result.resolve(rulePayload);if(!text||!text.length){completed.call(this);return;} target.CSSAgent.setStyleText(rulePayload.style.styleId,text,styleChanged.bind(this));} function inspectorStyleSheetAvailable(styleSheet) {if(!styleSheet) return;target.CSSAgent.addRule(styleSheet.id,selector,addedRule.bind(this));} if(styleSheetId) inspectorStyleSheetAvailable.call(this,WI.cssManager.styleSheetForIdentifier(styleSheetId));else WI.cssManager.preferredInspectorStyleSheetForFrame(this._node.frame,inspectorStyleSheetAvailable.bind(this));return result.promise;} effectivePropertyForName(name) {let property=this._propertyNameToEffectivePropertyMap[name];if(property) return property;let canonicalName=WI.cssManager.canonicalNameForPropertyName(name);return this._propertyNameToEffectivePropertyMap[canonicalName]||null;} mediaQueryResultDidChange() {this._markAsNeedsRefresh();} pseudoClassesDidChange(node) {this._includeUserAgentRulesOnNextRefresh=true;this._markAsNeedsRefresh();} attributeDidChange(node,attributeName) {this._markAsNeedsRefresh();} changeRuleSelector(rule,selector) {selector=selector||"";let result=new WI.WrappedPromise;let target=WI.assumingMainTarget();function ruleSelectorChanged(error,rulePayload) {if(error){result.reject(error);return;} target.DOMAgent.markUndoableState(); this.refresh().then(()=>{result.resolve(rulePayload);});} this._needsRefresh=true;this._ignoreNextContentDidChangeForStyleSheet=rule.ownerStyleSheet;target.CSSAgent.setRuleSelector(rule.id,selector,ruleSelectorChanged.bind(this));return result.promise;} changeStyleText(style,text,callback) {if(!style.ownerStyleSheet||!style.styleSheetTextRange){callback();return;} text=text||"";let didSetStyleText=(error,stylePayload)=>{if(error){callback(error);return;} callback();if(style.ownerRule&&!style.ownerRule.matchedSelectorIndices.length) this._parseStyleDeclarationPayload(stylePayload,this._node,false,null,style.type,style.ownerRule,false);this.refresh();};let target=WI.assumingMainTarget();target.CSSAgent.setStyleText(style.id,text,didSetStyleText);} _parseSourceRangePayload(payload) {if(!payload) return null;return new WI.TextRange(payload.startLine,payload.startColumn,payload.endLine,payload.endColumn);} _parseStylePropertyPayload(payload,index,styleDeclaration) {var text=payload.text||"";var name=payload.name;var value=payload.value||"";var priority=payload.priority||"";let range=payload.range||null;var enabled=true;var overridden=false;var implicit=payload.implicit||false;var anonymous=false;var valid="parsedOk"in payload?payload.parsedOk:true;switch(payload.status||"style"){case"active":enabled=true;break;case"inactive":overridden=true;enabled=true;break;case"disabled":enabled=false;break;case"style":anonymous=true;break;} if(range){let rangeLineCount=1+range.endLine-range.startLine;if(rangeLineCount>1){let textLineCount=text.lineCount;if(textLineCount===rangeLineCount-1){range.endLine=range.startLine+(textLineCount-1);range.endColumn=range.startColumn+text.lastLine.length;}}} var styleSheetTextRange=this._parseSourceRangePayload(payload.range);if(styleDeclaration){var property=isNaN(index)?styleDeclaration.propertyForName(name):styleDeclaration.properties[index]; if(property&&property.name===name&&(property.index===index||(isNaN(property.index)&&isNaN(index)))){property.update(text,name,value,priority,enabled,overridden,implicit,anonymous,valid,styleSheetTextRange);return property;} var pendingProperties=styleDeclaration.pendingProperties;for(var i=0;i{let ruleId=grouping.ruleId;let ruleIdForMap=null;if(ruleId){ruleIdForMap=`${ruleId.styleSheetId}-${ruleId.ordinal}`;let existingGroupingForRuleId=this._groupingsMap.get(ruleIdForMap);if(existingGroupingForRuleId){return existingGroupingForRuleId;}} let groupingType=WI.CSSManager.protocolGroupingTypeToEnum(grouping.type||grouping.source);let location={};if(payload.range){location.line=payload.range.startLine;location.column=payload.range.startColumn;location.documentNode=this._node.ownerDocument;} let groupingStyleSheet=ruleId?WI.cssManager.styleSheetForIdentifier(ruleId.styleSheetId):null;let groupingSourceCodeLocation=WI.DOMNodeStyles.createSourceCodeLocation(grouping.sourceURL,location);let offsetGroupingSourceCodeLocation=styleSheet?.offsetSourceCodeLocation(groupingSourceCodeLocation)??groupingSourceCodeLocation;let cssGrouping=new WI.CSSGrouping(this,groupingType,{ownerStyleSheet:groupingStyleSheet,id:grouping.ruleId,text:grouping.text,sourceCodeLocation:offsetGroupingSourceCodeLocation,});if(ruleIdForMap) this._groupingsMap.set(ruleIdForMap,cssGrouping);return cssGrouping;});if(rule){rule.update(sourceCodeLocation,selectorText,selectors,matchedSelectorIndices,style,groupings);return rule;} if(styleSheet) this._trackedStyleSheets.add(styleSheet);rule=new WI.CSSRule(this,styleSheet,id,type,sourceCodeLocation,selectorText,selectors,matchedSelectorIndices,style,groupings,payload.isImplicitlyNested);if(mapKey) this._rulesMap.set(mapKey,rule);return rule;} _markAsNeedsRefresh() {this._needsRefresh=true;this.dispatchEventToListeners(WI.DOMNodeStyles.Event.NeedsRefresh);} _handleCSSStyleSheetContentDidChange(event) {let styleSheet=event.target;if(!this._trackedStyleSheets.has(styleSheet)) return;if(styleSheet===this._ignoreNextContentDidChangeForStyleSheet){this._ignoreNextContentDidChangeForStyleSheet=null;return;} this._markAsNeedsRefresh();} _updateStyleCascade() {var cascadeOrderedStyleDeclarations=this._collectStylesInCascadeOrder(this._matchedRules,this._inlineStyle,this._attributesStyle);for(var i=0;iproperty.index;let propertyStyleIndex=styles.indexOf(property.ownerStyle);let shorthandStyleIndex=styles.indexOf(shorthand.ownerStyle);return shorthandStyleIndex>propertyStyleIndex;} for(var i=0;i{return style.enabledProperties.some((property)=>property.name===propertyName);});}};WI.DOMNodeStyles.Event={NeedsRefresh:"dom-node-styles-needs-refresh",Refreshed:"dom-node-styles-refreshed"};WI.DOMSearchMatchObject=class DOMSearchMatchObject {constructor(resource,domNode,title,searchTerm,textRange) {this._resource=resource;this._domNode=domNode;this._title=title;this._searchTerm=searchTerm;this._textRange=textRange;this._sourceCodeTextRange=null;} static titleForDOMNode(domNode) {switch(domNode.nodeType()){case Node.ELEMENT_NODE:var title="<"+domNode.nodeNameInCorrectCase();for(var attribute of domNode.attributes()){title+=" "+attribute.name;if(attribute.value.length) title+="=\""+attribute.value+"\"";} return title+">";case Node.TEXT_NODE:return"\""+domNode.nodeValue()+"\"";case Node.COMMENT_NODE:return"";case Node.DOCUMENT_TYPE_NODE:var title="";case Node.CDATA_SECTION_NODE:return"";case Node.PROCESSING_INSTRUCTION_NODE:var data=domNode.nodeValue();var dataString=data.length?" "+data:"";var title="";return title;default:console.error("Unknown DOM node type: ",domNode.nodeType());return domNode.nodeNameInCorrectCase();}} get textRange(){return this._textRange;} get resource() {return this._resource;} get domNode() {return this._domNode;} get title() {return this._title;} get className() {if(!this._className) this._className=this._generateClassName();return this._className;} get searchTerm() {return this._searchTerm;} get sourceCodeTextRange() {this._sourceCodeTextRange??=this._resource.createSourceCodeTextRange(this._textRange);return this._sourceCodeTextRange;} saveIdentityToCookie(cookie) {cookie[WI.DOMSearchMatchObject.URLCookieKey]=this._resource.url.hash;cookie[WI.DOMSearchMatchObject.TitleKey]=this._title;cookie[WI.DOMSearchMatchObject.TextRangeKey]=[this._textRange.startLine,this._textRange.startColumn,this._textRange.endLine,this._textRange.endColumn].join();} _generateClassName() {switch(this._domNode.nodeType()){case Node.ELEMENT_NODE:return WI.DOMSearchMatchObject.DOMMatchElementIconStyleClassName;case Node.TEXT_NODE:return WI.DOMSearchMatchObject.DOMMatchTextNodeIconStyleClassName;case Node.COMMENT_NODE:return WI.DOMSearchMatchObject.DOMMatchCommentIconStyleClassName;case Node.DOCUMENT_TYPE_NODE:return WI.DOMSearchMatchObject.DOMMatchDocumentTypeIconStyleClassName;case Node.CDATA_SECTION_NODE:return WI.DOMSearchMatchObject.DOMMatchCharacterDataIconStyleClassName;case Node.PROCESSING_INSTRUCTION_NODE: return WI.DOMSearchMatchObject.DOMMatchDocumentTypeIconStyleClassName;default:console.error("Unknown DOM node type: ",this._domNode.nodeType());return WI.DOMSearchMatchObject.DOMMatchNodeIconStyleClassName;}}};WI.DOMSearchMatchObject.DOMMatchElementIconStyleClassName="dom-match-element-icon";WI.DOMSearchMatchObject.DOMMatchTextNodeIconStyleClassName="dom-match-text-node-icon";WI.DOMSearchMatchObject.DOMMatchCommentIconStyleClassName="dom-match-comment-icon";WI.DOMSearchMatchObject.DOMMatchDocumentTypeIconStyleClassName="dom-match-document-type-icon";WI.DOMSearchMatchObject.DOMMatchCharacterDataIconStyleClassName="dom-match-character-data-icon";WI.DOMSearchMatchObject.DOMMatchNodeIconStyleClassName="dom-match-node-icon";WI.DOMSearchMatchObject.TypeIdentifier="dom-search-match-object";WI.DOMSearchMatchObject.URLCookieKey="resource-url";WI.DOMSearchMatchObject.TitleKey="title";WI.DOMSearchMatchObject.TextRangeKey="text-range";WI.DOMStorageObject=class DOMStorageObject extends WI.Object {constructor(id,host,isLocalStorage) {super();this._id=id;this._host=host;this._isLocalStorage=isLocalStorage;this._entries=new Map;} get id(){return this._id;} get host(){return this._host;} get entries(){return this._entries;} saveIdentityToCookie(cookie) {cookie[WI.DOMStorageObject.HostCookieKey]=this.host;cookie[WI.DOMStorageObject.LocalStorageCookieKey]=this.isLocalStorage();} isLocalStorage() {return this._isLocalStorage;} getEntries(callback) {function innerCallback(error,entries) {if(error) return;for(let[key,value]of entries){if(!key||!value) continue;this._entries.set(key,value);} callback(error,entries);} let target=WI.assumingMainTarget();target.DOMStorageAgent.getDOMStorageItems(this._id,innerCallback.bind(this));} removeItem(key) {let target=WI.assumingMainTarget();return target.DOMStorageAgent.removeDOMStorageItem(this._id,key);} setItem(key,value) {let target=WI.assumingMainTarget();return target.DOMStorageAgent.setDOMStorageItem(this._id,key,value);} clear() {let target=WI.assumingMainTarget();if(!target.hasCommand("DOMStorage.clearDOMStorageItems")){let promises=[];for(let key of this._entries.keys()) promises.push(this.removeItem(key));return Promise.all(promises);} return target.DOMStorageAgent.clearDOMStorageItems(this._id);} itemsCleared() {this._entries.clear();this.dispatchEventToListeners(WI.DOMStorageObject.Event.ItemsCleared);} itemRemoved(key) {let removed=this._entries.delete(key);this.dispatchEventToListeners(WI.DOMStorageObject.Event.ItemRemoved,{key});} itemAdded(key,value) {this._entries.set(key,value);this.dispatchEventToListeners(WI.DOMStorageObject.Event.ItemAdded,{key,value});} itemUpdated(key,oldValue,newValue) {this._entries.set(key,newValue);this.dispatchEventToListeners(WI.DOMStorageObject.Event.ItemUpdated,{key,oldValue,newValue});}};WI.DOMStorageObject.TypeIdentifier="dom-storage";WI.DOMStorageObject.HostCookieKey="dom-storage-object-host";WI.DOMStorageObject.LocalStorageCookieKey="dom-storage-object-local-storage";WI.DOMStorageObject.Event={ItemsCleared:"dom-storage-object-items-cleared",ItemAdded:"dom-storage-object-item-added",ItemRemoved:"dom-storage-object-item-removed",ItemUpdated:"dom-storage-object-updated",};WI.DOMStyleable=class DOMStyleable {constructor(node,{pseudoId}={}) {this._node=node;this._pseudoId=pseudoId||null;} static fromPayload({nodeId,pseudoId}) {return new WI.DOMStyleable(WI.domManager.nodeForId(nodeId),{pseudoId});} get node(){return this._node;} get pseudoId(){return this._pseudoId;} get displayName() {if(this._pseudoId) return WI.CSSManager.displayNameForPseudoId(this._pseudoId);return this._node.displayName;}};WI.DOMTree=class DOMTree extends WI.Object {constructor(frame) {super();this._frame=frame;this._rootDOMNode=null;this._requestIdentifier=0;this._frame.addEventListener(WI.Frame.Event.PageExecutionContextChanged,this._framePageExecutionContextChanged,this);WI.domManager.addEventListener(WI.DOMManager.Event.DocumentUpdated,this._documentUpdated,this);if(!this._frame.isMainFrame()){WI.domManager.addEventListener(WI.DOMManager.Event.NodeRemoved,this._nodeRemoved,this);this._frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._frameMainResourceDidChange,this);}} get frame(){return this._frame;} disconnect() {this._frame.removeEventListener(WI.Frame.Event.PageExecutionContextChanged,this._framePageExecutionContextChanged,this);WI.domManager.removeEventListener(WI.DOMManager.Event.DocumentUpdated,this._documentUpdated,this);if(!this._frame.isMainFrame()){WI.domManager.removeEventListener(WI.DOMManager.Event.NodeRemoved,this._nodeRemoved,this);this._frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._frameMainResourceDidChange,this);}} invalidate() {this._rootDOMNode=null; this._pendingRootDOMNodeRequests=null;if(this._invalidateTimeoutIdentifier) return;function performInvalidate() {this._invalidateTimeoutIdentifier=undefined;this.dispatchEventToListeners(WI.DOMTree.Event.RootDOMNodeInvalidated);} this._invalidateTimeoutIdentifier=setTimeout(performInvalidate.bind(this),0);} requestRootDOMNode(callback) {if(typeof callback!=="function") return;if(this._rootDOMNode){callback(this._rootDOMNode);return;} if(!this._frame.isMainFrame()&&!this._frame.pageExecutionContext){this._rootDOMNodeRequestWaitingForExecutionContext=true;if(!this._pendingRootDOMNodeRequests) this._pendingRootDOMNodeRequests=[];this._pendingRootDOMNodeRequests.push(callback);return;} if(this._pendingRootDOMNodeRequests){this._pendingRootDOMNodeRequests.push(callback);return;} this._pendingRootDOMNodeRequests=[callback];this._requestRootDOMNode();} _requestRootDOMNode() {var requestIdentifier=++this._requestIdentifier;function rootObjectAvailable(error,result) {if(!this._pendingRootDOMNodeRequests||requestIdentifier!==this._requestIdentifier) return;if(error){console.error(JSON.stringify(error));this._rootDOMNode=null;dispatchCallbacks.call(this);return;} var remoteObject=WI.RemoteObject.fromPayload(result);remoteObject.pushNodeToFrontend(rootDOMNodeAvailable.bind(this,remoteObject));} function rootDOMNodeAvailable(remoteObject,nodeId) {remoteObject.release();if(!this._pendingRootDOMNodeRequests||requestIdentifier!==this._requestIdentifier) return;if(!nodeId){this._rootDOMNode=null;dispatchCallbacks.call(this);return;} this._rootDOMNode=WI.domManager.nodeForId(nodeId);if(!this._rootDOMNode){dispatchCallbacks.call(this);return;} this._rootDOMNode.getChildNodes(dispatchCallbacks.bind(this));} function mainDocumentAvailable(document) {this._rootDOMNode=document;dispatchCallbacks.call(this);} function dispatchCallbacks() {if(!this._pendingRootDOMNodeRequests||requestIdentifier!==this._requestIdentifier) return;for(var i=0;iWI.BreakpointAction.fromJSON(actionJSON))||[],ignoreCount:json.ignoreCount,autoContinue:json.autoContinue,});} get type(){return this._type;} get eventName(){return this._eventName;} get caseSensitive(){return this._caseSensitive;} get isRegex(){return this._isRegex;} get eventListener(){return this._eventListener;} get displayName() {switch(this){case WI.domDebuggerManager.allAnimationFramesBreakpoint:return WI.repeatedUIString.allAnimationFrames();case WI.domDebuggerManager.allIntervalsBreakpoint:return WI.repeatedUIString.allIntervals();case WI.domDebuggerManager.allListenersBreakpoint:return WI.repeatedUIString.allEvents();case WI.domDebuggerManager.allTimeoutsBreakpoint:return WI.repeatedUIString.allTimeouts();} if(this._isRegex) return"/"+this._eventName+"/"+(!this._caseSensitive?"i":"");let displayName=this._eventName;if(!this._caseSensitive) displayName=WI.UIString("%s (Case Insensitive)","%s (Case Insensitive) @ EventBreakpoint","Label for case-insensitive match pattern of an event breakpoint.").format(displayName);return displayName;} get special() {switch(this){case WI.domDebuggerManager.allAnimationFramesBreakpoint:case WI.domDebuggerManager.allIntervalsBreakpoint:case WI.domDebuggerManager.allListenersBreakpoint:case WI.domDebuggerManager.allTimeoutsBreakpoint:return true;} return super.special;} get editable() {if(this._eventListener){return InspectorBackend.hasCommand("DOM.setBreakpointForEventListener","options");} return WI.EventBreakpoint.supportsEditing||super.editable;} matches(eventName) {if(!eventName||this.disabled) return false;if(this._isRegex) return(new RegExp(this._eventName,!this._caseSensitive?"i":"")).test(eventName);if(!this._caseSensitive) return eventName.toLowerCase()===this._eventName.toLowerCase();return eventName===this._eventName;} equals(other) {return this._eventName===other.eventName&&this._caseSensitive===other.caseSensitive&&this._isRegex===other.isRegex;} remove() {super.remove();if(this._eventListener) WI.domManager.removeBreakpointForEventListener(this._eventListener);else WI.domDebuggerManager.removeEventBreakpoint(this);} saveIdentityToCookie(cookie) {cookie["event-breakpoint-type"]=this._type;if(this._eventName){cookie["event-breakpoint-event-name"]=this._eventName;cookie["event-breakpoint-case-sensitive"]=this._caseSensitive;cookie["event-breakpoint-is-regex"]=this._isRegex;} if(this._eventListener) cookie["event-breakpoint-event-listener"]=this._eventListener.eventListenerId;} toJSON(key) {let json=super.toJSON(key);json.type=this._type;if(this._eventName){json.eventName=this._eventName;json.caseSensitive=this._caseSensitive;json.isRegex=this._isRegex;} if(key===WI.ObjectStore.toJSONSymbol) json[WI.objectStores.eventBreakpoints.keyPath]=this._type+(this._eventName?":"+this._eventName+"-"+this._caseSensitive+"-"+this._isRegex:"");return json;}};WI.EventBreakpoint.Type={AnimationFrame:"animation-frame",Interval:"interval",Listener:"listener",Timeout:"timeout",};WI.EventBreakpoint.ReferencePage=WI.ReferencePage.EventBreakpoints;WI.ExecutionContext=class ExecutionContext {constructor(target,id,type,name,frame) {this._target=target;this._id=id;this._type=type||WI.ExecutionContext.Type.Internal;this._name=name||"";this._frame=frame||null;} static typeFromPayload(payload) {if(!("type"in payload)) return payload.isPageContext?WI.ExecutionContext.Type.Normal:WI.ExecutionContext.Type.Internal;switch(payload.type){case InspectorBackend.Enum.Runtime.ExecutionContextType.Normal:return WI.ExecutionContext.Type.Normal;case InspectorBackend.Enum.Runtime.ExecutionContextType.User:return WI.ExecutionContext.Type.User;case InspectorBackend.Enum.Runtime.ExecutionContextType.Internal:return WI.ExecutionContext.Type.Internal;} return WI.ExecutionContext.Type.Internal;} get target(){return this._target;} get id(){return this._id;} get type(){return this._type;} get name(){return this._name;} get frame(){return this._frame;}};WI.ExecutionContext.Type={Normal:"normal",User:"user",Internal:"internal",};WI.ExecutionContextList=class ExecutionContextList {constructor() {this._contexts=[];this._pageExecutionContext=null;} get pageExecutionContext() {return this._pageExecutionContext;} get contexts() {return this._contexts;} add(context) {if(context.type===WI.ExecutionContext.Type.Normal&&this._pageExecutionContext){return;} this._contexts.push(context);if(context.type===WI.ExecutionContext.Type.Normal&&context.target.type===WI.TargetType.Page){this._pageExecutionContext=context;}} clear() {this._contexts=[];this._pageExecutionContext=null;}};WI.FPSInstrument=class FPSInstrument extends WI.Instrument { get timelineRecordType() {return WI.TimelineRecord.Type.RenderingFrame;}};WI.Font=class Font {constructor(name,variationAxes,{synthesizedBold,synthesizedOblique}={}) {this._name=name;this._variationAxes=variationAxes;this._synthesizedBold=!!synthesizedBold;this._synthesizedOblique=!!synthesizedOblique;} static fromPayload(payload) {let variationAxes=payload.variationAxes.map((axisPayload)=>WI.FontVariationAxis.fromPayload(axisPayload));let synthesizedBold=payload.synthesizedBold;let synthesizedOblique=payload.synthesizedOblique;return new WI.Font(payload.displayName,variationAxes,{synthesizedBold,synthesizedOblique});} get name(){return this._name;} get variationAxes(){return this._variationAxes;} get synthesizedBold(){return this._synthesizedBold;} get synthesizedOblique(){return this._synthesizedOblique;} variationAxis(tag) {return this._variationAxes.find((axis)=>axis.tag===tag);}};WI.FontStyles=class FontStyles {constructor(nodeStyles) {this._nodeStyles=nodeStyles;this._featuresMap=new Map;this._variationsMap=new Map;this._propertiesMap=new Map;this._authoredFontVariationSettingsMap=new Map;this._effectiveWritablePropertyForNameMap=new Map;this._significantChangeSinceLastRefresh=true;this._variationAxesTags=[];this._registeredAxesTags=[];const forceSignificantChange=true;this.refresh(forceSignificantChange);} get featuresMap(){return this._featuresMap;} get variationsMap(){return this._variationsMap;} get propertiesMap(){return this._propertiesMap;} get significantChangeSinceLastRefresh(){return this._significantChangeSinceLastRefresh;} static fontPropertyForAxisTag(tag){const tagToPropertyMap={"wght":"font-weight","wdth":"font-stretch","slnt":"font-style","ital":"font-style",} return tagToPropertyMap[tag];} static axisValueToFontPropertyValue(tag,value) {switch(tag){case"wdth":return`${value}%`;case"slnt":return`oblique ${value}deg`;case"ital":return value>=1?"italic":"normal";default:return String(value);}} static fontPropertyValueToAxisValue(tag,value) {switch(tag){case"wdth":return parseFloat(value);case"ital":case"slnt": const obliqueAngleDefaultValue=14;if(value==="normal") return 0;if(tag==="ital"&&(value==="oblique"||value==="italic")) return 1;if(tag==="slnt"&&(value==="oblique"||value==="italic")) return obliqueAngleDefaultValue;let degrees=value.match(/oblique (?-?\d+(\.\d+)?)deg/)?.groups?.degrees;if(degrees&&tag==="ital") return parseFloat(degrees)>=obliqueAngleDefaultValue?1:0;if(degrees&&tag==="slnt") return parseFloat(degrees);break;default:return parseFloat(value);}} writeFontVariation(tag,value) {let targetPropertyName=WI.FontStyles.fontPropertyForAxisTag(tag);let targetPropertyValue;if(targetPropertyName&&!this._authoredFontVariationSettingsMap.has(tag)) targetPropertyValue=WI.FontStyles.axisValueToFontPropertyValue(tag,value);else{this._authoredFontVariationSettingsMap.set(tag,value);let axes=[];for(let[tag,value]of this._authoredFontVariationSettingsMap){axes.push(`"${tag}" ${value}`);} targetPropertyName="font-variation-settings";targetPropertyValue=axes.join(", ");} const createIfMissing=true;let cssProperty=this._effectiveWritablePropertyForName(targetPropertyName,createIfMissing);cssProperty.rawValue=targetPropertyValue;} refresh(forceSignificantChange) {this._effectiveWritablePropertyForNameMap.clear();let prevVariationAxisTags=this._variationAxesTags.slice();let prevRegisteredAxisTags=this._registeredAxesTags.slice();this._variationAxesTags=[];this._registeredAxesTags=[];this._calculateFontProperties();if(forceSignificantChange) this._significantChangeSinceLastRefresh=true;else this._significantChangeSinceLastRefresh=!Array.shallowEqual(prevRegisteredAxisTags,this._registeredAxesTags)||!Array.shallowEqual(prevVariationAxisTags,this._variationAxesTags);} _calculateFontProperties() {this._featuresMap=this._calculateFontFeatureAxes(this._nodeStyles);this._variationsMap=this._calculateFontVariationAxes(this._nodeStyles);this._propertiesMap=this._calculateProperties({domNodeStyle:this._nodeStyles,featuresMap:this._featuresMap,variationsMap:this._variationsMap});} _calculateProperties(style) {let resultProperties=new Map;this._populateProperty("font-size",style,resultProperties,{keywordComputedReplacements:["larger","smaller","xx-small","x-small","small","medium","large","x-large","xx-large","xxx-large"],});this._populateProperty("font-style",style,resultProperties,{variations:["ital","slnt"],keywordReplacements:new Map([["oblique","oblique 14deg"],]),});this._populateProperty("font-weight",style,resultProperties,{variations:["wght"],keywordComputedReplacements:["bolder","lighter"],keywordReplacements:new Map([["normal","400"],["bold","700"],]),});this._populateProperty("font-stretch",style,resultProperties,{variations:["wdth"],keywordReplacements:new Map([["ultra-condensed","50%"],["extra-condensed","62.5%"],["condensed","75%"],["semi-condensed","87.5%"],["normal","100%"],["semi-expanded","112.5%"],["expanded","125%"],["extra-expanded","150%"],["ultra-expanded","200%"],]),});this._populateProperty("font-variant-ligatures",style,resultProperties,{features:["liga","clig","dlig","hlig","calt"]});this._populateProperty("font-variant-position",style,resultProperties,{features:["subs","sups"]});this._populateProperty("font-variant-caps",style,resultProperties,{features:["smcp","c2sc","pcap","c2pc","unic","titl"]});this._populateProperty("font-variant-numeric",style,resultProperties,{features:["lnum","onum","pnum","tnum","frac","afrc","ordn","zero"]});this._populateProperty("font-variant-alternates",style,resultProperties,{features:["hist"]});this._populateProperty("font-variant-east-asian",style,resultProperties,{features:["jp78","jp83","jp90","jp04","smpl","trad","fwid","pwid","ruby"]});return resultProperties;} _calculateFontFeatureAxes(domNodeStyle) {return this._parseFontFeatureOrVariationSettings(domNodeStyle,"font-feature-settings");} _calculateFontVariationAxes(domNodeStyle) {this._authoredFontVariationSettingsMap=this._parseFontFeatureOrVariationSettings(domNodeStyle,"font-variation-settings");let resultAxes=new Map;if(!this._nodeStyles.computedPrimaryFont) return resultAxes;for(let axis of this._nodeStyles.computedPrimaryFont.variationAxes){resultAxes.set(axis.tag,{tag:axis.tag,name:axis.name,minimumValue:axis.minimumValue,maximumValue:axis.maximumValue,defaultValue:axis.defaultValue,value:this._authoredFontVariationSettingsMap.get(axis.tag),});this._variationAxesTags.push(axis.tag);} return resultAxes;} _parseFontFeatureOrVariationSettings(domNodeStyle,property) {let cssSettings=new Map;let cssSettingsRawValue=this._computedPropertyValueForName(domNodeStyle,property);if(cssSettingsRawValue!=="normal"){for(let axis of cssSettingsRawValue.split(",")){let[tag,value]=axis.match(WI.FontStyles.SettingPattern);tag=tag.replaceAll(/["']/g,"");if(!value||value==="on") value=1;else if(value==="off") value=0;cssSettings.set(tag,parseFloat(value));}} return cssSettings;} _populateProperty(name,style,resultProperties,{variations,features,keywordComputedReplacements,keywordReplacements}) {resultProperties.set(name,this._computeProperty(name,style,{variations,features,keywordComputedReplacements,keywordReplacements}));} _computeProperty(name,style,{variations,features,keywordComputedReplacements,keywordReplacements}) {variations??=[];features??=[];keywordComputedReplacements??=[];keywordReplacements??=new Map;let resultProperties={};let value=this._effectivePropertyValueForName(style.domNodeStyle,name);if(!value||value==="inherit"||keywordComputedReplacements.includes(value)) value=this._computedPropertyValueForName(style.domNodeStyle,name);if(keywordReplacements.has(value)) value=keywordReplacements.get(value);resultProperties.value=value;for(let fontVariationTag of variations){let fontVariationAxis=style.variationsMap.get(fontVariationTag);if(fontVariationAxis){resultProperties.variations??=new Map;resultProperties.variations.set(fontVariationTag,fontVariationAxis);style.variationsMap.delete(fontVariationTag);this._registeredAxesTags.push(fontVariationTag);}} for(let fontFeatureSetting of features){let featureSettingValue=style.featuresMap.get(fontFeatureSetting);if(featureSettingValue||featureSettingValue===0){resultProperties.features??=new Map;resultProperties.features.set(fontFeatureSetting,featureSettingValue);style.featuresMap.delete(fontFeatureSetting);}} return resultProperties;} _effectivePropertyValueForName(domNodeStyle,name) {return domNodeStyle.effectivePropertyForName(name)?.value||"";} _effectiveWritablePropertyForName(name,createIfMissing) {let cssProperty=this._effectiveWritablePropertyForNameMap.get(name);if(cssProperty) return cssProperty; let inlineCSSStyleDeclaration=this._nodeStyles.inlineStyle;let properties=inlineCSSStyleDeclaration.visibleProperties;cssProperty=properties.find(property=>property.name===name);if(!cssProperty&&createIfMissing){cssProperty=inlineCSSStyleDeclaration.newBlankProperty(properties.length);cssProperty.name=name;} if(cssProperty) this._effectiveWritablePropertyForNameMap.set(name,cssProperty);return cssProperty;} _computedPropertyValueForName(domNodeStyle,name) {return domNodeStyle.computedStyle?.propertyForName(name)?.value||"";}};WI.FontStyles.SettingPattern=/[^\s"']+|["']([^"']*)["']/g;WI.FontVariationAxis=class FontVariationAxis {constructor(name,tag,minimumValue,maximumValue,defaultValue) {this._name=name;this._tag=tag;this._minimumValue=minimumValue;this._maximumValue=maximumValue;this._defaultValue=defaultValue;} static fromPayload(payload) {return new WI.FontVariationAxis(payload.name,payload.tag,payload.minimumValue,payload.maximumValue,payload.defaultValue);} get name(){return this._name;} get tag(){return this._tag;} get minimumValue(){return this._minimumValue;} get maximumValue(){return this._maximumValue;} get defaultValue(){return this._defaultValue;}};WI.Frame=class Frame extends WI.Object {constructor(id,name,securityOrigin,loaderIdentifier,mainResource) {super();this._id=id;this._name=null;this._securityOrigin=null;this._resourceCollection=new WI.ResourceCollection;this._provisionalResourceCollection=new WI.ResourceCollection;this._extraScriptCollection=new WI.ScriptCollection;this._childFrameCollection=new WI.FrameCollection;this._childFrameIdentifierMap=new Map;this._parentFrame=null;this._isMainFrame=false;this._domContentReadyEventTimestamp=NaN;this._loadEventTimestamp=NaN;this._executionContextList=new WI.ExecutionContextList;this.initialize(name,securityOrigin,loaderIdentifier,mainResource);} get resourceCollection(){return this._resourceCollection;} get extraScriptCollection(){return this._extraScriptCollection;} get childFrameCollection(){return this._childFrameCollection;} initialize(name,securityOrigin,loaderIdentifier,mainResource) {var oldName=this._name;var oldSecurityOrigin=this._securityOrigin;var oldMainResource=this._mainResource;this._name=name||null;this._securityOrigin=securityOrigin||null;this._loaderIdentifier=loaderIdentifier||null;this._mainResource=mainResource;this._mainResource._parentFrame=this;if(oldMainResource&&this._mainResource!==oldMainResource) this._disassociateWithResource(oldMainResource);this.removeAllResources();this.removeAllChildFrames();this.clearExecutionContexts();this.clearProvisionalLoad();if(this._mainResource!==oldMainResource) this._dispatchMainResourceDidChangeEvent(oldMainResource);if(this._securityOrigin!==oldSecurityOrigin) this.dispatchEventToListeners(WI.Frame.Event.SecurityOriginDidChange,{oldSecurityOrigin});if(this._name!==oldName) this.dispatchEventToListeners(WI.Frame.Event.NameDidChange,{oldName});} startProvisionalLoad(provisionalMainResource) {this._provisionalMainResource=provisionalMainResource;this._provisionalMainResource._parentFrame=this;this._provisionalLoaderIdentifier=provisionalMainResource.loaderIdentifier;this._provisionalResourceCollection.clear();this.dispatchEventToListeners(WI.Frame.Event.ProvisionalLoadStarted);} commitProvisionalLoad(securityOrigin) {if(!this._provisionalLoaderIdentifier) return;var oldSecurityOrigin=this._securityOrigin;var oldMainResource=this._mainResource;this._securityOrigin=securityOrigin||null;this._loaderIdentifier=this._provisionalLoaderIdentifier;this._mainResource=this._provisionalMainResource;this._domContentReadyEventTimestamp=NaN;this._loadEventTimestamp=NaN;if(oldMainResource&&this._mainResource!==oldMainResource) this._disassociateWithResource(oldMainResource);this.removeAllResources();this._resourceCollection=this._provisionalResourceCollection;this._provisionalResourceCollection=new WI.ResourceCollection;this._extraScriptCollection.clear();this.clearExecutionContexts(true);this.clearProvisionalLoad(true);this.removeAllChildFrames();this.dispatchEventToListeners(WI.Frame.Event.ProvisionalLoadCommitted);if(this._mainResource!==oldMainResource) this._dispatchMainResourceDidChangeEvent(oldMainResource);if(this._securityOrigin!==oldSecurityOrigin) this.dispatchEventToListeners(WI.Frame.Event.SecurityOriginDidChange,{oldSecurityOrigin});} clearProvisionalLoad(skipProvisionalLoadClearedEvent) {if(!this._provisionalLoaderIdentifier) return;this._provisionalLoaderIdentifier=null;this._provisionalMainResource=null;this._provisionalResourceCollection.clear();if(!skipProvisionalLoadClearedEvent) this.dispatchEventToListeners(WI.Frame.Event.ProvisionalLoadCleared);} get id() {return this._id;} get loaderIdentifier() {return this._loaderIdentifier;} get provisionalLoaderIdentifier() {return this._provisionalLoaderIdentifier;} get name() {return this._name;} get securityOrigin() {return this._securityOrigin;} get url() {return this._mainResource.url;} get urlComponents() {return this._mainResource.urlComponents;} get domTree() {if(!this._domTree) this._domTree=new WI.DOMTree(this);return this._domTree;} get pageExecutionContext() {return this._executionContextList.pageExecutionContext;} get executionContextList() {return this._executionContextList;} clearExecutionContexts(committingProvisionalLoad) {if(this._executionContextList.contexts.length){let contexts=this._executionContextList.contexts.slice();this._executionContextList.clear();this.dispatchEventToListeners(WI.Frame.Event.ExecutionContextsCleared,{committingProvisionalLoad:!!committingProvisionalLoad,contexts});}} addExecutionContext(context) {this._executionContextList.add(context);this.dispatchEventToListeners(WI.Frame.Event.ExecutionContextAdded,{context});if(this._executionContextList.pageExecutionContext===context) this.dispatchEventToListeners(WI.Frame.Event.PageExecutionContextChanged);} get mainResource() {return this._mainResource;} get provisionalMainResource() {return this._provisionalMainResource;} get parentFrame() {return this._parentFrame;} get domContentReadyEventTimestamp() {return this._domContentReadyEventTimestamp;} get loadEventTimestamp() {return this._loadEventTimestamp;} isMainFrame() {return this._isMainFrame;} markAsMainFrame() {this._isMainFrame=true;} unmarkAsMainFrame() {this._isMainFrame=false;} markDOMContentReadyEvent(timestamp) {this._domContentReadyEventTimestamp=timestamp||NaN;} markLoadEvent(timestamp) {this._loadEventTimestamp=timestamp||NaN;} isDetached() {var frame=this;while(frame){if(frame.isMainFrame()) return false;frame=frame.parentFrame;} return true;} childFrameForIdentifier(frameId) {return this._childFrameIdentifierMap.get(frameId)||null;} addChildFrame(frame) {if(!(frame instanceof WI.Frame)) return;if(frame._parentFrame===this) return;if(frame._parentFrame) frame._parentFrame.removeChildFrame(frame);this._childFrameCollection.add(frame);this._childFrameIdentifierMap.set(frame._id,frame);frame._parentFrame=this;this.dispatchEventToListeners(WI.Frame.Event.ChildFrameWasAdded,{childFrame:frame});} removeChildFrame(frameOrFrameId) {let childFrameId=frameOrFrameId;if(childFrameId instanceof WI.Frame) childFrameId=frameOrFrameId._id; let childFrame=this.childFrameForIdentifier(childFrameId);if(!(childFrame instanceof WI.Frame)) return;this._childFrameCollection.remove(childFrame);this._childFrameIdentifierMap.delete(childFrame._id);childFrame._detachFromParentFrame();this.dispatchEventToListeners(WI.Frame.Event.ChildFrameWasRemoved,{childFrame});} removeAllChildFrames() {this._detachFromParentFrame();for(let childFrame of this._childFrameCollection) childFrame.removeAllChildFrames();this._childFrameCollection.clear();this._childFrameIdentifierMap.clear();this.dispatchEventToListeners(WI.Frame.Event.AllChildFramesRemoved);} resourcesForURL(url,recursivelySearchChildFrames) {let resources=this._resourceCollection.resourcesForURL(url);for(let childFrame of this._childFrameCollection){if(childFrame.mainResource.url===url) resources.add(childFrame.mainResource);} if(recursivelySearchChildFrames){for(let childFrame of this._childFrameCollection) resources.addAll(childFrame.resourcesForURL(url,recursivelySearchChildFrames));} return resources;} resourceCollectionForType(type) {return this._resourceCollection.resourceCollectionForType(type);} addResource(resource) {if(!(resource instanceof WI.Resource)) return;if(resource.parentFrame===this) return;if(resource.parentFrame) resource.parentFrame.remove(resource);this._associateWithResource(resource);if(this._isProvisionalResource(resource)){this._provisionalResourceCollection.add(resource);this.dispatchEventToListeners(WI.Frame.Event.ProvisionalResourceWasAdded,{resource});}else{this._resourceCollection.add(resource);this.dispatchEventToListeners(WI.Frame.Event.ResourceWasAdded,{resource});}} removeResource(resource) {this._resourceCollection.remove(resource);this._disassociateWithResource(resource);this.dispatchEventToListeners(WI.Frame.Event.ResourceWasRemoved,{resource});} removeAllResources() {if(!this._resourceCollection.size) return;for(let resource of this._resourceCollection) this._disassociateWithResource(resource);this._resourceCollection.clear();this.dispatchEventToListeners(WI.Frame.Event.AllResourcesRemoved);} addExtraScript(script) {this._extraScriptCollection.add(script);this.dispatchEventToListeners(WI.Frame.Event.ExtraScriptAdded,{script});} saveIdentityToCookie(cookie) {cookie[WI.Frame.MainResourceURLCookieKey]=this.mainResource.url.hash;cookie[WI.Frame.IsMainFrameCookieKey]=this._isMainFrame;} _detachFromParentFrame() {if(this._domTree){this._domTree.disconnect();this._domTree=null;} this._parentFrame=null;} _isProvisionalResource(resource) {return resource.loaderIdentifier&&this._provisionalLoaderIdentifier&&resource.loaderIdentifier===this._provisionalLoaderIdentifier;} _associateWithResource(resource) {if(resource._parentFrame) return;resource._parentFrame=this;} _disassociateWithResource(resource) {if(resource.parentFrame!==this) return;resource._parentFrame=null;} _dispatchMainResourceDidChangeEvent(oldMainResource) {this.dispatchEventToListeners(WI.Frame.Event.MainResourceDidChange,{oldMainResource});}};WI.Frame.Event={NameDidChange:"frame-name-did-change",SecurityOriginDidChange:"frame-security-origin-did-change",MainResourceDidChange:"frame-main-resource-did-change",ProvisionalLoadStarted:"frame-provisional-load-started",ProvisionalLoadCommitted:"frame-provisional-load-committed",ProvisionalLoadCleared:"frame-provisional-load-cleared",ProvisionalResourceWasAdded:"frame-provisional-resource-was-added",ResourceWasAdded:"frame-resource-was-added",ResourceWasRemoved:"frame-resource-was-removed",AllResourcesRemoved:"frame-all-resources-removed",ExtraScriptAdded:"frame-extra-script-added",ChildFrameWasAdded:"frame-child-frame-was-added",ChildFrameWasRemoved:"frame-child-frame-was-removed",AllChildFramesRemoved:"frame-all-child-frames-removed",PageExecutionContextChanged:"frame-page-execution-context-changed",ExecutionContextAdded:"frame-execution-context-added",ExecutionContextsCleared:"frame-execution-contexts-cleared"};WI.Frame.TypeIdentifier="Frame";WI.Frame.MainResourceURLCookieKey="frame-main-resource-url";WI.Frame.IsMainFrameCookieKey="frame-is-main-frame";WI.GarbageCollection=class GarbageCollection {constructor(type,startTime,endTime) {this._type=type;this._startTime=startTime;this._endTime=endTime;} static fromPayload(payload) {let type=WI.GarbageCollection.Type.Full;if(payload.type===InspectorBackend.Enum.Heap.GarbageCollectionType.Partial) type=WI.GarbageCollection.Type.Partial;return new WI.GarbageCollection(type,payload.startTime,payload.endTime);} static fromJSON(json) {let{type,startTime,endTime}=json;return new WI.GarbageCollection(type,startTime,endTime);} toJSON() {return{__type:"GarbageCollection",type:this.type,startTime:this.startTime,endTime:this.endTime,};} get type(){return this._type;} get startTime(){return this._startTime;} get endTime(){return this._endTime;} get duration() {return this._endTime-this._startTime;}};WI.GarbageCollection.Type={Partial:"partial",Full:"full",};WI.Point=class Point {constructor(x,y) {this.x=x||0;this.y=y||0;} static fromEvent(event) {return new WI.Point(event.pageX,event.pageY);} static fromEventInElement(event,element) {let rect=element.getBoundingClientRect();return new WI.Point(event.pageX-rect.x,event.pageY-rect.y);} toString() {return"WI.Point["+this.x+","+this.y+"]";} copy() {return new WI.Point(this.x,this.y);} equals(anotherPoint) {return this.x===anotherPoint.x&&this.y===anotherPoint.y;} distance(anotherPoint) {let dx=anotherPoint.x-this.x;let dy=anotherPoint.y-this.y;return Math.sqrt((dx*dx)+(dy*dy));}};WI.Size=class Size {constructor(width,height) {this.width=width||0;this.height=height||0;} static fromJSON(json) {return new WI.Size(json.width,json.height);} toString() {return"WI.Size["+this.width+","+this.height+"]";} copy() {return new WI.Size(this.width,this.height);} equals(anotherSize) {return this.width===anotherSize.width&&this.height===anotherSize.height;}};WI.Size.ZERO_SIZE=new WI.Size(0,0);WI.Rect=class Rect {constructor(x,y,width,height) {this.origin=new WI.Point(x||0,y||0);this.size=new WI.Size(width||0,height||0);} static rectFromClientRect(clientRect) {return new WI.Rect(clientRect.left,clientRect.top,clientRect.width,clientRect.height);} static unionOfRects(rects) {var union=rects[0];for(var i=1;ix2) return WI.Rect.ZERO_RECT;var intersection=new WI.Rect;intersection.origin.x=x1;intersection.size.width=x2-x1;var y1=Math.max(this.minY(),rect.minY());var y2=Math.min(this.maxY(),rect.maxY());if(y1>y2) return WI.Rect.ZERO_RECT;intersection.origin.y=y1;intersection.size.height=y2-y1;return intersection;} unionWithRect(rect) {var x=Math.min(this.minX(),rect.minX());var y=Math.min(this.minY(),rect.minY());var width=Math.max(this.maxX(),rect.maxX())-x;var height=Math.max(this.maxY(),rect.maxY())-y;return new WI.Rect(x,y,width,height);} round() {return new WI.Rect(Math.floor(this.origin.x),Math.floor(this.origin.y),Math.ceil(this.size.width),Math.ceil(this.size.height));}};WI.Rect.ZERO_RECT=new WI.Rect(0,0,0,0);WI.EdgeInsets=class EdgeInsets {constructor(top,right,bottom,left) {if(arguments.length===1){this.top=top;this.right=top;this.bottom=top;this.left=top;}else if(arguments.length===4){this.top=top;this.right=right;this.bottom=bottom;this.left=left;}} equals(anotherInset) {return this.top===anotherInset.top&&this.right===anotherInset.right&&this.bottom===anotherInset.bottom&&this.left===anotherInset.left;} copy() {return new WI.EdgeInsets(this.top,this.right,this.bottom,this.left);}};WI.RectEdge={MIN_X:0,MIN_Y:1,MAX_X:2,MAX_Y:3};WI.Quad=class Quad {constructor(quad) {this.points=[new WI.Point(quad[0],quad[1]), new WI.Point(quad[2],quad[3]), new WI.Point(quad[4],quad[5]), new WI.Point(quad[6],quad[7]) ];this.width=Math.round(Math.sqrt(Math.pow(quad[0]-quad[2],2)+Math.pow(quad[1]-quad[3],2)));this.height=Math.round(Math.sqrt(Math.pow(quad[0]-quad[6],2)+Math.pow(quad[1]-quad[7],2)));} static fromJSON(json) {return new WI.Quad(json);} toJSON() {return this.toProtocol();} toProtocol() {return[this.points[0].x,this.points[0].y,this.points[1].x,this.points[1].y,this.points[2].x,this.points[2].y,this.points[3].x,this.points[3].y];}};WI.Polygon=class Polygon {constructor(points) {this.points=points;} bounds() {var minX=Number.MAX_VALUE;var minY=Number.MAX_VALUE;var maxX=-Number.MAX_VALUE;var maxY=-Number.MAX_VALUE;for(var point of this.points){minX=Math.min(minX,point.x);maxX=Math.max(maxX,point.x);minY=Math.min(minY,point.y);maxY=Math.max(maxY,point.y);} return new WI.Rect(minX,minY,maxX-minX,maxY-minY);}};WI.Gradient=class Gradient {constructor(type,stops) {this.type=type;this.stops=stops;} static angleFromString(string) {let match=string.match(/([-\d\.]+)(\w+)/);if(!match||!Object.values(WI.Gradient.AngleUnits).includes(match[2])) return null;return{value:parseFloat(match[1]),units:match[2]};} static fromString(cssString) {var type;var openingParenthesisIndex=cssString.indexOf("(");var typeString=cssString.substring(0,openingParenthesisIndex);if(typeString.includes(WI.Gradient.Types.Linear)) type=WI.Gradient.Types.Linear;else if(typeString.includes(WI.Gradient.Types.Radial)) type=WI.Gradient.Types.Radial;else if(typeString.includes(WI.Gradient.Types.Conic)) type=WI.Gradient.Types.Conic;else return null;var components=[];var currentParams=[];var currentParam="";var openParentheses=0;var ch=openingParenthesisIndex+1;var c=null;while(c=cssString[ch]){if(c==="(") openParentheses++;if(c===")") openParentheses--;var isComma=c===",";var isSpace=/\s/.test(c);if(openParentheses===0){if(isSpace){if(currentParam!=="") currentParams.push(currentParam);currentParam="";}else if(isComma){currentParams.push(currentParam);components.push(currentParams);currentParams=[];currentParam="";}} if(openParentheses===-1){currentParams.push(currentParam);components.push(currentParams);break;} if(openParentheses>0||(!isComma&&!isSpace)) currentParam+=c;ch++;} if(openParentheses!==-1) return null;let gradient=null;switch(type){case WI.Gradient.Types.Linear:gradient=WI.LinearGradient.fromComponents(components);break;case WI.Gradient.Types.Radial:gradient=WI.RadialGradient.fromComponents(components);break;case WI.Gradient.Types.Conic:gradient=WI.ConicGradient.fromComponents(components);break;} if(gradient) gradient.repeats=typeString.startsWith("repeating");return gradient;} static stopsWithComponents(components) {var stops=components.map(function(component){while(component.length){var color=WI.Color.fromString(component.shift());if(!color) continue;var stop={color};if(component.length&&component[0].substr(-1)==="%") stop.offset=parseFloat(component.shift())/100;return stop;}});if(!stops.length) return null;for(var i=0,count=stops.length;i{let workerProxy=WI.HeapSnapshotWorkerProxy.singleton();workerProxy.createSnapshot(snapshotStringData,({objectId,snapshot:serializedSnapshot})=>{let snapshot=WI.HeapSnapshotProxy.deserialize(objectId,serializedSnapshot);snapshot.snapshotStringData=snapshotStringData;WI.timelineManager.heapSnapshotAdded(timestamp,snapshot);});});}};WI.HeapAllocationsTimelineRecord=class HeapAllocationsTimelineRecord extends WI.TimelineRecord {constructor(timestamp,heapSnapshot) {super(WI.TimelineRecord.Type.HeapAllocations,timestamp,timestamp);this._timestamp=timestamp;this._heapSnapshot=heapSnapshot;} static async fromJSON(json) { let{timestamp,title,snapshotStringData}=json;return await new Promise((resolve,reject)=>{let workerProxy=WI.HeapSnapshotWorkerProxy.singleton();workerProxy.createImportedSnapshot(snapshotStringData,title,({objectId,snapshot:serializedSnapshot})=>{let snapshot=WI.HeapSnapshotProxy.deserialize(objectId,serializedSnapshot);snapshot.snapshotStringData=snapshotStringData;resolve(new WI.HeapAllocationsTimelineRecord(timestamp,snapshot));});});} toJSON() {return{type:this.type,timestamp:this._timestamp,title:WI.TimelineTabContentView.displayNameForRecord(this),snapshotStringData:this._heapSnapshot.snapshotStringData,};} get timestamp(){return this._timestamp;} get heapSnapshot(){return this._heapSnapshot;}};WI.HeapSnapshotRootPath=class HeapSnapshotRootPath {constructor(node,pathComponent,parent,isGlobalScope) {this._node=node||null;this._parent=parent||null;this._pathComponent=typeof pathComponent==="string"?pathComponent:null;this._isGlobalScope=isGlobalScope||false;if(this._parent&&this._parent.isEmpty()) this._parent=null;} static emptyPath() {return new WI.HeapSnapshotRootPath(null);} static pathComponentForIndividualEdge(edge) {switch(edge.type){case WI.HeapSnapshotEdgeProxy.EdgeType.Internal:return null;case WI.HeapSnapshotEdgeProxy.EdgeType.Index:return"["+edge.data+"]";case WI.HeapSnapshotEdgeProxy.EdgeType.Property:case WI.HeapSnapshotEdgeProxy.EdgeType.Variable:if(WI.HeapSnapshotRootPath.canPropertyNameBeDotAccess(edge.data)) return edge.data;return"["+doubleQuotedString(edge.data)+"]";}} static canPropertyNameBeDotAccess(propertyName) {return/^(?![0-9])\w+$/.test(propertyName);} get node(){return this._node;} get parent(){return this._parent;} get pathComponent(){return this._pathComponent;} get rootNode() {return this._parent?this._parent.rootNode:this._node;} get fullPath() {let components=[];for(let p=this;p&&p.pathComponent;p=p.parent) components.push(p.pathComponent);components.reverse();return components.join("");} isRoot() {return!this._parent;} isEmpty() {return!this._node;} isGlobalScope() {return this._isGlobalScope;} isPathComponentImpossible() {return this._pathComponent&&this._pathComponent.startsWith("@");} isFullPathImpossible() {if(this.isEmpty()) return true;if(this.isPathComponentImpossible()) return true;if(this._parent) return this._parent.isFullPathImpossible();return false;} appendInternal(node) {return new WI.HeapSnapshotRootPath(node,WI.HeapSnapshotRootPath.SpecialPathComponent.InternalPropertyName,this);} appendArrayIndex(node,index) {let component="["+index+"]";return new WI.HeapSnapshotRootPath(node,component,this);} appendPropertyName(node,propertyName) {let component=WI.HeapSnapshotRootPath.canPropertyNameBeDotAccess(propertyName)?"."+propertyName:"["+doubleQuotedString(propertyName)+"]";return new WI.HeapSnapshotRootPath(node,component,this);} appendVariableName(node,variableName) {if(this._isGlobalScope) return this.appendPropertyName(node,variableName);return new WI.HeapSnapshotRootPath(node,variableName,this);} appendGlobalScopeName(node,globalScopeName) {return new WI.HeapSnapshotRootPath(node,globalScopeName,this,true);} appendEdge(edge) {switch(edge.type){case WI.HeapSnapshotEdgeProxy.EdgeType.Internal:return this.appendInternal(edge.to);case WI.HeapSnapshotEdgeProxy.EdgeType.Index:return this.appendArrayIndex(edge.to,edge.data);case WI.HeapSnapshotEdgeProxy.EdgeType.Property:return this.appendPropertyName(edge.to,edge.data);case WI.HeapSnapshotEdgeProxy.EdgeType.Variable:return this.appendVariableName(edge.to,edge.data);} console.error("Unexpected edge type",edge.type);}};WI.HeapSnapshotRootPath.SpecialPathComponent={InternalPropertyName:"@internal",};WI.IndexedDatabase=class IndexedDatabase {constructor(name,securityOrigin,version,objectStores) {this._name=name;this._securityOrigin=securityOrigin;this._host=parseSecurityOrigin(securityOrigin).host;this._version=version;this._objectStores=objectStores||[];for(var objectStore of this._objectStores) objectStore.establishRelationship(this);} get name(){return this._name;} get securityOrigin(){return this._securityOrigin;} get host(){return this._host;} get version(){return this._version;} get objectStores(){return this._objectStores;} saveIdentityToCookie(cookie) {cookie[WI.IndexedDatabase.NameCookieKey]=this._name;cookie[WI.IndexedDatabase.HostCookieKey]=this._host;}};WI.IndexedDatabase.TypeIdentifier="indexed-database";WI.IndexedDatabase.NameCookieKey="indexed-database-name";WI.IndexedDatabase.HostCookieKey="indexed-database-host";WI.IndexedDatabaseObjectStore=class IndexedDatabaseObjectStore {constructor(name,keyPath,autoIncrement,indexes) {this._name=name;this._keyPath=keyPath;this._autoIncrement=autoIncrement||false;this._indexes=indexes||[];this._parentDatabase=null;for(var index of this._indexes) index.establishRelationship(this);} get name(){return this._name;} get keyPath(){return this._keyPath;} get autoIncrement(){return this._autoIncrement;} get parentDatabase(){return this._parentDatabase;} get indexes(){return this._indexes;} saveIdentityToCookie(cookie) {cookie[WI.IndexedDatabaseObjectStore.NameCookieKey]=this._name;cookie[WI.IndexedDatabaseObjectStore.KeyPathCookieKey]=this._keyPath;} establishRelationship(parentDatabase) {this._parentDatabase=parentDatabase||null;}};WI.IndexedDatabaseObjectStore.TypeIdentifier="indexed-database-object-store";WI.IndexedDatabaseObjectStore.NameCookieKey="indexed-database-object-store-name";WI.IndexedDatabaseObjectStore.KeyPathCookieKey="indexed-database-object-store-key-path";WI.IndexedDatabaseObjectStoreIndex=class IndexedDatabaseObjectStoreIndex {constructor(name,keyPath,unique,multiEntry) {this._name=name;this._keyPath=keyPath;this._unique=unique||false;this._multiEntry=multiEntry||false;this._parentObjectStore=null;} get name(){return this._name;} get keyPath(){return this._keyPath;} get unique(){return this._unique;} get multiEntry(){return this._multiEntry;} get parentObjectStore(){return this._parentObjectStore;} saveIdentityToCookie(cookie) {cookie[WI.IndexedDatabaseObjectStoreIndex.NameCookieKey]=this._name;cookie[WI.IndexedDatabaseObjectStoreIndex.KeyPathCookieKey]=this._keyPath;} establishRelationship(parentObjectStore) {this._parentObjectStore=parentObjectStore||null;}};WI.IndexedDatabaseObjectStoreIndex.TypeIdentifier="indexed-database-object-store-index";WI.IndexedDatabaseObjectStoreIndex.NameCookieKey="indexed-database-object-store-index-name";WI.IndexedDatabaseObjectStoreIndex.KeyPathCookieKey="indexed-database-object-store-index-key-path";WI.IssueMessage=class IssueMessage extends WI.Object {constructor(consoleMessage) {super();this._consoleMessage=consoleMessage;this._text=this._issueText();switch(this._consoleMessage.source){case WI.ConsoleMessage.MessageSource.JS: var prefixRegex=/^([^:]+): (?:DOM Exception \d+: )?/;var match=prefixRegex.exec(this._text);if(match&&match[1]in WI.IssueMessage.Type._prefixTypeMap){this._type=WI.IssueMessage.Type._prefixTypeMap[match[1]];this._text=this._text.substring(match[0].length);}else this._type=WI.IssueMessage.Type.OtherIssue;break;case WI.ConsoleMessage.MessageSource.CSS:case WI.ConsoleMessage.MessageSource.XML:this._type=WI.IssueMessage.Type.PageIssue;break;case WI.ConsoleMessage.MessageSource.Network:this._type=WI.IssueMessage.Type.NetworkIssue;break;case WI.ConsoleMessage.MessageSource.Security:this._type=WI.IssueMessage.Type.SecurityIssue;break;case WI.ConsoleMessage.MessageSource.ConsoleAPI:case WI.ConsoleMessage.MessageSource.Storage:case WI.ConsoleMessage.MessageSource.Appcache:case WI.ConsoleMessage.MessageSource.Rendering:case WI.ConsoleMessage.MessageSource.Media:case WI.ConsoleMessage.MessageSource.Mediasource:case WI.ConsoleMessage.MessageSource.WebRTC:case WI.ConsoleMessage.MessageSource.ITPDebug:case WI.ConsoleMessage.MessageSource.PrivateClickMeasurement:case WI.ConsoleMessage.MessageSource.PaymentRequest:case WI.ConsoleMessage.MessageSource.AdClickAttribution:case WI.ConsoleMessage.MessageSource.Other:this._type=WI.IssueMessage.Type.OtherIssue;break;default:console.error("Unknown issue source:",this._consoleMessage.source);this._type=WI.IssueMessage.Type.OtherIssue;} this._sourceCodeLocation=consoleMessage.sourceCodeLocation;if(this._sourceCodeLocation) this._sourceCodeLocation.addEventListener(WI.SourceCodeLocation.Event.DisplayLocationChanged,this._sourceCodeLocationDisplayLocationChanged,this);} static displayName(type) {switch(type){case WI.IssueMessage.Type.SemanticIssue:return WI.UIString("Semantic Issue");case WI.IssueMessage.Type.RangeIssue:return WI.UIString("Range Issue");case WI.IssueMessage.Type.ReferenceIssue:return WI.UIString("Reference Issue");case WI.IssueMessage.Type.TypeIssue:return WI.UIString("Type Issue");case WI.IssueMessage.Type.PageIssue:return WI.UIString("Page Issue");case WI.IssueMessage.Type.NetworkIssue:return WI.UIString("Network Issue");case WI.IssueMessage.Type.SecurityIssue:return WI.UIString("Security Issue");case WI.IssueMessage.Type.OtherIssue:return WI.UIString("Other Issue");default:console.error("Unknown issue message type:",type);return WI.UIString("Other Issue");}} get text(){return this._text;} get type(){return this._type;} get level(){return this._consoleMessage.level;} get source(){return this._consoleMessage.source;} get url(){return this._consoleMessage.url;} get sourceCodeLocation(){return this._sourceCodeLocation;} saveIdentityToCookie(cookie) {cookie[WI.IssueMessage.URLCookieKey]=this.url;cookie[WI.IssueMessage.LineNumberCookieKey]=this._sourceCodeLocation?this._sourceCodeLocation.lineNumber:0;cookie[WI.IssueMessage.ColumnNumberCookieKey]=this._sourceCodeLocation?this._sourceCodeLocation.columnNumber:0;} _issueText() {let parameters=this._consoleMessage.parameters;if(!parameters) return this._consoleMessage.messageText;if(parameters[0].type!=="string") return this._consoleMessage.messageText;function valueFormatter(obj) {return obj.description;} let formatters={};formatters.o=valueFormatter;formatters.s=valueFormatter;formatters.f=valueFormatter;formatters.i=valueFormatter;formatters.d=valueFormatter;function append(a,b) {a+=b;return a;} let result=String.format(parameters[0].description,parameters.slice(1),formatters,"",append);let resultText=result.formattedResult;for(let i=0;iWI.BreakpointAction.fromJSON(actionJSON))||[],ignoreCount:json.ignoreCount,autoContinue:json.autoContinue,});} toJSON(key) {let json=super.toJSON(key);if(this._contentIdentifier) json.contentIdentifier=this._contentIdentifier;if(isFinite(this._sourceCodeLocation.lineNumber)) json.lineNumber=this._sourceCodeLocation.lineNumber;if(isFinite(this._sourceCodeLocation.columnNumber)) json.columnNumber=this._sourceCodeLocation.columnNumber;if(key===WI.ObjectStore.toJSONSymbol) json[WI.objectStores.breakpoints.keyPath]=this._contentIdentifier+":"+this._sourceCodeLocation.lineNumber+":"+this._sourceCodeLocation.columnNumber;return json;} get sourceCodeLocation(){return this._sourceCodeLocation;} get contentIdentifier(){return this._contentIdentifier;} get scriptIdentifier(){return this._scriptIdentifier;} get target(){return this._target;} get resolvedLocations(){return this._resolvedLocations;} get displayName() {switch(this){case WI.debuggerManager.debuggerStatementsBreakpoint:return WI.repeatedUIString.debuggerStatements();case WI.debuggerManager.allExceptionsBreakpoint:return WI.repeatedUIString.allExceptions();case WI.debuggerManager.uncaughtExceptionsBreakpoint:return WI.repeatedUIString.uncaughtExceptions();case WI.debuggerManager.assertionFailuresBreakpoint:return WI.repeatedUIString.assertionFailures();case WI.debuggerManager.allMicrotasksBreakpoint:return WI.repeatedUIString.allMicrotasks();} return this._sourceCodeLocation.displayLocationString()} get special() {switch(this){case WI.debuggerManager.debuggerStatementsBreakpoint:case WI.debuggerManager.allExceptionsBreakpoint:case WI.debuggerManager.uncaughtExceptionsBreakpoint:case WI.debuggerManager.assertionFailuresBreakpoint:case WI.debuggerManager.allMicrotasksBreakpoint:return true;} if(this._isSpecial()) return true;return super.special;} get removable() {switch(this){case WI.debuggerManager.debuggerStatementsBreakpoint:case WI.debuggerManager.allExceptionsBreakpoint:case WI.debuggerManager.uncaughtExceptionsBreakpoint:return false;} return super.removable;} get editable() {switch(this){case WI.debuggerManager.debuggerStatementsBreakpoint:return WI.JavaScriptBreakpoint.supportsDebuggerStatements("options");case WI.debuggerManager.allExceptionsBreakpoint:case WI.debuggerManager.uncaughtExceptionsBreakpoint:return InspectorBackend.hasCommand("Debugger.setPauseOnExceptions","options");case WI.debuggerManager.assertionFailuresBreakpoint:return InspectorBackend.hasCommand("Debugger.setPauseOnAssertions","options");case WI.debuggerManager.allMicrotasksBreakpoint:return WI.JavaScriptBreakpoint.supportsMicrotasks("options");} return true;} get identifier() {return this._id;} set identifier(id) {this._id=id||null;} get resolved() {return super.resolved&&this._resolved;} set resolved(resolved) {if(this._resolved===resolved) return;this._resolved=resolved||false;this.dispatchEventToListeners(WI.JavaScriptBreakpoint.Event.ResolvedStateDidChange);} addResolvedLocation(location) {this._resolvedLocations.push(location);this.resolved=true;} hasResolvedLocation(location) {return this._resolvedLocations.some((resolvedLocation)=>resolvedLocation.isEqual(location));} clearResolvedLocations() {this._resolvedLocations=[];this.resolved=false;} remove() {super.remove();WI.debuggerManager.removeBreakpoint(this);} saveIdentityToCookie(cookie) {cookie["javascript-breakpoint-content-identifier"]=this._contentIdentifier;cookie["javascript-breakpoint-line-number"]=this._sourceCodeLocation.lineNumber;cookie["javascript-breakpoint-column-number"]=this._sourceCodeLocation.columnNumber;} _isSpecial() {return this._sourceCodeLocation.isEqual(WI.SourceCodeLocation.specialBreakpointLocation);} _sourceCodeLocationLocationChanged(event) {this.dispatchEventToListeners(WI.JavaScriptBreakpoint.Event.LocationDidChange,event.data);} _sourceCodeLocationDisplayLocationChanged(event) {this.dispatchEventToListeners(WI.JavaScriptBreakpoint.Event.DisplayLocationDidChange,event.data);}};WI.JavaScriptBreakpoint.TypeIdentifier="javascript-breakpoint";WI.JavaScriptBreakpoint.Event={ResolvedStateDidChange:"javascript-breakpoint-resolved-state-did-change",LocationDidChange:"javascript-breakpoint-location-did-change",DisplayLocationDidChange:"javascript-breakpoint-display-location-did-change",};WI.JavaScriptBreakpoint.ReferencePage=WI.ReferencePage.JavaScriptBreakpoints;WI.KeyboardShortcut=class KeyboardShortcut {constructor(modifiers,key,callback,targetElement) {if(typeof key==="string"){key=key[0].toUpperCase();key=new WI.Key(key.charCodeAt(0),key);} if(callback&&!targetElement) targetElement=document;this._modifiers=modifiers||WI.KeyboardShortcut.Modifier.None;this._key=key;this._targetElement=targetElement;this._callback=callback;this._disabled=false;this._implicitlyPreventsDefault=true;if(targetElement){var targetKeyboardShortcuts=targetElement._keyboardShortcuts;if(!targetKeyboardShortcuts) targetKeyboardShortcuts=targetElement._keyboardShortcuts=[];targetKeyboardShortcuts.push(this);if(!WI.KeyboardShortcut._registeredKeyDownListener){WI.KeyboardShortcut._registeredKeyDownListener=true;window.addEventListener("keydown",WI.KeyboardShortcut._handleKeyDown);}}} static _handleKeyDown(event) {if(event.defaultPrevented) return;for(var targetElement=event.target;targetElement;targetElement=targetElement.parentNode){if(!targetElement._keyboardShortcuts) continue;for(var i=0;inew WI.LinearTimingFunction.Point(...point)));let args=trimmedText.match(/^linear\(\s*([^\)]+)\s*\)$/)?.[1]?.split(/\s*,\s*/)??[];if(args.length<2) return null;let stops=[];let largestInput=-Infinity;let lastStopIsExtraPoint=false;for(let arg of args){let[_,output,input,extraPoint]=arg.match(/([\d\.-]+)\s*(?:([\d\.-]+)%)?\s*(?:([\d\.-]+)%)?/)??[];output=parseFloat(output);if(isNaN(output)) return null;let stop={output};stops.push(stop);lastStopIsExtraPoint=false;if(input!==undefined){input=parseFloat(input)/100;if(isNaN(input)) return null;largestInput=Math.max(input,largestInput);stop.input=largestInput;if(extraPoint!==undefined){extraPoint=parseFloat(extraPoint)/100;if(isNaN(extraPoint)) return null;largestInput=Math.max(extraPoint,largestInput);stops.push({output,input:largestInput});lastStopIsExtraPoint=true;}}else if(stops.length===1){largestInput=0;stop.input=largestInput;}} if(!lastStopIsExtraPoint&&!("input"in stops.lastValue)) stops.lastValue.input=Math.max(1,largestInput);let points=[];let missingInputRunStart=-1;for(let i=0;i<=stops.length;++i){if(i0?stops[missingInputRunStart-1].input:0;let inputHigh=ipoint.copy()));} equals(other) {if(this._points.length!==other._points.length) return false;for(let i=0;i `${point.value}${point.progress*100}%`).join(", ")})`;}};WI.LinearTimingFunction.Point=class LinearTimingFunctionPoint {constructor(value,progress) {this._value=value;this._progress=progress;} get value(){return this._value;} get progress(){return this._progress;} copy() {return new WI.LinearTimingFunction.Point(this._value,this._progress);} equals(other) {return this._value===other._value&&this._progress===other._progress;}};WI.LinearTimingFunction.keywordValues={"linear":[[0,0],[1,1]],};WI.LocalResourceOverride=class LocalResourceOverride extends WI.Object {constructor(url,type,localResource,{resourceErrorType,isCaseSensitive,isRegex,isPassthrough,disabled}={}) {super();this._url=WI.urlWithoutFragment(url);this._urlComponents=null;this._type=type;this._localResource=localResource;this._resourceErrorType=resourceErrorType||WI.LocalResourceOverride.ResourceErrorType.General;this._isCaseSensitive=isCaseSensitive!==undefined?isCaseSensitive:true;this._isRegex=isRegex!==undefined?isRegex:false;this._isPassthrough=isPassthrough!==undefined?isPassthrough:false;this._disabled=disabled!==undefined?disabled:false;this._localResource._localResourceOverride=this;} static create(url,type,{requestURL,requestMethod,requestHeaders,requestData,responseMIMEType,responseContent,responseBase64Encoded,responseStatusCode,responseStatusText,responseHeaders,mappedFilePath,resourceErrorType,isCaseSensitive,isRegex,isPassthrough,disabled}={}) {let localResource=new WI.LocalResource({request:{url:requestURL||url||"",method:requestMethod,headers:requestHeaders,data:requestData,},response:{headers:responseHeaders,mimeType:responseMIMEType,statusCode:responseStatusCode,statusText:responseStatusText,content:responseContent,base64Encoded:responseBase64Encoded,},mappedFilePath,});return new WI.LocalResourceOverride(url,type,localResource,{resourceErrorType,isCaseSensitive,isRegex,isPassthrough,disabled});} static displayNameForNetworkStageOfType(type) {switch(type){case WI.LocalResourceOverride.InterceptType.Block:case WI.LocalResourceOverride.InterceptType.Request:return WI.UIString("Request Override","Request Override @ Local Override Network Stage","Text indicating that the local override replaces the request of the network activity.");case WI.LocalResourceOverride.InterceptType.Response:case WI.LocalResourceOverride.InterceptType.ResponseMappedDirectory:case WI.LocalResourceOverride.InterceptType.ResponseSkippingNetwork:return WI.UIString("Response Override","Response Override @ Local Override Network Stage","Text indicating that the local override replaces the response of the network activity.");} return"";} static displayNameForType(type) {switch(type){case WI.LocalResourceOverride.InterceptType.Block:return WI.UIString("Block","Block @ Local Override Type","Text indicating that the local override will always block the network activity.");case WI.LocalResourceOverride.InterceptType.Request:return WI.UIString("Request","Request @ Local Override Type","Text indicating that the local override intercepts the request phase of network activity.");case WI.LocalResourceOverride.InterceptType.Response:case WI.LocalResourceOverride.InterceptType.ResponseMappedDirectory:case WI.LocalResourceOverride.InterceptType.ResponseSkippingNetwork:return WI.UIString("Response","Response @ Local Override Type","Text indicating that the local override intercepts the response phase of network activity.");} return"";} static displayNameForResourceErrorType(resourceErrorType) {switch(resourceErrorType){case WI.LocalResourceOverride.ResourceErrorType.AccessControl:return WI.UIString("Access Control","Access Control @ Local Override Type","Text indicating that the local override will block the network activity with an access error.");case WI.LocalResourceOverride.ResourceErrorType.Cancellation:return WI.UIString("Cancellation","Cancellation @ Local Override Type","Text indicating that the local override will block the network activity with a cancellation error.");case WI.LocalResourceOverride.ResourceErrorType.General:return WI.UIString("General","General @ Local Override Type","Text indicating that the local override will block the network activity with a general error.");case WI.LocalResourceOverride.ResourceErrorType.Timeout:return WI.UIString("Timeout","Timeout @ Local Override Type","Text indicating that the local override will block the network activity with an timeout error.");} return"";} static fromJSON(json) {let{url,type,localResource:localResourceJSON,resourceErrorType,isCaseSensitive,isRegex,isPassthrough,disabled}=json;let localResource=WI.LocalResource.fromJSON(localResourceJSON);url??=localResource.url;type??=WI.LocalResourceOverride.InterceptType.Response;return new WI.LocalResourceOverride(url,type,localResource,{resourceErrorType,isCaseSensitive,isRegex,isPassthrough,disabled});} toJSON(key) {let json={url:this._url,type:this._type,localResource:this._localResource.toJSON(key),isCaseSensitive:this._isCaseSensitive,isRegex:this._isRegex,isPassthrough:this._isPassthrough,disabled:this._disabled,};if(this._resourceErrorType) json.resourceErrorType=this._resourceErrorType;if(key===WI.ObjectStore.toJSONSymbol) json[WI.objectStores.localResourceOverrides.keyPath]=this._url;return json;} get url(){return this._url;} get type(){return this._type;} get localResource(){return this._localResource;} get isCaseSensitive(){return this._isCaseSensitive;} get isRegex(){return this._isRegex;} get isPassthrough(){return this._isPassthrough;} get urlComponents() {if(!this._urlComponents) this._urlComponents=parseURL(this._url);return this._urlComponents;} get networkStage() {switch(this._type){case WI.LocalResourceOverride.InterceptType.Block:case WI.LocalResourceOverride.InterceptType.Request:case WI.LocalResourceOverride.InterceptType.ResponseSkippingNetwork:return WI.NetworkManager.NetworkStage.Request;case WI.LocalResourceOverride.InterceptType.Response:case WI.LocalResourceOverride.InterceptType.ResponseMappedDirectory:return WI.NetworkManager.NetworkStage.Response;} return null;} get resourceErrorType() {return this._resourceErrorType;} set resourceErrorType(resourceErrorType) {if(this._resourceErrorType===resourceErrorType) return;this._resourceErrorType=resourceErrorType;this.dispatchEventToListeners(WI.LocalResourceOverride.Event.ResourceErrorTypeChanged);} get disabled() {return this._disabled;} set disabled(disabled) {if(this._disabled===disabled) return;this._disabled=!!disabled;this.dispatchEventToListeners(WI.LocalResourceOverride.Event.DisabledChanged);} get displayType() {let displayType=WI.LocalResourceOverride.displayNameForType(this._type);if(this._localResource.isMappedToDirectory) displayType=WI.UIString("%s (directory)","%s (directory) @ Local Override Type","Label modifier indicating that the local override maps to a directory on disk.").format(displayType);else if(this._localResource.mappedFilePath) displayType=WI.UIString("%s (file)","%s (file) @ Local Override Type","Label modifier indicating that the local override maps to a file on disk.").format(displayType);return displayType;} get displayName() {return this.displayURL();} displayURL({full}={}) {if(this._isRegex) return"/"+this._url+"/"+(!this._isCaseSensitive?"i":"");let displayName=full?this._url:WI.displayNameForURL(this._url,this.urlComponents);if(!this._isCaseSensitive) displayName=WI.UIString("%s (Case Insensitive)","%s (Case Insensitive) @ Local Override","Label for case-insensitive URL match pattern of a local override.").format(displayName);return displayName;} generateRequestRedirectURL(url) {let redirectURL=this._localResource.url;if(!redirectURL) return null;if(this._isRegex) return url.replace(this._urlRegex,redirectURL);return redirectURL;} generateSubpathForMappedDirectory(url) {return url.replace(this._urlRegex,this._localResource.url);} get canMapToFile() {if(!WI.LocalResource.canMapToFile()) return false;switch(this._type){case WI.LocalResourceOverride.InterceptType.Block:case WI.LocalResourceOverride.InterceptType.Request:return false;case WI.LocalResourceOverride.InterceptType.Response:case WI.LocalResourceOverride.InterceptType.ResponseMappedDirectory:case WI.LocalResourceOverride.InterceptType.ResponseSkippingNetwork:return true;} return false;} matches(url) {url=WI.urlWithoutFragment(url);if(this._isRegex) return this._urlRegex.test(url);if(!this._isCaseSensitive) return url.toLowerCase()===this._url.toLowerCase();return url===this._url;} equals(localResourceOverrideOrSerializedData) {return localResourceOverrideOrSerializedData.url===this._url&&localResourceOverrideOrSerializedData.isCaseSensitive===this._isCaseSensitive&&localResourceOverrideOrSerializedData.isRegex===this._isRegex;} saveIdentityToCookie(cookie) {cookie["local-resource-override-url"]=this._url;cookie["local-resource-override-type"]=this._type;cookie["local-resource-override-is-case-sensitive"]=this._isCaseSensitive;cookie["local-resource-override-is-regex"]=this._isRegex;cookie["local-resource-override-disabled"]=this._disabled;} get _urlRegex() {return new RegExp(this._url,!this._isCaseSensitive?"i":"");}};WI.LocalResourceOverride.TypeIdentifier="local-resource-override";WI.LocalResourceOverride.InterceptType={Block:"block",Request:"request",Response:"response",ResponseMappedDirectory:"response-mapped-directory",ResponseSkippingNetwork:"response-skipping-network",};WI.LocalResourceOverride.ResourceErrorType={AccessControl:"AccessControl",Cancellation:"Cancellation",General:"General",Timeout:"Timeout",};WI.LocalResourceOverride.Event={DisabledChanged:"local-resource-override-disabled-state-did-change",ResourceErrorTypeChanged:"local-resource-override-resource-error-type-changed",};WI.LogObject=class LogObject {};WI.LoggingChannel=class LoggingChannel {constructor(source,level) {this._source=source;this._level=level;} static fromPayload(payload) {return new WI.LoggingChannel(payload.source,payload.level);} get source(){return this._source;} get level(){return this._level;}};WI.LoggingChannel.Level={Off:"off",Basic:"basic",Verbose:"verbose",};WI.MediaInstrument=class MediaInstrument extends WI.Instrument {constructor() {super();} static supported() {return InspectorBackend.hasEvent("DOM.didFireEvent");} get timelineRecordType() {return WI.TimelineRecord.Type.Media;} startInstrumentation(initiatedByBackend) {if(!initiatedByBackend){if(InspectorBackend.hasDomain("Animation")){let target=WI.assumingMainTarget();target.AnimationAgent.startTracking();}}} stopInstrumentation(initiatedByBackend) {if(!initiatedByBackend){if(InspectorBackend.hasDomain("Animation")){let target=WI.assumingMainTarget();target.AnimationAgent.stopTracking();}}}};WI.MediaTimeline=class MediaTimeline extends WI.Timeline { recordForTrackingAnimationId(trackingAnimationId) {return this._trackingAnimationIdRecordMap.get(trackingAnimationId)||null;} recordForMediaElementEvents(domNode) {return this._mediaElementRecordMap.get(domNode)||null;} reset(suppressEvents) {this._trackingAnimationIdRecordMap=new Map;this._mediaElementRecordMap=new Map;super.reset(suppressEvents);} addRecord(record,options={}) {if(record.trackingAnimationId){this._trackingAnimationIdRecordMap.set(record.trackingAnimationId,record);} if(record.eventType===WI.MediaTimelineRecord.EventType.MediaElement){this._mediaElementRecordMap.set(record.domNode,record);} super.addRecord(record,options);}};WI.MediaTimelineRecord=class MediaTimelineRecord extends WI.TimelineRecord {constructor(eventType,domNodeOrInfo,{trackingAnimationId,animationName,transitionProperty}={}) {super(WI.TimelineRecord.Type.Media);this._eventType=eventType;this._domNode=domNodeOrInfo;this._domNodeDisplayName=domNodeOrInfo?.displayName;this._domNodeCSSPath=domNodeOrInfo instanceof WI.DOMNode?WI.cssPath(domNodeOrInfo,{full:true}):domNodeOrInfo?.cssPath; this._trackingAnimationId=trackingAnimationId||null; this._animationName=animationName||null;this._transitionProperty=transitionProperty||null;this._timestamps=[];this._activeStartTime=NaN;} static async fromJSON(json) {let{eventType,domNodeDisplayName,domNodeCSSPath,animationName,transitionProperty,timestamps}=json;let documentNode=null;if(InspectorBackend.hasDomain("DOM")) documentNode=await new Promise((resolve)=>WI.domManager.requestDocument(resolve));let domNode=null;if(documentNode&&domNodeCSSPath){try{let nodeId=await documentNode.querySelector(domNodeCSSPath);if(nodeId) domNode=WI.domManager.nodeForId(nodeId);}catch{}} if(!domNode){domNode={displayName:domNodeDisplayName,cssPath:domNodeCSSPath,};} let record=new MediaTimelineRecord(eventType,domNode,{animationName,transitionProperty});if(Array.isArray(timestamps)&×tamps.length){record._timestamps=[];for(let item of timestamps){if(item.type===MediaTimelineRecord.TimestampType.MediaElementDOMEvent){if(documentNode&&item.originatorCSSPath){try{let nodeId=await documentNode.querySelector(item.originatorCSSPath);if(nodeId) item.originator=WI.domManager.nodeForId(nodeId);}catch{} if(!item.originator){item.originator={displayName:item.originatorDisplayName,cssPath:item.originatorCSSPath,};}}} record._timestamps.push(item);}} return record;} toJSON() {let json={eventType:this._eventType,domNodeDisplayName:this._domNodeDisplayName,domNodeCSSPath:this._domNodeCSSPath,};if(this._animationName) json.animationName=this._animationName;if(this._transitionProperty) json.transitionProperty=this._transitionProperty;if(this._timestamps.length){json.timestamps=this._timestamps.map((item)=>{if(item.type===MediaTimelineRecord.TimestampType.MediaElementDOMEvent&&item.originator instanceof WI.DOMNode) delete item.originator;return item;});} return json;} get eventType(){return this._eventType;} get domNode(){return this._domNode;} get trackingAnimationId(){return this._trackingAnimationId;} get timestamps(){return this._timestamps;} get activeStartTime(){return this._activeStartTime;} get updatesDynamically() {return true;} get usesActiveStartTime() {return true;} get displayName() {switch(this._eventType){case MediaTimelineRecord.EventType.CSSAnimation:return this._animationName;case MediaTimelineRecord.EventType.CSSTransition:return this._transitionProperty;case MediaTimelineRecord.EventType.MediaElement:return WI.UIString("Media Element");} console.error("Unknown media record event type: ",this._eventType,this);return WI.UIString("Media Event");} get subtitle() {switch(this._eventType){case MediaTimelineRecord.EventType.CSSAnimation:return WI.UIString("CSS Animation");case MediaTimelineRecord.EventType.CSSTransition:return WI.UIString("CSS Transition");} return"";} saveIdentityToCookie(cookie) {super.saveIdentityToCookie(cookie);cookie["media-timeline-record-event-type"]=this._eventType;cookie["media-timeline-record-dom-node"]=this._domNode instanceof WI.DOMNode?this._domNode.path():this._domNode;if(this._animationName) cookie["media-timeline-record-animation-name"]=this._animationName;if(this._transitionProperty) cookie["media-timeline-record-transition-property"]=this._transitionProperty;} updateAnimationState(timestamp,animationState) {let type;switch(animationState){case InspectorBackend.Enum.Animation.AnimationState.Ready:type=MediaTimelineRecord.TimestampType.CSSAnimationReady;break;case InspectorBackend.Enum.Animation.AnimationState.Delayed:type=MediaTimelineRecord.TimestampType.CSSAnimationDelay;break;case InspectorBackend.Enum.Animation.AnimationState.Active:type=MediaTimelineRecord.TimestampType.CSSAnimationActive;break;case InspectorBackend.Enum.Animation.AnimationState.Canceled:type=MediaTimelineRecord.TimestampType.CSSAnimationCancel;break;case InspectorBackend.Enum.Animation.AnimationState.Done:type=MediaTimelineRecord.TimestampType.CSSAnimationDone;break;} this._timestamps.push({type,timestamp});this._updateTimes();} addDOMEvent(timestamp,domEvent) {let data={type:MediaTimelineRecord.TimestampType.MediaElementDOMEvent,timestamp,eventName:domEvent.eventName,};if(domEvent.originator instanceof WI.DOMNode){data.originator=domEvent.originator;data.originatorDisplayName=data.originator.displayName;data.originatorCSSPath=WI.cssPath(data.originator,{full:true});} if(!isEmptyObject(domEvent.data)) data.data=domEvent.data;this._timestamps.push(data);this._updateTimes();} powerEfficientPlaybackStateChanged(timestamp,isPowerEfficient) {this._timestamps.push({type:MediaTimelineRecord.TimestampType.MediaElementPowerEfficientPlaybackStateChange,timestamp,isPowerEfficient,});this._updateTimes();} _updateTimes() {let oldStartTime=this.startTime;let oldEndTime=this.endTime;let firstItem=this._timestamps[0];let lastItem=this._timestamps.lastValue;if(isNaN(this._startTime)) this._startTime=firstItem.timestamp;if(isNaN(this._activeStartTime)){if(this._eventType===MediaTimelineRecord.EventType.MediaElement) this._activeStartTime=firstItem.timestamp;else if(firstItem.type===MediaTimelineRecord.TimestampType.CSSAnimationActive) this._activeStartTime=firstItem.timestamp;} switch(lastItem.type){case MediaTimelineRecord.TimestampType.CSSAnimationCancel:case MediaTimelineRecord.TimestampType.CSSAnimationDone:this._endTime=lastItem.timestamp;break;case MediaTimelineRecord.TimestampType.MediaElementDOMEvent:if(WI.DOMNode.isPlayEvent(lastItem.eventName)) this._endTime=NaN;else if(!isNaN(this._endTime)||WI.DOMNode.isPauseEvent(lastItem.eventName)||WI.DOMNode.isStopEvent(lastItem.eventName)) this._endTime=lastItem.timestamp;break;} if(this.startTime!==oldStartTime||this.endTime!==oldEndTime) this.dispatchEventToListeners(WI.TimelineRecord.Event.Updated);}};WI.MediaTimelineRecord.EventType={CSSAnimation:"css-animation",CSSTransition:"css-transition",MediaElement:"media-element",};WI.MediaTimelineRecord.TimestampType={CSSAnimationReady:"css-animation-ready",CSSAnimationDelay:"css-animation-delay",CSSAnimationActive:"css-animation-active",CSSAnimationCancel:"css-animation-cancel",CSSAnimationDone:"css-animation-done",MediaElementDOMEvent:"media-element-dom-event",MediaElementPowerEfficientPlaybackStateChange:"media-element-power-efficient-playback-state-change",};WI.MemoryCategory=class MemoryCategory {constructor(type,size) {this.type=type;this.size=size;}};WI.MemoryCategory.Type={JavaScript:"javascript",Images:"images",Layers:"layers",Page:"page",};WI.MemoryInstrument=class MemoryInstrument extends WI.Instrument { get timelineRecordType() {return WI.TimelineRecord.Type.Memory;} startInstrumentation(initiatedByBackend) {if(!initiatedByBackend){let target=WI.assumingMainTarget();target.MemoryAgent.startTracking();}} stopInstrumentation(initiatedByBackend) {if(!initiatedByBackend){let target=WI.assumingMainTarget();target.MemoryAgent.stopTracking();}}};WI.MemoryPressureEvent=class MemoryPressureEvent {constructor(timestamp,severity) {this._timestamp=timestamp;this._severity=severity;} static fromPayload(timestamp,protocolSeverity) {let severity;switch(protocolSeverity){case InspectorBackend.Enum.Memory.MemoryPressureSeverity.Critical:severity=WI.MemoryPressureEvent.Severity.Critical;break;case InspectorBackend.Enum.Memory.MemoryPressureSeverity.NonCritical:severity=WI.MemoryPressureEvent.Severity.NonCritical;break;default:console.error("Unexpected memory pressure severity",protocolSeverity);severity=WI.MemoryPressureEvent.Severity.NonCritical;break;} return new WI.MemoryPressureEvent(timestamp,severity);} static fromJSON(json) {let{timestamp,severity}=json;return new WI.MemoryPressureEvent(timestamp,severity);} toJSON() {return{timestamp:this._timestamp,severity:this._severity,};} get timestamp(){return this._timestamp;} get severity(){return this._severity;}};WI.MemoryPressureEvent.Severity={Critical:"critical",NonCritical:"non-critical",};WI.MemoryTimeline=class MemoryTimeline extends WI.Timeline { get memoryPressureEvents(){return this._pressureEvents;} addMemoryPressureEvent(memoryPressureEvent) {this._pressureEvents.push(memoryPressureEvent);this.dispatchEventToListeners(WI.MemoryTimeline.Event.MemoryPressureEventAdded,{memoryPressureEvent});} reset(suppressEvents) {super.reset(suppressEvents);this._pressureEvents=[];} addRecord(record,options={}) {let lastRecord=this.records.lastValue;if(lastRecord){let startTime=lastRecord.endTime;if(options.discontinuity) startTime=options.discontinuity.endTime;record.adjustStartTime(startTime);} super.addRecord(record,options);}};WI.MemoryTimeline.Event={MemoryPressureEventAdded:"memory-timeline-memory-pressure-event-added",};WI.MemoryTimelineRecord=class MemoryTimelineRecord extends WI.TimelineRecord {constructor(timestamp,categories) {super(WI.TimelineRecord.Type.Memory,timestamp-MemoryTimelineRecord.samplingRatePerSecond,timestamp);this._timestamp=timestamp;this._categories=WI.MemoryTimelineRecord.memoryCategoriesFromProtocol(categories);this._exportCategories=categories;this._totalSize=0;for(let{size}of categories) this._totalSize+=size;} static get samplingRatePerSecond() {return 0.5;} static memoryCategoriesFromProtocol(categories) {let javascriptSize=0;let imagesSize=0;let layersSize=0;let pageSize=0;for(let{type,size}of categories){switch(type){case InspectorBackend.Enum.Memory.CategoryDataType.JavaScript:case InspectorBackend.Enum.Memory.CategoryDataType.JIT:javascriptSize+=size;break;case InspectorBackend.Enum.Memory.CategoryDataType.Images:imagesSize+=size;break;case InspectorBackend.Enum.Memory.CategoryDataType.Layers:layersSize+=size;break;case InspectorBackend.Enum.Memory.CategoryDataType.Page:case InspectorBackend.Enum.Memory.CategoryDataType.Other:pageSize+=size;break;default:console.warn("Unhandled Memory.CategoryDataType: "+type);break;}} let memoryCategories=[];if(javascriptSize) memoryCategories.push({type:WI.MemoryCategory.Type.JavaScript,size:javascriptSize});if(imagesSize) memoryCategories.push({type:WI.MemoryCategory.Type.Images,size:imagesSize});if(layersSize) memoryCategories.push({type:WI.MemoryCategory.Type.Layers,size:layersSize});if(pageSize) memoryCategories.push({type:WI.MemoryCategory.Type.Page,size:pageSize});return memoryCategories;} static async fromJSON(json) {let{timestamp,categories}=json;return new WI.MemoryTimelineRecord(timestamp,categories);} toJSON() {return{type:this.type,timestamp:this.startTime,categories:this._exportCategories,};} get timestamp(){return this._timestamp;} get categories(){return this._categories;} get totalSize(){return this._totalSize;} get unadjustedStartTime(){return this._timestamp;} adjustStartTime(startTime) {this._startTime=startTime;}};WI.NativeConstructorFunctionParameters={Object:{assign:"target, ...sources",create:"prototype, [propertiesObject]",defineProperties:"object, properties",defineProperty:"object, propertyName, descriptor",freeze:"object",getOwnPropertyDescriptor:"object, propertyName",getOwnPropertyNames:"object",getOwnPropertySymbols:"object",getPrototypeOf:"object",is:"value1, value2",isExtensible:"object",isFrozen:"object",isSealed:"object",keys:"object",preventExtensions:"object",seal:"object",setPrototypeOf:"object, prototype",__proto__:null,},Array:{from:"arrayLike, [mapFunction], [thisArg]",isArray:"object",of:"[...values]",__proto__:null,},ArrayBuffer:{isView:"object",transfer:"oldBuffer, [newByteLength=length]",__proto__:null,},Number:{isFinite:"value",isInteger:"value",isNaN:"value",isSafeInteger:"value",parseFloat:"string",parseInt:"string, [radix]",__proto__:null,},Math:{abs:"x",acos:"x",acosh:"x",asin:"x",asinh:"x",atan2:"y, x",atan:"x",atanh:"x",cbrt:"x",ceil:"x",clz32:"x",cos:"x",cosh:"x",exp:"x",expm1:"x",floor:"x",fround:"x",hypot:"[...x]",imul:"x",log:"x",log1p:"x",log2:"x",log10:"x",max:"[...x]",min:"[...x]",pow:"x, y",round:"x",sign:"x",sin:"x",sinh:"x",sqrt:"x",tan:"x",tanh:"x",trunc:"x",__proto__:null,},JSON:{parse:"text, [reviver]",stringify:"value, [replacer], [space]",__proto__:null,},Date:{parse:"dateString",UTC:"year, [month], [day], [hour], [minute], [second], [ms]",__proto__:null,},Promise:{all:"iterable",race:"iterable",reject:"reason",resolve:"value",__proto__:null,},Reflect:{apply:"target, thisArgument, argumentsList",construct:"target, argumentsList, [newTarget=target]",defineProperty:"target, propertyKey, attributes",deleteProperty:"target, propertyKey",get:"target, propertyKey, [receiver]",getOwnPropertyDescriptor:"target, propertyKey",getPrototypeOf:"target",has:"target, propertyKey",isExtensible:"target",ownKeys:"target",preventExtensions:"target",set:"target, propertyKey, value, [receiver]",setPrototypeOf:"target, prototype",__proto__:null,},String:{fromCharCode:"...codeUnits",fromCodePoint:"...codePoints",raw:"template, ...substitutions",__proto__:null,},Symbol:{for:"key",keyFor:"symbol",__proto__:null,},Console:{assert:"condition, [message], [...values]",count:"label = \"default\"",countReset:"label = \"default\"",debug:"message, [...values]",dir:"object",dirxml:"object",error:"message, [...values]",group:"[name]",groupCollapsed:"[name]",groupEnd:"[name]",info:"message, [...values]",log:"message, [...values]",profile:"name",profileEnd:"name",record:"object, [options]",recordEnd:"object",screenshot:"[node]",table:"data, [columns]",takeHeapSnapshot:"[label]",time:"label = \"default\"",timeLog:"label = \"default\"",timeEnd:"label = \"default\"",timeStamp:"[label]",trace:"message, [...values]",warn:"message, [...values]",__proto__:null,},IDBKeyRangeConstructor:{bound:"lower, upper, [lowerOpen], [upperOpen]",lowerBound:"lower, [open]",only:"value",upperBound:"upper, [open]",__proto__:null,},MediaSourceConstructor:{isTypeSupported:"type",__proto__:null,},MediaStreamTrackConstructor:{getSources:"callback",__proto__:null,},NotificationConstructor:{requestPermission:"[callback]",__proto__:null,},URLConstructor:{createObjectURL:"blob",revokeObjectURL:"url",__proto__:null,},WebKitMediaKeysConstructor:{isTypeSupported:"keySystem, [type]",__proto__:null,},};WI.NativePrototypeFunctionParameters={Object:{__defineGetter__:"propertyName, getterFunction",__defineSetter__:"propertyName, setterFunction",__lookupGetter__:"propertyName",__lookupSetter__:"propertyName",hasOwnProperty:"propertyName",isPrototypeOf:"property",propertyIsEnumerable:"propertyName",__proto__:null,},Array:{concat:"value, ...",copyWithin:"targetIndex, startIndex, [endIndex=length]",every:"callback, [thisArg]",fill:"value, [startIndex=0], [endIndex=length]",filter:"callback, [thisArg]",find:"callback, [thisArg]",findIndex:"callback, [thisArg]",findLast:"callback, [thisArg]",findLastIndex:"callback, [thisArg]",forEach:"callback, [thisArg]",includes:"searchValue, [startIndex=0]",indexOf:"searchValue, [startIndex=0]",join:"[separator=\",\"]",lastIndexOf:"searchValue, [startIndex=length]",map:"callback, [thisArg]",push:"value, ...",reduce:"callback, [initialValue]",reduceRight:"callback, [initialValue]",slice:"[startIndex=0], [endIndex=length]",some:"callback, [thisArg]",sort:"[compareFunction]",splice:"startIndex, [deleteCount=0], ...itemsToAdd",__proto__:null,},ArrayBuffer:{slice:"startIndex, [endIndex=byteLength]",__proto__:null,},DataView:{setInt8:"byteOffset, value",setInt16:"byteOffset, value, [littleEndian=false]",setInt23:"byteOffset, value, [littleEndian=false]",setUint8:"byteOffset, value",setUint16:"byteOffset, value, [littleEndian=false]",setUint32:"byteOffset, value, [littleEndian=false]",setFloat32:"byteOffset, value, [littleEndian=false]",setFloat64:"byteOffset, value, [littleEndian=false]",getInt8:"byteOffset",getInt16:"byteOffset, [littleEndian=false]",getInt23:"byteOffset, [littleEndian=false]",getUint8:"byteOffset",getUint16:"byteOffset, [littleEndian=false]",getUint32:"byteOffset, [littleEndian=false]",getFloat32:"byteOffset, [littleEndian=false]",getFloat64:"byteOffset, [littleEndian=false]",__proto__:null,},Date:{setDate:"day",setFullYear:"year, [month=getMonth()], [day=getDate()]",setHours:"hours, [minutes=getMinutes()], [seconds=getSeconds()], [ms=getMilliseconds()]",setMilliseconds:"ms",setMinutes:"minutes, [seconds=getSeconds()], [ms=getMilliseconds()]",setMonth:"month, [day=getDate()]",setSeconds:"seconds, [ms=getMilliseconds()]",setTime:"time",setUTCDate:"day",setUTCFullYear:"year, [month=getUTCMonth()], [day=getUTCDate()]",setUTCHours:"hours, [minutes=getUTCMinutes()], [seconds=getUTCSeconds()], [ms=getUTCMilliseconds()]",setUTCMilliseconds:"ms",setUTCMinutes:"minutes, [seconds=getUTCSeconds()], [ms=getUTCMilliseconds()]",setUTCMonth:"month, [day=getUTCDate()]",setUTCSeconds:"seconds, [ms=getUTCMilliseconds()]",setUTCTime:"time",setYear:"year",__proto__:null,},Function:{apply:"thisObject, [argumentsArray]",bind:"thisObject, ...arguments",call:"thisObject, ...arguments",__proto__:null,},Map:{delete:"key",forEach:"callback, [thisArg]",get:"key",has:"key",set:"key, value",__proto__:null,},Number:{toExponential:"[digits]",toFixed:"[digits]",toPrecision:"[significantDigits]",toString:"[radix=10]",__proto__:null,},RegExp:{compile:"pattern, flags",exec:"string",test:"string",__proto__:null,},Set:{delete:"value",forEach:"callback, [thisArg]",has:"value",add:"value",__proto__:null,},String:{charAt:"index",charCodeAt:"index",codePoints:"index",concat:"string, ...",includes:"searchValue, [startIndex=0]",indexOf:"searchValue, [startIndex=0]",lastIndexOf:"searchValue, [startIndex=length]",localeCompare:"string",match:"regex",repeat:"count",replace:"regex|string, replaceString|replaceHandler, [flags]",search:"regex",slice:"startIndex, [endIndex=length]",split:"[separator], [limit]",substr:"startIndex, [numberOfCharacters]",substring:"startIndex, [endIndex=length]",__proto__:null,},WeakMap:{delete:"key",get:"key",has:"key",set:"key, value",__proto__:null,},WeakSet:{delete:"value",has:"value",add:"value",__proto__:null,},Promise:{catch:"rejectionHandler",then:"resolvedHandler, rejectionHandler",__proto__:null,},Generator:{next:"value",return:"value",throw:"exception",__proto__:null,},Element:{closest:"selectors",getAttribute:"attributeName",getAttributeNS:"namespace, attributeName",getAttributeNode:"attributeName",getAttributeNodeNS:"namespace, attributeName",hasAttribute:"attributeName",hasAttributeNS:"namespace, attributeName",matches:"selector",removeAttribute:"attributeName",removeAttributeNS:"namespace, attributeName",removeAttributeNode:"attributeName",scrollIntoView:"[alignWithTop]",scrollIntoViewIfNeeded:"[centerIfNeeded]",setAttribute:"name, value",setAttributeNS:"namespace, name, value",setAttributeNode:"attributeNode",setAttributeNodeNS:"namespace, attributeNode",webkitMatchesSelector:"selectors",__proto__:null,},Node:{appendChild:"child",cloneNode:"[deep]",compareDocumentPosition:"[node]",contains:"[node]",insertBefore:"insertElement, referenceElement",isDefaultNamespace:"[namespace]",isEqualNode:"[node]",lookupNamespaceURI:"prefix",removeChild:"node",replaceChild:"newChild, oldChild",__proto__:null,},Window:{alert:"[message]",atob:"encodedData",btoa:"stringToEncode",cancelAnimationFrame:"id",clearInterval:"intervalId",clearTimeout:"timeoutId",confirm:"[message]",find:"string, [caseSensitive], [backwards], [wrapAround]",getComputedStyle:"[element], [pseudoElement]",getMatchedCSSRules:"[element], [pseudoElement]",matchMedia:"mediaQueryString",moveBy:"[deltaX], [deltaY]",moveTo:"[screenX], [screenY]",open:"url, windowName, [featuresString]",openDatabase:"name, version, displayName, estimatedSize, [creationCallback]",postMessage:"message, targetOrigin, [...transferables]",prompt:"[message], [value]",requestAnimationFrame:"callback",resizeBy:"[deltaX], [deltaY]",resizeTo:"[width], [height]",scrollBy:"[deltaX], [deltaY]",scrollTo:"[x], [y]",setInterval:"func, [delay], [...params]",setTimeout:"func, [delay], [...params]",showModalDialog:"url, [arguments], [options]",__proto__:null,},Document:{adoptNode:"[node]",caretRangeFromPoint:"[x], [y]",createAttribute:"attributeName",createAttributeNS:"namespace, qualifiedName",createCDATASection:"data",createComment:"data",createElement:"tagName",createElementNS:"namespace, qualifiedName",createEntityReference:"name",createEvent:"type",createExpression:"xpath, resolver",createNSResolver:"node",createNodeIterator:"root, whatToShow, filter",createProcessingInstruction:"target, data",createTextNode:"data",createTreeWalker:"root, whatToShow, filter, entityReferenceExpansion",elementFromPoint:"x, y",evaluate:"xpath, contextNode, namespaceResolver, resultType, result",execCommand:"command, userInterface, value",getCSSCanvasContext:"contextId, name, width, height",getElementById:"id",getElementsByName:"name",importNode:"node, deep",queryCommandEnabled:"command",queryCommandIndeterm:"command",queryCommandState:"command",queryCommandSupported:"command",queryCommandValue:"command",__proto__:null,},ANGLEInstancedArrays:{drawArraysInstancedANGLE:"mode, first, count, primcount",drawElementsInstancedANGLE:"mode, count, type, offset, primcount",vertexAttribDivisorANGLE:"index, divisor",__proto__:null,},AnalyserNode:{getByteFrequencyData:"array",getByteTimeDomainData:"array",getFloatFrequencyData:"array",__proto__:null,},AudioBuffer:{getChannelData:"channelIndex",__proto__:null,},AudioBufferCallback:{handleEvent:"audioBuffer",__proto__:null,},AudioBufferSourceNode:{noteGrainOn:"when, grainOffset, grainDuration",noteOff:"when",noteOn:"when",start:"[when], [grainOffset], [grainDuration]",stop:"[when]",__proto__:null,},AudioListener:{setOrientation:"x, y, z, xUp, yUp, zUp",setPosition:"x, y, z",setVelocity:"x, y, z",__proto__:null,},AudioNode:{connect:"destination, [output], [input]",disconnect:"[output]",__proto__:null,},AudioParam:{cancelScheduledValues:"startTime",exponentialRampToValueAtTime:"value, time",linearRampToValueAtTime:"value, time",setTargetAtTime:"target, time, timeConstant",setTargetValueAtTime:"targetValue, time, timeConstant",setValueAtTime:"value, time",setValueCurveAtTime:"values, time, duration",__proto__:null,},AudioTrackList:{getTrackById:"id",item:"index",__proto__:null,},BiquadFilterNode:{getFrequencyResponse:"frequencyHz, magResponse, phaseResponse",__proto__:null,},Blob:{slice:"[start], [end], [contentType]",__proto__:null,},CSS:{supports:"property, value",__proto__:null,},CSSKeyframesRule:{appendRule:"[rule]",deleteRule:"[key]",findRule:"[key]",insertRule:"[rule]",__proto__:null,},CSSMediaRule:{deleteRule:"[index]",insertRule:"[rule], [index]",__proto__:null,},CSSPrimitiveValue:{getFloatValue:"[unitType]",setFloatValue:"[unitType], [floatValue]",setStringValue:"[stringType], [stringValue]",__proto__:null,},CSSRuleList:{item:"[index]",__proto__:null,},CSSStyleDeclaration:{getPropertyCSSValue:"[propertyName]",getPropertyPriority:"[propertyName]",getPropertyValue:"[propertyName]",item:"[index]",removeProperty:"[propertyName]",setProperty:"[propertyName], [value], [priority]",__proto__:null,},CSSStyleSheet:{addRule:"[selector], [style], [index]",deleteRule:"[index]",insertRule:"[rule], [index]",removeRule:"[index]",__proto__:null,},CSSSupportsRule:{deleteRule:"[index]",insertRule:"[rule], [index]",__proto__:null,},CSSValueList:{item:"[index]",__proto__:null,},CanvasGradient:{addColorStop:"[offset], [color]",__proto__:null,},CanvasRenderingContext2D:{arc:"x, y, radius, startAngle, endAngle, [anticlockwise]",arcTo:"x1, y1, x2, y2, radius",bezierCurveTo:"cp1x, cp1y, cp2x, cp2y, x, y",clearRect:"x, y, width, height",clip:"path, [winding]",createImageData:"imagedata",createConicGradient:"angle, x, y",createLinearGradient:"x0, y0, x1, y1",createPattern:"canvas, repetitionType",createRadialGradient:"x0, y0, r0, x1, y1, r1",drawFocusIfNeeded:"element",drawImage:"image, x, y",drawImageFromRect:"image, [sx], [sy], [sw], [sh], [dx], [dy], [dw], [dh], [compositeOperation]",ellipse:"x, y, radiusX, radiusY, rotation, startAngle, endAngle, [anticlockwise]",fill:"path, [winding]",fillRect:"x, y, width, height",fillText:"text, x, y, [maxWidth]",getImageData:"sx, sy, sw, sh",isPointInPath:"path, x, y, [winding]",isPointInStroke:"path, x, y",lineTo:"x, y",measureText:"text",moveTo:"x, y",putImageData:"imagedata, dx, dy",quadraticCurveTo:"cpx, cpy, x, y",rect:"x, y, width, height",rotate:"angle",scale:"sx, sy",setAlpha:"[alpha]",setCompositeOperation:"[compositeOperation]",setFillColor:"color, [alpha]",setLineCap:"[cap]",setLineDash:"dash",setLineJoin:"[join]",setLineWidth:"[width]",setMiterLimit:"[limit]",setShadow:"width, height, blur, [color], [alpha]",setStrokeColor:"color, [alpha]",setTransform:"m11, m12, m21, m22, dx, dy",stroke:"path",strokeRect:"x, y, width, height",strokeText:"text, x, y, [maxWidth]",transform:"m11, m12, m21, m22, dx, dy",translate:"tx, ty",__proto__:null,},CharacterData:{appendData:"[data]",deleteData:"[offset], [length]",insertData:"[offset], [data]",replaceData:"[offset], [length], [data]",substringData:"[offset], [length]",__proto__:null,},CommandLineAPIHost:{copyText:"text",databaseId:"database",getEventListeners:"target",inspect:"objectId, hints",storageId:"storage",__proto__:null,},CompositionEvent:{initCompositionEvent:"[typeArg], [canBubbleArg], [cancelableArg], [viewArg], [dataArg]",__proto__:null,},Crypto:{getRandomValues:"array",__proto__:null,},CustomElementRegistry:{define:"name, constructor",get:"name",whenDefined:"name",__proto__:null,},CustomEvent:{initCustomEvent:"type, [bubbles], [cancelable], [detail]",__proto__:null,},DOMApplicationCache:{__proto__:null,},DOMImplementation:{createCSSStyleSheet:"[title], [media]",createDocument:"[namespaceURI], [qualifiedName], [doctype]",createDocumentType:"[qualifiedName], [publicId], [systemId]",createHTMLDocument:"[title]",hasFeature:"[feature], [version]",__proto__:null,},DOMParser:{parseFromString:"[str], [contentType]",__proto__:null,},DOMStringList:{contains:"[string]",item:"[index]",__proto__:null,},DOMTokenList:{add:"tokens...",contains:"token",item:"index",remove:"tokens...",toggle:"token, [force]",__proto__:null,},DataTransfer:{clearData:"[type]",getData:"type",setData:"type, data",setDragImage:"image, x, y",__proto__:null,},DataTransferItem:{getAsString:"[callback]",__proto__:null,},DataTransferItemList:{add:"file",item:"[index]",__proto__:null,},Database:{changeVersion:"oldVersion, newVersion, [callback], [errorCallback], [successCallback]",readTransaction:"callback, [errorCallback], [successCallback]",transaction:"callback, [errorCallback], [successCallback]",__proto__:null,},DatabaseCallback:{handleEvent:"database",__proto__:null,},DedicatedWorkerGlobalScope:{postMessage:"message, [messagePorts]",__proto__:null,},DeviceMotionEvent:{initDeviceMotionEvent:"[type], [bubbles], [cancelable], [acceleration], [accelerationIncludingGravity], [rotationRate], [interval]",__proto__:null,},DeviceOrientationEvent:{initDeviceOrientationEvent:"[type], [bubbles], [cancelable], [alpha], [beta], [gamma], [absolute]",__proto__:null,},DocumentFragment:{getElementById:"id",querySelector:"selectors",querySelectorAll:"selectors",__proto__:null,},Event:{initEvent:"type, [bubbles], [cancelable]",__proto__:null,},FileList:{item:"index",__proto__:null,},FileReader:{readAsArrayBuffer:"blob",readAsBinaryString:"blob",readAsDataURL:"blob",readAsText:"blob, [encoding]",__proto__:null,},FileReaderSync:{readAsArrayBuffer:"blob",readAsBinaryString:"blob",readAsDataURL:"blob",readAsText:"blob, [encoding]",__proto__:null,},FontFaceSet:{add:"font",check:"font, [text=\" \"]",delete:"font",load:"font, [text=\" \"]",__proto__:null,},FormData:{append:"[name], [value], [filename]",__proto__:null,},Geolocation:{clearWatch:"watchID",getCurrentPosition:"successCallback, [errorCallback], [options]",watchPosition:"successCallback, [errorCallback], [options]",__proto__:null,},HTMLAllCollection:{item:"[index]",namedItem:"name",tags:"name",__proto__:null,},HTMLButtonElement:{setCustomValidity:"error",__proto__:null,},HTMLCanvasElement:{getContext:"contextId",toDataURL:"[type]",__proto__:null,},HTMLCollection:{item:"[index]",namedItem:"[name]",__proto__:null,},HTMLDocument:{write:"[html]",writeln:"[html]",__proto__:null,},HTMLElement:{insertAdjacentElement:"[position], [element]",insertAdjacentHTML:"[position], [html]",insertAdjacentText:"[position], [text]",__proto__:null,},HTMLFieldSetElement:{setCustomValidity:"error",__proto__:null,},HTMLFormControlsCollection:{namedItem:"[name]",__proto__:null,},HTMLInputElement:{setCustomValidity:"error",setRangeText:"replacement",setSelectionRange:"start, end, [direction]",stepDown:"[n]",stepUp:"[n]",__proto__:null,},HTMLKeygenElement:{setCustomValidity:"error",__proto__:null,},HTMLMediaElement:{addTextTrack:"kind, [label], [language]",canPlayType:"[type], [keySystem]",fastSeek:"time",webkitAddKey:"keySystem, key, [initData], [sessionId]",webkitCancelKeyRequest:"keySystem, [sessionId]",webkitGenerateKeyRequest:"keySystem, [initData]",webkitSetMediaKeys:"mediaKeys",__proto__:null,},HTMLObjectElement:{setCustomValidity:"error",__proto__:null,},HTMLOptionsCollection:{add:"element, [before]",namedItem:"[name]",remove:"[index]",__proto__:null,},HTMLOutputElement:{setCustomValidity:"error",__proto__:null,},HTMLSelectElement:{add:"element, [before]",item:"index",namedItem:"[name]",setCustomValidity:"error",__proto__:null,},HTMLSlotElement:{assignedNodes:"[options]",__proto__:null,},HTMLTableElement:{deleteRow:"index",insertRow:"[index]",__proto__:null,},HTMLTableRowElement:{deleteCell:"index",insertCell:"[index]",__proto__:null,},HTMLTableSectionElement:{deleteRow:"index",insertRow:"[index]",__proto__:null,},HTMLTextAreaElement:{setCustomValidity:"error",setRangeText:"replacement",setSelectionRange:"[start], [end], [direction]",__proto__:null,},HTMLVideoElement:{webkitSetPresentationMode:"mode",webkitSupportsPresentationMode:"mode",__proto__:null,},HashChangeEvent:{initHashChangeEvent:"[type], [canBubble], [cancelable], [oldURL], [newURL]",__proto__:null,},History:{go:"[distance]",pushState:"data, title, [url]",replaceState:"data, title, [url]",__proto__:null,},IDBCursor:{advance:"count",continue:"[key]",update:"value",__proto__:null,},IDBDatabase:{createObjectStore:"name, [options]",deleteObjectStore:"name",transaction:"storeName, [mode]",__proto__:null,},IDBFactory:{cmp:"first, second",deleteDatabase:"name",open:"name, [version]",__proto__:null,},IDBIndex:{count:"[range]",get:"key",getKey:"key",openCursor:"[range], [direction]",openKeyCursor:"[range], [direction]",__proto__:null,},IDBObjectStore:{add:"value, [key]",count:"[range]",createIndex:"name, keyPath, [options]",delete:"keyRange",deleteIndex:"name",get:"key",index:"name",openCursor:"[range], [direction]",put:"value, [key]",__proto__:null,},IDBTransaction:{objectStore:"name",__proto__:null,},ImageBitmapRenderingContext:{transferFromImageBitmap:"[bitmap]",__proto__:null,},KeyboardEvent:{initKeyboardEvent:"[type], [canBubble], [cancelable], [view], [keyIdentifier], [location], [ctrlKey], [altKey], [shiftKey], [metaKey], [altGraphKey]",__proto__:null,},Location:{assign:"[url]",reload:"[force=false]",replace:"[url]",__proto__:null,},MediaController:{__proto__:null,},MediaControlsHost:{displayNameForTrack:"track",mediaUIImageData:"partID",setSelectedTextTrack:"track",sortedTrackListForMenu:"trackList",__proto__:null,},MediaList:{appendMedium:"[newMedium]",deleteMedium:"[oldMedium]",item:"[index]",__proto__:null,},MediaQueryList:{addListener:"[listener]",removeListener:"[listener]",__proto__:null,},MediaSource:{addSourceBuffer:"type",endOfStream:"[error]",removeSourceBuffer:"buffer",__proto__:null,},MediaStreamTrack:{applyConstraints:"constraints",__proto__:null,},MediaStreamTrackSourcesCallback:{handleEvent:"sources",__proto__:null,},MessageEvent:{initMessageEvent:"type, [bubbles], [cancelable], [data], [origin], [lastEventId], [source], [messagePorts]",__proto__:null,},MessagePort:{__proto__:null,},MimeTypeArray:{item:"[index]",namedItem:"[name]",__proto__:null,},MouseEvent:{initMouseEvent:"[type], [canBubble], [cancelable], [view], [detail], [screenX], [screenY], [clientX], [clientY], [ctrlKey], [altKey], [shiftKey], [metaKey], [button], [relatedTarget]",__proto__:null,},MutationEvent:{initMutationEvent:"[type], [canBubble], [cancelable], [relatedNode], [prevValue], [newValue], [attrName], [attrChange]",__proto__:null,},MutationObserver:{observe:"target, options",__proto__:null,},NamedNodeMap:{getNamedItem:"[name]",getNamedItemNS:"[namespaceURI], [localName]",item:"[index]",removeNamedItem:"[name]",removeNamedItemNS:"[namespaceURI], [localName]",setNamedItem:"[node]",setNamedItemNS:"[node]",__proto__:null,},Navigator:{getUserMedia:"options, successCallback, errorCallback",__proto__:null,},NavigatorUserMediaErrorCallback:{handleEvent:"error",__proto__:null,},NavigatorUserMediaSuccessCallback:{handleEvent:"stream",__proto__:null,},NodeFilter:{acceptNode:"[n]",__proto__:null,},NodeList:{item:"index",__proto__:null,},Notification:{__proto__:null,},NotificationCenter:{createNotification:"iconUrl, title, body",requestPermission:"[callback]",__proto__:null,},NotificationPermissionCallback:{handleEvent:"permission",__proto__:null,},OESVertexArrayObject:{bindVertexArrayOES:"[arrayObject]",deleteVertexArrayOES:"[arrayObject]",isVertexArrayOES:"[arrayObject]",__proto__:null,},OscillatorNode:{noteOff:"when",noteOn:"when",setPeriodicWave:"wave",start:"[when]",stop:"[when]",__proto__:null,},Path2D:{addPath:"path, [transform]",arc:"[x], [y], [radius], [startAngle], [endAngle], [anticlockwise]",arcTo:"[x1], [y1], [x2], [y2], [radius]",bezierCurveTo:"[cp1x], [cp1y], [cp2x], [cp2y], [x], [y]",ellipse:"x, y, radiusX, radiusY, rotation, startAngle, endAngle, [anticlockwise]",lineTo:"[x], [y]",moveTo:"[x], [y]",quadraticCurveTo:"[cpx], [cpy], [x], [y]",rect:"[x], [y], [width], [height]",__proto__:null,},Performance:{clearMarks:"[name]",clearMeasures:"name",getEntriesByName:"name, [type]",getEntriesByType:"type",mark:"name",measure:"name, [startMark], [endMark]",__proto__:null,},PerformanceObserver:{observe:"options",__proto__:null,},PerformanceObserverEntryList:{getEntriesByName:"name, [type]",getEntriesByType:"type",__proto__:null,},Plugin:{item:"[index]",namedItem:"[name]",__proto__:null,},PluginArray:{item:"[index]",namedItem:"[name]",refresh:"[reload]",__proto__:null,},PositionCallback:{handleEvent:"position",__proto__:null,},PositionErrorCallback:{handleEvent:"error",__proto__:null,},RTCDTMFSender:{insertDTMF:"tones, [duration], [interToneGap]",__proto__:null,},RTCDataChannel:{send:"data",__proto__:null,},RTCPeerConnectionErrorCallback:{handleEvent:"error",__proto__:null,},RTCSessionDescriptionCallback:{handleEvent:"sdp",__proto__:null,},RTCStatsCallback:{handleEvent:"response",__proto__:null,},RTCStatsReport:{stat:"name",__proto__:null,},RTCStatsResponse:{namedItem:"[name]",__proto__:null,},Range:{collapse:"[toStart]",compareBoundaryPoints:"[how], [sourceRange]",compareNode:"[refNode]",comparePoint:"[refNode], [offset]",createContextualFragment:"[html]",expand:"[unit]",insertNode:"[newNode]",intersectsNode:"[refNode]",isPointInRange:"[refNode], [offset]",selectNode:"[refNode]",selectNodeContents:"[refNode]",setEnd:"[refNode], [offset]",setEndAfter:"[refNode]",setEndBefore:"[refNode]",setStart:"[refNode], [offset]",setStartAfter:"[refNode]",setStartBefore:"[refNode]",surroundContents:"[newParent]",__proto__:null,},ReadableStream:{cancel:"reason",pipeThrough:"dest, options",pipeTo:"streams, options",__proto__:null,},WritableStream:{abort:"reason",close:"",write:"chunk",__proto__:null,},RequestAnimationFrameCallback:{handleEvent:"highResTime",__proto__:null,},SQLResultSetRowList:{item:"index",__proto__:null,},SQLStatementCallback:{handleEvent:"transaction, resultSet",__proto__:null,},SQLStatementErrorCallback:{handleEvent:"transaction, error",__proto__:null,},SQLTransaction:{executeSql:"sqlStatement, arguments, [callback], [errorCallback]",__proto__:null,},SQLTransactionCallback:{handleEvent:"transaction",__proto__:null,},SQLTransactionErrorCallback:{handleEvent:"error",__proto__:null,},SVGAngle:{convertToSpecifiedUnits:"unitType",newValueSpecifiedUnits:"unitType, valueInSpecifiedUnits",__proto__:null,},SVGAnimationElement:{beginElementAt:"[offset]",endElementAt:"[offset]",hasExtension:"[extension]",__proto__:null,},SVGColor:{setColor:"colorType, rgbColor, iccColor",setRGBColor:"rgbColor",setRGBColorICCColor:"rgbColor, iccColor",__proto__:null,},SVGCursorElement:{hasExtension:"[extension]",__proto__:null,},SVGDocument:{createEvent:"[eventType]",__proto__:null,},SVGElement:{getPresentationAttribute:"[name]",__proto__:null,},SVGFEDropShadowElement:{setStdDeviation:"[stdDeviationX], [stdDeviationY]",__proto__:null,},SVGFEGaussianBlurElement:{setStdDeviation:"[stdDeviationX], [stdDeviationY]",__proto__:null,},SVGFEMorphologyElement:{setRadius:"[radiusX], [radiusY]",__proto__:null,},SVGFilterElement:{setFilterRes:"[filterResX], [filterResY]",__proto__:null,},SVGGraphicsElement:{getTransformToElement:"[element]",hasExtension:"[extension]",__proto__:null,},SVGLength:{convertToSpecifiedUnits:"unitType",newValueSpecifiedUnits:"unitType, valueInSpecifiedUnits",__proto__:null,},SVGLengthList:{appendItem:"item",getItem:"index",initialize:"item",insertItemBefore:"item, index",removeItem:"index",replaceItem:"item, index",__proto__:null,},SVGMarkerElement:{setOrientToAngle:"[angle]",__proto__:null,},SVGMaskElement:{hasExtension:"[extension]",__proto__:null,},SVGMatrix:{multiply:"secondMatrix",rotate:"angle",rotateFromVector:"x, y",scale:"scaleFactor",scaleNonUniform:"scaleFactorX, scaleFactorY",skewX:"angle",skewY:"angle",translate:"x, y",__proto__:null,},SVGNumberList:{appendItem:"item",getItem:"index",initialize:"item",insertItemBefore:"item, index",removeItem:"index",replaceItem:"item, index",__proto__:null,},SVGPaint:{setPaint:"paintType, uri, rgbColor, iccColor",setUri:"uri",__proto__:null,},SVGPathElement:{createSVGPathSegArcAbs:"[x], [y], [r1], [r2], [angle], [largeArcFlag], [sweepFlag]",createSVGPathSegArcRel:"[x], [y], [r1], [r2], [angle], [largeArcFlag], [sweepFlag]",createSVGPathSegCurvetoCubicAbs:"[x], [y], [x1], [y1], [x2], [y2]",createSVGPathSegCurvetoCubicRel:"[x], [y], [x1], [y1], [x2], [y2]",createSVGPathSegCurvetoCubicSmoothAbs:"[x], [y], [x2], [y2]",createSVGPathSegCurvetoCubicSmoothRel:"[x], [y], [x2], [y2]",createSVGPathSegCurvetoQuadraticAbs:"[x], [y], [x1], [y1]",createSVGPathSegCurvetoQuadraticRel:"[x], [y], [x1], [y1]",createSVGPathSegCurvetoQuadraticSmoothAbs:"[x], [y]",createSVGPathSegCurvetoQuadraticSmoothRel:"[x], [y]",createSVGPathSegLinetoAbs:"[x], [y]",createSVGPathSegLinetoHorizontalAbs:"[x]",createSVGPathSegLinetoHorizontalRel:"[x]",createSVGPathSegLinetoRel:"[x], [y]",createSVGPathSegLinetoVerticalAbs:"[y]",createSVGPathSegLinetoVerticalRel:"[y]",createSVGPathSegMovetoAbs:"[x], [y]",createSVGPathSegMovetoRel:"[x], [y]",getPathSegAtLength:"[distance]",getPointAtLength:"[distance]",__proto__:null,},SVGPathSegList:{appendItem:"newItem",getItem:"index",initialize:"newItem",insertItemBefore:"newItem, index",removeItem:"index",replaceItem:"newItem, index",__proto__:null,},SVGPatternElement:{hasExtension:"[extension]",__proto__:null,},SVGPoint:{matrixTransform:"matrix",__proto__:null,},SVGPointList:{appendItem:"item",getItem:"index",initialize:"item",insertItemBefore:"item, index",removeItem:"index",replaceItem:"item, index",__proto__:null,},SVGSVGElement:{checkEnclosure:"[element], [rect]",checkIntersection:"[element], [rect]",createSVGTransformFromMatrix:"[matrix]",getElementById:"[elementId]",getEnclosureList:"[rect], [referenceElement]",getIntersectionList:"[rect], [referenceElement]",setCurrentTime:"[seconds]",suspendRedraw:"[maxWaitMilliseconds]",unsuspendRedraw:"[suspendHandleId]",__proto__:null,},SVGStringList:{appendItem:"item",getItem:"index",initialize:"item",insertItemBefore:"item, index",removeItem:"index",replaceItem:"item, index",__proto__:null,},SVGTextContentElement:{getCharNumAtPosition:"[point]",getEndPositionOfChar:"[offset]",getExtentOfChar:"[offset]",getRotationOfChar:"[offset]",getStartPositionOfChar:"[offset]",getSubStringLength:"[offset], [length]",selectSubString:"[offset], [length]",__proto__:null,},SVGTransform:{setMatrix:"matrix",setRotate:"angle, cx, cy",setScale:"sx, sy",setSkewX:"angle",setSkewY:"angle",setTranslate:"tx, ty",__proto__:null,},SVGTransformList:{appendItem:"item",createSVGTransformFromMatrix:"matrix",getItem:"index",initialize:"item",insertItemBefore:"item, index",removeItem:"index",replaceItem:"item, index",__proto__:null,},SecurityPolicy:{allowsConnectionTo:"url",allowsFontFrom:"url",allowsFormAction:"url",allowsFrameFrom:"url",allowsImageFrom:"url",allowsMediaFrom:"url",allowsObjectFrom:"url",allowsPluginType:"type",allowsScriptFrom:"url",allowsStyleFrom:"url",__proto__:null,},Selection:{addRange:"[range]",collapse:"[node], [index]",containsNode:"[node], [allowPartial]",extend:"[node], [offset]",getRangeAt:"[index]",modify:"[alter], [direction], [granularity]",selectAllChildren:"[node]",setBaseAndExtent:"[baseNode], [baseOffset], [extentNode], [extentOffset]",setPosition:"[node], [offset]",__proto__:null,},SourceBuffer:{appendBuffer:"data",remove:"start, end",__proto__:null,},SourceBufferList:{item:"index",__proto__:null,},SpeechSynthesis:{speak:"utterance",__proto__:null,},SpeechSynthesisUtterance:{__proto__:null,},Storage:{getItem:"key",key:"index",removeItem:"key",setItem:"key, data",__proto__:null,},StorageErrorCallback:{handleEvent:"error",__proto__:null,},StorageEvent:{initStorageEvent:"[typeArg], [canBubbleArg], [cancelableArg], [keyArg], [oldValueArg], [newValueArg], [urlArg], [storageAreaArg]",__proto__:null,},StorageInfo:{queryUsageAndQuota:"storageType, [usageCallback], [errorCallback]",requestQuota:"storageType, newQuotaInBytes, [quotaCallback], [errorCallback]",__proto__:null,},StorageQuota:{queryUsageAndQuota:"usageCallback, [errorCallback]",requestQuota:"newQuotaInBytes, [quotaCallback], [errorCallback]",__proto__:null,},StorageQuotaCallback:{handleEvent:"grantedQuotaInBytes",__proto__:null,},StorageUsageCallback:{handleEvent:"currentUsageInBytes, currentQuotaInBytes",__proto__:null,},StringCallback:{handleEvent:"data",__proto__:null,},StyleSheetList:{item:"[index]",__proto__:null,},Text:{replaceWholeText:"[content]",splitText:"offset",__proto__:null,},TextEvent:{initTextEvent:"[typeArg], [canBubbleArg], [cancelableArg], [viewArg], [dataArg]",__proto__:null,},TextTrack:{addCue:"cue",addRegion:"region",removeCue:"cue",removeRegion:"region",__proto__:null,},TextTrackCue:{__proto__:null,},TextTrackCueList:{getCueById:"id",item:"index",__proto__:null,},TextTrackList:{getTrackById:"id",item:"index",__proto__:null,},TimeRanges:{end:"index",start:"index",__proto__:null,},TouchEvent:{initTouchEvent:"[touches], [targetTouches], [changedTouches], [type], [view], [screenX], [screenY], [clientX], [clientY], [ctrlKey], [altKey], [shiftKey], [metaKey]",__proto__:null,},TouchList:{item:"index",__proto__:null,},UIEvent:{initUIEvent:"[type], [canBubble], [cancelable], [view], [detail]",__proto__:null,},UserMessageHandler:{postMessage:"message",__proto__:null,},VTTRegionList:{getRegionById:"id",item:"index",__proto__:null,},VideoTrackList:{getTrackById:"id",item:"index",__proto__:null,},WebGL2RenderingContext:{beginQuery:"target, query",beginTransformFeedback:"primitiveMode",bindBufferBase:"target, index, buffer",bindBufferRange:"target, index, buffer, offset, size",bindSampler:"unit, sampler",bindTransformFeedback:"target, id",bindVertexArray:"vertexArray",blitFramebuffer:"srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter",clearBufferfi:"buffer, drawbuffer, depth, stencil",clearBufferfv:"buffer, drawbuffer, value",clearBufferiv:"buffer, drawbuffer, value",clearBufferuiv:"buffer, drawbuffer, value",clientWaitSync:"sync, flags, timeout",compressedTexImage3D:"target, level, internalformat, width, height, depth, border, imageSize, data",compressedTexSubImage3D:"target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data",copyBufferSubData:"readTarget, writeTarget, readOffset, writeOffset, size",copyTexSubImage3D:"target, level, xoffset, yoffset, zoffset, x, y, width, height",deleteQuery:"query",deleteSampler:"sampler",deleteSync:"sync",deleteTransformFeedback:"id",deleteVertexArray:"vertexArray",drawArraysInstanced:"mode, first, count, instanceCount",drawBuffers:"buffers",drawElementsInstanced:"mode, count, type, offset, instanceCount",drawRangeElements:"mode, start, end, count, type, offset",endQuery:"target",fenceSync:"condition, flags",framebufferTextureLayer:"target, attachment, texture, level, layer",getActiveUniformBlockName:"program, uniformBlockIndex",getActiveUniformBlockParameter:"program, uniformBlockIndex, pname",getActiveUniforms:"program, uniformIndices, pname",getBufferSubData:"target, offset, returnedData",getFragDataLocation:"program, name",getIndexedParameter:"target, index",getInternalformatParameter:"target, internalformat, pname",getQuery:"target, pname",getQueryParameter:"query, pname",getSamplerParameter:"sampler, pname",getSyncParameter:"sync, pname",getTransformFeedbackVarying:"program, index",getUniformBlockIndex:"program, uniformBlockName",getUniformIndices:"program, uniformNames",invalidateFramebuffer:"target, attachments",invalidateSubFramebuffer:"target, attachments, x, y, width, height",isQuery:"query",isSampler:"sampler",isSync:"sync",isTransformFeedback:"id",isVertexArray:"vertexArray",readBuffer:"src",renderbufferStorageMultisample:"target, samples, internalformat, width, height",samplerParameterf:"sampler, pname, param",samplerParameteri:"sampler, pname, param",texImage3D:"target, level, internalformat, width, height, depth, border, format, type, pixels",texStorage2D:"target, levels, internalformat, width, height",texStorage3D:"target, levels, internalformat, width, height, depth",texSubImage3D:"target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels",transformFeedbackVaryings:"program, varyings, bufferMode",uniform1ui:"location, v0",uniform1uiv:"location, value",uniform2ui:"location, v0, v1",uniform2uiv:"location, value",uniform3ui:"location, v0, v1, v2",uniform3uiv:"location, value",uniform4ui:"location, v0, v1, v2, v3",uniform4uiv:"location, value",uniformBlockBinding:"program, uniformBlockIndex, uniformBlockBinding",uniformMatrix2x3fv:"location, transpose, value",uniformMatrix2x4fv:"location, transpose, value",uniformMatrix3x2fv:"location, transpose, value",uniformMatrix3x4fv:"location, transpose, value",uniformMatrix4x2fv:"location, transpose, value",uniformMatrix4x3fv:"location, transpose, value",vertexAttribDivisor:"index, divisor",vertexAttribI4i:"index, x, y, z, w",vertexAttribI4iv:"index, v",vertexAttribI4ui:"index, x, y, z, w",vertexAttribI4uiv:"index, v",vertexAttribIPointer:"index, size, type, stride, offset",waitSync:"sync, flags, timeout",__proto__:null,},WebGLDebugShaders:{getTranslatedShaderSource:"shader",__proto__:null,},WebGLDrawBuffers:{drawBuffersWEBGL:"buffers",__proto__:null,},WebGLMultiDraw:{multiDrawArraysWebGL:"mode, firstsList, firstsOffset, countsList, countsOffset, drawcount",multiDrawArraysInstancedWebGL:"mode, firstsList, firstsOffset, countsList, countsOffset, instanceCountsList, instanceCountsOffset, drawcount",multiDrawElementsWebGL:"mode, countsList, countsOffset, type, offsetsList, offsetsOffset, drawcount",multiDrawElementsInstancedWebGL:"mode, countsList, countsOffset, type, offsetsList, offsetsOffset, instanceCountsList, instanceCountsOffset, drawcount",__proto__:null,},WebGLRenderingContextBase:{activeTexture:"texture",attachShader:"program, shader",bindAttribLocation:"program, index, name",bindBuffer:"target, buffer",bindFramebuffer:"target, framebuffer",bindRenderbuffer:"target, renderbuffer",bindTexture:"target, texture",blendColor:"red, green, blue, alpha",blendEquation:"mode",blendEquationSeparate:"modeRGB, modeAlpha",blendFunc:"sfactor, dfactor",blendFuncSeparate:"srcRGB, dstRGB, srcAlpha, dstAlpha",bufferData:"target, data, usage",bufferSubData:"target, offset, data",checkFramebufferStatus:"target",clear:"mask",clearColor:"red, green, blue, alpha",clearDepth:"depth",clearStencil:"s",colorMask:"red, green, blue, alpha",compileShader:"shader",compressedTexImage2D:"target, level, internalformat, width, height, border, data",compressedTexSubImage2D:"target, level, xoffset, yoffset, width, height, format, data",copyTexImage2D:"target, level, internalformat, x, y, width, height, border",copyTexSubImage2D:"target, level, xoffset, yoffset, x, y, width, height",createShader:"type",cullFace:"mode",deleteBuffer:"buffer",deleteFramebuffer:"framebuffer",deleteProgram:"program",deleteRenderbuffer:"renderbuffer",deleteShader:"shader",deleteTexture:"texture",depthFunc:"func",depthMask:"flag",depthRange:"zNear, zFar",detachShader:"program, shader",disable:"cap",disableVertexAttribArray:"index",drawArrays:"mode, first, count",drawElements:"mode, count, type, offset",enable:"cap",enableVertexAttribArray:"index",framebufferRenderbuffer:"target, attachment, renderbuffertarget, renderbuffer",framebufferTexture2D:"target, attachment, textarget, texture, level",frontFace:"mode",generateMipmap:"target",getActiveAttrib:"program, index",getActiveUniform:"program, index",getAttachedShaders:"program",getAttribLocation:"program, name",getBufferParameter:"target, pname",getExtension:"name",getFramebufferAttachmentParameter:"target, attachment, pname",getParameter:"pname",getProgramInfoLog:"program",getProgramParameter:"program, pname",getRenderbufferParameter:"target, pname",getShaderInfoLog:"shader",getShaderParameter:"shader, pname",getShaderPrecisionFormat:"shadertype, precisiontype",getShaderSource:"shader",getTexParameter:"target, pname",getUniform:"program, location",getUniformLocation:"program, name",getVertexAttrib:"index, pname",getVertexAttribOffset:"index, pname",hint:"target, mode",isBuffer:"buffer",isEnabled:"cap",isFramebuffer:"framebuffer",isProgram:"program",isRenderbuffer:"renderbuffer",isShader:"shader",isTexture:"texture",lineWidth:"width",linkProgram:"program",pixelStorei:"pname, param",polygonOffset:"factor, units",readPixels:"x, y, width, height, format, type, pixels",renderbufferStorage:"target, internalformat, width, height",sampleCoverage:"value, invert",scissor:"x, y, width, height",shaderSource:"shader, string",stencilFunc:"func, ref, mask",stencilFuncSeparate:"face, func, ref, mask",stencilMask:"mask",stencilMaskSeparate:"face, mask",stencilOp:"fail, zfail, zpass",stencilOpSeparate:"face, fail, zfail, zpass",texImage2D:"target, level, internalformat, width, height, border, format, type, pixels",texParameterf:"target, pname, param",texParameteri:"target, pname, param",texSubImage2D:"target, level, xoffset, yoffset, width, height, format, type, pixels",uniform1f:"location, x",uniform1fv:"location, v",uniform1i:"location, x",uniform1iv:"location, v",uniform2f:"location, x, y",uniform2fv:"location, v",uniform2i:"location, x, y",uniform2iv:"location, v",uniform3f:"location, x, y, z",uniform3fv:"location, v",uniform3i:"location, x, y, z",uniform3iv:"location, v",uniform4f:"location, x, y, z, w",uniform4fv:"location, v",uniform4i:"location, x, y, z, w",uniform4iv:"location, v",uniformMatrix2fv:"location, transpose, array",uniformMatrix3fv:"location, transpose, array",uniformMatrix4fv:"location, transpose, array",useProgram:"program",validateProgram:"program",vertexAttrib1f:"indx, x",vertexAttrib1fv:"indx, values",vertexAttrib2f:"indx, x, y",vertexAttrib2fv:"indx, values",vertexAttrib3f:"indx, x, y, z",vertexAttrib3fv:"indx, values",vertexAttrib4f:"indx, x, y, z, w",vertexAttrib4fv:"indx, values",vertexAttribPointer:"indx, size, type, normalized, stride, offset",viewport:"x, y, width, height",__proto__:null,},WebKitCSSMatrix:{multiply:"[secondMatrix]",rotate:"[rotX], [rotY], [rotZ]",rotateAxisAngle:"[x], [y], [z], [angle]",scale:"[scaleX], [scaleY], [scaleZ]",setMatrixValue:"[string]",skewX:"[angle]",skewY:"[angle]",translate:"[x], [y], [z]",__proto__:null,},WebKitMediaKeySession:{update:"key",__proto__:null,},WebKitMediaKeys:{createSession:"[type], [initData]",__proto__:null,},WebKitNamedFlow:{getRegionsByContent:"contentNode",__proto__:null,},WebKitNamedFlowCollection:{item:"index",namedItem:"name",__proto__:null,},WebKitSubtleCrypto:{decrypt:"algorithm, key, data",digest:"algorithm, data",encrypt:"algorithm, key, data",exportKey:"format, key",generateKey:"algorithm, [extractable], [keyUsages]",importKey:"format, keyData, algorithm, [extractable], [keyUsages]",sign:"algorithm, key, data",unwrapKey:"format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, [extractable], [keyUsages]",verify:"algorithm, key, signature, data",wrapKey:"format, key, wrappingKey, wrapAlgorithm",__proto__:null,},WebSocket:{close:"[code], [reason]",send:"data",__proto__:null,},WheelEvent:{initWebKitWheelEvent:"[wheelDeltaX], [wheelDeltaY], [view], [screenX], [screenY], [clientX], [clientY], [ctrlKey], [altKey], [shiftKey], [metaKey]",__proto__:null,},Worker:{postMessage:"message, [messagePorts]",__proto__:null,},WorkerGlobalScope:{clearInterval:"[handle]",clearTimeout:"[handle]",setInterval:"handler, [timeout]",setTimeout:"handler, [timeout]",__proto__:null,},XMLHttpRequest:{getResponseHeader:"header",open:"method, url, [async], [user], [password]",overrideMimeType:"override",setRequestHeader:"header, value",__proto__:null,},XMLHttpRequestUpload:{__proto__:null,},XMLSerializer:{serializeToString:"[node]",__proto__:null,},XPathEvaluator:{createExpression:"[expression], [resolver]",createNSResolver:"[nodeResolver]",evaluate:"[expression], [contextNode], [resolver], [type], [inResult]",__proto__:null,},XPathExpression:{evaluate:"[contextNode], [type], [inResult]",__proto__:null,},XPathNSResolver:{lookupNamespaceURI:"[prefix]",__proto__:null,},XPathResult:{snapshotItem:"[index]",__proto__:null,},XSLTProcessor:{getParameter:"namespaceURI, localName",importStylesheet:"[stylesheet]",removeParameter:"namespaceURI, localName",setParameter:"namespaceURI, localName, value",transformToDocument:"[source]",transformToFragment:"[source], [docVal]",__proto__:null,},webkitAudioContext:{createBuffer:"numberOfChannels, numberOfFrames, sampleRate",createChannelMerger:"[numberOfInputs]",createChannelSplitter:"[numberOfOutputs]",createDelay:"[maxDelayTime]",createDelayNode:"[maxDelayTime]",createJavaScriptNode:"bufferSize, [numberOfInputChannels], [numberOfOutputChannels]",createMediaElementSource:"mediaElement",createPeriodicWave:"real, imag",createScriptProcessor:"bufferSize, [numberOfInputChannels], [numberOfOutputChannels]",decodeAudioData:"audioData, successCallback, [errorCallback]",__proto__:null,},webkitAudioPannerNode:{setOrientation:"x, y, z",setPosition:"x, y, z",setVelocity:"x, y, z",__proto__:null,},webkitMediaStream:{addTrack:"track",getTrackById:"trackId",removeTrack:"track",__proto__:null,},webkitRTCPeerConnection:{addIceCandidate:"candidate, successCallback, failureCallback",addStream:"stream",createAnswer:"successCallback, failureCallback, [answerOptions]",createDTMFSender:"track",createDataChannel:"label, [options]",createOffer:"successCallback, failureCallback, [offerOptions]",getStats:"successCallback, failureCallback, [selector]",getStreamById:"streamId",removeStream:"stream",setLocalDescription:"description, successCallback, failureCallback",setRemoteDescription:"description, successCallback, failureCallback",updateIce:"configuration",__proto__:null,},EventTarget:{addEventListener:"type, listener, [useCapture=false]",removeEventListener:"type, listener, [useCapture=false]",dispatchEvent:"event",__proto__:null,},};(function(){var ElementQueries={getElementsByClassName:"classNames",getElementsByTagName:"tagName",getElementsByTagNameNS:"namespace, localName",querySelector:"selectors",querySelectorAll:"selectors",};Object.assign(WI.NativePrototypeFunctionParameters.Element,ElementQueries);Object.assign(WI.NativePrototypeFunctionParameters.Document,ElementQueries);var ChildNode={after:"[node|string]...",before:"[node|string]...",replaceWith:"[node|string]...",};Object.assign(WI.NativePrototypeFunctionParameters.Element,ChildNode);Object.assign(WI.NativePrototypeFunctionParameters.CharacterData,ChildNode);var ParentNode={append:"[node|string]...",prepend:"[node|string]...",};Object.assign(WI.NativePrototypeFunctionParameters.Element,ParentNode);Object.assign(WI.NativePrototypeFunctionParameters.Document,ParentNode);Object.assign(WI.NativePrototypeFunctionParameters.DocumentFragment,ParentNode);})();WI.NetworkInstrument=class NetworkInstrument extends WI.Instrument { get timelineRecordType() {return WI.TimelineRecord.Type.Network;} startInstrumentation(initiatedByBackend) {} stopInstrumentation(initiatedByBackend) {}};WI.NetworkTimeline=class NetworkTimeline extends WI.Timeline { recordForResource(resource) {return this._resourceRecordMap.get(resource)||null;} reset(suppressEvents) {this._resourceRecordMap=new Map;super.reset(suppressEvents);} addRecord(record,options={}) {if(this._resourceRecordMap.has(record.resource)) return;this._resourceRecordMap.set(record.resource,record);super.addRecord(record,options);}};WI.ObjectPreview=class ObjectPreview {constructor(type,subtype,description,lossless,overflow,properties,entries,size) {this._type=type;this._subtype=subtype;this._description=description||"";this._lossless=lossless;this._overflow=overflow||false;this._size=size;this._properties=properties||null;this._entries=entries||null;} static fromPayload(payload) {if(payload.properties) payload.properties=payload.properties.map(WI.PropertyPreview.fromPayload);if(payload.entries) payload.entries=payload.entries.map(WI.CollectionEntryPreview.fromPayload);return new WI.ObjectPreview(payload.type,payload.subtype,payload.description,payload.lossless,payload.overflow,payload.properties,payload.entries,payload.size);} get type(){return this._type;} get subtype(){return this._subtype;} get description(){return this._description;} get lossless(){return this._lossless;} get overflow(){return this._overflow;} get propertyPreviews(){return this._properties;} get collectionEntryPreviews(){return this._entries;} get size(){return this._size;} hasSize() {return this._size!==undefined&&(this._subtype==="array"||this._subtype==="set"||this._subtype==="map"||this._subtype==="weakmap"||this._subtype==="weakset");}};WI.ProbeSample=class ProbeSample {constructor(sampleId,batchId,elapsedTime,object) {this.sampleId=sampleId;this.batchId=batchId;this.timestamp=elapsedTime;this.object=object;}};WI.Probe=class Probe extends WI.Object {constructor(id,breakpoint,expression) {super();this._id=id;this._breakpoint=breakpoint;this._expression=expression;this._samples=[];} get id() {return this._id;} get breakpoint() {return this._breakpoint;} get expression() {return this._expression;} set expression(value) {if(this._expression===value) return;var data={oldValue:this._expression,newValue:value};this._expression=value;this.clearSamples();this.dispatchEventToListeners(WI.Probe.Event.ExpressionChanged,data);} get samples() {return this._samples.slice();} clearSamples() {this._samples=[];this.dispatchEventToListeners(WI.Probe.Event.SamplesCleared);} addSample(sample) {this._samples.push(sample);this.dispatchEventToListeners(WI.Probe.Event.SampleAdded,sample);}};WI.Probe.Event={ExpressionChanged:"probe-object-expression-changed",SampleAdded:"probe-object-sample-added",SamplesCleared:"probe-object-samples-cleared"};WI.ProbeSet=class ProbeSet extends WI.Object {constructor(breakpoint) {super();this._breakpoint=breakpoint;this._probes=[];this._probesByIdentifier=new Map;this._createDataTable();WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceChanged,this);WI.Probe.addEventListener(WI.Probe.Event.SampleAdded,this._sampleCollected,this);} get breakpoint(){return this._breakpoint;} get probes(){return this._probes.slice();} get dataTable(){return this._dataTable;} clear() {this._breakpoint.clearActions(WI.BreakpointAction.Type.Probe);} clearSamples() {for(var probe of this._probes) probe.clearSamples();var oldTable=this._dataTable;this._createDataTable();this.dispatchEventToListeners(WI.ProbeSet.Event.SamplesCleared,{oldTable});} createProbe(expression) {this._breakpoint.addAction(new WI.BreakpointAction(WI.BreakpointAction.Type.Probe,{data:expression}));} addProbe(probe) {this._probes.push(probe);this._probesByIdentifier.set(probe.id,probe);this.dataTable.addProbe(probe);this.dispatchEventToListeners(WI.ProbeSet.Event.ProbeAdded,probe);} removeProbe(probe) {this._probes.splice(this._probes.indexOf(probe),1);this._probesByIdentifier.delete(probe.id);this.dataTable.removeProbe(probe);this.dispatchEventToListeners(WI.ProbeSet.Event.ProbeRemoved,probe);} willRemove() {WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceChanged,this);WI.Probe.removeEventListener(WI.Probe.Event.SampleAdded,this._sampleCollected,this);} _mainResourceChanged() {this.dataTable.mainResourceChanged();} _createDataTable() {if(this.dataTable) this.dataTable.willRemove();this._dataTable=new WI.ProbeSetDataTable(this);} _sampleCollected(event) {var sample=event.data;var probe=event.target;if(!this._probesByIdentifier.has(probe.id)) return;this.dataTable.addSampleForProbe(probe,sample);this.dispatchEventToListeners(WI.ProbeSet.Event.SampleAdded,{probe,sample});}};WI.ProbeSet.Event={ProbeAdded:"probe-set-probe-added",ProbeRemoved:"probe-set-probe-removed",SampleAdded:"probe-set-sample-added",SamplesCleared:"probe-set-samples-cleared",};WI.ProbeSetDataFrame=class ProbeSetDataFrame {constructor(index) {this._count=0;this._index=index;this._separator=false;} static compare(a,b) {return a.index-b.index;} get key() {return String(this._index);} get count() {return this._count;} get index() {return this._index;} get isSeparator() {return this._separator;} set isSeparator(value) {this._separator=!!value;} addSampleForProbe(probe,sample) {this[probe.id]=sample;this._count++;} missingKeys(probeSet) {return probeSet.probes.filter(function(probe){return!this.hasOwnProperty(probe.id);},this);} isComplete(probeSet) {return!this.missingKeys(probeSet).length;} fillMissingValues(probeSet) {for(var key of this.missingKeys(probeSet)) this[key]=WI.ProbeSetDataFrame.MissingValue;}};WI.ProbeSetDataFrame.MissingValue="?";WI.ProbeSetDataTable=class ProbeSetDataTable extends WI.Object {constructor(probeSet) {super();this._probeSet=probeSet;this._frames=[];this._previousBatchIdentifier=WI.ProbeSetDataTable.SentinelValue;} get frames() {return this._frames.slice();} get separators() {return this._frames.filter(function(frame){return frame.isSeparator;});} willRemove() {this.dispatchEventToListeners(WI.ProbeSetDataTable.Event.WillRemove);this._frames=[];delete this._probeSet;} mainResourceChanged() {this.addSeparator();} addSampleForProbe(probe,sample) {if(sample.batchId!==this._previousBatchIdentifier){if(this._openFrame){this._openFrame.fillMissingValues(this._probeSet);this.addFrame(this._openFrame);} this._openFrame=this.createFrame();this._previousBatchIdentifier=sample.batchId;} this._openFrame.addSampleForProbe(probe,sample);if(this._openFrame.count===this._probeSet.probes.length){this.addFrame(this._openFrame);this._openFrame=null;}} addProbe(probe) {for(var frame of this.frames) if(!frame[probe.id]) frame[probe.id]=WI.ProbeSetDataTable.UnknownValue;} removeProbe(probe) {for(var frame of this.frames) delete frame[probe.id];} createFrame() {return new WI.ProbeSetDataFrame(this._frames.length);} addFrame(frame) {this._frames.push(frame);this.dispatchEventToListeners(WI.ProbeSetDataTable.Event.FrameInserted,frame);} addSeparator() {if(!this._frames.length) return;var previousFrame=this._frames.lastValue;if(previousFrame.isSeparator) return;previousFrame.isSeparator=true;this.dispatchEventToListeners(WI.ProbeSetDataTable.Event.SeparatorInserted,previousFrame);}};WI.ProbeSetDataTable.Event={FrameInserted:"probe-set-data-table-frame-inserted",SeparatorInserted:"probe-set-data-table-separator-inserted",WillRemove:"probe-set-data-table-will-remove"};WI.ProbeSetDataTable.SentinelValue=-1;WI.ProbeSetDataTable.UnknownValue="?";WI.Profile=class Profile {constructor(topDownRootNodes) {topDownRootNodes=topDownRootNodes||[];this._topDownRootNodes=topDownRootNodes;} get topDownRootNodes() {return this._topDownRootNodes;} get bottomUpRootNodes() {return[];}};WI.ProfileNode=class ProfileNode {constructor(id,type,functionName,sourceCodeLocation,callInfo,childNodes) {childNodes=childNodes||[];this._id=id;this._type=type||WI.ProfileNode.Type.Function;this._functionName=functionName||null;this._sourceCodeLocation=sourceCodeLocation||null;this._callInfo=callInfo;this._childNodes=childNodes;this._parentNode=null;this._previousSibling=null;this._nextSibling=null;this._computedTotalTimes=false;this._startTime=this._callInfo.startTime;this._endTime=this._callInfo.endTime;this._totalTime=this._callInfo.totalTime;this._callCount=this._callInfo.callCount;for(var i=0;iframe.actions));this._visualActionIndexes=[];this._source=null;this._processContext=null;this._processStates=[];this._processing=false;} static fromPayload(payload,frames) {if(typeof payload!=="object"||payload===null) return null;if(typeof payload.version!=="number"){WI.Recording.synthesizeError(WI.UIString("non-number %s").format(WI.unlocalizedString("version")));return null;} if(payload.version<1||payload.version>WI.Recording.Version){WI.Recording.synthesizeError(WI.UIString("unsupported %s").format(WI.unlocalizedString("version")));return null;} if(parseInt(payload.version)!==payload.version){WI.Recording.synthesizeWarning(WI.UIString("non-integer %s").format(WI.unlocalizedString("version")));payload.version=parseInt(payload.version);} let type=null;switch(payload.type){case InspectorBackend.Enum.Recording.Type.Canvas2D:type=WI.Recording.Type.Canvas2D;break;case InspectorBackend.Enum.Recording.Type.OffscreenCanvas2D:type=WI.Recording.Type.OffscreenCanvas2D;break;case InspectorBackend.Enum.Recording.Type.CanvasBitmapRenderer:type=WI.Recording.Type.CanvasBitmapRenderer;break;case InspectorBackend.Enum.Recording.Type.OffscreenCanvasBitmapRenderer:type=WI.Recording.Type.OffscreenCanvasBitmapRenderer;break;case InspectorBackend.Enum.Recording.Type.CanvasWebGL:type=WI.Recording.Type.CanvasWebGL;break;case InspectorBackend.Enum.Recording.Type.OffscreenCanvasWebGL:type=WI.Recording.Type.OffscreenCanvasWebGL;break;case InspectorBackend.Enum.Recording.Type.CanvasWebGL2:type=WI.Recording.Type.CanvasWebGL2;break;case InspectorBackend.Enum.Recording.Type.OffscreenCanvasWebGL2:type=WI.Recording.Type.OffscreenCanvasWebGL2;break;default:WI.Recording.synthesizeWarning(WI.UIString("unknown %s \u0022%s\u0022").format(WI.unlocalizedString("type"),payload.type));type=String(payload.type);break;} if(typeof payload.initialState!=="object"||payload.initialState===null){if("initialState"in payload) WI.Recording.synthesizeWarning(WI.UIString("non-object %s").format(WI.unlocalizedString("initialState")));payload.initialState={};} if(typeof payload.initialState.attributes!=="object"||payload.initialState.attributes===null){if("attributes"in payload.initialState) WI.Recording.synthesizeWarning(WI.UIString("non-object %s").format(WI.unlocalizedString("initialState.attributes")));payload.initialState.attributes={};} if(!Array.isArray(payload.initialState.states)||payload.initialState.states.some((item)=>typeof item!=="object"||item===null)){if("states"in payload.initialState) WI.Recording.synthesizeWarning(WI.UIString("non-array %s").format(WI.unlocalizedString("initialState.states")));payload.initialState.states=[]; if(!isEmptyObject(payload.initialState.attributes)){let{width,height,...state}=payload.initialState.attributes;if(!isEmptyObject(state)) payload.initialState.states.push(state);}} if(!Array.isArray(payload.initialState.parameters)){if("parameters"in payload.initialState) WI.Recording.synthesizeWarning(WI.UIString("non-array %s").format(WI.unlocalizedString("initialState.attributes")));payload.initialState.parameters=[];} if(typeof payload.initialState.content!=="string"){if("content"in payload.initialState) WI.Recording.synthesizeWarning(WI.UIString("non-string %s").format(WI.unlocalizedString("initialState.content")));payload.initialState.content="";} if(!Array.isArray(payload.frames)){if("frames"in payload) WI.Recording.synthesizeWarning(WI.UIString("non-array %s").format(WI.unlocalizedString("frames")));payload.frames=[];} if(!Array.isArray(payload.data)){if("data"in payload) WI.Recording.synthesizeWarning(WI.UIString("non-array %s").format(WI.unlocalizedString("data")));payload.data=[];} if(!frames) frames=payload.frames.map(WI.RecordingFrame.fromPayload) return new WI.Recording(payload.version,type,payload.initialState,frames,payload.data);} static displayNameForRecordingType(recordingType) {switch(recordingType){case Recording.Type.Canvas2D:return WI.UIString("2D","Recording Type Canvas 2D","A type of canvas recording in the Graphics Tab.");case Recording.Type.OffscreenCanvas2D:return WI.UIString("Offscreen2D","Recording Type Offscreen Canvas 2D","A type of canvas recording in the Graphics Tab.");case Recording.Type.CanvasBitmapRenderer:return WI.UIString("Bitmap Renderer","Recording Type Canvas Bitmap Renderer","A type of canvas recording in the Graphics Tab.");case Recording.Type.OffscreenCanvasBitmapRenderer:return WI.UIString("Bitmap Renderer (Offscreen)","Recording Type Offscreen Canvas Bitmap Renderer","A type of canvas recording in the Graphics Tab.");case Recording.Type.CanvasWebGL:return WI.UIString("WebGL","Recording Type Canvas WebGL","A type of canvas recording in the Graphics Tab.");case Recording.Type.OffscreenCanvasWebGL:return WI.UIString("WebGL (Offscreen)","Recording Type Offscreen Canvas WebGL","A type of canvas recording in the Graphics Tab.");case Recording.Type.CanvasWebGL2:return WI.UIString("WebGL2","Recording Type Canvas WebGL2","A type of canvas recording in the Graphics Tab.");case Recording.Type.OffscreenCanvasWebGL2:return WI.UIString("WebGL2 (Offscreen)","Recording Type Offscreen Canvas WebGL2","A type of canvas recording in the Graphics Tab.");} return null;} static displayNameForSwizzleType(swizzleType) {switch(swizzleType){case WI.Recording.Swizzle.None:return WI.unlocalizedString("None");case WI.Recording.Swizzle.Number:return WI.unlocalizedString("Number");case WI.Recording.Swizzle.Boolean:return WI.unlocalizedString("Boolean");case WI.Recording.Swizzle.String:return WI.unlocalizedString("String");case WI.Recording.Swizzle.Array:return WI.unlocalizedString("Array");case WI.Recording.Swizzle.TypedArray:return WI.unlocalizedString("TypedArray");case WI.Recording.Swizzle.Image:return WI.unlocalizedString("Image");case WI.Recording.Swizzle.ImageData:return WI.unlocalizedString("ImageData");case WI.Recording.Swizzle.DOMMatrix:return WI.unlocalizedString("DOMMatrix");case WI.Recording.Swizzle.Path2D:return WI.unlocalizedString("Path2D");case WI.Recording.Swizzle.CanvasGradient:return WI.unlocalizedString("CanvasGradient");case WI.Recording.Swizzle.CanvasPattern:return WI.unlocalizedString("CanvasPattern");case WI.Recording.Swizzle.WebGLBuffer:return WI.unlocalizedString("WebGLBuffer");case WI.Recording.Swizzle.WebGLFramebuffer:return WI.unlocalizedString("WebGLFramebuffer");case WI.Recording.Swizzle.WebGLRenderbuffer:return WI.unlocalizedString("WebGLRenderbuffer");case WI.Recording.Swizzle.WebGLTexture:return WI.unlocalizedString("WebGLTexture");case WI.Recording.Swizzle.WebGLShader:return WI.unlocalizedString("WebGLShader");case WI.Recording.Swizzle.WebGLProgram:return WI.unlocalizedString("WebGLProgram");case WI.Recording.Swizzle.WebGLUniformLocation:return WI.unlocalizedString("WebGLUniformLocation");case WI.Recording.Swizzle.ImageBitmap:return WI.unlocalizedString("ImageBitmap");case WI.Recording.Swizzle.WebGLQuery:return WI.unlocalizedString("WebGLQuery");case WI.Recording.Swizzle.WebGLSampler:return WI.unlocalizedString("WebGLSampler");case WI.Recording.Swizzle.WebGLSync:return WI.unlocalizedString("WebGLSync");case WI.Recording.Swizzle.WebGLTransformFeedback:return WI.unlocalizedString("WebGLTransformFeedback");case WI.Recording.Swizzle.WebGLVertexArrayObject:return WI.unlocalizedString("WebGLVertexArrayObject");case WI.Recording.Swizzle.DOMPointInit:return WI.unlocalizedString("DOMPointInit");default:console.error("Unknown swizzle type",swizzleType);return null;}} static synthesizeWarning(message) {message=WI.UIString("Recording Warning: %s").format(message);if(window.InspectorTest){console.warn(message);return;} let consoleMessage=new WI.ConsoleMessage(WI.mainTarget,WI.ConsoleMessage.MessageSource.Other,WI.ConsoleMessage.MessageLevel.Warning,message);consoleMessage.shouldRevealConsole=true;WI.consoleLogViewController.appendConsoleMessage(consoleMessage);} static synthesizeError(message) {message=WI.UIString("Recording Error: %s").format(message);if(window.InspectorTest){console.error(message);return;} let consoleMessage=new WI.ConsoleMessage(WI.mainTarget,WI.ConsoleMessage.MessageSource.Other,WI.ConsoleMessage.MessageLevel.Error,message);consoleMessage.shouldRevealConsole=true;WI.consoleLogViewController.appendConsoleMessage(consoleMessage);} get displayName(){return this._displayName;} get type(){return this._type;} get initialState(){return this._initialState;} get frames(){return this._frames;} get data(){return this._data;} get actions(){return this._actions;} get visualActionIndexes(){return this._visualActionIndexes;} get source(){return this._source;} set source(source){this._source=source;} get processing(){return this._processing;} get ready() {return this._actions.lastValue.ready;} get isCanvas() {return this.isCanvas2D||this.isCanvasBitmapRender||this.isCanvasWebGL||this.isCanvasWebGL2;} get isCanvas2D() {return this._type===WI.Recording.Type.Canvas2D||this._type===WI.Recording.Type.OffscreenCanvas2D;} get isCanvasBitmapRender() {return this._type===WI.Recording.Type.CanvasBitmapRenderer||this._type===WI.Recording.Type.OffscreenCanvasBitmapRenderer;} get isCanvasWebGL() {return this._type===WI.Recording.Type.CanvasWebGL||this._type===WI.Recording.Type.OffscreenCanvasWebGL;} get isCanvasWebGL2() {return this._type===WI.Recording.Type.CanvasWebGL2||this._type===WI.Recording.Type.OffscreenCanvasWebGL2;} startProcessing() {if(this._processing||this.ready) return;this._processing=true;this._process();} stopProcessing() {if(!this._processing||this.ready) return;this._processing=false;} createDisplayName(suggestedName) {let recordingNameSet;if(this._source){recordingNameSet=this._source[WI.Recording.CanvasRecordingNamesSymbol];if(!recordingNameSet) this._source[WI.Recording.CanvasRecordingNamesSymbol]=recordingNameSet=new Set;}else recordingNameSet=WI.Recording._importedRecordingNameSet;let name;if(suggestedName){name=suggestedName;let duplicateNumber=2;while(recordingNameSet.has(name)) name=`${suggestedName} (${duplicateNumber++})`;}else{let recordingNumber=1;do{name=WI.UIString("Recording %d").format(recordingNumber++);}while(recordingNameSet.has(name));} recordingNameSet.add(name);this._displayName=name;} is2D() {return WI.Recording.is2D(this._type);} async swizzle(index,type) {if(!this._swizzle) this._swizzle={};if(typeof this._swizzle[index]!=="object") this._swizzle[index]={};if(type===WI.Recording.Swizzle.Number) return parseFloat(index);if(type===WI.Recording.Swizzle.Boolean) return!!index;if(type===WI.Recording.Swizzle.Array) return Array.isArray(index)?index:[];if(type===WI.Recording.Swizzle.DOMMatrix) return new DOMMatrix(index); if(type===WI.Recording.Swizzle.TypedArray||type===WI.Recording.Swizzle.WebGLBuffer||type===WI.Recording.Swizzle.WebGLFramebuffer||type===WI.Recording.Swizzle.WebGLRenderbuffer||type===WI.Recording.Swizzle.WebGLTexture||type===WI.Recording.Swizzle.WebGLShader||type===WI.Recording.Swizzle.WebGLProgram||type===WI.Recording.Swizzle.WebGLUniformLocation||type===WI.Recording.Swizzle.WebGLQuery||type===WI.Recording.Swizzle.WebGLSampler||type===WI.Recording.Swizzle.WebGLSync||type===WI.Recording.Swizzle.WebGLTransformFeedback||type===WI.Recording.Swizzle.WebGLVertexArrayObject){return index;} if(!(type in this._swizzle[index])){try{let data=this._data[index];switch(type){case WI.Recording.Swizzle.None:this._swizzle[index][type]=data;break;case WI.Recording.Swizzle.String:if(Array.isArray(data)) this._swizzle[index][type]=await Promise.all(data.map((item)=>this.swizzle(item,WI.Recording.Swizzle.String)));else this._swizzle[index][type]=String(data);break;case WI.Recording.Swizzle.Image:this._swizzle[index][type]=await WI.ImageUtilities.promisifyLoad(data);this._swizzle[index][type].__data=data;break;case WI.Recording.Swizzle.ImageData:{let[object,width,height]=await Promise.all([this.swizzle(data[0],WI.Recording.Swizzle.Array),this.swizzle(data[1],WI.Recording.Swizzle.Number),this.swizzle(data[2],WI.Recording.Swizzle.Number),]);object=await Promise.all(object.map((item)=>this.swizzle(item,WI.Recording.Swizzle.Number)));this._swizzle[index][type]=new ImageData(new Uint8ClampedArray(object),width,height);this._swizzle[index][type].__data={data:object,width,height};break;} case WI.Recording.Swizzle.Path2D:this._swizzle[index][type]=new Path2D(data);this._swizzle[index][type].__data=data;break;case WI.Recording.Swizzle.CanvasGradient:{let[gradientType,points]=await Promise.all([this.swizzle(data[0],WI.Recording.Swizzle.String),this.swizzle(data[1],WI.Recording.Swizzle.Array),]);points=await Promise.all(points.map((item)=>this.swizzle(item,WI.Recording.Swizzle.Number)));WI.ImageUtilities.scratchCanvasContext2D((context)=>{if(gradientType=="radial-gradient") this._swizzle[index][type]=context.createRadialGradient(...points);else if(gradientType=="linear-gradient") this._swizzle[index][type]=context.createLinearGradient(...points);else this._swizzle[index][type]=context.createConicGradient(...points);});let stops=[];for(let stop of data[2]){let[offset,color]=await Promise.all([this.swizzle(stop[0],WI.Recording.Swizzle.Number),this.swizzle(stop[1],WI.Recording.Swizzle.String),]);this._swizzle[index][type].addColorStop(offset,color);stops.push({offset,color});} this._swizzle[index][type].__data={type:gradientType,points,stops};break;} case WI.Recording.Swizzle.CanvasPattern:{let[image,repeat]=await Promise.all([this.swizzle(data[0],WI.Recording.Swizzle.Image),this.swizzle(data[1],WI.Recording.Swizzle.String),]);WI.ImageUtilities.scratchCanvasContext2D((context)=>{this._swizzle[index][type]=context.createPattern(image,repeat);this._swizzle[index][type].__image=image;});this._swizzle[index][type].__data={image:image.__data,repeat};break;} case WI.Recording.Swizzle.ImageBitmap:{let image=await this.swizzle(index,WI.Recording.Swizzle.Image);this._swizzle[index][type]=await createImageBitmap(image);this._swizzle[index][type].__data=data;break;} case WI.Recording.Swizzle.CallStack:{let array=await this.swizzle(data,WI.Recording.Swizzle.Array);if(!isNaN(array[0])){ array=[array];} let promises=[]; promises.push(Promise.all(array[0].map((item)=>this.swizzle(item,WI.Recording.Swizzle.CallFrame)))); if(array.length>1) promises.push(this.swizzle(array[1],WI.Recording.Swizzle.Boolean)); if(array.length>2) promises.push(this.swizzle(array[2],WI.Recording.Swizzle.Boolean)); if(array.length>3) promises.push(this.swizzle(array[3],WI.Recording.Swizzle.StackTrace));let[callFrames,topCallFrameIsBoundary,truncated,parentStackTrace]=await Promise.all(promises);this._swizzle[index][type]=WI.StackTrace.fromPayload(WI.assumingMainTarget(),{callFrames,topCallFrameIsBoundary,truncated,parentStackTrace});break;} case WI.Recording.Swizzle.CallFrame:{let array=await this.swizzle(data,WI.Recording.Swizzle.Array);let[functionName,url]=await Promise.all([this.swizzle(array[0],WI.Recording.Swizzle.String),this.swizzle(array[1],WI.Recording.Swizzle.String),]);this._swizzle[index][type]=WI.CallFrame.fromPayload(WI.assumingMainTarget(),{functionName,url,lineNumber:array[2],columnNumber:array[3],});break;}}}catch{}} return this._swizzle[index][type];} createContext() {let createCanvasContext=(type)=>{let canvas=document.createElement("canvas");if("width"in this._initialState.attributes) canvas.width=this._initialState.attributes.width;if("height"in this._initialState.attributes) canvas.height=this._initialState.attributes.height;return canvas.getContext(type,...this._initialState.parameters);};let createOffscreenCanvasContext=(type)=>{let width=1;let height=1;if("width"in this._initialState.attributes) width=this._initialState.attributes.width;if("height"in this._initialState.attributes) height=this._initialState.attributes.height;let canvas=new OffscreenCanvas(width,height);return canvas.getContext(type,...this._initialState.parameters);};switch(this._type){case WI.Recording.Type.Canvas2D:return createCanvasContext("2d");case WI.Recording.Type.OffscreenCanvas2D:return createOffscreenCanvasContext("2d");case WI.Recording.Type.CanvasBitmapRenderer:return createCanvasContext("bitmaprenderer");case WI.Recording.Type.OffscreenCanvasBitmapRenderer:return createOffscreenCanvasContext("bitmaprenderer");case WI.Recording.Type.CanvasWebGL:return createCanvasContext("webgl");case WI.Recording.Type.OffscreenCanvasWebGL:return createOffscreenCanvasContext("webgl");case WI.Recording.Type.CanvasWebGL2:return createCanvasContext("webgl2");case WI.Recording.Type.OffscreenCanvasWebGL2:return createOffscreenCanvasContext("webgl2");} console.error("Unknown recording type",this._type);return null;} toJSON() {let initialState={};if(!isEmptyObject(this._initialState.attributes)) initialState.attributes=this._initialState.attributes;if(this._initialState.states.length) initialState.states=this._initialState.states;if(this._initialState.parameters.length) initialState.parameters=this._initialState.parameters;if(this._initialState.content&&this._initialState.content.length) initialState.content=this._initialState.content;return{version:this._version,type:this._type,initialState,frames:this._frames.map((frame)=>frame.toJSON()),data:this._data,};} toHTML() {let lines=[];let objects=[];function processObject(object){objects.push({object,index:objects.length});return`objects[${objects.length - 1}]`;} function processValue(value){if(typeof value==="object"&&!Array.isArray(value)) return processObject(value);return JSON.stringify(value);} function escapeHTML(s){return s.replace(/[^0-9A-Za-z ]/g,(c)=>{return`&#${c.charCodeAt(0)};`;});} lines.push(``);lines.push(``);lines.push(`${escapeHTML(this._displayName)}`);lines.push(``);lines.push(``);lines.push(``);lines.push(``);lines.push(``);return lines.join(`\n`);} async _process() {if(!this._processContext){this._processContext=this.createContext();if(this.isCanvas2D){let initialContent=await WI.ImageUtilities.promisifyLoad(this._initialState.content);this._processContext.drawImage(initialContent,0,0);for(let initialState of this._initialState.states){let state=await WI.RecordingState.swizzleInitialState(this,initialState);state.apply(this._type,this._processContext);if(initialState!==this._initialState.states.lastValue){this._processContext.save();this._processStates.push(WI.RecordingState.fromCanvasContext2D(this._processContext));}}}} if(!this._actions[0].ready){this._actions[0].process(this,this._processContext,this._processStates);this.dispatchEventToListeners(WI.Recording.Event.ProcessedAction,{action:this._actions[0],index:0});} const workInterval=10;let startTime=Date.now();let cumulativeActionIndex=0;let lastAction=this._actions[cumulativeActionIndex];for(let frameIndex=0;frameIndexworkInterval){await Promise.delay(); startTime=Date.now();} lastAction=action;if(!this._processing) return;} if(!this._processing) return;} this._swizzle=null;this._processContext=null;this._processing=false;}};WI.Recording.Version=2;WI.Recording.Event={ProcessedAction:"recording-processed-action",StartProcessingFrame:"recording-start-processing-frame",};WI.Recording._importedRecordingNameSet=new Set;WI.Recording.CanvasRecordingNamesSymbol=Symbol("canvas-recording-names");WI.Recording.Type={Canvas2D:"canvas-2d",OffscreenCanvas2D:"offscreen-canvas-2d",CanvasBitmapRenderer:"canvas-bitmaprenderer",OffscreenCanvasBitmapRenderer:"offscreen-canvas-bitmaprenderer",CanvasWebGL:"canvas-webgl",OffscreenCanvasWebGL:"offscreen-canvas-webgl",CanvasWebGL2:"canvas-webgl2",OffscreenCanvasWebGL2:"offscreen-canvas-webgl2",};WI.Recording.Swizzle={None:0,Number:1,Boolean:2,String:3,Array:4,TypedArray:5,Image:6,ImageData:7,DOMMatrix:8,Path2D:9,CanvasGradient:10,CanvasPattern:11,WebGLBuffer:12,WebGLFramebuffer:13,WebGLRenderbuffer:14,WebGLTexture:15,WebGLShader:16,WebGLProgram:17,WebGLUniformLocation:18,ImageBitmap:19,WebGLQuery:20,WebGLSampler:21,WebGLSync:22,WebGLTransformFeedback:23,WebGLVertexArrayObject:24,CallStack:Symbol("CallStack"),CallFrame:Symbol("CallFrame"),};WI.RecordingAction=class RecordingAction extends WI.Object {constructor(name,parameters,swizzleTypes,stackTrace,snapshot) {super();this._payloadName=name;this._payloadParameters=parameters;this._payloadSwizzleTypes=swizzleTypes;this._payloadStackTrace=stackTrace;this._payloadSnapshot=snapshot??-1;this._name="";this._parameters=[];this._stackTrace=null;this._snapshot="";this._valid=true;this._isFunction=false;this._isGetter=false;this._isVisual=false;this._contextReplacer=null;this._states=[];this._stateModifiers=new Set;this._warning=null;this._swizzled=false;this._processed=false;} static fromPayload(payload) {if(!Array.isArray(payload)) payload=[];if(typeof payload[0]!=="number"){if(payload.length>0) WI.Recording.synthesizeWarning(WI.UIString("non-number %s").format(WI.unlocalizedString("name")));payload[0]=-1;} if(!Array.isArray(payload[1])){if(payload.length>1) WI.Recording.synthesizeWarning(WI.UIString("non-array %s").format(WI.unlocalizedString("parameters")));payload[1]=[];} if(!Array.isArray(payload[2])){if(payload.length>2) WI.Recording.synthesizeWarning(WI.UIString("non-array %s").format(WI.unlocalizedString("swizzleTypes")));payload[2]=[];} if(typeof payload[3]!=="number"||isNaN(payload[3])||(!payload[3]&&payload[3]!==0)){ if(!Array.isArray(payload[3])){if(payload.length>3) WI.Recording.synthesizeWarning(WI.UIString("non-number %s").format(WI.unlocalizedString("stackTrace")));payload[3]=[];}} if(typeof payload[4]!=="number"||isNaN(payload[4])){if(payload.length>4) WI.Recording.synthesizeWarning(WI.UIString("non-number %s").format(WI.unlocalizedString("snapshot")));payload[4]=-1;} return new WI.RecordingAction(...payload);} static isFunctionForType(type,name) {let prototype=WI.RecordingAction._prototypeForType(type);if(!prototype) return false;let propertyDescriptor=Object.getOwnPropertyDescriptor(prototype,name);if(!propertyDescriptor) return false;return typeof propertyDescriptor.value==="function";} static bitfieldNamesForParameter(type,name,value,index,count) {if(!value) return null;let prototype=WI.RecordingAction._prototypeForType(type);if(!prototype) return null;function testAndClearBit(name){let bit=prototype[name];if(!bit) return;if(value&bit) names.push(name);value=value&~bit;} function hexString(value){return"0x"+value.toString(16);} let names=[];if((name==="clear"&&index===0&&(type===WI.Recording.Type.CanvasWebGL||type===WI.Recording.Type.CanvasWebGL2))||(name==="blitFramebuffer"&&index===8&&type===WI.Recording.Type.CanvasWebGL2)){testAndClearBit("COLOR_BUFFER_BIT");testAndClearBit("DEPTH_BUFFER_BIT");testAndClearBit("STENCIL_BUFFER_BIT");if(value) names.push(hexString(value));} if(name==="clientWaitSync"&&index===1&&type===WI.Recording.Type.CanvasWebGL2){testAndClearBit("SYNC_FLUSH_COMMANDS_BIT");if(value) names.push(hexString(value));} if(!names.length) return null;return names;} static constantNameForParameter(type,name,value,index,count) {let indexesForType=WI.RecordingAction._constantIndexes[type];if(!indexesForType) return null;let indexesForAction=indexesForType[name];if(!indexesForAction) return null;if(Array.isArray(indexesForAction)){if(!indexesForAction.includes(index)) return null;}else if(typeof indexesForAction==="object"){let indexesForActionVariant=indexesForAction[count];if(!indexesForActionVariant) return null;if(Array.isArray(indexesForActionVariant)&&!indexesForActionVariant.includes(index)) return null;} if(value===0&&(type===WI.Recording.Type.CanvasWebGL||type===WI.Recording.Type.CanvasWebGL2)){if(name==="blendFunc"||name==="blendFuncSeparate") return"ZERO";if(index===0){if(name==="drawArrays"||name==="drawElements") return"POINTS";if(name==="pixelStorei") return"NONE";}} let prototype=WI.RecordingAction._prototypeForType(type);if(prototype){for(let key in prototype){let descriptor=Object.getOwnPropertyDescriptor(prototype,key);if(descriptor&&descriptor.value===value) return key;}} return null;} static _prototypeForType(type) {switch(type){case WI.Recording.Type.Canvas2D:return CanvasRenderingContext2D.prototype;case WI.Recording.Type.OffscreenCanvas2D:if(window.OffscreenCanvasRenderingContext2D) return OffscreenCanvasRenderingContext2D.prototype;break;case WI.Recording.Type.CanvasBitmapRenderer:case WI.Recording.Type.OffscreenCanvasBitmapRenderer:if(window.ImageBitmapRenderingContext) return ImageBitmapRenderingContext.prototype;break;case WI.Recording.Type.CanvasWebGL:case WI.Recording.Type.OffscreenCanvasWebGL:if(window.WebGLRenderingContext) return WebGLRenderingContext.prototype;break;case WI.Recording.Type.CanvasWebGL2:case WI.Recording.Type.OffscreenCanvasWebGL2:if(window.WebGL2RenderingContext) return WebGL2RenderingContext.prototype;break;} WI.reportInternalError("Unknown recording type: "+type);return null;} get name(){return this._name;} get parameters(){return this._parameters;} get swizzleTypes(){return this._payloadSwizzleTypes;} get stackTrace(){return this._stackTrace;} get snapshot(){return this._snapshot;} get valid(){return this._valid;} get isFunction(){return this._isFunction;} get isGetter(){return this._isGetter;} get isVisual(){return this._isVisual;} get contextReplacer(){return this._contextReplacer;} get states(){return this._states;} get stateModifiers(){return this._stateModifiers;} get warning(){return this._warning;} get ready() {return this._swizzled&&this._processed;} process(recording,context,states,{lastAction}={}) {this._processed=true;if(recording.type===WI.Recording.Type.CanvasWebGL||recording.type===WI.Recording.Type.CanvasWebGL2){if(this._valid&&this._isVisual){let contentBefore=recording.visualActionIndexes.length?recording.actions[recording.visualActionIndexes.lastValue].snapshot:recording.initialState.content;if(this._snapshot===contentBefore) this._warning=WI.UIString("This action causes no visual change");} return;} function getContent(){if(context instanceof CanvasRenderingContext2D||(window.OffscreenCanvasRenderingContext2D&&context instanceof OffscreenCanvasRenderingContext2D)) return context.getImageData(0,0,context.canvas.width,context.canvas.height).data;if((window.WebGLRenderingContext&&context instanceof WebGLRenderingContext)||(window.WebGL2RenderingContext&&context instanceof WebGL2RenderingContext)){let pixels=new Uint8Array(context.drawingBufferWidth*context.drawingBufferHeight*4);context.readPixels(0,0,context.canvas.width,context.canvas.height,context.RGBA,context.UNSIGNED_BYTE,pixels);return pixels;} if(context.canvas instanceof HTMLCanvasElement) return[context.canvas.toDataURL()];return[];} let contentBefore=null;let shouldCheckHasVisualEffect=this._valid&&this._isVisual;if(shouldCheckHasVisualEffect) contentBefore=getContent();this.apply(context);if(shouldCheckHasVisualEffect){let contentAfter=getContent();if(Array.shallowEqual(contentBefore,contentAfter)) this._warning=WI.UIString("This action causes no visual change");} if(recording.isCanvas2D){let currentState=WI.RecordingState.fromCanvasContext2D(context,{source:this});if(this.name==="save") states.push(currentState);else if(this.name==="restore") states.pop();this._states=states.slice();this._states.push(currentState);let lastState=null;if(lastAction){lastState=lastAction.states.lastValue;for(let[name,value]of currentState){let previousValue=lastState.get(name);if(value!==previousValue&&!Object.shallowEqual(value,previousValue)) this._stateModifiers.add(name);}} let currentX=currentState.get("currentX");let invalidX=(currentX<0||currentX>=context.canvas.width)&&(!lastState||currentX!==lastState.get("currentX"));let currentY=currentState.get("currentY");let invalidY=(currentY<0||currentY>=context.canvas.height)&&(!lastState||currentY!==lastState.get("currentY"));if(invalidX||invalidY) this._warning=WI.UIString("This action moves the path outside the visible area");}} async swizzle(recording,lastAction) {if(!this._valid){this._swizzled=true;return;} let swizzleParameter=(item,index)=>{return recording.swizzle(item,this._payloadSwizzleTypes[index]);};let swizzlePromises=[recording.swizzle(this._payloadName,WI.Recording.Swizzle.String),Promise.all(this._payloadParameters.map(swizzleParameter)),];if(!isNaN(this._payloadStackTrace)) swizzlePromises.push(recording.swizzle(this._payloadStackTrace,WI.Recording.Swizzle.CallStack));else{ let stackTracePromise=Promise.all(this._payloadStackTrace.map((item)=>recording.swizzle(item,WI.Recording.Swizzle.CallFrame))).then((callFrames)=>WI.StackTrace.fromPayload(WI.assumingMainTarget(),callFrames));swizzlePromises.push(stackTracePromise);} if(this._payloadSnapshot>=0) swizzlePromises.push(recording.swizzle(this._payloadSnapshot,WI.Recording.Swizzle.String));let[name,parameters,stackTrace,snapshot]=await Promise.all(swizzlePromises);this._name=name;this._parameters=parameters;this._stackTrace=stackTrace;if(this._payloadSnapshot>=0) this._snapshot=snapshot;if(recording.isCanvas){if(this._name==="width"||this._name==="height"){this._contextReplacer="canvas";this._isFunction=false;this._isGetter=!this._parameters.length;this._isVisual=!this._isGetter;}} if(!this._contextReplacer){this._isFunction=WI.RecordingAction.isFunctionForType(recording.type,this._name);this._isGetter=!this._isFunction&&!this._parameters.length;if(this._snapshot) this._isVisual=true;else{let visualNames=WI.RecordingAction._visualNames[recording.type];this._isVisual=visualNames?visualNames.has(this._name):false;} if(this._valid){let prototype=WI.RecordingAction._prototypeForType(recording.type);if(prototype&&!(name in prototype)){this.markInvalid();WI.Recording.synthesizeWarning(WI.UIString("\u0022%s\u0022 is not valid for %s").format(name,prototype.constructor.name));}}} if(this._valid){let parametersSpecified=this._parameters.every((parameter)=>parameter!==undefined);let parametersCanBeSwizzled=this._payloadSwizzleTypes.every((swizzleType)=>swizzleType!==WI.Recording.Swizzle.None);if(!parametersSpecified||!parametersCanBeSwizzled) this.markInvalid();} if(this._valid){let stateModifiers=WI.RecordingAction._stateModifiers[recording.type];if(stateModifiers){this._stateModifiers.add(this._name);let modifiedByAction=stateModifiers[this._name]||[];for(let item of modifiedByAction) this._stateModifiers.add(item);}} this._swizzled=true;} apply(context,options={}) {if(!this.valid) return;try{let name=options.nameOverride||this._name;if(this._contextReplacer) context=context[this._contextReplacer];if(this.isFunction) context[name](...this._parameters);else{if(this.isGetter) context[name];else context[name]=this._parameters[0];}}catch{this.markInvalid();WI.Recording.synthesizeWarning(WI.UIString("\u0022%s\u0022 threw an error").format(this._name));}} markInvalid() {if(!this._valid) return;this._valid=false;this.dispatchEventToListeners(WI.RecordingAction.Event.ValidityChanged);} getColorParameters() {switch(this._name){ case"fillStyle":case"strokeStyle":case"shadowColor":case"setFillColor":case"setStrokeColor": case"blendColor":case"clearColor":case"colorMask":return this._parameters;case"setShadow":return this._parameters.slice(3);} return[];} getImageParameters() {switch(this._name){ case"createImageData":case"createPattern":case"drawImage":case"fillStyle":case"putImageData":case"strokeStyle":case"drawImageFromRect": case"transferFromImageBitmap":return this._parameters.slice(0,1); case"texImage2D":case"texSubImage2D":case"compressedTexImage2D":return[this._parameters.lastValue];} return[];} toJSON() {let json=[this._payloadName,this._payloadParameters,this._payloadSwizzleTypes,this._payloadStackTrace];if(this._payloadSnapshot>=0) json.push(this._payloadSnapshot);return json;}};WI.RecordingAction.Event={ValidityChanged:"recording-action-marked-invalid",};WI.RecordingAction._constantIndexes={[WI.Recording.Type.CanvasWebGL]:{"activeTexture":true,"bindBuffer":true,"bindFramebuffer":true,"bindRenderbuffer":true,"bindTexture":true,"blendEquation":true,"blendEquationSeparate":true,"blendFunc":true,"blendFuncSeparate":true,"bufferData":[0,2],"bufferSubData":[0],"checkFramebufferStatus":true,"compressedTexImage2D":[0,2],"compressedTexSubImage2D":[0],"copyTexImage2D":[0,2],"copyTexSubImage2D":[0],"createShader":true,"cullFace":true,"depthFunc":true,"disable":true,"drawArrays":[0],"drawElements":[0,2],"enable":true,"framebufferRenderbuffer":true,"framebufferTexture2D":[0,1,2],"frontFace":true,"generateMipmap":true,"getBufferParameter":true,"getFramebufferAttachmentParameter":true,"getParameter":true,"getProgramParameter":true,"getRenderbufferParameter":true,"getShaderParameter":true,"getShaderPrecisionFormat":true,"getTexParameter":true,"getVertexAttrib":[1],"getVertexAttribOffset":[1],"hint":true,"isEnabled":true,"pixelStorei":[0],"readPixels":[4,5],"renderbufferStorage":[0,1],"stencilFunc":[0],"stencilFuncSeparate":[0,1],"stencilMaskSeparate":[0],"stencilOp":true,"stencilOpSeparate":true,"texImage2D":{5:[0,2,3,4],6:[0,2,3,4],8:[0,2,6,7],9:[0,2,6,7],},"texParameterf":[0,1],"texParameteri":[0,1],"texSubImage2D":{6:[0,4,5],7:[0,4,5],8:[0,6,7],9:[0,6,7],},"vertexAttribPointer":[2],},[WI.Recording.Type.CanvasWebGL2]:{"activeTexture":true,"beginQuery":[0],"beginTransformFeedback":true,"bindBuffer":true,"bindBufferBase":[0],"bindBufferRange":[0],"bindFramebuffer":true,"bindRenderbuffer":true,"bindTexture":true,"bindTransformFeedback":[0],"blendEquation":true,"blendEquationSeparate":true,"blendFunc":true,"blendFuncSeparate":true,"blitFramebuffer":[10],"bufferData":[0,2],"bufferSubData":[0],"checkFramebufferStatus":true,"clearBufferfi":[0],"clearBufferfv":[0],"clearBufferiv":[0],"clearBufferuiv":[0],"compressedTexImage2D":[0,2],"compressedTexSubImage2D":[0],"compressedTexSubImage3D":[0],"copyBufferSubData":[0,1],"copyTexImage2D":[0,2],"copyTexSubImage2D":[0],"copyTexSubImage3D":[0],"createShader":true,"cullFace":true,"depthFunc":true,"disable":true,"drawArrays":[0],"drawArraysInstanced":[0],"drawBuffers":true,"drawElements":[0,2],"drawElementsInstanced":[0,2],"drawRangeElements":[0,4],"enable":true,"endQuery":true,"fenceSync":[0],"framebufferRenderbuffer":true,"framebufferTexture2D":[0,1,2],"framebufferTextureLayer":[0,1],"frontFace":true,"generateMipmap":true,"getActiveUniformBlockParameter":[2],"getActiveUniforms":[2],"getBufferParameter":true,"getBufferSubData":[0],"getFramebufferAttachmentParameter":true,"getIndexedParameter":[0],"getInternalformatParameter":true,"getParameter":true,"getProgramParameter":true,"getQuery":true,"getQueryParameter":[1],"getRenderbufferParameter":true,"getSamplerParameter":[1],"getShaderParameter":true,"getShaderPrecisionFormat":true,"getSyncParameter":[1],"getTexParameter":true,"getVertexAttrib":[1],"getVertexAttribOffset":[1],"hint":true,"invalidateFramebuffer":[0,1],"invalidateSubFramebuffer":[0,1],"isEnabled":true,"pixelStorei":[0],"readBuffer":true,"readPixels":[4,5],"renderbufferStorage":[0,1],"renderbufferStorageMultisample":[0,2],"samplerParameterf":[1],"samplerParameteri":[1],"stencilFunc":[0],"stencilFuncSeparate":[0,1],"stencilMaskSeparate":[0],"stencilOp":true,"stencilOpSeparate":true,"texImage2D":{5:[0,2,3,4],6:[0,2,3,4],8:[0,2,6,7],9:[0,2,6,7],10:[0,2,6,7],11:[0,2,7,8],},"texParameterf":[0,1],"texParameteri":[0,1],"texStorage2D":[0,2],"texSubImage2D":{6:[0,4,5],7:[0,4,5],8:[0,6,7],9:[0,6,7],10:[0,6,7],11:[0,8,9],12:[0,8,9],},"transformFeedbackVaryings":[2],"vertexAttribIPointer":[2],"vertexAttribPointer":[2],},};WI.RecordingAction._constantIndexes[WI.Recording.Type.OffscreenCanvasWebGL]=WI.RecordingAction._constantIndexes[WI.Recording.Type.CanvasWebGL];WI.RecordingAction._constantIndexes[WI.Recording.Type.OffscreenCanvasWebGL2]=WI.RecordingAction._constantIndexes[WI.Recording.Type.CanvasWebGL2];WI.RecordingAction._visualNames={[WI.Recording.Type.Canvas2D]:new Set(["clearRect","drawFocusIfNeeded","drawImage","drawImageFromRect","fill","fillRect","fillText","putImageData","stroke","strokeRect","strokeText",]),[WI.Recording.Type.OffscreenCanvas2D]:new Set(["clearRect","drawImage","fill","fillRect","fillText","putImageData","strokeRect","strokeText",]),[WI.Recording.Type.CanvasBitmapRenderer]:new Set(["transferFromImageBitmap",]),[WI.Recording.Type.CanvasWebGL]:new Set(["clear","drawArrays","drawElements",]),[WI.Recording.Type.CanvasWebGL2]:new Set(["clear","drawArrays","drawArraysInstanced","drawElements","drawElementsInstanced",]),};WI.RecordingAction._visualNames[WI.Recording.Type.OffscreenCanvasBitmapRenderer]=WI.RecordingAction._visualNames[WI.Recording.Type.CanvasBitmapRenderer];WI.RecordingAction._visualNames[WI.Recording.Type.OffscreenCanvasWebGL]=WI.RecordingAction._visualNames[WI.Recording.Type.CanvasWebGL];WI.RecordingAction._visualNames[WI.Recording.Type.OffscreenCanvasWebGL2]=WI.RecordingAction._visualNames[WI.Recording.Type.CanvasWebGL2];WI.RecordingAction._stateModifiers={[WI.Recording.Type.Canvas2D]:{arc:["currentX","currentY"],arcTo:["currentX","currentY"],beginPath:["currentX","currentY"],bezierCurveTo:["currentX","currentY"],clearShadow:["shadowOffsetX","shadowOffsetY","shadowBlur","shadowColor"],closePath:["currentX","currentY"],ellipse:["currentX","currentY"],lineTo:["currentX","currentY"],moveTo:["currentX","currentY"],quadraticCurveTo:["currentX","currentY"],rect:["currentX","currentY"],resetTransform:["transform"],rotate:["transform"],scale:["transform"],setAlpha:["globalAlpha"],setCompositeOperation:["globalCompositeOperation"],setFillColor:["fillStyle"],setLineCap:["lineCap"],setLineJoin:["lineJoin"],setLineWidth:["lineWidth"],setMiterLimit:["miterLimit"],setShadow:["shadowOffsetX","shadowOffsetY","shadowBlur","shadowColor"],setStrokeColor:["strokeStyle"],setTransform:["transform"],translate:["transform"],},[WI.Recording.Type.OffscreenCanvas2D]:{arc:["currentX","currentY"],arcTo:["currentX","currentY"],beginPath:["currentX","currentY"],bezierCurveTo:["currentX","currentY"],closePath:["currentX","currentY"],ellipse:["currentX","currentY"],lineTo:["currentX","currentY"],moveTo:["currentX","currentY"],quadraticCurveTo:["currentX","currentY"],rect:["currentX","currentY"],resetTransform:["transform"],rotate:["transform"],scale:["transform"],setTransform:["transform"],translate:["transform"],},};WI.RecordingFrame=class RecordingFrame {constructor(actions,{duration,incomplete}={}) {this._actions=actions;this._duration=duration||NaN;this._incomplete=incomplete||false;} static fromPayload(payload) {if(typeof payload!=="object"||payload===null) payload={};if(!Array.isArray(payload.actions)){if("actions"in payload) WI.Recording.synthesizeWarning(WI.UIString("non-array %s").format(WI.unlocalizedString("actions")));payload.actions=[];} let actions=payload.actions.map(WI.RecordingAction.fromPayload);return new WI.RecordingFrame(actions,{duration:payload.duration||NaN,incomplete:!!payload.incomplete,});} get actions(){return this._actions;} get duration(){return this._duration;} get incomplete(){return this._incomplete;} toJSON() {let json={actions:this._actions.map((action)=>action.toJSON()),};if(!isNaN(this._duration)) json.duration=this._duration;if(this._incomplete) json.incomplete=this._incomplete;return json;}};WI.RecordingInitialStateAction=class RecordingInitialStateAction extends WI.RecordingAction {constructor() {super();this._name=WI.UIString("Initial State");this._valid=false;this._swizzled=true;}};WI.RecordingState=class RecordingState {constructor(data,{source}={}) {this._data=data;this._source=source||null;} static fromCanvasContext2D(context,options={}) {let matrix=context.getTransform();let data={};data.direction=context.direction;data.fillStyle=context.fillStyle;data.font=context.font;data.globalAlpha=context.globalAlpha;data.globalCompositeOperation=context.globalCompositeOperation;data.imageSmoothingEnabled=context.imageSmoothingEnabled;data.imageSmoothingQuality=context.imageSmoothingQuality;data.lineCap=context.lineCap;data.lineDash=context.getLineDash();data.lineDashOffset=context.lineDashOffset;data.lineJoin=context.lineJoin;data.lineWidth=context.lineWidth;data.miterLimit=context.miterLimit;data.shadowBlur=context.shadowBlur;data.shadowColor=context.shadowColor;data.shadowOffsetX=context.shadowOffsetX;data.shadowOffsetY=context.shadowOffsetY;data.strokeStyle=context.strokeStyle;data.textAlign=context.textAlign;data.textBaseline=context.textBaseline;data.transform=[matrix.a,matrix.b,matrix.c,matrix.d,matrix.e,matrix.f];data.webkitImageSmoothingEnabled=context.webkitImageSmoothingEnabled;data.webkitLineDash=context.webkitLineDash;data.webkitLineDashOffset=context.webkitLineDashOffset;data.currentX=context.currentX;data.currentY=context.currentY;data.setPath=[context.getPath()];return new WI.RecordingState(data,options);} static async swizzleInitialState(recording,initialState) {if(recording.isCanvas2D){let swizzledState={};for(let[name,value]of Object.entries(initialState)){ let nameIndex=parseInt(name);if(!isNaN(nameIndex)) name=await recording.swizzle(nameIndex,WI.Recording.Swizzle.String);switch(name){case"setTransform":value=[await recording.swizzle(value,WI.Recording.Swizzle.DOMMatrix)];break;case"fillStyle":case"strokeStyle":var[gradient,pattern,string]=await Promise.all([recording.swizzle(value,WI.Recording.Swizzle.CanvasGradient),recording.swizzle(value,WI.Recording.Swizzle.CanvasPattern),recording.swizzle(value,WI.Recording.Swizzle.String),]);if(gradient&&!pattern) value=gradient;else if(pattern&&!gradient) value=pattern;else value=string;break;case"direction":case"font":case"globalCompositeOperation":case"imageSmoothingQuality":case"lineCap":case"lineJoin":case"shadowColor":case"textAlign":case"textBaseline":value=await recording.swizzle(value,WI.Recording.Swizzle.String);break;case"globalAlpha":case"lineWidth":case"miterLimit":case"shadowOffsetX":case"shadowOffsetY":case"shadowBlur":case"lineDashOffset":value=await recording.swizzle(value,WI.Recording.Swizzle.Number);break;case"setPath":value=[await recording.swizzle(value[0],WI.Recording.Swizzle.Path2D)];break;} if(value===undefined||(Array.isArray(value)&&value.includes(undefined))) continue;swizzledState[name]=value;} return new WI.RecordingState(swizzledState);} return null;} get source(){return this._source;} has(name) {return name in this._data;} get(name) {return this._data[name];} apply(type,context) {for(let[name,value]of this){if(!(name in context)) continue;if(name==="currentX"||name==="currentY") continue;try{if(WI.RecordingAction.isFunctionForType(type,name)) context[name](...value);else context[name]=value;}catch{}}} toJSON() {return this._data;} [Symbol.iterator]() {return Object.entries(this._data)[Symbol.iterator]();}};WI.Redirect=class Redirect {constructor(url,requestMethod,requestHeaders,responseStatusCode,responseStatusText,responseHeaders,timestamp) {this._url=url;this._urlComponents=null;this._requestMethod=requestMethod;this._requestHeaders=requestHeaders;this._responseStatusCode=responseStatusCode;this._responseStatusText=responseStatusText;this._responseHeaders=responseHeaders;this._timestamp=timestamp;} get url(){return this._url;} get requestMethod(){return this._requestMethod;} get requestHeaders(){return this._requestHeaders;} get responseStatusCode(){return this._responseStatusCode;} get responseStatusText(){return this._responseStatusText;} get responseHeaders(){return this._responseHeaders;} get timestamp(){return this._timestamp;} get urlComponents() {if(!this._urlComponents) this._urlComponents=parseURL(this._url);return this._urlComponents;}};WI.RenderingFrameTimelineRecord=class RenderingFrameTimelineRecord extends WI.TimelineRecord {constructor(startTime,endTime,name) {super(WI.TimelineRecord.Type.RenderingFrame,startTime,endTime);this._name=name||"";this._durationByTaskType=new Map;this._frameIndex=-1;} static resetFrameIndex() {WI.RenderingFrameTimelineRecord._nextFrameIndex=0;} static displayNameForTaskType(taskType) {switch(taskType){case WI.RenderingFrameTimelineRecord.TaskType.Script:return WI.UIString("Script");case WI.RenderingFrameTimelineRecord.TaskType.Layout:return WI.repeatedUIString.timelineRecordLayout();case WI.RenderingFrameTimelineRecord.TaskType.Paint:return WI.repeatedUIString.timelineRecordPaint();case WI.RenderingFrameTimelineRecord.TaskType.Other:return WI.UIString("Other");}} static taskTypeForTimelineRecord(record) {switch(record.type){case WI.TimelineRecord.Type.Script:return WI.RenderingFrameTimelineRecord.TaskType.Script;case WI.TimelineRecord.Type.Layout:if(record.eventType===WI.LayoutTimelineRecord.EventType.Paint||record.eventType===WI.LayoutTimelineRecord.EventType.Composite) return WI.RenderingFrameTimelineRecord.TaskType.Paint;return WI.RenderingFrameTimelineRecord.TaskType.Layout;default:console.error("Unsupported timeline record type: "+record.type);return null;}} static async fromJSON(json) {let{startTime,endTime}=json;let record=new WI.RenderingFrameTimelineRecord(startTime,endTime);record.setupFrameIndex();return record;} toJSON() {return{type:this.type,startTime:this.startTime,endTime:this.endTime,};} get frameIndex() {return this._frameIndex;} get frameNumber() {return this._frameIndex+1;} get name() {return this._name;} setupFrameIndex() {if(this._frameIndex>=0) return;this._frameIndex=WI.RenderingFrameTimelineRecord._nextFrameIndex++;} durationForTask(taskType) {if(this._durationByTaskType.has(taskType)) return this._durationByTaskType.get(taskType);var duration;if(taskType===WI.RenderingFrameTimelineRecord.TaskType.Other) duration=this._calculateDurationRemainder();else{duration=this.children.reduce(function(previousValue,currentValue){if(taskType!==WI.RenderingFrameTimelineRecord.taskTypeForTimelineRecord(currentValue)) return previousValue;var currentDuration=currentValue.duration;if(currentValue.usesActiveStartTime) currentDuration-=currentValue.inactiveDuration;return previousValue+currentDuration;},0);if(taskType===WI.RenderingFrameTimelineRecord.TaskType.Script){ duration-=this.children.reduce(function(previousValue,currentValue){if(currentValue.type===WI.TimelineRecord.Type.Layout&&(currentValue.sourceCodeLocation||currentValue.stackTrace)) return previousValue+currentValue.duration;return previousValue;},0);}} this._durationByTaskType.set(taskType,duration);return duration;} _calculateDurationRemainder() {return Object.keys(WI.RenderingFrameTimelineRecord.TaskType).reduce((previousValue,key)=>{let taskType=WI.RenderingFrameTimelineRecord.TaskType[key];if(taskType===WI.RenderingFrameTimelineRecord.TaskType.Other) return previousValue;return previousValue-this.durationForTask(taskType);},this.duration);}};WI.RenderingFrameTimelineRecord.TaskType={Script:"rendering-frame-timeline-record-script",Layout:"rendering-frame-timeline-record-layout",Paint:"rendering-frame-timeline-record-paint",Other:"rendering-frame-timeline-record-other"};WI.RenderingFrameTimelineRecord.TypeIdentifier="rendering-frame-timeline-record";WI.RenderingFrameTimelineRecord._nextFrameIndex=0;WI.ResourceCollection=class ResourceCollection extends WI.Collection {constructor(resourceType) {super();this._resourceType=resourceType||null;this._resourceURLMap=new Multimap;this._resourcesTypeMap=new Map;} get resourceType(){return this._resourceType;} get displayName() {const plural=true;return this._resourceType?WI.Resource.displayNameForType(this._resourceType,plural):WI.UIString("Resources");} objectIsRequiredType(object) {if(this._resourceType===WI.Resource.Type.StyleSheet&&object instanceof WI.CSSStyleSheet) return true;if(!(object instanceof WI.Resource)) return false;if(!this._resourceType) return true;return object.type===this._resourceType;} resourcesForURL(url) {return this._resourceURLMap.get(url)||new Set;} resourceCollectionForType(type) {if(this._resourceType){return this;} let resourcesCollectionForType=this._resourcesTypeMap.get(type);if(!resourcesCollectionForType){resourcesCollectionForType=new WI.ResourceCollection(type);this._resourcesTypeMap.set(type,resourcesCollectionForType);} return resourcesCollectionForType;} clear() {super.clear();this._resourceURLMap.clear();if(!this._resourceType) this._resourcesTypeMap.clear();} itemAdded(item) {this._associateWithResource(item);} itemRemoved(item) {this._disassociateWithResource(item);} itemsCleared(items) {const skipRemoval=true;for(let item of items) this._disassociateWithResource(item,skipRemoval);} _associateWithResource(resource) {this._resourceURLMap.add(resource.url,resource);if(!this._resourceType){let resourcesCollectionForType=this.resourceCollectionForType(resource.type);resourcesCollectionForType.add(resource);} resource.addEventListener(WI.Resource.Event.URLDidChange,this._resourceURLDidChange,this);resource.addEventListener(WI.Resource.Event.TypeDidChange,this._resourceTypeDidChange,this);} _disassociateWithResource(resource,skipRemoval) {resource.removeEventListener(WI.Resource.Event.URLDidChange,this._resourceURLDidChange,this);resource.removeEventListener(WI.Resource.Event.TypeDidChange,this._resourceTypeDidChange,this);if(skipRemoval) return;if(!this._resourceType){let resourcesCollectionForType=this.resourceCollectionForType(resource.type);resourcesCollectionForType.remove(resource);} this._resourceURLMap.delete(resource.url,resource);} _resourceURLDidChange(event) {let resource=event.target;if(!(resource instanceof WI.Resource)) return;let oldURL=event.data.oldURL;if(!oldURL) return;this._resourceURLMap.add(resource.url,resource);this._resourceURLMap.delete(oldURL,resource);} _resourceTypeDidChange(event) {let resource=event.target;if(!(resource instanceof WI.Resource)) return;if(this._resourceType){this.remove(resource);return;} let resourcesWithNewType=this.resourceCollectionForType(resource.type);resourcesWithNewType.add(resource); }};WI.ResourceQueryResult=class ResourceQueryResult extends WI.QueryResult {constructor(resource,searchString,matches,cookie) {super(resource,matches);this._searchString=searchString;this._cookie=cookie||null;} get resource(){return this.value;} get searchString(){return this._searchString;} get cookie(){return this._cookie;} __test_createMatchesMask() {let filename=this.resource.displayName;let lastIndex=-1;let result="";for(let match of this._matches){let gap=" ".repeat(match.index-lastIndex-1);result+=gap;result+=filename[match.index];lastIndex=match.index;} return result;}};WI.ResourceTimelineRecord=class ResourceTimelineRecord extends WI.TimelineRecord {constructor(resource) {super(WI.TimelineRecord.Type.Network);this._resource=resource;this._resource.addEventListener(WI.Resource.Event.TimestampsDidChange,this._dispatchUpdatedEvent,this);} static async fromJSON(json) {let{entry,archiveStartTime}=json;let localResource=WI.LocalResource.fromHAREntry(entry,archiveStartTime);return new WI.ResourceTimelineRecord(localResource);} toJSON() {const content="";return{type:this.type,archiveStartTime:this._resource.requestSentWalltime-this.startTime,entry:WI.HARBuilder.entry(this._resource,content),};} get resource() {return this._resource;} get updatesDynamically() {return true;} get usesActiveStartTime() {return true;} get startTime() {return this._resource.timingData.startTime;} get activeStartTime() {return this._resource.timingData.responseStart;} get endTime() {return this._resource.timingData.responseEnd;} _dispatchUpdatedEvent() {this.dispatchEventToListeners(WI.TimelineRecord.Event.Updated);}};WI.ResourceTimingData=class ResourceTimingData {constructor(resource,data) {data=data||{};this._resource=resource;this._startTime=data.startTime||NaN;this._redirectStart=data.redirectStart||NaN;this._redirectEnd=data.redirectEnd||NaN;this._fetchStart=data.fetchStart||NaN;this._domainLookupStart=data.domainLookupStart||NaN;this._domainLookupEnd=data.domainLookupEnd||NaN;this._connectStart=data.connectStart||NaN;this._connectEnd=data.connectEnd||NaN;this._secureConnectionStart=data.secureConnectionStart||NaN;this._requestStart=data.requestStart||NaN;this._responseStart=data.responseStart||NaN;this._responseEnd=data.responseEnd||NaN;if(this._domainLookupStart>=this._domainLookupEnd) this._domainLookupStart=this._domainLookupEnd=NaN;if(this._connectStart>=this._connectEnd) this._connectStart=this._connectEnd=NaN;} static fromPayload(payload,resource) {payload=payload||{};let startTime=payload.startTime;let fetchStart=payload.fetchStart;let redirectStart=payload.redirectStart;let redirectEnd=payload.redirectEnd;if(isNaN(fetchStart)||fetchStartfetchStart||redirectStart>redirectEnd) redirectStart=NaN;if(redirectEndfetchStart||redirectEnd0?fetchStart+(offset/1000):NaN;} let data={startTime,redirectStart,redirectEnd,fetchStart,domainLookupStart:offsetToTimestamp(payload.domainLookupStart),domainLookupEnd:offsetToTimestamp(payload.domainLookupEnd),connectStart:offsetToTimestamp(payload.connectStart),connectEnd:offsetToTimestamp(payload.connectEnd),secureConnectionStart:offsetToTimestamp(payload.secureConnectionStart),requestStart:offsetToTimestamp(payload.requestStart),responseStart:offsetToTimestamp(payload.responseStart),responseEnd:offsetToTimestamp(payload.responseEnd)};return new WI.ResourceTimingData(resource,data);} get startTime(){return this._startTime||this._resource.requestSentTimestamp;} get redirectStart(){return this._redirectStart;} get redirectEnd(){return this._redirectEnd;} get fetchStart(){return this._fetchStart||this._resource.requestSentTimestamp;} get domainLookupStart(){return this._domainLookupStart;} get domainLookupEnd(){return this._domainLookupEnd;} get connectStart(){return this._connectStart;} get connectEnd(){return this._connectEnd;} get secureConnectionStart(){return this._secureConnectionStart;} get requestStart(){return this._requestStart||this._startTime||this._resource.requestSentTimestamp;} get responseStart(){return this._responseStart||this._startTime||this._resource.responseReceivedTimestamp||this._resource.finishedOrFailedTimestamp;} get responseEnd(){return this._responseEnd||this._resource.finishedOrFailedTimestamp;} markResponseEndTime(responseEnd) {this._responseEnd=responseEnd;}};WI.Revision=class Revision { apply() {console.error("Needs to be implemented by a subclass.");} revert() {console.error("Needs to be implemented by a subclass.");} copy() {return this;}};WI.ScopeChainNode=class ScopeChainNode {constructor(type,objects,name,location,empty) {if(type in WI.ScopeChainNode.Type) type=WI.ScopeChainNode.Type[type];this._type=type||null;this._objects=objects||[];this._name=name||"";this._location=location||null;this._empty=empty||false;} get type(){return this._type;} get objects(){return this._objects;} get name(){return this._name;} get location(){return this._location;} get empty(){return this._empty;} get hash() {if(this._hash) return this._hash;this._hash=this._name;if(this._location) this._hash+=`:${this._location.scriptId}:${this._location.lineNumber}:${this._location.columnNumber}`;return this._hash;} convertToLocalScope() {this._type=WI.ScopeChainNode.Type.Local;}};WI.ScopeChainNode.Type={Local:"scope-chain-type-local",Global:"scope-chain-type-global",GlobalLexicalEnvironment:"scope-chain-type-global-lexical-environment",With:"scope-chain-type-with",Closure:"scope-chain-type-closure",Catch:"scope-chain-type-catch",FunctionName:"scope-chain-type-function-name",Block:"scope-chain-type-block",};WI.ScreenshotsInstrument=class ScreenshotsInstrument extends WI.Instrument {constructor() {super();} static supported() {if(WI.sharedApp.debuggableType===WI.DebuggableType.Page) return false;return InspectorBackend.Enum.Timeline.Instrument.Screenshot;} get timelineRecordType() {return WI.TimelineRecord.Type.Screenshots;}};WI.ScreenshotsTimelineRecord=class ScreenshotsTimelineRecord extends WI.TimelineRecord {constructor(timestamp,imageData) {super(WI.TimelineRecord.Type.Screenshots,timestamp,timestamp);this._imageData=imageData;} static async fromJSON(json) {return new WI.ScreenshotsTimelineRecord(json.timestamp,json.imageData);} toJSON() {return{type:this.type,timestamp:this.startTime,imageData:this._imageData,};} get imageData(){return this._imageData;}};WI.ScriptInstrument=class ScriptInstrument extends WI.Instrument { get timelineRecordType() {return WI.TimelineRecord.Type.Script;} startInstrumentation(initiatedByBackend) {let target=WI.assumingMainTarget();const includeSamples=true;if(!initiatedByBackend) target.ScriptProfilerAgent.startTracking(includeSamples);} stopInstrumentation(initiatedByBackend) {let target=WI.assumingMainTarget();if(!initiatedByBackend) target.ScriptProfilerAgent.stopTracking();}};WI.ScriptSyntaxTree=class ScriptSyntaxTree {constructor(sourceText,script) {this._script=script;try{let sourceType=this._script.sourceType===WI.Script.SourceType.Module?"module":"script";let esprimaSyntaxTree=esprima.parse(sourceText,{loc:true,range:true,sourceType});this._syntaxTree=this._createInternalSyntaxTree(esprimaSyntaxTree);this._parsedSuccessfully=true;}catch(error){this._parsedSuccessfully=false;this._syntaxTree=null;console.error("Couldn't parse JavaScript File: "+script.url,error);}} get parsedSuccessfully() {return this._parsedSuccessfully;} forEachNode(callback) {if(!this._parsedSuccessfully) return;this._recurse(this._syntaxTree,callback,this._defaultParserState());} filter(predicate,startNode) {if(!this._parsedSuccessfully) return[];var nodes=[];function filter(node,state) {if(predicate(node)) nodes.push(node);else state.skipChildNodes=true;} this._recurse(startNode,filter,this._defaultParserState());return nodes;} containersOfPosition(position) {if(!this._parsedSuccessfully) return[];let allNodes=[];this.forEachNode((node,state)=>{if(node.endPosition.isBefore(position)) state.skipChildNodes=true;else if(node.startPosition.isAfter(position)) state.shouldStopEarly=true;else allNodes.push(node);});return allNodes;} filterByRange(startPosition,endPosition) {if(!this._parsedSuccessfully) return[];var allNodes=[];function filterForNodesInRange(node,state) { if(node.endPosition.isBefore(startPosition)){state.skipChildNodes=true;return;} if(node.startPosition.isWithin(startPosition,endPosition)){allNodes.push(node);return;} if(node.startPosition.isAfter(endPosition)) state.shouldStopEarly=true;} this.forEachNode(filterForNodesInRange);return allNodes;} containsNonEmptyReturnStatement(startNode) {if(!this._parsedSuccessfully) return false;if(startNode.attachments._hasNonEmptyReturnStatement!==undefined) return startNode.attachments._hasNonEmptyReturnStatement;function removeFunctionsFilter(node) {return node.type!==WI.ScriptSyntaxTree.NodeType.FunctionExpression&&node.type!==WI.ScriptSyntaxTree.NodeType.FunctionDeclaration&&node.type!==WI.ScriptSyntaxTree.NodeType.ArrowFunctionExpression;} var nodes=this.filter(removeFunctionsFilter,startNode);var hasNonEmptyReturnStatement=false;var returnStatementType=WI.ScriptSyntaxTree.NodeType.ReturnStatement;for(var node of nodes){if(node.type===returnStatementType&&node.argument){hasNonEmptyReturnStatement=true;break;}} startNode.attachments._hasNonEmptyReturnStatement=hasNonEmptyReturnStatement;return hasNonEmptyReturnStatement;} static functionReturnDivot(node) {return node.typeProfilingReturnDivot;} updateTypes(nodesToUpdate,callback) {if(!this._parsedSuccessfully) return;var allRequests=[];var allRequestNodes=[];var sourceID=this._script.id;for(var node of nodesToUpdate){switch(node.type){case WI.ScriptSyntaxTree.NodeType.FunctionDeclaration:case WI.ScriptSyntaxTree.NodeType.FunctionExpression:case WI.ScriptSyntaxTree.NodeType.ArrowFunctionExpression:for(var param of node.params){for(var identifier of this._gatherIdentifiersInDeclaration(param)){allRequests.push({typeInformationDescriptor:WI.ScriptSyntaxTree.TypeProfilerSearchDescriptor.NormalExpression,sourceID,divot:identifier.range[0]});allRequestNodes.push(identifier);}} allRequests.push({typeInformationDescriptor:WI.ScriptSyntaxTree.TypeProfilerSearchDescriptor.FunctionReturn,sourceID,divot:WI.ScriptSyntaxTree.functionReturnDivot(node)});allRequestNodes.push(node);break;case WI.ScriptSyntaxTree.NodeType.VariableDeclarator:for(var identifier of this._gatherIdentifiersInDeclaration(node.id)){allRequests.push({typeInformationDescriptor:WI.ScriptSyntaxTree.TypeProfilerSearchDescriptor.NormalExpression,sourceID,divot:identifier.range[0]});allRequestNodes.push(identifier);} break;}} function handleTypes(error,typeInformationArray) {if(error) return;for(var i=0;i{if(error){WI.reportInternalError(error);callback(null);return;} callback(source);});} updateShader(shaderType,source) {this._target.CanvasAgent.updateShader(this._identifier,shaderType,source);} showHighlight() {this._target.CanvasAgent.setShaderProgramHighlighted(this._identifier,true);} hideHighlight() {this._target.CanvasAgent.setShaderProgramHighlighted(this._identifier,false);}};WI.ShaderProgram.ProgramType={Compute:"compute",Render:"render",};WI.ShaderProgram.ShaderType={Compute:"compute",Fragment:"fragment",Vertex:"vertex",};WI.ShaderProgram.Event={DisabledChanged:"shader-program-disabled-changed",};WI.SourceCodePosition=class SourceCodePosition {constructor(lineNumber,columnNumber) {this._lineNumber=lineNumber||0;this._columnNumber=columnNumber||0;} get lineNumber(){return this._lineNumber;} get columnNumber(){return this._columnNumber;} offsetColumn(delta) {return new WI.SourceCodePosition(this._lineNumber,this._columnNumber+delta);} equals(position) {return this._lineNumber===position.lineNumber&&this._columnNumber===position.columnNumber;} isBefore(position) {if(this._lineNumberposition.lineNumber) return true;if(this._lineNumber===position.lineNumber&&this._columnNumber>position.columnNumber) return true;return false;} isWithin(startPosition,endPosition) {if(this.equals(startPosition)||this.equals(endPosition)) return true;if(this.isAfter(startPosition)&&this.isBefore(endPosition)) return true;return false;} toCodeMirror() {return{line:this._lineNumber,ch:this._columnNumber};}};WI.SourceCodeRevision=class SourceCodeRevision extends WI.Revision {constructor(sourceCode,content,base64Encoded,mimeType) {super();this._sourceCode=sourceCode;this._content=content||"";this._base64Encoded=!!base64Encoded;this._mimeType=mimeType;this._blobContent=null;} get sourceCode(){return this._sourceCode;} get content(){return this._content;} get base64Encoded(){return this._base64Encoded;} get mimeType(){return this._mimeType;} get blobContent() {if(!this._blobContent&&this._content) this._blobContent=WI.BlobUtilities.blobForContent(this._content,this._base64Encoded,this._mimeType);return this._blobContent;} updateRevisionContent(content,{base64Encoded,mimeType,blobContent}={}) {this._content=content||"";if(base64Encoded!==undefined){this._base64Encoded=!!base64Encoded;} if(mimeType!==undefined){this._mimeType=mimeType;} this._blobContent=blobContent!==undefined?blobContent:null;this._sourceCode.revisionContentDidChange(this);} apply() {this._sourceCode.currentRevision=this;} revert() {this._sourceCode.currentRevision=this._sourceCode.originalRevision;} copy() {return new WI.SourceCodeRevision(this._sourceCode,this._content,this._base64Encoded,this._mimeType);}};WI.SourceCodeSearchMatchObject=class SourceCodeSearchMatchObject {constructor(sourceCode,lineText,searchTerm,textRange) {this._sourceCode=sourceCode;this._lineText=lineText;this._searchTerm=searchTerm;this._textRange=textRange;this._sourceCodeTextRange=null;} get sourceCode(){return this._sourceCode;} get title(){return this._lineText;} get searchTerm(){return this._searchTerm;} get textRange(){return this._textRange;} get sourceCodeTextRange() {this._sourceCodeTextRange??=this._sourceCode.createSourceCodeTextRange(this._textRange);return this._sourceCodeTextRange;} get className() {return"source-code-match";} saveIdentityToCookie(cookie) {if(this._sourceCode.url) cookie[WI.SourceCodeSearchMatchObject.URLCookieKey]=this._sourceCode.url.hash;cookie[WI.SourceCodeSearchMatchObject.TextRangeKey]=[this._textRange.startLine,this._textRange.startColumn,this._textRange.endLine,this._textRange.endColumn].join();}};WI.SourceCodeSearchMatchObject.TypeIdentifier="source-code-search-match-object";WI.SourceCodeSearchMatchObject.URLCookieKey="source-code-url";WI.SourceCodeSearchMatchObject.TextRangeKey="text-range";WI.SourceCodeTextRange=class SourceCodeTextRange extends WI.Object {constructor(sourceCode){super();this._sourceCode=sourceCode;if(arguments.length===2){var textRange=arguments[1];this._startLocation=sourceCode.createSourceCodeLocation(textRange.startLine,textRange.startColumn);this._endLocation=sourceCode.createSourceCodeLocation(textRange.endLine,textRange.endColumn);}else{this._startLocation=arguments[1];this._endLocation=arguments[2];} this._startLocation.addEventListener(WI.SourceCodeLocation.Event.LocationChanged,this._sourceCodeLocationChanged,this);this._endLocation.addEventListener(WI.SourceCodeLocation.Event.LocationChanged,this._sourceCodeLocationChanged,this);} get sourceCode() {return this._sourceCode;} get textRange() {var startLine=this._startLocation.lineNumber;var startColumn=this._startLocation.columnNumber;var endLine=this._endLocation.lineNumber;var endColumn=this._endLocation.columnNumber;return new WI.TextRange(startLine,startColumn,endLine,endColumn);} get formattedTextRange() {var startLine=this._startLocation.formattedLineNumber;var startColumn=this._startLocation.formattedColumnNumber;var endLine=this._endLocation.formattedLineNumber;var endColumn=this._endLocation.formattedColumnNumber;return new WI.TextRange(startLine,startColumn,endLine,endColumn);} get displaySourceCode() {if(!this._startAndEndLocationsInSameMappedResource()) return this._sourceCode;return this._startLocation.displaySourceCode;} get displayTextRange() {if(!this._startAndEndLocationsInSameMappedResource()) return this.formattedTextRange;var startLine=this._startLocation.displayLineNumber;var startColumn=this._startLocation.displayColumnNumber;var endLine=this._endLocation.displayLineNumber;var endColumn=this._endLocation.displayColumnNumber;return new WI.TextRange(startLine,startColumn,endLine,endColumn);} get synthesizedTextValue() {return this._sourceCode.url+":"+(this._startLocation.lineNumber+1);} _startAndEndLocationsInSameMappedResource() {return this._startLocation.hasMappedLocation()&&this._endLocation.hasMappedLocation()&&this._startLocation.displaySourceCode===this._endLocation.displaySourceCode;} _sourceCodeLocationChanged(event) {this.dispatchEventToListeners(WI.SourceCodeLocation.Event.RangeChanged);}};WI.SourceCodeTextRange.Event={RangeChanged:"source-code-text-range-range-changed"};WI.SourceCodeTimeline=class SourceCodeTimeline extends WI.Timeline {constructor(sourceCode,sourceCodeLocation,recordType,recordEventType) {super();this._sourceCode=sourceCode;this._sourceCodeLocation=sourceCodeLocation||null;this._recordType=recordType;this._recordEventType=recordEventType||null;} get sourceCode(){return this._sourceCode;} get sourceCodeLocation(){return this._sourceCodeLocation;} get recordType(){return this._recordType;} get recordEventType(){return this._recordEventType;} saveIdentityToCookie(cookie) {cookie[WI.SourceCodeTimeline.SourceCodeURLCookieKey]=this._sourceCode.url?this._sourceCode.url.hash:null;cookie[WI.SourceCodeTimeline.SourceCodeLocationLineCookieKey]=this._sourceCodeLocation?this._sourceCodeLocation.lineNumber:null;cookie[WI.SourceCodeTimeline.SourceCodeLocationColumnCookieKey]=this._sourceCodeLocation?this._sourceCodeLocation.columnNumber:null;cookie[WI.SourceCodeTimeline.RecordTypeCookieKey]=this._recordType||null;cookie[WI.SourceCodeTimeline.RecordEventTypeCookieKey]=this._recordEventType||null;}};WI.SourceCodeTimeline.TypeIdentifier="source-code-timeline";WI.SourceCodeTimeline.SourceCodeURLCookieKey="source-code-timeline-source-code-url";WI.SourceCodeTimeline.SourceCodeLocationLineCookieKey="source-code-timeline-source-code-location-line";WI.SourceCodeTimeline.SourceCodeLocationColumnCookieKey="source-code-timeline-source-code-location-column";WI.SourceCodeTimeline.SourceCodeURLCookieKey="source-code-timeline-source-code-url";WI.SourceCodeTimeline.RecordTypeCookieKey="source-code-timeline-record-type";WI.SourceCodeTimeline.RecordEventTypeCookieKey="source-code-timeline-record-event-type";WI.SourceMap=class SourceMap {constructor(sourceMappingURL,payload,originalSourceCode) {if(!WI.SourceMap._base64Map){var base64Digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";WI.SourceMap._base64Map={};for(var i=0;i1){var step=count>>1;var middle=first+step;var mapping=this._mappings[middle];if(lineNumber>=1;return negative?-result:result;}};WI.SourceMap.VLQ_BASE_SHIFT=5;WI.SourceMap.VLQ_BASE_MASK=(1<<5)-1;WI.SourceMap.VLQ_CONTINUATION_MASK=1<<5;WI.SourceMap.StringCharIterator=class StringCharIterator {constructor(string) {this._string=string;this._position=0;} next() {return this._string.charAt(this._position++);} peek() {return this._string.charAt(this._position);} hasNext() {return this._position=epsilon||minimum>=epsilon){current=Math.abs(1-this.solve(t)); if(minimum=epsilon) minimum=Number.POSITIVE_INFINITY; else if(currentWI.CallFrame.fromPayload(target,x));let stackTrace=new WI.StackTrace(callFrames,{topCallFrameIsBoundary:payload.topCallFrameIsBoundary,truncated:payload.truncated,});if(!result) result=stackTrace;if(previousStackTrace) previousStackTrace._parentStackTrace=stackTrace;previousStackTrace=stackTrace;payload=payload.parentStackTrace;} return result;} static fromString(target,stack) {let callFrames=WI.StackTrace._parseStackTrace(stack);return WI.StackTrace.fromPayload(target,{callFrames});} static isLikelyStackTrace(stack) {const smallestPossibleStackTraceLength="http://a.bc/:9:1".length;if(stack.lengthapproximateStackLengthOf50Items) return false;if(/^[^a-z$_@]/i.test(stack[0])) return false;if(!WI.StackTrace._likelyStackTraceRegex){const reasonablyLongProtocolLength=10;const reasonablyLongLineLength=500;const reasonablyLongNativeMethodLength=120;const stackTraceLine=`(global code|eval code|module code|\\w+)?([^:]{1,${reasonablyLongProtocolLength}}://[^:]{1,${reasonablyLongLineLength}}:\\d+:\\d+|[^@]{1,${reasonablyLongNativeMethodLength}}@\\[native code\\])`;WI.StackTrace._likelyStackTraceRegex=new RegExp(`^${stackTraceLine}([\\n\\r]${stackTraceLine})+$`);} WI.StackTrace._likelyStackTraceRegex.lastIndex=0;return WI.StackTrace._likelyStackTraceRegex.test(stack);} static _parseStackTrace(stack) {var lines=stack.split(/\n/g);var result=[];for(var line of lines){var functionName="";var url="";var lineNumber=0;var columnNumber=0;var atIndex=line.indexOf("@");if(atIndex!==-1){functionName=line.slice(0,atIndex);({url,lineNumber,columnNumber}=WI.StackTrace._parseLocation(line.slice(atIndex+1)));}else if(line.includes("/")) ({url,lineNumber,columnNumber}=WI.StackTrace._parseLocation(line));else functionName=line;result.push({functionName,url,lineNumber,columnNumber});} return result;} static _parseLocation(locationString) {var result={url:"",lineNumber:0,columnNumber:0};var locationRegEx=/(.+?)(?::(\d+)(?::(\d+))?)?$/;var matched=locationString.match(locationRegEx);if(!matched) return result;result.url=matched[1];if(matched[2]) result.lineNumber=parseInt(matched[2]);if(matched[3]) result.columnNumber=parseInt(matched[3]);return result;} get callFrames(){return this._callFrames;} get topCallFrameIsBoundary(){return this._topCallFrameIsBoundary;} get truncated(){return this._truncated;} get parentStackTrace(){return this._parentStackTrace;} get firstNonNativeNonAnonymousNotBlackboxedCallFrame() {let firstNonNativeNonAnonymousCallFrame=null;for(let frame of this._callFrames){if(frame.nativeCode) continue;if(frame.sourceCodeLocation){let sourceCode=frame.sourceCodeLocation.sourceCode;if(sourceCode instanceof WI.Script&&sourceCode.anonymous) continue; firstNonNativeNonAnonymousCallFrame??=frame;} if(frame.blackboxed) continue;return frame;} return firstNonNativeNonAnonymousCallFrame;}};WI.StepsTimingFunction=class StepsTimingFunction {constructor(type,count) {this._type=type;this._count=count;} static fromString(text) {if(!text?.length) return null;let trimmedText=text.toLowerCase().replace(/\s/g,"");if(!trimmedText.length) return null;let keywordValue=WI.StepsTimingFunction.keywordValues[trimmedText];if(keywordValue) return new WI.StepsTimingFunction(...keywordValue);let matches=trimmedText.match(/^steps\((\d+)(?:,([a-z-]+))?\)$/);if(!matches) return null;let type=matches[2]||WI.StepsTimingFunction.Type.JumpEnd;if(Object.values(WI.StepsTimingFunction).includes(type)) return null;let count=Number(matches[1]);if(isNaN(count)||count<=0) return null;return new WI.StepsTimingFunction(type,count);} get type(){return this._type;} get count(){return this._count;} copy() {return new WI.StepsTimingFunction(this._type,this._count);} toString() {if(this._type===WI.StepsTimingFunction.Type.JumpStart&&this._count===1) return"step-start";if(this._type===WI.StepsTimingFunction.Type.JumpEnd&&this._count===1) return"step-end";return`steps(${this._count}, ${this._type})`;}};WI.StepsTimingFunction.Type={JumpStart:"jump-start",JumpEnd:"jump-end",JumpNone:"jump-none",JumpBoth:"jump-both",Start:"start",End:"end",};WI.StepsTimingFunction.keywordValues={"step-start":[WI.StepsTimingFunction.Type.JumpStart,1],"step-end":[WI.StepsTimingFunction.Type.JumpEnd,1],};WI.StructureDescription=class StructureDescription {constructor(fields,optionalFields,constructorName,prototypeStructure,imprecise) {this._fields=fields||null;this._optionalFields=optionalFields||null;this._constructorName=constructorName||"";this._prototypeStructure=prototypeStructure||null;this._imprecise=imprecise||false;} static fromPayload(payload) {if(payload.prototypeStructure) payload.prototypeStructure=WI.StructureDescription.fromPayload(payload.prototypeStructure);return new WI.StructureDescription(payload.fields,payload.optionalFields,payload.constructorName,payload.prototypeStructure,payload.imprecise);} get fields(){return this._fields;} get optionalFields(){return this._optionalFields;} get constructorName(){return this._constructorName;} get prototypeStructure(){return this._prototypeStructure;} get imprecise(){return this._imprecise;}};WI.SymbolicBreakpoint=class SymbolicBreakpoint extends WI.Breakpoint {constructor(symbol,{caseSensitive,isRegex,disabled,actions,condition,ignoreCount,autoContinue}={}) {super({disabled,condition,actions,ignoreCount,autoContinue});this._symbol=symbol;this._caseSensitive=caseSensitive!==undefined?!!caseSensitive:true;this._isRegex=isRegex!==undefined?!!isRegex:false;} static supported(target) {return(target||InspectorBackend).hasCommand("Debugger.addSymbolicBreakpoint");} static fromJSON(json) {return new WI.SymbolicBreakpoint(json.symbol,{caseSensitive:json.caseSensitive,isRegex:json.isRegex,disabled:json.disabled,condition:json.condition,actions:json.actions?.map((actionJSON)=>WI.BreakpointAction.fromJSON(actionJSON))||[],ignoreCount:json.ignoreCount,autoContinue:json.autoContinue,});} get symbol(){return this._symbol;} get caseSensitive(){return this._caseSensitive;} get isRegex(){return this._isRegex;} get displayName() {if(this._isRegex) return"/"+this._symbol+"/"+(!this._caseSensitive?"i":"");let displayName=this._symbol;if(!this._caseSensitive) displayName=WI.UIString("%s (Case Insensitive)","%s (Case Insensitive) @ Symbolic Breakpoint","Label for case-insensitive match pattern of a symbolic breakpoint.").format(displayName);return displayName;} get editable() {return true;} matches(symbol) {if(!symbol||this.disabled) return false;if(this._isRegex) return(new RegExp(this._symbol,!this._caseSensitive?"i":"")).test(symbol);if(!this._caseSensitive) return symbol.toLowerCase()===this._symbol.toLowerCase();return symbol===this._symbol;} equals(other) {return this._symbol===other.symbol&&this._caseSensitive===other.caseSensitive&&this._isRegex===other.isRegex;} remove() {super.remove();WI.debuggerManager.removeSymbolicBreakpoint(this);} saveIdentityToCookie(cookie) {cookie["symbolic-breakpoint-symbol"]=this._symbol;cookie["symbolic-breakpoint-symbolic-case-sensitive"]=this._caseSensitive;cookie["symbolic-breakpoint-symbolic-is-regex"]=this._isRegex;} toJSON(key) {let json=super.toJSON(key);json.symbol=this._symbol;json.caseSensitive=this._caseSensitive;json.isRegex=this._isRegex;if(key===WI.ObjectStore.toJSONSymbol) json[WI.objectStores.eventBreakpoints.keyPath]=this._symbol+"-"+this._caseSensitive+"-"+this._isRegex;return json;}};WI.SymbolicBreakpoint.ReferencePage=WI.ReferencePage.SymbolicBreakpoints;WI.TextMarker=class TextMarker {constructor(codeMirrorTextMarker,type) {this._codeMirrorTextMarker=codeMirrorTextMarker;codeMirrorTextMarker.__webInspectorTextMarker=this;this._type=type||WI.TextMarker.Type.Plain;} static textMarkerForCodeMirrorTextMarker(codeMirrorTextMarker) {return codeMirrorTextMarker.__webInspectorTextMarker||new WI.TextMarker(codeMirrorTextMarker);} get codeMirrorTextMarker() {return this._codeMirrorTextMarker;} get type() {return this._type;} get range() {var range=this._codeMirrorTextMarker.find();if(!range) return null;return new WI.TextRange(range.from.line,range.from.ch,range.to.line,range.to.ch);} get rects() {var range=this._codeMirrorTextMarker.find();if(!range) return WI.Rect.ZERO_RECT;return this._codeMirrorTextMarker.doc.cm.rectsForRange({start:range.from,end:range.to});} clear() {this._codeMirrorTextMarker.clear();}};WI.TextMarker.Type={Color:"text-marker-type-color",CubicBezierTimingFunction:"text-marker-type-cubic-bezier-timing-function",Gradient:"text-marker-type-gradient",LinearTimingFunction:"text-marker-type-linear-timing-function",Plain:"text-marker-type-plain",SpringTimingFunction:"text-marker-type-spring-timing-function",StepsTimingFunction:"text-marker-type-steps-timing-function",Variable:"text-marker-type-variable",};WI.TextRange=class TextRange {constructor(startLineOrStartOffset,startColumnOrEndOffset,endLine,endColumn) {if(arguments.length===4){this._startLine=typeof startLineOrStartOffset==="number"?startLineOrStartOffset:NaN;this._startColumn=typeof startColumnOrEndOffset==="number"?startColumnOrEndOffset:NaN;this._endLine=typeof endLine==="number"?endLine:NaN;this._endColumn=typeof endColumn==="number"?endColumn:NaN;this._startOffset=NaN;this._endOffset=NaN;}else if(arguments.length===2){this._startOffset=typeof startLineOrStartOffset==="number"?startLineOrStartOffset:NaN;this._endOffset=typeof startColumnOrEndOffset==="number"?startColumnOrEndOffset:NaN;this._startLine=NaN;this._startColumn=NaN;this._endLine=NaN;this._endColumn=NaN;}} static fromText(text) {let lines=text.split("\n");return new WI.TextRange(0,0,lines.length-1,lines.lastValue.length);} get startLine(){return this._startLine;} get startColumn(){return this._startColumn;} get endLine(){return this._endLine;} get endColumn(){return this._endColumn;} get startOffset(){return this._startOffset;} get endOffset(){return this._endOffset;} startPosition() {return new WI.SourceCodePosition(this._startLine,this._startColumn);} endPosition() {return new WI.SourceCodePosition(this._endLine,this._endColumn);} resolveOffsets(text) {if(typeof text!=="string") return;if(isNaN(this._startLine)||isNaN(this._startColumn)||isNaN(this._endLine)||isNaN(this._endColumn)) return;var lastNewLineOffset=0;for(var i=0;ithis._endLine) return false;if(line===this._startLine&&columnthis._endColumn) return false;return true;} clone() {return new WI.TextRange(this._startLine,this._startColumn,this._endLine,this._endColumn);} cloneAndModify(deltaStartLine,deltaStartColumn,deltaEndLine,deltaEndColumn) {let startLine=this._startLine+deltaStartLine;let startColumn=this._startColumn+deltaStartColumn;let endLine=this._endLine+deltaEndLine;let endColumn=this._endColumn+deltaEndColumn;return new WI.TextRange(startLine,startColumn,endLine,endColumn);} collapseToStart() {return new WI.TextRange(this._startLine,this._startColumn,this._startLine,this._startColumn);} collapseToEnd() {return new WI.TextRange(this._endLine,this._endColumn,this._endLine,this._endColumn);} relativeTo(line,column) {let deltaStartColumn=0;if(this._startLine===line) deltaStartColumn=-column;let deltaEndColumn=0;if(this._endLine===line) deltaEndColumn=-column;return this.cloneAndModify(-line,deltaStartColumn,-line,deltaEndColumn);}};WI.TimelineMarker=class TimelineMarker extends WI.Object {constructor(time,type,details) {super();this._time=time||0;this._type=type;this._details=details||null;} static fromJSON(json) {let{time,type,details}=json;return new WI.TimelineMarker(time,type,details);} toJSON() {return{time:this._time,type:this._type,details:this._details||undefined,};} get type(){return this._type;} get details(){return this._details;} get time() {return this._time;} set time(x) {x=x||0;if(this._time===x) return;this._time=x;this.dispatchEventToListeners(WI.TimelineMarker.Event.TimeChanged);}};WI.TimelineMarker.Event={TimeChanged:"timeline-marker-time-changed"};WI.TimelineMarker.Type={CurrentTime:"current-time",LoadEvent:"load-event",DOMContentEvent:"dom-content-event",TimeStamp:"timestamp",Scanner:"scanner",};WI.TimelineRecording=class TimelineRecording extends WI.Object {constructor(identifier,displayName,instruments) {super();this._identifier=identifier;this._timelines=new Map;this._displayName=displayName;this._capturing=false;this._readonly=false;this._imported=false;this._instruments=instruments||[];this._startTime=NaN;this._endTime=NaN;this._discontinuityStartTime=NaN;this._discontinuities=null;this._firstRecordOfTypeAfterDiscontinuity=new Set;this._exportDataMarkers=null;this._exportDataRecords=null;this._exportDataMemoryPressureEvents=null;this._exportDataSampleStackTraces=null;this._exportDataSampleDurations=null;this._topDownCallingContextTree=new WI.CallingContextTree(WI.CallingContextTree.Type.TopDown);this._bottomUpCallingContextTree=new WI.CallingContextTree(WI.CallingContextTree.Type.BottomUp);this._topFunctionsTopDownCallingContextTree=new WI.CallingContextTree(WI.CallingContextTree.Type.TopFunctionsTopDown);this._topFunctionsBottomUpCallingContextTree=new WI.CallingContextTree(WI.CallingContextTree.Type.TopFunctionsBottomUp);for(let type of WI.TimelineManager.availableTimelineTypes()){let timeline=WI.Timeline.create(type);this._timelines.set(type,timeline);timeline.addEventListener(WI.Timeline.Event.TimesUpdated,this._timelineTimesUpdated,this);} this.reset(true);} static sourceCodeTimelinesSupported() {return WI.sharedApp.isWebDebuggable();} static async import(identifier,json,displayName) {let{startTime,endTime,discontinuities,instrumentTypes,records,markers,memoryPressureEvents,sampleStackTraces,sampleDurations}=json;let importedDisplayName=WI.UIString("Imported - %s").format(displayName);let instruments=instrumentTypes.map((type)=>WI.Instrument.createForTimelineType(type));let recording=new WI.TimelineRecording(identifier,importedDisplayName,instruments);recording._readonly=true;recording._imported=true;recording._startTime=startTime;recording._endTime=endTime;recording._discontinuities=discontinuities;recording.initializeCallingContextTrees(sampleStackTraces,sampleDurations);for(let recordJSON of records){let record=await WI.TimelineRecord.fromJSON(recordJSON);if(record){recording.addRecord(record);if(record instanceof WI.ScriptTimelineRecord) record.profilePayload=recording._topDownCallingContextTree.toCPUProfilePayload(record.startTime,record.endTime);}} for(let memoryPressureJSON of memoryPressureEvents){let memoryPressureEvent=WI.MemoryPressureEvent.fromJSON(memoryPressureJSON);if(memoryPressureEvent) recording.addMemoryPressureEvent(memoryPressureEvent);} setTimeout(()=>{recording.__importing=true;for(let markerJSON of markers){let marker=WI.TimelineMarker.fromJSON(markerJSON);if(marker) recording.addEventMarker(marker);} recording.__importing=false;});return recording;} exportData() {return{displayName:this._displayName,startTime:this._startTime,endTime:this._endTime,discontinuities:this._discontinuities,instrumentTypes:this._instruments.map((instrument)=>instrument.timelineRecordType),records:this._exportDataRecords,markers:this._exportDataMarkers,memoryPressureEvents:this._exportDataMemoryPressureEvents,sampleStackTraces:this._exportDataSampleStackTraces,sampleDurations:this._exportDataSampleDurations,};} get displayName(){return this._displayName;} get identifier(){return this._identifier;} get timelines(){return this._timelines;} get instruments(){return this._instruments;} get capturing(){return this._capturing;} get readonly(){return this._readonly;} get imported(){return this._imported;} get startTime(){return this._startTime;} get endTime(){return this._endTime;} get topDownCallingContextTree(){return this._topDownCallingContextTree;} get bottomUpCallingContextTree(){return this._bottomUpCallingContextTree;} get topFunctionsTopDownCallingContextTree(){return this._topFunctionsTopDownCallingContextTree;} get topFunctionsBottomUpCallingContextTree(){return this._topFunctionsBottomUpCallingContextTree;} start(initiatedByBackend) {this._capturing=true;for(let instrument of this._instruments) instrument.startInstrumentation(initiatedByBackend);if(!isNaN(this._discontinuityStartTime)){for(let instrument of this._instruments) this._firstRecordOfTypeAfterDiscontinuity.add(instrument.timelineRecordType);}} stop(initiatedByBackend) {this._capturing=false;for(let instrument of this._instruments) instrument.stopInstrumentation(initiatedByBackend);} capturingStarted(startTime) { if(!isNaN(this._discontinuityStartTime)){this._discontinuities.push({startTime:this._discontinuityStartTime,endTime:startTime,});this._discontinuityStartTime=NaN;}} capturingStopped(endTime) {this._discontinuityStartTime=endTime;} saveIdentityToCookie() { } isEmpty() {for(var timeline of this._timelines.values()){if(timeline.records.length) return false;} return true;} unloaded(importing) {this._readonly=true;this.dispatchEventToListeners(WI.TimelineRecording.Event.Unloaded);} reset(suppressEvents) {this._sourceCodeTimelinesMap=new Map;this._startTime=NaN;this._endTime=NaN;this._discontinuityStartTime=NaN;this._discontinuities=[];this._firstRecordOfTypeAfterDiscontinuity.clear();this._exportDataMarkers=[];this._exportDataRecords=[];this._exportDataMemoryPressureEvents=[];this._exportDataSampleStackTraces=[];this._exportDataSampleDurations=[];this._topDownCallingContextTree.reset();this._bottomUpCallingContextTree.reset();this._topFunctionsTopDownCallingContextTree.reset();this._topFunctionsBottomUpCallingContextTree.reset();for(var timeline of this._timelines.values()) timeline.reset(suppressEvents);WI.RenderingFrameTimelineRecord.resetFrameIndex();if(!suppressEvents){this.dispatchEventToListeners(WI.TimelineRecording.Event.Reset);this.dispatchEventToListeners(WI.TimelineRecording.Event.TimesUpdated);}} get sourceCodeTimelines() {let timelines=[];for(let timelinesForSourceCode of this._sourceCodeTimelinesMap.values()) timelines.pushAll(timelinesForSourceCode.values());return timelines;} timelineForInstrument(instrument) {return this._timelines.get(instrument.timelineRecordType);} instrumentForTimeline(timeline) {return this._instruments.find((instrument)=>instrument.timelineRecordType===timeline.type);} timelineForRecordType(recordType) {return this._timelines.get(recordType);} addInstrument(instrument) {this._instruments.push(instrument);this.dispatchEventToListeners(WI.TimelineRecording.Event.InstrumentAdded,{instrument});} removeInstrument(instrument) {this._instruments.remove(instrument);this.dispatchEventToListeners(WI.TimelineRecording.Event.InstrumentRemoved,{instrument});} addEventMarker(marker) {this._exportDataMarkers.push(marker);if(!this._capturing&&!this.__importing) return;this.dispatchEventToListeners(WI.TimelineRecording.Event.MarkerAdded,{marker});} addRecord(record) {this._exportDataRecords.push(record);let timeline=this._timelines.get(record.type);if(!timeline) return;let discontinuity=null;if(this._firstRecordOfTypeAfterDiscontinuity.take(record.type)) discontinuity=this._discontinuities.lastValue;timeline.addRecord(record,{discontinuity});if(record.type===WI.TimelineRecord.Type.Network||record.type===WI.TimelineRecord.Type.RenderingFrame||record.type===WI.TimelineRecord.Type.CPU||record.type===WI.TimelineRecord.Type.Memory||record.type===WI.TimelineRecord.Type.HeapAllocations||record.type===WI.TimelineRecord.Type.Screenshots) return;if(!WI.TimelineRecording.sourceCodeTimelinesSupported()) return;let sourceCode=null;if(record.sourceCodeLocation) sourceCode=record.sourceCodeLocation.sourceCode;else if(record.type===WI.TimelineRecord.Type.Media){if(record.domNode&&record.domNode.frame) sourceCode=record.domNode.frame.mainResource;} if(!sourceCode) sourceCode=WI.networkManager.mainFrame.provisionalMainResource||WI.networkManager.mainFrame.mainResource;var sourceCodeTimelines=this._sourceCodeTimelinesMap.get(sourceCode);if(!sourceCodeTimelines){sourceCodeTimelines=new Map;this._sourceCodeTimelinesMap.set(sourceCode,sourceCodeTimelines);} var newTimeline=false;var key=this._keyForRecord(record);var sourceCodeTimeline=sourceCodeTimelines.get(key);if(!sourceCodeTimeline){sourceCodeTimeline=new WI.SourceCodeTimeline(sourceCode,record.sourceCodeLocation,record.type,record.eventType);sourceCodeTimelines.set(key,sourceCodeTimeline);newTimeline=true;} sourceCodeTimeline.addRecord(record);if(newTimeline) this.dispatchEventToListeners(WI.TimelineRecording.Event.SourceCodeTimelineAdded,{sourceCodeTimeline});} addMemoryPressureEvent(memoryPressureEvent) {this._exportDataMemoryPressureEvents.push(memoryPressureEvent);let memoryTimeline=this._timelines.get(WI.TimelineRecord.Type.Memory);if(!memoryTimeline) return;memoryTimeline.addMemoryPressureEvent(memoryPressureEvent);} discontinuitiesInTimeRange(startTime,endTime) {return this._discontinuities.filter((item)=>item.startTime<=endTime&&item.endTime>=startTime);} addScriptInstrumentForProgrammaticCapture() {for(let instrument of this._instruments){if(instrument instanceof WI.ScriptInstrument) return;} this.addInstrument(new WI.ScriptInstrument);let instrumentTypes=this._instruments.map((instrument)=>instrument.timelineRecordType);WI.timelineManager.enabledTimelineTypes=instrumentTypes;} computeElapsedTime(timestamp) {if(!timestamp||isNaN(timestamp)) return NaN;return timestamp;} initializeTimeBoundsIfNecessary(timestamp) {if(isNaN(this._startTime)){this._startTime=timestamp;this._endTime=timestamp;this.dispatchEventToListeners(WI.TimelineRecording.Event.TimesUpdated);}} initializeCallingContextTrees(stackTraces,sampleDurations) {this._exportDataSampleStackTraces.pushAll(stackTraces);this._exportDataSampleDurations.pushAll(sampleDurations);for(let i=0;iWI.BreakpointAction.fromJSON(actionJSON))||[],ignoreCount:json.ignoreCount,autoContinue:json.autoContinue,});} get type(){return this._type;} get url(){return this._url;} get displayName() {if(this===WI.domDebuggerManager.allRequestsBreakpoint) return WI.repeatedUIString.allRequests();switch(this._type){case WI.URLBreakpoint.Type.Text:return doubleQuotedString(this._url);case WI.URLBreakpoint.Type.RegularExpression:return"/"+this._url+"/";} return WI.UIString("URL");} get special() {return this===WI.domDebuggerManager.allRequestsBreakpoint||super.special;} get editable() {return WI.URLBreakpoint.supportsEditing||super.editable;} remove() {super.remove();WI.domDebuggerManager.removeURLBreakpoint(this);} saveIdentityToCookie(cookie) {cookie["url-breakpoint-type"]=this._type;cookie["url-breakpoint-url"]=this._url;} toJSON(key) {let json=super.toJSON(key);json.type=this._type;json.url=this._url;if(key===WI.ObjectStore.toJSONSymbol) json[WI.objectStores.urlBreakpoints.keyPath]=this._type+":"+this._url;return json;}};WI.URLBreakpoint.Type={Text:"text",RegularExpression:"regex",};WI.URLBreakpoint.ReferencePage=WI.ReferencePage.URLBreakpoints;WI.WebInspectorExtension=class WebInspectorExtension {constructor(extensionID,extensionBundleIdentifier,displayName) {this._extensionID=extensionID;this._extensionBundleIdentifier=extensionBundleIdentifier;this._displayName=displayName;} get extensionID(){return this._extensionID;} get extensionBundleIdentifier(){return this._extensionBundleIdentifier;} get displayName(){return this._displayName;}};WI.WebInspectorExtension.ErrorCode={ContextDestroyed:"ContextDestroyed",InternalError:"InternalError",InvalidRequest:"InvalidRequest",RegistrationFailed:"RegistrationFailed",NotImplemented:"NotImplemented",};WI.WebSocketResource=class WebSocketResource extends WI.Resource {constructor(url,{loaderIdentifier,requestIdentifier,requestHeaders,timestamp,walltime,requestSentTimestamp}={}) {super(url,{type:WI.Resource.Type.WebSocket,loaderIdentifier,requestIdentifier,requestMethod:"GET",requestHeaders,requestSentTimestamp,});this._timestamp=timestamp;this._walltime=walltime;this._readyState=WI.WebSocketResource.ReadyState.Connecting;this._frames=[];} get frames(){return this._frames;} get walltime(){return this._walltime;} get readyState() {return this._readyState;} set readyState(state) {if(state===this._readyState) return;let previousState=this._readyState;this._readyState=state;this.dispatchEventToListeners(WI.WebSocketResource.Event.ReadyStateChanged,{previousState,state});} addFrame(data,payloadLength,isOutgoing,opcode,timestamp,elapsedTime) {let frameData;if(opcode===WI.WebSocketResource.OpCodes.BinaryFrame) frameData=null;else frameData=data;let frame={data:frameData,isOutgoing,opcode,walltime:this._walltimeForWebSocketTimestamp(timestamp)};this._frames.push(frame);if(InspectorFrontendHost.isUnderTest()) frame.dataForTest=data;this.increaseSize(payloadLength,elapsedTime);this.dispatchEventToListeners(WI.WebSocketResource.Event.FrameAdded,frame);} requestContentFromBackend() {return super.requestContentFromBackend();} _walltimeForWebSocketTimestamp(timestamp) {return this._walltime+(timestamp-this._timestamp);}};WI.WebSocketResource.Event={FrameAdded:"web-socket-frame-added",ReadyStateChanged:"web-socket-resource-ready-state-changed",};WI.WebSocketResource.ReadyState={Closed:Symbol("closed"),Connecting:Symbol("connecting"),Open:Symbol("open"),};WI.WebSocketResource.OpCodes={ContinuationFrame:0,TextFrame:1,BinaryFrame:2,ConnectionCloseFrame:8,PingFrame:9,PongFrame:10,};WI.WrappedPromise=class WrappedPromise {constructor(work) {this._settled=false;this._promise=new Promise((resolve,reject)=>{this._resolveCallback=resolve;this._rejectCallback=reject; if(work&&typeof work==="function") return work(this.resolve.bind(this),this.reject.bind(this));});} get settled() {return this._settled;} get promise() {return this._promise;} resolve(value) {if(this._settled) throw new Error("Promise is already settled, cannot call resolve().");this._settled=true;this._resolveCallback(value);} reject(value) {if(this._settled) throw new Error("Promise is already settled, cannot call reject().");this._settled=true;this._rejectCallback(value);}}; WI.LocalResource=class LocalResource extends WI.Resource {constructor({request,response,metrics,timing,mappedFilePath}) {metrics=metrics||{};timing=timing||{};super(request.url,{mimeType:response.mimeType||(response.headers||{}).valueForCaseInsensitiveKey("Content-Type")||null,requestMethod:request.method,requestHeaders:request.headers,requestData:request.data,requestSentTimestamp:request.timestamp,requestSentWalltime:request.walltime,});this._finishedOrFailedTimestamp=request.finishedTimestamp||NaN;this._statusCode=response.statusCode||NaN;this._statusText=response.statusText||null;this._responseHeaders=response.headers||{};this._failureReasonText=response.failureReasonText||null;this._timingData=new WI.ResourceTimingData(this,timing);this._responseSource=metrics.responseSource||WI.Resource.ResponseSource.Unknown;this._protocol=metrics.protocol||null;this._priority=metrics.priority||WI.Resource.NetworkPriority.Unknown;this._remoteAddress=metrics.remoteAddress||null;this._connectionIdentifier=metrics.connectionIdentifier||null;this._requestHeadersTransferSize=!isNaN(metrics.requestHeaderBytesSent)?metrics.requestHeaderBytesSent:NaN;this._requestBodyTransferSize=!isNaN(metrics.requestBodyBytesSent)?metrics.requestBodyBytesSent:NaN;this._responseHeadersTransferSize=!isNaN(metrics.responseHeaderBytesReceived)?metrics.responseHeaderBytesReceived:NaN;this._responseBodyTransferSize=!isNaN(metrics.responseBodyBytesReceived)?metrics.responseBodyBytesReceived:NaN;this._responseBodySize=!isNaN(metrics.responseBodyDecodedSize)?metrics.responseBodyDecodedSize:NaN;this._isProxyConnection=!!metrics.isProxyConnection;this._localResourceOverride=null;this._finished=true;this._failed=false;this._cached=false;let content=response.content||"";let base64Encoded=response.base64Encoded||false;this._originalRevision=new WI.SourceCodeRevision(this,content,base64Encoded,this._mimeType);this._currentRevision=this._originalRevision;this._mappedFilePath=mappedFilePath||null;} static canMapToFile() {return InspectorFrontendHost.canLoad();} static resetPathsThatFailedToLoadFromFileSystem() {WI.LocalResource._pathsThatFailedToLoadFromFileSystem.clear();} static headersArrayToHeadersObject(headers) {let result={};if(headers){for(let{name,value}of headers) result[name]=value;} return result;} static fromHAREntry(entry,archiveStartWalltime) { let{request,response,startedDateTime,timings}=entry;let requestSentWalltime=WI.HARBuilder.dateFromHARDate(startedDateTime)/1000;let requestSentTimestamp=requestSentWalltime-archiveStartWalltime;let finishedTimestamp=NaN;let timing={startTime:NaN,domainLookupStart:NaN,domainLookupEnd:NaN,connectStart:NaN,connectEnd:NaN,secureConnectionStart:NaN,requestStart:NaN,responseStart:NaN,responseEnd:NaN,};if(!isNaN(requestSentWalltime)&&!isNaN(archiveStartWalltime)){let hasBlocked=timings.blocked!==-1;let hasDNS=timings.dns!==-1;let hasConnect=timings.connect!==-1;let hasSecureConnect=timings.ssl!==-1; timing.startTime=requestSentTimestamp||Number.EPSILON;timing.fetchStart=timing.startTime;let accumulation=timing.startTime;if(hasBlocked) accumulation+=(timings.blocked/1000);if(hasDNS){timing.domainLookupStart=accumulation;accumulation+=(timings.dns/1000);timing.domainLookupEnd=accumulation;} if(hasConnect){timing.connectStart=accumulation;accumulation+=(timings.connect/1000);timing.connectEnd=accumulation;if(hasSecureConnect) timing.secureConnectionStart=timing.connectEnd-(timings.ssl/1000);} accumulation+=(timings.send/1000);timing.requestStart=accumulation;accumulation+=(timings.wait/1000);timing.responseStart=accumulation;accumulation+=(timings.receive/1000);timing.responseEnd=accumulation;finishedTimestamp=timing.responseEnd;} let serverAddress=entry.serverIPAddress||null;if(serverAddress&&typeof entry._serverPort==="number") serverAddress+=":"+entry._serverPort;return new WI.LocalResource({request:{url:request.url,method:request.method,headers:LocalResource.headersArrayToHeadersObject(request.headers),timestamp:requestSentTimestamp,walltime:requestSentWalltime,finishedTimestamp:finishedTimestamp,data:request.postData?request.postData.text:null,},response:{headers:LocalResource.headersArrayToHeadersObject(response.headers),mimeType:response.content.mimeType,statusCode:response.status,statusText:response.statusText,failureReasonText:response._error||null,content:response.content.text,base64Encoded:response.content.encoding==="base64",},metrics:{responseSource:WI.HARBuilder.responseSourceFromHARFetchType(entry._fetchType),protocol:WI.HARBuilder.protocolFromHARProtocol(response.httpVersion),priority:WI.HARBuilder.networkPriorityFromHARPriority(entry._priority),remoteAddress:serverAddress,connectionIdentifier:entry.connection?parseInt(entry.connection):null,requestHeaderBytesSent:request.headersSize>=0?request.headersSize:NaN,requestBodyBytesSent:request.bodySize>=0?request.bodySize:NaN,responseHeaderBytesReceived:response.headersSize>=0?response.headersSize:NaN,responseBodyBytesReceived:response.bodySize>=0?response.bodySize:NaN,responseBodyDecodedSize:response.content.size||NaN,},timing,});} static fromJSON(json) {return new WI.LocalResource(json);} toJSON(key) {return{request:{url:this.url,method:this.requestMethod,headers:this.requestHeaders,data:this.requestData,},response:{headers:this.responseHeaders,mimeType:this.mimeType,statusCode:this.statusCode,statusText:this.statusText,content:this.currentRevision.content,base64Encoded:this.currentRevision.base64Encoded,},mappedFilePath:this._mappedFilePath,};} get localResourceOverride(){return this._localResourceOverride;} get mappedFilePath() {return this._mappedFilePath;} set mappedFilePath(mappedFilePath) {if(mappedFilePath===this._mappedFilePath) return;this._mappedFilePath=mappedFilePath;const forceUpdate=true;this._updateContentFromFileSystem(forceUpdate).then(()=>{this.dispatchEventToListeners(WI.LocalResource.Event.MappedFilePathChanged);});} get isMappedToDirectory() {return this._mappedFilePath?.endsWith("/");} async requestContentFromMappedDirectory(subpath) {return this._loadFromFileSystem({subpath});} async requestContent() {await this._updateContentFromFileSystem();return super.requestContent();} requestContentFromBackend() {return Promise.resolve({content:this._originalRevision.content,base64Encoded:this._originalRevision.base64Encoded,});} handleCurrentRevisionContentChange() {if(this._mimeType!==this.currentRevision.mimeType){let oldMIMEType=this._mimeType;this._mimeType=this.currentRevision.mimeType;this.dispatchEventToListeners(WI.Resource.Event.MIMETypeDidChange,{oldMIMEType});}} async _loadFromFileSystem({subpath}={}) {let path=this._mappedFilePath;if(!path) return null;if(this.isMappedToDirectory){if(!subpath) return null;path+=subpath;} let content=null;try{content=await InspectorFrontendHost.load(path);}catch{} if(typeof content==="string") WI.LocalResource._pathsThatFailedToLoadFromFileSystem.delete(path);else if(!WI.LocalResource._pathsThatFailedToLoadFromFileSystem.has(path)){WI.LocalResource._pathsThatFailedToLoadFromFileSystem.add(path);let message=WI.UIString("Local Override: could not load \u201C%s\u201D").format(path);if(window.InspectorTest) console.warn(message);else{let consoleMessage=new WI.ConsoleMessage(WI.mainTarget,WI.ConsoleMessage.MessageSource.Other,WI.ConsoleMessage.MessageLevel.Warning,message);consoleMessage.shouldRevealConsole=true;WI.consoleLogViewController.appendConsoleMessage(consoleMessage);}} return content;} async _updateContentFromFileSystem(forceUpdate) {let content=await this._loadFromFileSystem();if(typeof content!=="string") return;if(!forceUpdate&&content===this.currentRevision.content) return;this.editableRevision.updateRevisionContent(content);}};WI.LocalResource._pathsThatFailedToLoadFromFileSystem=new Set;WI.LocalResource.Event={MappedFilePathChanged:"local-resource-mapped-file-path-changed",};WI.SourceMapResource=class SourceMapResource extends WI.Resource {constructor(url,sourceMap) {super(url);this._sourceMap=sourceMap;var inheritedMIMEType=this._sourceMap.originalSourceCode instanceof WI.Resource?this._sourceMap.originalSourceCode.syntheticMIMEType:null;let fileExtension=WI.fileExtensionForURL(url)||"";let fileExtensionMIMEType=fileExtension==="js"?"text/jsx":WI.mimeTypeForFileExtension(fileExtension,true); this._mimeType=fileExtensionMIMEType||inheritedMIMEType||"text/javascript";this._type=WI.Resource.typeFromMIMEType(this._mimeType);this.markAsFinished();} get sourceMap(){return this._sourceMap;} get sourceMapDisplaySubpath() {var sourceMappingBasePathURLComponents=this._sourceMap.sourceMappingBasePathURLComponents;var resourceURLComponents=this.urlComponents;if(!resourceURLComponents.path) resourceURLComponents.path=this.url;if(resourceURLComponents.scheme!==sourceMappingBasePathURLComponents.scheme||resourceURLComponents.host!==sourceMappingBasePathURLComponents.host){let subpath="";if(resourceURLComponents.host){subpath+=resourceURLComponents.host;if(resourceURLComponents.port) subpath+=":"+resourceURLComponents.port;subpath+=resourceURLComponents.path;}else{subpath+=resourceURLComponents.path.substring(1);} return subpath;} if(!resourceURLComponents.path.startsWith(sourceMappingBasePathURLComponents.path)) return relativePath(resourceURLComponents.path,sourceMappingBasePathURLComponents.path);return resourceURLComponents.path.substring(sourceMappingBasePathURLComponents.path.length,resourceURLComponents.length);} get supportsScriptBlackboxing() {return false;} requestContentFromBackend() {this.revertMarkAsFinished();var inlineContent=this._sourceMap.sourceContent(this.url);if(inlineContent){return Promise.resolve().then(sourceMapResourceLoaded.bind(this,{content:inlineContent,mimeType:this.mimeType,statusCode:200}));} function sourceMapResourceNotAvailable(error,content,mimeType,statusCode) {this.markAsFailed();return Promise.resolve({error:WI.UIString("An error occurred trying to load the resource."),content,mimeType,statusCode});} function sourceMapResourceLoadError(error) {console.error(error||"There was an unknown error calling Network.loadResource.");this.markAsFailed();return Promise.resolve({error:WI.UIString("An error occurred trying to load the resource.")});} function sourceMapResourceLoaded(parameters) {var{error,content,mimeType,statusCode}=parameters;var base64encoded=false;if(statusCode>=400||error) return sourceMapResourceNotAvailable(error,content,mimeType,statusCode);this.markAsFinished();return Promise.resolve({content,mimeType,base64encoded,statusCode});} if(!this._target.hasCommand("Network.loadResource")) return sourceMapResourceLoadError.call(this);var frameIdentifier=null;if(this._sourceMap.originalSourceCode instanceof WI.Resource&&this._sourceMap.originalSourceCode.parentFrame) frameIdentifier=this._sourceMap.originalSourceCode.parentFrame.id;if(!frameIdentifier) frameIdentifier=WI.networkManager.mainFrame?WI.networkManager.mainFrame.id:"";return this._target.NetworkAgent.loadResource(frameIdentifier,this.url).then(sourceMapResourceLoaded.bind(this)).catch(sourceMapResourceLoadError.bind(this));} createSourceCodeLocation(lineNumber,columnNumber) {var entry=this._sourceMap.findEntryReversed(this.url,lineNumber);var rawLineNumber=entry[0];var rawColumnNumber=entry[1];var originalSourceCode=this._sourceMap.originalSourceCode;if(originalSourceCode instanceof WI.Script){if(rawLineNumber===0) rawColumnNumber+=originalSourceCode.range.startColumn;rawLineNumber+=originalSourceCode.range.startLine;} var location=originalSourceCode.createSourceCodeLocation(rawLineNumber,rawColumnNumber);location._setMappedLocation(this,lineNumber,columnNumber);return location;} createSourceCodeTextRange(textRange) {var startSourceCodeLocation=this.createSourceCodeLocation(textRange.startLine,textRange.startColumn);var endSourceCodeLocation=this.createSourceCodeLocation(textRange.endLine,textRange.endColumn);return new WI.SourceCodeTextRange(this._sourceMap.originalSourceCode,startSourceCodeLocation,endSourceCodeLocation);}};WI.AuditTestBase=class AuditTestBase extends WI.Object {constructor(name,{description,supports,setup,disabled}={}) {super();this._name=name;this._description=description||"";this._supports=supports??NaN;this._setup=setup||"";this.determineIfSupported({warn:true});this._runningState=disabled?WI.AuditManager.RunningState.Disabled:WI.AuditManager.RunningState.Inactive;this._result=null;this._parent=null;this._default=false;} get runningState(){return this._runningState;} get result(){return this._result;} get supported(){return this._supported;} get name() {return this._name;} set name(name) {if(name===this._name) return;let oldName=this._name;this._name=name;this.dispatchEventToListeners(WI.AuditTestBase.Event.NameChanged,{oldName});} get description() {return this._description;} set description(description) {if(description===this._description) return;this._description=description;} get supports() {return this._supports;} set supports(supports) {if(supports===this._supports) return;this._supports=supports;this.determineIfSupported();} get setup() {return this._setup;} set setup(setup) {if(setup===this._setup) return;this._setup=setup;this.clearResult();} get disabled() {return this._runningState===WI.AuditManager.RunningState.Disabled;} set disabled(disabled) {this.updateDisabled(disabled);} get editable() {return!this._default;} get default() {return this._default;} markAsDefault() {this._default=true;} get topLevelTest() {let test=this;while(test._parent) test=test._parent;return test;} async runSetup() {if(!this._setup) return;let target=WI.assumingMainTarget();let agentCommandFunction=null;let agentCommandArguments={};if(target.hasDomain("Audit")){agentCommandFunction=target.AuditAgent.run;agentCommandArguments.test=this._setup;}else{agentCommandFunction=target.RuntimeAgent.evaluate;agentCommandArguments.expression=`(function() { "use strict"; return eval(\`(${this._setup.replace(/`/g,"\\`")})\`)(); })()`;agentCommandArguments.objectGroup=AuditTestBase.ObjectGroup;agentCommandArguments.doNotPauseOnExceptionsAndMuteConsole=true;} try{let response=await agentCommandFunction.invoke(agentCommandArguments);if(response.result.type==="object"&&response.result.className==="Promise"){if(WI.RuntimeManager.supportsAwaitPromise()) response=await target.RuntimeAgent.awaitPromise(response.result.objectId);else{response=null;WI.AuditManager.synthesizeError(WI.UIString("Async audits are not supported."));}} if(response){let remoteObject=WI.RemoteObject.fromPayload(response.result,WI.mainTarget);if(response.wasThrown||(remoteObject.type==="object"&&remoteObject.subtype==="error")) WI.AuditManager.synthesizeError(remoteObject.description);}}catch(error){WI.AuditManager.synthesizeError(error.message);}} async start() {if(!this._supported||this.disabled) return;if(this._runningState!==WI.AuditManager.RunningState.Inactive) return;this._runningState=WI.AuditManager.RunningState.Active;this.dispatchEventToListeners(WI.AuditTestBase.Event.Scheduled);await this.run();this._runningState=WI.AuditManager.RunningState.Inactive;this.dispatchEventToListeners(WI.AuditTestBase.Event.Completed);} stop() {if(!this._supported||this.disabled) return;if(this._runningState!==WI.AuditManager.RunningState.Active) return;this._runningState=WI.AuditManager.RunningState.Stopping;this.dispatchEventToListeners(WI.AuditTestBase.Event.Stopping);} clearResult(options={}) {if(!this._result) return false;this._result=null;if(!options.suppressResultChangedEvent) this.dispatchEventToListeners(WI.AuditTestBase.Event.ResultChanged);return true;} async clone() {return this.constructor.fromPayload(this.toJSON());} remove() {if(!this._parent||this._default){WI.auditManager.removeTest(this);return;} this._parent.removeTest(this);} saveIdentityToCookie(cookie) {let path=[];let test=this;while(test){path.push(test.name);test=test._parent;} path.reverse();cookie["audit-path"]=path.join(",");} toJSON(key) {let json={type:this.constructor.TypeIdentifier,name:this._name,};if(this._description) json.description=this._description;if(!isNaN(this._supports)) json.supports=Number.isFinite(this._supports)?this._supports:WI.AuditTestBase.Version+1;if(this._setup) json.setup=this._setup;if(key===WI.ObjectStore.toJSONSymbol) json.disabled=this.disabled;return json;} async run() {throw WI.NotImplementedError.subclassMustOverride();} determineIfSupported(options={}) {let supportedBefore=this._supported;if(this._supports>WI.AuditTestBase.Version){this.updateSupported(false,options);if(options.warn&&supportedBefore!==this._supported&&Number.isFinite(this._supports)) WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 is too new to run in this Web Inspector").format(this.name));}else if(InspectorBackend.hasDomain("Audit")&&this._supports>InspectorBackend.getVersion("Audit")){this.updateSupported(false,options);if(options.warn&&supportedBefore!==this._supported&&Number.isFinite(this._supports)) WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 is too new to run in the inspected page").format(this.name));}else this.updateSupported(true,options);return this._supported;} updateSupported(supported,options={}) {if(supported===this._supported) return;this._supported=supported;if(!options.silent) this.dispatchEventToListeners(WI.AuditTestBase.Event.SupportedChanged);if(!this._supported) this.clearResult();} updateDisabled(disabled,options={}) {if(this._runningState!==WI.AuditManager.RunningState.Disabled&&this._runningState!==WI.AuditManager.RunningState.Inactive) return;let runningState=disabled?WI.AuditManager.RunningState.Disabled:WI.AuditManager.RunningState.Inactive;if(runningState===this._runningState) return;this._runningState=runningState;if(!options.silent) this.dispatchEventToListeners(WI.AuditTestBase.Event.DisabledChanged);if(this.disabled) this.clearResult();} updateResult(result) {this._result=result;this.dispatchEventToListeners(WI.AuditTestBase.Event.ResultChanged);}};WI.AuditTestBase.Version=4;WI.AuditTestBase.ObjectGroup="audit";WI.AuditTestBase.Event={Completed:"audit-test-base-completed",DisabledChanged:"audit-test-base-disabled-changed",NameChanged:"audit-test-base-name-changed",Progress:"audit-test-base-progress",ResultChanged:"audit-test-base-result-changed",Scheduled:"audit-test-base-scheduled",Stopping:"audit-test-base-stopping",SupportedChanged:"audit-test-base-supported-changed",TestChanged:"audit-test-base-test-changed",};WI.AuditTestCase=class AuditTestCase extends WI.AuditTestBase {constructor(name,test,options={}) {super(name,options);this._test=test;} static async fromPayload(payload) {if(typeof payload!=="object"||payload===null) return null;if(payload.type!==WI.AuditTestCase.TypeIdentifier) return null;if(typeof payload.name!=="string"){WI.AuditManager.synthesizeError(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("name")));return null;} if(typeof payload.test!=="string"){WI.AuditManager.synthesizeError(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("test")));return null;} let options={};if(typeof payload.description==="string") options.description=payload.description;else if("description"in payload) WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("description")));if(typeof payload.supports==="number") options.supports=payload.supports;else if("supports"in payload) WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-number \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("supports")));if(typeof payload.setup==="string") options.setup=payload.setup;else if("setup"in payload) WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("setup")));if(typeof payload.disabled==="boolean") options.disabled=payload.disabled;return new WI.AuditTestCase(payload.name,payload.test,options);} get test() {return this._test;} set test(test) {if(test===this._test) return;this._test=test;this.clearResult();this.dispatchEventToListeners(WI.AuditTestBase.Event.TestChanged);} toJSON(key) {let json=super.toJSON(key);json.test=this._test;return json;} async run() {const levelStrings=Object.values(WI.AuditTestCaseResult.Level);let level=null;let data={};let metadata={url:WI.networkManager.mainFrame.url,startTimestamp:null,endTimestamp:null,};let resolvedDOMNodes=null;function setLevel(newLevel){let newLevelIndex=levelStrings.indexOf(newLevel);if(newLevelIndex<0){addError(WI.UIString("Return string must be one of %s").format(JSON.stringify(levelStrings)));return;} if(newLevelIndex<=levelStrings.indexOf(level)) return;level=newLevel;} function addError(value){setLevel(WI.AuditTestCaseResult.Level.Error);if(!data.errors) data.errors=[];data.errors.push(value);} async function parseResponse(response){let remoteObject=WI.RemoteObject.fromPayload(response.result,WI.mainTarget);if(response.wasThrown||(remoteObject.type==="object"&&remoteObject.subtype==="error")){addError(remoteObject.description);return;} if(remoteObject.type==="boolean"){setLevel(remoteObject.value?WI.AuditTestCaseResult.Level.Pass:WI.AuditTestCaseResult.Level.Fail);return;} if(remoteObject.type==="string"){setLevel(remoteObject.value.trim().toLowerCase());return;} if(remoteObject.type!=="object"||remoteObject.subtype){addError(WI.UIString("Return value is not an object, string, or boolean"));return;} const options={ownProperties:true,};function checkResultProperty(key,value,type,subtype){function addErrorForValueType(valueType){let errorString=null;if(valueType==="object"||valueType==="array") errorString=WI.UIString("\u0022%s\u0022 must be an %s");else errorString=WI.UIString("\u0022%s\u0022 must be a %s");addError(errorString.format(key,valueType));} if(value.subtype!==subtype){addErrorForValueType(subtype);return null;} if(value.type!==type){addErrorForValueType(type);return null;} if(type==="boolean"||type==="string") return value.value;return value;} async function resultArrayForEach(key,value,callback){let array=checkResultProperty(key,value,"object","array");if(!array) return;let arrayProperties=await new Promise((resolve,reject)=>array.getPropertyDescriptors(resolve,options));for(let i=0;iarrayProperty.name===String(i));if(arrayPropertyForIndex) await callback(arrayPropertyForIndex);}} let properties=await new Promise((resolve,reject)=>remoteObject.getPropertyDescriptors(resolve,options));for(let property of properties){let key=property.name;if(key==="__proto__") continue;let value=property.value;switch(key){case"level":{let levelString=checkResultProperty(key,value,"string");if(levelString) setLevel(levelString.trim().toLowerCase());break;} case"pass":if(checkResultProperty(key,value,"boolean")) setLevel(WI.AuditTestCaseResult.Level.Pass);break;case"warn":if(checkResultProperty(key,value,"boolean")) setLevel(WI.AuditTestCaseResult.Level.Warn);break;case"fail":if(checkResultProperty(key,value,"boolean")) setLevel(WI.AuditTestCaseResult.Level.Fail);break;case"error":if(checkResultProperty(key,value,"boolean")) setLevel(WI.AuditTestCaseResult.Level.Error);break;case"unsupported":if(checkResultProperty(key,value,"boolean")) setLevel(WI.AuditTestCaseResult.Level.Unsupported);break;case"domNodes":await resultArrayForEach(key,value,async(item)=>{if(!item||!item.value||item.value.type!=="object"||item.value.subtype!=="node"){addError(WI.UIString("All items in \u0022%s\u0022 must be valid DOM nodes").format(WI.unlocalizedString("domNodes")));return;} let domNodeId=await new Promise((resolve,reject)=>item.value.pushNodeToFrontend(resolve));let domNode=WI.domManager.nodeForId(domNodeId);if(!domNode) return;if(!data.domNodes) data.domNodes=[];data.domNodes.push(WI.cssPath(domNode,{full:true}));if(!resolvedDOMNodes) resolvedDOMNodes=[];resolvedDOMNodes.push(domNode);});break;case"domAttributes":await resultArrayForEach(key,value,(item)=>{if(!item||!item.value||item.value.type!=="string"||!item.value.value.length){addError(WI.UIString("All items in \u0022%s\u0022 must be non-empty strings").format(WI.unlocalizedString("domAttributes")));return;} if(!data.domAttributes) data.domAttributes=[];data.domAttributes.push(item.value.value);});break;case"errors":await resultArrayForEach(key,value,(item)=>{if(!item||!item.value||item.value.type!=="object"||item.value.subtype!=="error"){addError(WI.UIString("All items in \u0022%s\u0022 must be error objects").format(WI.unlocalizedString("errors")));return;} addError(item.value.description);});break;default:if(value.objectId){try{function inspectedPage_stringify(){return JSON.stringify(this);} let stringifiedValue=await value.callFunction(inspectedPage_stringify);data[key]=JSON.parse(stringifiedValue.value);}catch{addError(WI.UIString("\u0022%s\u0022 is not JSON serializable").format(key));}}else data[key]=value.value;break;}}} let target=WI.assumingMainTarget();let agentCommandFunction=null;let agentCommandArguments={};if(target.hasDomain("Audit")){agentCommandFunction=target.AuditAgent.run;agentCommandArguments.test=this._test;}else{agentCommandFunction=target.RuntimeAgent.evaluate;agentCommandArguments.expression=`(function() { "use strict"; return eval(\`(${this._test.replace(/`/g,"\\`")})\`)(); })()`;agentCommandArguments.objectGroup=WI.AuditTestCase.ObjectGroup;agentCommandArguments.doNotPauseOnExceptionsAndMuteConsole=true;} try{metadata.startTimestamp=new Date;let response=await agentCommandFunction.invoke(agentCommandArguments);metadata.endTimestamp=new Date;if(response.result.type==="object"&&response.result.className==="Promise"){if(WI.RuntimeManager.supportsAwaitPromise()){metadata.asyncTimestamp=metadata.endTimestamp;response=await target.RuntimeAgent.awaitPromise(response.result.objectId);metadata.endTimestamp=new Date;}else{response=null;addError(WI.UIString("Async audits are not supported."));setLevel(WI.AuditTestCaseResult.Level.Unsupported);}} if(response) await parseResponse(response);}catch(error){metadata.endTimestamp=new Date;addError(error.message);} if(!level) addError(WI.UIString("Missing result level"));let options={description:this.description,metadata,};if(!isEmptyObject(data)) options.data=data;if(resolvedDOMNodes) options.resolvedDOMNodes=resolvedDOMNodes;this.updateResult(new WI.AuditTestCaseResult(this.name,level,options));}};WI.AuditTestCase.TypeIdentifier="test-case";WI.AuditTestGroup=class AuditTestGroup extends WI.AuditTestBase {constructor(name,tests,options={}) {let disabled=options.disabled;options.disabled=false;super(name,options);this._tests=[];for(let test of tests) this.addTest(test);if(disabled) this.updateDisabled(true);} static async fromPayload(payload) {if(typeof payload!=="object"||payload===null) return null;if(payload.type!==WI.AuditTestGroup.TypeIdentifier) return null;if(typeof payload.name!=="string"){WI.AuditManager.synthesizeError(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("name")));return null;} if(!Array.isArray(payload.tests)){WI.AuditManager.synthesizeError(WI.UIString("\u0022%s\u0022 has a non-array \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("tests")));return null;} let tests=await Promise.all(payload.tests.map(async(test)=>{let testCase=await WI.AuditTestCase.fromPayload(test);if(testCase) return testCase;let testGroup=await WI.AuditTestGroup.fromPayload(test);if(testGroup) return testGroup;return null;}));tests=tests.filter((test)=>!!test);if(!tests.length) return null;let options={};if(typeof payload.description==="string") options.description=payload.description;else if("description"in payload) WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("description")));if(typeof payload.supports==="number") options.supports=payload.supports;else if("supports"in payload) WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-number \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("supports")));if(typeof payload.setup==="string") options.setup=payload.setup;else if("setup"in payload) WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("setup")));if(typeof payload.disabled==="boolean") options.disabled=payload.disabled;return new WI.AuditTestGroup(payload.name,tests,options);} get tests(){return this._tests;} addTest(test) {this._tests.push(test);test._parent=this;test.addEventListener(WI.AuditTestBase.Event.Completed,this._handleTestCompleted,this);test.addEventListener(WI.AuditTestBase.Event.DisabledChanged,this._handleTestDisabledChanged,this);test.addEventListener(WI.AuditTestBase.Event.Progress,this._handleTestProgress,this);if(this.editable){test.addEventListener(WI.AuditTestBase.Event.SupportedChanged,this._handleTestSupportedChanged,this);test.addEventListener(WI.AuditTestBase.Event.TestChanged,this._handleTestChanged,this);} this.dispatchEventToListeners(WI.AuditTestGroup.Event.TestAdded,{test});this.determineIfSupported();if(this._checkDisabled(test)) test.updateDisabled(true,{silent:true});} removeTest(test) {test.removeEventListener(WI.AuditTestBase.Event.Completed,this._handleTestCompleted,this);test.removeEventListener(WI.AuditTestBase.Event.DisabledChanged,this._handleTestDisabledChanged,this);test.removeEventListener(WI.AuditTestBase.Event.Progress,this._handleTestProgress,this);test.removeEventListener(WI.AuditTestBase.Event.SupportedChanged,this._handleTestSupportedChanged,this);test.removeEventListener(WI.AuditTestBase.Event.TestChanged,this._handleTestChanged,this);this._tests.remove(test);test._parent=null;this.dispatchEventToListeners(WI.AuditTestGroup.Event.TestRemoved,{test});this.determineIfSupported();this._checkDisabled();} stop() {for(let test of this._tests) test.stop();super.stop();} clearResult(options={}) {let cleared=!!this.result;if(!options.excludeTests&&this._tests){for(let test of this._tests){if(test.clearResult(options)) cleared=true;}} return super.clearResult({...options,suppressResultChangedEvent:!cleared,});} toJSON(key) {let json=super.toJSON(key);json.tests=this._tests.map((testCase)=>testCase.toJSON(key));return json;} async run() {let count=this._tests.length;for(let index=0;index!test.supported))){supported=false;for(let test of this._tests) test.updateSupported(supported,{silent:true});} super.updateSupported(supported,options);} updateDisabled(disabled,options={}) {if(!options.excludeTests&&this._tests){for(let test of this._tests) test.updateDisabled(disabled,options);} super.updateDisabled(disabled,options);} updateResult() {let results=this._tests.map((test)=>test.result).filter((result)=>!!result);if(!results.length) return;super.updateResult(new WI.AuditTestGroupResult(this.name,results,{description:this.description,}));} _checkDisabled(test) {let testDisabled=!test||!test.supported||test.disabled;let enabledTestCount=this._tests.filter((existing)=>existing.supported&&!existing.disabled).length;if(testDisabled&&!enabledTestCount) this.updateDisabled(true);else if(!testDisabled&&enabledTestCount===1) this.updateDisabled(false,{excludeTests:true});else{this.dispatchEventToListeners(WI.AuditTestBase.Event.DisabledChanged);} return this.disabled;} _handleTestCompleted(event) {if(this._runningState===WI.AuditManager.RunningState.Active) return;this.updateResult();this.dispatchEventToListeners(WI.AuditTestBase.Event.Completed);} _handleTestDisabledChanged(event) {this._checkDisabled(event.target);} _handleTestProgress(event) {if(this._runningState!==WI.AuditManager.RunningState.Active) return;let walk=(tests)=>{let count=0;for(let test of tests){if(test.disabled||!test.supported) continue;if(test instanceof WI.AuditTestCase) ++count;else if(test instanceof WI.AuditTestGroup) count+=walk(test.tests);} return count;};this.dispatchEventToListeners(WI.AuditTestBase.Event.Progress,{index:event.data.index+walk(this._tests.slice(0,this._tests.indexOf(event.target))),count:walk(this._tests),});} _handleTestSupportedChanged(event) {this.determineIfSupported();} _handleTestChanged(event) {this.clearResult({excludeTests:true});this.dispatchEventToListeners(WI.AuditTestBase.Event.TestChanged);}};WI.AuditTestGroup.TypeIdentifier="test-group";WI.AuditTestGroup.Event={TestAdded:"audit-test-group-test-added",TestRemoved:"audit-test-group-test-removed",};WI.AuditTestResultBase=class AuditTestResultBase {constructor(name,{description}={}) {this._name=name;this._description=description||null;} get name(){return this._name;} get description(){return this._description;} get result() {return this;} get didPass() {throw WI.NotImplementedError.subclassMustOverride();} get didWarn() {throw WI.NotImplementedError.subclassMustOverride();} get didFail() {throw WI.NotImplementedError.subclassMustOverride();} get didError() {throw WI.NotImplementedError.subclassMustOverride();} get unsupported() {throw WI.NotImplementedError.subclassMustOverride();} get disabled() {return false;} get editable() {return false;} saveIdentityToCookie(cookie) {cookie["audit-"+this.constructor.TypeIdentifier+"-name"]=this._name;} toJSON() {let json={type:this.constructor.TypeIdentifier,name:this._name,};if(this._description) json.description=this._description;return json;}};WI.AuditTestCaseResult=class AuditTestCaseResult extends WI.AuditTestResultBase {constructor(name,level,{description,data,metadata,resolvedDOMNodes}={}) {super(name,{description});this._level=level;this._data=data||{};this._metadata=metadata||{};this._resolvedDOMNodes=resolvedDOMNodes||[];} static async fromPayload(payload) {if(typeof payload!=="object"||payload===null) return null;if(payload.type!==WI.AuditTestCaseResult.TypeIdentifier) return null;if(typeof payload.name!=="string"){WI.AuditManager.synthesizeError(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("name")));return null;} if(!Object.values(WI.AuditTestCaseResult.Level).includes(payload.level)){WI.AuditManager.synthesizeError(WI.UIString("\u0022%s\u0022 has an invalid \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("level")));return null;} if(typeof payload.data!=="object"||payload.data===null){if("data"in payload) WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-object \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("data")));payload.data={};}else{function checkArray(key){if(!(key in payload.data)) return;if(!Array.isArray(payload.data[key])){WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-array \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("data.%s").format(key)));payload.data[key]=[];} payload.data[key]=payload.data[key].filter((item)=>typeof item==="string");} checkArray("domNodes");checkArray("domAttributes");checkArray("errors");} if(typeof payload.metadata!=="object"||payload.metadata===null){if("metadata"in payload) WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-object \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("metadata")));payload.metadata={};}else{if(typeof payload.metadata.startTimestamp==="string") payload.metadata.startTimestamp=new Date(payload.metadata.startTimestamp);else{if("startTimestamp"in payload.metadata) WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-object \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("metadata.startTimestamp")));payload.metadata.startTimestamp=null;} if(typeof payload.metadata.asyncTimestamp==="string") payload.metadata.asyncTimestamp=new Date(payload.metadata.asyncTimestamp);else{if("asyncTimestamp"in payload.metadata) WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-object \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("metadata.asyncTimestamp")));payload.metadata.asyncTimestamp=null;} if(typeof payload.metadata.endTimestamp==="string") payload.metadata.endTimestamp=new Date(payload.metadata.endTimestamp);else{if("endTimestamp"in payload.metadata) WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-object \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("metadata.endTimestamp")));payload.metadata.endTimestamp=null;} if(typeof payload.metadata.url!=="string"){if("url"in payload.metadata) WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-object \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("metadata.url")));payload.metadata.url=null;}} let options={};if(typeof payload.description==="string") options.description=payload.description;else if("description"in payload) WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("description")));if(!isEmptyObject(payload.data)){options.data={};for(let key in payload.data){if(key==="domNodes"||key==="domAttributes"||key==="errors"){if(!payload.data[key].length) continue;} if(key==="domNodes"){if(InspectorBackend.hasDomain("DOM")&&(!payload.metadata.url||payload.metadata.url===WI.networkManager.mainFrame.url)){let documentNode=await new Promise((resolve)=>WI.domManager.requestDocument(resolve));options.resolvedDOMNodes=await Promise.all(payload.data.domNodes.map(async(domNodeString)=>{let nodeId=0;try{nodeId=await documentNode.querySelector(domNodeString);}catch{} return WI.domManager.nodeForId(nodeId);}));}} options.data[key]=payload.data[key];}} if(!isEmptyObject(payload.metadata)){options.metadata={};if(payload.metadata.startTimestamp&&!isNaN(payload.metadata.startTimestamp)) options.metadata.startTimestamp=payload.metadata.startTimestamp;if(payload.metadata.asyncTimestamp&&!isNaN(payload.metadata.asyncTimestamp)) options.metadata.asyncTimestamp=payload.metadata.asyncTimestamp;if(payload.metadata.endTimestamp&&!isNaN(payload.metadata.endTimestamp)) options.metadata.endTimestamp=payload.metadata.endTimestamp;if(payload.metadata.url) options.metadata.url=payload.metadata.url;} return new WI.AuditTestCaseResult(payload.name,payload.level,options);} get level(){return this._level;} get data(){return this._data;} get metadata(){return this._metadata;} get resolvedDOMNodes(){return this._resolvedDOMNodes;} get result() {return this;} get didPass() {return this._level===WI.AuditTestCaseResult.Level.Pass;} get didWarn() {return this._level===WI.AuditTestCaseResult.Level.Warn;} get didFail() {return this._level===WI.AuditTestCaseResult.Level.Fail;} get didError() {return this._level===WI.AuditTestCaseResult.Level.Error;} get unsupported() {return this._level===WI.AuditTestCaseResult.Level.Unsupported;} toJSON() {let json=super.toJSON();json.level=this._level;let data={};for(let key in this._data){if(key==="domNodes"||key==="domAttributes"||key==="errors"){if(!this._data[key].length) continue;} data[key]=this._data[key];} if(!isEmptyObject(data)) json.data=data;let metadata={};if(this._metadata.startTimestamp&&!isNaN(this._metadata.startTimestamp)) metadata.startTimestamp=this._metadata.startTimestamp;if(this._metadata.asyncTimestamp&&!isNaN(this._metadata.asyncTimestamp)) metadata.asyncTimestamp=this._metadata.asyncTimestamp;if(this._metadata.endTimestamp&&!isNaN(this._metadata.endTimestamp)) metadata.endTimestamp=this._metadata.endTimestamp;if(this._metadata.url) metadata.url=this._metadata.url;if(!isEmptyObject(metadata)) json.metadata=metadata;return json;}};WI.AuditTestCaseResult.TypeIdentifier="test-case-result";WI.AuditTestCaseResult.Level={Pass:"pass",Warn:"warn",Fail:"fail",Error:"error",Unsupported:"unsupported",};WI.AuditTestGroupResult=class AuditTestGroupResult extends WI.AuditTestResultBase {constructor(name,results,{description}={}) {super(name,{description});this._results=results;} static async fromPayload(payload) {if(typeof payload!=="object"||payload===null) return null;if(payload.type!==WI.AuditTestGroupResult.TypeIdentifier) return null;if(typeof payload.name!=="string"){WI.AuditManager.synthesizeError(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("name")));return null;} if(!Array.isArray(payload.results)){WI.AuditManager.synthesizeError(WI.UIString("\u0022%s\u0022 has a non-array \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("results")));return null;} let results=await Promise.all(payload.results.map(async(test)=>{let testCaseResult=await WI.AuditTestCaseResult.fromPayload(test);if(testCaseResult) return testCaseResult;let testGroupResult=await WI.AuditTestGroupResult.fromPayload(test);if(testGroupResult) return testGroupResult;return null;}));results=results.filter((result)=>!!result);if(!results.length) return null;let options={};if(typeof payload.description==="string") options.description=payload.description;else if("description"in payload) WI.AuditManager.synthesizeWarning(WI.UIString("\u0022%s\u0022 has a non-string \u0022%s\u0022 value").format(payload.name,WI.unlocalizedString("description")));return new WI.AuditTestGroupResult(payload.name,results,options);} get results(){return this._results;} get levelCounts() {let counts={};for(let level of Object.values(WI.AuditTestCaseResult.Level)) counts[level]=0;for(let result of this._results){if(result instanceof WI.AuditTestCaseResult) ++counts[result.level];else if(result instanceof WI.AuditTestGroupResult){for(let[level,count]of Object.entries(result.levelCounts)) counts[level]+=count;}} return counts;} get didPass() {return this._results.some((result)=>result.didPass);} get didWarn() {return this._results.some((result)=>result.didWarn);} get didFail() {return this._results.some((result)=>result.didFail);} get didError() {return this._results.some((result)=>result.didError);} get unsupported() {return this._results.some((result)=>result.unsupported);} toJSON() {let json=super.toJSON();json.results=this._results.map((result)=>result.toJSON());return json;}};WI.AuditTestGroupResult.TypeIdentifier="test-group-result";WI.FormatterWorkerProxy=class FormatterWorkerProxy {constructor() {this._formatterWorker=new Worker("Workers/Formatter/FormatterWorker.js");this._formatterWorker.addEventListener("message",this._handleMessage.bind(this));this._nextCallId=1;this._callbacks=new Map;} static singleton() {if(!FormatterWorkerProxy.instance) FormatterWorkerProxy.instance=new FormatterWorkerProxy;return FormatterWorkerProxy.instance;} formatJavaScript(sourceText,isModule,indentString,includeSourceMapData) {this.performAction("formatJavaScript",...arguments);} formatCSS(sourceText,indentString,includeSourceMapData) {this.performAction("formatCSS",...arguments);} formatHTML(sourceText,indentString,includeSourceMapData) {this.performAction("formatHTML",...arguments);} formatXML(sourceText,indentString,includeSourceMapData) {this.performAction("formatXML",...arguments);} performAction(actionName) {let callId=this._nextCallId++;let callback=arguments[arguments.length-1];let actionArguments=Array.prototype.slice.call(arguments,1,arguments.length-1);this._callbacks.set(callId,callback);this._postMessage({callId,actionName,actionArguments});} _postMessage() {this._formatterWorker.postMessage(...arguments);} _handleMessage(event) {let data=event.data;if(data.callId){let callback=this._callbacks.get(data.callId);this._callbacks.delete(data.callId);callback(data.result);return;} console.error("Unexpected FormatterWorker message",data);}};WI.HeapSnapshotDiffProxy=class HeapSnapshotDiffProxy extends WI.Object {constructor(snapshotDiffObjectId,snapshot1,snapshot2,totalSize,totalObjectCount,categories) {super();this._proxyObjectId=snapshotDiffObjectId;this._snapshot1=snapshot1;this._snapshot2=snapshot2;this._totalSize=totalSize;this._totalObjectCount=totalObjectCount;this._categories=Map.fromObject(categories);} static deserialize(objectId,serializedSnapshotDiff) {let{snapshot1:serializedSnapshot1,snapshot2:serializedSnapshot2,totalSize,totalObjectCount,categories}=serializedSnapshotDiff; let snapshot1=WI.HeapSnapshotProxy.deserialize(objectId,serializedSnapshot1);let snapshot2=WI.HeapSnapshotProxy.deserialize(objectId,serializedSnapshot2);return new WI.HeapSnapshotDiffProxy(objectId,snapshot1,snapshot2,totalSize,totalObjectCount,categories);} get snapshot1(){return this._snapshot1;} get snapshot2(){return this._snapshot2;} get totalSize(){return this._totalSize;} get totalObjectCount(){return this._totalObjectCount;} get categories(){return this._categories;} get invalid(){return this._snapshot1.invalid||this._snapshot2.invalid;} updateForCollectionEvent(event) {if(!event.data.affectedSnapshots.includes(this._snapshot2._identifier)) return;this.update(()=>{this.dispatchEventToListeners(WI.HeapSnapshotProxy.Event.CollectedNodes,event.data);});} allocationBucketCounts(bucketSizes,callback) {WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"allocationBucketCounts",bucketSizes,callback);} instancesWithClassName(className,callback) {WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"instancesWithClassName",className,(serializedNodes)=>{callback(serializedNodes.map(WI.HeapSnapshotNodeProxy.deserialize.bind(null,this._proxyObjectId)));});} update(callback) {WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"update",({liveSize,categories})=>{this._categories=Map.fromObject(categories);callback();});} nodeWithIdentifier(nodeIdentifier,callback) {WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"nodeWithIdentifier",nodeIdentifier,(serializedNode)=>{callback(WI.HeapSnapshotNodeProxy.deserialize(this._proxyObjectId,serializedNode));});}};WI.HeapSnapshotEdgeProxy=class HeapSnapshotEdgeProxy {constructor(objectId,fromIdentifier,toIdentifier,type,data) {this._proxyObjectId=objectId;this.fromIdentifier=fromIdentifier;this.toIdentifier=toIdentifier;this.type=type;this.data=data;this.from=null;this.to=null;} isPrivateSymbol() {if(WI.settings.engineeringShowPrivateSymbolsInHeapSnapshot.value) return false;return typeof this.data==="string"&&this.data.startsWith("PrivateSymbol");} static deserialize(objectId,serializedEdge) {let{from,to,type,data}=serializedEdge;return new WI.HeapSnapshotEdgeProxy(objectId,from,to,type,data);}};WI.HeapSnapshotEdgeProxy.EdgeType={Internal:"Internal",Property:"Property",Index:"Index",Variable:"Variable",};WI.HeapSnapshotNodeProxy=class HeapSnapshotNodeProxy {constructor(snapshotObjectId,{id,className,size,retainedSize,internal,isObjectType,gcRoot,dead,dominatorNodeIdentifier,hasChildren}) {this._proxyObjectId=snapshotObjectId;this.id=id;this.className=className;this.size=size;this.retainedSize=retainedSize;this.internal=internal;this.isObjectType=isObjectType;this.gcRoot=gcRoot;this.dead=dead;this.dominatorNodeIdentifier=dominatorNodeIdentifier;this.hasChildren=hasChildren;} static deserialize(objectId,serializedNode) {return new WI.HeapSnapshotNodeProxy(objectId,serializedNode);} shortestGCRootPath(callback) {WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"shortestGCRootPath",this.id,(serializedPath)=>{let isNode=false;let path=serializedPath.map((component)=>{isNode=!isNode;if(isNode) return WI.HeapSnapshotNodeProxy.deserialize(this._proxyObjectId,component);return WI.HeapSnapshotEdgeProxy.deserialize(this._proxyObjectId,component);});for(let i=1;i{callback(serializedNodes.map(WI.HeapSnapshotNodeProxy.deserialize.bind(null,this._proxyObjectId)));});} retainedNodes(callback) {WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"retainedNodes",this.id,({retainedNodes:serializedNodes,edges:serializedEdges})=>{let deserializedNodes=serializedNodes.map(WI.HeapSnapshotNodeProxy.deserialize.bind(null,this._proxyObjectId));let deserializedEdges=serializedEdges.map(WI.HeapSnapshotEdgeProxy.deserialize.bind(null,this._proxyObjectId));callback(deserializedNodes,deserializedEdges);});} retainers(callback) {WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"retainers",this.id,({retainers:serializedNodes,edges:serializedEdges})=>{let deserializedNodes=serializedNodes.map(WI.HeapSnapshotNodeProxy.deserialize.bind(null,this._proxyObjectId));let deserializedEdges=serializedEdges.map(WI.HeapSnapshotEdgeProxy.deserialize.bind(null,this._proxyObjectId));callback(deserializedNodes,deserializedEdges);});}};WI.HeapSnapshotProxy=class HeapSnapshotProxy extends WI.Object {constructor(snapshotObjectId,identifier,title,totalSize,totalObjectCount,liveSize,categories,imported) {super();this._proxyObjectId=snapshotObjectId;this._identifier=identifier;this._title=title;this._totalSize=totalSize;this._totalObjectCount=totalObjectCount;this._liveSize=liveSize;this._categories=Map.fromObject(categories);this._imported=imported;this._snapshotStringData=null;if(!WI.HeapSnapshotProxy.ValidSnapshotProxies) WI.HeapSnapshotProxy.ValidSnapshotProxies=[];WI.HeapSnapshotProxy.ValidSnapshotProxies.push(this);} static deserialize(objectId,serializedSnapshot) {let{identifier,title,totalSize,totalObjectCount,liveSize,categories,imported}=serializedSnapshot;return new WI.HeapSnapshotProxy(objectId,identifier,title,totalSize,totalObjectCount,liveSize,categories,imported);} static invalidateSnapshotProxies() {if(!WI.HeapSnapshotProxy.ValidSnapshotProxies) return;for(let snapshotProxy of WI.HeapSnapshotProxy.ValidSnapshotProxies) snapshotProxy._invalidate();WI.HeapSnapshotProxy.ValidSnapshotProxies=null;} get proxyObjectId(){return this._proxyObjectId;} get identifier(){return this._identifier;} get title(){return this._title;} get totalSize(){return this._totalSize;} get totalObjectCount(){return this._totalObjectCount;} get liveSize(){return this._liveSize;} get categories(){return this._categories;} get imported(){return this._imported;} get invalid(){return this._proxyObjectId===0;} get snapshotStringData() {return this._snapshotStringData;} set snapshotStringData(data) {this._snapshotStringData=data;} updateForCollectionEvent(event) {if(!event.data.affectedSnapshots.includes(this._identifier)) return;this.update(()=>{this.dispatchEventToListeners(WI.HeapSnapshotProxy.Event.CollectedNodes,event.data);});} allocationBucketCounts(bucketSizes,callback) {WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"allocationBucketCounts",bucketSizes,callback);} instancesWithClassName(className,callback) {WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"instancesWithClassName",className,(serializedNodes)=>{callback(serializedNodes.map(WI.HeapSnapshotNodeProxy.deserialize.bind(null,this._proxyObjectId)));});} update(callback) {WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"update",({liveSize,categories})=>{this._liveSize=liveSize;this._categories=Map.fromObject(categories);callback();});} nodeWithIdentifier(nodeIdentifier,callback) {WI.HeapSnapshotWorkerProxy.singleton().callMethod(this._proxyObjectId,"nodeWithIdentifier",nodeIdentifier,(serializedNode)=>{callback(WI.HeapSnapshotNodeProxy.deserialize(this._proxyObjectId,serializedNode));});} _invalidate() {this._proxyObjectId=0;this._liveSize=0;this.dispatchEventToListeners(WI.HeapSnapshotProxy.Event.Invalidated);}};WI.HeapSnapshotProxy.Event={CollectedNodes:"heap-snapshot-proxy-collected-nodes",Invalidated:"heap-snapshot-proxy-invalidated",};WI.HeapSnapshotWorkerProxy=class HeapSnapshotWorkerProxy extends WI.Object {constructor() {super();this._heapSnapshotWorker=new Worker("Workers/HeapSnapshot/HeapSnapshotWorker.js");this._heapSnapshotWorker.addEventListener("message",this._handleMessage.bind(this));this._nextCallId=1;this._callbacks=new Map;WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);} static singleton() {if(!HeapSnapshotWorkerProxy.instance) HeapSnapshotWorkerProxy.instance=new HeapSnapshotWorkerProxy;return HeapSnapshotWorkerProxy.instance;} clearSnapshots(callback) {this.performAction("clearSnapshots",callback);} createSnapshot(snapshotStringData,callback) {this.performAction("createSnapshot",...arguments);} createSnapshotDiff(objectId1,objectId2,callback) {this.performAction("createSnapshotDiff",...arguments);} createImportedSnapshot(snapshotStringData,title,callback) {const imported=true;this.performAction("createSnapshot",snapshotStringData,title,imported,callback);} performAction(actionName) {let callId=this._nextCallId++;let callback=arguments[arguments.length-1];let actionArguments=Array.prototype.slice.call(arguments,1,arguments.length-1);this._callbacks.set(callId,callback);this._postMessage({callId,actionName,actionArguments});} callMethod(objectId,methodName) {let callId=this._nextCallId++;let callback=arguments[arguments.length-1];let methodArguments=Array.prototype.slice.call(arguments,2,arguments.length-1);this._callbacks.set(callId,callback);this._postMessage({callId,objectId,methodName,methodArguments});} _mainResourceDidChange(event) {if(!event.target.isMainFrame()) return;this.clearSnapshots(()=>{WI.HeapSnapshotProxy.invalidateSnapshotProxies();});} _postMessage() {this._heapSnapshotWorker.postMessage(...arguments);} _handleMessage(event) {let data=event.data;if(data.error){this._callbacks.delete(data.callId);return;} if(data.eventName){this.dispatchEventToListeners(data.eventName,data.eventData);return;} if(data.callId){let callback=this._callbacks.get(data.callId);this._callbacks.delete(data.callId);callback(data.result);return;} console.error("Unexpected HeapSnapshotWorker message",data);}};WI.HeapSnapshotWorkerProxy.Event={Collection:"heap-snapshot-collection",};WI.View=class View extends WI.Object {constructor(element) {super();this._element=element||document.createElement("div");this._element.__view=this;this._parentView=null;this._subviews=[];this._dirty=false;this._dirtyDescendantsCount=0;this._isAttachedToRoot=false;this._layoutReason=null;this._didInitialLayout=false;} static fromElement(element) {if(!element||!(element instanceof HTMLElement)) return null;if(element.__view instanceof WI.View) return element.__view;return null;} static rootView() {if(!WI.View._rootView){ WI.View._rootView=new WI.View(document.body);WI.View._rootView._isAttachedToRoot=true;} return WI.View._rootView;} get element(){return this._element;} get layoutPending(){return this._dirty;} get parentView(){return this._parentView;} get subviews(){return this._subviews;} get isAttached(){return this._isAttachedToRoot;} isDescendantOf(view) {let parentView=this._parentView;while(parentView){if(parentView===view) return true;parentView=parentView.parentView;} return false;} addSubview(view) {this.insertSubviewBefore(view,null);} insertSubviewBefore(view,referenceView) {if(this._subviews.includes(view)){return;} const beforeIndex=referenceView?this._subviews.indexOf(referenceView):this._subviews.length;if(beforeIndex===-1){return;} this._subviews.insertAtIndex(view,beforeIndex);if(!view.element.parentNode) this._element.insertBefore(view.element,referenceView?referenceView.element:null);view._didMoveToParent(this);} removeSubview(view) {let index=this._subviews.lastIndexOf(view);if(index===-1){return;} view._didMoveToParent(null);this._subviews.splice(index,1);view.element.remove();} removeAllSubviews() {for(let subview of this._subviews) subview._didMoveToParent(null);this._subviews=[];this._element.removeChildren();} replaceSubview(oldView,newView) {if(oldView===newView) return;this.insertSubviewBefore(newView,oldView);this.removeSubview(oldView);} updateLayout(layoutReason) {this._setLayoutReason(layoutReason);this._layoutSubtree();this._parentView?.didLayoutSubtree();} updateLayoutIfNeeded(layoutReason) {if(!this._dirty&&this._didInitialLayout) return;this.updateLayout(layoutReason);} needsLayout(layoutReason) {this._setLayoutReason(layoutReason);WI.View._scheduleLayoutForView(this);} get layoutReason(){return this._layoutReason;} get didInitialLayout(){return this._didInitialLayout;} attached() {} detached() {} initialLayout() { } layout() {} didLayoutSubtree() {} sizeDidChange() {} _setDirty(dirty) {if(this._dirty===dirty) return;this._dirty=dirty;for(let parentView=this.parentView;parentView;parentView=parentView.parentView){parentView._dirtyDescendantsCount+=this._dirty?1:-1;}} _didMoveToParent(parentView) {if(this._parentView===parentView) return;let dirtyDescendantsCount=this._dirtyDescendantsCount;if(this._dirty) ++dirtyDescendantsCount;if(dirtyDescendantsCount){for(let view=this.parentView;view;view=view.parentView){view._dirtyDescendantsCount-=dirtyDescendantsCount;}} this._parentView=parentView;let isAttachedToRoot=this.isDescendantOf(WI.View._rootView);let views=[this];for(let i=0;i{if(this._element) this._element.style.outline=this._layoutFlashingPreviousOutline;this._layoutFlashingTimeout=undefined;this._layoutFlashingPreviousOutline=null;},500);} static _scheduleLayoutForView(view) {view._setDirty(true);if(!view._isAttachedToRoot) return;if(WI.View._scheduledLayoutUpdateIdentifier) return;WI.View._scheduledLayoutUpdateIdentifier=requestAnimationFrame(WI.View._visitViewTreeForLayout);} static _visitViewTreeForLayout() {WI.View._scheduledLayoutUpdateIdentifier=undefined;let views=[WI.View._rootView];let cleanViews=new Set;for(let i=0;i{a=itemForRepresentedObject(a);b=itemForRepresentedObject(b);if(!a||!b) return 0;let getLevel=(item)=>{let level=0;while(item=item.parent) level++;return level;};let compareSiblings=(s,t)=>{return s.parent.children.indexOf(s)-s.parent.children.indexOf(t);};if(a.parent===b.parent) return compareSiblings(a,b);let aLevel=getLevel(a);let bLevel=getLevel(b);while(aLevel>bLevel){if(a.parent===b) return 1;a=a.parent;aLevel--;} while(bLevel>aLevel){if(b.parent===a) return-1;b=b.parent;bLevel--;} while(a.parent!==b.parent){a=a.parent;b=b.parent;} return compareSiblings(a,b);};} static createListComparator(indexForRepresentedObject) {return(a,b)=>{return indexForRepresentedObject(a)-indexForRepresentedObject(b);};} get delegate(){return this._delegate;} get lastSelectedItem(){return this._lastSelectedItem;} get selectedItems(){return this._selectedItems;} get allowsEmptySelection(){return this._allowsEmptySelection;} set allowsEmptySelection(flag){this._allowsEmptySelection=flag;} get allowsMultipleSelection() {return this._allowsMultipleSelection;} set allowsMultipleSelection(flag) {if(this._allowsMultipleSelection===flag) return;this._allowsMultipleSelection=flag;if(this._allowsMultipleSelection) return;if(this._selectedItems.size>1) this._updateSelectedItems(new Set([this._lastSelectedItem]));} hasSelectedItem(item) {return this._selectedItems.has(item);} selectItem(item,extendSelection=false) {if(!this._allowsMultipleSelection) extendSelection=false;this._lastSelectedItem=item;this._shiftAnchorItem=null;let newItems=new Set(extendSelection?this._selectedItems:null);newItems.add(item);this._updateSelectedItems(newItems);} selectItems(items) {if(!this._allowsMultipleSelection) return;if(!this._lastSelectedItem||!items.has(this._lastSelectedItem)) this._lastSelectedItem=items.lastValue;if(!this._shiftAnchorItem||!items.has(this._shiftAnchorItem)) this._shiftAnchorItem=this._lastSelectedItem;this._updateSelectedItems(items);} deselectItem(item) {if(!this.hasSelectedItem(item)) return;if(!this._allowsEmptySelection&&this._selectedItems.size===1) return;let newItems=new Set(this._selectedItems);newItems.delete(item);if(this._lastSelectedItem===item){this._lastSelectedItem=null;if(newItems.size){const operation=WI.SelectionController.Operation.Extend;let previous=item;let next=item;while(!this._lastSelectedItem&&previous&&next){previous=this._previousSelectableItem(previous,operation);if(this.hasSelectedItem(previous)){this._lastSelectedItem=previous;break;} next=this._nextSelectableItem(next,operation);if(this.hasSelectedItem(next)){this._lastSelectedItem=next;break;}}}} if(this._shiftAnchorItem===item) this._shiftAnchorItem=null;this._updateSelectedItems(newItems);} selectAll() {if(!this._allowsMultipleSelection) return;const operation=WI.SelectionController.Operation.Extend;let newItems=new Set;this._addRange(newItems,this._firstSelectableItem(operation),this._lastSelectableItem(operation));this.selectItems(newItems);} deselectAll() {this._deselectAllAndSelect(null);} removeSelectedItems() {if(!this._selectedItems.size) return;let operation=this._allowsMultipleSelection?WI.SelectionController.Operation.Extend:WI.SelectionController.Operation.Direct;let orderedSelection=Array.from(this._selectedItems).sort(this._comparator);let firstSelectedItem=orderedSelection[0];let itemToSelect=this._previousSelectableItem(firstSelectedItem,operation);if(!itemToSelect){ itemToSelect=firstSelectedItem;while(itemToSelect&&this.hasSelectedItem(itemToSelect)) itemToSelect=this._nextSelectableItem(itemToSelect,operation);if(!itemToSelect||this.hasSelectedItem(itemToSelect)){ itemToSelect=this._nextSelectableItem(orderedSelection.lastValue,operation);}} this._deselectAllAndSelect(itemToSelect);} reset() {this._lastSelectedItem=null;this._shiftAnchorItem=null;this._selectedItems.clear();} didRemoveItems(items) {if(!items.size||!this._selectedItems.size) return;this._updateSelectedItems(this._selectedItems.difference(items));} handleKeyDown(event) {if(event.key==="a"&&event.commandOrControlKey){this.selectAll();return true;} if(event.metaKey||event.ctrlKey) return false;if(event.keyIdentifier==="Up"||event.keyIdentifier==="Down"){this._selectItemsFromArrowKey(event.keyIdentifier==="Up",event.shiftKey);event.preventDefault();event.stopPropagation();return true;} return false;} handleItemMouseDown(item,event) {if(event.button!==0||event.ctrlKey) return; if(event.commandOrControlKey){if(this.hasSelectedItem(item)) this.deselectItem(item);else this.selectItem(item,this._allowsMultipleSelection);return;} let shiftExtendSelection=this._allowsMultipleSelection&&event.shiftKey;if(!shiftExtendSelection){this.selectItem(item);return;} let newItems=new Set(this._selectedItems); if(!newItems.size){this._lastSelectedItem=item;this._shiftAnchorItem=this._firstSelectableItem(WI.SelectionController.Operation.Extend);this._addRange(newItems,this._shiftAnchorItem,this._lastSelectedItem);this._updateSelectedItems(newItems);return;} if(!this._shiftAnchorItem) this._shiftAnchorItem=this._lastSelectedItem; let sortItemPair=(a,b)=>{return[a,b].sort(this._comparator);};if(this._shiftAnchorItem!==this._lastSelectedItem){let[startItem,endItem]=sortItemPair(this._shiftAnchorItem,this._lastSelectedItem);this._deleteRange(newItems,startItem,endItem);} let[startItem,endItem]=sortItemPair(this._shiftAnchorItem,item);this._addRange(newItems,startItem,endItem);this._lastSelectedItem=item;this._updateSelectedItems(newItems);} _deselectAllAndSelect(item) {if(!this._selectedItems.size&&!item) return;if(this._selectedItems.size===1&&this.hasSelectedItem(item)) return;this._lastSelectedItem=item;this._shiftAnchorItem=null;let newItems=new Set;if(item) newItems.add(item);this._updateSelectedItems(newItems);} _selectItemsFromArrowKey(goingUp,shiftKey) {let extendSelection=shiftKey&&this._allowsMultipleSelection;let operation=extendSelection?WI.SelectionController.Operation.Extend:WI.SelectionController.Operation.Direct;if(!this._selectedItems.size){this.selectItem(goingUp?this._lastSelectableItem(operation):this._firstSelectableItem(operation));return;} let item=goingUp?this._previousSelectableItem(this._lastSelectedItem,operation):this._nextSelectableItem(this._lastSelectedItem,operation);if(!item) return;if(!extendSelection||!this.hasSelectedItem(item)){this.selectItem(item,extendSelection);return;} let priorItem=goingUp?this._nextSelectableItem(this._lastSelectedItem,operation):this._previousSelectableItem(this._lastSelectedItem,operation);if(!priorItem||!this.hasSelectedItem(priorItem)){this.deselectItem(this._lastSelectedItem);return;} while(item){if(!this.hasSelectedItem(item)){this.selectItem(item,extendSelection);break;} this._lastSelectedItem=item;item=goingUp?this._previousSelectableItem(item,operation):this._nextSelectableItem(item,operation);}} _firstSelectableItem(operation) {return this._delegate.selectionControllerFirstSelectableItem(this,operation);} _lastSelectableItem(operation) {return this._delegate.selectionControllerLastSelectableItem(this,operation);} _previousSelectableItem(item,operation) {return this._delegate.selectionControllerPreviousSelectableItem(this,item,operation);} _nextSelectableItem(item,operation) {return this._delegate.selectionControllerNextSelectableItem(this,item,operation);} _updateSelectedItems(items) {let oldSelectedItems=this._selectedItems;this._selectedItems=items;if(this._suppressSelectionDidChange||!this._delegate.selectionControllerSelectionDidChange) return;let deselectedItems=oldSelectedItems.difference(items);let selectedItems=items.difference(oldSelectedItems);if(deselectedItems.size||selectedItems.size) this._delegate.selectionControllerSelectionDidChange(this,deselectedItems,selectedItems);} _addRange(items,firstItem,lastItem) {const operation=WI.SelectionController.Operation.Extend;let current=firstItem;while(current){items.add(current);if(current===lastItem) break;current=this._nextSelectableItem(current,operation);}} _deleteRange(items,firstItem,lastItem) {const operation=WI.SelectionController.Operation.Extend;let current=firstItem;while(current){items.delete(current);if(current===lastItem) break;current=this._nextSelectableItem(current,operation);}}};WI.SelectionController.Operation={Direct:Symbol("selection-operation-direct"),Extend:Symbol("selection-operation-extend"),};WI.ConsoleCommandView=class ConsoleCommandView {constructor(commandText,{classNames,handleClick}={}) {this._commandText=commandText;this._classNames=classNames||null;this._handleClick=handleClick||null;} render() {this._element=document.createElement("div");this._element.classList.add("console-user-command");this._element.dir="ltr";this._element.setAttribute("data-labelprefix",WI.UIString("Input: "));if(this._classNames) this._element.classList.add(...this._classNames);this._formattedCommandElement=this._element.appendChild(document.createElement("span"));this._formattedCommandElement.classList.add("console-message-body");this._formattedCommandElement.textContent=this._commandText;if(this._handleClick) this._formattedCommandElement.addEventListener("click",this._handleClick); this._element.__commandView=this;} get element() {return this._element;} get commandText() {return this._commandText;} toClipboardString(isPrefixOptional) {return(isPrefixOptional?"":"> ")+this._commandText.removeWordBreakCharacters();}};WI.ConsoleMessageView=class ConsoleMessageView extends WI.Object {constructor(message) {super();this._message=message;this._expandable=false;this._repeatCount=message._repeatCount||0;this._timestamp=message._timestamp||null;this._extraParameters=message.parameters;this._timestampElement=null;} render() {this._element=document.createElement("div");this._element.classList.add("console-message");this._element.dir="ltr"; this._element.__message=this._message;this._element.__messageView=this;if(this._message.type===WI.ConsoleMessage.MessageType.Result){this._element.classList.add("console-user-command-result");this._element.setAttribute("data-labelprefix",WI.UIString("Output: "));}else if(this._message.type===WI.ConsoleMessage.MessageType.StartGroup||this._message.type===WI.ConsoleMessage.MessageType.StartGroupCollapsed) this._element.classList.add("console-group-title");switch(this._message.level){case WI.ConsoleMessage.MessageLevel.Log:this._element.classList.add("console-log-level");this._element.setAttribute("data-labelprefix",WI.UIString("Log: "));break;case WI.ConsoleMessage.MessageLevel.Info:this._element.classList.add("console-info-level");this._element.setAttribute("data-labelprefix",WI.UIString("Info: "));break;case WI.ConsoleMessage.MessageLevel.Debug:this._element.classList.add("console-debug-level");this._element.setAttribute("data-labelprefix",WI.UIString("Debug: "));break;case WI.ConsoleMessage.MessageLevel.Warning:this._element.classList.add("console-warning-level");this._element.setAttribute("data-labelprefix",WI.UIString("Warning: "));break;case WI.ConsoleMessage.MessageLevel.Error:this._element.classList.add("console-error-level");this._element.setAttribute("data-labelprefix",WI.UIString("Error: "));break;} this._appendLocationLink();this._messageBodyElement=this._element.appendChild(document.createElement("span"));this._messageBodyElement.classList.add("console-top-level-message","console-message-body");this._appendMessageTextAndArguments(this._messageBodyElement);this._appendSavedResultIndex();this._appendExtraParameters();this._appendStackTrace();this._renderRepeatCount();this.renderTimestamp();if(this._message.type===WI.ConsoleMessage.MessageType.Dir) this.expand();else if(this._message.type===WI.ConsoleMessage.MessageType.Image){this._element.classList.add("console-image");this._element.addEventListener("contextmenu",this._handleContextMenu.bind(this));} WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BlackboxChanged,this._handleDebuggerBlackboxChanged,this);} get element() {return this._element;} get message() {return this._message;} get repeatCount() {return this._repeatCount;} set repeatCount(count) {if(this._repeatCount===count) return;this._repeatCount=count;if(this._element) this._renderRepeatCount();} _renderRepeatCount() {let count=this._repeatCount;if(count<=1){if(this._repeatCountElement){this._repeatCountElement.remove();this._repeatCountElement=null;} return;} if(!this._repeatCountElement){this._repeatCountElement=document.createElement("span");this._repeatCountElement.classList.add("repeat-count");this._element.insertBefore(this._repeatCountElement,this._element.firstChild);} this._repeatCountElement.textContent=Number.abbreviate(count);} get timestamp() {return this._timestamp;} set timestamp(timestamp) {this._timestamp=timestamp;if(this._element){this.renderTimestamp();}} renderTimestamp() {if(!this._timestamp){this._timestampElement?.remove();this._timestampElement=null;return;} if(!this._timestampElement){this._timestampElement=document.createElement("span");this._timestampElement.classList.add("timestamp");this._element.insertBefore(this._timestampElement,this._element.firstChild);} let date=new Date(this._timestamp*1000);let timeFormat=new Intl.DateTimeFormat("default",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,hour12:false});this._timestampElement.textContent=timeFormat.format(date);} get expandable() {if(this._expandable) return true;if(this._objectTree) return true;return false;} expand() {if(this._expandable) this._element.classList.add("expanded");if(this._objectTree&&this._message.type!==WI.ConsoleMessage.MessageType.Trace){if(!this._extraParameters||this._extraParameters.length<=1) this._objectTree.expand();}} collapse() {if(this._expandable) this._element.classList.remove("expanded");if(this._objectTree){if(!this._extraParameters||this._extraParameters.length<=1) this._objectTree.collapse();}} toggle() {if(this._element.classList.contains("expanded")) this.collapse();else this.expand();} toClipboardString(isPrefixOptional) {let clipboardString=this._messageBodyElement.innerText.removeWordBreakCharacters();if(this._message.savedResultIndex){let escapedSavedResultPrefix=WI.RuntimeManager.preferredSavedResultPrefix().escapeForRegExp();clipboardString=clipboardString.replace(new RegExp(`\\s*=\\s*${escapedSavedResultPrefix}\\d+\\s*$`),"");} let hasStackTrace=this._shouldShowStackTrace();if(!hasStackTrace){let repeatString=this.repeatCount>1?"x"+this.repeatCount:"";let urlLine="";if(this._message.url){let components=[WI.displayNameForURL(this._message.url),"line "+this._message.line];if(repeatString) components.push(repeatString);urlLine=" ("+components.join(", ")+")";}else if(repeatString) urlLine=" ("+repeatString+")";if(urlLine){let lines=clipboardString.split("\n");lines[0]+=urlLine;clipboardString=lines.join("\n");}} if(this._extraElementsList) clipboardString+="\n"+this._extraElementsList.innerText.removeWordBreakCharacters().trim();if(hasStackTrace){this._message.stackTrace.callFrames.forEach(function(frame){clipboardString+="\n\t"+frame.displayName;if(frame.sourceCodeLocation) clipboardString+=" ("+frame.sourceCodeLocation.originalLocationString()+")";});} if(!isPrefixOptional||this._enforcesClipboardPrefixString()) return this._clipboardPrefixString()+clipboardString;return clipboardString;} clearSessionState() {for(let node of this._messageBodyElement.querySelectorAll(".console-saved-variable")) node.remove();if(this._objectTree instanceof WI.ObjectTreeView) this._objectTree.resetPropertyPath();WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.BlackboxChanged,this._handleDebuggerBlackboxChanged,this);} _appendMessageTextAndArguments(element) {if(this._message.source===WI.ConsoleMessage.MessageSource.ConsoleAPI){switch(this._message.type){case WI.ConsoleMessage.MessageType.Trace:var args=[WI.UIString("Trace")];if(this._message.parameters){if(this._message.parameters[0].type==="string"){var prefixedFormatString=WI.UIString("Trace: %s").format(this._message.parameters[0].description);args=[prefixedFormatString].concat(this._message.parameters.slice(1));}else args.pushAll(this._message.parameters);} this._appendFormattedArguments(element,args);return;case WI.ConsoleMessage.MessageType.Assert:var args=[WI.UIString("Assertion Failed")];if(this._message.parameters){if(this._message.parameters[0].type==="string"){var prefixedFormatString=WI.UIString("Assertion Failed: %s").format(this._message.parameters[0].description);args=[prefixedFormatString].concat(this._message.parameters.slice(1));}else args.pushAll(this._message.parameters);} this._appendFormattedArguments(element,args);return;case WI.ConsoleMessage.MessageType.Dir:var obj=this._message.parameters?this._message.parameters[0]:undefined;this._appendFormattedArguments(element,["%O",obj]);return;case WI.ConsoleMessage.MessageType.Table:var args=this._message.parameters;element.appendChild(this._formatParameterAsTable(args));this._extraParameters=null;return;case WI.ConsoleMessage.MessageType.StartGroup:case WI.ConsoleMessage.MessageType.StartGroupCollapsed:var args=this._message.parameters||[this._message.messageText||WI.UIString("Group")];this._formatWithSubstitutionString(args,element);this._extraParameters=null;return;case WI.ConsoleMessage.MessageType.Timing:{let args=[this._message.messageText];if(this._extraParameters) args.pushAll(this._extraParameters);this._appendFormattedArguments(element,args);return;} case WI.ConsoleMessage.MessageType.Image:{if(this._message.level===WI.ConsoleMessage.MessageLevel.Log){let divider=null;if(this._message.parameters.length>1){this._appendFormattedArguments(element,this._message.parameters.slice(1));divider=element.appendChild(document.createElement("hr"));} let target=this._message.parameters[0];if(target==="Viewport") target=WI.UIString("Viewport");this._appendFormattedArguments(element,[target]);if(this._message.messageText){let img=document.createElement("img");img.classList.add("show-grid");img.src=this._message.messageText;img.setAttribute("filename",WI.FileUtilities.screenshotString()+".png");img.addEventListener("load",(event)=>{if(img.width>=img.height) img.width=img.width/window.devicePixelRatio;else img.height=img.height/window.devicePixelRatio;element.appendChild(img);});img.addEventListener("error",(event)=>{this._element.setAttribute("data-labelprefix",WI.UIString("Error: "));this._element.classList.add("console-error-level");this._element.classList.remove("console-log-level");if(divider){while(divider.nextSibling) divider.nextSibling.remove();}else element.removeChildren();let args=[WI.UIString("Could not capture screenshot"),this._message.messageText];if(this._extraParameters) args.pushAll(this._extraParameters);this._appendFormattedArguments(element,args);});} return;} if(this._message.level===WI.ConsoleMessage.MessageLevel.Error){let args=[];if(this._message.messageText==="Could not capture screenshot") args.push(WI.UIString("Could not capture screenshot"));else args.push(this._message.messageText);if(this._extraParameters) args.pushAll(this._extraParameters);this._appendFormattedArguments(element,args);return;} break;}}} var args=this._message.parameters||[this._message.messageText];this._appendFormattedArguments(element,args);} _appendSavedResultIndex(element) {let savedResultIndex=this._message.savedResultIndex;if(!savedResultIndex) return;var savedVariableElement=document.createElement("span");savedVariableElement.classList.add("console-saved-variable"); function updateSavedVariableText(){savedVariableElement.textContent=" = "+WI.RuntimeManager.preferredSavedResultPrefix()+savedResultIndex;} WI.settings.consoleSavedResultAlias.addEventListener(WI.Setting.Event.Changed,updateSavedVariableText,savedVariableElement);updateSavedVariableText();if(this._objectTree) this._objectTree.appendTitleSuffix(savedVariableElement);else this._messageBodyElement.appendChild(savedVariableElement);} _appendLocationLink() {if(this._message.source===WI.ConsoleMessage.MessageSource.Network){if(this._message.url){var anchor=WI.linkifyURLAsNode(this._message.url,this._message.url,"console-message-url");anchor.classList.add("console-message-location");this._element.appendChild(anchor);} return;} var callFrame;let firstNonNativeNonAnonymousNotBlackboxedCallFrame=this._message.stackTrace?.firstNonNativeNonAnonymousNotBlackboxedCallFrame;if(firstNonNativeNonAnonymousNotBlackboxedCallFrame){callFrame=firstNonNativeNonAnonymousNotBlackboxedCallFrame;}else if(this._message.url&&!this._shouldHideURL(this._message.url)){callFrame=WI.CallFrame.fromPayload(this._message.target,{functionName:"",url:this._message.url,lineNumber:this._message.line,columnNumber:this._message.column});} if(callFrame&&(!callFrame.isConsoleEvaluation||WI.settings.debugShowConsoleEvaluations.value)){let existingCallFrameView=this._callFrameView;this._callFrameView=new WI.CallFrameView(callFrame,{showFunctionName:!!callFrame.functionName});this._callFrameView.classList.add("console-message-location");if(existingCallFrameView) this._element.replaceChild(this._callFrameView,existingCallFrameView);else this._element.appendChild(this._callFrameView);return;} if(this._message.parameters&&this._message.parameters.length===1){var parameter=this._createRemoteObjectIfNeeded(this._message.parameters[0]);parameter.findFunctionSourceCodeLocation().then((result)=>{if(result===WI.RemoteObject.SourceCodeLocationPromise.NoSourceFound||result===WI.RemoteObject.SourceCodeLocationPromise.MissingObjectId) return;let link=WI.linkifySourceCode(result.sourceCode,new WI.SourceCodePosition(result.lineNumber,result.columnNumber),{className:"console-message-url",ignoreNetworkTab:true,ignoreSearchTab:true,});link.classList.add("console-message-location");if(this._element.hasChildNodes()) this._element.insertBefore(link,this._element.firstChild);else this._element.appendChild(link);});}} _appendExtraParameters() {if(!this._extraParameters||!this._extraParameters.length) return;this._makeExpandable();if(this._extraParameters.length>1) this.expand();this._extraElementsList=this._element.appendChild(document.createElement("ol"));this._extraElementsList.classList.add("console-message-extra-parameters-container");for(var parameter of this._extraParameters){var listItemElement=this._extraElementsList.appendChild(document.createElement("li"));const forceObjectFormat=parameter.type==="object"&&(parameter.subtype!=="null"&¶meter.subtype!=="regexp"&¶meter.subtype!=="node"&¶meter.subtype!=="error");listItemElement.classList.add("console-message-extra-parameter");listItemElement.appendChild(this._formatParameter(parameter,forceObjectFormat));}} _appendStackTrace() {if(!this._shouldShowStackTrace()) return;this._makeExpandable();if(this._message.type===WI.ConsoleMessage.MessageType.Trace&&WI.settings.consoleAutoExpandTrace.value) this.expand();this._stackTraceElement=this._element.appendChild(document.createElement("div"));this._stackTraceElement.classList.add("console-message-body","console-message-stack-trace-container");let callFramesElement=new WI.StackTraceView(this._message.stackTrace);this._stackTraceElement.appendChild(callFramesElement);} _createRemoteObjectIfNeeded(parameter) {if(parameter instanceof WI.RemoteObject) return parameter;if(typeof parameter==="object") return WI.RemoteObject.fromPayload(parameter,this._message.target);return WI.RemoteObject.fromPrimitiveValue(parameter);} _appendFormattedArguments(element,parameters) {if(!parameters.length) return;for(let i=0;i .console-message-body > img");if(!image) return;let contextMenu=WI.ContextMenu.createFromEvent(event);if(WI.FileUtilities.canSave(WI.FileUtilities.SaveMode.SingleFile)){contextMenu.appendItem(WI.UIString("Save Image"),()=>{const forceSaveAs=true;WI.FileUtilities.save(WI.FileUtilities.SaveMode.SingleFile,{content:parseDataURL(this._message.messageText).data,base64Encoded:true,suggestedName:image.getAttribute("filename"),},forceSaveAs);});} contextMenu.appendSeparator();} _handleDebuggerBlackboxChanged(event) {if(this._callFrameView) this._appendLocationLink();}};WI.ContentBrowser=class ContentBrowser extends WI.View {constructor(element,delegate,{hideBackForwardButtons,disableBackForwardNavigation,disableFindBanner,flexibleNavigationItem,contentViewNavigationItemGroup}={}) {super(element);this.element.classList.add("content-browser");this._navigationBar=new WI.NavigationBar;this.addSubview(this._navigationBar);this._contentViewContainer=new WI.ContentViewContainer({disableBackForwardNavigation});this._contentViewContainer.addEventListener(WI.ContentViewContainer.Event.CurrentContentViewDidChange,this._currentContentViewDidChange,this);this.addSubview(this._contentViewContainer);if(!hideBackForwardButtons){let isRTL=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL;let goBack=()=>{this.goBack();};let goForward=()=>{this.goForward();};let backShortcutKey=isRTL?WI.KeyboardShortcut.Key.Right:WI.KeyboardShortcut.Key.Left;let forwardShortcutKey=isRTL?WI.KeyboardShortcut.Key.Left:WI.KeyboardShortcut.Key.Right;this._backKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Control,backShortcutKey,goBack,this.element);this._forwardKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Control,forwardShortcutKey,goForward,this.element);let leftArrow="Images/BackForwardArrows.svg#left-arrow-mask";let rightArrow="Images/BackForwardArrows.svg#right-arrow-mask";let backButtonImage=isRTL?rightArrow:leftArrow;let forwardButtonImage=isRTL?leftArrow:rightArrow;this._backNavigationItem=new WI.ButtonNavigationItem("back",WI.UIString("Back (%s)").format(this._backKeyboardShortcut.displayName),backButtonImage,8,13);this._backNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,goBack,this);this._backNavigationItem.enabled=false;this._forwardNavigationItem=new WI.ButtonNavigationItem("forward",WI.UIString("Forward (%s)").format(this._forwardKeyboardShortcut.displayName),forwardButtonImage,8,13);this._forwardNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,goForward,this);this._forwardNavigationItem.enabled=false;let navigationButtonsGroup=new WI.GroupNavigationItem([this._backNavigationItem,this._forwardNavigationItem]);this._navigationBar.addNavigationItem(navigationButtonsGroup);} if(!disableFindBanner){this._findBanner=new WI.FindBanner(this);this._findBanner.addEventListener(WI.FindBanner.Event.DidShow,this._findBannerDidShow,this);this._findBanner.addEventListener(WI.FindBanner.Event.DidHide,this._findBannerDidHide,this);} this._hierarchicalPathNavigationItem=new WI.HierarchicalPathNavigationItem;this._hierarchicalPathNavigationItem.addEventListener(WI.HierarchicalPathNavigationItem.Event.PathComponentWasSelected,this._hierarchicalPathComponentWasSelected,this);this._navigationBar.addNavigationItem(this._hierarchicalPathNavigationItem);this._contentViewSelectionPathNavigationItem=new WI.HierarchicalPathNavigationItem;this._flexibleNavigationItem=flexibleNavigationItem||new WI.FlexibleSpaceNavigationItem;this._navigationBar.addNavigationItem(this._flexibleNavigationItem);this._currentContentViewNavigationItemsGroup=contentViewNavigationItemGroup||null;WI.ContentView.addEventListener(WI.ContentView.Event.SelectionPathComponentsDidChange,this._contentViewSelectionPathComponentDidChange,this);WI.ContentView.addEventListener(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange,this._contentViewSupplementalRepresentedObjectsDidChange,this);WI.ContentView.addEventListener(WI.ContentView.Event.NumberOfSearchResultsDidChange,this._contentViewNumberOfSearchResultsDidChange,this);WI.ContentView.addEventListener(WI.ContentView.Event.NavigationItemsDidChange,this._contentViewNavigationItemsDidChange,this);this._delegate=delegate||null;this._currentContentViewNavigationItems=[];this._dispatchCurrentRepresentedObjectsDidChangeDebouncer=new Debouncer(()=>{this.dispatchEventToListeners(WI.ContentBrowser.Event.CurrentRepresentedObjectsDidChange);});} get navigationBar() {return this._navigationBar;} get contentViewContainer() {return this._contentViewContainer;} get delegate() {return this._delegate;} set delegate(newDelegate) {this._delegate=newDelegate||null;} get currentContentView() {return this._contentViewContainer.currentContentView;} get currentRepresentedObjects() {var representedObjects=[];var lastComponent=this._hierarchicalPathNavigationItem.lastComponent;if(lastComponent&&lastComponent.representedObject) representedObjects.push(lastComponent.representedObject);lastComponent=this._contentViewSelectionPathNavigationItem.lastComponent;if(lastComponent&&lastComponent.representedObject) representedObjects.push(lastComponent.representedObject);var currentContentView=this.currentContentView;if(currentContentView){var supplementalRepresentedObjects=currentContentView.supplementalRepresentedObjects;if(supplementalRepresentedObjects&&supplementalRepresentedObjects.length) representedObjects.pushAll(supplementalRepresentedObjects);} return representedObjects;} showContentViewForRepresentedObject(representedObject,cookie,extraArguments) {var contentView=this.contentViewForRepresentedObject(representedObject,false,extraArguments);return this._contentViewContainer.showContentView(contentView,cookie);} showContentView(contentView,cookie) {return this._contentViewContainer.showContentView(contentView,cookie);} contentViewForRepresentedObject(representedObject,onlyExisting,extraArguments) {return this._contentViewContainer.contentViewForRepresentedObject(representedObject,onlyExisting,extraArguments);} updateHierarchicalPathForCurrentContentView() {var currentContentView=this.currentContentView;this._updateHierarchicalPathNavigationItem(currentContentView?currentContentView.representedObject:null);} canGoBack() {var currentContentView=this.currentContentView;if(currentContentView&¤tContentView.canGoBack()) return true;return this._contentViewContainer.canGoBack();} canGoForward() {var currentContentView=this.currentContentView;if(currentContentView&¤tContentView.canGoForward()) return true;return this._contentViewContainer.canGoForward();} goBack() {var currentContentView=this.currentContentView;if(currentContentView&¤tContentView.canGoBack()){currentContentView.goBack();this._updateBackForwardButtons();return;} this._contentViewContainer.goBack();} goForward() {var currentContentView=this.currentContentView;if(currentContentView&¤tContentView.canGoForward()){currentContentView.goForward();this._updateBackForwardButtons();return;} this._contentViewContainer.goForward();} showFindBanner() {if(!this._findBanner) return;var currentContentView=this.currentContentView;if(!currentContentView||!currentContentView.supportsSearch) return;if(currentContentView.supportsCustomFindBanner){currentContentView.showCustomFindBanner();return;} this._findBanner.show();} attached() {super.attached();this._updateContentViewSelectionPathNavigationItem(this.currentContentView);this.updateHierarchicalPathForCurrentContentView();} handlePopulateFindShortcut() {let currentContentView=this.currentContentView;if(!currentContentView?.supportsSearch) return;if(!WI.updateFindString(currentContentView.searchQueryWithSelection())) return;this._findBanner.searchQuery=WI.findString;currentContentView.performSearch(this._findBanner.searchQuery);} async handleFindNextShortcut() {if(!this._findBanner.showing&&this._findBanner.searchQuery!==WI.findString){let searchQuery=WI.findString;this._findBanner.searchQuery=searchQuery;let currentContentView=this.currentContentView;if(currentContentView?.supportsSearch){currentContentView.performSearch(this._findBanner.searchQuery);await currentContentView.awaitEvent(WI.ContentView.Event.NumberOfSearchResultsDidChange,this);if(this._findBanner.searchQuery!==searchQuery||this.currentContentView!==currentContentView) return;}} this.findBannerRevealNextResult(this._findBanner);} async handleFindPreviousShortcut() {if(!this._findBanner.showing&&this._findBanner.searchQuery!==WI.findString){let searchQuery=WI.findString;this._findBanner.searchQuery=searchQuery;let currentContentView=this.currentContentView;if(currentContentView?.supportsSearch){currentContentView.performSearch(this._findBanner.searchQuery);await currentContentView.awaitEvent(WI.ContentView.Event.NumberOfSearchResultsDidChange,this);if(this._findBanner.searchQuery!==searchQuery||this.currentContentView!==currentContentView) return;}} this.findBannerRevealPreviousResult(this._findBanner);} findBannerPerformSearch(findBanner,query) {let currentContentView=this.currentContentView;if(!currentContentView||!currentContentView.supportsSearch) return;currentContentView.performSearch(query);} findBannerSearchCleared(findBanner) {let currentContentView=this.currentContentView;if(!currentContentView||!currentContentView.supportsSearch) return;currentContentView.searchCleared();} findBannerRevealPreviousResult(findBanner) {let currentContentView=this.currentContentView;if(!currentContentView||!currentContentView.supportsSearch) return;currentContentView.revealPreviousSearchResult(!findBanner.showing);} findBannerRevealNextResult(findBanner) {let currentContentView=this.currentContentView;if(!currentContentView||!currentContentView.supportsSearch) return;currentContentView.revealNextSearchResult(!findBanner.showing);} _findBannerDidShow(event) {var currentContentView=this.currentContentView;if(!currentContentView||!currentContentView.supportsSearch) return;currentContentView.automaticallyRevealFirstSearchResult=true;if(this._findBanner.searchQuery!=="") currentContentView.performSearch(this._findBanner.searchQuery);} _findBannerDidHide(event) {var currentContentView=this.currentContentView;if(!currentContentView||!currentContentView.supportsSearch) return;currentContentView.automaticallyRevealFirstSearchResult=false;currentContentView.searchHidden();} _contentViewNumberOfSearchResultsDidChange(event) {if(!this._findBanner) return;if(event.target!==this.currentContentView) return;this._findBanner.numberOfResults=this.currentContentView.numberOfSearchResults;} _updateHierarchicalPathNavigationItem(representedObject) {if(!this.delegate||typeof this.delegate.contentBrowserTreeElementForRepresentedObject!=="function") return;var treeElement=representedObject?this.delegate.contentBrowserTreeElementForRepresentedObject(this,representedObject):null;var pathComponents=[];while(treeElement&&!treeElement.root){var pathComponent=new WI.GeneralTreeElementPathComponent(treeElement);pathComponents.unshift(pathComponent);treeElement=treeElement.parent;} this._hierarchicalPathNavigationItem.components=pathComponents;} _updateContentViewSelectionPathNavigationItem(contentView) {var selectionPathComponents=contentView?contentView.selectionPathComponents||[]:[];this._contentViewSelectionPathNavigationItem.components=selectionPathComponents;if(this._currentContentViewNavigationItemsGroup) return;if(!selectionPathComponents.length){this._hierarchicalPathNavigationItem.alwaysShowLastPathComponentSeparator=false;this._navigationBar.removeNavigationItem(this._contentViewSelectionPathNavigationItem);return;} if(!this._navigationBar.navigationItems.includes(this._contentViewSelectionPathNavigationItem)){var hierarchicalPathItemIndex=this._navigationBar.navigationItems.indexOf(this._hierarchicalPathNavigationItem);this._navigationBar.insertNavigationItem(this._contentViewSelectionPathNavigationItem,hierarchicalPathItemIndex+1);this._hierarchicalPathNavigationItem.alwaysShowLastPathComponentSeparator=true;}} _updateBackForwardButtons() {if(!this._backNavigationItem||!this._forwardNavigationItem) return;this._backNavigationItem.enabled=this.canGoBack();this._forwardNavigationItem.enabled=this.canGoForward();} _updateContentViewNavigationItems(forceUpdate) {let currentContentView=this.currentContentView;if(!currentContentView){this._removeAllNavigationItems();this._currentContentViewNavigationItems=[];if(this._currentContentViewNavigationItemsGroup) this._currentContentViewNavigationItems.push(this._contentViewSelectionPathNavigationItem);return;} if(currentContentView.parentContainer!==this._contentViewContainer) return;if(!forceUpdate){let previousItems=this._currentContentViewNavigationItems.filter((item)=>!(item instanceof WI.DividerNavigationItem));let isUnchanged=Array.shallowEqual(previousItems,currentContentView.navigationItems);if(isUnchanged) return;} this._removeAllNavigationItems();let navigationBar=this.navigationBar;let insertionIndex=navigationBar.navigationItems.indexOf(this._flexibleNavigationItem)+1;let newNavigationItems=[];let shouldInsert=!this._currentContentViewNavigationItemsGroup;currentContentView.navigationItems.forEach(function(navigationItem,index){if(shouldInsert) navigationBar.insertNavigationItem(navigationItem,insertionIndex++);newNavigationItems.push(navigationItem);});if(this._currentContentViewNavigationItemsGroup) this._currentContentViewNavigationItemsGroup.navigationItems=[this._contentViewSelectionPathNavigationItem].concat(newNavigationItems); this._currentContentViewNavigationItems=newNavigationItems;} _removeAllNavigationItems() {if(this._currentContentViewNavigationItemsGroup) this._currentContentViewNavigationItemsGroup.navigationItems=[];else{for(let navigationItem of this._currentContentViewNavigationItems){if(navigationItem.parentNavigationBar) navigationItem.parentNavigationBar.removeNavigationItem(navigationItem);}}} _updateFindBanner(currentContentView) {if(!this._findBanner) return;if(!currentContentView){this._findBanner.targetElement=null;this._findBanner.numberOfResults=null;return;} this._findBanner.targetElement=currentContentView.element;this._findBanner.numberOfResults=currentContentView.hasPerformedSearch?currentContentView.numberOfSearchResults:null;if(currentContentView.supportsSearch&&this._findBanner.searchQuery){currentContentView.automaticallyRevealFirstSearchResult=this._findBanner.showing;currentContentView.performSearch(this._findBanner.searchQuery);}} _contentViewSelectionPathComponentDidChange(event) {if(event.target!==this.currentContentView) return;if(event.target.parentContainer!==this._contentViewContainer) return;this._updateContentViewSelectionPathNavigationItem(event.target);this._updateBackForwardButtons();this._updateContentViewNavigationItems();this._navigationBar.needsLayout();this._dispatchCurrentRepresentedObjectsDidChangeDebouncer.delayForTime(0);} _contentViewSupplementalRepresentedObjectsDidChange(event) {if(event.target!==this.currentContentView) return;if(event.target.parentContainer!==this._contentViewContainer) return;this._dispatchCurrentRepresentedObjectsDidChangeDebouncer.delayForTime(0);} _currentContentViewDidChange(event) {var currentContentView=this.currentContentView;this._updateHierarchicalPathNavigationItem(currentContentView?currentContentView.representedObject:null);this._updateContentViewSelectionPathNavigationItem(currentContentView);this._updateBackForwardButtons();this._updateContentViewNavigationItems();this._updateFindBanner(currentContentView);this._navigationBar.needsLayout();this.dispatchEventToListeners(WI.ContentBrowser.Event.CurrentContentViewDidChange);this._dispatchCurrentRepresentedObjectsDidChangeDebouncer.force();} _contentViewNavigationItemsDidChange(event) {if(event.target!==this.currentContentView) return;if(event.target.parentContainer!==this._contentViewContainer) return;const forceUpdate=true;this._updateContentViewNavigationItems(forceUpdate);this._navigationBar.needsLayout();} _hierarchicalPathComponentWasSelected(event) {var treeElement=event.data.pathComponent.generalTreeElement;var originalTreeElement=treeElement;while(treeElement&&!WI.ContentView.isViewable(treeElement.representedObject)) treeElement=treeElement.traverseNextTreeElement(false,originalTreeElement,false);if(!treeElement) return;treeElement.revealAndSelect();}};WI.ContentBrowser.Event={CurrentRepresentedObjectsDidChange:"content-browser-current-represented-objects-did-change",CurrentContentViewDidChange:"content-browser-current-content-view-did-change"};WI.ContentView=class ContentView extends WI.View {constructor(representedObject,extraArguments) {super();this._representedObject=representedObject;this.element.classList.add("content-view");this._parentContainer=null;this._isClosed=false;this._visible=false;} static shouldNotRemoveFromDOMWhenHidden() {return false;} static createFromRepresentedObject(representedObject,extraArguments) {if(representedObject instanceof WI.Frame) return new WI.ResourceClusterContentView(representedObject.mainResource,extraArguments);if(representedObject instanceof WI.Resource) return new WI.ResourceClusterContentView(representedObject,extraArguments);if(representedObject instanceof WI.Script) return new WI.ScriptContentView(representedObject,extraArguments);if(representedObject instanceof WI.CSSStyleSheet) return new WI.TextResourceContentView(representedObject,extraArguments);if(representedObject instanceof WI.Canvas) return new WI.CanvasContentView(representedObject,extraArguments);if(representedObject instanceof WI.ShaderProgram) return new WI.ShaderProgramContentView(representedObject,extraArguments);if(representedObject instanceof WI.TimelineRecording) return new WI.TimelineRecordingContentView(representedObject,extraArguments);if(representedObject instanceof WI.Timeline){var timelineType=representedObject.type;if(timelineType===WI.TimelineRecord.Type.Network) return new WI.NetworkTimelineView(representedObject,extraArguments);if(timelineType===WI.TimelineRecord.Type.Layout) return new WI.LayoutTimelineView(representedObject,extraArguments);if(timelineType===WI.TimelineRecord.Type.Script) return new WI.ScriptClusterTimelineView(representedObject,extraArguments);if(timelineType===WI.TimelineRecord.Type.RenderingFrame) return new WI.RenderingFrameTimelineView(representedObject,extraArguments);if(timelineType===WI.TimelineRecord.Type.CPU) return new WI.CPUTimelineView(representedObject,extraArguments);if(timelineType===WI.TimelineRecord.Type.Memory) return new WI.MemoryTimelineView(representedObject,extraArguments);if(timelineType===WI.TimelineRecord.Type.HeapAllocations) return new WI.HeapAllocationsTimelineView(representedObject,extraArguments);if(timelineType===WI.TimelineRecord.Type.Media) return new WI.MediaTimelineView(representedObject,extraArguments);if(timelineType===WI.TimelineRecord.Type.Screenshots) return new WI.ScreenshotsTimelineView(representedObject,extraArguments);} if(representedObject instanceof WI.JavaScriptBreakpoint||representedObject instanceof WI.IssueMessage){if(representedObject.sourceCodeLocation) return WI.ContentView.createFromRepresentedObject(representedObject.sourceCodeLocation.displaySourceCode,extraArguments);} if(representedObject instanceof WI.LocalResourceOverride){if(representedObject.type===WI.LocalResourceOverride.InterceptType.Block||representedObject.type===WI.LocalResourceOverride.InterceptType.Request) return new WI.LocalResourceOverrideRequestContentView(representedObject);return WI.ContentView.createFromRepresentedObject(representedObject.localResource);} if(representedObject instanceof WI.DOMStorageObject) return new WI.DOMStorageContentView(representedObject,extraArguments);if(representedObject instanceof WI.CookieStorageObject) return new WI.CookieStorageContentView(representedObject,extraArguments);if(representedObject instanceof WI.DatabaseTableObject) return new WI.DatabaseTableContentView(representedObject,extraArguments);if(representedObject instanceof WI.DatabaseObject) return new WI.DatabaseContentView(representedObject,extraArguments);if(representedObject instanceof WI.IndexedDatabase) return new WI.IndexedDatabaseContentView(representedObject,extraArguments);if(representedObject instanceof WI.IndexedDatabaseObjectStore) return new WI.IndexedDatabaseObjectStoreContentView(representedObject,extraArguments);if(representedObject instanceof WI.IndexedDatabaseObjectStoreIndex) return new WI.IndexedDatabaseObjectStoreContentView(representedObject,extraArguments);if(representedObject instanceof WI.ApplicationCacheFrame) return new WI.ApplicationCacheFrameContentView(representedObject,extraArguments);if(representedObject instanceof WI.DOMTree) return new WI.FrameDOMTreeContentView(representedObject,extraArguments);if(representedObject instanceof WI.DOMSearchMatchObject){var resultView=new WI.FrameDOMTreeContentView(WI.networkManager.mainFrame.domTree,extraArguments);resultView.restoreFromCookie({nodeToSelect:representedObject.domNode});return resultView;} if(representedObject instanceof WI.DOMNode){if(representedObject.frame){let resultView=WI.ContentView.createFromRepresentedObject(representedObject.frame,extraArguments);resultView.restoreFromCookie({nodeToSelect:representedObject});return resultView;}} if(representedObject instanceof WI.SourceCodeSearchMatchObject){var resultView;if(representedObject.sourceCode instanceof WI.Resource) resultView=new WI.ResourceClusterContentView(representedObject.sourceCode,extraArguments);else if(representedObject.sourceCode instanceof WI.Script) resultView=new WI.ScriptContentView(representedObject.sourceCode,extraArguments);else console.error("Unknown SourceCode",representedObject.sourceCode);var textRangeToSelect=representedObject.sourceCodeTextRange.formattedTextRange;var startPosition=textRangeToSelect.startPosition();resultView.restoreFromCookie({lineNumber:startPosition.lineNumber,columnNumber:startPosition.columnNumber});return resultView;} if(representedObject instanceof WI.LogObject) return new WI.LogContentView(representedObject,extraArguments);if(representedObject instanceof WI.CallingContextTree) return new WI.ProfileView(representedObject,extraArguments);if(representedObject instanceof WI.HeapSnapshotProxy||representedObject instanceof WI.HeapSnapshotDiffProxy) return new WI.HeapSnapshotClusterContentView(representedObject,extraArguments);if(representedObject instanceof WI.Recording) return new WI.RecordingContentView(representedObject,extraArguments);if(representedObject instanceof WI.ResourceCollection) return new WI.ResourceCollectionContentView(representedObject,extraArguments);if(representedObject instanceof WI.AuditTestCase||representedObject instanceof WI.AuditTestCaseResult) return new WI.AuditTestCaseContentView(representedObject,extraArguments);if(representedObject instanceof WI.AuditTestGroup||representedObject instanceof WI.AuditTestGroupResult) return new WI.AuditTestGroupContentView(representedObject,extraArguments);if(representedObject instanceof WI.Animation) return new WI.AnimationContentView(representedObject,extraArguments);if(representedObject instanceof WI.Collection) return new WI.CollectionContentView(representedObject,extraArguments);if(typeof representedObject==="string"||representedObject instanceof String) return new WI.TextContentView(representedObject,extraArguments);throw new Error("Can't make a ContentView for an unknown representedObject of type: "+representedObject.constructor.name);} static contentViewForRepresentedObject(representedObject,onlyExisting,extraArguments) {let resolvedRepresentedObject=WI.ContentView.resolvedRepresentedObjectForRepresentedObject(representedObject);if(!resolvedRepresentedObject) return null;let existingContentView=resolvedRepresentedObject[WI.ContentView.ContentViewForRepresentedObjectSymbol];if(existingContentView) return existingContentView;if(onlyExisting) return null;let newContentView=WI.ContentView.createFromRepresentedObject(representedObject,extraArguments);if(!newContentView) return null;if(typeof resolvedRepresentedObject==="object") newContentView.representedObject[WI.ContentView.ContentViewForRepresentedObjectSymbol]=newContentView;return newContentView;} static closedContentViewForRepresentedObject(representedObject) {let resolvedRepresentedObject=WI.ContentView.resolvedRepresentedObjectForRepresentedObject(representedObject);if(typeof resolvedRepresentedObject==="object") resolvedRepresentedObject[WI.ContentView.ContentViewForRepresentedObjectSymbol]=null;} static resolvedRepresentedObjectForRepresentedObject(representedObject) {if(representedObject instanceof WI.Frame) return representedObject.mainResource;if(representedObject instanceof WI.JavaScriptBreakpoint||representedObject instanceof WI.IssueMessage){if(representedObject.sourceCodeLocation) return representedObject.sourceCodeLocation.displaySourceCode;return representedObject;} if(representedObject instanceof WI.DOMBreakpoint){if(representedObject.domNode) return WI.ContentView.resolvedRepresentedObjectForRepresentedObject(representedObject.domNode);return representedObject;} if(representedObject instanceof WI.DOMNode){if(representedObject.frame) return WI.ContentView.resolvedRepresentedObjectForRepresentedObject(representedObject.frame);return representedObject;} if(representedObject instanceof WI.DOMSearchMatchObject) return WI.networkManager.mainFrame.domTree;if(representedObject instanceof WI.SourceCodeSearchMatchObject) return representedObject.sourceCode;if(representedObject instanceof WI.LocalResourceOverride){if(representedObject.type===WI.LocalResourceOverride.InterceptType.Response||representedObject.type===WI.LocalResourceOverride.InterceptType.ResponseMappedDirectory||representedObject.type===WI.LocalResourceOverride.InterceptType.ResponseSkippingNetwork) return representedObject.localResource;return representedObject;} return representedObject;} static isViewable(representedObject) {if(representedObject instanceof WI.Frame) return true;if(representedObject instanceof WI.Resource) return true;if(representedObject instanceof WI.Script) return true;if(representedObject instanceof WI.CSSStyleSheet) return true;if(representedObject instanceof WI.Canvas) return true;if(representedObject instanceof WI.ShaderProgram) return true;if(representedObject instanceof WI.TimelineRecording) return true;if(representedObject instanceof WI.Timeline) return true;if(representedObject instanceof WI.JavaScriptBreakpoint||representedObject instanceof WI.IssueMessage) return representedObject.sourceCodeLocation;if(representedObject instanceof WI.LocalResourceOverride) return true;if(representedObject instanceof WI.DOMStorageObject) return true;if(representedObject instanceof WI.CookieStorageObject) return true;if(representedObject instanceof WI.DatabaseTableObject) return true;if(representedObject instanceof WI.DatabaseObject) return true;if(representedObject instanceof WI.IndexedDatabase) return true;if(representedObject instanceof WI.IndexedDatabaseObjectStore) return true;if(representedObject instanceof WI.IndexedDatabaseObjectStoreIndex) return true;if(representedObject instanceof WI.ApplicationCacheFrame) return true;if(representedObject instanceof WI.DOMTree) return true;if(representedObject instanceof WI.DOMSearchMatchObject) return true;if(representedObject instanceof WI.SourceCodeSearchMatchObject) return true;if(representedObject instanceof WI.LogObject) return true;if(representedObject instanceof WI.CallingContextTree) return true;if(representedObject instanceof WI.HeapSnapshotProxy||representedObject instanceof WI.HeapSnapshotDiffProxy) return true;if(representedObject instanceof WI.Recording) return true;if(representedObject instanceof WI.AuditTestCase||representedObject instanceof WI.AuditTestGroup||representedObject instanceof WI.AuditTestCaseResult||representedObject instanceof WI.AuditTestGroupResult) return true;if(representedObject instanceof WI.Animation) return true;if(representedObject instanceof WI.Collection) return true;if(typeof representedObject==="string"||representedObject instanceof String) return true;if(representedObject[WI.ContentView.isViewableSymbol]) return true;return false;} get isClosed(){return this._isClosed;} get visible() {return!this.isClosed&&this._visible;} set visible(value) {this._visible=!!value;this.element.classList.toggle("not-visible",!this._visible);} get representedObject() {return this._representedObject;} get navigationItems() {return[];} get parentContainer() {return this._parentContainer;} get scrollableElements() {return[];} get shouldKeepElementsScrolledToBottom() {return false;} get shouldSaveStateWhenHidden() {return false;} get selectionPathComponents() {return[];} get supplementalRepresentedObjects() {return[];} get supportsSplitContentBrowser() {return WI.dockedConfigurationSupportsSplitContentBrowser();} closed() {this._isClosed=true;} saveToCookie(cookie) {} restoreFromCookie(cookie) {} canGoBack() {return false;} canGoForward() {return false;} goBack() {} goForward() {} get supportsSearch() {return false;} get supportsCustomFindBanner() {return false;} showCustomFindBanner() {} get numberOfSearchResults() {return null;} get hasPerformedSearch() {return false;} set automaticallyRevealFirstSearchResult(reveal) {} performSearch(query) {} searchHidden() {} searchCleared() {} searchQueryWithSelection() {let selection=window.getSelection();if(selection.isCollapsed) return null;return selection.toString().removeWordBreakCharacters();} revealPreviousSearchResult(changeFocus) {} revealNextSearchResult(changeFocus) {}};WI.ContentView.Event={SelectionPathComponentsDidChange:"content-view-selection-path-components-did-change",SupplementalRepresentedObjectsDidChange:"content-view-supplemental-represented-objects-did-change",NumberOfSearchResultsDidChange:"content-view-number-of-search-results-did-change",NavigationItemsDidChange:"content-view-navigation-items-did-change"};WI.ContentView.isViewableSymbol=Symbol("is-viewable");WI.ContentView.ContentViewForRepresentedObjectSymbol=Symbol("content-view-for-represented-object");WI.DataGrid=class DataGrid extends WI.View {constructor(columnsData,{beforeEditCallback,afterEditCallback,copyCallback,deleteCallback,preferredColumnOrder}={}) {super();this.columns=new Map;this.orderedColumns=[];this._settingsIdentifier=null;this._sortColumnIdentifier=null;this._sortColumnIdentifierSetting=null;this._sortOrder=WI.DataGrid.SortOrder.Indeterminate;this._sortOrderSetting=null;this._columnVisibilitySetting=null;this._columnChooserEnabled=false;this._headerVisible=true;this._rows=[];this.children=[];this.expandNodesWhenArrowing=false;this.root=true;this.hasChildren=false;this.expanded=true;this.revealed=true;this.selected=false;this.dataGrid=this;this.indentWidth=15;this.rowHeight=20;this.resizers=[];this._columnWidthsInitialized=false;this._scrollbarWidth=0;this._cachedScrollTop=NaN;this._cachedScrollableOffsetHeight=NaN;this._previousRevealedRowCount=NaN;this._topDataTableMarginHeight=NaN;this._bottomDataTableMarginHeight=NaN;this._filterText="";this._filterDelegate=null;this._filterDidModifyNodeWhileProcessingItems=false;let itemForRepresentedObject=this.dataGridNodeForSelectionItem.bind(this);let selectionComparator=WI.SelectionController.createTreeComparator(itemForRepresentedObject);this._selectionController=new WI.SelectionController(this,selectionComparator);this._processingSelectionChange=false;this._suppressNextSelectionDidChangeEvent=false;this.element.className="data-grid";this.element.tabIndex=0;this.element.addEventListener("keydown",this._keyDown.bind(this),false);this.element.copyHandler=this;this._headerWrapperElement=document.createElement("div");this._headerWrapperElement.classList.add("header-wrapper");this._headerTableElement=document.createElement("table");this._headerTableElement.className="header";this._headerWrapperElement.appendChild(this._headerTableElement);this._headerTableColumnGroupElement=this._headerTableElement.createChild("colgroup");this._headerTableBodyElement=this._headerTableElement.createChild("tbody");this._headerTableRowElement=this._headerTableBodyElement.createChild("tr");this._headerTableRowElement.addEventListener("contextmenu",this._contextMenuInHeader.bind(this),true);this._headerTableCellElements=new Map;this._scrollContainerElement=document.createElement("div");this._scrollContainerElement.className="data-container";this._scrollListener=()=>this._noteScrollPositionChanged();this._updateScrollListeners();this._topDataTableMarginElement=this._scrollContainerElement.createChild("div");this._dataTableElement=this._scrollContainerElement.createChild("table","data");this._bottomDataTableMarginElement=this._scrollContainerElement.createChild("div");this._dataTableElement.addEventListener("mousedown",this._mouseDownInDataTable.bind(this));this._dataTableElement.addEventListener("click",this._clickInDataTable.bind(this));this._dataTableElement.addEventListener("contextmenu",this._contextMenuInDataTable.bind(this),true); if(afterEditCallback){this._dataTableElement.addEventListener("dblclick",this._ondblclick.bind(this),false);this._beforeEditCallback=beforeEditCallback;this._afterEditCallback=afterEditCallback;} if(copyCallback) this._copyCallback=copyCallback;if(deleteCallback) this._deleteCallback=deleteCallback;this._dataTableColumnGroupElement=this._headerTableColumnGroupElement.cloneNode(true);this._dataTableElement.appendChild(this._dataTableColumnGroupElement);this.dataTableBodyElement=this._dataTableElement.createChild("tbody");this._fillerRowElement=this.dataTableBodyElement.createChild("tr","filler");this.element.appendChild(this._headerWrapperElement);this.element.appendChild(this._scrollContainerElement);if(preferredColumnOrder){for(var columnIdentifier of preferredColumnOrder) this.insertColumn(columnIdentifier,columnsData[columnIdentifier]);}else{for(var columnIdentifier in columnsData) this.insertColumn(columnIdentifier,columnsData[columnIdentifier]);} this._updateScrollbarPadding();this._copyTextDelimiter="\t";} _updateScrollbarPadding() {if(this._inline) return;let scrollbarWidth=this._scrollContainerElement.offsetWidth-this._scrollContainerElement.scrollWidth;if(this._scrollbarWidth===scrollbarWidth) return;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL) this._headerWrapperElement.style.setProperty("padding-left",`${scrollbarWidth}px`);else this._headerWrapperElement.style.setProperty("padding-right",`${scrollbarWidth}px`);this._scrollbarWidth=scrollbarWidth;} static createSortableDataGrid(columnNames,values) {var numColumns=columnNames.length;if(!numColumns) return null;var columnsData={};for(var columnName of columnNames){columnsData[columnName]={width:columnName.length,title:columnName,sortable:true,};} let dataGrid=new WI.DataGrid(columnsData,{preferredColumnOrder:columnNames});for(var i=0;inumber2?1:0);}else comparison=item1item2?1:0);return comparison;} dataGrid.sortNodes(comparator);} dataGrid.addEventListener(WI.DataGrid.Event.SortChanged,sortDataGrid,this);dataGrid.sortOrder=WI.DataGrid.SortOrder.Ascending;dataGrid.sortColumnIdentifier=columnNames[0];return dataGrid;} get headerVisible(){return this._headerVisible;} set headerVisible(x) {if(x===this._headerVisible) return;this._headerVisible=x;this.element.classList.toggle("no-header",!this._headerVisible);} get columnChooserEnabled(){return this._columnChooserEnabled;} set columnChooserEnabled(x){this._columnChooserEnabled=x;} get copyTextDelimiter(){return this._copyTextDelimiter;} set copyTextDelimiter(x){this._copyTextDelimiter=x;} get refreshCallback() {return this._refreshCallback;} set refreshCallback(refreshCallback) {this._refreshCallback=refreshCallback;} get sortOrder() {return this._sortOrder;} set sortOrder(order) {if(!order||order===this._sortOrder) return;this._sortOrder=order;if(this._sortOrderSetting) this._sortOrderSetting.value=this._sortOrder;if(!this._sortColumnIdentifier) return;var sortHeaderCellElement=this._headerTableCellElements.get(this._sortColumnIdentifier);sortHeaderCellElement.classList.toggle(WI.DataGrid.SortColumnAscendingStyleClassName,this._sortOrder===WI.DataGrid.SortOrder.Ascending);sortHeaderCellElement.classList.toggle(WI.DataGrid.SortColumnDescendingStyleClassName,this._sortOrder===WI.DataGrid.SortOrder.Descending);this.dispatchEventToListeners(WI.DataGrid.Event.SortChanged);} get sortColumnIdentifier() {return this._sortColumnIdentifier;} set sortColumnIdentifier(columnIdentifier) {if(this._sortColumnIdentifier===columnIdentifier) return;let oldSortColumnIdentifier=this._sortColumnIdentifier;this._sortColumnIdentifier=columnIdentifier;this._updateSortedColumn(oldSortColumnIdentifier);} get inline(){return this._inline;} set inline(x) {if(this._inline===x) return;this._inline=x||false;this._element.classList.toggle("inline",this._inline);this._updateScrollListeners();} get variableHeightRows(){return this._variableHeightRows;} set variableHeightRows(x) {if(this._variableHeightRows===x) return;this._variableHeightRows=x||false;this._element.classList.toggle("variable-height-rows",this._variableHeightRows);this._updateScrollListeners();} get allowsMultipleSelection() {return this._selectionController.allowsMultipleSelection;} set allowsMultipleSelection(flag) {this._selectionController.allowsMultipleSelection=flag;} get selectedNode() {return this.dataGridNodeForSelectionItem(this._selectionController.lastSelectedItem);} set selectedNode(dataGridNode) {if(dataGridNode) this._selectionController.selectItem(this.selectionItemForDataGridNode(dataGridNode));else this._selectionController.deselectAll();} get selectedDataGridNodes() {if(this.allowsMultipleSelection){let selectedDataGridNodes=[];for(let item of this._selectionController.selectedItems) selectedDataGridNodes.push(this.dataGridNodeForSelectionItem(item));return selectedDataGridNodes;} let selectedNode=this.selectedNode;if(selectedNode) return[selectedNode];return[];} get filterText(){return this._filterText;} set filterText(x) {if(this._filterText===x) return;this._filterText=x;this.filterDidChange();} get filterDelegate(){return this._filterDelegate;} set filterDelegate(delegate) {this._filterDelegate=delegate;this.filterDidChange();} filterDidChange() {if(this._scheduledFilterUpdateIdentifier) return;if(this._applyFilterToNodesTask){this._applyFilterToNodesTask.cancel();this._applyFilterToNodesTask=null;} this._scheduledFilterUpdateIdentifier=requestAnimationFrame(this._updateFilter.bind(this));} hasFilters() {return this._textFilterRegex||this._hasFilterDelegate();} matchNodeAgainstCustomFilters(node) {if(!this._hasFilterDelegate()) return true;return this._filterDelegate.dataGridMatchNodeAgainstCustomFilters(node);} createSettings(identifier) {if(this._settingsIdentifier===identifier) return;this._settingsIdentifier=identifier;this._sortColumnIdentifierSetting=new WI.Setting(this._settingsIdentifier+"-sort",this._sortColumnIdentifier);this._sortOrderSetting=new WI.Setting(this._settingsIdentifier+"-sort-order",this._sortOrder);this._columnVisibilitySetting=new WI.Setting(this._settingsIdentifier+"-column-visibility",{});if(!this.columns) return;if(this._sortColumnIdentifierSetting.value){this.sortColumnIdentifier=this._sortColumnIdentifierSetting.value;this.sortOrder=this._sortOrderSetting.value;} let visibilitySettings=this._columnVisibilitySetting.value;for(let columnIdentifier in visibilitySettings){let visible=visibilitySettings[columnIdentifier];this.setColumnVisible(columnIdentifier,visible);}} startEditingNode(node) {if(this._editing||this._editingNode) return;this._startEditingNodeAtColumnIndex(node,0);} _updateScrollListeners() {if(this._inline||this._variableHeightRows){this._scrollContainerElement.removeEventListener("scroll",this._scrollListener);this._scrollContainerElement.removeEventListener("mousewheel",this._scrollListener);}else{this._scrollContainerElement.addEventListener("scroll",this._scrollListener);this._scrollContainerElement.addEventListener("mousewheel",this._scrollListener);}} _applyFiltersToNodeAndDispatchEvent(node) {const nodeWasHidden=node.hidden;this._applyFiltersToNode(node);if(nodeWasHidden!==node.hidden) this.dispatchEventToListeners(WI.DataGrid.Event.NodeWasFiltered,{node});return nodeWasHidden!==node.hidden;} _applyFiltersToNode(node) {if(!this.hasFilters()){node.hidden=false;if(node.expanded&&node[WI.DataGrid.WasExpandedDuringFilteringSymbol]){node[WI.DataGrid.WasExpandedDuringFilteringSymbol]=false;node.collapse();} return;} let filterableData=node.filterableData||[];let flags={expandNode:false};let filterRegex=this._textFilterRegex;function matchTextFilter() {if(!filterableData.length||!filterRegex) return true;if(filterableData.some((value)=>filterRegex.test(value))){flags.expandNode=true;return true;} return false;} function makeVisible() {node.hidden=false;let currentAncestor=node.parent;while(currentAncestor&&!currentAncestor.root){currentAncestor.hidden=false;if(flags.expandNode&&!currentAncestor.expanded){currentAncestor[WI.DataGrid.WasExpandedDuringFilteringSymbol]=true;currentAncestor.expand();} currentAncestor=currentAncestor.parent;}} if(matchTextFilter()&&this.matchNodeAgainstCustomFilters(node)){makeVisible();if(!flags.expandNode&&node.expanded&&node[WI.DataGrid.WasExpandedDuringFilteringSymbol]){node[WI.DataGrid.WasExpandedDuringFilteringSymbol]=false;node.collapse();} return;} node.hidden=true;} _updateSortedColumn(oldSortColumnIdentifier) {if(this._sortColumnIdentifierSetting) this._sortColumnIdentifierSetting.value=this._sortColumnIdentifier;if(oldSortColumnIdentifier){let oldSortHeaderCellElement=this._headerTableCellElements.get(oldSortColumnIdentifier);oldSortHeaderCellElement.classList.remove(WI.DataGrid.SortColumnAscendingStyleClassName);oldSortHeaderCellElement.classList.remove(WI.DataGrid.SortColumnDescendingStyleClassName);} if(this._sortColumnIdentifier){let newSortHeaderCellElement=this._headerTableCellElements.get(this._sortColumnIdentifier);newSortHeaderCellElement.classList.toggle(WI.DataGrid.SortColumnAscendingStyleClassName,this._sortOrder===WI.DataGrid.SortOrder.Ascending);newSortHeaderCellElement.classList.toggle(WI.DataGrid.SortColumnDescendingStyleClassName,this._sortOrder===WI.DataGrid.SortOrder.Descending);} this.dispatchEventToListeners(WI.DataGrid.Event.SortChanged);} _hasFilterDelegate() {return this._filterDelegate&&typeof this._filterDelegate.dataGridMatchNodeAgainstCustomFilters==="function";} _ondblclick(event) {if(this._editing||this._editingNode) return;this._startEditing(event.target);} _startEditingNodeAtColumnIndex(node,columnIndex) {this.updateLayoutIfNeeded();this._editing=true;this._editingNode=node;this._editingNode.select();this._beforeEditCallback?.(node,this.orderedColumns[columnIndex]);var element=this._editingNode.element.children[columnIndex];WI.startEditing(element,this._startEditingConfig(element));window.getSelection().setBaseAndExtent(element,0,element,1);} _startEditing(target) {let cell=target.closest("td");if(!cell) return;let node=this.dataGridNodeFromNode(target);if(!node.editable) return;this._editingNode=node;if(!this._editingNode){if(!this.placeholderNode) return;this._editingNode=this.placeholderNode;} if(this._editingNode.isPlaceholderNode) return this._startEditingNodeAtColumnIndex(this._editingNode,0);let columnIndex=this._editingNode.element.children.indexOf(cell);this._beforeEditCallback?.(node,this.orderedColumns[columnIndex]);this._editing=true;let element=this._editingNode.element.children[columnIndex];WI.startEditing(element,this._startEditingConfig(element));window.getSelection().setBaseAndExtent(element,0,element,1);} _startEditingConfig(element) {return new WI.EditingConfig(this._editingCommitted.bind(this),this._editingCancelled.bind(this),element.textContent);} _editingCommitted(element,newText,oldText,context,moveDirection) {var columnIdentifier=element.__columnIdentifier;var columnIndex=this.orderedColumns.indexOf(columnIdentifier);var textBeforeEditing=this._editingNode.data[columnIdentifier]||"";var currentEditingNode=this._editingNode;currentEditingNode.data[columnIdentifier]=newText.trim(); function determineNextCell(valueDidChange){if(moveDirection==="forward"){if(columnIndex0) return{shouldSort:false,editingNode:currentEditingNode,columnIndex:columnIndex-1};var previousDataGridNode=currentEditingNode.traversePreviousNode(true,null,true);return{shouldSort:true,editingNode:previousDataGridNode||currentEditingNode,columnIndex:this.orderedColumns.length-1};} return{shouldSort:true};} function moveToNextCell(valueDidChange){var moveCommand=determineNextCell.call(this,valueDidChange);if(moveCommand.shouldSort&&this._sortAfterEditingCallback){this._sortAfterEditingCallback();this._sortAfterEditingCallback=null;} if(moveCommand.editingNode) this._startEditingNodeAtColumnIndex(moveCommand.editingNode,moveCommand.columnIndex);} this._editingCancelled(element);this._afterEditCallback(currentEditingNode,columnIdentifier,textBeforeEditing,newText,moveDirection);var textDidChange=textBeforeEditing.trim()!==newText.trim();moveToNextCell.call(this,textDidChange);} _editingCancelled(element) {this._editingNode.refresh();this._editing=false;this._editingNode=null;} autoSizeColumns(minPercent,maxPercent,maxDescentLevel) {if(minPercent) minPercent=Math.min(minPercent,Math.floor(100/this.orderedColumns.length));var widths={};for(var[identifier,column]of this.columns) widths[identifier]=(column["title"]||"").length;var children=maxDescentLevel?this._enumerateChildren(this,[],maxDescentLevel+1):this.children;for(var node of children){for(var identifier of this.columns.keys()){var text=this.textForDataGridNodeColumn(node,identifier);if(text.length>widths[identifier]) widths[identifier]=text.length;}} var totalColumnWidths=0;for(var identifier of this.columns.keys()) totalColumnWidths+=widths[identifier];var recoupPercent=0;for(var identifier of this.columns.keys()){var width=Math.round(100*widths[identifier]/totalColumnWidths);if(minPercent&&widthmaxPercent){recoupPercent-=width-maxPercent;width=maxPercent;} widths[identifier]=width;} while(minPercent&&recoupPercent>0){for(var identifier of this.columns.keys()){if(widths[identifier]>minPercent){--widths[identifier];--recoupPercent;if(!recoupPercent) break;}}} while(maxPercent&&recoupPercent<0){for(var identifier of this.columns.keys()){if(widths[identifier]=insertionIndex) existingColumn["ordinal"]=ordinal+1;} this.columns.set(columnIdentifier,column);if(column["disclosure"]) this.disclosureColumnIdentifier=columnIdentifier;var headerColumnElement=document.createElement("col");if(column["width"]) headerColumnElement.style.width=column["width"];column["element"]=headerColumnElement;var referenceElement=this._headerTableColumnGroupElement.children[insertionIndex];this._headerTableColumnGroupElement.insertBefore(headerColumnElement,referenceElement);var headerCellElement=document.createElement("th");headerCellElement.className=columnIdentifier+"-column";headerCellElement.columnIdentifier=columnIdentifier;if(column["aligned"]) headerCellElement.classList.add(column["aligned"]);this._headerTableCellElements.set(columnIdentifier,headerCellElement);var referenceElement=this._headerTableRowElement.children[insertionIndex];this._headerTableRowElement.insertBefore(headerCellElement,referenceElement);if(column["headerView"]){let headerView=column["headerView"];headerView.element.classList.add("header-cell-content");headerCellElement.appendChild(headerView.element);this.addSubview(headerView);}else{let titleElement=headerCellElement.createChild("div","header-cell-content");if(column["titleDOMFragment"]) titleElement.appendChild(column["titleDOMFragment"]);else titleElement.textContent=column["title"]||"";} if(column["sortable"]){headerCellElement.addEventListener("click",this._headerCellClicked.bind(this));headerCellElement.classList.add(WI.DataGrid.SortableColumnStyleClassName);} if(column["group"]) headerCellElement.classList.add("column-group-"+column["group"]);if(column["tooltip"]) headerCellElement.title=column["tooltip"];if(column["collapsesGroup"]){headerCellElement.createChild("div","divider");var collapseDiv=headerCellElement.createChild("div","collapser-button");collapseDiv.title=this._collapserButtonCollapseColumnsToolTip();collapseDiv.addEventListener("mouseover",this._mouseoverColumnCollapser.bind(this));collapseDiv.addEventListener("mouseout",this._mouseoutColumnCollapser.bind(this));collapseDiv.addEventListener("click",this._clickInColumnCollapser.bind(this));headerCellElement.collapsesGroup=column["collapsesGroup"];headerCellElement.classList.add("collapser");} this._headerTableColumnGroupElement.span=this.orderedColumns.length;var dataColumnElement=headerColumnElement.cloneNode();var referenceElement=this._dataTableColumnGroupElement.children[insertionIndex];this._dataTableColumnGroupElement.insertBefore(dataColumnElement,referenceElement);column["bodyElement"]=dataColumnElement;var fillerCellElement=document.createElement("td");fillerCellElement.className=columnIdentifier+"-column";fillerCellElement.__columnIdentifier=columnIdentifier;if(column["group"]) fillerCellElement.classList.add("column-group-"+column["group"]);var referenceElement=this._fillerRowElement.children[insertionIndex];this._fillerRowElement.insertBefore(fillerCellElement,referenceElement);this.setColumnVisible(columnIdentifier,!column.hidden);} removeColumn(columnIdentifier) {var removedColumn=this.columns.get(columnIdentifier);this.columns.delete(columnIdentifier);this.orderedColumns.splice(this.orderedColumns.indexOf(columnIdentifier),1);var removedOrdinal=removedColumn["ordinal"];for(var[identifier,column]of this.columns){var ordinal=column["ordinal"];if(ordinal>removedOrdinal) column["ordinal"]=ordinal-1;} if(removedColumn["disclosure"]) this.disclosureColumnIdentifier=undefined;if(this.sortColumnIdentifier===columnIdentifier) this.sortColumnIdentifier=null;this._headerTableCellElements.delete(columnIdentifier);this._headerTableRowElement.children[removedOrdinal].remove();this._headerTableColumnGroupElement.children[removedOrdinal].remove();this._dataTableColumnGroupElement.children[removedOrdinal].remove();this._fillerRowElement.children[removedOrdinal].remove();this._headerTableColumnGroupElement.span=this.orderedColumns.length;for(var child of this.children) child.refresh();} _enumerateChildren(rootNode,result,maxLevel) {if(!rootNode.root) result.push(rootNode);if(!maxLevel) return;for(var i=0;i=0;--i){let rowElement=this._rows[i].element;if(rowElement.nextSibling!==nextElement) this.dataTableBodyElement.insertBefore(rowElement,nextElement);nextElement=rowElement;} if(focusedDataGridNode) focusedDataGridNode.element.scrollIntoViewIfNeeded(false);return;} let rowHeight=this.rowHeight;let updateOffsetThreshold=rowHeight*5;let overflowPadding=updateOffsetThreshold*3;if(isNaN(this._cachedScrollTop)) this._cachedScrollTop=this._scrollContainerElement.scrollTop;if(isNaN(this._cachedScrollableOffsetHeight)) this._cachedScrollableOffsetHeight=this._scrollContainerElement.offsetHeight;let visibleRowCount=Math.ceil((this._cachedScrollableOffsetHeight+(overflowPadding*2))/rowHeight);if(!focusedDataGridNode){let currentTopMargin=this._topDataTableMarginHeight;let currentBottomMargin=this._bottomDataTableMarginHeight;let currentTableBottom=currentTopMargin+(visibleRowCount*rowHeight);let belowTopThreshold=!currentTopMargin||this._cachedScrollTop>currentTopMargin+updateOffsetThreshold;let aboveBottomThreshold=!currentBottomMargin||this._cachedScrollTop+this._cachedScrollableOffsetHeightrow.revealed&&!row.hidden);this._previousRevealedRowCount=revealedRows.length;if(focusedDataGridNode){let focusedIndex=revealedRows.indexOf(focusedDataGridNode);let firstVisibleRowIndex=this._cachedScrollTop/rowHeight;if(focusedIndexfirstVisibleRowIndex+visibleRowCount) this._scrollContainerElement.scrollTop=this._cachedScrollTop=(focusedIndex*rowHeight)-(this._cachedScrollableOffsetHeight/2)+(rowHeight/2);} let topHiddenRowCount=Math.max(0,Math.floor((this._cachedScrollTop-overflowPadding)/rowHeight));let bottomHiddenRowCount=Math.max(0,this._previousRevealedRowCount-topHiddenRowCount-visibleRowCount);let marginTop=topHiddenRowCount*rowHeight;let marginBottom=bottomHiddenRowCount*rowHeight;if(this._topDataTableMarginHeight!==marginTop){this._topDataTableMarginHeight=marginTop;this._topDataTableMarginElement.style.height=marginTop+"px";} if(this._bottomDataTableMarginElement!==marginBottom){this._bottomDataTableMarginHeight=marginBottom;this._bottomDataTableMarginElement.style.height=marginBottom+"px";} this._dataTableElement.classList.toggle("even-first-zebra-stripe",!!(topHiddenRowCount%2));this.dataTableBodyElement.removeChildren();for(let i=topHiddenRowCount;i{if(this._sortNodesComparator) this._sortNodesCallback(this._sortNodesComparator);});} sortNodesImmediately(comparator) {this._sortNodesCallback(comparator);} _sortNodesCallback(comparator) {function comparatorWrapper(aNode,bNode) {if(aNode.isPlaceholderNode) return 1;if(bNode.isPlaceholderNode) return-1;var reverseFactor=this.sortOrder!==WI.DataGrid.SortOrder.Ascending?-1:1;return reverseFactor*comparator(aNode,bNode);} this._sortNodesRequestId=undefined;this._sortNodesComparator=null;if(this._editing){this._sortAfterEditingCallback=this.sortNodes.bind(this,comparator);return;} this._rows.sort(comparatorWrapper.bind(this));this._noteRowsChanged();let previousSiblingNode=null;for(let node of this._rows){node.previousSibling=previousSiblingNode;if(previousSiblingNode) previousSiblingNode.nextSibling=node;previousSiblingNode=node;} if(previousSiblingNode) previousSiblingNode.nextSibling=null;if(!this.parentView) this.updateLayoutIfNeeded();} _toggledSortOrder() {return this._sortOrder!==WI.DataGrid.SortOrder.Descending?WI.DataGrid.SortOrder.Descending:WI.DataGrid.SortOrder.Ascending;} _selectSortColumnAndSetOrder(columnIdentifier,sortOrder) {this.sortColumnIdentifier=columnIdentifier;this.sortOrder=sortOrder;} _keyDown(event) {if(this._editing) return;let isRTL=WI.resolveLayoutDirectionForElement(this.element)===WI.LayoutDirection.RTL;let expandKeyIdentifier=isRTL?"Left":"Right";let collapseKeyIdentifier=isRTL?"Right":"Left";var handled=false;var nextSelectedNode;if(this.selectedNode){if(event.keyIdentifier===collapseKeyIdentifier){if(this.selectedNode.expanded){if(event.altKey) this.selectedNode.collapseRecursively();else this.selectedNode.collapse();handled=true;}else if(this.selectedNode.parent&&!this.selectedNode.parent.root){handled=true;if(this.selectedNode.parent.selectable){nextSelectedNode=this.selectedNode.parent;while(nextSelectedNode&&!nextSelectedNode.selectable) nextSelectedNode=nextSelectedNode.parent;handled=!!nextSelectedNode;}else if(this.selectedNode.parent) this.selectedNode.parent.collapse();}}else if(event.keyIdentifier===expandKeyIdentifier){if(!this.selectedNode.revealed){this.selectedNode.reveal();handled=true;}else if(this.selectedNode.hasChildren){handled=true;if(this.selectedNode.expanded){nextSelectedNode=this.selectedNode.children[0];while(nextSelectedNode&&!nextSelectedNode.selectable) nextSelectedNode=nextSelectedNode.nextSibling;handled=!!nextSelectedNode;}else{if(event.altKey) this.selectedNode.expandRecursively();else this.selectedNode.expand();}}}else if(event.keyCode===8||event.keyCode===46){if(this._deleteCallback){handled=true;this._deleteCallback(this.selectedNode);}}else if(isEnterKey(event)){if(this._afterEditCallback){handled=true;this._startEditing(this.selectedNode.element.children[0]);}}} if(!handled){handled=this._selectionController.handleKeyDown(event);if(handled) nextSelectedNode=this.selectedNode;} if(nextSelectedNode){nextSelectedNode.reveal();nextSelectedNode.select();} if(handled){event.preventDefault();event.stopPropagation();}} closed() {} expand() {} collapse() {} reveal() {} revealAndSelect() {} selectNodes(nodes) {if(!nodes.length) return;if(nodes.length===1){this.selectedNode=nodes[0];return;} if(!this.allowsMultipleSelection) return;let selectableObjects=nodes.map((node)=>this.selectionItemForDataGridNode(node));this._selectionController.selectItems(new Set(selectableObjects));} dataGridNodeFromNode(target) {var rowElement=target.closest("tr");return rowElement&&rowElement._dataGridNode;} dataGridNodeFromPoint(x,y) {var node=this._dataTableElement.ownerDocument.elementFromPoint(x,y);var rowElement=node.closest("tr");return rowElement&&rowElement._dataGridNode;} _headerCellClicked(event) {let cell=event.target.closest("th");if(!cell||!cell.columnIdentifier||!cell.classList.contains(WI.DataGrid.SortableColumnStyleClassName)) return;let sortOrder=this._sortColumnIdentifier===cell.columnIdentifier?this._toggledSortOrder():this.sortOrder;this._selectSortColumnAndSetOrder(cell.columnIdentifier,sortOrder);} _mouseoverColumnCollapser(event) {var cell=event.target.closest("th");if(!cell||!cell.collapsesGroup) return;cell.classList.add("mouse-over-collapser");} _mouseoutColumnCollapser(event) {var cell=event.target.closest("th");if(!cell||!cell.collapsesGroup) return;cell.classList.remove("mouse-over-collapser");} _clickInColumnCollapser(event) {var cell=event.target.closest("th");if(!cell||!cell.collapsesGroup) return;this._collapseColumnGroupWithCell(cell);event.stopPropagation();event.preventDefault();} collapseColumnGroup(columnGroup) {var collapserColumnIdentifier=null;for(var[identifier,column]of this.columns){if(column["collapsesGroup"]===columnGroup){collapserColumnIdentifier=identifier;break;}} if(!collapserColumnIdentifier) return;var cell=this._headerTableCellElements.get(collapserColumnIdentifier);this._collapseColumnGroupWithCell(cell);} _collapseColumnGroupWithCell(cell) {var columnsWillCollapse=cell.classList.toggle("collapsed");this.willToggleColumnGroup(cell.collapsesGroup,columnsWillCollapse);for(var[identifier,column]of this.columns){if(column["group"]===cell.collapsesGroup) this.setColumnVisible(identifier,!columnsWillCollapse);} var collapserButton=cell.querySelector(".collapser-button");if(collapserButton) collapserButton.title=columnsWillCollapse?this._collapserButtonExpandColumnsToolTip():this._collapserButtonCollapseColumnsToolTip();this.didToggleColumnGroup(cell.collapsesGroup,columnsWillCollapse);} _collapserButtonCollapseColumnsToolTip() {return WI.UIString("Collapse columns");} _collapserButtonExpandColumnsToolTip() {return WI.UIString("Expand columns");} willToggleColumnGroup(columnGroup,willCollapse) {} didToggleColumnGroup(columnGroup,didCollapse) {} headerTableHeader(columnIdentifier) {return this._headerTableCellElements.get(columnIdentifier);} _mouseDownInDataTable(event) {let dataGridNode=this.dataGridNodeFromNode(event.target);if(!dataGridNode){this._selectionController.deselectAll();return;} if(!dataGridNode.selectable||dataGridNode.isEventWithinDisclosureTriangle(event)) return;this._selectionController.handleItemMouseDown(this.selectionItemForDataGridNode(dataGridNode),event);} _contextMenuInHeader(event) {let contextMenu=WI.ContextMenu.createFromEvent(event);if(this._hasCopyableData()) contextMenu.appendItem(WI.UIString("Copy Table"),this._copyTable.bind(this));let headerCellElement=event.target.closest("th");if(!headerCellElement) return;let columnIdentifier=headerCellElement.columnIdentifier;let column=this.columns.get(columnIdentifier);if(!column) return;if(column.sortable){contextMenu.appendSeparator();if(this.sortColumnIdentifier!==columnIdentifier||this.sortOrder!==WI.DataGrid.SortOrder.Ascending){contextMenu.appendItem(WI.UIString("Sort Ascending"),()=>{this._selectSortColumnAndSetOrder(columnIdentifier,WI.DataGrid.SortOrder.Ascending);});} if(this.sortColumnIdentifier!==columnIdentifier||this.sortOrder!==WI.DataGrid.SortOrder.Descending){contextMenu.appendItem(WI.UIString("Sort Descending"),()=>{this._selectSortColumnAndSetOrder(columnIdentifier,WI.DataGrid.SortOrder.Descending);});}} if(this._columnChooserEnabled){let didAddSeparator=false;for(let[identifier,columnInfo]of this.columns){if(columnInfo.locked) continue;if(!didAddSeparator){contextMenu.appendSeparator();didAddSeparator=true;const disabled=true;contextMenu.appendItem(WI.UIString("Displayed Columns"),()=>{},disabled);} contextMenu.appendCheckboxItem(columnInfo.title,()=>{this.setColumnVisible(identifier,!!columnInfo.hidden);},!columnInfo.hidden);}}} _contextMenuInDataTable(event) {let contextMenu=WI.ContextMenu.createFromEvent(event);let gridNode=this.dataGridNodeFromNode(event.target);if(gridNode) gridNode.appendContextMenuItems(contextMenu);if(this.dataGrid._refreshCallback&&(!gridNode||gridNode!==this.placeholderNode)) contextMenu.appendItem(WI.UIString("Refresh"),this._refreshCallback.bind(this));if(gridNode){if(gridNode.selectable&&gridNode.copyable&&!gridNode.isEventWithinDisclosureTriangle(event)){contextMenu.appendItem(WI.UIString("Copy Row"),this._copyRow.bind(this,gridNode));contextMenu.appendItem(WI.UIString("Copy Table"),this._copyTable.bind(this));if(this.dataGrid._afterEditCallback){if(gridNode===this.placeholderNode) contextMenu.appendItem(WI.UIString("Add New"),this._startEditing.bind(this,event.target));else if(gridNode.editable){let element=event.target.closest("td");let columnIdentifier=element.__columnIdentifier;let columnTitle=this.dataGrid.columns.get(columnIdentifier)["title"];contextMenu.appendItem(WI.UIString("Edit %s").format(columnTitle),this._startEditing.bind(this,event.target));}} if(this.dataGrid._deleteCallback&&gridNode!==this.placeholderNode&&gridNode.editable) contextMenu.appendItem(WI.UIString("Delete"),this._deleteCallback.bind(this,gridNode));} if(gridNode.children.some((child)=>child.hasChildren)||(gridNode.hasChildren&&!gridNode.children.length)){contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Expand All"),gridNode.expandRecursively.bind(gridNode));contextMenu.appendItem(WI.UIString("Collapse All"),gridNode.collapseRecursively.bind(gridNode));}}} _clickInDataTable(event) {var gridNode=this.dataGridNodeFromNode(event.target);if(!gridNode||!gridNode.hasChildren) return;if(!gridNode.isEventWithinDisclosureTriangle(event)) return;if(gridNode.expanded){if(event.altKey) gridNode.collapseRecursively();else gridNode.collapse();}else{if(event.altKey) gridNode.expandRecursively();else gridNode.expand();}} textForDataGridNodeColumn(node,columnIdentifier) {var data=node.data[columnIdentifier];return(data instanceof Node?data.textContent:data)||"";} _copyTextForDataGridNode(node) {let fields=node.dataGrid.orderedColumns.map((identifier)=>{let text=this.textForDataGridNodeColumn(node,identifier);if(this._copyCallback) text=this._copyCallback(node,identifier,text);return text;});return fields.join(this._copyTextDelimiter);} _copyTextForDataGridHeaders() {let fields=this.orderedColumns.map((identifier)=>this.headerTableHeader(identifier).textContent);return fields.join(this._copyTextDelimiter);} handleBeforeCopyEvent(event) {if(this.selectedNode&&window.getSelection().isCollapsed) event.preventDefault();} handleCopyEvent(event) {if(!window.getSelection().isCollapsed) return;let copyData=[];for(let dataGridNode of this.selectedDataGridNodes){if(!dataGridNode.copyable||dataGridNode.isPlaceholderNode) continue;copyData.push(this._copyTextForDataGridNode(dataGridNode));} if(!copyData.length) return;event.clipboardData.setData("text/plain",copyData.join("\n"));event.stopPropagation();event.preventDefault();} _copyRow(dataGridNode) {if(!dataGridNode.copyable||dataGridNode.isPlaceholderNode) return;let copyText=this._copyTextForDataGridNode(dataGridNode);InspectorFrontendHost.copyText(copyText);} _copyTable() {let copyData=[];copyData.push(this._copyTextForDataGridHeaders());for(let dataGridNode of this._rows){if(!dataGridNode.copyable||dataGridNode.isPlaceholderNode) continue;copyData.push(this._copyTextForDataGridNode(dataGridNode));} if(!copyData.length) return;InspectorFrontendHost.copyText(copyData.join("\n"));} _hasCopyableData() {const skipHidden=true;const stayWithin=null;const dontPopulate=true;let dataGridNode=this._rows[0];while(dataGridNode&&(!dataGridNode.selectable||!dataGridNode.copyable||dataGridNode.isPlaceholderNode)) dataGridNode=dataGridNode.traverseNextNode(skipHidden,stayWithin,dontPopulate);return!!dataGridNode;} resizerDragStarted(resizer) {if(!resizer[WI.DataGrid.NextColumnOrdinalSymbol]) return true;this._currentResizer=resizer;} resizerDragging(resizer,positionDelta) {if(resizer!==this._currentResizer) return;let isRTL=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL;if(isRTL) positionDelta*=-1;let dragPoint=0;if(isRTL) dragPoint+=this.element.totalOffsetRight-resizer.initialPosition-positionDelta;else dragPoint+=resizer.initialPosition-this.element.totalOffsetLeft-positionDelta; var leftColumnIndex=resizer[WI.DataGrid.PreviousColumnOrdinalSymbol];var rightColumnIndex=resizer[WI.DataGrid.NextColumnOrdinalSymbol];var firstRowCells=this._headerTableBodyElement.rows[0].cells;let leadingEdgeOfPreviousColumn=0;for(let i=0;inode.refresh());} updateLayout() {} createCell(columnIdentifier) {var cellElement=document.createElement("td");cellElement.className=columnIdentifier+"-column";cellElement.__columnIdentifier=columnIdentifier;var div=cellElement.createChild("div","cell-content");var content=this.createCellContent(columnIdentifier,cellElement);div.append(content);let column=this.dataGrid.columns.get(columnIdentifier);if(column){if(column["aligned"]) cellElement.classList.add(column["aligned"]);if(column["group"]) cellElement.classList.add("column-group-"+column["group"]);if(column["icon"]){let iconElement=document.createElement("div");iconElement.classList.add("icon");iconElement.title=this.generateIconTitle(columnIdentifier);div.insertBefore(iconElement,div.firstChild);}} if(columnIdentifier===this.dataGrid.disclosureColumnIdentifier){cellElement.classList.add("disclosure");if(this.indentPadding){if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL) cellElement.style.setProperty("padding-right",`${this.indentPadding}px`);else cellElement.style.setProperty("padding-left",`${this.indentPadding}px`);}} return cellElement;} createCellContent(columnIdentifier) {if(!(columnIdentifier in this.data)) return zeroWidthSpace;let data=this.data[columnIdentifier];return typeof data==="number"?data.maxDecimals(2).toLocaleString():data;} generateIconTitle(columnIdentifier) {return"";} elementWithColumnIdentifier(columnIdentifier) {if(!this.dataGrid) return null;let index=this.dataGrid.orderedColumns.indexOf(columnIdentifier);if(index===-1) return null;return this.element.children[index];} appendChild(){return WI.DataGrid.prototype.appendChild.apply(this,arguments);} insertChild(){return WI.DataGrid.prototype.insertChild.apply(this,arguments);} removeChild(){return WI.DataGrid.prototype.removeChild.apply(this,arguments);} removeChildren(){return WI.DataGrid.prototype.removeChildren.apply(this,arguments);} _recalculateSiblings(myIndex) {if(!this.parent) return;var previousChild=myIndex>0?this.parent.children[myIndex-1]:null;if(previousChild){previousChild.nextSibling=this;this.previousSibling=previousChild;}else this.previousSibling=null;var nextChild=this.parent.children[myIndex+1];if(nextChild){nextChild.previousSibling=this;this.nextSibling=nextChild;}else this.nextSibling=null;} collapse() {if(this._element) this._element.classList.remove("expanded");this._expanded=false;for(var i=0;i=start&&event.pageX<=start+this.disclosureToggleWidth;} _attach() {if(!this.dataGrid||this._attached) return;this._attached=true;let insertionIndex=-1;if(!this.isPlaceholderNode){let previousGridNode=this.traversePreviousNode(true,true);if(previousGridNode){insertionIndex=this.dataGrid._rows.lastIndexOf(previousGridNode)+1;}else insertionIndex=0;} if(insertionIndex===-1) this.dataGrid._rows.push(this);else this.dataGrid._rows.insertAtIndex(this,insertionIndex);this.dataGrid._noteRowsChanged();if(this.expanded){for(var i=0;ithis._truncatedDisplayNameLength) truncatedDisplayName=truncatedDisplayName.substring(0,this._truncatedDisplayNameLength)+ellipsis;this._titleContentElement.textContent=truncatedDisplayName;if(this.hideTooltip) this._element.title="";else this._element.title=this._tooltip;} _updateSelectElement() {this._selectElement.removeChildren();function createOption(component) {let optionElement=document.createElement("option");let maxPopupMenuLength=130; optionElement.textContent=component.displayName.length<=maxPopupMenuLength?component.displayName:component.displayName.substring(0,maxPopupMenuLength)+ellipsis;optionElement._pathComponent=component;return optionElement;} let previousSiblingCount=0;let sibling=this.previousSibling;while(sibling){this._selectElement.insertBefore(createOption(sibling),this._selectElement.firstChild);sibling=sibling.previousSibling;++previousSiblingCount;} this._selectElement.appendChild(createOption(this));sibling=this.nextSibling;while(sibling){this._selectElement.appendChild(createOption(sibling));sibling=sibling.nextSibling;} this._selectElement.selectedIndex=previousSiblingCount;} _selectElementMouseOver(event) {if(typeof this.mouseOver==="function") this.mouseOver();} _selectElementMouseOut(event) {if(typeof this.mouseOut==="function") this.mouseOut();} _selectElementMouseDown(event) {this._updateSelectElement();if(this._selectElement.options.length===1){event.preventDefault();this._selectElementSelectionChanged();}} _selectElementMouseUp(event) {this.dispatchEventToListeners(WI.HierarchicalPathComponent.Event.Clicked,{pathComponent:this.selectedPathComponent});} _selectElementSelectionChanged(event) {this.dispatchEventToListeners(WI.HierarchicalPathComponent.Event.SiblingWasSelected,{pathComponent:this.selectedPathComponent});}};WI.HierarchicalPathComponent.MinimumWidth=32;WI.HierarchicalPathComponent.MinimumWidthCollapsed=24;WI.HierarchicalPathComponent.MinimumWidthForOneCharacterTruncatedTitle=54;WI.HierarchicalPathComponent.SelectorArrowsWidth=12;WI.HierarchicalPathComponent.Event={SiblingWasSelected:"hierarchical-path-component-sibling-was-selected",Clicked:"hierarchical-path-component-clicked"};WI.NavigationItem=class NavigationItem extends WI.Object {constructor(identifier,role,label) {super();this._identifier=identifier||null;this._element=document.createElement("div");this._hidden=false;this._parentNavigationBar=null;this._visibilityPriority=WI.NavigationItem.VisibilityPriority.Normal;this._cachedWidth=NaN;if(label) this._element.setAttribute("aria-label",label);this._element.classList.add(...this._classNames);this._element.role=role;this._element.navigationItem=this;} get identifier(){return this._identifier;} get element(){return this._element;} get minimumWidth(){return this.width;} get parentNavigationBar(){return this._parentNavigationBar;} get width() {if(isNaN(this._cachedWidth)) this._cachedWidth=this._element.realOffsetWidth+this.totalMargin;return this._cachedWidth;} get visibilityPriority(){return this._visibilityPriority;} set visibilityPriority(priority){this._visibilityPriority=priority;} update(options={}) {this._cachedWidth=NaN;} get hidden() {return this._hidden;} set hidden(flag) {if(this._hidden===flag) return;this._hidden=flag;this._element.classList.toggle("hidden",flag);if(this._parentNavigationBar) this._parentNavigationBar.needsLayout();} get tooltip() {return this.element.title;} set tooltip(x) {this.element.title=x;} get totalMargin() {return 0;} didAttach(navigationBar) {this._parentNavigationBar=navigationBar;} didDetach() {this._cachedWidth=NaN;this._parentNavigationBar=null;} get _classNames() {var classNames=["item"];if(this._identifier) classNames.push(this._identifier);if(Array.isArray(this.additionalClassNames)) classNames.pushAll(this.additionalClassNames);return classNames;}};WI.NavigationItem.VisibilityPriority={Low:-100,Normal:0,High:100,};WI.Popover=class Popover extends WI.Object {constructor(delegate) {super();this.delegate=delegate;this._edge=null;this._frame=new WI.Rect;this._content=null;this._targetFrame=new WI.Rect;this._anchorPoint=new WI.Point;this._preferredEdges=null;this._resizeHandler=null;this._contentNeedsUpdate=false;this._dismissing=false;this._element=document.createElement("div");this._element.className="popover";this._element.addEventListener("transitionend",this,true);this._container=this._element.appendChild(document.createElement("div"));this._container.className="container";this._backgroundCanvasContext=null;this._drawBackgroundAnimationIdentifier=undefined;} get element(){return this._element;} get visible() {return this._element.parentNode===document.body&&!this._element.classList.contains(WI.Popover.FadeOutClassName);} get frame() {return this._frame;} set frame(frame) {this._element.style.left=frame.minX()+"px";this._element.style.top=frame.minY()+"px";this._element.style.width=frame.size.width+"px";this._element.style.height=frame.size.height+"px";this._element.style.backgroundSize=frame.size.width+"px "+frame.size.height+"px";this._frame=frame;} set content(content) {if(content===this._content) return;this._content=content;this._contentNeedsUpdate=true;if(this.visible) this._update(true);} set windowResizeHandler(resizeHandler) {this._resizeHandler=resizeHandler;} resize() {if(this.visible&&this._resizeHandler) this._resizeHandler();} update(shouldAnimate=true) {if(!this.visible) return;var previouslyFocusedElement=document.activeElement;this._contentNeedsUpdate=true;this._update(shouldAnimate);if(previouslyFocusedElement) previouslyFocusedElement.focus();} present(targetFrame,preferredEdges,{updateContent,shouldAnimate}={}) {this._targetFrame=targetFrame;this._preferredEdges=preferredEdges;if(!this._content) return;this._addListenersIfNeeded();if(updateContent&&this.visible) this.update(shouldAnimate);else this._update(shouldAnimate);} presentNewContentWithFrame(content,targetFrame,preferredEdges) {this._content=content;this._contentNeedsUpdate=true;this._targetFrame=targetFrame;this._preferredEdges=preferredEdges;this._addListenersIfNeeded();var shouldAnimate=this.visible;this._update(shouldAnimate);} dismiss() {if(this._dismissing||this._element.parentNode!==document.body) return;this._dismissing=true;this._isListeningForPopoverEvents=false;window.removeEventListener("mousedown",this,true);window.removeEventListener("scroll",this,true);window.removeEventListener("resize",this,true);window.removeEventListener("keypress",this,true);WI.tabBrowser.contentViewContainer.removeEventListener(WI.ContentViewContainer.Event.CurrentContentViewDidChange,this.dismiss,this);this._prefersDarkColorSchemeMediaQueryList.removeListener(this._boundUpdate);WI.quickConsole.keyboardShortcutDisabled=false;this._element.classList.add(WI.Popover.FadeOutClassName);if(this.delegate&&typeof this.delegate.willDismissPopover==="function") this.delegate.willDismissPopover(this);WI.Popover._visibleInstance=null;} handleEvent(event) {switch(event.type){case"mousedown":case"scroll":if(!this._element.contains(event.target)&&!event.target.closest("."+WI.Popover.IgnoreAutoDismissClassName)&&!event[WI.Popover.EventPreventDismissSymbol]){this.dismiss();} break;case"resize":this.resize();break;case"keypress":if(event.keyCode===WI.KeyboardShortcut.Key.Escape.keyCode) this.dismiss();break;case"transitionend":if(event.target===this._element){document.body.removeChild(this._element);this._element.classList.remove(WI.Popover.FadeOutClassName);this._container.textContent="";if(this.delegate&&typeof this.delegate.didDismissPopover==="function") this.delegate.didDismissPopover(this);this._dismissing=false;if(this._backgroundCanvasContext){WI.Popover._backgroundCanvasContexts.push(new WeakRef(this._backgroundCanvasContext));this._backgroundCanvasContext=null;} break;} break;}} _update(shouldAnimate) {if(WI.Popover._visibleInstance!==this){WI.Popover._visibleInstance?.dismiss();WI.Popover._visibleInstance=this;} if(shouldAnimate) var previousEdge=this._edge;var targetFrame=this._targetFrame;var preferredEdges=this._preferredEdges; if(this._element.parentNode!==document.body) document.body.appendChild(this._element);else this._element.classList.remove(WI.Popover.FadeOutClassName);this._dismissing=false;if(this._edge!==null) this._element.classList.remove(this._cssClassNameForEdge());if(this._contentNeedsUpdate){this._element.style.removeProperty("left");this._element.style.removeProperty("top");this._element.style.removeProperty("width");this._element.style.removeProperty("height");this._container.replaceWith(this._content);var popoverBounds=this._element.getBoundingClientRect();this._preferredSize=new WI.Size(Math.ceil(popoverBounds.width),Math.ceil(popoverBounds.height));} var titleBarOffset=WI.undockedTitleAreaHeight();var containerFrame=new WI.Rect(0,titleBarOffset,window.innerWidth,window.innerHeight-titleBarOffset);containerFrame=containerFrame.inset(WI.Popover.ShadowEdgeInsets);var metrics=new Array(preferredEdges.length);for(var edgeName in WI.RectEdge){var edge=WI.RectEdge[edgeName];var item={edge,metrics:this._bestMetricsForEdge(this._preferredSize,targetFrame,containerFrame,edge)};var preferredIndex=preferredEdges.indexOf(edge);if(preferredIndex!==-1) metrics[preferredIndex]=item;else metrics.push(item);} function area(size) {return Math.max(0,size.width)*Math.max(0,size.height);} var bestEdge=metrics[0].edge;var bestMetrics=metrics[0].metrics;for(var i=1;iarea(bestMetrics.contentSize)){bestEdge=metrics[i].edge;bestMetrics=itemMetrics;}} var anchorPoint;var bestFrame=bestMetrics.frame.round();this._edge=bestEdge;if(bestFrame===WI.Rect.ZERO_RECT){this.dismiss();}else{switch(bestEdge){case WI.RectEdge.MIN_X:anchorPoint=new WI.Point(bestFrame.size.width-WI.Popover.ShadowPadding,targetFrame.midY()-bestFrame.minY());break;case WI.RectEdge.MAX_X:anchorPoint=new WI.Point(WI.Popover.ShadowPadding,targetFrame.midY()-bestFrame.minY());break;case WI.RectEdge.MIN_Y:anchorPoint=new WI.Point(targetFrame.midX()-bestFrame.minX(),bestFrame.size.height-WI.Popover.ShadowPadding);break;case WI.RectEdge.MAX_Y:anchorPoint=new WI.Point(targetFrame.midX()-bestFrame.minX(),WI.Popover.ShadowPadding);break;} this._element.classList.add(this._cssClassNameForEdge());if(shouldAnimate&&this._edge===previousEdge) this._animateFrame(bestFrame,anchorPoint);else{this.frame=bestFrame;this._setAnchorPoint(anchorPoint);this._drawBackground();} if(this._preferredSize.width{this._backgroundCanvasContext.save();callback();this._backgroundCanvasContext.restore();};isolate(()=>{this._backgroundCanvasContext.scale(scaleFactor,scaleFactor);this._drawFrame(bounds);isolate(()=>{this._backgroundCanvasContext.shadowBlur=4;this._backgroundCanvasContext.shadowColor=computedStyle.getPropertyValue("--popover-shadow-color").trim();this._backgroundCanvasContext.strokeStyle=computedStyle.getPropertyValue("--popover-border-color").trim();this._backgroundCanvasContext.lineWidth=2;this._backgroundCanvasContext.stroke();});isolate(()=>{this._backgroundCanvasContext.fillStyle=computedStyle.getPropertyValue("--popover-background-color").trim();this._backgroundCanvasContext.fill();});});this._element.appendChild(this._backgroundCanvasContext.canvas);} _bestMetricsForEdge(preferredSize,targetFrame,containerFrame,edge) {var x,y;var width=preferredSize.width+(WI.Popover.ShadowPadding*2)+(WI.Popover.ContentPadding*2);var height=preferredSize.height+(WI.Popover.ShadowPadding*2)+(WI.Popover.ContentPadding*2);switch(edge){case WI.RectEdge.MIN_X:width+=WI.Popover.AnchorSize;x=targetFrame.origin.x-width+WI.Popover.ShadowPadding;y=targetFrame.origin.y-(height-targetFrame.size.height)/2;break;case WI.RectEdge.MAX_X:width+=WI.Popover.AnchorSize;x=targetFrame.origin.x+targetFrame.size.width-WI.Popover.ShadowPadding;y=targetFrame.origin.y-(height-targetFrame.size.height)/2;break;case WI.RectEdge.MIN_Y:height+=WI.Popover.AnchorSize;x=targetFrame.origin.x-(width-targetFrame.size.width)/2;y=targetFrame.origin.y-height+WI.Popover.ShadowPadding;break;case WI.RectEdge.MAX_Y:height+=WI.Popover.AnchorSize;x=targetFrame.origin.x-(width-targetFrame.size.width)/2;y=targetFrame.origin.y+targetFrame.size.height-WI.Popover.ShadowPadding;break;} if(edge!==WI.RectEdge.MIN_X&&xcontainerFrame.maxX()) x=containerFrame.maxX()-width;if(edge!==WI.RectEdge.MIN_Y&&ycontainerFrame.maxY()) y=containerFrame.maxY()-height;var preferredFrame=new WI.Rect(x,y,width,height);var bestFrame=preferredFrame.intersectionWithRect(containerFrame);width=bestFrame.size.width-(WI.Popover.ShadowPadding*2);height=bestFrame.size.height-(WI.Popover.ShadowPadding*2);switch(edge){case WI.RectEdge.MIN_X:case WI.RectEdge.MAX_X:width-=WI.Popover.AnchorSize;break;case WI.RectEdge.MIN_Y:case WI.RectEdge.MAX_Y:height-=WI.Popover.AnchorSize;break;} return{frame:bestFrame,contentSize:new WI.Size(width,height)};} _drawFrame(bounds) {let cornerRadius=WI.Popover.CornerRadius;let anchorPointX=this._anchorPoint.x;let anchorPointY=this._anchorPoint.y;let arrowPadding=cornerRadius+WI.Popover.AnchorSize;if(this._edge===WI.RectEdge.MIN_Y||this._edge===WI.RectEdge.MAX_Y) anchorPointX=Number.constrain(anchorPointX,bounds.minX()+arrowPadding,bounds.maxX()-arrowPadding);else anchorPointY=Number.constrain(anchorPointY,bounds.minY()+arrowPadding,bounds.maxY()-arrowPadding);this._backgroundCanvasContext.beginPath();switch(this._edge){case WI.RectEdge.MIN_X:this._backgroundCanvasContext.moveTo(bounds.maxX(),bounds.minY()+cornerRadius);this._backgroundCanvasContext.lineTo(bounds.maxX(),anchorPointY-WI.Popover.AnchorSize);this._backgroundCanvasContext.lineTo(anchorPointX,anchorPointY);this._backgroundCanvasContext.lineTo(bounds.maxX(),anchorPointY+WI.Popover.AnchorSize);this._backgroundCanvasContext.arcTo(bounds.maxX(),bounds.maxY(),bounds.minX(),bounds.maxY(),cornerRadius);this._backgroundCanvasContext.arcTo(bounds.minX(),bounds.maxY(),bounds.minX(),bounds.minY(),cornerRadius);this._backgroundCanvasContext.arcTo(bounds.minX(),bounds.minY(),bounds.maxX(),bounds.minY(),cornerRadius);this._backgroundCanvasContext.arcTo(bounds.maxX(),bounds.minY(),bounds.maxX(),bounds.maxY(),cornerRadius);break;case WI.RectEdge.MAX_X:this._backgroundCanvasContext.moveTo(bounds.minX(),bounds.maxY()-cornerRadius);this._backgroundCanvasContext.lineTo(bounds.minX(),anchorPointY+WI.Popover.AnchorSize);this._backgroundCanvasContext.lineTo(anchorPointX,anchorPointY);this._backgroundCanvasContext.lineTo(bounds.minX(),anchorPointY-WI.Popover.AnchorSize);this._backgroundCanvasContext.arcTo(bounds.minX(),bounds.minY(),bounds.maxX(),bounds.minY(),cornerRadius);this._backgroundCanvasContext.arcTo(bounds.maxX(),bounds.minY(),bounds.maxX(),bounds.maxY(),cornerRadius);this._backgroundCanvasContext.arcTo(bounds.maxX(),bounds.maxY(),bounds.minX(),bounds.maxY(),cornerRadius);this._backgroundCanvasContext.arcTo(bounds.minX(),bounds.maxY(),bounds.minX(),bounds.minY(),cornerRadius);break;case WI.RectEdge.MIN_Y:this._backgroundCanvasContext.moveTo(bounds.maxX()-cornerRadius,bounds.maxY());this._backgroundCanvasContext.lineTo(anchorPointX+WI.Popover.AnchorSize,bounds.maxY());this._backgroundCanvasContext.lineTo(anchorPointX,anchorPointY);this._backgroundCanvasContext.lineTo(anchorPointX-WI.Popover.AnchorSize,bounds.maxY());this._backgroundCanvasContext.arcTo(bounds.minX(),bounds.maxY(),bounds.minX(),bounds.minY(),cornerRadius);this._backgroundCanvasContext.arcTo(bounds.minX(),bounds.minY(),bounds.maxX(),bounds.minY(),cornerRadius);this._backgroundCanvasContext.arcTo(bounds.maxX(),bounds.minY(),bounds.maxX(),bounds.maxY(),cornerRadius);this._backgroundCanvasContext.arcTo(bounds.maxX(),bounds.maxY(),bounds.minX(),bounds.maxY(),cornerRadius);break;case WI.RectEdge.MAX_Y:this._backgroundCanvasContext.moveTo(bounds.minX()+cornerRadius,bounds.minY());this._backgroundCanvasContext.lineTo(anchorPointX-WI.Popover.AnchorSize,bounds.minY());this._backgroundCanvasContext.lineTo(anchorPointX,anchorPointY);this._backgroundCanvasContext.lineTo(anchorPointX+WI.Popover.AnchorSize,bounds.minY());this._backgroundCanvasContext.arcTo(bounds.maxX(),bounds.minY(),bounds.maxX(),bounds.maxY(),cornerRadius);this._backgroundCanvasContext.arcTo(bounds.maxX(),bounds.maxY(),bounds.minX(),bounds.maxY(),cornerRadius);this._backgroundCanvasContext.arcTo(bounds.minX(),bounds.maxY(),bounds.minX(),bounds.minY(),cornerRadius);this._backgroundCanvasContext.arcTo(bounds.minX(),bounds.minY(),bounds.maxX(),bounds.minY(),cornerRadius);break;} this._backgroundCanvasContext.closePath();} _addListenersIfNeeded() {if(!this._isListeningForPopoverEvents){this._isListeningForPopoverEvents=true;window.addEventListener("mousedown",this,true);window.addEventListener("scroll",this,true);window.addEventListener("resize",this,true);window.addEventListener("keypress",this,true);WI.tabBrowser.contentViewContainer.addEventListener(WI.ContentViewContainer.Event.CurrentContentViewDidChange,this.dismiss,this);if(!this._boundUpdate) this._boundUpdate=this._update.bind(this);if(!this._prefersDarkColorSchemeMediaQueryList) this._prefersDarkColorSchemeMediaQueryList=window.matchMedia("(prefers-color-scheme: dark)");this._prefersDarkColorSchemeMediaQueryList.addListener(this._boundUpdate);WI.quickConsole.keyboardShortcutDisabled=true;}}};WI.Popover._visibleInstance=null;WI.Popover._backgroundCanvasContexts=[];WI.Popover.FadeOutClassName="fade-out";WI.Popover.CornerRadius=5;WI.Popover.MinWidth=40;WI.Popover.MinHeight=40;WI.Popover.ShadowPadding=5;WI.Popover.ContentPadding=5;WI.Popover.AnchorSize=11;WI.Popover.ShadowEdgeInsets=new WI.EdgeInsets(WI.Popover.ShadowPadding);WI.Popover.IgnoreAutoDismissClassName="popover-ignore-auto-dismiss";WI.Popover.EventPreventDismissSymbol=Symbol("popover-event-prevent-dismiss");WI.Sidebar=class Sidebar extends WI.View {constructor(element,side,label) {super(element);this._side=side;this._collapsed=true;this._collapsable=true;this.element.classList.add("sidebar",this._side,WI.Sidebar.CollapsedStyleClassName);this.element.setAttribute("role","group");if(label) this.element.setAttribute("aria-label",label);this._sidebarPanels=[];this._selectedSidebarPanel=null;this._heightResizer=new WI.Resizer(WI.Resizer.RuleOrientation.Horizontal,this);this.element.insertBefore(this._heightResizer.element,this.element.firstChild);this.canMoveToBottom=false;this._didMoveToBottom=false;} get sidebarPanels(){return this._sidebarPanels;} get side(){return this._side;} addSidebarPanel(sidebarPanel) {this.insertSidebarPanel(sidebarPanel,this.sidebarPanels.length);} insertSidebarPanel(sidebarPanel,index) {if(!(sidebarPanel instanceof WI.SidebarPanel)) return;if(!this.shouldInsertSidebarPanel(sidebarPanel,index)) return;this._sidebarPanels.splice(index,0,sidebarPanel);this.didInsertSidebarPanel(sidebarPanel,index);} removeSidebarPanel(sidebarPanelOrIdentifierOrIndex) {let sidebarPanel=this._findSidebarPanel(sidebarPanelOrIdentifierOrIndex);if(!sidebarPanel) return;this._sidebarPanels.remove(sidebarPanel);if(this.selectedSidebarPanel===sidebarPanel) this.selectedSidebarPanel=0;this.didRemoveSidebarPanel(sidebarPanel);} get selectedSidebarPanel() {return this._selectedSidebarPanel;} set selectedSidebarPanel(sidebarPanelOrIdentifierOrIndex) {let sidebarPanel=this._findSidebarPanel(sidebarPanelOrIdentifierOrIndex);if(!sidebarPanel) sidebarPanel=this._findSidebarPanel(0);if(this._selectedSidebarPanel===sidebarPanel) return;this.willSetSelectedSidebarPanel(sidebarPanel);this._selectedSidebarPanel=sidebarPanel;this.didSetSelectedSidebarPanel(sidebarPanel);this.dispatchEventToListeners(WI.Sidebar.Event.SidebarPanelSelected);} get collapsed() {return this._collapsed;} set collapsed(flag) {if(flag===this._collapsed) return;if(flag&&!this._collapsable) return;this._collapsed=flag||false;this.element.classList.toggle(WI.Sidebar.CollapsedStyleClassName);this.didSetCollapsed();this.dispatchEventToListeners(WI.Sidebar.Event.CollapsedStateDidChange);} get collapsable() {return this._collapsable;} set collapsable(allow){if(allow===this._collapsable) return;this._collapsable=!!allow;if(!allow&&this.collapsed) this.collapsed=false;} get minimumWidth() {let minimumWidth=WI.Sidebar.AbsoluteMinimumWidth;if(this.selectedSidebarPanel) minimumWidth=Math.max(minimumWidth,this.selectedSidebarPanel.minimumWidth);return minimumWidth;} get maximumWidth() {return WI.getMaximumSidebarWidth(this);} get height() {return this.element.offsetHeight;} set height(newHeight) {if(newHeight===this.height) return;if(WI.layoutMode===WI.LayoutMode.Narrow) this._recalculateHeight(newHeight);} shouldInsertSidebarPanel(sidebarPanel,index) {return true;} didInsertSidebarPanel(sidebarPanel,index) {} didRemoveSidebarPanel(sidebarPanel) {} willSetSelectedSidebarPanel(sidebarPanel) {} didSetSelectedSidebarPanel(sidebarPanel) {} didSetCollapsed(flag) {} sizeDidChange() {super.sizeDidChange();if(this._side!==WI.Sidebar.Sides.Trailing||!this.canMoveToBottom) return;if(WI.layoutMode===WI.LayoutMode.Narrow&&!this._didMoveToBottom){this._didMoveToBottom=true;this.element.style.width="";this.dispatchEventToListeners(WI.Sidebar.Event.PositionDidChange);}else if(WI.layoutMode!==WI.LayoutMode.Narrow&&this._didMoveToBottom){this._didMoveToBottom=false;this.element.style.height="";this.dispatchEventToListeners(WI.Sidebar.Event.PositionDidChange);}} resizerDragStarted(resizer) {if(resizer!==this._heightResizer) return;this._heightBeforeResize=this.height;} resizerDragging(resizer,positionDelta) {if(resizer!==this._heightResizer) return;this.height=positionDelta+this._heightBeforeResize;} resizerDragEnded(resizer) {if(resizer!==this._heightResizer||this._heightBeforeResize===this.width) return;this.updateLayout(WI.View.LayoutReason.Resize);} _findSidebarPanel(sidebarPanelOrIdentifierOrIndex) {let sidebarPanel=null;if(sidebarPanelOrIdentifierOrIndex instanceof WI.SidebarPanel){if(this._sidebarPanels.includes(sidebarPanelOrIdentifierOrIndex)) sidebarPanel=sidebarPanelOrIdentifierOrIndex;}else if(typeof sidebarPanelOrIdentifierOrIndex==="number"){sidebarPanel=this._sidebarPanels[sidebarPanelOrIdentifierOrIndex];}else if(typeof sidebarPanelOrIdentifierOrIndex==="string"){sidebarPanel=this._sidebarPanels.find((existingSidebarPanel)=>existingSidebarPanel.identifier===sidebarPanelOrIdentifierOrIndex)||null;} return sidebarPanel;} _recalculateHeight(newHeight) {newHeight=Math.ceil(Number.constrain(newHeight,this.minimumHeight+1,WI.getMaximumSidebarHeight(this)));this.element.style.height=`${newHeight}px`;if(this.collapsed) return;this.needsLayout(WI.View.LayoutReason.Resize);this.dispatchEventToListeners(WI.Sidebar.Event.HeightDidChange,{newHeight});}};WI.Sidebar.CollapsedStyleClassName="collapsed";WI.Sidebar.AbsoluteMinimumWidth=250;WI.Sidebar.AbsoluteMinimumHeight=200;WI.Sidebar.Sides={Leading:"leading",Trailing:"trailing",};WI.Sidebar.Event={SidebarPanelSelected:"sidebar-panel-selected",CollapsedStateDidChange:"sidebar-collapsed-state-did-change",WidthDidChange:"sidebar-width-did-change",HeightDidChange:"sidebar-height-did-change",PositionDidChange:"sidebar-position-did-change",};WI.SidebarPanel=class SidebarPanel extends WI.View {constructor(identifier,displayName) {super();this._identifier=identifier;this._displayName=displayName;this._selected=false;this._exclusive=false;this._savedScrollPosition=0;this.element.classList.add("panel",identifier);this.element.setAttribute("role","group");this.element.setAttribute("aria-label",displayName);this._contentView=new WI.View;this._contentView.element.classList.add("content");this.addSubview(this._contentView);} get identifier() {return this._identifier;} get contentView() {return this._contentView;} get displayName() {return this._displayName;} get visible() {return this.selected&&this.parentSidebar&&!this.parentSidebar.collapsed;} get selected() {return this._selected;} set selected(flag) {if(flag===this._selected) return;this._selected=flag||false;this.element.classList.toggle("selected",this._selected);} get parentSidebar() {return this.parentView;} get minimumWidth() {return 0;} get exclusive() {return this._exclusive;} set exclusive(exclusive) {if(exclusive===this._exclusive) return;this._exclusive=!!exclusive;this.element.classList.toggle("exclusive-presentation",this._exclusive);} get allowExclusivePresentation() {return false;} attached() {super.attached();this.scrollElement.scrollTop=this._savedScrollPosition;} detached() {this._savedScrollPosition=this.scrollElement.scrollTop;super.detached();} get scrollElement() {return this.contentView.element;}};WI.TabBar=class TabBar extends WI.View {constructor(element) {super(element);this.element.classList.add("tab-bar");this.element.addEventListener("mousedown",this._handleMouseDown.bind(this));this.element.createChild("div","border top");const navigationBarBeforeElement=null;this._navigationBarBefore=new WI.NavigationBar(navigationBarBeforeElement,{sizesToFit:true});this.addSubview(this._navigationBarBefore);this._tabContainer=this.element.appendChild(document.createElement("div"));this._tabContainer.className="tabs";this._tabContainer.setAttribute("role","tablist");this._tabContainer.addEventListener("mousedown",this._handleTabContainerMouseDown.bind(this));this._tabContainer.addEventListener("mouseleave",this._handleTabContainerMouseLeave.bind(this));this._tabContainer.addEventListener("contextmenu",this._handleTabContainerContextMenu.bind(this));const navigationBarAfterElement=null;this._navigationBarAfter=new WI.NavigationBar(navigationBarAfterElement,{sizesToFit:true});this.addSubview(this._navigationBarAfter);this.element.createChild("div","border bottom");this._tabBarItems=[];this._hiddenTabBarItems=[];const showHiddenTabsRepresentedObject=null;const showHiddenTabsDisplayName=null;this._showHiddenTabsTabBarItem=new WI.PinnedTabBarItem(showHiddenTabsRepresentedObject,"Images/Overflow.svg",showHiddenTabsDisplayName,WI.UIString("Show hidden tabs\u2026"));this._showHiddenTabsTabBarItem.hidden=true;this.addTabBarItem(this._showHiddenTabsTabBarItem,{suppressAnimations:true});const openClosedTabsRepresentedObject=null;const openClosedTabsDisplayName=null;this._openClosedTabsTabBarItem=new WI.PinnedTabBarItem(openClosedTabsRepresentedObject,"Images/Plus15.svg",openClosedTabsDisplayName,WI.UIString("Open closed tabs\u2026"));this._openClosedTabsTabBarItem.hidden=true;this.addTabBarItem(this._openClosedTabsTabBarItem,{suppressAnimations:true});this._mouseDownPageX=NaN;this._isDragging=false;} addNavigationItemBefore(navigationItem) {this._navigationBarBefore.addNavigationItem(navigationItem);this.needsLayout();} addNavigationItemAfter(navigationItem) {this._navigationBarAfter.addNavigationItem(navigationItem);this.needsLayout();} addTabBarItem(tabBarItem,options={}) {return this.insertTabBarItem(tabBarItem,this._tabBarItems.length,options);} insertTabBarItem(tabBarItem,index,options={}) {if(!(tabBarItem instanceof WI.TabBarItem)) return null;if(tabBarItem.parentTabBar===this) return null;if(this._tabAnimatedClosedSinceMouseEnter){this._finishExpandingTabsAfterClose().then(()=>{this.insertTabBarItem(tabBarItem,index,options);});return null;} if(tabBarItem.parentTabBar) tabBarItem.parentTabBar.removeTabBarItem(tabBarItem);tabBarItem.parentTabBar=this;if(tabBarItem instanceof WI.GeneralTabBarItem) index=Number.constrain(index,0,this.normalTabCount);else index=Number.constrain(index,this.normalTabCount,this._tabBarItems.length);if(this._tabContainer.classList.contains("animating")){requestAnimationFrame(removeStyles.bind(this));options.suppressAnimations=true;} var beforeTabSizesAndPositions;if(!options.suppressAnimations) beforeTabSizesAndPositions=this._recordTabBarItemSizesAndPositions();this._tabBarItems.splice(index,0,tabBarItem);let nextSibling=this._tabBarItems[index+1]||this._tabBarItems.lastValue;if(this._tabContainer.contains(nextSibling.element)){if(!(tabBarItem instanceof WI.PinnedTabBarItem)&&nextSibling instanceof WI.PinnedTabBarItem) this._tabContainer.insertBefore(tabBarItem.element,this._pinnedButtons()[0].element);else this._tabContainer.insertBefore(tabBarItem.element,nextSibling.element);}else{if(tabBarItem instanceof WI.PinnedTabBarItem) this._tabContainer.appendChild(tabBarItem.element);else this._tabContainer.insertBefore(tabBarItem.element,this._pinnedButtons()[0].element);} tabBarItem.element.style.left=null;tabBarItem.element.style.width=null;function animateTabs() {this._tabContainer.classList.add("animating");this._tabContainer.classList.add("inserting-tab");this._applyTabBarItemSizesAndPositions(afterTabSizesAndPositions);this._tabContainer.addEventListener("transitionend",removeStylesListener);} function removeStyles() {this._tabContainer.classList.remove("static-layout");this._tabContainer.classList.remove("animating");this._tabContainer.classList.remove("inserting-tab");tabBarItem.element.classList.remove("being-inserted");this._clearTabBarItemSizesAndPositions();this._tabContainer.removeEventListener("transitionend",removeStylesListener);} if(!options.suppressAnimations){var afterTabSizesAndPositions=this._recordTabBarItemSizesAndPositions();this.updateLayout();let tabBarItems=this._tabBarItemsFromLeftToRight();let previousTabBarItem=tabBarItems[tabBarItems.indexOf(tabBarItem)-1]||null;let previousTabBarItemSizeAndPosition=previousTabBarItem?beforeTabSizesAndPositions.get(previousTabBarItem):null;if(previousTabBarItemSizeAndPosition) beforeTabSizesAndPositions.set(tabBarItem,{left:previousTabBarItemSizeAndPosition.left+previousTabBarItemSizeAndPosition.width,width:0});else beforeTabSizesAndPositions.set(tabBarItem,{left:0,width:0});this._tabContainer.classList.add("static-layout");tabBarItem.element.classList.add("being-inserted");this._applyTabBarItemSizesAndPositions(beforeTabSizesAndPositions);var removeStylesListener=removeStyles.bind(this);requestAnimationFrame(animateTabs.bind(this));}else this.needsLayout();this.dispatchEventToListeners(WI.TabBar.Event.TabBarItemAdded,{tabBarItem});return tabBarItem;} removeTabBarItem(tabBarItemOrIndex,options={}) {let tabBarItem=this._findTabBarItem(tabBarItemOrIndex);if(!tabBarItem||tabBarItem instanceof WI.PinnedTabBarItem) return null;if(this.normalTabCount===1) return null;tabBarItem.parentTabBar=null;if(this._selectedTabBarItem===tabBarItem){var index=this._tabBarItems.indexOf(tabBarItem);var nextTabBarItem=this._tabBarItems[index+1];if(!nextTabBarItem||nextTabBarItem instanceof WI.PinnedTabBarItem) nextTabBarItem=this._tabBarItems[index-1];this.selectedTabBarItem=nextTabBarItem;} if(this._tabContainer.classList.contains("animating")){requestAnimationFrame(removeStyles.bind(this));options.suppressAnimations=true;} var beforeTabSizesAndPositions;if(!options.suppressAnimations) beforeTabSizesAndPositions=this._recordTabBarItemSizesAndPositions();let wasLastNormalTab=this._tabBarItems.indexOf(tabBarItem)===this.normalTabCount-1;this._tabBarItems.remove(tabBarItem);tabBarItem.element.remove();this._openClosedTabsTabBarItem.hidden=!this._closedTabClasses().length;if(!this._hasMoreThanOneNormalTab()||wasLastNormalTab||!options.suppressExpansion){if(!options.suppressAnimations){this._tabAnimatedClosedSinceMouseEnter=true;this._finishExpandingTabsAfterClose(beforeTabSizesAndPositions);}else this.needsLayout();this.dispatchEventToListeners(WI.TabBar.Event.TabBarItemRemoved,{tabBarItem});return tabBarItem;} var lastNormalTabBarItem;function animateTabs() {this._tabContainer.classList.add("animating");this._tabContainer.classList.add("closing-tab"); let extraSpaceBetweenNormalAndPinnedTabs=0;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL){extraSpaceBetweenNormalAndPinnedTabs=this._tabContainer.getBoundingClientRect().width;for(let currentTabBarItem of this._tabBarItemsFromLeftToRight()) extraSpaceBetweenNormalAndPinnedTabs-=currentTabBarItem.element.getBoundingClientRect().width;} let left=0;for(let currentTabBarItem of this._tabBarItemsFromLeftToRight()){let sizeAndPosition=beforeTabSizesAndPositions.get(currentTabBarItem);if(!(currentTabBarItem instanceof WI.PinnedTabBarItem)){currentTabBarItem.element.style.left=extraSpaceBetweenNormalAndPinnedTabs+left+"px";left+=sizeAndPosition.width;lastNormalTabBarItem=currentTabBarItem;}else left=sizeAndPosition.left+sizeAndPosition.width;} if(this._selectedTabBarItem) this._selectedTabBarItem.element.style.width=(parseFloat(this._selectedTabBarItem.element.style.width)+1)+"px";if(lastNormalTabBarItem!==this._selectedTabBarItem) lastNormalTabBarItem.element.style.width=(parseFloat(lastNormalTabBarItem.element.style.width)+1)+"px";this._tabContainer.addEventListener("transitionend",removeStylesListener);} function removeStyles() {if(this._selectedTabBarItem&&this._selectedTabBarItem!==lastNormalTabBarItem) this._selectedTabBarItem.element.style.width=(parseFloat(this._selectedTabBarItem.element.style.width)-1)+"px";this._tabContainer.classList.remove("animating");this._tabContainer.classList.remove("closing-tab");this.updateLayout();this._tabContainer.removeEventListener("transitionend",removeStylesListener);} if(!options.suppressAnimations){this._tabContainer.classList.add("static-layout");this._tabAnimatedClosedSinceMouseEnter=true;this._applyTabBarItemSizesAndPositions(beforeTabSizesAndPositions);var removeStylesListener=removeStyles.bind(this);requestAnimationFrame(animateTabs.bind(this));}else this.needsLayout();this.dispatchEventToListeners(WI.TabBar.Event.TabBarItemRemoved,{tabBarItem});return tabBarItem;} selectPreviousTab() {if(this._tabBarItems.length<=1) return;var startIndex=this._tabBarItems.indexOf(this._selectedTabBarItem);var newIndex=startIndex;do{if(newIndex===0) newIndex=this._tabBarItems.length-1;else newIndex--;if(!(this._tabBarItems[newIndex]instanceof WI.PinnedTabBarItem)) break;}while(newIndex!==startIndex);if(newIndex===startIndex) return;this.selectedTabBarItem=this._tabBarItems[newIndex];} selectNextTab() {if(this._tabBarItems.length<=1) return;var startIndex=this._tabBarItems.indexOf(this._selectedTabBarItem);var newIndex=startIndex;do{if(newIndex===this._tabBarItems.length-1) newIndex=0;else newIndex++;if(!(this._tabBarItems[newIndex]instanceof WI.PinnedTabBarItem)) break;}while(newIndex!==startIndex);if(newIndex===startIndex) return;this.selectedTabBarItem=this._tabBarItems[newIndex];} get selectedTabBarItem() {return this._selectedTabBarItem;} set selectedTabBarItem(tabBarItemOrIndex) {this.selectTabBarItem(tabBarItemOrIndex);} selectTabBarItem(tabBarItemOrIndex,options={}) {let tabBarItem=this._findTabBarItem(tabBarItemOrIndex);if(this._pinnedButtons().includes(tabBarItem)){tabBarItem=this._tabBarItems[this.normalTabCount-1];} if(this._selectedTabBarItem===tabBarItem) return;let previousTabBarItem=this._selectedTabBarItem;if(this._selectedTabBarItem) this._selectedTabBarItem.selected=false;this._selectedTabBarItem=tabBarItem||null;if(this._selectedTabBarItem){this._selectedTabBarItem.selected=true;if(this._selectedTabBarItem.hidden) this.needsLayout();} let initiatorHint=options.initiatorHint||WI.TabBrowser.TabNavigationInitiator.Unknown;this.dispatchEventToListeners(WI.TabBar.Event.TabBarItemSelected,{previousTabBarItem,initiatorHint});} get tabBarItems() {return this._tabBarItems;} get visibleTabBarItemsFromLeftToRight() {return this._tabBarItemsFromLeftToRight().filter((item)=>!item.hidden);} get tabCount() {return this._tabBarItems.filter((item)=>item.representedObject instanceof WI.TabContentView).length;} get normalTabCount() {return this._tabBarItems.filter((item)=>!(item instanceof WI.PinnedTabBarItem)).length;} resetCachedWidths() {for(let tabBarItem of this._tabBarItems) tabBarItem[WI.TabBar.CachedWidthSymbol]=0;} layout() {if(this._tabContainer.classList.contains("static-layout")) return;let undocked=WI.dockConfiguration===WI.DockConfiguration.Undocked;function measureWidth(tabBarItem){if(!tabBarItem[WI.TabBar.CachedWidthSymbol]) tabBarItem[WI.TabBar.CachedWidthSymbol]=tabBarItem.element.realOffsetWidth;return tabBarItem[WI.TabBar.CachedWidthSymbol];} let availableSpace=this._tabContainer.realOffsetWidth;this._tabContainer.classList.add("calculate-width");this._hiddenTabBarItems=[];let normalTabBarItems=[];for(let tabBarItem of this._tabBarItemsFromLeftToRight()){switch(tabBarItem){case this._showHiddenTabsTabBarItem:tabBarItem.hidden=true;continue;case this._openClosedTabsTabBarItem:tabBarItem.hidden=!this._closedTabClasses().length;if(tabBarItem.hidden) continue;else break;} tabBarItem.hidden=false;if(tabBarItem instanceof WI.PinnedTabBarItem){availableSpace-=measureWidth(tabBarItem);continue;} normalTabBarItems.push(tabBarItem); if(undocked) tabBarItem[WI.TabBar.CachedWidthSymbol]=0;} let normalTabBarItemsWidth=normalTabBarItems.reduce((accumulator,tabBarItem)=>accumulator+measureWidth(tabBarItem),0);if(Math.round(normalTabBarItemsWidth)>=Math.floor(availableSpace)){this._showHiddenTabsTabBarItem.hidden=false;availableSpace-=measureWidth(this._showHiddenTabsTabBarItem);let index=normalTabBarItems.length-1;do{let tabBarItem=normalTabBarItems[index];if(tabBarItem===this._selectedTabBarItem) continue;normalTabBarItemsWidth-=measureWidth(tabBarItem);tabBarItem.hidden=true;this._hiddenTabBarItems.push(tabBarItem);}while(normalTabBarItemsWidth>=availableSpace&&--index>=0);} this._hiddenTabBarItems.reverse();this._tabContainer.classList.remove("calculate-width");} didLayoutSubtree() {super.didLayoutSubtree();this._tabContainer.classList.toggle("hide-border-start",this._navigationBarBefore.navigationItems.every((item)=>item.hidden));this._tabContainer.classList.toggle("hide-border-end",this._navigationBarAfter.navigationItems.every((item)=>item.hidden));} _pinnedButtons() {return[this._showHiddenTabsTabBarItem,this._openClosedTabsTabBarItem];} _tabBarItemsFromLeftToRight() {return WI.resolvedLayoutDirection()===WI.LayoutDirection.LTR?this._tabBarItems:this._tabBarItems.slice().reverse();} _closedTabClasses() {return Array.from(WI.knownTabClasses()).filter((tabClass)=>WI.isNewTabWithTypeAllowed(tabClass.Type));} _findTabBarItem(tabBarItemOrIndex) {if(typeof tabBarItemOrIndex==="number") return this._tabBarItems[tabBarItemOrIndex]||null;if(tabBarItemOrIndex instanceof WI.TabBarItem){if(this._tabBarItems.includes(tabBarItemOrIndex)) return tabBarItemOrIndex;} return null;} _hasMoreThanOneNormalTab() {let normalTabCount=0;for(let tabBarItem of this._tabBarItems){if(tabBarItem instanceof WI.PinnedTabBarItem) continue;++normalTabCount;if(normalTabCount>=2) return true;} return false;} _recordTabBarItemSizesAndPositions() {var tabBarItemSizesAndPositions=new Map;let barRect=this._tabContainer.getBoundingClientRect();for(let tabBarItem of this._tabBarItems){if(tabBarItem.hidden) continue;let boundingRect=tabBarItem.element.getBoundingClientRect();tabBarItemSizesAndPositions.set(tabBarItem,{left:boundingRect.left-barRect.left,width:boundingRect.width,});} return tabBarItemSizesAndPositions;} _applyTabBarItemSizesAndPositions(tabBarItemSizesAndPositions,skipTabBarItem) {for(var[tabBarItem,sizeAndPosition]of tabBarItemSizesAndPositions){if(skipTabBarItem&&tabBarItem===skipTabBarItem) continue;tabBarItem.element.style.left=sizeAndPosition.left+"px";tabBarItem.element.style.width=sizeAndPosition.width+"px";}} _clearTabBarItemSizesAndPositions(skipTabBarItem) {for(var tabBarItem of this._tabBarItems){if(skipTabBarItem&&tabBarItem===skipTabBarItem) continue;tabBarItem.element.style.left=null;tabBarItem.element.style.width=null;}} _finishExpandingTabsAfterClose(beforeTabSizesAndPositions) {return new Promise(function(resolve,reject){this._tabAnimatedClosedSinceMouseEnter=false;if(!beforeTabSizesAndPositions) beforeTabSizesAndPositions=this._recordTabBarItemSizesAndPositions();this._tabContainer.classList.remove("static-layout");this._clearTabBarItemSizesAndPositions();var afterTabSizesAndPositions=this._recordTabBarItemSizesAndPositions();this._applyTabBarItemSizesAndPositions(beforeTabSizesAndPositions);this._tabContainer.classList.add("static-layout");function animateTabs() {this._tabContainer.classList.add("static-layout");this._tabContainer.classList.add("animating");this._tabContainer.classList.add("expanding-tabs");this._applyTabBarItemSizesAndPositions(afterTabSizesAndPositions);this._tabContainer.addEventListener("transitionend",removeStylesListener);} function removeStyles() {this._tabContainer.classList.remove("static-layout");this._tabContainer.classList.remove("animating");this._tabContainer.classList.remove("expanding-tabs");this._clearTabBarItemSizesAndPositions();this.updateLayout();this._tabContainer.removeEventListener("transitionend",removeStylesListener);resolve();} var removeStylesListener=removeStyles.bind(this);requestAnimationFrame(animateTabs.bind(this));}.bind(this));} _handleMouseDown(event) {if(event.button!==0||event.ctrlKey) return;if(event.target!==this.element) return;switch(WI.dockConfiguration){case WI.DockConfiguration.Bottom:WI.resizeDockedFrameMouseDown(event);break;case WI.DockConfiguration.Undocked:WI.moveUndockedWindowMouseDown(event);break;}} _handleTabContainerMouseDown(event) {if(event.button!==0||event.ctrlKey) return;let itemElement=event.target.closest("."+WI.TabBarItem.StyleClassName);if(!itemElement) return;let tabBarItem=itemElement[WI.TabBarItem.ElementReferenceSymbol];if(!tabBarItem) return;if(tabBarItem.disabled) return;switch(tabBarItem){case this._showHiddenTabsTabBarItem:this._handleShowHiddenTabsTabBarItemMouseDown(event);return;case this._openClosedTabsTabBarItem:this._handleAddClosedTabsTabBarItemMouseDown(event);return;} this.selectTabBarItem(tabBarItem,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.TabClick});if(tabBarItem instanceof WI.PinnedTabBarItem||!this._hasMoreThanOneNormalTab()) return;this._firstNormalTabItemIndex=0;for(let i=0;i{this._ignoreShowHiddenTabsTabBarItemMouseDown=false;});for(let item of this._hiddenTabBarItems){contextMenu.appendItem(item.displayName,()=>{this.selectTabBarItem(item,{initiator:WI.TabBrowser.TabNavigationInitiator.ContextMenu});});} contextMenu.show();} _handleAddClosedTabsTabBarItemMouseDown(event) {let closedTabClasses=this._closedTabClasses();if(!closedTabClasses.length) return;if(this._ignoreAddClosedTabsTabBarItemMouseDown) return;this._ignoreAddClosedTabsTabBarItemMouseDown=true;let contextMenu=WI.ContextMenu.createFromEvent(event);contextMenu.addBeforeShowCallback(()=>{this._ignoreAddClosedTabsTabBarItemMouseDown=false;});for(let closedTabClass of closedTabClasses){if(!closedTabClass.shouldSaveTab()) continue;contextMenu.appendItem(closedTabClass.tabInfo().displayName,()=>{WI.createNewTabWithType(closedTabClass.Type,{shouldShowNewTab:true});});} WI.sharedApp.extensionController.addContextMenuItemsForClosedExtensionTabs(contextMenu);contextMenu.show();} _handleMouseMoved(event) {if(isNaN(this._mouseDownPageX)) return;if(!this._selectedTabBarItem) return;if(this._mouseOffset===undefined) this._mouseOffset=event.pageX-this._selectedTabBarItem.element.totalOffsetLeft;if(!this._isDragging){const dragThreshold=12;if(Math.abs(this._mouseDownPageX-event.pageX)tabBarItemRect.right) continue;newIndex=this._tabBarItems.indexOf(tabBarItem);break;} newIndex=Number.constrain(newIndex,this._firstNormalTabItemIndex,this.normalTabCount-1);if(currentIndex===newIndex) return;this._tabBarItems.splice(currentIndex,1);this._tabBarItems.splice(newIndex,0,this._selectedTabBarItem);let nextSibling=this._tabBarItems[newIndex+1];let nextSiblingElement=nextSibling?nextSibling.element:null;this._tabContainer.insertBefore(this._selectedTabBarItem.element,nextSiblingElement);function inlineStyleValue(element,property){return element.getComputedCSSPropertyNumberValue(property)||0;} let accumulatedLeft=0;for(let tabBarItem of this._tabBarItemsFromLeftToRight()){if(tabBarItem.hidden) continue;if(tabBarItem!==this._selectedTabBarItem&&inlineStyleValue(tabBarItem.element,"left")!==accumulatedLeft) tabBarItem.element.style.left=accumulatedLeft+"px";accumulatedLeft+=inlineStyleValue(tabBarItem.element,"width");}} _handleMouseUp(event) {if(isNaN(this._mouseDownPageX)) return;this._tabContainer.classList.remove("dragging-tab");if(!this._tabAnimatedClosedSinceMouseEnter){this._tabContainer.classList.remove("static-layout");this._clearTabBarItemSizesAndPositions();}else{let left=0;for(let tabBarItem of this._tabBarItemsFromLeftToRight()){if(tabBarItem===this._selectedTabBarItem) tabBarItem.element.style.left=left+"px";left+=parseFloat(tabBarItem.element.style.width);}} this._isDragging=false;this._mouseDownPageX=NaN;this._mouseOffset=undefined;document.removeEventListener("mousemove",this._mouseMovedEventListener,true);document.removeEventListener("mouseup",this._mouseUpEventListener,true);this._mouseMovedEventListener=null;this._mouseUpEventListener=null;event.preventDefault();event.stopPropagation();this.dispatchEventToListeners(WI.TabBar.Event.TabBarItemsReordered);} _handleTabContainerMouseLeave(event) {if(!isNaN(this._mouseDownPageX)||!this._tabAnimatedClosedSinceMouseEnter||!this._tabContainer.classList.contains("static-layout")||this._tabContainer.classList.contains("animating")) return;let barRect=this._tabContainer.getBoundingClientRect();if(event.pageY>barRect.top&&event.pageYbarRect.left&&event.pageX{if(openTabBarItem) this.removeTabBarItem(openTabBarItem);else WI.createNewTabWithType(tabClass.Type,{shouldShowNewTab:true});},checked,disabled);} WI.sharedApp.extensionController.addContextMenuItemsForAllExtensionTabs(contextMenu);}};WI.TabBar.CachedWidthSymbol=Symbol("cached-width");WI.TabBar.Event={TabBarItemSelected:"tab-bar-tab-bar-item-selected",TabBarItemAdded:"tab-bar-tab-bar-item-added",TabBarItemRemoved:"tab-bar-tab-bar-item-removed",TabBarItemsReordered:"tab-bar-tab-bar-items-reordered",};WI.TabBarItem=class TabBarItem {constructor(representedObject,image,displayName,title) {this._representedObject=representedObject||null;this._parentTabBar=null;this._element=document.createElement("div");this._element.classList.add(WI.TabBarItem.StyleClassName);this._element.setAttribute("role","tab");this._element.tabIndex=0;this._element[WI.TabBarItem.ElementReferenceSymbol]=this;this._element.createChild("div","flex-space");this._iconElement=document.createElement("img");this._iconElement.classList.add("icon");this._element.appendChild(this._iconElement);this._element.createChild("div","flex-space");this.displayName=displayName;this.title=title;this.image=image;} get element(){return this._element;} get representedObject(){return this._representedObject;} get parentTabBar(){return this._parentTabBar;} set parentTabBar(tabBar){this._parentTabBar=tabBar||null;} get selected() {return this._element.classList.contains("selected");} set selected(selected) {this._element.classList.toggle("selected",selected);if(selected) this._element.setAttribute("aria-selected","true");else this._element.removeAttribute("aria-selected");} get disabled() {return this._element.classList.contains("disabled");} set disabled(disabled) {this._element.classList.toggle("disabled",!!disabled);} get hidden() {return this._element.classList.contains("hidden");} set hidden(hidden) {this._element.classList.toggle("hidden",!!hidden);} get image(){return this._iconElement.src;} set image(url){this._iconElement.src=url||"";} get displayName() {return this._displayName;} set displayName(displayName) {displayName=displayName||"";if(this._displayName===displayName) return;this._displayName=displayName;} get title() {return this._title;} set title(title) {title=title||"";if(this._title===title) return;this._title=title;if(!this._title) this._element.removeAttribute("title");else this._element.title=this._title;}};WI.TabBarItem.StyleClassName="item";WI.TabBarItem.ElementReferenceSymbol=Symbol("tab-bar-item");WI.TabBrowser=class TabBrowser extends WI.View {constructor(element,tabBar,navigationSidebar,detailsSidebar) {super(element);this.element.classList.add("tab-browser");this._tabBar=tabBar;this._navigationSidebar=navigationSidebar||null;this._detailsSidebar=detailsSidebar||null;if(this._navigationSidebar){this._navigationSidebar.addEventListener(WI.Sidebar.Event.CollapsedStateDidChange,this._handleSidebarCollapsedStateDidChange,this);this._navigationSidebar.addEventListener(WI.Sidebar.Event.WidthDidChange,this._handleSidebarSizeDidChange,this);} if(this._detailsSidebar){this._detailsSidebar.addEventListener(WI.Sidebar.Event.CollapsedStateDidChange,this._handleSidebarCollapsedStateDidChange,this);this._detailsSidebar.addEventListener(WI.Sidebar.Event.WidthDidChange,this._handleSidebarSizeDidChange,this);this._detailsSidebar.addEventListener(WI.Sidebar.Event.SidebarPanelSelected,this._handleSidebarPanelSelected,this);this._detailsSidebar.addEventListener(WI.MultiSidebar.Event.SidebarAdded,this._handleMultiSidebarSidebarAdded,this);this._detailsSidebar.addEventListener(WI.Sidebar.Event.HeightDidChange,this._handleSidebarSizeDidChange,this);this._detailsSidebar.addEventListener(WI.Sidebar.Event.PositionDidChange,this._handleSidebarPositionDidChange,this);} this._contentViewContainer=new WI.ContentViewContainer;this.addSubview(this._contentViewContainer);let showNextTab=()=>{this._showNextTab();};let showPreviousTab=()=>{this._showPreviousTab();};let isRTL=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL;let nextKey1=isRTL?WI.KeyboardShortcut.Key.LeftCurlyBrace:WI.KeyboardShortcut.Key.RightCurlyBrace;let previousKey1=isRTL?WI.KeyboardShortcut.Key.RightCurlyBrace:WI.KeyboardShortcut.Key.LeftCurlyBrace;this._showNextTabKeyboardShortcut1=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Shift,nextKey1,showNextTab);this._showPreviousTabKeyboardShortcut1=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Shift,previousKey1,showPreviousTab);let nextModifier2=isRTL?WI.KeyboardShortcut.Modifier.Shift:0;let previousModifier2=isRTL?0:WI.KeyboardShortcut.Modifier.Shift;this._showNextTabKeyboardShortcut2=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Control|nextModifier2,WI.KeyboardShortcut.Key.Tab,showNextTab);this._showPreviousTabKeyboardShortcut2=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Control|previousModifier2,WI.KeyboardShortcut.Key.Tab,showPreviousTab);let previousTabKey=isRTL?WI.KeyboardShortcut.Key.Right:WI.KeyboardShortcut.Key.Left;let nextTabKey=isRTL?WI.KeyboardShortcut.Key.Left:WI.KeyboardShortcut.Key.Right;this._previousTabKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Shift,previousTabKey,this._showPreviousTabCheckingForEditableField.bind(this));this._previousTabKeyboardShortcut.implicitlyPreventsDefault=false;this._nextTabKeyboardShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl|WI.KeyboardShortcut.Modifier.Shift,nextTabKey,this._showNextTabCheckingForEditableField.bind(this));this._nextTabKeyboardShortcut.implicitlyPreventsDefault=false;this._tabBar.addEventListener(WI.TabBar.Event.TabBarItemSelected,this._tabBarItemSelected,this);this._tabBar.addEventListener(WI.TabBar.Event.TabBarItemAdded,this._tabBarItemAdded,this);this._tabBar.addEventListener(WI.TabBar.Event.TabBarItemRemoved,this._tabBarItemRemoved,this);this._recentTabContentViews=[];this._closedTabClasses=new Set;} get tabBar() {return this._tabBar;} get navigationSidebar() {return this._navigationSidebar;} get detailsSidebar() {return this._detailsSidebar;} get selectedTabContentView() {return this._contentViewContainer.currentContentView;} get contentViewContainer(){return this._contentViewContainer;} bestTabContentViewForClass(constructor) {for(var tabContentView of this._recentTabContentViews){if(tabContentView instanceof constructor) return tabContentView;} return null;} bestTabContentViewForRepresentedObject(representedObject,options={}) {let shouldSaveTab=this.selectedTabContentView?.constructor.shouldSaveTab()||this.selectedTabContentView?.constructor.shouldPinTab();let tabContentView=this._recentTabContentViews.find((tabContentView)=>tabContentView.type===options.preferredTabType);if(tabContentView&&tabContentView.canShowRepresentedObject(representedObject)) return tabContentView;for(let tabContentView of this._recentTabContentViews){if(options.ignoreSearchTab&&tabContentView instanceof WI.SearchTabContentView) continue;if(options.ignoreNetworkTab&&tabContentView instanceof WI.NetworkTabContentView) continue;if(tabContentView.canShowRepresentedObject(representedObject)) return tabContentView;} return null;} addTabForContentView(tabContentView,options={}) {if(!(tabContentView instanceof WI.TabContentView)) return false;let tabBarItem=tabContentView.tabBarItem;if(!(tabBarItem instanceof WI.TabBarItem)) return false;if(tabBarItem.representedObject!==tabContentView) tabBarItem.representedObject=tabContentView;if(tabBarItem.parentTabBar===this._tabBar) return true; if(this._recentTabContentViews.length&&this.selectedTabContentView) this._recentTabContentViews.splice(1,0,tabContentView);else this._recentTabContentViews.push(tabContentView);if(typeof options.insertionIndex==="number") this._tabBar.insertTabBarItem(tabBarItem,options.insertionIndex,options);else this._tabBar.addTabBarItem(tabBarItem,options);let shouldSaveTab=this.selectedTabContentView?.constructor.shouldSaveTab()||this.selectedTabContentView?.constructor.shouldPinTab();return true;} showTabForContentView(tabContentView,options={}) {if(!this.addTabForContentView(tabContentView,options)) return false;this._tabBar.selectTabBarItem(tabContentView.tabBarItem,options); this.needsLayout();return true;} closeTabForContentView(tabContentView,options={}) {if(!(tabContentView instanceof WI.TabContentView)) return false;if(!(tabContentView.tabBarItem instanceof WI.TabBarItem)) return false;if(tabContentView.tabBarItem.parentTabBar!==this._tabBar) return false;this._tabBar.removeTabBarItem(tabContentView.tabBarItem,options);let shouldSaveTab=this.selectedTabContentView?.constructor.shouldSaveTab()||this.selectedTabContentView?.constructor.shouldPinTab();return true;} sizeDidChange() {super.sizeDidChange();for(let tabContentView of this._recentTabContentViews) tabContentView[WI.TabBrowser.NeedsResizeLayoutSymbol]=tabContentView!==this.selectedTabContentView;} _tabBarItemSelected(event) {this._saveFocusedNodeForTabContentView(event.data.previousTabBarItem?event.data.previousTabBarItem.representedObject:null);let tabContentView=this._tabBar.selectedTabBarItem?this._tabBar.selectedTabBarItem.representedObject:null;if(tabContentView){let tabClass=tabContentView.constructor;let shouldSaveTab=tabClass.shouldSaveTab()||tabClass.shouldPinTab();if(shouldSaveTab){this._recentTabContentViews.remove(tabContentView);this._recentTabContentViews.unshift(tabContentView);} this._contentViewContainer.showContentView(tabContentView);}else{this._contentViewContainer.closeAllContentViews();} this._showNavigationSidebarPanelForTabContentView(tabContentView);this._showDetailsSidebarPanelsForTabContentView(tabContentView);if(tabContentView&&tabContentView[WI.TabBrowser.NeedsResizeLayoutSymbol]){tabContentView[WI.TabBrowser.NeedsResizeLayoutSymbol]=false;tabContentView.updateLayout(WI.View.LayoutReason.Resize);} let outgoingTab=event.data.previousTabBarItem?event.data.previousTabBarItem.representedObject:null;let incomingTab=tabContentView;let initiator=event.data.initiatorHint||WI.TabBrowser.TabNavigationInitiator.Unknown;this.dispatchEventToListeners(WI.TabBrowser.Event.SelectedTabContentViewDidChange,{outgoingTab,incomingTab,initiator});this._restoreFocusedNodeForTabContentView(tabContentView);} _tabBarItemAdded(event) {let tabContentView=event.data.tabBarItem.representedObject;if(!tabContentView) return;this._closedTabClasses.delete(tabContentView.constructor);} _tabBarItemRemoved(event) {let tabContentView=event.data.tabBarItem.representedObject;if(!tabContentView) return;this._recentTabContentViews.remove(tabContentView);if(tabContentView.constructor.shouldSaveTab()) this._closedTabClasses.add(tabContentView.constructor);this._contentViewContainer.closeContentView(tabContentView);let shouldSaveTab=this.selectedTabContentView?.constructor.shouldSaveTab()||this.selectedTabContentView?.constructor.shouldPinTab();} _handleSidebarPanelSelected(event) {if(this._ignoreSidebarEvents) return;var tabContentView=this.selectedTabContentView;if(!tabContentView) return;if(tabContentView.managesDetailsSidebarPanels) return;var selectedSidebarPanel=this._detailsSidebar.selectedSidebarPanel;tabContentView.detailsSidebarSelectedPanelSetting.value=selectedSidebarPanel?.identifier??null;} _handleSidebarCollapsedStateDidChange(event) {if(this._ignoreSidebarEvents) return;var tabContentView=this.selectedTabContentView;if(!tabContentView) return;if(event.target===this._navigationSidebar&&!tabContentView.managesNavigationSidebarPanel) tabContentView.navigationSidebarCollapsedSetting.value=this._navigationSidebar.collapsed;else if(event.target===this._detailsSidebar&&!tabContentView.managesDetailsSidebarPanels) tabContentView.detailsSidebarCollapsedSetting.value=this._detailsSidebar.collapsed;} _handleSidebarSizeDidChange(event) {if(this._ignoreSidebarEvents||!event.data) return;let tabContentView=this.selectedTabContentView;if(!tabContentView) return;switch(event.target){case this._navigationSidebar:tabContentView.navigationSidebarWidthSetting.value=event.data.newWidth;break;case this._detailsSidebar:if(event.data.sidebar&&event.data.newWidth&&WI.layoutMode!==WI.LayoutMode.Narrow){let identifier=event.data.sidebar===this._detailsSidebar.primarySidebar?WI.TabBrowser.SidebarWidthSettingPrimarySidebarIdentifier:(event.data.sidebar.sidebarPanels[0]?.identifier||null);if(identifier){tabContentView.detailsSidebarWidthSetting.value[identifier]=event.data.newWidth;tabContentView.detailsSidebarWidthSetting.save();}}else if(event.data.newHeight&&WI.layoutMode===WI.LayoutMode.Narrow) tabContentView.detailsSidebarHeightSetting.value=event.data.newHeight;break;}} _handleSidebarPositionDidChange() {let tabContentView=this.selectedTabContentView;if(WI.layoutMode===WI.LayoutMode.Narrow) this._detailsSidebar.height=tabContentView.detailsSidebarHeightSetting.value||WI.TabContentView.DefaultSidebarHeight;else{for(let sidebar of this._detailsSidebar.sidebars){let identifier=sidebar===this._detailsSidebar.primarySidebar?WI.TabBrowser.SidebarWidthSettingPrimarySidebarIdentifier:(sidebar.sidebarPanels[0]?.identifier||null);sidebar.width=tabContentView.detailsSidebarWidthSetting.value[identifier]||WI.TabContentView.DefaultSidebarWidth;}}} _handleMultiSidebarSidebarAdded(event) {let tabContentView=this.selectedTabContentView;if(!tabContentView) return;if(event.target!==this._detailsSidebar) return;let sidebar=event.data.sidebar;let identifier=event.data.sidebar===this._detailsSidebar.primarySidebar?WI.TabBrowser.SidebarWidthSettingPrimarySidebarIdentifier:(event.data.sidebar.sidebarPanels[0]?.identifier||null);sidebar.width=tabContentView.detailsSidebarWidthSetting.value[identifier]||WI.TabContentView.DefaultSidebarWidth;} _saveFocusedNodeForTabContentView(tabContentView) {if(!tabContentView) return;if(!WI.isContentAreaFocused()) return;tabContentView[WI.TabBrowser.FocusedNodeSymbol]=document.activeElement;} _restoreFocusedNodeForTabContentView(tabContentView) {if(!tabContentView) return;let node=tabContentView[WI.TabBrowser.FocusedNodeSymbol];if(node&&!WI.isContentAreaFocused()) node.focus();tabContentView[WI.TabBrowser.FocusedNodeSymbol]=null;} _showNavigationSidebarPanelForTabContentView(tabContentView) {if(!this._navigationSidebar) return;this._ignoreSidebarEvents=true;this._navigationSidebar.removeSidebarPanel(0);if(!tabContentView){this._ignoreSidebarEvents=false;return;} if(tabContentView.navigationSidebarWidthSetting.value) this._navigationSidebar.width=tabContentView.navigationSidebarWidthSetting.value;var navigationSidebarPanel=tabContentView.navigationSidebarPanel;if(!navigationSidebarPanel){this._navigationSidebar.collapsed=true;this._ignoreSidebarEvents=false;return;} if(tabContentView.managesNavigationSidebarPanel){tabContentView.showNavigationSidebarPanel();this._ignoreSidebarEvents=false;return;} this._navigationSidebar.addSidebarPanel(navigationSidebarPanel);this._navigationSidebar.selectedSidebarPanel=navigationSidebarPanel;this._navigationSidebar.collapsed=tabContentView.navigationSidebarCollapsedSetting.value;this._ignoreSidebarEvents=false;} _showDetailsSidebarPanelsForTabContentView(tabContentView) {if(!this._detailsSidebar) return;this._ignoreSidebarEvents=true;for(var i=this._detailsSidebar.sidebarPanels.length-1;i>=0;--i) this._detailsSidebar.removeSidebarPanel(i);if(!tabContentView){this._ignoreSidebarEvents=false;return;} for(let sidebar of this._detailsSidebar.sidebars){let identifier=sidebar===this._detailsSidebar.primarySidebar?WI.TabBrowser.SidebarWidthSettingPrimarySidebarIdentifier:(sidebar.sidebarPanels[0]?.identifier||null);sidebar.width=tabContentView.detailsSidebarWidthSetting.value[identifier]||WI.TabContentView.DefaultSidebarWidth;} this._detailsSidebar.height=tabContentView.detailsSidebarHeightSetting.value||WI.TabContentView.DefaultSidebarHeight;this._detailsSidebar.allowMultipleSidebars=tabContentView.allowMultipleDetailSidebars;if(tabContentView.managesDetailsSidebarPanels){tabContentView.showDetailsSidebarPanels();this._ignoreSidebarEvents=false;return;} var detailsSidebarPanels=tabContentView.detailsSidebarPanels;if(!detailsSidebarPanels){this._detailsSidebar.collapsed=true;this._ignoreSidebarEvents=false;return;} for(var detailsSidebarPanel of detailsSidebarPanels) this._detailsSidebar.addSidebarPanel(detailsSidebarPanel);this._detailsSidebar.selectedSidebarPanel=tabContentView.detailsSidebarSelectedPanelSetting.value||detailsSidebarPanels[0];this._detailsSidebar.collapsed=tabContentView.detailsSidebarCollapsedSetting.value||!detailsSidebarPanels.length;this._ignoreSidebarEvents=false;} _showPreviousTab(event) {this._tabBar.selectPreviousTab();} _showNextTab(event) {this._tabBar.selectNextTab();} _showNextTabCheckingForEditableField(event) {if(WI.isEventTargetAnEditableField(event)) return;this._showNextTab(event);event.preventDefault();} _showPreviousTabCheckingForEditableField(event) {if(WI.isEventTargetAnEditableField(event)) return;this._showPreviousTab(event);event.preventDefault();}};WI.TabBrowser.MinimumHeight=110;WI.TabBrowser.NeedsResizeLayoutSymbol=Symbol("needs-resize-layout");WI.TabBrowser.FocusedNodeSymbol=Symbol("focused-node");WI.TabBrowser.SidebarWidthSettingPrimarySidebarIdentifier="primary-sidebar";WI.TabBrowser.TabNavigationInitiator={TabClick:"tab-browser-tab-navigation-initiator-tab-click",LinkClick:"tab-browser-tab-navigation-initiator-link-click",ButtonClick:"tab-browser-tab-navigation-initiator-button-click",ContextMenu:"tab-browser-tab-navigation-initiator-context-menu",Dashboard:"tab-browser-tab-navigation-initiator-dashboard",Breakpoint:"tab-browser-tab-navigation-initiator-breakpoint",Inspect:"tab-browser-tab-navigation-initiator-inspect",KeyboardShortcut:"tab-browser-tab-navigation-initiator-keyboard-shortcut",FrontendAPI:"tab-browser-tab-navigation-initiator-frontend-api",Unknown:"tab-browser-tab-navigation-initiator-unknown"} WI.TabBrowser.Event={SelectedTabContentViewDidChange:"tab-browser-selected-tab-content-view-did-change"};WI.Table=class Table extends WI.View {constructor(identifier,dataSource,delegate,rowHeight) {super();this._identifier=identifier;this._dataSource=dataSource;this._delegate=delegate;this._rowHeight=rowHeight; this.element.classList.add("table",identifier);this.element.tabIndex=0;this.element.addEventListener("keydown",this._handleKeyDown.bind(this));this._headerElement=this.element.appendChild(document.createElement("div"));this._headerElement.className="header";let scrollHandler=this._handleScroll.bind(this);this._scrollContainerElement=this.element.appendChild(document.createElement("div"));this._scrollContainerElement.className="data-container";this._scrollContainerElement.addEventListener("scroll",scrollHandler);this._scrollContainerElement.addEventListener("mousewheel",scrollHandler);this._scrollContainerElement.addEventListener("mousedown",this._handleMouseDown.bind(this));if(this._delegate.tableCellContextMenuClicked) this._scrollContainerElement.addEventListener("contextmenu",this._handleContextMenu.bind(this));this._topSpacerElement=this._scrollContainerElement.appendChild(document.createElement("div"));this._topSpacerElement.className="spacer";this._listElement=this._scrollContainerElement.appendChild(document.createElement("ul"));this._listElement.className="data-list";this._bottomSpacerElement=this._scrollContainerElement.appendChild(document.createElement("div"));this._bottomSpacerElement.className="spacer";this._fillerRow=this._listElement.appendChild(document.createElement("li"));this._fillerRow.className="filler";this._resizersElement=this._element.appendChild(document.createElement("div"));this._resizersElement.className="resizers";this._cachedRows=new Map;this._columnSpecs=new Map;this._columnOrder=[];this._visibleColumns=[];this._hiddenColumns=[];this._widthGeneration=1;this._columnWidths=null;this._fillerHeight=0;let selectionComparator=WI.SelectionController.createListComparator(this._indexForRepresentedObject.bind(this));this._selectionController=new WI.SelectionController(this,selectionComparator);this._resizers=[];this._currentResizer=null;this._resizeLeftColumns=null;this._resizeRightColumns=null;this._resizeOriginalColumnWidths=null;this._lastColumnIndexToAcceptRemainderPixel=0;this._sortOrderSetting=new WI.Setting(this._identifier+"-sort-order",WI.Table.SortOrder.Indeterminate);this._sortColumnIdentifierSetting=new WI.Setting(this._identifier+"-sort",null);this._columnVisibilitySetting=new WI.Setting(this._identifier+"-column-visibility",{});this._sortOrder=this._sortOrderSetting.value;this._sortColumnIdentifier=this._sortColumnIdentifierSetting.value;this._cachedWidth=NaN;this._cachedHeight=NaN;this._cachedScrollTop=NaN;this._previousCachedWidth=NaN;this._previousRevealedRowCount=NaN;this._topSpacerHeight=NaN;this._bottomSpacerHeight=NaN;this._visibleRowIndexStart=NaN;this._visibleRowIndexEnd=NaN;} get identifier(){return this._identifier;} get dataSource(){return this._dataSource;} get delegate(){return this._delegate;} get rowHeight(){return this._rowHeight;} get selectedRow() {let item=this._selectionController.lastSelectedItem;let index=this._indexForRepresentedObject(item);return index>=0?index:NaN;} get selectedRows() {let rowIndexes=[];for(let item of this._selectionController.selectedItems) rowIndexes.push(this._indexForRepresentedObject(item));return rowIndexes;} get scrollContainer(){return this._scrollContainerElement;} get numberOfRows() {return this._dataSource.tableNumberOfRows(this);} get sortOrder() {return this._sortOrder;} set sortOrder(sortOrder) {if(sortOrder===this._sortOrder&&this.didInitialLayout) return;this._sortOrder=sortOrder;this._sortOrderSetting.value=sortOrder;if(this._sortColumnIdentifier){let column=this._columnSpecs.get(this._sortColumnIdentifier);let columnIndex=this._visibleColumns.indexOf(column);if(columnIndex!==-1){let headerCell=this._headerElement.children[columnIndex];headerCell.classList.toggle("sort-ascending",this._sortOrder===WI.Table.SortOrder.Ascending);headerCell.classList.toggle("sort-descending",this._sortOrder===WI.Table.SortOrder.Descending);} if(this._dataSource.tableSortChanged) this._dataSource.tableSortChanged(this);}} get sortColumnIdentifier() {return this._sortColumnIdentifier;} set sortColumnIdentifier(columnIdentifier) {if(columnIdentifier===this._sortColumnIdentifier&&this.didInitialLayout) return;let column=this._columnSpecs.get(columnIdentifier);if(!column) return;if(!column.sortable) return;let oldSortColumnIdentifier=this._sortColumnIdentifier;this._sortColumnIdentifier=columnIdentifier;this._sortColumnIdentifierSetting.value=columnIdentifier;if(oldSortColumnIdentifier){let oldColumn=this._columnSpecs.get(oldSortColumnIdentifier);let oldColumnIndex=this._visibleColumns.indexOf(oldColumn);if(oldColumnIndex!==-1){let headerCell=this._headerElement.children[oldColumnIndex];headerCell.classList.remove("sort-ascending","sort-descending");}} if(this._sortColumnIdentifier){let newColumnIndex=this._visibleColumns.indexOf(column);if(newColumnIndex!==-1){let headerCell=this._headerElement.children[newColumnIndex];headerCell.classList.toggle("sort-ascending",this._sortOrder===WI.Table.SortOrder.Ascending);headerCell.classList.toggle("sort-descending",this._sortOrder===WI.Table.SortOrder.Descending);}else this._sortColumnIdentifier=null;} if(this._dataSource.tableSortChanged) this._dataSource.tableSortChanged(this);} get allowsMultipleSelection() {return this._selectionController.allowsMultipleSelection;} set allowsMultipleSelection(flag) {this._selectionController.allowsMultipleSelection=flag;} get columns() {return Array.from(this._columnSpecs.values());} isRowSelected(rowIndex) {return this._selectionController.hasSelectedItem(this._representedObjectForIndex(rowIndex));} reloadData() {this._cachedRows.clear();this._selectionController.reset();this._previousRevealedRowCount=NaN;this.needsLayout();} reloadDataAddedToEndOnly() {this._previousRevealedRowCount=NaN;this.needsLayout();} reloadRow(rowIndex) {if(this._isRowVisible(rowIndex)){let row=this._cachedRows.get(rowIndex);if(!row) return;this._populateRow(row);return;} this._cachedRows.delete(rowIndex);} restyleRow(rowIndex) {if(!this._isRowVisible(rowIndex)) return;let row=this._cachedRows.get(rowIndex);if(!row) return;this._styleRow(row);} reloadVisibleColumnCells(column) {let columnIndex=this._visibleColumns.indexOf(column);if(columnIndex===-1) return;let numberOfRows=Math.min(this._visibleRowIndexEnd,this.numberOfRows);for(let rowIndex=this._visibleRowIndexStart;rowIndex=this.numberOfRows) return;if(this._isRowVisible(rowIndex)){let row=this._cachedRows.get(rowIndex);if(row){row.scrollIntoViewIfNeeded(false);this._cachedScrollTop=NaN;this.needsLayout();}}else{let rowPosition=rowIndex*this._rowHeight;let scrollableOffsetHeight=this._calculateOffsetHeight();let scrollTop=this._calculateScrollTop();let newScrollTop=NaN;if(rowPosition+this._rowHeightscrollTop+scrollableOffsetHeight) newScrollTop=scrollTop+scrollableOffsetHeight-this._rowHeight;if(!isNaN(newScrollTop)){this._scrollContainerElement.scrollTop=newScrollTop;this.updateLayout();}}} columnWithIdentifier(identifier) {return this._columnSpecs.get(identifier);} cellForRowAndColumn(rowIndex,column) {if(!this._isRowVisible(rowIndex)) return null;let row=this._cachedRows.get(rowIndex);if(!row) return null;let columnIndex=this._visibleColumns.indexOf(column);if(columnIndex===-1) return null;return row.children[columnIndex];} addColumn(column) {this._columnSpecs.set(column.identifier,column);this._columnOrder.push(column.identifier);if(column.hidden){this._hiddenColumns.push(column);column.width=NaN;}else{this._visibleColumns.push(column);this._headerElement.appendChild(this._createHeaderCell(column));this._fillerRow.appendChild(this._createFillerCell(column));if(column.headerView) this.addSubview(column.headerView);} let savedColumnVisibility=this._columnVisibilitySetting.value;if(column.identifier in savedColumnVisibility){let visible=savedColumnVisibility[column.identifier];if(visible) this.showColumn(column);else this.hideColumn(column);} this.reloadData();} showColumn(column) {if(column.locked) return;if(!column.hidden) return;column.hidden=false;let columnIndex=this._hiddenColumns.indexOf(column);this._hiddenColumns.splice(columnIndex,1);let newColumnIndex=this._indexToInsertColumn(column);this._visibleColumns.insertAtIndex(column,newColumnIndex);let savedColumnVisibility=this._columnVisibilitySetting.value;if(savedColumnVisibility[column.identifier]!==true){let copy=Object.shallowCopy(savedColumnVisibility);if(column.defaultHidden) copy[column.identifier]=true;else delete copy[column.identifier];this._columnVisibilitySetting.value=copy;} this._headerElement.insertBefore(this._createHeaderCell(column),this._headerElement.children[newColumnIndex]);this._fillerRow.insertBefore(this._createFillerCell(column),this._fillerRow.children[newColumnIndex]);if(column.headerView) this.addSubview(column.headerView);if(this._sortColumnIdentifier===column.identifier){let headerCell=this._headerElement.children[newColumnIndex];headerCell.classList.toggle("sort-ascending",this._sortOrder===WI.Table.SortOrder.Ascending);headerCell.classList.toggle("sort-descending",this._sortOrder===WI.Table.SortOrder.Descending);} if(!this._columnWidths) return; let cellsToPopulate=[];for(let row of this._listElement.children){if(row!==this._fillerRow){let unpopulatedCell=this._createCell(column,newColumnIndex);cellsToPopulate.push(unpopulatedCell);row.insertBefore(unpopulatedCell,row.children[newColumnIndex]);}} this._widthGeneration++;this._columnWidths=null;this._resizeColumnsAndFiller();for(let cell of cellsToPopulate) this._delegate.tablePopulateCell(this,cell,column,cell.parentElement.__index);for(let visibleColumn of this._visibleColumns){if(visibleColumn!==column){if(visibleColumn.needsReloadOnResize) this.reloadVisibleColumnCells(visibleColumn);}}} hideColumn(column) {if(column.locked) return;if(!column.hideable) return;if(column.hidden) return;column.hidden=true;this._hiddenColumns.push(column);let columnIndex=this._visibleColumns.indexOf(column);this._visibleColumns.splice(columnIndex,1);let savedColumnVisibility=this._columnVisibilitySetting.value;if(savedColumnVisibility[column.identifier]!==false){let copy=Object.shallowCopy(savedColumnVisibility);if(column.defaultHidden) delete copy[column.identifier];else copy[column.identifier]=false;this._columnVisibilitySetting.value=copy;} this._headerElement.removeChild(this._headerElement.children[columnIndex]);this._fillerRow.removeChild(this._fillerRow.children[columnIndex]);if(column.headerView) this.removeSubview(column.headerView);if(!this._columnWidths) return;for(let row of this._listElement.children){if(row!==this._fillerRow) row.removeChild(row.children[columnIndex]);} this._widthGeneration++;this._columnWidths=null;this._resizeColumnsAndFiller();for(let visibleColumn of this._visibleColumns){if(visibleColumn.needsReloadOnResize) this.reloadVisibleColumnCells(visibleColumn);}} attached() {super.attached();if(this._cachedScrollTop&&!this._scrollContainerElement.scrollTop) this._scrollContainerElement.scrollTop=this._cachedScrollTop;} initialLayout() {this.sortOrder=this._sortOrderSetting.value;let restoreSortColumnIdentifier=this._sortColumnIdentifierSetting.value;if(!this._columnSpecs.has(restoreSortColumnIdentifier)) this._sortColumnIdentifierSetting.value=null;else this.sortColumnIdentifier=restoreSortColumnIdentifier;} layout() {this._updateVisibleRows();this._resizeColumnsAndFiller();} sizeDidChange() {super.sizeDidChange();this._previousCachedWidth=this._cachedWidth;this._cachedWidth=NaN;this._cachedHeight=NaN;} selectionControllerSelectionDidChange(controller,deselectedItems,selectedItems) {for(let item of deselectedItems){let rowIndex=this._indexForRepresentedObject(item);let row=this._cachedRows.get(rowIndex);if(row) row.classList.toggle("selected",false);} for(let item of selectedItems){let rowIndex=this._indexForRepresentedObject(item);let row=this._cachedRows.get(rowIndex);if(row) row.classList.toggle("selected",true);} if(this._selectionController.lastSelectedItem){let rowIndex=this._indexForRepresentedObject(this._selectionController.lastSelectedItem);this.revealRow(rowIndex);} if(this._delegate.tableSelectionDidChange) this._delegate.tableSelectionDidChange(this);} selectionControllerFirstSelectableItem(controller) {return this._representedObjectForIndex(0);} selectionControllerLastSelectableItem(controller) {return this._representedObjectForIndex(this.numberOfRows-1);} selectionControllerPreviousSelectableItem(controller,item) {let index=this._indexForRepresentedObject(item);return index>0?this._representedObjectForIndex(index-1):null;} selectionControllerNextSelectableItem(controller,item) {let index=this._indexForRepresentedObject(item);return index0;let rightDirection=!leftDirection;let columnWidths=this._columnWidths;let visibleColumns=this._visibleColumns;function growableSize(column){let width=columnWidths[visibleColumns.indexOf(column)];if(column.maxWidth) return column.maxWidth-width;return Infinity;} function shrinkableSize(column){let width=columnWidths[visibleColumns.indexOf(column)];if(column.minWidth) return width-column.minWidth;return width;} function canGrow(column){return growableSize(column)>0;} function canShrink(column){return shrinkableSize(column)>0;} function columnToResize(columns,isShrinking){for(let column of columns){if(!column.flexible) continue;if(isShrinking?canShrink(column):canGrow(column)) return column;} let immediateColumn=columns[0];if((isShrinking&&canShrink(immediateColumn))||(!isShrinking&&canGrow(immediateColumn))) return immediateColumn;return null;} while(delta>0){let leftColumn=columnToResize(this._resizeLeftColumns,leftDirection);let rightColumn=columnToResize(this._resizeRightColumns,rightDirection);if(!leftColumn||!rightColumn){break;} let incrementalDelta=Math.min(delta,leftDirection?shrinkableSize(leftColumn):shrinkableSize(rightColumn),leftDirection?growableSize(rightColumn):growableSize(leftColumn));let leftIndex=this._visibleColumns.indexOf(leftColumn);let rightIndex=this._visibleColumns.indexOf(rightColumn);if(leftDirection){this._columnWidths[leftIndex]-=incrementalDelta;this._columnWidths[rightIndex]+=incrementalDelta;}else{this._columnWidths[leftIndex]+=incrementalDelta;this._columnWidths[rightIndex]-=incrementalDelta;} delta-=incrementalDelta;} this._widthGeneration++;this._applyColumnWidths();this._positionHeaderViews();} resizerDragEnded(resizer) {if(resizer!==this._currentResizer) return;this._currentResizer=null;this._resizeLeftColumns=null;this._resizeRightColumns=null;this._resizeOriginalColumnWidths=null;this._positionResizerElements();this._positionHeaderViews();} _createHeaderCell(column) {let cell=document.createElement("span");cell.classList.add("cell",column.identifier);cell.textContent=column.name;if(column.align) cell.classList.add("align-"+column.align);if(column.sortable){cell.classList.add("sortable");cell.addEventListener("click",this._handleHeaderCellClicked.bind(this,column));} cell.addEventListener("contextmenu",this._handleHeaderContextMenu.bind(this,column));return cell;} _createFillerCell(column) {let cell=document.createElement("span");cell.classList.add("cell",column.identifier);return cell;} _createCell(column,columnIndex) {let cell=document.createElement("span");cell.classList.add("cell",column.identifier);if(column.align) cell.classList.add("align-"+column.align);if(this._columnWidths) cell.style.width=this._columnWidths[columnIndex]+"px";return cell;} _getOrCreateRow(rowIndex) {let cachedRow=this._cachedRows.get(rowIndex);if(cachedRow) return cachedRow;let row=document.createElement("li");row.__index=rowIndex;row.__widthGeneration=0;this._styleRow(row);if(this._delegate.tableRowHovered){this._boundHandleRowMouseEnter??=this._handleRowMouseEnter.bind(this);this._boundHandleRowMouseLeave??=this._handleRowMouseLeave.bind(this);row.addEventListener("mouseenter",this._boundHandleRowMouseEnter);row.addEventListener("mouseleave",this._boundHandleRowMouseLeave);} this._cachedRows.set(rowIndex,row);return row;} _styleRow(row) {let selected=row.classList.contains("selected");row.className="";if(selected||this.isRowSelected(row.__index)) row.classList.add("selected");if(this._delegate.tableRowClassNames) row.classList.add(...this._delegate.tableRowClassNames(this,row.__index));} _populatedCellForColumnAndRow(column,columnIndex,rowIndex) {let cell=this._createCell(column,columnIndex);this._delegate.tablePopulateCell(this,cell,column,rowIndex);return cell;} _populateRow(row) {row.removeChildren();let rowIndex=row.__index;for(let i=0;i0){let initialRemainder=remainder;for(let i=indexToStartAddingRemainderPixels;icolumn.minWidth)){this._columnWidths[i]--;remainder--;}}else{if(ignoreConstraints||(column.maxWidth&&this._columnWidths[i]{if(!column.preferredInitialWidth||width<=column.preferredInitialWidth) return-1;return column.preferredInitialWidth;});bestFit.call(this,(column,width)=>{if(!column.maxWidth||width<=column.maxWidth) return-1;return column.maxWidth;});bestFit.call(this,(column,width)=>{if(!column.minWidth||width>=column.minWidth) return-1;return column.minWidth;});bestFit.call(this,(column,width)=>width);let remainder=availableWidth-(lockedWidth+bestFitWidth);let shrinking=remainder<0;distributeRemainingPixels.call(this,Math.abs(remainder),shrinking);}else{let originalTotalColumnWidth=0;for(let width of this._columnWidths) originalTotalColumnWidth+=width;let remainder=Math.abs(availableWidth-originalTotalColumnWidth);let shrinking=availableWidthcurrentTopMargin+updateOffsetThreshold;let aboveBottomThreshold=!currentBottomMargin||scrollTop+scrollableOffsetHeight=rowsThatCanFitOnScreen){let maximumScrollTop=Math.max(0,(numberOfRows*rowHeight)-scrollableOffsetHeight);if(scrollTop>maximumScrollTop){this._scrollContainerElement.scrollTop=maximumScrollTop;this._cachedScrollTop=maximumScrollTop;}}} let topHiddenRowCount=Math.max(0,Math.floor((scrollTop-overflowPadding)/rowHeight));let bottomHiddenRowCount=Math.max(0,this._previousRevealedRowCount-topHiddenRowCount-visibleRowCount);let marginTop=topHiddenRowCount*rowHeight;let marginBottom=bottomHiddenRowCount*rowHeight;if(this._topSpacerHeight!==marginTop){this._topSpacerHeight=marginTop;this._topSpacerElement.style.height=marginTop+"px";} if(this._bottomDataTableMarginElement!==marginBottom){this._bottomSpacerHeight=marginBottom;this._bottomSpacerElement.style.height=marginBottom+"px";} this._visibleRowIndexStart=topHiddenRowCount;this._visibleRowIndexEnd=this._visibleRowIndexStart+visibleRowCount;this._listElement.removeChildren();this._listElement.classList.toggle("even-first-zebra-stripe",!!(topHiddenRowCount%2));for(let i=this._visibleRowIndexStart;iresizersNeededCount);}} const columnResizerAdjustment=3;let positionAttribute=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"right":"left";let totalWidth=0;for(let i=0;i=this._visibleRowIndexStart&&rowIndex<=this._visibleRowIndexEnd;} _indexToInsertColumn(column) {let currentVisibleColumnIndex=0;for(let columnIdentifier of this._columnOrder){if(columnIdentifier===column.identifier) return currentVisibleColumnIndex;if(columnIdentifier===this._visibleColumns[currentVisibleColumnIndex].identifier){currentVisibleColumnIndex++;if(currentVisibleColumnIndex>=this._visibleColumns.length) break;}} return currentVisibleColumnIndex;} _handleScroll(event) {if(event.type==="mousewheel"&&!event.wheelDeltaY) return;this._cachedScrollTop=NaN;this.needsLayout();} _handleKeyDown(event) {this._selectionController.handleKeyDown(event);} _handleMouseDown(event) {let cell=event.target.closest(".cell");if(!cell) return;let row=cell.parentElement;if(row===this._fillerRow) return;let rowIndex=row.__index; if(!this.isRowSelected(rowIndex)&&this._delegate.tableShouldSelectRow){let columnIndex=Array.from(row.children).indexOf(cell);let column=this._visibleColumns[columnIndex];if(!this._delegate.tableShouldSelectRow(this,cell,column,rowIndex)) return;} this._selectionController.handleItemMouseDown(this._representedObjectForIndex(rowIndex),event);} _handleContextMenu(event) {let cell=event.target.closest(".cell");if(!cell) return;let row=cell.parentElement;if(row===this._fillerRow) return;let columnIndex=Array.from(row.children).indexOf(cell);let column=this._visibleColumns[columnIndex];let rowIndex=row.__index;this._delegate.tableCellContextMenuClicked(this,cell,column,rowIndex,event);} _handleHeaderCellClicked(column,event) {let sortOrder=this._sortOrder;if(sortOrder===WI.Table.SortOrder.Indeterminate) sortOrder=WI.Table.SortOrder.Descending;else if(this._sortColumnIdentifier===column.identifier) sortOrder=sortOrder===WI.Table.SortOrder.Ascending?WI.Table.SortOrder.Descending:WI.Table.SortOrder.Ascending;this.sortColumnIdentifier=column.identifier;this.sortOrder=sortOrder;} _handleHeaderContextMenu(column,event) {let contextMenu=WI.ContextMenu.createFromEvent(event);if(column.sortable){if(this.sortColumnIdentifier!==column.identifier||this.sortOrder!==WI.Table.SortOrder.Ascending){contextMenu.appendItem(WI.UIString("Sort Ascending"),()=>{this.sortColumnIdentifier=column.identifier;this.sortOrder=WI.Table.SortOrder.Ascending;});} if(this.sortColumnIdentifier!==column.identifier||this.sortOrder!==WI.Table.SortOrder.Descending){contextMenu.appendItem(WI.UIString("Sort Descending"),()=>{this.sortColumnIdentifier=column.identifier;this.sortOrder=WI.Table.SortOrder.Descending;});}} contextMenu.appendSeparator();let didAppendHeaderItem=false;for(let[columnIdentifier,column]of this._columnSpecs){if(column.locked) continue;if(!column.hideable) continue;if(!didAppendHeaderItem){const disabled=true;contextMenu.appendItem(WI.UIString("Displayed Columns"),()=>{},disabled);didAppendHeaderItem=true;} let checked=!column.hidden;contextMenu.appendCheckboxItem(column.name,()=>{if(column.hidden) this.showColumn(column);else this.hideColumn(column);},checked);}} _handleRowMouseEnter(event) {let row=event.target;this.delegate.tableRowHovered(this,row.__index);} _handleRowMouseLeave(event) {this.delegate.tableRowHovered(this,NaN);} _removeRows(representedObjects) {let removed=0;let adjustRowAtIndex=(index)=>{let row=this._cachedRows.get(index);if(row){this._cachedRows.delete(index);row.__index-=removed;this._cachedRows.set(row.__index,row);}};let rowIndexes=[];for(let object of representedObjects) rowIndexes.push(this._indexForRepresentedObject(object));rowIndexes.sort((a,b)=>a-b);let lastIndex=rowIndexes.lastValue;for(let index=rowIndexes[0];index<=lastIndex;++index){if(rowIndexes.binaryIndexOf(index)>=0){let row=this._cachedRows.get(index);if(row){this._cachedRows.delete(index);row.remove();} removed++;continue;} if(removed) adjustRowAtIndex(index);} if(!removed) return;for(let index=lastIndex+1;index0;} updateFormattedState(formatted) {return this._format(formatted);} hasFormatter() {let mode=this._codeMirror.getMode().name;return mode==="javascript"||mode==="css"||mode==="htmlmixed"||mode==="xml";} canBeFormatted() {return this.hasFormatter();} canShowTypeAnnotations() {return false;} canShowCoverageHints() {return false;} get selectedTextRange() {var start=this._codeMirror.getCursor(true);var end=this._codeMirror.getCursor(false);return this._textRangeFromCodeMirrorPosition(start,end);} set selectedTextRange(textRange) {if(document.activeElement===document.body) this.focus();var position=this._codeMirrorPositionFromTextRange(textRange);this._codeMirror.setSelection(position.start,position.end);} get scrollOffset() {let scrollInfo=this._codeMirror.getScrollInfo();return new WI.Point(scrollInfo.left,scrollInfo.top);} set scrollOffset(scrollOffset) {this._codeMirror.scrollTo(scrollOffset.x,scrollOffset.y);} get mimeType() {return this._mimeType;} set mimeType(newMIMEType) {newMIMEType=parseMIMEType(newMIMEType).type;this._mimeType=newMIMEType;this._codeMirror.setOption("mode",{name:newMIMEType,globalVars:true});this.dispatchEventToListeners(WI.TextEditor.Event.MIMETypeChanged);} get executionLineNumber() {return this._executionLineNumber;} get executionColumnNumber() {return this._executionColumnNumber;} get formatterSourceMap() {return this._formatterSourceMap;} get tokenTrackingController() {return this._tokenTrackingController;} get delegate() {return this._delegate;} set delegate(newDelegate) {this._delegate=newDelegate||null;} get numberOfSearchResults() {return this._searchResults.length;} get currentSearchQuery() {return this._searchQuery;} set automaticallyRevealFirstSearchResult(reveal) {this._automaticallyRevealFirstSearchResult=reveal;if(this._automaticallyRevealFirstSearchResult&&this._searchResults.length>0){if(this._currentSearchResultIndex===-1) this._revealFirstSearchResultAfterCursor();}} set deferReveal(defer) {this._deferReveal=defer;} set repeatReveal(repeat) {this._repeatReveal=repeat;} performSearch(query) {if(this._searchQuery===query) return;this.searchCleared();this._searchQuery=query;if(this._initialStringNotSet) return;if(typeof this.customPerformSearch==="function"&&!this.formatted){if(this.customPerformSearch(query)) return;} let queryRegex=WI.SearchUtilities.searchRegExpForString(query,WI.SearchUtilities.defaultSettings);if(!queryRegex){this.searchCleared();this.dispatchEventToListeners(WI.TextEditor.Event.NumberOfSearchResultsDidChange);return;} var searchCursor=this._codeMirror.getSearchCursor(queryRegex,{line:0,ch:0},false);var boundBatchSearch=batchSearch.bind(this);var numberOfSearchResultsDidChangeTimeout=null;function reportNumberOfSearchResultsDidChange() {if(numberOfSearchResultsDidChangeTimeout){clearTimeout(numberOfSearchResultsDidChangeTimeout);numberOfSearchResultsDidChangeTimeout=null;} this.dispatchEventToListeners(WI.TextEditor.Event.NumberOfSearchResultsDidChange);} function batchSearch() {if(this._searchQuery!==query) return;var newSearchResults=[];var foundResult=false;for(var i=0;i{for(let searchResult of this._searchResults) searchResult.clear();});this._searchQuery=null;this._searchResults=[];this._currentSearchResultIndex=-1;} searchQueryWithSelection() {if(!this._codeMirror.somethingSelected()) return null;return this._codeMirror.getSelection();} revealPreviousSearchResult(changeFocus) {if(!this._searchResults.length) return;if(this._currentSearchResultIndex===-1||this._cursorDoesNotMatchLastRevealedSearchResult()){this._revealFirstSearchResultBeforeCursor(changeFocus);return;} if(this._currentSearchResultIndex>0) --this._currentSearchResultIndex;else this._currentSearchResultIndex=this._searchResults.length-1;this._revealSearchResult(this._searchResults[this._currentSearchResultIndex],changeFocus,-1);} revealNextSearchResult(changeFocus) {if(!this._searchResults.length) return;if(this._currentSearchResultIndex===-1||this._cursorDoesNotMatchLastRevealedSearchResult()){this._revealFirstSearchResultAfterCursor(changeFocus);return;} if(this._currentSearchResultIndex+1{setTimeout(this.revealPosition.bind(this),0,position,textRangeToSelect);});return;} let line=Number.constrain(position.lineNumber,0,this._codeMirror.lineCount()-1);let lineHandle=this._codeMirror.getLineHandle(line);if(!textRangeToSelect){let column=Number.constrain(position.columnNumber,0,this._codeMirror.getLine(line).length);textRangeToSelect=new WI.TextRange(line,column,line,column);} function removeStyleClass() {this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.HighlightedStyleClassName);} function revealAndHighlightLine() {if(scrollOffset) this._codeMirror.scrollTo(scrollOffset.x,scrollOffset.y);else{let position=this._codeMirrorPositionFromTextRange(textRangeToSelect);if(!this._isPositionVisible(position.start)) this._scrollIntoViewCentered(position.start);} this.selectedTextRange=textRangeToSelect;if(!this.readOnly) this.focus();if(preventHighlight) return;if(WI.debuggerManager.paused&&line===this._executionLineNumber) return;this._codeMirror.addLineClass(lineHandle,"wrap",WI.TextEditor.HighlightedStyleClassName); setTimeout(removeStyleClass.bind(this),WI.TextEditor.HighlightAnimationDuration);} this._codeMirror.operation(revealAndHighlightLine.bind(this));} attached() {super.attached();this._codeMirror.refresh(); this._revealPendingPositionIfPossible();} setBreakpointInfoForLineAndColumn(lineNumber,columnNumber,breakpointInfo) {if(this._ignoreSetBreakpointInfoCalls) return;if(breakpointInfo) this._addBreakpointToLineAndColumnWithInfo(lineNumber,columnNumber,breakpointInfo);else this._removeBreakpointFromLineAndColumn(lineNumber,columnNumber);} updateBreakpointLineAndColumn(oldLineNumber,oldColumnNumber,newLineNumber,newColumnNumber) {if(!this._breakpoints[oldLineNumber]) return;if(!this._breakpoints[oldLineNumber][oldColumnNumber]) return;var breakpointInfo=this._breakpoints[oldLineNumber][oldColumnNumber];this._removeBreakpointFromLineAndColumn(oldLineNumber,oldColumnNumber);this._addBreakpointToLineAndColumnWithInfo(newLineNumber,newColumnNumber,breakpointInfo);} addStyleClassToLine(lineNumber,styleClassName) {var lineHandle=this._codeMirror.getLineHandle(lineNumber);if(!lineHandle) return null;return this._codeMirror.addLineClass(lineHandle,"wrap",styleClassName);} removeStyleClassFromLine(lineNumber,styleClassName) {var lineHandle=this._codeMirror.getLineHandle(lineNumber);if(!lineHandle) return null;return this._codeMirror.removeLineClass(lineHandle,"wrap",styleClassName);} toggleStyleClassForLine(lineNumber,styleClassName) {var lineHandle=this._codeMirror.getLineHandle(lineNumber);if(!lineHandle) return false;return this._codeMirror.toggleLineClass(lineHandle,"wrap",styleClassName);} createWidgetForLine(lineNumber) {var lineHandle=this._codeMirror.getLineHandle(lineNumber);if(!lineHandle) return null;var widgetElement=document.createElement("div");var lineWidget=this._codeMirror.addLineWidget(lineHandle,widgetElement,{coverGutter:false,noHScroll:true});return new WI.LineWidget(lineWidget,widgetElement);} get lineCount() {return this._codeMirror.lineCount();} focus() {this._codeMirror.focus();} contentDidChange(replacedRanges,newRanges) {} rectsForRange(range) {return this._codeMirror.rectsForRange(range);} get markers() {return this._codeMirror.getAllMarks().map(WI.TextMarker.textMarkerForCodeMirrorTextMarker);} markersAtPosition(position) {return this._codeMirror.findMarksAt(position).map(WI.TextMarker.textMarkerForCodeMirrorTextMarker);} createColorMarkers(range) {return createCodeMirrorColorTextMarkers(this._codeMirror,range);} createGradientMarkers(range) {return createCodeMirrorGradientTextMarkers(this._codeMirror,range);} createCubicBezierTimingFunctionMarkers(range) {return createCodeMirrorCubicBezierTimingFunctionTextMarkers(this._codeMirror,range);} createLinearTimingFunctionMarkers(range) {return createCodeMirrorLinearTimingFunctionTextMarkers(this._codeMirror,range);} createSpringTimingFunctionMarkers(range) {return createCodeMirrorSpringTimingFunctionTextMarkers(this._codeMirror,range);} createStepsTimingFunctionMarkers(range) {return createCodeMirrorStepsTimingFunctionTextMarkers(this._codeMirror,range);} editingControllerForMarker(editableMarker) {switch(editableMarker.type){case WI.TextMarker.Type.Color:return new WI.CodeMirrorColorEditingController(this._codeMirror,editableMarker);case WI.TextMarker.Type.Gradient:return new WI.CodeMirrorGradientEditingController(this._codeMirror,editableMarker);case WI.TextMarker.Type.CubicBezierTimingFunction:return new WI.CodeMirrorCubicBezierTimingFunctionEditingController(this._codeMirror,editableMarker);case WI.TextMarker.Type.LinearTimingFunction:return new WI.CodeMirrorLinearTimingFunctionEditingController(this._codeMirror,editableMarker);case WI.TextMarker.Type.SpringTimingFunction:return new WI.CodeMirrorSpringTimingFunctionEditingController(this._codeMirror,editableMarker);case WI.TextMarker.Type.StepsTimingFunction:return new WI.CodeMirrorStepsTimingFunctionEditingController(this._codeMirror,editableMarker);default:return new WI.CodeMirrorEditingController(this._codeMirror,editableMarker);}} visibleRangeOffsets() {var startOffset=null;var endOffset=null;var visibleRange=this._codeMirror.getViewport();if(this._formatterSourceMap){startOffset=this._formatterSourceMap.formattedToOriginalOffset(Math.max(visibleRange.from-1,0),0);endOffset=this._formatterSourceMap.formattedToOriginalOffset(visibleRange.to-1,0);}else{startOffset=this._codeMirror.getDoc().indexFromPos({line:visibleRange.from,ch:0});endOffset=this._codeMirror.getDoc().indexFromPos({line:visibleRange.to,ch:0});} return{startOffset,endOffset};} visibleRangePositions() {let visibleRange=this._codeMirror.getViewport();let startLine;let endLine;if(this._formatterSourceMap){startLine=this._formatterSourceMap.formattedToOriginal(Math.max(visibleRange.from-1,0),0).lineNumber;endLine=this._formatterSourceMap.formattedToOriginal(visibleRange.to-1,0).lineNumber;}else{startLine=visibleRange.from;endLine=visibleRange.to;} return{startPosition:new WI.SourceCodePosition(startLine,0),endPosition:new WI.SourceCodePosition(endLine,0)};} originalPositionToCurrentPosition(position) {if(!this._formatterSourceMap) return position;let{lineNumber,columnNumber}=this._formatterSourceMap.originalToFormatted(position.lineNumber,position.columnNumber);return new WI.SourceCodePosition(lineNumber,columnNumber);} originalOffsetToCurrentPosition(offset) {var position=null;if(this._formatterSourceMap){var location=this._formatterSourceMap.originalPositionToFormatted(offset);position={line:location.lineNumber,ch:location.columnNumber};}else position=this._codeMirror.getDoc().posFromIndex(offset);return position;} currentOffsetToCurrentPosition(offset) {let pos=this._codeMirror.getDoc().posFromIndex(offset);return new WI.SourceCodePosition(pos.line,pos.ch);} currentPositionToOriginalOffset(position) {let offset=null;if(this._formatterSourceMap) offset=this._formatterSourceMap.formattedToOriginalOffset(position.line,position.ch);else offset=this._codeMirror.getDoc().indexFromPos(position);return offset;} currentPositionToOriginalPosition(position) {if(!this._formatterSourceMap) return position;let location=this._formatterSourceMap.formattedToOriginal(position.lineNumber,position.columnNumber);return new WI.SourceCodePosition(location.lineNumber,location.columnNumber);} currentPositionToCurrentOffset(position) {return this._codeMirror.getDoc().indexFromPos(position.toCodeMirror());} setInlineWidget(position,inlineElement) {return this._codeMirror.setUniqueBookmark(position.toCodeMirror(),{widget:inlineElement});} addScrollHandler(handler) {this._codeMirror.on("scroll",handler);} removeScrollHandler(handler) {this._codeMirror.off("scroll",handler);} layout() {super.layout();this._codeMirror.refresh();} _format(formatted) {if(this._formatted===formatted) return Promise.resolve(this._formatted);if(formatted&&!this.canBeFormatted()) return Promise.resolve(this._formatted);if(this._formattingPromise) return this._formattingPromise;this._ignoreCodeMirrorContentDidChangeEvent++;this._formattingPromise=this.prettyPrint(formatted).then(()=>{this._ignoreCodeMirrorContentDidChangeEvent--;this._formattingPromise=null;let originalFormatted=this._formatted;this._formatted=!!this._formatterSourceMap;if(this._formatted!==originalFormatted) this.dispatchEventToListeners(WI.TextEditor.Event.FormattingDidChange);return this._formatted;});return this._formattingPromise;} prettyPrint(pretty) {return new Promise((resolve,reject)=>{let beforePrettyPrintState={selectionAnchor:this._codeMirror.getCursor("anchor"),selectionHead:this._codeMirror.getCursor("head"),};if(!pretty) this._undoFormatting(beforePrettyPrintState,resolve);else this._startWorkerPrettyPrint(beforePrettyPrintState,resolve);});} _attemptToDetermineMIMEType() {let startTime=Date.now();const isModule=false;const includeSourceMapData=false;let workerProxy=WI.FormatterWorkerProxy.singleton();workerProxy.formatJavaScript(this.string,isModule,WI.indentString(),includeSourceMapData,({formattedText})=>{if(!formattedText) return;this.mimeType="text/javascript";if(Date.now()-startTime<100) this.updateFormattedState(true);});} _startWorkerPrettyPrint(beforePrettyPrintState,callback) {let workerProxy=WI.FormatterWorkerProxy.singleton();let sourceText=this._codeMirror.getValue();let indentString=WI.indentString();const includeSourceMapData=true;let formatCallback=({formattedText,sourceMapData})=>{if(formattedText===null){callback();return;} this._finishPrettyPrint(beforePrettyPrintState,formattedText,sourceMapData,callback);};let mode=this._codeMirror.getMode().name;switch(mode){case"javascript":{let sourceType=this._delegate?this._delegate.textEditorScriptSourceType(this):WI.Script.SourceType.Program;const isModule=sourceType===WI.Script.SourceType.Module;workerProxy.formatJavaScript(sourceText,isModule,indentString,includeSourceMapData,formatCallback);break;} case"css":workerProxy.formatCSS(sourceText,indentString,includeSourceMapData,formatCallback);break;case"htmlmixed":workerProxy.formatHTML(sourceText,indentString,includeSourceMapData,formatCallback);break;case"xml":workerProxy.formatXML(sourceText,indentString,includeSourceMapData,formatCallback);break;default:break;}} _finishPrettyPrint(beforePrettyPrintState,formattedText,sourceMapData,callback) {this._codeMirror.operation(()=>{this._formatterSourceMap=WI.FormatterSourceMap.fromSourceMapData(sourceMapData);this._codeMirror.setValue(formattedText);this._updateAfterFormatting(true,beforePrettyPrintState);});callback();} _undoFormatting(beforePrettyPrintState,callback) {this._codeMirror.operation(()=>{this._codeMirror.undo();this._updateAfterFormatting(false,beforePrettyPrintState);});callback();} _updateAfterFormatting(pretty,beforePrettyPrintState) {let oldSelectionAnchor=beforePrettyPrintState.selectionAnchor;let oldSelectionHead=beforePrettyPrintState.selectionHead;let newSelectionAnchor,newSelectionHead;let newExecutionLocation=null;if(pretty){if(this._pendingPositionToReveal){let newRevealPosition=this._formatterSourceMap.originalToFormatted(this._pendingPositionToReveal.lineNumber,this._pendingPositionToReveal.columnNumber);this._pendingPositionToReveal=new WI.SourceCodePosition(newRevealPosition.lineNumber,newRevealPosition.columnNumber);} if(this._pendingRevealPositionOptions?.textRangeToSelect){let mappedRevealSelectionStart=this._formatterSourceMap.originalToFormatted(this._pendingRevealPositionOptions.textRangeToSelect.startLine,this._pendingRevealPositionOptions.textRangeToSelect.startColumn);let mappedRevealSelectionEnd=this._formatterSourceMap.originalToFormatted(this._pendingRevealPositionOptions.textRangeToSelect.endLine,this._pendingRevealPositionOptions.textRangeToSelect.endColumn);this._pendingRevealPositionOptions.textRangeToSelect=new WI.TextRange(mappedRevealSelectionStart.lineNumber,mappedRevealSelectionStart.columnNumber,mappedRevealSelectionEnd.lineNumber,mappedRevealSelectionEnd.columnNumber);} if(!isNaN(this._executionLineNumber)){newExecutionLocation=this._formatterSourceMap.originalToFormatted(this._executionLineNumber,this._executionColumnNumber);} let mappedAnchorLocation=this._formatterSourceMap.originalToFormatted(oldSelectionAnchor.line,oldSelectionAnchor.ch);let mappedHeadLocation=this._formatterSourceMap.originalToFormatted(oldSelectionHead.line,oldSelectionHead.ch);newSelectionAnchor={line:mappedAnchorLocation.lineNumber,ch:mappedAnchorLocation.columnNumber};newSelectionHead={line:mappedHeadLocation.lineNumber,ch:mappedHeadLocation.columnNumber};}else{if(this._pendingPositionToReveal){let newRevealPosition=this._formatterSourceMap.formattedToOriginal(this._pendingPositionToReveal.lineNumber,this._pendingPositionToReveal.columnNumber);this._pendingPositionToReveal=new WI.SourceCodePosition(newRevealPosition.lineNumber,newRevealPosition.columnNumber);} if(this._pendingRevealPositionOptions?.textRangeToSelect){let mappedRevealSelectionStart=this._formatterSourceMap.formattedToOriginal(this._pendingRevealPositionOptions.textRangeToSelect.startLine,this._pendingRevealPositionOptions.textRangeToSelect.startColumn);let mappedRevealSelectionEnd=this._formatterSourceMap.formattedToOriginal(this._pendingRevealPositionOptions.textRangeToSelect.endLine,this._pendingRevealPositionOptions.textRangeToSelect.endColumn);this._pendingRevealPositionOptions.textRangeToSelect=new WI.TextRange(mappedRevealSelectionStart.lineNumber,mappedRevealSelectionStart.columnNumber,mappedRevealSelectionEnd.lineNumber,mappedRevealSelectionEnd.columnNumber);} if(!isNaN(this._executionLineNumber)){newExecutionLocation=this._formatterSourceMap.formattedToOriginal(this._executionLineNumber,this._executionColumnNumber);} let mappedAnchorLocation=this._formatterSourceMap.formattedToOriginal(oldSelectionAnchor.line,oldSelectionAnchor.ch);let mappedHeadLocation=this._formatterSourceMap.formattedToOriginal(oldSelectionHead.line,oldSelectionHead.ch);newSelectionAnchor={line:mappedAnchorLocation.lineNumber,ch:mappedAnchorLocation.columnNumber};newSelectionHead={line:mappedHeadLocation.lineNumber,ch:mappedHeadLocation.columnNumber};this._formatterSourceMap=null;} this._scrollIntoViewCentered(newSelectionAnchor);this._codeMirror.setSelection(newSelectionAnchor,newSelectionHead);if(newExecutionLocation){this._executionLineHandle=null;this._executionMultilineHandles=[];this.setExecutionLineAndColumn(newExecutionLocation.lineNumber,newExecutionLocation.columnNumber);} if(this.currentSearchQuery){let searchQuery=this.currentSearchQuery;this.searchCleared();setTimeout(()=>{this.performSearch(searchQuery);},0);} if(this._delegate&&typeof this._delegate.textEditorUpdatedFormatting==="function") this._delegate.textEditorUpdatedFormatting(this);} hasEdits() {return!this._codeMirror.isClean();} _editorFocused(codeMirror) {this.dispatchEventToListeners(WI.TextEditor.Event.Focused);} _contentChanged(codeMirror,change) {if(this._ignoreCodeMirrorContentDidChangeEvent>0) return;var replacedRanges=[];var newRanges=[];while(change){replacedRanges.push(new WI.TextRange(change.from.line,change.from.ch,change.to.line,change.to.ch));newRanges.push(new WI.TextRange(change.from.line,change.from.ch,change.from.line+change.text.length-1,change.text.length===1?change.from.ch+change.text[0].length:change.text.lastValue.length));change=change.next;} this.contentDidChange(replacedRanges,newRanges);if(this._formatted){this._formatterSourceMap=null;this._formatted=false;if(this._delegate&&typeof this._delegate.textEditorUpdatedFormatting==="function") this._delegate.textEditorUpdatedFormatting(this);this.dispatchEventToListeners(WI.TextEditor.Event.FormattingDidChange);} this.dispatchEventToListeners(WI.TextEditor.Event.ContentDidChange);} _textRangeFromCodeMirrorPosition(start,end) {return new WI.TextRange(start.line,start.ch,end.line,end.ch);} _codeMirrorPositionFromTextRange(textRange) {var start={line:textRange.startLine,ch:textRange.startColumn};var end={line:textRange.endLine,ch:textRange.endColumn};return{start,end};} _revealPendingPositionIfPossible() {if(!this._pendingPositionToReveal) return;if(!this.isAttached) return;this.revealPosition(this._pendingPositionToReveal,this._pendingRevealPositionOptions);} _revealSearchResult(result,changeFocus,directionInCaseOfRevalidation) {let position=result.find();if(!position){this._revalidateSearchResults(directionInCaseOfRevalidation);return;} if(!this._isPositionVisible(position.from)) this._scrollIntoViewCentered(position.from);this.selectedTextRange=this._textRangeFromCodeMirrorPosition(position.from,position.to);this._automaticallyRevealFirstSearchResult=false;if(changeFocus) this._codeMirror.focus();let highlightEditorPosition=this._codeMirror.getCursor("start");let textContent=this._codeMirror.getSelection(); this._removeBouncyHighlightElementIfNeeded();this._bouncyHighlightElement=document.createElement("div");this._bouncyHighlightElement.className=WI.TextEditor.BouncyHighlightStyleClassName;this._bouncyHighlightElement.textContent=textContent;function positionBouncyHighlight(){let coordinates=this._codeMirror.cursorCoords(highlightEditorPosition,"page");let textEditorRect=this.element.getBoundingClientRect();coordinates.top-=textEditorRect.top;coordinates.left-=textEditorRect.left;this._bouncyHighlightElement.style.top=coordinates.top+"px";this._bouncyHighlightElement.style.left=coordinates.left+"px";} positionBouncyHighlight.call(this);this.element.appendChild(this._bouncyHighlightElement);this._bouncyHighlightScrollHandler=()=>{positionBouncyHighlight.call(this);};this.addScrollHandler(this._bouncyHighlightScrollHandler);this._bouncyHighlightElement.addEventListener("animationend",()=>{this._removeBouncyHighlightElementIfNeeded();});} _removeBouncyHighlightElementIfNeeded() {if(!this._bouncyHighlightElement) return;this.removeScrollHandler(this._bouncyHighlightScrollHandler);this._bouncyHighlightScrollHandler=null;this._bouncyHighlightElement.remove();this._bouncyHighlightElement=null;} _binarySearchInsertionIndexInSearchResults(object,comparator) { var array=this._searchResults;var first=0;var last=array.length-1;while(first<=last){var mid=(first+last)>>1;var c=comparator(object,array[mid]);if(c===null) return null;if(c>0) first=mid+1;else if(c<0) last=mid-1;else return mid;} return first-1;} _revealFirstSearchResultBeforeCursor(changeFocus) {var currentCursorPosition=this._codeMirror.getCursor("start");if(currentCursorPosition.line===0&¤tCursorPosition.ch===0){this._currentSearchResultIndex=this._searchResults.length-1;this._revealSearchResult(this._searchResults[this._currentSearchResultIndex],changeFocus,-1);return;} var index=this._binarySearchInsertionIndexInSearchResults(currentCursorPosition,function(current,searchResult){var searchResultMarker=searchResult.find();if(!searchResultMarker) return null;return WI.compareCodeMirrorPositions(current,searchResultMarker.from);});if(index===null){this._revalidateSearchResults(-1);return;} this._currentSearchResultIndex=index;this._revealSearchResult(this._searchResults[this._currentSearchResultIndex],changeFocus);} _revealFirstSearchResultAfterCursor(changeFocus) {var currentCursorPosition=this._codeMirror.getCursor("start");if(currentCursorPosition.line===0&¤tCursorPosition.ch===0){this._currentSearchResultIndex=0;this._revealSearchResult(this._searchResults[this._currentSearchResultIndex],changeFocus,1);return;} var index=this._binarySearchInsertionIndexInSearchResults(currentCursorPosition,function(current,searchResult){var searchResultMarker=searchResult.find();if(!searchResultMarker) return null;return WI.compareCodeMirrorPositions(current,searchResultMarker.from);});if(index===null){this._revalidateSearchResults(1);return;} if(index+10) this._revealFirstSearchResultAfterCursor();else this._revealFirstSearchResultBeforeCursor();}} _clearMultilineExecutionLineHighlights() {if(this._executionMultilineHandles.length){for(let lineHandle of this._executionMultilineHandles) this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.ExecutionLineStyleClassName);this._executionMultilineHandles=[];}} _updateExecutionLine() {this._codeMirror.operation(()=>{if(this._executionLineHandle){this._codeMirror.removeLineClass(this._executionLineHandle,"wrap",WI.TextEditor.ExecutionLineStyleClassName);this._codeMirror.removeLineClass(this._executionLineHandle,"wrap","primary");} this._clearMultilineExecutionLineHighlights();this._executionLineHandle=!isNaN(this._executionLineNumber)?this._codeMirror.getLineHandle(this._executionLineNumber):null;if(this._executionLineHandle){this._codeMirror.addLineClass(this._executionLineHandle,"wrap",WI.TextEditor.ExecutionLineStyleClassName);this._codeMirror.addLineClass(this._executionLineHandle,"wrap","primary");this._codeMirror.removeLineClass(this._executionLineHandle,"wrap",WI.TextEditor.HighlightedStyleClassName);}});} _updateExecutionRangeHighlight() {if(this._executionRangeHighlightMarker){this._executionRangeHighlightMarker.clear();this._executionRangeHighlightMarker=null;} if(isNaN(this._executionLineNumber)) return;let currentPosition=new WI.SourceCodePosition(this._executionLineNumber,this._executionColumnNumber);this._delegate.textEditorExecutionHighlightRange(currentPosition,(range)=>{let start,end;if(!range){start={line:this._executionLineNumber,ch:this._executionColumnNumber};end={line:this._executionLineNumber};}else{start=range.startPosition.toCodeMirror();end=range.endPosition.toCodeMirror();} if(this._executionRangeHighlightMarker){this._executionRangeHighlightMarker.clear();this._executionRangeHighlightMarker=null;} let text=this._codeMirror.getRange(start,end);let trailingWhitespace=text.match(/\s+$/);if(trailingWhitespace) end.ch=Math.max(0,end.ch-trailingWhitespace[0].length);this._clearMultilineExecutionLineHighlights();if(start.line!==end.line){for(let line=start.line;line1;for(var columnNumber in columnBreakpoints){var breakpointInfo=columnBreakpoints[columnNumber];if(!breakpointInfo.disabled) allDisabled=false;if(!breakpointInfo.resolved) allResolved=false;if(!breakpointInfo.autoContinue) allAutoContinue=false;} allResolved=allResolved&&WI.debuggerManager.breakpointsEnabled;function updateStyles() {var lineHandle=this._codeMirror.getLineHandle(lineNumber);if(!lineHandle) return;this._codeMirror.addLineClass(lineHandle,"wrap",WI.TextEditor.HasBreakpointStyleClassName);if(allResolved) this._codeMirror.addLineClass(lineHandle,"wrap",WI.TextEditor.BreakpointResolvedStyleClassName);else this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.BreakpointResolvedStyleClassName);if(allDisabled) this._codeMirror.addLineClass(lineHandle,"wrap",WI.TextEditor.BreakpointDisabledStyleClassName);else this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.BreakpointDisabledStyleClassName);if(allAutoContinue) this._codeMirror.addLineClass(lineHandle,"wrap",WI.TextEditor.BreakpointAutoContinueStyleClassName);else this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.BreakpointAutoContinueStyleClassName);if(multiple) this._codeMirror.addLineClass(lineHandle,"wrap",WI.TextEditor.MultipleBreakpointsStyleClassName);else this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.MultipleBreakpointsStyleClassName);} this._codeMirror.operation(updateStyles.bind(this));} _addBreakpointToLineAndColumnWithInfo(lineNumber,columnNumber,breakpointInfo) {if(!this._breakpoints[lineNumber]) this._breakpoints[lineNumber]={};this._breakpoints[lineNumber][columnNumber]=breakpointInfo;this._setBreakpointStylesOnLine(lineNumber);} _removeBreakpointFromLineAndColumn(lineNumber,columnNumber) {if(!nullish(columnNumber)){delete this._breakpoints[lineNumber][columnNumber];if(!isEmptyObject(this._breakpoints[lineNumber])){this._setBreakpointStylesOnLine(lineNumber);return;}} delete this._breakpoints[lineNumber];function updateStyles() {var lineHandle=this._codeMirror.getLineHandle(lineNumber);if(!lineHandle) return;this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.HasBreakpointStyleClassName);this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.BreakpointResolvedStyleClassName);this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.BreakpointDisabledStyleClassName);this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.BreakpointAutoContinueStyleClassName);this._codeMirror.removeLineClass(lineHandle,"wrap",WI.TextEditor.MultipleBreakpointsStyleClassName);} this._codeMirror.operation(updateStyles.bind(this));} _allColumnBreakpointInfoForLine(lineNumber) {return this._breakpoints[lineNumber];} _setColumnBreakpointInfoForLine(lineNumber,columnBreakpointInfo) {this._breakpoints[lineNumber]=columnBreakpointInfo;this._setBreakpointStylesOnLine(lineNumber);} _gutterMouseDown(codeMirror,lineNumber,gutterElement,event) {if(event.button!==0||event.ctrlKey) return;if(!this._codeMirror.hasLineClass(lineNumber,"wrap",WI.TextEditor.HasBreakpointStyleClassName)){if(this._delegate&&typeof this._delegate.textEditorBreakpointAdded==="function"){var data=this._delegate.textEditorBreakpointAdded(this,lineNumber,0);if(data){var breakpointInfo=data.breakpointInfo;if(breakpointInfo) this._addBreakpointToLineAndColumnWithInfo(data.lineNumber,data.columnNumber,breakpointInfo);}} return;} this._lineNumberWithMousedDownBreakpoint=lineNumber;this._lineNumberWithDraggedBreakpoint=lineNumber;this._draggingBreakpointInfo=this._breakpoints[lineNumber];let columnNumbers=Object.keys(this._breakpoints[lineNumber]);if(columnNumbers.length===1){let columnNumber=columnNumbers[0];this._draggingBreakpointInfo=this._draggingBreakpointInfo[columnNumber];this._columnNumberWithMousedDownBreakpoint=columnNumber;this._columnNumberWithDraggedBreakpoint=columnNumber;} this._documentMouseMovedEventListener=this._documentMouseMoved.bind(this);this._documentMouseUpEventListener=this._documentMouseUp.bind(this);document.addEventListener("mousemove",this._documentMouseMovedEventListener,true);document.addEventListener("mouseup",this._documentMouseUpEventListener,true);} _gutterContextMenu(codeMirror,lineNumber,gutterElement,event) {if(this._delegate&&typeof this._delegate.textEditorGutterContextMenu==="function"){var breakpoints=[];for(var columnNumber in this._breakpoints[lineNumber]) breakpoints.push({lineNumber,columnNumber});this._delegate.textEditorGutterContextMenu(this,lineNumber,0,breakpoints,event);}} _documentMouseMoved(event) {if(!("_lineNumberWithMousedDownBreakpoint"in this)) return;event.preventDefault();var lineNumber;var position=this._codeMirror.coordsChar({left:event.pageX,top:event.pageY}); var gutterBounds=this._codeMirror.getGutterElement().getBoundingClientRect();if(event.pageXgutterBounds.right||event.pageYgutterBounds.bottom) position=null;if(position&&"line"in position) lineNumber=position.line; if(lineNumber===this._lineNumberWithDraggedBreakpoint) return; this._mouseDragged=true;if(!("_columnNumberWithMousedDownBreakpoint"in this)){if(lineNumber===this._lineNumberWithMousedDownBreakpoint){this._setColumnBreakpointInfoForLine(lineNumber,this._draggingBreakpointInfo);this._lineNumberWithDraggedBreakpoint=lineNumber;}else{this._removeBreakpointFromLineAndColumn(this._lineNumberWithMousedDownBreakpoint);delete this._lineNumberWithDraggedBreakpoint;} return;} if("_lineNumberWithDraggedBreakpoint"in this){ if(this._previousColumnBreakpointInfo) this._setColumnBreakpointInfoForLine(this._lineNumberWithDraggedBreakpoint,this._previousColumnBreakpointInfo);else this._removeBreakpointFromLineAndColumn(this._lineNumberWithDraggedBreakpoint,this._columnNumberWithDraggedBreakpoint);delete this._previousColumnBreakpointInfo;delete this._lineNumberWithDraggedBreakpoint;delete this._columnNumberWithDraggedBreakpoint;} if(lineNumber!==undefined){var newColumnBreakpoints={};var columnNumber=lineNumber===this._lineNumberWithMousedDownBreakpoint?this._columnNumberWithDraggedBreakpoint:0;newColumnBreakpoints[columnNumber]=this._draggingBreakpointInfo;this._previousColumnBreakpointInfo=this._allColumnBreakpointInfoForLine(lineNumber);this._setColumnBreakpointInfoForLine(lineNumber,newColumnBreakpoints);this._lineNumberWithDraggedBreakpoint=lineNumber;this._columnNumberWithDraggedBreakpoint=columnNumber;}} _documentMouseUp(event) {if(!("_lineNumberWithMousedDownBreakpoint"in this)) return;event.preventDefault();document.removeEventListener("mousemove",this._documentMouseMovedEventListener,true);document.removeEventListener("mouseup",this._documentMouseUpEventListener,true);var delegateImplementsBreakpointClicked=this._delegate&&typeof this._delegate.textEditorBreakpointClicked==="function";var delegateImplementsBreakpointRemoved=this._delegate&&typeof this._delegate.textEditorBreakpointRemoved==="function";var delegateImplementsBreakpointMoved=this._delegate&&typeof this._delegate.textEditorBreakpointMoved==="function";if(this._mouseDragged){if(!("_lineNumberWithDraggedBreakpoint"in this)){if(delegateImplementsBreakpointRemoved){this._ignoreSetBreakpointInfoCalls=true;this._delegate.textEditorBreakpointRemoved(this,this._lineNumberWithMousedDownBreakpoint,this._columnNumberWithMousedDownBreakpoint);delete this._ignoreSetBreakpointInfoCalls;}}else if(this._lineNumberWithMousedDownBreakpoint!==this._lineNumberWithDraggedBreakpoint){ if(this._previousColumnBreakpointInfo&&delegateImplementsBreakpointRemoved){this._ignoreSetBreakpointInfoCalls=true;this._delegate.textEditorBreakpointRemoved(this,this._lineNumberWithDraggedBreakpoint);delete this._ignoreSetBreakpointInfoCalls;} if("_columnNumberWithDraggedBreakpoint"in this&&delegateImplementsBreakpointMoved){this._ignoreSetBreakpointInfoCalls=true;this._delegate.textEditorBreakpointMoved(this,this._lineNumberWithMousedDownBreakpoint,this._columnNumberWithMousedDownBreakpoint,this._lineNumberWithDraggedBreakpoint,this._columnNumberWithDraggedBreakpoint);delete this._ignoreSetBreakpointInfoCalls;}}}else{if(this._lineNumberWithMousedDownBreakpoint in this._breakpoints&&(!("_columnNumberWithMousedDownBreakpoint"in this)||this._columnNumberWithMousedDownBreakpoint in this._breakpoints[this._lineNumberWithMousedDownBreakpoint])&&delegateImplementsBreakpointClicked) this._delegate.textEditorBreakpointClicked(this,this._lineNumberWithMousedDownBreakpoint,this._columnNumberWithMousedDownBreakpoint);} delete this._documentMouseMovedEventListener;delete this._documentMouseUpEventListener;delete this._lineNumberWithMousedDownBreakpoint;delete this._lineNumberWithDraggedBreakpoint;delete this._columnNumberWithMousedDownBreakpoint;delete this._columnNumberWithDraggedBreakpoint;delete this._previousColumnBreakpointInfo;delete this._mouseDragged;} _openClickedLinks(event) {if(!this.readOnly&&!event.commandOrControlKey) return;var position=this._codeMirror.coordsChar({left:event.pageX,top:event.pageY});var tokenInfo=this._codeMirror.getTokenAt(position);if(!tokenInfo||!tokenInfo.type||!tokenInfo.string) return;if(!/\blink\b/.test(tokenInfo.type)) return;var url=tokenInfo.string;var baseURL="";if(this._delegate&&typeof this._delegate.textEditorBaseURL==="function") baseURL=this._delegate.textEditorBaseURL(this);WI.openURL(absoluteURL(url,baseURL));event.preventDefault();event.stopPropagation();} _isPositionVisible(position) {var scrollInfo=this._codeMirror.getScrollInfo();var visibleRangeStart=scrollInfo.top;var visibleRangeEnd=visibleRangeStart+scrollInfo.clientHeight;var coords=this._codeMirror.charCoords(position,"local");return coords.top>=visibleRangeStart&&coords.bottom<=visibleRangeEnd;} _scrollIntoViewCentered(position) {var scrollInfo=this._codeMirror.getScrollInfo();var lineHeight=Math.ceil(this._codeMirror.defaultTextHeight());var margin=Math.floor((scrollInfo.clientHeight-lineHeight)/2);this._codeMirror.scrollIntoView(position,margin);}};WI.TextEditor.HighlightedStyleClassName="highlighted";WI.TextEditor.SearchResultStyleClassName="search-result";WI.TextEditor.HasBreakpointStyleClassName="has-breakpoint";WI.TextEditor.BreakpointResolvedStyleClassName="breakpoint-resolved";WI.TextEditor.BreakpointAutoContinueStyleClassName="breakpoint-auto-continue";WI.TextEditor.BreakpointDisabledStyleClassName="breakpoint-disabled";WI.TextEditor.MultipleBreakpointsStyleClassName="multiple-breakpoints";WI.TextEditor.ExecutionLineStyleClassName="execution-line";WI.TextEditor.BouncyHighlightStyleClassName="bouncy-highlight";WI.TextEditor.NumberOfFindsPerSearchBatch=10;WI.TextEditor.HighlightAnimationDuration=2000;WI.TextEditor.Event={Focused:"text-editor-focused",ExecutionLineNumberDidChange:"text-editor-execution-line-number-did-change",NumberOfSearchResultsDidChange:"text-editor-number-of-search-results-did-change",ContentDidChange:"text-editor-content-did-change",FormattingDidChange:"text-editor-formatting-did-change",MIMETypeChanged:"text-editor-mime-type-changed",};WI.TimelineOverviewGraph=class TimelineOverviewGraph extends WI.View {constructor(timelineOverview) {super();this.element.classList.add("timeline-overview-graph");this._zeroTime=0;this._startTime=0;this._endTime=5;this._currentTime=0;this._timelineOverview=timelineOverview;this._selectedRecord=null;this._selectedRecordBar=null;this._scheduledSelectedRecordLayoutUpdateIdentifier=undefined;this._selected=false;this._hidden=false;} static createForTimeline(timeline,timelineOverview) {var timelineType=timeline.type;if(timelineType===WI.TimelineRecord.Type.Network) return new WI.NetworkTimelineOverviewGraph(timeline,timelineOverview);if(timelineType===WI.TimelineRecord.Type.Layout) return new WI.LayoutTimelineOverviewGraph(timeline,timelineOverview);if(timelineType===WI.TimelineRecord.Type.Script) return new WI.ScriptTimelineOverviewGraph(timeline,timelineOverview);if(timelineType===WI.TimelineRecord.Type.RenderingFrame) return new WI.RenderingFrameTimelineOverviewGraph(timeline,timelineOverview);if(timelineType===WI.TimelineRecord.Type.CPU) return new WI.CPUTimelineOverviewGraph(timeline,timelineOverview);if(timelineType===WI.TimelineRecord.Type.Memory) return new WI.MemoryTimelineOverviewGraph(timeline,timelineOverview);if(timelineType===WI.TimelineRecord.Type.HeapAllocations) return new WI.HeapAllocationsTimelineOverviewGraph(timeline,timelineOverview);if(timelineType===WI.TimelineRecord.Type.Media) return new WI.MediaTimelineOverviewGraph(timeline,timelineOverview);if(timelineType===WI.TimelineRecord.Type.Screenshots) return new WI.ScreenshotsTimelineOverviewGraph(timeline,timelineOverview);throw new Error("Can't make a graph for an unknown timeline.");} get zeroTime() {return this._zeroTime;} set zeroTime(x) {x=x||0;if(this._zeroTime===x) return;this._zeroTime=x;this.needsLayout();} get startTime() {return this._startTime;} set startTime(x) {x=x||0;if(this._startTime===x) return;this._startTime=x;this.needsLayout();} get endTime() {return this._endTime;} set endTime(x) {x=x||0;if(this._endTime===x) return;this._endTime=x;this.needsLayout();} get currentTime() {return this._currentTime;} set currentTime(x) {x=x||0;if(this._currentTime===x) return;let oldCurrentTime=this._currentTime;this._currentTime=x;if((this._startTime<=oldCurrentTime&&oldCurrentTime<=this._endTime)||(this._startTime<=this._currentTime&&this._currentTime<=this._endTime)) this.needsLayout();} get timelineOverview() {return this._timelineOverview;} get secondsPerPixel(){return this._timelineOverview.secondsPerPixel;} get hidden() {return this._hidden;} set hidden(hidden) {if(!xor(hidden,this._hidden)) return;this._hidden=hidden;this.element.classList.toggle("hidden",this._hidden);if(!this._hidden) this.updateLayout();} get selectedRecord() {return this._selectedRecord;} set selectedRecord(x) {if(this._selectedRecord===x) return;this._selectedRecord=x;this._needsSelectedRecordLayout();} get selectedRecordBar() {return this._selectedRecordBar;} set selectedRecordBar(recordBar) {if(this._selectedRecordBar===recordBar) return;if(this._selectedRecordBar) this._selectedRecordBar.selected=false;this._selectedRecordBar=recordBar;if(this._selectedRecordBar){this._selectedRecordBar.selected=true;}} get height() {return 36;} get selected() {return this._selected;} set selected(x) {if(this._selected===x) return;this._selected=x;this.element.classList.toggle("selected",this._selected);} reset() {} recordWasFiltered(record,filtered) {} needsLayout() {if(this._hidden) return;super.needsLayout();} didLayoutSubtree() {super.didLayoutSubtree();this.updateSelectedRecord();} timelineRecordBarClicked(timelineRecord) {this.selectedRecord=timelineRecord;} updateSelectedRecord() {} _needsSelectedRecordLayout() {if(this.layoutPending) return;if(this._scheduledSelectedRecordLayoutUpdateIdentifier) return;this._scheduledSelectedRecordLayoutUpdateIdentifier=requestAnimationFrame(()=>{this._scheduledSelectedRecordLayoutUpdateIdentifier=undefined;this.updateSelectedRecord();this.dispatchEventToListeners(WI.TimelineOverviewGraph.Event.RecordSelected,{record:this.selectedRecord,recordBar:this.selectedRecordBar});});}};WI.TimelineOverviewGraph.Event={RecordSelected:"timeline-overview-graph-record-selected"};WI.TimelineView=class TimelineView extends WI.ContentView {constructor(representedObject) {super(representedObject);this.element.classList.add("timeline-view");this._zeroTime=0;this._startTime=0;this._endTime=5;this._currentTime=0;} get scrollableElements() {if(!this._timelineDataGrid) return[];return[this._timelineDataGrid.scrollContainer];} get showsLiveRecordingData() {return true;} get showsImportedRecordingMessage() {return false;} get showsFilterBar() {return true;} get navigationItems() {return this._scopeBar?[this._scopeBar]:[];} get selectionPathComponents() {return null;} get zeroTime() {return this._zeroTime;} set zeroTime(x) {x=x||0;if(this._zeroTime===x) return;this._zeroTime=x;this._timesDidChange();} get startTime() {return this._startTime;} set startTime(x) {x=x||0;if(this._startTime===x) return;this._startTime=x;this._timesDidChange();this._scheduleFilterDidChange();} get endTime() {return this._endTime;} set endTime(x) {x=x||0;if(this._endTime===x) return;this._endTime=x;this._timesDidChange();this._scheduleFilterDidChange();} get currentTime() {return this._currentTime;} set currentTime(x) {x=x||0;if(this._currentTime===x) return;let oldCurrentTime=this._currentTime;this._currentTime=x;function checkIfLayoutIsNeeded(currentTime) {const wiggleTime=0.05; return this._startTime-wiggleTime<=currentTime&¤tTime<=this._endTime+wiggleTime;} if(checkIfLayoutIsNeeded.call(this,oldCurrentTime)||checkIfLayoutIsNeeded.call(this,this._currentTime)) this._timesDidChange();} get filterStartTime() {return this.startTime;} get filterEndTime() {return this.endTime;} setupDataGrid(dataGrid) {if(this._timelineDataGrid){this._timelineDataGrid.filterDelegate=null;this._timelineDataGrid.removeEventListener(WI.DataGrid.Event.SelectedNodeChanged,this._timelineDataGridSelectedNodeChanged,this);this._timelineDataGrid.removeEventListener(WI.DataGrid.Event.NodeWasFiltered,this._timelineDataGridNodeWasFiltered,this);this._timelineDataGrid.removeEventListener(WI.DataGrid.Event.FilterDidChange,this.filterDidChange,this);} this._timelineDataGrid=dataGrid;this._timelineDataGrid.filterDelegate=this;this._timelineDataGrid.addEventListener(WI.DataGrid.Event.SelectedNodeChanged,this._timelineDataGridSelectedNodeChanged,this);this._timelineDataGrid.addEventListener(WI.DataGrid.Event.NodeWasFiltered,this._timelineDataGridNodeWasFiltered,this);this._timelineDataGrid.addEventListener(WI.DataGrid.Event.FilterDidChange,this.filterDidChange,this);} selectRecord(record) {if(!this._timelineDataGrid) return;let selectedDataGridNode=this._timelineDataGrid.selectedNode;if(!record){if(selectedDataGridNode) selectedDataGridNode.deselect();return;} let dataGridNode=this._timelineDataGrid.findNode((node)=>node.record===record);if(!dataGridNode||dataGridNode.selected) return;if(selectedDataGridNode&&selectedDataGridNode.hasAncestor(dataGridNode)) return;dataGridNode.revealAndSelect();} reset() {} updateFilter(filters) {if(!this._timelineDataGrid) return;this._timelineDataGrid.filterText=filters?filters.text:"";} matchDataGridNodeAgainstCustomFilters(node) {return true;} dataGridMatchNodeAgainstCustomFilters(node) {if(!this.matchDataGridNodeAgainstCustomFilters(node)) return false;let startTime=this.filterStartTime;let endTime=this.filterEndTime;let currentTime=this.currentTime;function checkTimeBounds(itemStartTime,itemEndTime) {itemStartTime=itemStartTime||currentTime;itemEndTime=itemEndTime||currentTime;return startTime<=itemEndTime&&itemStartTime<=endTime;} if(node instanceof WI.ResourceTimelineDataGridNode){let resource=node.resource;return checkTimeBounds(resource.requestSentTimestamp,resource.finishedOrFailedTimestamp);} if(node instanceof WI.SourceCodeTimelineTimelineDataGridNode){let sourceCodeTimeline=node.sourceCodeTimeline;if(!checkTimeBounds(sourceCodeTimeline.startTime,sourceCodeTimeline.endTime)) return false;for(let record of sourceCodeTimeline.records){if(checkTimeBounds(record.startTime,record.endTime)) return true;} return false;} if(node instanceof WI.ProfileNodeDataGridNode){let profileNode=node.profileNode;if(checkTimeBounds(profileNode.startTime,profileNode.endTime)) return true;return false;} if(node instanceof WI.TimelineDataGridNode){let record=node.record;return checkTimeBounds(record.startTime,record.endTime);} if(node instanceof WI.ProfileDataGridNode) return node.callingContextTreeNode.hasStackTraceInTimeRange(startTime,endTime);console.error("Unknown DataGridNode, can't filter by time.");return true;} initialLayout() {super.initialLayout();this.element.appendChild(this.constructor.ReferencePage.createLinkElement());} filterDidChange() {} _timelineDataGridSelectedNodeChanged(event) {this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);} _timelineDataGridNodeWasFiltered(event) {let node=event.data.node;if(!(node instanceof WI.TimelineDataGridNode)) return;this.dispatchEventToListeners(WI.TimelineView.Event.RecordWasFiltered,{record:node.record,filtered:node.hidden});} _timesDidChange() {if(!WI.timelineManager.isCapturing()||this.showsLiveRecordingData) this.needsLayout();} _scheduleFilterDidChange() {if(!this._timelineDataGrid||this._updateFilterTimeout) return;this._updateFilterTimeout=setTimeout(()=>{this._updateFilterTimeout=undefined;this._timelineDataGrid.filterDidChange();},0);}};WI.TimelineView.Event={RecordWasFiltered:"timeline-view-record-was-filtered",RecordWasSelected:"timeline-view-record-was-selected",ScannerShow:"timeline-view-scanner-show",ScannerHide:"timeline-view-scanner-hide",NeedsEntireSelectedRange:"timeline-view-needs-entire-selected-range",NeedsFiltersCleared:"timeline-view-needs-filters-cleared",};WI.TreeElement=class TreeElement extends WI.Object {constructor(title,representedObject,options={}) {super();this._title=title;this.representedObject=representedObject||{};if(this.representedObject.__treeElementIdentifier) this.identifier=this.representedObject.__treeElementIdentifier;else{this.identifier=WI.TreeOutline._knownTreeElementNextIdentifier++;this.representedObject.__treeElementIdentifier=this.identifier;} this._hidden=false;this._selectable=true;this.expanded=false;this.selected=false;this.hasChildren=options.hasChildren;this.children=[];this.treeOutline=null;this.parent=null;this.previousSibling=null;this.nextSibling=null;this._listItemNode=null;} appendChild(){return WI.TreeOutline.prototype.appendChild.apply(this,arguments);} insertChild(){return WI.TreeOutline.prototype.insertChild.apply(this,arguments);} removeChild(){return WI.TreeOutline.prototype.removeChild.apply(this,arguments);} removeChildAtIndex(){return WI.TreeOutline.prototype.removeChildAtIndex.apply(this,arguments);} removeChildren(){return WI.TreeOutline.prototype.removeChildren.apply(this,arguments);} selfOrDescendant(){return WI.TreeOutline.prototype.selfOrDescendant.apply(this,arguments);} get arrowToggleWidth() {return 10;} get selectable() {if(this._hidden) return false;return this._selectable;} set selectable(x) {if(x===this._selectable) return;this._selectable=x;this._listItemNode?.classList.toggle("non-selectable",!this._selectable);} get expandable() {return this.hasChildren;} get listItemElement() {return this._listItemNode;} get title() {return this._title;} set title(x) {this._title=x;this._setListItemNodeContent();this.didChange();} get titleHTML() {return this._titleHTML;} set titleHTML(x) {this._titleHTML=x;this._setListItemNodeContent();this.didChange();} get tooltip() {return this._tooltip;} set tooltip(x) {this._tooltip=x;if(this._listItemNode) this._listItemNode.title=x?x:"";} get hasChildren() {return this._hasChildren;} set hasChildren(x) {if(this._hasChildren===x) return;this._hasChildren=x;if(!this._listItemNode) return;if(x) this._listItemNode.classList.add("parent");else{this._listItemNode.classList.remove("parent");this.collapse();} this.didChange();} get hidden() {return this._hidden;} set hidden(x) {if(this._hidden===x) return;this._hidden=x;if(this._listItemNode) this._listItemNode.hidden=this._hidden;if(this._childrenListNode) this._childrenListNode.hidden=this._hidden;if(this.treeOutline){if(this.treeOutline.virtualized) this.treeOutline.updateVirtualizedElementsDebouncer.delayForFrame();this.treeOutline.dispatchEventToListeners(WI.TreeOutline.Event.ElementVisibilityDidChange,{element:this});}} get shouldRefreshChildren() {return this._shouldRefreshChildren;} set shouldRefreshChildren(x) {this._shouldRefreshChildren=x;if(x&&this.expanded) this.expand();} get previousSelectableSibling() {let treeElement=this.previousSibling;while(treeElement&&!treeElement.selectable) treeElement=treeElement.previousSibling;return treeElement;} get nextSelectableSibling() {let treeElement=this.nextSibling;while(treeElement&&!treeElement.selectable) treeElement=treeElement.nextSibling;return treeElement;} canSelectOnMouseDown(event) {return true;} _fireDidChange() {if(this.treeOutline) this.treeOutline._treeElementDidChange(this);} didChange() {if(!this.treeOutline) return;if(!this._fireDidChangeDebouncer){this._fireDidChangeDebouncer=new Debouncer(()=>{this._fireDidChange();});} this._fireDidChangeDebouncer.delayForFrame();} _setListItemNodeContent() {if(!this._listItemNode) return;if(!this._titleHTML&&!this._title) this._listItemNode.removeChildren();else if(typeof this._titleHTML==="string") this._listItemNode.innerHTML=this._titleHTML;else if(typeof this._title==="string") this._listItemNode.textContent=this._title;else{this._listItemNode.removeChildren();if(this._title.parentNode) this._title.parentNode.removeChild(this._title);this._listItemNode.appendChild(this._title);}} _attach() {if(!this._listItemNode||this.parent._shouldRefreshChildren){if(this.parent._shouldRefreshChildren) this._detach();this._listItemNode=this.treeOutline._childrenListNode.ownerDocument.createElement("li");this._listItemNode.treeElement=this;this._setListItemNodeContent();this._listItemNode.title=this._tooltip?this._tooltip:"";this._listItemNode.hidden=this.hidden;this._listItemNode.role="treeitem";if(this.hasChildren) this._listItemNode.classList.add("parent");if(this.expanded) this._listItemNode.classList.add("expanded");if(this.selected) this._listItemNode.classList.add("selected");if(!this.selectable) this._listItemNode.classList.add("non-selectable");this._listItemNode.addEventListener("click",WI.TreeElement.treeElementToggled);this._listItemNode.addEventListener("dblclick",WI.TreeElement.treeElementDoubleClicked);if(this.onattach) this.onattach(this);} var nextSibling=null;if(this.nextSibling&&this.nextSibling._listItemNode&&this.nextSibling._listItemNode.parentNode===this.parent._childrenListNode) nextSibling=this.nextSibling._listItemNode;if(!this.treeOutline||!this.treeOutline.virtualized){this.parent._childrenListNode.insertBefore(this._listItemNode,nextSibling);if(this._childrenListNode) this.parent._childrenListNode.insertBefore(this._childrenListNode,this._listItemNode.nextSibling);} if(this.selected) this.select();if(this.expanded) this.expand();} _detach() {if(this.ondetach&&this._listItemNode) this.ondetach(this);if(this._listItemNode&&this._listItemNode.parentNode) this._listItemNode.parentNode.removeChild(this._listItemNode);if(this._childrenListNode&&this._childrenListNode.parentNode) this._childrenListNode.parentNode.removeChild(this._childrenListNode);} static treeElementToggled(event) {let element=event.currentTarget;if(!element) return;let treeElement=element.treeElement;if(!treeElement) return;if(treeElement.toggleOnClick||treeElement.isEventWithinDisclosureTriangle(event)){if(treeElement.expanded){if(event.altKey) treeElement.collapseRecursively();else treeElement.collapse();}else{if(event.altKey) treeElement.expandRecursively();else treeElement.expand();} event.stopPropagation();} if(treeElement.treeOutline&&!treeElement.treeOutline.selectable) treeElement.treeOutline.dispatchEventToListeners(WI.TreeOutline.Event.ElementClicked,{treeElement});} static treeElementDoubleClicked(event) {var element=event.currentTarget;if(!element||!element.treeElement) return;if(element.treeElement.isEventWithinDisclosureTriangle(event)) return;if(element.treeElement.dispatchEventToListeners(WI.TreeElement.Event.DoubleClick)) return;if(element.treeElement.ondblclick) element.treeElement.ondblclick.call(element.treeElement,event);else if(element.treeElement.hasChildren&&!element.treeElement.expanded) element.treeElement.expand();} collapse() {if(this._listItemNode){this._listItemNode.classList.remove("expanded");this._listItemNode.ariaExpanded=false;} if(this._childrenListNode){this._childrenListNode.classList.remove("expanded");this._childrenListNode.ariaExpanded=false;} this.expanded=false;if(this.treeOutline) this.treeOutline._treeElementsExpandedState[this.identifier]=false;if(this.oncollapse) this.oncollapse(this);if(this.treeOutline){if(this.treeOutline.virtualized) this.treeOutline.updateVirtualizedElementsDebouncer.delayForFrame();this.treeOutline.dispatchEventToListeners(WI.TreeOutline.Event.ElementDisclosureDidChanged,{element:this});}} collapseRecursively() {var item=this;while(item){if(item.expanded) item.collapse();item=item.traverseNextTreeElement(false,this,true);}} expand() {if(this.expanded&&!this._shouldRefreshChildren&&this._childrenListNode) return; this.expanded=true;if(this.treeOutline) this.treeOutline._treeElementsExpandedState[this.identifier]=true;if(!this.hasChildren) return;if(this.treeOutline&&(!this._childrenListNode||this._shouldRefreshChildren)){if(this._childrenListNode&&this._childrenListNode.parentNode) this._childrenListNode.parentNode.removeChild(this._childrenListNode);this._childrenListNode=this.treeOutline._childrenListNode.ownerDocument.createElement("ol");this._childrenListNode.parentTreeElement=this;this._childrenListNode.classList.add("children");this._childrenListNode.hidden=this.hidden;this._childrenListNode.role="group";this.onpopulate(); this.expanded=true;for(var i=0;i=maxDepth,info);depth+=info.depthChange;}} hasAncestor(ancestor) {if(!ancestor) return false;var currentNode=this.parent;while(currentNode){if(ancestor===currentNode) return true;currentNode=currentNode.parent;} return false;} reveal({skipExpandingAncestors}={}) {if(!skipExpandingAncestors){let currentAncestor=this.parent;while(currentAncestor&&!currentAncestor.root){if(!currentAncestor.expanded) currentAncestor.expand();currentAncestor=currentAncestor.parent;}} if(this.treeOutline&&this.treeOutline.virtualized) this.treeOutline.updateVirtualizedElementsDebouncer.force(this);if(this.onreveal) this.onreveal(this);if(this.treeOutline) this.treeOutline.dispatchEventToListeners(WI.TreeOutline.Event.ElementRevealed,{element:this});} revealed(ignoreHidden) {if(!ignoreHidden&&this.hidden) return false;var currentAncestor=this.parent;while(currentAncestor&&!currentAncestor.root){if(!currentAncestor.expanded) return false;if(!ignoreHidden&¤tAncestor.hidden) return false;currentAncestor=currentAncestor.parent;} return true;} select(omitFocus,selectedByUser,suppressNotification) {let treeOutline=this.treeOutline;if(!treeOutline||!this.selectable) return;if(!omitFocus) this.focus();else if(treeOutline.element.contains(document.activeElement)){this.focus();} if(this.selected&&!this.treeOutline.allowsRepeatSelection) return;treeOutline=this.treeOutline;if(!treeOutline) return;this.selected=true;treeOutline.selectTreeElementInternal(this,suppressNotification,selectedByUser);if(this._listItemNode) this._listItemNode.ariaSelected=true;} revealAndSelect(omitFocus,selectedByUser,suppressNotification) {this.reveal();this.select(omitFocus,selectedByUser,suppressNotification);} deselect(suppressNotification) {if(!this.treeOutline||!this.selected) return false;this.selected=false;this.treeOutline.selectTreeElementInternal(null,suppressNotification);if(this._listItemNode){this.unfocus();this._listItemNode.ariaSelected=false;} return true;} focus() {if(!this._listItemNode) return;this._listItemNode.tabIndex=0;this._listItemNode.focus();} unfocus() {if(!this._listItemNode) return;this._listItemNode.removeAttribute("tabIndex");} onpopulate() {} traverseNextTreeElement(skipUnrevealed,stayWithin,dontPopulate,info) {function shouldSkip(element){return skipUnrevealed&&!element.revealed(true);} var depthChange=0;var element=this;if(!dontPopulate) element.onpopulate();do{if(element.hasChildren&&element.children[0]&&(!skipUnrevealed||element.expanded)){element=element.children[0];depthChange+=1;}else{while(element&&!element.nextSibling&&element.parent&&!element.parent.root&&element.parent!==stayWithin){element=element.parent;depthChange-=1;} if(element) element=element.nextSibling;}}while(element&&shouldSkip(element));if(info) info.depthChange=depthChange;return element;} traversePreviousTreeElement(skipUnrevealed,dontPopulate) {function shouldSkip(element){return skipUnrevealed&&!element.revealed(true);} var element=this;do{if(element.previousSibling){element=element.previousSibling;while(element&&element.hasChildren&&element.expanded&&!shouldSkip(element)){if(!dontPopulate) element.onpopulate();element=element.children.lastValue;}}else element=element.parent&&element.parent.root?null:element.parent;}while(element&&shouldSkip(element));return element;} isEventWithinDisclosureTriangle(event) {if(!document.contains(this._listItemNode)) return false;let computedStyle=window.getComputedStyle(this._listItemNode);let start=0;if(computedStyle.direction===WI.LayoutDirection.RTL) start+=this._listItemNode.totalOffsetRight-this._listItemNode.getComputedCSSPropertyNumberValue("padding-right")-this.arrowToggleWidth;else start+=this._listItemNode.totalOffsetLeft+this._listItemNode.getComputedCSSPropertyNumberValue("padding-left");return event.pageX>=start&&event.pageX<=start+this.arrowToggleWidth&&this.hasChildren;} populateContextMenu(contextMenu,event) {if(this.children.some((child)=>child.hasChildren)||(this.hasChildren&&!this.children.length)){contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Expand All"),this.expandRecursively.bind(this));contextMenu.appendItem(WI.UIString("Collapse All"),this.collapseRecursively.bind(this));}}};WI.TreeElement.Event={DoubleClick:"tree-element-double-click",};WI.TreeOutline=class TreeOutline extends WI.Object {constructor(selectable=true) {super();this.element=document.createElement("ol");this.element.classList.add(WI.TreeOutline.ElementStyleClassName);this.element.role="tree";this.element.addEventListener("contextmenu",this._handleContextmenu.bind(this));this.children=[];this._childrenListNode=this.element;this._childrenListNode.removeChildren();this._knownTreeElements=[];this._treeElementsExpandedState=[];this.allowsRepeatSelection=false;this.root=true;this.hasChildren=false;this.expanded=true;this.selected=false;this.treeOutline=this;this._hidden=false;this._compact=false;this._large=false;this._disclosureButtons=true;this._customIndent=false;this._selectable=selectable;this._cachedNumberOfDescendants=0;let itemForRepresentedObject=this.getCachedTreeElement.bind(this);let selectionComparator=WI.SelectionController.createTreeComparator(itemForRepresentedObject);this._selectionController=new WI.SelectionController(this,selectionComparator);this._itemWasSelectedByUser=false;this._processingSelectionChange=false;this._suppressNextSelectionDidChangeEvent=false;this._virtualizedDebouncer=null;this._virtualizedVisibleTreeElements=null;this._virtualizedAttachedTreeElements=null;this._virtualizedScrollContainer=null;this._virtualizedTreeItemHeight=NaN;this._virtualizedTopSpacer=null;this._virtualizedBottomSpacer=null;this._childrenListNode.tabIndex=0;this._childrenListNode.addEventListener("keydown",this._treeKeyDown.bind(this),true);this._childrenListNode.addEventListener("mousedown",this._handleMouseDown.bind(this));WI.TreeOutline._generateStyleRulesIfNeeded();if(!this._selectable) this.element.classList.add("non-selectable");} get allowsEmptySelection() {return this._selectionController.allowsEmptySelection;} set allowsEmptySelection(flag) {this._selectionController.allowsEmptySelection=flag;} get allowsMultipleSelection() {return this._selectionController.allowsMultipleSelection;} set allowsMultipleSelection(flag) {this._selectionController.allowsMultipleSelection=flag;} get selectedTreeElement() {return this.getCachedTreeElement(this._selectionController.lastSelectedItem);} set selectedTreeElement(treeElement) {if(treeElement) this._selectionController.selectItem(this.objectForSelection(treeElement));else this._selectionController.deselectAll();} get selectedTreeElements() {if(this.allowsMultipleSelection){let treeElements=[];for(let representedObject of this._selectionController.selectedItems) treeElements.push(this.getCachedTreeElement(representedObject));return treeElements;} let selectedTreeElement=this.selectedTreeElement;if(selectedTreeElement) return[selectedTreeElement];return[];} get processingSelectionChange(){return this._processingSelectionChange;} get hidden() {return this._hidden;} set hidden(x) {if(this._hidden===x) return;this._hidden=x;this.element.hidden=this._hidden;} get compact() {return this._compact;} set compact(x) {if(this._compact===x) return;this._compact=x;if(this._compact) this.large=false;this.element.classList.toggle("compact",this._compact);} get large() {return this._large;} set large(x) {if(this._large===x) return;this._large=x;if(this._large) this.compact=false;this.element.classList.toggle("large",this._large);} get disclosureButtons() {return this._disclosureButtons;} set disclosureButtons(x) {if(this._disclosureButtons===x) return;this._disclosureButtons=x;this.element.classList.toggle("hide-disclosure-buttons",!this._disclosureButtons);} get customIndent() {return this._customIndent;} set customIndent(x) {if(this._customIndent===x) return;this._customIndent=x;this.element.classList.toggle(WI.TreeOutline.CustomIndentStyleClassName,this._customIndent);} get selectable(){return this._selectable;} appendChild(child) {if(!child) return;var lastChild=this.children[this.children.length-1];if(lastChild){lastChild.nextSibling=child;child.previousSibling=lastChild;}else{child.previousSibling=null;child.nextSibling=null;} var isFirstChild=!this.children.length;this.children.push(child);this.hasChildren=true;child.parent=this;child.treeOutline=this.treeOutline;child.treeOutline._rememberTreeElement(child);var current=child.children[0];while(current){current.treeOutline=this.treeOutline;current.treeOutline._rememberTreeElement(current);current=current.traverseNextTreeElement(false,child,true);} if(child.hasChildren&&child.treeOutline._treeElementsExpandedState[child.identifier]!==undefined) child.expanded=child.treeOutline._treeElementsExpandedState[child.identifier];if(this._childrenListNode) child._attach();if(this.treeOutline) this.treeOutline.dispatchEventToListeners(WI.TreeOutline.Event.ElementAdded,{element:child});if(isFirstChild&&this.expanded) this.expand();} insertChild(child,index) {if(!child) return;var previousChild=index>0?this.children[index-1]:null;if(previousChild){previousChild.nextSibling=child;child.previousSibling=previousChild;}else{child.previousSibling=null;} var nextChild=this.children[index];if(nextChild){nextChild.previousSibling=child;child.nextSibling=nextChild;}else{child.nextSibling=null;} var isFirstChild=!this.children.length;this.children.splice(index,0,child);this.hasChildren=true;child.parent=this;child.treeOutline=this.treeOutline;child.treeOutline._rememberTreeElement(child);var current=child.children[0];while(current){current.treeOutline=this.treeOutline;current.treeOutline._rememberTreeElement(current);current=current.traverseNextTreeElement(false,child,true);} if(child.expandable&&child.treeOutline._treeElementsExpandedState[child.identifier]!==undefined) child.expanded=child.treeOutline._treeElementsExpandedState[child.identifier];if(this._childrenListNode) child._attach();if(this.treeOutline) this.treeOutline.dispatchEventToListeners(WI.TreeOutline.Event.ElementAdded,{element:child});if(isFirstChild&&this.expanded) this.expand();} removeChildAtIndex(childIndex,suppressOnDeselect,suppressSelectSibling) {if(childIndex<0||childIndex>=this.children.length) return;let child=this.children[childIndex];let parent=child.parent;let childOrDescendantWasSelected=child.deselect(suppressOnDeselect)||child.selfOrDescendant((descendant)=>descendant.selected);if(childOrDescendantWasSelected&&!suppressSelectSibling){const omitFocus=true;if(child.previousSibling) child.previousSibling.select(omitFocus);else if(child.nextSibling) child.nextSibling.select(omitFocus);else parent.select(omitFocus);} let treeOutline=child.treeOutline;if(treeOutline){treeOutline._forgetTreeElement(child);treeOutline._forgetChildrenRecursive(child);} if(child.previousSibling) child.previousSibling.nextSibling=child.nextSibling;if(child.nextSibling) child.nextSibling.previousSibling=child.previousSibling;this.children.splice(childIndex,1);child._detach();child.treeOutline=null;child.parent=null;child.nextSibling=null;child.previousSibling=null;if(treeOutline) treeOutline.dispatchEventToListeners(WI.TreeOutline.Event.ElementRemoved,{element:child});} removeChild(child,suppressOnDeselect,suppressSelectSibling) {if(!child) return;var childIndex=this.children.indexOf(child);if(childIndex===-1) return;this.removeChildAtIndex(childIndex,suppressOnDeselect,suppressSelectSibling);if(!this.children.length){if(this._listItemNode) this._listItemNode.classList.remove("parent");this.hasChildren=false;}} removeChildren(suppressOnDeselect) {for(let child of this.children){child.deselect(suppressOnDeselect);let treeOutline=child.treeOutline;if(treeOutline){treeOutline._forgetTreeElement(child);treeOutline._forgetChildrenRecursive(child);} child._detach();child.treeOutline=null;child.parent=null;child.nextSibling=null;child.previousSibling=null;if(treeOutline) treeOutline.dispatchEventToListeners(WI.TreeOutline.Event.ElementRemoved,{element:child});} this.children=[];} _rememberTreeElement(element) {if(!this._knownTreeElements[element.identifier]) this._knownTreeElements[element.identifier]=[];var elements=this._knownTreeElements[element.identifier];if(!elements.includes(element)){elements.push(element);this._cachedNumberOfDescendants++;} if(this.virtualized) this._virtualizedDebouncer.delayForFrame();} _forgetTreeElement(element) {if(this.selectedTreeElement===element){element.deselect(true);this.selectedTreeElement=null;} if(this._knownTreeElements[element.identifier]){if(this._knownTreeElements[element.identifier].remove(element)) this._cachedNumberOfDescendants--;} if(this.virtualized) this._virtualizedDebouncer.delayForFrame();} _forgetChildrenRecursive(parentElement) {var child=parentElement.children[0];while(child){this._forgetTreeElement(child);child=child.traverseNextTreeElement(false,parentElement,true);}} getCachedTreeElement(representedObject) {if(!representedObject) return null; if(representedObject.__proxyObjectTreeElement) return representedObject.__proxyObjectTreeElement;if(representedObject.__treeElementIdentifier){ var elements=this._knownTreeElements[representedObject.__treeElementIdentifier];if(elements){for(var i=0;ithis.objectForSelection(treeElement));this._selectionController.selectItems(new Set(selectableObjects));} get virtualized() {return this._virtualizedScrollContainer&&!isNaN(this._virtualizedTreeItemHeight);} registerScrollVirtualizer(scrollContainer,treeItemHeight) {let boundUpdateVirtualizedElements=(focusedTreeElement)=>{this._updateVirtualizedElements(focusedTreeElement);};this._virtualizedDebouncer=new Debouncer(boundUpdateVirtualizedElements);this._virtualizedVisibleTreeElements=new Set;this._virtualizedAttachedTreeElements=new Set;this._virtualizedScrollContainer=scrollContainer;this._virtualizedTreeItemHeight=treeItemHeight;this._virtualizedTopSpacer=document.createElement("div");this._virtualizedBottomSpacer=document.createElement("div");let throttler=new Throttler(boundUpdateVirtualizedElements,1000/16);this._virtualizedScrollContainer.addEventListener("scroll",(event)=>{throttler.fire();});this._updateVirtualizedElements();} get updateVirtualizedElementsDebouncer() {return this._virtualizedDebouncer;} selectionControllerSelectionDidChange(controller,deselectedItems,selectedItems) {this._processingSelectionChange=true;for(let representedObject of deselectedItems){let treeElement=this.getCachedTreeElement(representedObject);if(!treeElement) continue;if(treeElement.listItemElement) treeElement.listItemElement.classList.remove("selected");treeElement.deselect();} for(let representedObject of selectedItems){let treeElement=this.getCachedTreeElement(representedObject);if(!treeElement) continue;if(treeElement.listItemElement) treeElement.listItemElement.classList.add("selected");const omitFocus=true;treeElement.select(omitFocus);} this._dispatchSelectionDidChangeEvent();this._processingSelectionChange=false;} selectionControllerFirstSelectableItem(controller) {let firstChild=this.children[0];if(firstChild.selectable) return firstChild.representedObject;return this.selectionControllerNextSelectableItem(controller,firstChild.representedObject);} selectionControllerLastSelectableItem(controller) {let treeElement=this.children.lastValue;while(treeElement.expanded&&treeElement.children.length) treeElement=treeElement.children.lastValue;let item=this.objectForSelection(treeElement);if(this.canSelectTreeElement(treeElement)) return item;return this.selectionControllerPreviousSelectableItem(controller,item);} selectionControllerPreviousSelectableItem(controller,item) {let treeElement=this.getCachedTreeElement(item);if(!treeElement) return null;const skipUnrevealed=true;const stayWithin=null;const dontPopulate=true;while(treeElement=treeElement.traversePreviousTreeElement(skipUnrevealed,stayWithin,dontPopulate)){if(this.canSelectTreeElement(treeElement)) return this.objectForSelection(treeElement);} return null;} selectionControllerNextSelectableItem(controller,item) {let treeElement=this.getCachedTreeElement(item);if(!treeElement) return null;const skipUnrevealed=true;const stayWithin=null;const dontPopulate=true;while(treeElement=treeElement.traverseNextTreeElement(skipUnrevealed,stayWithin,dontPopulate)){if(this.canSelectTreeElement(treeElement)) return this.objectForSelection(treeElement);} return null;} canSelectTreeElement(treeElement) {return treeElement.selectable;} objectForSelection(treeElement) {return treeElement.representedObject;} selectTreeElementInternal(treeElement,suppressNotification=false,selectedByUser=false) {if(this._processingSelectionChange) return;this._itemWasSelectedByUser=selectedByUser;this._suppressNextSelectionDidChangeEvent=suppressNotification;if(this.allowsRepeatSelection&&this.selectedTreeElement===treeElement){this._dispatchSelectionDidChangeEvent();return;} this.selectedTreeElement=treeElement;} treeElementFromEvent(event) { let scrollContainer=this.element.parentElement;if(scrollContainer.offsetWidth>this.element.offsetWidth) scrollContainer=this.element; let isRTL=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL;let trailingEdgeOffset=isRTL?36:(scrollContainer.offsetWidth-36);let x=scrollContainer.totalOffsetLeft+trailingEdgeOffset;let y=event.pageY; let elementUnderMouse=this.treeElementFromPoint(x,y);let elementAboveMouse=this.treeElementFromPoint(x,y-2);let element=null;if(elementUnderMouse===elementAboveMouse) element=elementUnderMouse;else element=this.treeElementFromPoint(x,y+2);return element;} populateContextMenu(contextMenu,event,treeElement) {treeElement.populateContextMenu(contextMenu,event);} static _generateStyleRulesIfNeeded() {if(WI.TreeOutline._styleElement) return;WI.TreeOutline._styleElement=document.createElement("style");let maximumTreeDepth=32;let depthPadding=10;let styleText="";let childrenSubstring="";for(let i=1;i<=maximumTreeDepth;++i){childrenSubstring+=i===maximumTreeDepth?" .children":" > .children";styleText+=`.${WI.TreeOutline.ElementStyleClassName}:not(.${WI.TreeOutline.CustomIndentStyleClassName})${childrenSubstring} > .item { `;styleText+=`padding-inline-start: calc(var(--tree-outline-item-padding) + ${depthPadding * i}px);`;styleText+=` }\n`;} WI.TreeOutline._styleElement.textContent=styleText;document.head.appendChild(WI.TreeOutline._styleElement);} _updateVirtualizedElements(focusedTreeElement) {this._virtualizedDebouncer.cancel();function walk(parent,callback,count=0){let shouldReturn=false;for(let child of parent.children){if(!child.revealed(false)) continue;shouldReturn=callback(child,count);if(shouldReturn) break;++count;if(child.expanded){let result=walk(child,callback,count);count=result.count;if(result.shouldReturn) break;}} return{count,shouldReturn};} function calculateOffsetFromContainer(node,target){let top=0;while(node!==target){top+=node.offsetTop;node=node.offsetParent;if(!node) return 0;} return top;} let offsetFromContainer=calculateOffsetFromContainer(this._virtualizedTopSpacer.parentNode?this._virtualizedTopSpacer:this.element,this._virtualizedScrollContainer);let numberVisible=Math.ceil(Math.max(0,this._virtualizedScrollContainer.offsetHeight-offsetFromContainer)/this._virtualizedTreeItemHeight);let extraRows=Math.max(numberVisible*5,50);let firstItem=Math.floor((this._virtualizedScrollContainer.scrollTop-offsetFromContainer)/this._virtualizedTreeItemHeight)-extraRows;let lastItem=firstItem+numberVisible+(extraRows*2);let shouldScroll=false;if(focusedTreeElement&&focusedTreeElement.revealed(false)){let index=walk(this,(treeElement)=>treeElement===focusedTreeElement).count;if(indexlastItem){firstItem=index-numberVisible-extraRows;lastItem=index+extraRows;} shouldScroll=(indexlastItem-extraRows);} let visibleTreeElements=new Set;let treeElementsToAttach=new Set;let treeElementsToDetach=new Set;let totalItems=walk(this,(treeElement,count)=>{if(count>=firstItem&&count<=lastItem){treeElementsToAttach.add(treeElement);if(count>=firstItem+extraRows&&count<=lastItem-extraRows) visibleTreeElements.add(treeElement);}else if(treeElement._listItemNode.parentNode) treeElementsToDetach.add(treeElement);return false;}).count;if(!shouldScroll){if(visibleTreeElements.size===this._virtualizedVisibleTreeElements.size){if(visibleTreeElements.intersects(this._virtualizedVisibleTreeElements)){if(visibleTreeElements.isSubsetOf(this._virtualizedAttachedTreeElements)) return;}}} this._virtualizedVisibleTreeElements=visibleTreeElements;this._virtualizedAttachedTreeElements=treeElementsToAttach;for(let treeElement of treeElementsToDetach) treeElement._listItemNode.remove();for(let treeElement of treeElementsToAttach){treeElement.parent._childrenListNode.appendChild(treeElement._listItemNode);if(treeElement._childrenListNode) treeElement.parent._childrenListNode.appendChild(treeElement._childrenListNode);} this._virtualizedTopSpacer.style.height=(Number.constrain(firstItem,0,totalItems)*this._virtualizedTreeItemHeight)+"px";if(this.element.previousElementSibling!==this._virtualizedTopSpacer) this.element.parentNode.insertBefore(this._virtualizedTopSpacer,this.element);this._virtualizedBottomSpacer.style.height=(Number.constrain(totalItems-lastItem,0,totalItems)*this._virtualizedTreeItemHeight)+"px";if(this.element.nextElementSibling!==this._virtualizedBottomSpacer) this.element.parentNode.insertBefore(this._virtualizedBottomSpacer,this.element.nextElementSibling);if(shouldScroll) this._virtualizedScrollContainer.scrollTop=offsetFromContainer+((firstItem+extraRows)*this._virtualizedTreeItemHeight);} _handleContextmenu(event) {let treeElement=this.treeElementFromEvent(event);if(!treeElement) return;let contextMenu=WI.ContextMenu.createFromEvent(event);this.populateContextMenu(contextMenu,event,treeElement);} _handleMouseDown(event) {let treeElement=this.treeElementFromEvent(event);if(!treeElement||!treeElement.selectable) return;if(treeElement.isEventWithinDisclosureTriangle(event)){event.preventDefault();return;} if(!treeElement.canSelectOnMouseDown(event)) return;if(this.allowsRepeatSelection&&treeElement.selected&&this._selectionController.selectedItems.size===1){ this._itemWasSelectedByUser=true;this._dispatchSelectionDidChangeEvent();return;} this._itemWasSelectedByUser=true;this._selectionController.handleItemMouseDown(this.objectForSelection(treeElement),event);this._itemWasSelectedByUser=false;treeElement.focus();} _dispatchSelectionDidChangeEvent() {let selectedByUser=this._itemWasSelectedByUser;this._itemWasSelectedByUser=false;if(this._suppressNextSelectionDidChangeEvent){this._suppressNextSelectionDidChangeEvent=false;return;} this.dispatchEventToListeners(WI.TreeOutline.Event.SelectionDidChange,{selectedByUser});}};WI.TreeOutline._styleElement=null;WI.TreeOutline.ElementStyleClassName="tree-outline";WI.TreeOutline.CustomIndentStyleClassName="custom-indent";WI.TreeOutline.Event={ElementAdded:"element-added",ElementDidChange:"element-did-change",ElementRemoved:"element-removed",ElementRevealed:"element-revealed",ElementClicked:"element-clicked",ElementDisclosureDidChanged:"element-disclosure-did-change",ElementVisibilityDidChange:"element-visbility-did-change",SelectionDidChange:"selection-did-change",};WI.TreeOutline._knownTreeElementNextIdentifier=1;WI.TreeOutlineGroup=class TreeOutlineGroup extends WI.Collection { objectIsRequiredType(object) {return object instanceof WI.TreeOutline;} get selectedTreeElement() {for(let treeOutline of this){if(treeOutline.selectedTreeElement) return treeOutline.selectedTreeElement;} return null;} itemAdded(treeOutline) {if(treeOutline.selectedTreeElement) this._removeConflictingTreeSelections(treeOutline);treeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._treeOutlineSelectionDidChange,this);} itemRemoved(treeOutline) {treeOutline.removeEventListener(WI.TreeOutline.Event.SelectionDidChange,this._treeOutlineSelectionDidChange,this);} _removeConflictingTreeSelections(selectedTreeOutline) {for(let treeOutline of this){if(selectedTreeOutline===treeOutline) continue;treeOutline.selectedTreeElement=null;}} _treeOutlineSelectionDidChange(event) {let treeOutline=event.target;if(!treeOutline.selectedTreeElement) return;this._removeConflictingTreeSelections(treeOutline);}};WI.DetailsSection=class DetailsSection extends WI.Object {constructor(identifier,title,groups,optionsElement,defaultCollapsedSettingValue) {super();this._element=document.createElement("div");this._element.classList.add(identifier,"details-section");this._headerElement=document.createElement("div");this._headerElement.addEventListener("mousedown",this._headerElementMouseDown.bind(this));this._headerElement.addEventListener("click",this._headerElementClicked.bind(this));this._headerElement.addEventListener("keydown",this._handleHeaderElementKeyDown.bind(this));this._headerElement.className="header";this._headerElement.tabIndex=0;this._element.appendChild(this._headerElement);if(optionsElement instanceof HTMLElement){this._optionsElement=optionsElement;this._optionsElement.classList.add("options");this._optionsElement.addEventListener("mousedown",this._optionsElementMouseDown.bind(this));this._optionsElement.addEventListener("mouseup",this._optionsElementMouseUp.bind(this));this._headerElement.appendChild(this._optionsElement);} this._titleElement=document.createElement("span");this._titleElement.className="title";this._headerElement.appendChild(this._titleElement);this._contentElement=document.createElement("div");this._contentElement.className="content";this._element.appendChild(this._contentElement);this._identifier=identifier;this.title=title;this.groups=groups||[new WI.DetailsSectionGroup];this._collapsedSetting=new WI.Setting(identifier+"-details-section-collapsed",!!defaultCollapsedSettingValue);this.collapsed=this._collapsedSetting.value;} get element(){return this._element;} get headerElement(){return this._headerElement;} get identifier(){return this._identifier;} get title() {return this._titleElement.textContent;} set title(title) {this._headerElement.toggleAttribute("hidden",!title);this._titleElement.textContent=title;} get titleElement() {return this._titleElement;} set titleElement(element) {this._headerElement.replaceChild(element,this._titleElement);this._titleElement=element;} get collapsed() {return this._element.classList.contains(WI.DetailsSection.CollapsedStyleClassName);} set collapsed(flag) {if(flag) this._element.classList.add(WI.DetailsSection.CollapsedStyleClassName);else this._element.classList.remove(WI.DetailsSection.CollapsedStyleClassName);this._collapsedSetting.value=flag||false;this.dispatchEventToListeners(WI.DetailsSection.Event.CollapsedStateChanged,{collapsed:this._collapsedSetting.value});} get groups() {return this._groups;} set groups(groups) {this._contentElement.removeChildren();this._groups=groups||[];for(var i=0;i{WI.archiveMainFrame();}};} get supportsSearch() {return true;} get numberOfSearchResults() {return this._numberOfSearchResults;} get hasPerformedSearch() {return this._numberOfSearchResults!==null;} set automaticallyRevealFirstSearchResult(reveal) {this._automaticallyRevealFirstSearchResult=reveal;if(this._automaticallyRevealFirstSearchResult&&this._numberOfSearchResults>0){if(this._currentSearchResultIndex===-1) this.revealNextSearchResult();}} performSearch(query) {if(this._searchQuery===query) return;let target=WI.assumingMainTarget();if(this._searchIdentifier){target.DOMAgent.discardSearchResults(this._searchIdentifier);this._hideSearchHighlights();} this._searchQuery=query;this._searchIdentifier=null;this._numberOfSearchResults=null;this._currentSearchResultIndex=-1;function searchResultsReady(error,searchIdentifier,resultsCount) {if(error) return;this._searchIdentifier=searchIdentifier;this._numberOfSearchResults=resultsCount;this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);this._showSearchHighlights();if(this._automaticallyRevealFirstSearchResult) this.revealNextSearchResult();} function contextNodesReady(nodeIds) {if(this._searchQuery!==query) return;let commandArguments={query:this._searchQuery,nodeIds,caseSensitive:WI.SearchUtilities.defaultSettings.caseSensitive.value,};target.DOMAgent.performSearch.invoke(commandArguments,searchResultsReady.bind(this));} this.getSearchContextNodes(contextNodesReady.bind(this));} getSearchContextNodes(callback) {callback(undefined);} searchCleared() {if(this._searchIdentifier){let target=WI.assumingMainTarget();target.DOMAgent.discardSearchResults(this._searchIdentifier);this._hideSearchHighlights();} this._searchQuery=null;this._searchIdentifier=null;this._numberOfSearchResults=null;this._currentSearchResultIndex=-1;} revealPreviousSearchResult(changeFocus) {if(!this._numberOfSearchResults) return;if(this._currentSearchResultIndex>0) --this._currentSearchResultIndex;else this._currentSearchResultIndex=this._numberOfSearchResults-1;this._revealSearchResult(this._currentSearchResultIndex,changeFocus);} revealNextSearchResult(changeFocus) {if(!this._numberOfSearchResults) return;if(this._currentSearchResultIndex+1{WI.settings.enabledDOMTreeBadgeTypes.value.toggleIncludes(WI.DOMTreeElement.BadgeType.Grid);WI.settings.enabledDOMTreeBadgeTypes.save();},WI.settings.enabledDOMTreeBadgeTypes.value.includes(WI.DOMTreeElement.BadgeType.Grid));} if(InspectorBackend.hasCommand("DOM.showFlexOverlay")){contextMenu.appendCheckboxItem(WI.unlocalizedString("flex"),()=>{WI.settings.enabledDOMTreeBadgeTypes.value.toggleIncludes(WI.DOMTreeElement.BadgeType.Flex);WI.settings.enabledDOMTreeBadgeTypes.save();},WI.settings.enabledDOMTreeBadgeTypes.value.includes(WI.DOMTreeElement.BadgeType.Flex));} if(InspectorBackend.hasCommand("DOM.getEventListenersForNode","includeAncestors")){contextMenu.appendCheckboxItem(WI.UIString("Event"),()=>{WI.settings.enabledDOMTreeBadgeTypes.value.toggleIncludes(WI.DOMTreeElement.BadgeType.Event);WI.settings.enabledDOMTreeBadgeTypes.save();},WI.settings.enabledDOMTreeBadgeTypes.value.includes(WI.DOMTreeElement.BadgeType.Event));} if(InspectorBackend.Enum.CSS?.LayoutFlag?.Scrollable){contextMenu.appendCheckboxItem(WI.UIString("Scroll","Title for a badge applied to DOM nodes that are a scrollable container."),()=>{WI.settings.enabledDOMTreeBadgeTypes.value.toggleIncludes(WI.DOMTreeElement.BadgeType.Scrollable);WI.settings.enabledDOMTreeBadgeTypes.save();},WI.settings.enabledDOMTreeBadgeTypes.value.includes(WI.DOMTreeElement.BadgeType.Scrollable));}} _domTreeElementAdded(event) {if(!this._pendingBreakpointNodes.size) return;let treeElement=event.data.element;let node=treeElement.representedObject;if(!(node instanceof WI.DOMNode)) return;if(!this._pendingBreakpointNodes.delete(node)) return;this._updateBreakpointStatus(node);} _domTreeSelectionDidChange(event) {let treeElement=this._domTreeOutline.selectedTreeElement;let domNode=treeElement?treeElement.representedObject:null;let selectedByUser=event.data.selectedByUser;this._domTreeOutline.suppressRevealAndSelect=true;this._domTreeOutline.selectDOMNode(domNode,selectedByUser);if(domNode&&selectedByUser) domNode.highlight();this._domTreeOutline.updateSelectionArea();this._domTreeOutline.suppressRevealAndSelect=false;} _selectedNodeDidChange(event) {var selectedDOMNode=this._domTreeOutline.selectedDOMNode();if(selectedDOMNode&&!this._dontSetLastSelectedNodePath) this._lastSelectedNodePathSetting.value={url:WI.networkManager.mainFrame.url.hash,path:selectedDOMNode.path()};if(selectedDOMNode) WI.domManager.setInspectedNode(selectedDOMNode);this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);} _handlePathComponentSelected(event) {if(!event.data.pathComponent) return;this._domTreeOutline.selectDOMNode(event.data.pathComponent.domTreeElement.representedObject,true);} _domNodeChanged(event) {var selectedDOMNode=this._domTreeOutline.selectedDOMNode();if(selectedDOMNode!==event.data.node) return;this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);} _mouseWasClicked(event) {var anchorElement=event.target.closest("a");if(!anchorElement||!anchorElement.href) return;event.preventDefault();event.stopPropagation();if(WI.isBeingEdited(anchorElement)){return;} if(this._followLinkTimeoutIdentifier){clearTimeout(this._followLinkTimeoutIdentifier);delete this._followLinkTimeoutIdentifier;} if(event.detail>1) return;function followLink() { const options={alwaysOpenExternally:event?.metaKey??false,frame:this._frame,lineNumber:anchorElement.lineNumber,ignoreNetworkTab:true,ignoreSearchTab:true,};WI.openURL(anchorElement.href,options);} this._followLinkTimeoutIdentifier=setTimeout(followLink.bind(this),333);} _handleCompositingBordersVisibleChanged(event) {this._compositingBordersButtonNavigationItem.activated=WI.layerTreeManager.compositingBordersVisible;} _handleCompositingBordersButtonClicked(event) {WI.layerTreeManager.compositingBordersVisible=!WI.layerTreeManager.compositingBordersVisible;} _handleShowPaintRectsChanged(event) {this._paintFlashingButtonNavigationItem.activated=WI.layerTreeManager.showPaintRects;} _handlePaingFlashingButtonClicked(event) {WI.layerTreeManager.showPaintRects=!WI.layerTreeManager.showPaintRects;} _showPrintStylesChanged() {this._showPrintStylesButtonNavigationItem.activated=WI.printStylesEnabled;let mediaType=WI.printStylesEnabled?"print":"";for(let target of WI.targets){if(target.hasCommand("Page.setEmulatedMedia")) target.PageAgent.setEmulatedMedia(mediaType);} WI.cssManager.mediaTypeChanged();} _togglePrintStyles(event) {WI.printStylesEnabled=!WI.printStylesEnabled;this._showPrintStylesChanged();} _handleOverrideUserPreferencesButtonClicked() {if(this._userPreferencesOverridesPopover) return;this._userPreferencesOverridesPopover=new WI.OverrideUserPreferencesPopover(this);this._userPreferencesOverridesPopover.show(this._overrideUserPreferencesNavigationItem.element);} _overriddenUserPreferencesDidChange() {this._overrideUserPreferencesNavigationItem.activated=WI.cssManager.overriddenUserPreferences.size>0;} _defaultUserPreferencesDidChange() {this._overrideUserPreferencesNavigationItem.enabled=WI.cssManager.supportsOverrideUserPreference||WI.cssManager.supportsOverrideColorScheme;} _showRulersChanged() {let activated=WI.settings.showRulers.value;this._showRulersButtonNavigationItem.activated=activated;for(let target of WI.targets){if(target.hasCommand("Page.setShowRulers")) target.PageAgent.setShowRulers(activated).catch((error)=>{console.error(error);});}} _toggleShowRulers(event) {WI.settings.showRulers.value=!WI.settings.showRulers.value;this._showRulersChanged();} _showSearchHighlights() {this._searchResultNodes=[];var searchIdentifier=this._searchIdentifier;let target=WI.assumingMainTarget();target.DOMAgent.getSearchResults(this._searchIdentifier,0,this._numberOfSearchResults,function(error,nodeIdentifiers){if(error) return;if(this._searchIdentifier!==searchIdentifier) return;for(var i=0;iitem.disabled)) treeElement.breakpointStatus=WI.DOMTreeElement.BreakpointStatus.DisabledBreakpoint;else treeElement.breakpointStatus=WI.DOMTreeElement.BreakpointStatus.Breakpoint;}else treeElement.breakpointStatus=WI.DOMTreeElement.BreakpointStatus.None;this.breakpointGutterEnabled=this._domTreeOutline.children.some((child)=>child.hasBreakpoint);} _restoreBreakpointsAfterUpdate() {this._pendingBreakpointNodes.clear();this.breakpointGutterEnabled=false;let updatedNodes=new Set;for(let breakpoint of WI.domDebuggerManager.domBreakpoints){if(updatedNodes.has(breakpoint.domNode)) continue;this._updateBreakpointStatus(breakpoint.domNode);}} _breakpointsEnabledDidChange(event) {this._domTreeOutline.element.classList.toggle("breakpoints-disabled",!WI.debuggerManager.breakpointsEnabled);} _updateDOMTreeDeemphasizesNodesThatAreNotRendered() {this.element.classList.toggle("deemphasize-unrendered",WI.settings.domTreeDeemphasizesNodesThatAreNotRendered.value);} _handleDOMTreeDeemphasizesNodesThatAreNotRenderedChanged(event) {this._updateDOMTreeDeemphasizesNodesThatAreNotRendered()} didDismissPopover(popover) {if(popover===this._userPreferencesOverridesPopover) this._userPreferencesOverridesPopover=null;};};WI.DetailsSidebarPanel=class DetailsSidebarPanel extends WI.SidebarPanel {constructor(identifier,displayName,dontCreateNavigationItem) {super(identifier,displayName);this.element.classList.add("details");if(!dontCreateNavigationItem) this._navigationItem=new WI.RadioButtonNavigationItem(identifier,displayName);} get navigationItem() {return this._navigationItem;} inspect(objects) {return false;}};WI.GeneralTabBarItem=class GeneralTabBarItem extends WI.TabBarItem { static fromTabContentView(tabContentView) {let{image,displayName,title}=tabContentView.tabInfo();return new WI.GeneralTabBarItem(tabContentView,image,displayName,title);} get displayName() {return super.displayName;} set displayName(displayName) {if(displayName){this._displayNameElement=document.createElement("span");this._displayNameElement.className="name";let displayNameContentElement=this._displayNameElement.appendChild(document.createElement("span"));displayNameContentElement.className="content";displayNameContentElement.textContent=displayName;this.element.insertBefore(this._displayNameElement,this.element.lastChild);}else{if(this._displayNameElement) this._displayNameElement.remove();this._displayNameElement=null;} super.displayName=displayName;}};WI.GeneralTreeElement=class GeneralTreeElement extends WI.TreeElement {constructor(classNames,title,subtitle,representedObject,options) {super("",representedObject,options);this.classNames=classNames;this._tooltipHandledSeparately=false;this._mainTitle=title||"";this._subtitle=subtitle||"";this._status="";} get element() {return this._listItemNode;} get iconElement() {this._createElementsIfNeeded();return this._iconElement;} get statusElement() {return this._statusElement;} get titlesElement() {this._createElementsIfNeeded();return this._titlesElement;} get mainTitleElement() {this._createElementsIfNeeded();return this._mainTitleElement;} get subtitleElement() {this._createElementsIfNeeded();this._createSubtitleElementIfNeeded();return this._subtitleElement;} get classNames() {return this._classNames;} set classNames(x) {x=x||[];if(typeof x==="string") x=[x];if(Array.shallowEqual(this._classNames,x)) return;if(this._listItemNode&&this._classNames) this._listItemNode.classList.remove(...this._classNames);this._classNames=x;if(this._listItemNode) this._listItemNode.classList.add(...this._classNames);} addClassName(className) {if(this._classNames.includes(className)) return;this._classNames.push(className);if(this._listItemNode) this._listItemNode.classList.add(className);} removeClassName(className) {if(!this._classNames.includes(className)) return;this._classNames.remove(className);if(this._listItemNode) this._listItemNode.classList.remove(className);} get mainTitle() {return this._mainTitle;} set mainTitle(x) {x=x||"";if(this._mainTitle===x) return;this._mainTitle=x;this._updateTitleElements();this.didChange();this.dispatchEventToListeners(WI.GeneralTreeElement.Event.MainTitleDidChange);} get subtitle() {return this._subtitle;} set subtitle(x) {x=x||"";if(this._subtitle===x) return;this._subtitle=x;this._updateTitleElements();this.didChange();} get status() {return this._status;} set status(x) {x=x||"";if(this._status===x) return;if(!this._statusElement){this._statusElement=document.createElement("div");this._statusElement.className=WI.GeneralTreeElement.StatusElementStyleClassName;} this._status=x;this._updateStatusElement();} get filterableData() {return{text:[this.mainTitle,this.subtitle]};} get tooltipHandledSeparately() {return this._tooltipHandledSeparately;} set tooltipHandledSeparately(x) {this._tooltipHandledSeparately=!!x;} createFoldersAsNeededForSubpath(subpath,comparator) {if(!subpath) return this;let components=subpath.split("/");if(components.length===1) return this;if(!this._subpathFolderTreeElementMap) this._subpathFolderTreeElementMap=new Map;let currentPath="";let currentFolderTreeElement=this;for(let component of components){if(component===components.lastValue) break;if(currentPath) currentPath+="/";currentPath+=component;let cachedFolder=this._subpathFolderTreeElementMap.get(currentPath);if(cachedFolder){currentFolderTreeElement=cachedFolder;continue;} let newFolder=new WI.FolderTreeElement(component);this._subpathFolderTreeElementMap.set(currentPath,newFolder);let index=insertionIndexForObjectInListSortedByFunction(newFolder,currentFolderTreeElement.children,comparator||WI.ResourceTreeElement.compareFolderAndResourceTreeElements);currentFolderTreeElement.insertChild(newFolder,index);currentFolderTreeElement=newFolder;} return currentFolderTreeElement;} isEventWithinDisclosureTriangle(event) {return event.target===this._disclosureButton;} onattach() {this._createElementsIfNeeded();this._updateTitleElements();this._listItemNode.classList.add("item");if(this._classNames) this._listItemNode.classList.add(...this._classNames);this._listItemNode.appendChild(this._disclosureButton);this._listItemNode.appendChild(this._iconElement);if(this._statusElement) this._listItemNode.appendChild(this._statusElement);this._listItemNode.appendChild(this._titlesElement);} ondetach() {} onreveal() {if(this._listItemNode) this._listItemNode.scrollIntoViewIfNeeded(false);} callFirstAncestorFunction(functionName,args) {var currentNode=this.parent;while(currentNode){if(typeof currentNode[functionName]==="function"){currentNode[functionName].apply(currentNode,args);break;} currentNode=currentNode.parent;}} customTitleTooltip() {} _createElementsIfNeeded() {if(this._createdElements) return;this._disclosureButton=document.createElement("button");this._disclosureButton.className=WI.GeneralTreeElement.DisclosureButtonStyleClassName; this._disclosureButton.tabIndex=-1;this._iconElement=document.createElement("img");this._iconElement.className=WI.GeneralTreeElement.IconElementStyleClassName;this._titlesElement=document.createElement("div");this._titlesElement.className=WI.GeneralTreeElement.TitlesElementStyleClassName;this._mainTitleElement=document.createElement("span");this._mainTitleElement.className=WI.GeneralTreeElement.MainTitleElementStyleClassName;this._titlesElement.appendChild(this._mainTitleElement);this._createdElements=true;} _createSubtitleElementIfNeeded() {if(this._subtitleElement) return;this._subtitleElement=document.createElement("span");this._subtitleElement.className=WI.GeneralTreeElement.SubtitleElementStyleClassName;this._titlesElement.appendChild(this._subtitleElement);} _updateTitleElements() {if(!this._createdElements) return;if(typeof this._mainTitle==="string"){if(this._mainTitleElement.textContent!==this._mainTitle) this._mainTitleElement.textContent=this._mainTitle;}else if(this._mainTitle instanceof Node){this._mainTitleElement.removeChildren();this._mainTitleElement.appendChild(this._mainTitle);if(this._mainTitle instanceof DocumentFragment) this._mainTitle=this._mainTitleElement.textContent;} if(typeof this._subtitle==="string"&&this._subtitle){this._createSubtitleElementIfNeeded();if(this._subtitleElement.textContent!==this._subtitle) this._subtitleElement.textContent=this._subtitle;this._titlesElement.classList.remove(WI.GeneralTreeElement.NoSubtitleStyleClassName);}else if(this._subtitle instanceof Node){this._createSubtitleElementIfNeeded();this._subtitleElement.removeChildren();this._subtitleElement.appendChild(this._subtitle);if(this._subtitle instanceof DocumentFragment) this._subtitle=this._subtitleElement.textContent;this._titlesElement.classList.remove(WI.GeneralTreeElement.NoSubtitleStyleClassName);}else{if(this._subtitleElement) this._subtitleElement.textContent="";this._titlesElement.classList.add(WI.GeneralTreeElement.NoSubtitleStyleClassName);} if(!this.tooltip&&!this._tooltipHandledSeparately) this._updateTitleTooltip();} _updateTitleTooltip() {if(!this._listItemNode) return;let tooltip=this.customTitleTooltip();if(!tooltip){let mainTitleText=this._mainTitleElement.textContent;let subtitleText=this._subtitleElement?this._subtitleElement.textContent:"";let large=this.treeOutline&&this.treeOutline.large;if(mainTitleText&&subtitleText) tooltip=mainTitleText+(large?"\n":" \u2014 ")+subtitleText;else if(mainTitleText) tooltip=mainTitleText;else tooltip=subtitleText;} this._listItemNode.title=tooltip;} _updateStatusElement() {if(!this._statusElement) return;if(!this._statusElement.parentNode&&this._listItemNode) this._listItemNode.insertBefore(this._statusElement,this._titlesElement);if(this._status instanceof Node){this._statusElement.removeChildren();this._statusElement.appendChild(this._status);}else this._statusElement.textContent=this._status;}};WI.GeneralTreeElement.DisclosureButtonStyleClassName="disclosure-button";WI.GeneralTreeElement.IconElementStyleClassName="icon";WI.GeneralTreeElement.StatusElementStyleClassName="status";WI.GeneralTreeElement.TitlesElementStyleClassName="titles";WI.GeneralTreeElement.MainTitleElementStyleClassName="title";WI.GeneralTreeElement.SubtitleElementStyleClassName="subtitle";WI.GeneralTreeElement.NoSubtitleStyleClassName="no-subtitle";WI.GeneralTreeElement.Event={MainTitleDidChange:"general-tree-element-main-title-did-change"};WI.GroupNavigationItem=class GroupNavigationItem extends WI.NavigationItem {constructor(navigationItems) {super();this._needsUpdate=false;this.navigationItems=navigationItems||[];} get navigationItems() {return this._navigationItems;} set navigationItems(items) {this._navigationItems=items;this._needsUpdate=true;} get hidden() {return super.hidden||this._navigationItems.every((item)=>item.hidden);} set hidden(flag) {super.hidden=flag;} get width() {this._updateItems();return super.width;} get minimumWidth() {this._updateItems();return this._navigationItems.reduce((total,item)=>total+item.minimumWidth,0);} get additionalClassNames() {return["group"];} update(options={}) {super.update(options);this._updateItems();for(let item of this._navigationItems) item.update(options);} didAttach(navigationBar) {super.didAttach(navigationBar);this._updateItems();for(let item of this._navigationItems) item.didAttach(navigationBar);} didDetach() {for(let item of this._navigationItems) item.didDetach();super.didDetach();} _updateItems() {if(!this._needsUpdate) return;this._needsUpdate=false;this.element.removeChildren();for(let item of this._navigationItems){this.element.appendChild(item.element);}}};WI.NavigationSidebarPanel=class NavigationSidebarPanel extends WI.SidebarPanel {constructor(identifier,displayName,shouldAutoPruneStaleTopLevelResourceTreeElements,wantsTopOverflowShadow) {super(identifier,displayName);this.element.classList.add("navigation");this._updateContentOverflowShadowVisibilityDebouncer=new Debouncer(()=>{this._updateContentOverflowShadowVisibility();});this._boundUpdateContentOverflowShadowVisibilitySoon=(event)=>{this._updateContentOverflowShadowVisibilityDebouncer.delayForTime(0);};this.contentView.element.addEventListener("scroll",this._boundUpdateContentOverflowShadowVisibilitySoon);this._contentTreeOutlineGroup=new WI.TreeOutlineGroup;this._contentTreeOutline=this.createContentTreeOutline();this._filterBar=new WI.FilterBar;this._filterBar.addEventListener(WI.FilterBar.Event.FilterDidChange,this._filterDidChange,this);this.element.appendChild(this._filterBar.element);this._bottomOverflowShadowElement=document.createElement("div");this._bottomOverflowShadowElement.className=WI.NavigationSidebarPanel.OverflowShadowElementStyleClassName;this.element.appendChild(this._bottomOverflowShadowElement);if(wantsTopOverflowShadow){this._topOverflowShadowElement=this.element.appendChild(document.createElement("div"));this._topOverflowShadowElement.classList.add(WI.NavigationSidebarPanel.OverflowShadowElementStyleClassName,"top");} window.addEventListener("resize",this._boundUpdateContentOverflowShadowVisibilitySoon);this._filtersSetting=new WI.Setting(identifier+"-navigation-sidebar-filters",{});this._filterBar.filters=this._filtersSetting.value;this._emptyContentPlaceholderElements=new Map;this._emptyFilterResults=new Set;this._shouldAutoPruneStaleTopLevelResourceTreeElements=shouldAutoPruneStaleTopLevelResourceTreeElements||false;if(this._shouldAutoPruneStaleTopLevelResourceTreeElements){WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._checkForStaleResources,this);WI.Frame.addEventListener(WI.Frame.Event.ChildFrameWasRemoved,this._checkForStaleResources,this);WI.Frame.addEventListener(WI.Frame.Event.ResourceWasRemoved,this._checkForStaleResources,this);} this._pendingViewStateCookie=null;this._restoringState=false;} get filterBar(){return this._filterBar;} get hasActiveFilters(){return this._filterBar.hasActiveFilters();} closed() {window.removeEventListener("resize",this._boundUpdateContentOverflowShadowVisibilitySoon);if(this._shouldAutoPruneStaleTopLevelResourceTreeElements){WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._checkForStaleResources,this);WI.Frame.removeEventListener(WI.Frame.Event.ChildFrameWasRemoved,this._checkForStaleResources,this);WI.Frame.removeEventListener(WI.Frame.Event.ResourceWasRemoved,this._checkForStaleResources,this);}} get contentBrowser() {return this._contentBrowser;} set contentBrowser(contentBrowser) {this._contentBrowser=contentBrowser||null;} get contentTreeOutline() {return this._contentTreeOutline;} get contentTreeOutlines() {return Array.from(this._contentTreeOutlineGroup);} get currentRepresentedObject() {if(!this._contentBrowser) return null;return this._contentBrowser.currentRepresentedObjects[0]||null;} get restoringState() {return this._restoringState;} cancelRestoringState() {this._pendingViewStateCookie=null;if(!this._finalAttemptToRestoreViewStateTimeout) return;clearTimeout(this._finalAttemptToRestoreViewStateTimeout);this._finalAttemptToRestoreViewStateTimeout=undefined;} createContentTreeOutline({ignoreCookieRestoration,suppressFiltering}={}) {let contentTreeOutline=new WI.TreeOutline;contentTreeOutline.allowsRepeatSelection=true;contentTreeOutline.element.classList.add(WI.NavigationSidebarPanel.ContentTreeOutlineElementStyleClassName);this._contentTreeOutlineGroup.add(contentTreeOutline);this.contentView.element.appendChild(contentTreeOutline.element);if(!suppressFiltering){contentTreeOutline.addEventListener(WI.TreeOutline.Event.ElementAdded,this._treeElementAddedOrChanged,this);contentTreeOutline.addEventListener(WI.TreeOutline.Event.ElementDidChange,this._treeElementAddedOrChanged,this);contentTreeOutline.addEventListener(WI.TreeOutline.Event.ElementDisclosureDidChanged,this._treeElementDisclosureDidChange,this);contentTreeOutline.addEventListener(WI.TreeOutline.Event.ElementRemoved,this._handleTreeElementRemoved,this);} contentTreeOutline[WI.NavigationSidebarPanel.IgnoreCookieRestoration]=ignoreCookieRestoration;contentTreeOutline[WI.NavigationSidebarPanel.SuppressFilteringSymbol]=suppressFiltering;return contentTreeOutline;} suppressFilteringOnTreeElements(treeElements) {for(let treeElement of treeElements) treeElement[WI.NavigationSidebarPanel.SuppressFilteringSymbol]=true;this.updateFilter();} treeElementForRepresentedObject(representedObject) {let treeElement=null;for(let treeOutline of this.contentTreeOutlines){treeElement=treeOutline.getCachedTreeElement(representedObject);if(treeElement) break;} return treeElement;} showDefaultContentView() {} showDefaultContentViewForTreeElement(treeElement) {if(!treeElement||!treeElement.representedObject) return false; if(!this.selected){let contentView=this.contentBrowser.contentViewForRepresentedObject(treeElement.representedObject);if(contentView&&contentView.parentContainer&&contentView.parentContainer!==this.contentBrowser.contentViewContainer) return false;let selectedTabContentView=WI.tabBrowser.selectedTabContentView;if(selectedTabContentView&&selectedTabContentView.contentBrowser!==this.contentBrowser) return false;} let contentView=this.contentBrowser.showContentViewForRepresentedObject(treeElement.representedObject);if(!contentView) return false;treeElement.revealAndSelect(true,false,true);return true;} canShowRepresentedObject(representedObject) {let selectedTabContentView=WI.tabBrowser.selectedTabContentView;return selectedTabContentView&&selectedTabContentView.canShowRepresentedObject(representedObject);} saveStateToCookie(cookie) {if(!this._contentBrowser) return;let representedObject=this.currentRepresentedObject;if(!representedObject) return;cookie[WI.TypeIdentifierCookieKey]=representedObject.constructor.TypeIdentifier;if(representedObject.saveIdentityToCookie){representedObject.saveIdentityToCookie(cookie);return;} console.error("NavigationSidebarPanel representedObject is missing a saveIdentityToCookie implementation.",representedObject);} restoreStateFromCookie(cookie,relaxedMatchDelay) {this._pendingViewStateCookie=cookie;this._restoringState=true;this._checkOutlinesForPendingViewStateCookie();if(this._finalAttemptToRestoreViewStateTimeout) clearTimeout(this._finalAttemptToRestoreViewStateTimeout);if(relaxedMatchDelay===0) return;function finalAttemptToRestoreViewStateFromCookie() {this._finalAttemptToRestoreViewStateTimeout=undefined;this._checkOutlinesForPendingViewStateCookie(true);this._pendingViewStateCookie=null;this._restoringState=false;} this._finalAttemptToRestoreViewStateTimeout=setTimeout(finalAttemptToRestoreViewStateFromCookie.bind(this),relaxedMatchDelay);} showEmptyContentPlaceholder(message,treeOutline) {treeOutline=treeOutline||this._contentTreeOutline;let emptyContentPlaceholderElement=this._emptyContentPlaceholderElements.get(treeOutline);if(emptyContentPlaceholderElement) emptyContentPlaceholderElement.remove();emptyContentPlaceholderElement=message instanceof Node?message:WI.createMessageTextView(message);this._emptyContentPlaceholderElements.set(treeOutline,emptyContentPlaceholderElement);let emptyContentPlaceholderParentElement=treeOutline.element.parentNode;emptyContentPlaceholderParentElement.appendChild(emptyContentPlaceholderElement);this._updateContentOverflowShadowVisibilityDebouncer.force();return emptyContentPlaceholderElement;} hideEmptyContentPlaceholder(treeOutline) {treeOutline=treeOutline||this._contentTreeOutline;let emptyContentPlaceholderElement=this._emptyContentPlaceholderElements.get(treeOutline);if(!emptyContentPlaceholderElement||!emptyContentPlaceholderElement.parentNode) return;emptyContentPlaceholderElement.remove();this._emptyContentPlaceholderElements.delete(treeOutline);this._updateContentOverflowShadowVisibilityDebouncer.force();} updateEmptyContentPlaceholder(message,treeOutline) {treeOutline=treeOutline||this._contentTreeOutline;if(!treeOutline.children.length){this.showEmptyContentPlaceholder(message,treeOutline);}else if(!this._emptyFilterResults.has(treeOutline)){this.hideEmptyContentPlaceholder(treeOutline);}} updateFilter() {let filters=this._filterBar.filters;this._textFilterRegex=filters.text?WI.SearchUtilities.filterRegExpForString(filters.text,WI.SearchUtilities.defaultSettings):null;this._filtersSetting.value=filters;this._filterFunctions=filters.functions;this._filterBar.invalid=filters.text&&!this._textFilterRegex;let dontPopulate=!this._filterBar.hasActiveFilters()&&!this.shouldFilterPopulate();for(let treeOutline of this.contentTreeOutlines){if(treeOutline.hidden||treeOutline[WI.NavigationSidebarPanel.SuppressFilteringSymbol]) continue;let currentTreeElement=treeOutline.children[0];while(currentTreeElement&&!currentTreeElement.root){if(!currentTreeElement[WI.NavigationSidebarPanel.SuppressFilteringSymbol]){const currentTreeElementWasHidden=currentTreeElement.hidden;this.applyFiltersToTreeElement(currentTreeElement);if(currentTreeElementWasHidden!==currentTreeElement.hidden) this._treeElementWasFiltered(currentTreeElement);} currentTreeElement=currentTreeElement.traverseNextTreeElement(false,null,dontPopulate);} this._checkForEmptyFilterResults(treeOutline);} this._updateContentOverflowShadowVisibilityDebouncer.force();} resetFilter() {this._filterBar.clear();} shouldFilterPopulate() {return this.hasCustomFilters();} hasCustomFilters() {return false;} matchTreeElementAgainstCustomFilters(treeElement) {return true;} matchTreeElementAgainstFilterFunctions(treeElement) {if(!this._filterFunctions||!this._filterFunctions.length) return true;for(var filterFunction of this._filterFunctions){if(filterFunction(treeElement)) return true;} return false;} applyFiltersToTreeElement(treeElement) {if(!this._filterBar.hasActiveFilters()&&!this.hasCustomFilters()){treeElement.hidden=false;if(treeElement.expanded&&treeElement[WI.NavigationSidebarPanel.WasExpandedDuringFilteringSymbol]){treeElement[WI.NavigationSidebarPanel.WasExpandedDuringFilteringSymbol]=false;treeElement.collapse();} return;} var filterableData=treeElement.filterableData||{};var flags={expandTreeElement:false};var filterRegex=this._textFilterRegex;function matchTextFilter(inputs) {if(!inputs||!filterRegex) return true;for(var input of inputs){if(!input) continue;if(filterRegex.test(input)){flags.expandTreeElement=true;return true;}} return false;} function makeVisible() {treeElement.hidden=false;var currentAncestor=treeElement.parent;while(currentAncestor&&!currentAncestor.root){currentAncestor.hidden=false;if(flags.expandTreeElement&&!currentAncestor.expanded){currentAncestor.__wasExpandedDuringFiltering=true;currentAncestor.expand();} currentAncestor=currentAncestor.parent;}} let suppressFiltering=treeElement[WI.NavigationSidebarPanel.SuppressFilteringSymbol];if(suppressFiltering||(matchTextFilter(filterableData.text)&&this.matchTreeElementAgainstFilterFunctions(treeElement,flags)&&this.matchTreeElementAgainstCustomFilters(treeElement,flags))){makeVisible();if(!flags.expandTreeElement&&treeElement.expanded&&treeElement[WI.NavigationSidebarPanel.WasExpandedDuringFilteringSymbol]){treeElement[WI.NavigationSidebarPanel.WasExpandedDuringFilteringSymbol]=false;treeElement.collapse();} return;} treeElement.hidden=true;} attached() {super.attached();this._updateContentOverflowShadowVisibilityDebouncer.force();if(this._contentBrowser&&!this._contentBrowser.currentContentView) this.showDefaultContentView();} pruneStaleResourceTreeElements() {if(this._checkForStaleResourcesTimeoutIdentifier){clearTimeout(this._checkForStaleResourcesTimeoutIdentifier);this._checkForStaleResourcesTimeoutIdentifier=undefined;} for(let contentTreeOutline of this.contentTreeOutlines){ for(let i=contentTreeOutline.children.length-1;i>=0;--i){let treeElement=contentTreeOutline.children[i];if(!(treeElement instanceof WI.ResourceTreeElement)) continue;let resource=treeElement.resource;if(resource.localResourceOverride) continue;if(!resource.parentFrame||resource.parentFrame.isDetached()) contentTreeOutline.removeChildAtIndex(i,true,true);}}} _updateContentOverflowShadowVisibility() {if(!this.visible) return;let scrollHeight=this.contentView.element.scrollHeight;let offsetHeight=this.contentView.element.offsetHeight;if(scrollHeight{this.resetFilter();});this.showEmptyContentPlaceholder(message,treeOutline);this._emptyFilterResults.add(treeOutline);} _filterDidChange() {this.updateFilter();} _treeElementAddedOrChanged(event) {var dontPopulate=!this._filterBar.hasActiveFilters()&&!this.shouldFilterPopulate();let treeElement=event.data.element;let currentTreeElement=treeElement;while(currentTreeElement&&!currentTreeElement.root){if(!currentTreeElement[WI.NavigationSidebarPanel.SuppressFilteringSymbol]){const currentTreeElementWasHidden=currentTreeElement.hidden;this.applyFiltersToTreeElement(currentTreeElement);if(currentTreeElementWasHidden!==currentTreeElement.hidden) this._treeElementWasFiltered(currentTreeElement);} currentTreeElement=currentTreeElement.traverseNextTreeElement(false,treeElement,dontPopulate);} this._checkForEmptyFilterResults(event.target);if(this.visible) this._updateContentOverflowShadowVisibilityDebouncer.delayForTime(0);if(this.selected&&!treeElement.treeOutline[WI.NavigationSidebarPanel.IgnoreCookieRestoration]) this._checkElementsForPendingViewStateCookie([treeElement]);} _treeElementDisclosureDidChange(event) {this._updateContentOverflowShadowVisibilityDebouncer.delayForTime(0);} _handleTreeElementRemoved(event) {this._checkForEmptyFilterResults(event.target);if(this.visible) this._updateContentOverflowShadowVisibilityDebouncer.delayForTime(0);} _checkForStaleResourcesIfNeeded() {if(!this._checkForStaleResourcesTimeoutIdentifier||!this._shouldAutoPruneStaleTopLevelResourceTreeElements) return;this.pruneStaleResourceTreeElements();} _checkForStaleResources(event) {if(this._checkForStaleResourcesTimeoutIdentifier) return;this._checkForStaleResourcesTimeoutIdentifier=setTimeout(this.pruneStaleResourceTreeElements.bind(this));} _isTreeElementWithoutRepresentedObject(treeElement) {return treeElement instanceof WI.FolderTreeElement||treeElement instanceof WI.DatabaseHostTreeElement||treeElement instanceof WI.IndexedDatabaseHostTreeElement||treeElement instanceof WI.ApplicationCacheManifestTreeElement||treeElement instanceof WI.ThreadTreeElement||treeElement instanceof WI.IdleTreeElement||treeElement instanceof WI.DOMBreakpointTreeElement||treeElement instanceof WI.EventBreakpointTreeElement||treeElement instanceof WI.URLBreakpointTreeElement||treeElement instanceof WI.SymbolicBreakpointTreeElement||treeElement instanceof WI.CSSStyleSheetTreeElement||typeof treeElement.representedObject==="string"||treeElement.representedObject instanceof String;} _checkOutlinesForPendingViewStateCookie(matchTypeOnly) {if(!this._pendingViewStateCookie) return;this._checkForStaleResourcesIfNeeded();var visibleTreeElements=[];this.contentTreeOutlines.forEach(function(outline){if(outline[WI.NavigationSidebarPanel.IgnoreCookieRestoration]) return;var currentTreeElement=outline.hasChildren?outline.children[0]:null;while(currentTreeElement){visibleTreeElements.push(currentTreeElement);currentTreeElement=currentTreeElement.traverseNextTreeElement(false,null,false);}});this._checkElementsForPendingViewStateCookie(visibleTreeElements,matchTypeOnly);} _checkElementsForPendingViewStateCookie(treeElements,matchTypeOnly) {if(!this._pendingViewStateCookie) return;var cookie=this._pendingViewStateCookie;function treeElementMatchesCookie(treeElement) {if(this._isTreeElementWithoutRepresentedObject(treeElement)) return false;var representedObject=treeElement.representedObject;if(!representedObject) return false;var typeIdentifier=cookie[WI.TypeIdentifierCookieKey];if(typeIdentifier!==representedObject.constructor.TypeIdentifier) return false;if(matchTypeOnly) return!!typeIdentifier;var candidateObjectCookie={};if(representedObject.saveIdentityToCookie) representedObject.saveIdentityToCookie(candidateObjectCookie);var candidateCookieKeys=Object.keys(candidateObjectCookie);return candidateCookieKeys.length&&candidateCookieKeys.every((key)=>candidateObjectCookie[key]===cookie[key]);} var matchedElement=null;treeElements.some((element)=>{if(treeElementMatchesCookie.call(this,element)){matchedElement=element;return true;} return false;});if(matchedElement){let didShowContentView=this.showDefaultContentViewForTreeElement(matchedElement);if(!didShowContentView) return;this._pendingViewStateCookie=null; setTimeout(()=>{this._restoringState=false;},0);if(this._finalAttemptToRestoreViewStateTimeout){clearTimeout(this._finalAttemptToRestoreViewStateTimeout);this._finalAttemptToRestoreViewStateTimeout=undefined;}}} _treeElementWasFiltered(treeElement) {if(treeElement.selected||treeElement.hidden) return;let representedObject=this.currentRepresentedObject;if(!representedObject||treeElement.representedObject!==representedObject) return;const omitFocus=true;const selectedByUser=false;const suppressNotification=true;treeElement.revealAndSelect(omitFocus,selectedByUser,suppressNotification);}};WI.NavigationSidebarPanel.IgnoreCookieRestoration=Symbol("ignore-cookie-restoration");WI.NavigationSidebarPanel.SuppressFilteringSymbol=Symbol("suppress-filtering");WI.NavigationSidebarPanel.WasExpandedDuringFilteringSymbol=Symbol("was-expanded-during-filtering");WI.NavigationSidebarPanel.OverflowShadowElementStyleClassName="overflow-shadow";WI.NavigationSidebarPanel.ContentTreeOutlineElementStyleClassName="navigation-sidebar-panel-content-tree-outline";WI.PinnedTabBarItem=class PinnedTabBarItem extends WI.TabBarItem {constructor(representedObject,image,displayName,title) {super(representedObject,image,displayName,title);this.element.classList.add("pinned");} static fromTabContentView(tabContentView) {let{image,displayName,title}=tabContentView.tabInfo();return new WI.PinnedTabBarItem(tabContentView,image,displayName,title);}};WI.ResourceContentView=class ResourceContentView extends WI.ContentView {constructor(resource,styleClassName) {super(resource);this._resource=resource;this.element.classList.add(styleClassName,"resource");this._spinnerTimeout=setTimeout(()=>{if(!this._hasContent()){ let spinner=new WI.IndeterminateProgressSpinner;this.element.appendChild(spinner.element);} this._spinnerTimeout=undefined;},100);this.element.addEventListener("click",this._mouseWasClicked.bind(this),false);resource.requestContent().then(this._contentAvailable.bind(this)).catch(this.showGenericErrorMessage.bind(this));if(!this.managesOwnIssues){WI.consoleManager.addEventListener(WI.ConsoleManager.Event.IssueAdded,this._issueWasAdded,this);var issues=WI.consoleManager.issuesForSourceCode(resource);for(var i=0;i{WI.FileUtilities.import(async(fileList)=>{this._getContentForLocalResourceOverrideFromFile(fileList[0],({mimeType,base64Encoded,content})=>{resolve({mimeType,base64Encoded,content});});});});} showGenericNoContentMessage() {this.showMessage(WI.UIString("Resource has no content."));this.dispatchEventToListeners(WI.ResourceContentView.Event.ContentError);} showNoCachedContentMessage() {this.showMessage(WI.UIString("Resource has no cached content.","Resource has no cached content. @ Resource Preview","An error message shown when there is no cached content for a HTTP 304 Not Modified resource response."));this.dispatchEventToListeners(WI.ResourceContentView.Event.ContentError);} showGenericErrorMessage() {this._contentError(WI.UIString("An error occurred trying to load the resource."));} showMessage(message) {this.removeAllSubviews();this.element.appendChild(WI.createMessageTextView(message));} addIssue(issue) {this.removeAllSubviews();this.element.appendChild(WI.createMessageTextView(issue.text,issue.level===WI.IssueMessage.Level.Error));} closed() {super.closed();if(WI.NetworkManager.supportsOverridingResponses()){WI.networkManager.removeEventListener(WI.NetworkManager.Event.LocalResourceOverrideAdded,this._handleLocalResourceOverrideChanged,this);WI.networkManager.removeEventListener(WI.NetworkManager.Event.LocalResourceOverrideRemoved,this._handleLocalResourceOverrideChanged,this);} if(!this.managesOwnIssues) WI.consoleManager.removeEventListener(WI.ConsoleManager.Event.IssueAdded,this._issueWasAdded,this);} removeLoadingIndicator() {if(this._spinnerTimeout){clearTimeout(this._spinnerTimeout);this._spinnerTimeout=undefined;} this.removeAllSubviews();if(this._localResourceOverrideBannerView) this.addSubview(this._localResourceOverrideBannerView);} _contentAvailable(parameters) {if(parameters.error){if(parameters.sourceCode.statusCode==304&¶meters.reason==="Missing content of resource for given requestId"){this.showNoCachedContentMessage();return;} this._contentError(parameters.error);return;} if(parameters.message){this.showMessage(parameters.message);return;} if(parameters.sourceCode instanceof WI.LocalResource){if(this.resource.mappedFilePath){this._handleMappedFilePathChanged();return;}} if(this._hasContent()) return;if(!parameters.sourceCode.content&&!parameters.sourceCode.mimeType){this.showGenericNoContentMessage();return;} this.contentAvailable(parameters.sourceCode.content,parameters.base64Encoded);if(this._createLocalResourceOverrideButtonNavigationItem) this._createLocalResourceOverrideButtonNavigationItem.enabled=WI.networkManager.canBeOverridden(this._resource);} _contentError(error) {if(this._hasContent()) return;this.removeLoadingIndicator();this.element.appendChild(WI.createMessageTextView(error,true));this.dispatchEventToListeners(WI.ResourceContentView.Event.ContentError);} _hasContent() {return this.element.hasChildNodes()&&!this.element.querySelector(".indeterminate-progress-spinner");} _issueWasAdded(event) {var issue=event.data.issue;if(!WI.ConsoleManager.issueMatchSourceCode(issue,this._resource)) return;this.addIssue(issue);} async _getContentForLocalResourceOverrideFromFile(file,callback) {let mimeType=file.type||WI.mimeTypeForFileExtension(WI.fileExtensionForFilename(file.name));if(WI.shouldTreatMIMETypeAsText(mimeType)){await WI.FileUtilities.readText(file,async({text})=>{await callback({mimeType,base64Encoded:false,content:text,});});}else{await WI.FileUtilities.readData(file,async({mimeType,base64Encoded,content})=>{await callback({mimeType,base64Encoded,content});});}} async _createAndShowLocalResourceOverride(type,{requestInitialContent}={}) {let initialContent=requestInitialContent?await this.requestLocalResourceOverrideInitialContent():{};let localResourceOverride=await this._resource.createLocalResourceOverride(type,initialContent);WI.networkManager.addLocalResourceOverride(localResourceOverride);WI.showLocalResourceOverride(localResourceOverride,{overriddenResource:this._resource});} _populateCreateLocalResourceOverrideContextMenu(contextMenu,event) {if(!this._createLocalResourceOverrideButtonNavigationItem.enabled) return;if(WI.NetworkManager.supportsOverridingRequests()){contextMenu.appendItem(WI.UIString("Create Request Local Override"),()=>{this._createAndShowLocalResourceOverride(WI.LocalResourceOverride.InterceptType.Request);});} contextMenu.appendItem(WI.UIString("Create Response Local Override"),()=>{this._createAndShowLocalResourceOverride(WI.LocalResourceOverride.InterceptType.Response,{requestInitialContent:!event.shiftKey,});});if(WI.NetworkManager.supportsBlockingRequests()){contextMenu.appendItem(WI.UIString("Block Request URL"),async()=>{let localResourceOverride=await this._resource.createLocalResourceOverride(WI.LocalResourceOverride.InterceptType.Block);WI.networkManager.addLocalResourceOverride(localResourceOverride);});}} _handleCreateLocalResourceOverride(event) {let{nativeEvent}=event.data;this._createAndShowLocalResourceOverride(WI.LocalResourceOverride.InterceptType.Response,{requestInitialContent:!nativeEvent.shiftKey,});} _handleImportLocalResourceOverride(event) {let localResourceOverride=this.resource.localResourceOverride||WI.networkManager.localResourceOverridesForURL(this.resource.url)[0];WI.FileUtilities.import(async(fileList)=>{await this._getContentForLocalResourceOverrideFromFile(fileList[0],({mimeType,base64Encoded,content})=>{let revision=localResourceOverride.localResource.editableRevision;revision.updateRevisionContent(content,{base64Encoded,mimeType});});if(!this._resource.localResourceOverride) WI.showLocalResourceOverride(localResourceOverride,{overriddenResource:this._resource});});} _handleMapLocalResourceOverrideToFile(event) {WI.FileUtilities.import((files)=>{this.resource.mappedFilePath=WI.FileUtilities.longestCommonPrefix(files,{directory:this.resource.localResourceOverride.type===WI.LocalResourceOverride.InterceptType.ResponseMappedDirectory,});},{directory:true});} _handleMappedFilePathChanged(event) {let mappedFilePath=this.resource.mappedFilePath;let mappedFilePathLink=document.createElement("a");mappedFilePathLink.href="file://"+mappedFilePath;mappedFilePathLink.textContent=mappedFilePath.insertWordBreakCharacters();mappedFilePathLink.addEventListener("click",(event)=>{event.stop();InspectorFrontendHost.revealFileExternally(event.target.href);});let fragment=document.createDocumentFragment();String.format(WI.UIString("Mapped to \u201C%s\u201D"),[mappedFilePathLink],String.standardFormatters,fragment,(a,b)=>{a.append(b);return a;});this.showMessage(fragment);if(this._localResourceOverrideBannerView){this.element.insertBefore(this._localResourceOverrideBannerView.element,this.element.firstChild);this.addSubview(this._localResourceOverrideBannerView);}} _handleRemoveLocalResourceOverride(event) {let localResourceOverride=this.resource.localResourceOverride||WI.networkManager.localResourceOverridesForURL(this._resource.url)[0];WI.networkManager.removeLocalResourceOverride(localResourceOverride);} _handleLocalResourceOverrideChanged(event) {let{localResourceOverride}=event.data;if(!localResourceOverride.matches(this._resource.url)) return;if(this._createLocalResourceOverrideButtonNavigationItem) this._createLocalResourceOverrideButtonNavigationItem.enabled=WI.networkManager.canBeOverridden(this._resource);} _mouseWasClicked(event) {WI.handlePossibleLinkClick(event,{frame:this._resource.parentFrame});}};WI.ResourceContentView.Event={ContentError:"resource-content-view-content-error",};WI.TabContentView=class TabContentView extends WI.ContentView {constructor(tabInfo,{navigationSidebarPanelConstructor,detailsSidebarPanelConstructors}={}) {super(null);this._identifier=tabInfo.identifier;this._navigationSidebarPanelConstructor=navigationSidebarPanelConstructor||null;this._detailsSidebarPanelConstructors=detailsSidebarPanelConstructors||[];this._navigationSidebarCollapsedSetting=new WI.Setting(this._identifier+"-navigation-sidebar-collapsed",false);this._navigationSidebarWidthSetting=new WI.Setting(this._identifier+"-navigation-sidebar-width",WI.TabContentView.DefaultSidebarWidth);this._detailsSidebarCollapsedSetting=new WI.Setting(this._identifier+"-details-sidebar-collapsed",!this.detailsSidebarExpandedByDefault);this._detailsSidebarSelectedPanelSetting=new WI.Setting(this._identifier+"-details-sidebar-selected-panel",null);this._detailsSidebarWidthSetting=new WI.Setting(this._identifier+"-details-sidebar-widths",{});this._detailsSidebarHeightSetting=new WI.Setting(this._identifier+"-details-sidebar-height",null);this._cookieSetting=new WI.Setting(this._identifier+"-tab-cookie",{});this.element.classList.add("tab",this._identifier);} static isTabAllowed() {return true;} static shouldPinTab() {return false;} static shouldSaveTab() {return true;} get type() {return null;} get identifier() {return this._identifier;} get tabBarItem() {if(!this._tabBarItem) this._tabBarItem=this.constructor.shouldPinTab()?WI.PinnedTabBarItem.fromTabContentView(this):WI.GeneralTabBarItem.fromTabContentView(this);return this._tabBarItem;} get managesNavigationSidebarPanel() {return false;} get managesDetailsSidebarPanels() {return false;} get detailsSidebarExpandedByDefault() {return false;} showDetailsSidebarPanels() {} showRepresentedObject(representedObject,cookie) {} canShowRepresentedObject(representedObject) {return false;} get allowMultipleDetailSidebars() {return false;} tabInfo() {return this.constructor.tabInfo();} attached() {super.attached();if(this._shouldRestoreStateWhenShown) this.restoreStateFromCookie(WI.StateRestorationType.Delayed);} restoreStateFromCookie(restorationType) {if(!this.isAttached){this._shouldRestoreStateWhenShown=true;return;} this._shouldRestoreStateWhenShown=false;var relaxMatchDelay=0;if(restorationType===WI.StateRestorationType.Load) relaxMatchDelay=1000;else if(restorationType===WI.StateRestorationType.Navigation) relaxMatchDelay=2000;let cookie=this._cookieSetting.value||{};if(this.navigationSidebarPanel) this.navigationSidebarPanel.restoreStateFromCookie(cookie,relaxMatchDelay);this.restoreFromCookie(cookie);} saveStateToCookie(cookie) {if(this._shouldRestoreStateWhenShown) return;cookie=cookie||{};if(this.navigationSidebarPanel) this.navigationSidebarPanel.saveStateToCookie(cookie);this.saveToCookie(cookie);this._cookieSetting.value=cookie;} get navigationSidebarPanel() {if(!this._navigationSidebarPanelConstructor) return null;if(!this._navigationSidebarPanel) this._navigationSidebarPanel=new this._navigationSidebarPanelConstructor;return this._navigationSidebarPanel;} get navigationSidebarCollapsedSetting(){return this._navigationSidebarCollapsedSetting;} get navigationSidebarWidthSetting(){return this._navigationSidebarWidthSetting;} get detailsSidebarPanels() {if(!this._detailsSidebarPanels) this._detailsSidebarPanels=this._detailsSidebarPanelConstructors.map((constructor)=>new constructor);return this._detailsSidebarPanels;} get detailsSidebarCollapsedSetting(){return this._detailsSidebarCollapsedSetting;} get detailsSidebarSelectedPanelSetting(){return this._detailsSidebarSelectedPanelSetting;} get detailsSidebarWidthSetting(){return this._detailsSidebarWidthSetting;} get detailsSidebarHeightSetting(){return this._detailsSidebarHeightSetting;}};WI.TabContentView.DefaultSidebarWidth=300;WI.TabContentView.DefaultSidebarHeight=400;WI.TextContentView=class TextContentView extends WI.ContentView {constructor(string,mimeType,representedObject) {super(representedObject||string);this.element.classList.add("text");this._textEditor=new WI.TextEditor;this._textEditor.addEventListener(WI.TextEditor.Event.NumberOfSearchResultsDidChange,this._numberOfSearchResultsDidChange,this);this._textEditor.addEventListener(WI.TextEditor.Event.FormattingDidChange,this._textEditorFormattingDidChange,this);this._textEditor.addEventListener(WI.TextEditor.Event.MIMETypeChanged,this._handleTextEditorMIMETypeChanged,this);this.addSubview(this._textEditor);var toolTip=WI.UIString("Pretty print");var activatedToolTip=WI.UIString("Original formatting");this._prettyPrintButtonNavigationItem=new WI.ActivateButtonNavigationItem("pretty-print",toolTip,activatedToolTip,"Images/NavigationItemCurleyBraces.svg",13,13);this._prettyPrintButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._togglePrettyPrint,this);this._prettyPrintButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;var toolTipTypes=WI.UIString("Show type information");var activatedToolTipTypes=WI.UIString("Hide type information");this._showTypesButtonNavigationItem=new WI.ActivateButtonNavigationItem("show-types",toolTipTypes,activatedToolTipTypes,"Images/NavigationItemTypes.svg",13,14);this._showTypesButtonNavigationItem.enabled=false;this._showTypesButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;let toolTipCodeCoverage=WI.UIString("Fade unexecuted code");let activatedToolTipCodeCoverage=WI.UIString("Do not fade unexecuted code");this._codeCoverageButtonNavigationItem=new WI.ActivateButtonNavigationItem("code-coverage",toolTipCodeCoverage,activatedToolTipCodeCoverage,"Images/NavigationItemCodeCoverage.svg",13,14);this._codeCoverageButtonNavigationItem.enabled=false;this._codeCoverageButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._textEditor.readOnly=true;this._textEditor.mimeType=mimeType;this._textEditor.string=string;this._prettyPrintButtonNavigationItem.enabled=this._textEditor.canBeFormatted();} get textEditor() {return this._textEditor;} get navigationItems() {return[this._prettyPrintButtonNavigationItem,this._showTypesButtonNavigationItem,this._codeCoverageButtonNavigationItem];} revealPosition(position,options={}) {this._textEditor.revealPosition(position,options);} get supportsSave() {return true;} get saveMode() {return WI.FileUtilities.SaveMode.SingleFile;} get saveData() {return{content:this._textEditor.string,suggestedName:WI.UIString("Untitled")+".txt",forceSaveAs:true,};} get supportsSearch() {return true;} get numberOfSearchResults() {return this._textEditor.numberOfSearchResults;} get hasPerformedSearch() {return this._textEditor.currentSearchQuery!==null;} set automaticallyRevealFirstSearchResult(reveal) {this._textEditor.automaticallyRevealFirstSearchResult=reveal;} performSearch(query) {this._textEditor.performSearch(query);} searchCleared() {this._textEditor.searchCleared();} searchQueryWithSelection() {return this._textEditor.searchQueryWithSelection();} revealPreviousSearchResult(changeFocus) {this._textEditor.revealPreviousSearchResult(changeFocus);} revealNextSearchResult(changeFocus) {this._textEditor.revealNextSearchResult(changeFocus);} _togglePrettyPrint(event) {var activated=!this._prettyPrintButtonNavigationItem.activated;this._textEditor.updateFormattedState(activated);} _textEditorFormattingDidChange(event) {this._prettyPrintButtonNavigationItem.activated=this._textEditor.formatted;} _handleTextEditorMIMETypeChanged(event) {this._prettyPrintButtonNavigationItem.enabled=this._textEditor.canBeFormatted();} _numberOfSearchResultsDidChange(event) {this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);}};WI.TimelineDataGrid=class TimelineDataGrid extends WI.DataGrid {constructor(columns) {super(columns);this.element.classList.add("timeline");this._sortDelegate=null;this._scopeBarColumns=[];for(var[identifier,column]of this.columns){var scopeBar=column.scopeBar;if(!scopeBar) continue;this._scopeBarColumns.push(identifier);scopeBar.columnIdentifier=identifier;scopeBar.addEventListener(WI.ScopeBar.Event.SelectionChanged,this._scopeBarSelectedItemsDidChange,this);} if(this._scopeBarColumns.length>1){console.error("Creating a TimelineDataGrid with more than one filterable column is not yet supported.");return;} this.addEventListener(WI.DataGrid.Event.SelectedNodeChanged,this._dataGridSelectedNodeChanged,this);this.addEventListener(WI.DataGrid.Event.SortChanged,this._sort,this);this.columnChooserEnabled=true;} static createColumnScopeBar(prefix,map) {prefix=prefix+"-timeline-data-grid-";var scopeBarItems=[];for(var[key,value]of map){var id=prefix+key;var item=new WI.ScopeBarItem(id,value);item.value=key;scopeBarItems.push(item);} var allItem=new WI.ScopeBarItem(prefix+"type-all",WI.UIString("All"));scopeBarItems.unshift(allItem);return new WI.ScopeBar(prefix+"scope-bar",scopeBarItems,allItem,true);} get sortDelegate() {return this._sortDelegate;} set sortDelegate(delegate) {delegate=delegate||null;if(this._sortDelegate===delegate) return;this._sortDelegate=delegate;if(this.sortOrder!==WI.DataGrid.SortOrder.Indeterminate) this.dispatchEventToListeners(WI.DataGrid.Event.SortChanged);} reset() {this.removeChildren();this._hidePopover();} detached() {this._hidePopover();super.detached();} callFramePopoverAnchorElement() {return null;} shouldShowCallFramePopover() {return false;} addRowInSortOrder(dataGridNode,parentDataGridNode) {parentDataGridNode=parentDataGridNode||this;if(this.sortColumnIdentifier){let insertionIndex=insertionIndexForObjectInListSortedByFunction(dataGridNode,parentDataGridNode.children,this._sortComparator.bind(this));parentDataGridNode.insertChild(dataGridNode,insertionIndex);}else parentDataGridNode.appendChild(dataGridNode);} shouldIgnoreSelectionEvent() {return this._ignoreSelectionEvent||false;} dataGridNodeNeedsRefresh(dataGridNode) {if(!this._dirtyDataGridNodes) this._dirtyDataGridNodes=new Set;this._dirtyDataGridNodes.add(dataGridNode);if(this._scheduledDataGridNodeRefreshIdentifier) return;this._scheduledDataGridNodeRefreshIdentifier=requestAnimationFrame(this._refreshDirtyDataGridNodes.bind(this));} hasCustomFilters() {return true;} matchNodeAgainstCustomFilters(node) {if(!super.matchNodeAgainstCustomFilters(node)) return false;for(let identifier of this._scopeBarColumns){let scopeBar=this.columns.get(identifier).scopeBar;if(!scopeBar||scopeBar.defaultItem.selected) continue;let value=node.data[identifier];if(!scopeBar.selectedItems.some((scopeBarItem)=>scopeBarItem.value===value)) return false;} return true;} _refreshDirtyDataGridNodes() {if(this._scheduledDataGridNodeRefreshIdentifier){cancelAnimationFrame(this._scheduledDataGridNodeRefreshIdentifier);this._scheduledDataGridNodeRefreshIdentifier=undefined;} if(!this._dirtyDataGridNodes) return;let selectedNode=this.selectedNode;let sortComparator=this._sortComparator.bind(this);for(let dataGridNode of this._dirtyDataGridNodes){dataGridNode.refresh();if(!this.sortColumnIdentifier) continue;if(dataGridNode===selectedNode) this._ignoreSelectionEvent=true;if(dataGridNode.parent===this) this.removeChild(dataGridNode);let insertionIndex=insertionIndexForObjectInListSortedByFunction(dataGridNode,this.children,sortComparator);this.insertChild(dataGridNode,insertionIndex);if(dataGridNode===selectedNode){selectedNode.revealAndSelect();this._ignoreSelectionEvent=false;}} this._dirtyDataGridNodes=null;} _sort() {if(!this.children.length) return;let sortColumnIdentifier=this.sortColumnIdentifier;if(!sortColumnIdentifier) return;let selectedNode=this.selectedNode;this._ignoreSelectionEvent=true; let parentDataGridNodes=[this];let currentDataGridNode=this.children[0];while(currentDataGridNode){if(currentDataGridNode.children.length) parentDataGridNodes.push(currentDataGridNode);currentDataGridNode=currentDataGridNode.traverseNextNode(false,null,true);} for(let parentDataGridNode of parentDataGridNodes){let childDataGridNodes=parentDataGridNode.children.slice();parentDataGridNode.removeChildren();childDataGridNodes.sort(this._sortComparator.bind(this));for(let dataGridNode of childDataGridNodes) parentDataGridNode.appendChild(dataGridNode);} if(selectedNode) selectedNode.revealAndSelect();this._ignoreSelectionEvent=false;} _sortComparator(node1,node2) {var sortColumnIdentifier=this.sortColumnIdentifier;if(!sortColumnIdentifier) return 0;var sortDirection=this.sortOrder===WI.DataGrid.SortOrder.Ascending?1:-1;if(this._sortDelegate&&typeof this._sortDelegate.dataGridSortComparator==="function"){let result=this._sortDelegate.dataGridSortComparator(sortColumnIdentifier,sortDirection,node1,node2);if(typeof result==="number") return result;} var value1=node1.data[sortColumnIdentifier];var value2=node2.data[sortColumnIdentifier];if(typeof value1==="number"&&typeof value2==="number"){if(isNaN(value1)&&isNaN(value2)) return 0;if(isNaN(value1)) return-sortDirection;if(isNaN(value2)) return sortDirection;return(value1-value2)*sortDirection;} if(typeof value1==="string"&&typeof value2==="string") return value1.extendedLocaleCompare(value2)*sortDirection;if(value1 instanceof WI.CallFrame||value2 instanceof WI.CallFrame){value1=value1&&value1.functionName?value1.functionName:(value1&&value1.sourceCodeLocation?value1.sourceCodeLocation.sourceCode:"");value2=value2&&value2.functionName?value2.functionName:(value2&&value2.sourceCodeLocation?value2.sourceCodeLocation.sourceCode:"");} if(value1 instanceof WI.SourceCode||value2 instanceof WI.SourceCode){value1=value1?value1.displayName||"":"";value2=value2?value2.displayName||"":"";} if(value1 instanceof WI.SourceCodeLocation||value2 instanceof WI.SourceCodeLocation){value1=value1?value1.displayLocationString()||"":"";value2=value2?value2.displayLocationString()||"":"";} return(value1value2?1:0))*sortDirection;} _scopeBarSelectedItemsDidChange(event) {this.filterDidChange();} _dataGridSelectedNodeChanged(event) {if(!this.selectedNode){this._hidePopover();return;} var record=this.selectedNode.record;if(!record||!record.stackTrace?.callFrames.length){this._hidePopover();return;} if(this.shouldShowCallFramePopover()) this._showPopoverForSelectedNodeSoon();} _showPopoverForSelectedNodeSoon() {if(this._showPopoverTimeout) return;this._showPopoverTimeout=setTimeout(()=>{if(!this._popover){this._popover=new WI.Popover;this._popover.windowResizeHandler=()=>{this._updatePopoverForSelectedNode(false);};} this._updatePopoverForSelectedNode(true);this._showPopoverTimeout=undefined;},WI.TimelineDataGrid.DelayedPopoverShowTimeout);} _hidePopover() {if(this._showPopoverTimeout){clearTimeout(this._showPopoverTimeout);this._showPopoverTimeout=undefined;} if(this._popover) this._popover.dismiss();if(this._hidePopoverContentClearTimeout) clearTimeout(this._hidePopoverContentClearTimeout);this._hidePopoverContentClearTimeout=setTimeout(()=>{if(this._popoverCallStackTreeOutline) this._popoverCallStackTreeOutline.removeChildren();},WI.TimelineDataGrid.DelayedPopoverHideContentClearTimeout);} _updatePopoverForSelectedNode(updateContent) {if(!this._popover||!this.selectedNode) return;let targetPopoverElement=this.callFramePopoverAnchorElement();if(!targetPopoverElement) return;let rect=WI.Rect.rectFromClientRect(targetPopoverElement.getBoundingClientRect());if(!rect.size.width&&!rect.size.height) return;if(this._hidePopoverContentClearTimeout){clearTimeout(this._hidePopoverContentClearTimeout);this._hidePopoverContentClearTimeout=undefined;} let targetFrame=rect.pad(2);let preferredEdges=[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X];if(updateContent) this._popover.presentNewContentWithFrame(this._createPopoverContent(),targetFrame,preferredEdges);else this._popover.present(targetFrame,preferredEdges);} _createPopoverContent() {if(!this._popoverCallStackTreeOutline){this._popoverCallStackTreeOutline=new WI.TreeOutline;this._popoverCallStackTreeOutline.disclosureButtons=false;this._popoverCallStackTreeOutline.element.classList.add("timeline-data-grid");this._popoverCallStackTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._popoverCallStackTreeSelectionDidChange,this);this._popoverCallStackTreeOutline.addEventListener(WI.TreeOutline.Event.ElementRemoved,this._popoverCallStackTreeElementRemoved,this);}else this._popoverCallStackTreeOutline.removeChildren();if(this.selectedNode.record.stackTrace) WI.StackTraceTreeController.groupBlackboxedStackTrace(this._popoverCallStackTreeOutline,this.selectedNode.record.stackTrace);let content=document.createElement("div");content.appendChild(this._popoverCallStackTreeOutline.element);return content;} _popoverCallStackTreeSelectionDidChange(event) {let treeElement=this._popoverCallStackTreeOutline.selectedTreeElement;if(!treeElement) return;this._popover.dismiss();var callFrame=treeElement.callFrame;if(!callFrame.sourceCodeLocation) return;WI.showSourceCodeLocation(callFrame.sourceCodeLocation,{ignoreNetworkTab:true,ignoreSearchTab:true,});} _popoverCallStackTreeElementRemoved(event) {if(event.data.element instanceof WI.BlackboxedGroupTreeElement) this._popover?.update();}};WI.TimelineDataGrid.HasNonDefaultFilterStyleClassName="has-non-default-filter";WI.TimelineDataGrid.DelayedPopoverShowTimeout=250;WI.TimelineDataGrid.DelayedPopoverHideContentClearTimeout=500;WI.TimelineDataGridNode=class TimelineDataGridNode extends WI.DataGridNode {constructor(records,{hasChildren,includesGraph,graphDataSource}={}) {super({},{hasChildren,copyable:false});this._records=records;this._includesGraph=includesGraph||false;this._graphDataSource=graphDataSource||null;this._cachedData=null;if(this._graphDataSource){this._graphContainerElement=document.createElement("div");this._timelineRecordBars=[];}} get records(){return this._records;} get record() {return this.records&&this.records.length?this.records[0]:null;} get graphDataSource() {return this._graphDataSource;} get data() {if(!this._graphDataSource) return{};return{graph:this.record?this.record.startTime:0,};} collapse() {super.collapse();if(!this._graphDataSource||!this.revealed) return;this.refreshGraph();} expand() {super.expand();if(!this._graphDataSource||!this.revealed) return;this.refreshGraph();var childNode=this.children[0];while(childNode){if(childNode instanceof WI.TimelineDataGridNode) childNode.refreshGraph();childNode=childNode.traverseNextNode(true,this);}} createCellContent(columnIdentifier,cell) {if(columnIdentifier==="graph"&&this._graphDataSource){this.needsGraphRefresh();return this._graphContainerElement;} var value=this.data[columnIdentifier];if(!value) return emDash;const options={useGoToArrowButton:true,ignoreNetworkTab:true,ignoreSearchTab:true,};if(value instanceof WI.SourceCodeLocation){if(value.sourceCode instanceof WI.Resource){cell.classList.add(WI.ResourceTreeElement.ResourceIconStyleClassName,...WI.Resource.classNamesForResource(value.sourceCode));}else if(value.sourceCode instanceof WI.Script){if(value.sourceCode.url){cell.classList.add(WI.ResourceTreeElement.ResourceIconStyleClassName);cell.classList.add(WI.Resource.Type.Script);}else cell.classList.add(WI.ScriptTreeElement.AnonymousScriptIconStyleClassName);}else console.error("Unknown SourceCode subclass.");value.populateLiveDisplayLocationTooltip(cell);var fragment=document.createDocumentFragment();fragment.appendChild(WI.createSourceCodeLocationLink(value,options));var titleElement=document.createElement("span");value.populateLiveDisplayLocationString(titleElement,"textContent");fragment.appendChild(titleElement);return fragment;} if(value instanceof WI.CallFrame){var callFrame=value;var isAnonymousFunction=false;var functionName=callFrame.functionName;if(!functionName){functionName=WI.UIString("(anonymous function)");isAnonymousFunction=true;} cell.classList.add(WI.CallFrameView.FunctionIconStyleClassName);var fragment=document.createDocumentFragment();let iconElement=document.createElement("div");iconElement.classList.add("icon");let sourceCode=callFrame.sourceCodeLocation?.sourceCode;if(sourceCode){callFrame.sourceCodeLocation.populateLiveDisplayLocationTooltip(cell);fragment.appendChild(WI.createSourceCodeLocationLink(callFrame.sourceCodeLocation,options));if(isAnonymousFunction){if(sourceCode instanceof WI.Resource){cell.classList.add(WI.ResourceTreeElement.ResourceIconStyleClassName,...WI.Resource.classNamesForResource(sourceCode));if(sourceCode.responseSource===WI.Resource.ResponseSource.InspectorOverride) iconElement.title=WI.UIString("This resource was loaded from a local override");}else if(sourceCode instanceof WI.Script){if(sourceCode.url){cell.classList.add(WI.ResourceTreeElement.ResourceIconStyleClassName);cell.classList.add(WI.Resource.Type.Script);}else cell.classList.add(WI.ScriptTreeElement.AnonymousScriptIconStyleClassName);}else console.error("Unknown SourceCode subclass.");var titleElement=document.createElement("span");callFrame.sourceCodeLocation.populateLiveDisplayLocationString(titleElement,"textContent");fragment.appendChild(titleElement);}else{cell.classList.add(WI.CallFrameView.FunctionIconStyleClassName);fragment.append(functionName);var subtitleElement=document.createElement("span");subtitleElement.classList.add("subtitle");callFrame.sourceCodeLocation.populateLiveDisplayLocationString(subtitleElement,"textContent");fragment.appendChild(subtitleElement);} return fragment;} fragment.append(iconElement,functionName);return fragment;} if(value instanceof WI.DOMNode){cell.classList.add(WI.DOMTreeElementPathComponent.iconClassNameForNode(value));return WI.linkifyNodeReference(value);} return super.createCellContent(columnIdentifier,cell);} generateIconTitle(columnIdentifier) {let value=this.data[columnIdentifier];if(value instanceof WI.SourceCodeLocation&&value.sourceCode instanceof WI.Resource&&value.sourceCode.responseSource===WI.Resource.ResponseSource.InspectorOverride) return WI.UIString("This resource was loaded from a local override");return super.generateIconTitle(columnIdentifier);} refresh() {this._cachedData=null;if(this._graphDataSource&&this._includesGraph) this.needsGraphRefresh();super.refresh();} refreshGraph() {if(!this._graphDataSource) return;if(this._scheduledGraphRefreshIdentifier){cancelAnimationFrame(this._scheduledGraphRefreshIdentifier);this._scheduledGraphRefreshIdentifier=undefined;} if(!this.revealed) return;let secondsPerPixel=this._graphDataSource.secondsPerPixel;if(isNaN(secondsPerPixel)) return;var recordBarIndex=0;function createBar(records,renderMode) {var timelineRecordBar=this._timelineRecordBars[recordBarIndex];if(!timelineRecordBar) timelineRecordBar=this._timelineRecordBars[recordBarIndex]=new WI.TimelineRecordBar(this,records,renderMode);else{timelineRecordBar.renderMode=renderMode;timelineRecordBar.records=records;} timelineRecordBar.refresh(this._graphDataSource);if(!timelineRecordBar.element.parentNode){this._graphContainerElement.appendChild(timelineRecordBar.element);this.didAddRecordBar(timelineRecordBar);} ++recordBarIndex;} function collectRecordsByType(records,recordsByTypeMap) {for(var record of records){var typedRecords=recordsByTypeMap.get(record.type);if(!typedRecords){typedRecords=[];recordsByTypeMap.set(record.type,typedRecords);} typedRecords.push(record);}} var boundCreateBar=createBar.bind(this);if(this.expanded){WI.TimelineRecordBar.createCombinedBars(this.records,secondsPerPixel,this._graphDataSource,boundCreateBar);}else{var recordTypeMap=new Map;collectRecordsByType(this.records,recordTypeMap);var childNode=this.children[0];while(childNode){if(childNode instanceof WI.TimelineDataGridNode) collectRecordsByType(childNode.records,recordTypeMap);childNode=childNode.traverseNextNode(false,this);} for(var records of recordTypeMap.values()) WI.TimelineRecordBar.createCombinedBars(records,secondsPerPixel,this._graphDataSource,boundCreateBar);} for(;recordBarIndexthis.graphDataSource.currentTime||record.startTime>this.graphDataSource.endTime) return false;return true;} filterableDataForColumn(columnIdentifier) {let value=this.data[columnIdentifier];if(value instanceof WI.SourceCodeLocation) return value.displayLocationString();if(value instanceof WI.CallFrame) return[value.functionName,value.sourceCodeLocation.displayLocationString()];return super.filterableDataForColumn(columnIdentifier);} didAddRecordBar(recordBar) {} didRemoveRecordBar(recordBar) {} didResizeColumn(columnIdentifier) {if(columnIdentifier!=="graph") return;this.needsGraphRefresh();}};WI.ContentBrowserTabContentView=class ContentBrowserTabContentView extends WI.TabContentView {constructor(tabInfo,{navigationSidebarPanelConstructor,detailsSidebarPanelConstructors,hideBackForwardButtons,disableBackForwardNavigation,flexibleNavigationItem}={}) {super(tabInfo,{navigationSidebarPanelConstructor,detailsSidebarPanelConstructors});const contentBrowserElement=null;const disableFindBanner=false;this._contentBrowser=new WI.ContentBrowser(contentBrowserElement,this,{hideBackForwardButtons,disableBackForwardNavigation,flexibleNavigationItem});this._ignoreNavigationSidebarPanelCollapsedEvent=false;this._ignoreDetailsSidebarPanelCollapsedEvent=false;this._ignoreDetailsSidebarPanelSelectedEvent=false;this._lastSelectedDetailsSidebarPanelSetting=new WI.Setting(this._identifier+"-last-selected-details-sidebar-panel",null);this._contentBrowser.addEventListener(WI.ContentBrowser.Event.CurrentRepresentedObjectsDidChange,this._contentBrowserCurrentRepresentedObjectsDidChange,this);this._contentBrowser.addEventListener(WI.ContentBrowser.Event.CurrentContentViewDidChange,this._contentBrowserCurrentContentViewDidChange,this);this._contentBrowser.updateHierarchicalPathForCurrentContentView();if(this._navigationSidebarPanelConstructor){let showToolTip=WI.UIString("Show the navigation sidebar (%s)").format(WI.navigationSidebarKeyboardShortcut.displayName);let hideToolTip=WI.UIString("Hide the navigation sidebar (%s)").format(WI.navigationSidebarKeyboardShortcut.displayName);let image=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"Images/ToggleRightSidebar.svg":"Images/ToggleLeftSidebar.svg";this._showNavigationSidebarItem=new WI.ActivateButtonNavigationItem("toggle-navigation-sidebar",showToolTip,hideToolTip,image,16,16);this._showNavigationSidebarItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI.toggleNavigationSidebar,this);this._showNavigationSidebarItem.activated=!WI.navigationSidebar.collapsed;this._showNavigationSidebarItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._contentBrowser.navigationBar.insertNavigationItem(this._showNavigationSidebarItem,0);this._contentBrowser.navigationBar.insertNavigationItem(new WI.DividerNavigationItem,1);WI.navigationSidebar.addEventListener(WI.Sidebar.Event.CollapsedStateDidChange,this._navigationSidebarCollapsedStateDidChange,this);} if(this._detailsSidebarPanelConstructors.length){let showToolTip=WI.UIString("Show the details sidebar (%s)").format(WI.detailsSidebarKeyboardShortcut.displayName);let hideToolTip=WI.UIString("Hide the details sidebar (%s)").format(WI.detailsSidebarKeyboardShortcut.displayName);this._showDetailsSidebarItem=new WI.ActivateButtonNavigationItem("toggle-details-sidebar",showToolTip,hideToolTip,"Images/ToggleRightSidebar.svg",16,16);this._showDetailsSidebarItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI.toggleDetailsSidebar,this);this._showDetailsSidebarItem.activated=!WI.detailsSidebar.collapsed;this._showDetailsSidebarItem.enabled=false;this._showDetailsSidebarItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._contentBrowser.navigationBar.addNavigationItem(new WI.DividerNavigationItem);this._contentBrowser.navigationBar.addNavigationItem(this._showDetailsSidebarItem);WI.detailsSidebar.addEventListener(WI.Sidebar.Event.PositionDidChange,this._detailsSidebarPositionDidChange,this);WI.detailsSidebar.addEventListener(WI.Sidebar.Event.CollapsedStateDidChange,this._detailsSidebarCollapsedStateDidChange,this);WI.detailsSidebar.addEventListener(WI.Sidebar.Event.SidebarPanelSelected,this._detailsSidebarPanelSelected,this);} this.element.classList.add("content-browser");this.addSubview(this._contentBrowser);} get contentBrowser() {return this._contentBrowser;} attached() {if(this.navigationSidebarPanel&&!this.navigationSidebarPanel.contentBrowser) this.navigationSidebarPanel.contentBrowser=this._contentBrowser;super.attached();} closed() {super.closed();if(this._navigationSidebarPanelConstructor) WI.navigationSidebar.removeEventListener(WI.Sidebar.Event.CollapsedStateDidChange,this._navigationSidebarCollapsedStateDidChange,this);if(this._detailsSidebarPanelConstructors.length){WI.detailsSidebar.removeEventListener(WI.Sidebar.Event.CollapsedStateDidChange,this._detailsSidebarCollapsedStateDidChange,this);WI.detailsSidebar.removeEventListener(WI.Sidebar.Event.SidebarPanelSelected,this._detailsSidebarPanelSelected,this);} if(this.navigationSidebarPanel&&typeof this.navigationSidebarPanel.closed==="function") this.navigationSidebarPanel.closed();this._contentBrowser.contentViewContainer.closeAllContentViews();} get managesDetailsSidebarPanels() {return true;} showNavigationSidebarPanel() {if(!this.isAttached) return;if(!this.navigationSidebarPanel) return;this._ignoreNavigationSidebarPanelCollapsedEvent=true;let currentRepresentedObjects=this._contentBrowser.currentRepresentedObjects;let shouldShowSidebar=currentRepresentedObjects.some((object)=>this.navigationSidebarPanel.canShowRepresentedObject(object));if(shouldShowSidebar){if(!this.navigationSidebarPanel.parentSidebar) WI.navigationSidebar.addSidebarPanel(this.navigationSidebarPanel);WI.navigationSidebar.collapsed=this.navigationSidebarCollapsedSetting.value;WI.navigationSidebar.selectedSidebarPanel=this.navigationSidebarPanel;}else{if(this.navigationSidebarPanel.parentSidebar) WI.navigationSidebar.removeSidebarPanel(this.navigationSidebarPanel);WI.navigationSidebar.collapsed=true;} this._ignoreNavigationSidebarPanelCollapsedEvent=false;this._showNavigationSidebarItem.enabled=!!this.navigationSidebarPanel.parentSidebar;} showDetailsSidebarPanels() {if(!this.isAttached) return;var currentRepresentedObjects=this._contentBrowser.currentRepresentedObjects;var wasSidebarEmpty=!WI.detailsSidebar.sidebarPanels.length; this._ignoreDetailsSidebarPanelSelectedEvent=true;this._ignoreDetailsSidebarPanelCollapsedEvent=true;let hiddenSidebarPanels=0;let sidebarPanelToSelect=null;for(var i=0;i=WI.FolderizedTreeElement.LargeChildCountThreshold){if(numberOfSmallCategories||numberOfMediumCategories) return true;foundLargeCategory=true;return false;} if(childCount>=WI.FolderizedTreeElement.MediumChildCountThreshold){return++numberOfMediumCategories>=WI.FolderizedTreeElement.NumberOfMediumCategoriesThreshold;} ++numberOfSmallCategories;return false;} for(var settings of this._folderizeSettingsMap.values()){if(pushCategory(settings.representedObject.size)) return true;} return false;}};WI.FolderizedTreeElement.MediumChildCountThreshold=5;WI.FolderizedTreeElement.LargeChildCountThreshold=15;WI.FolderizedTreeElement.NumberOfMediumCategoriesThreshold=2;WI.FolderizedTreeElement.NewChildQueueUpdateInterval=500;WI.NetworkDetailView=class NetworkDetailView extends WI.View {constructor(representedObject,delegate) {super();this._representedObject=representedObject;this._delegate=delegate||null;this.element.classList.add("network-detail");this._contentBrowser=null;this._detailNavigationItemMap=new Map;this._contentViewCookie=null;} get representedObject(){return this._representedObject;} attached() {super.attached();if(!this._contentBrowser) return;this._showPreferredContentView();if(this._contentViewCookie){this._contentBrowser.showContentView(this._contentBrowser.currentContentView,this._contentViewCookie);this._contentViewCookie=null;}} dispose() {this._delegate=null;this._contentBrowser.contentViewContainer.closeAllContentViews();} willShowWithCookie(cookie) {this._contentViewCookie=cookie;} initialLayout() {let closeNavigationItem=new WI.ButtonNavigationItem("close",WI.UIString("Close detail view"),"Images/CloseLarge.svg",16,16);closeNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleCloseButton,this);closeNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;let contentViewNavigationItemGroup=new WI.GroupNavigationItem;let flexibleNavigationItem=new WI.FlexibleSpaceNavigationItem(contentViewNavigationItemGroup,WI.FlexibleSpaceNavigationItem.Align.End);flexibleNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;const element=null;this._contentBrowser=new WI.ContentBrowser(element,this,{hideBackForwardButtons:true,flexibleNavigationItem,contentViewNavigationItemGroup});this._contentBrowser.addEventListener(WI.ContentBrowser.Event.CurrentContentViewDidChange,this._handleCurrentContentViewDidChange,this);let index=0;this._contentBrowser.navigationBar.insertNavigationItem(closeNavigationItem,index++);for(let detailNavigationItem of this._detailNavigationItemMap.values()) this._contentBrowser.navigationBar.insertNavigationItem(detailNavigationItem,index++);this._contentBrowser.navigationBar.addEventListener(WI.NavigationBar.Event.NavigationItemSelected,this._navigationItemSelected,this);this.addSubview(this._contentBrowser);this._showPreferredContentView();} createDetailNavigationItem(identifier,toolTip) {this._detailNavigationItemMap.set(identifier,new WI.RadioButtonNavigationItem(identifier,toolTip));} detailNavigationItemForIdentifier(identifier) {return this._detailNavigationItemMap.get(identifier);} showContentViewForIdentifier(identifier) {} _showPreferredContentView() {let detailNavigationItems=Array.from(this._detailNavigationItemMap.values());let firstNavigationItem=null;let defaultIdentifier=WI.settings.selectedNetworkDetailContentViewIdentifier.value;for(let navigationItem of this._contentBrowser.navigationBar.navigationItems){if(!(navigationItem instanceof WI.RadioButtonNavigationItem)) continue;if(!detailNavigationItems.includes(navigationItem)) continue;if(!firstNavigationItem) firstNavigationItem=navigationItem;if(navigationItem.identifier===defaultIdentifier){this._contentBrowser.navigationBar.selectedNavigationItem=navigationItem;return;}} this._contentBrowser.navigationBar.selectedNavigationItem=firstNavigationItem;} _handleCurrentContentViewDidChange(event) {this.dispatchEventToListeners(event.type,event.data);} _navigationItemSelected(event) {let navigationItem=event.target.selectedNavigationItem;if(!(navigationItem instanceof WI.RadioButtonNavigationItem)) return;this.showContentViewForIdentifier(navigationItem.identifier);WI.settings.selectedNetworkDetailContentViewIdentifier.value=navigationItem.identifier;} _handleCloseButton(event) {if(this._delegate&&this._delegate.networkDetailViewClose) this._delegate.networkDetailViewClose(this);}};WI.NetworkTabContentView=class NetworkTabContentView extends WI.TabContentView {constructor() {super(NetworkTabContentView.tabInfo());this._networkTableContentView=new WI.NetworkTableContentView;this._contentBrowser=new WI.ContentBrowser(null,this,{hideBackForwardButtons:true,disableFindBanner:true});this._contentBrowser.showContentView(this._networkTableContentView);let filterNavigationItems=this._networkTableContentView.filterNavigationItems;for(let i=0;ithis._networkTableContentView.processHAR(result));} _handleEmulatedConditionChanged(event) {let hasEmulatedCondition=WI.networkManager.emulatedCondition!==WI.NetworkManager.EmulatedCondition.None;this.tabBarItem.image=hasEmulatedCondition?"Images/Warning.svg":"Images/Network.svg";this.tabBarItem.title=hasEmulatedCondition?WI.UIString("Network throttling is enabled"):"";}};WI.NetworkTabContentView.Type="network";WI.ObjectTreeBaseTreeElement=class ObjectTreeBaseTreeElement extends WI.GeneralTreeElement {constructor(representedObject,propertyPath,property) {const classNames=null;const title=null;const subtitle=null;super(classNames,title,subtitle,representedObject);this._property=property;this._propertyPath=propertyPath;this.toggleOnClick=true;this.selectable=false;this.tooltipHandledSeparately=true;} get property() {return this._property;} get propertyPath() {return this._propertyPath;} resolvedValue() {if(this._getterValue) return this._getterValue;if(this._property.hasValue()) return this._property.value;return null;} resolvedValuePropertyPath() {if(this._getterValue) return this._propertyPath.appendPropertyDescriptor(this._getterValue,this._property,WI.PropertyPath.Type.Value);if(this._property.hasValue()) return this._propertyPath.appendPropertyDescriptor(this._property.value,this._property,WI.PropertyPath.Type.Value);return null;} thisPropertyPath() {return this._propertyPath.appendPropertyDescriptor(null,this._property,this.propertyPathType());} hadError() {return this._property.wasThrown||this._getterHadError;} propertyPathType() {if(this._getterValue||this._property.hasValue()) return WI.PropertyPath.Type.Value;if(this._property.hasGetter()) return WI.PropertyPath.Type.Getter;if(this._property.hasSetter()) return WI.PropertyPath.Type.Setter;return WI.PropertyPath.Type.Value;} propertyPathString(propertyPath) {if(propertyPath.isFullPathImpossible()) return WI.UIString("Unable to determine path to property from root");return propertyPath.displayPath(this.propertyPathType());} createGetterElement(interactive) {var getterElement=document.createElement("img");getterElement.className="getter";if(!interactive){getterElement.classList.add("disabled");getterElement.title=WI.UIString("Getter");return getterElement;} getterElement.title=WI.UIString("Invoke getter");getterElement.addEventListener("click",(event)=>{event.stopPropagation();var lastNonPrototypeObject=this._propertyPath.lastNonPrototypeObject;var getterObject=this._property.get;lastNonPrototypeObject.invokeGetter(getterObject,(error,result,wasThrown)=>{this._getterHadError=!!(error||wasThrown);this._getterValue=result;if(this.invokedGetter&&typeof this.invokedGetter==="function") this.invokedGetter();});});return getterElement;} createSetterElement(interactive) {var setterElement=document.createElement("img");setterElement.className="setter";setterElement.title=WI.UIString("Setter");if(!interactive) setterElement.classList.add("disabled");return setterElement;} populateContextMenu(contextMenu,event) {if(event.__addedObjectPreviewContextMenuItems) return;if(event.__addedObjectTreeContextMenuItems) return;event.__addedObjectTreeContextMenuItems=true;if(typeof this.treeOutline.objectTreeElementAddContextMenuItems==="function"){this.treeOutline.objectTreeElementAddContextMenuItems(this,contextMenu);if(!contextMenu.isEmpty()) contextMenu.appendSeparator();} let resolvedValue=this.resolvedValue();if(!resolvedValue) return;if(this._property&&this._property.symbol) contextMenu.appendItem(WI.UIString("Log Symbol"),this._logSymbolProperty.bind(this));contextMenu.appendItem(WI.UIString("Log Value"),this._logValue.bind(this));let propertyPath=this.resolvedValuePropertyPath();if(propertyPath&&!propertyPath.isFullPathImpossible()){contextMenu.appendItem(WI.UIString("Copy Path to Property"),()=>{InspectorFrontendHost.copyText(propertyPath.displayPath(WI.PropertyPath.Type.Value));});} contextMenu.appendSeparator();this._appendMenusItemsForObject(contextMenu,resolvedValue);super.populateContextMenu(contextMenu,event);} _logSymbolProperty() {var symbol=this._property.symbol;if(!symbol) return;var text=WI.UIString("Selected Symbol");WI.consoleLogViewController.appendImmediateExecutionWithResult(text,symbol,{addSpecialUserLogClass:true,shouldRevealConsole:true});} _logValue(value) {var resolvedValue=value||this.resolvedValue();if(!resolvedValue) return;var propertyPath=this.resolvedValuePropertyPath();var isImpossible=propertyPath.isFullPathImpossible();var text=isImpossible?WI.UIString("Selected Value"):propertyPath.displayPath(this.propertyPathType());if(!isImpossible) WI.quickConsole.prompt.pushHistoryItem(text);WI.consoleLogViewController.appendImmediateExecutionWithResult(text,resolvedValue,{addSpecialUserLogClass:isImpossible,shouldRevealConsole:true});} _appendMenusItemsForObject(contextMenu,resolvedValue) {if(resolvedValue.type==="function"){if(!isFunctionStringNativeCode(resolvedValue.description)){contextMenu.appendItem(WI.UIString("Jump to Definition"),function(){resolvedValue.target.DebuggerAgent.getFunctionDetails(resolvedValue.objectId,function(error,response){if(error) return;let location=response.location;let sourceCode=WI.debuggerManager.scriptForIdentifier(location.scriptId,resolvedValue.target);if(!sourceCode) return;let sourceCodeLocation=sourceCode.createSourceCodeLocation(location.lineNumber,location.columnNumber||0);const options={ignoreNetworkTab:true,ignoreSearchTab:true,};WI.showSourceCodeLocation(sourceCodeLocation,options);});});} return;}}};WI.SourceCodeTreeElement=class SourceCodeTreeElement extends WI.FolderizedTreeElement {constructor(sourceCode,classNames,title,subtitle,representedObject) {super(classNames,title,subtitle,representedObject||sourceCode);this._updateSourceCode(sourceCode);} updateSourceMapResources() {if(!this.treeOutline||!this.treeOutline.includeSourceMapResourceChildren) return;this.hasChildren=!!this._sourceCode.sourceMaps.length;this.shouldRefreshChildren=this.hasChildren;if(!this.hasChildren) this.removeChildren();} onattach() {super.onattach();this.updateSourceMapResources();} onpopulate() {if(!this.treeOutline||!this.treeOutline.includeSourceMapResourceChildren) return;if(!this.hasChildren||!this.shouldRefreshChildren) return;this.shouldRefreshChildren=false;this.removeChildren();function combineFolderChain(topFolder,bottomFolder) {var components=[];for(var currentFolder=bottomFolder;currentFolder!==topFolder;currentFolder=currentFolder.parent) components.push(currentFolder.mainTitle);components.push(topFolder.mainTitle);var folderName=components.reverse().join("/");var newFolder=new WI.FolderTreeElement(folderName);var folderIndex=topFolder.parent.children.indexOf(topFolder);topFolder.parent.insertChild(newFolder,folderIndex);topFolder.parent.removeChild(topFolder);var children=bottomFolder.children;bottomFolder.removeChildren();for(var i=0;i=Math.abs(event.deltaY)*0.5){let newWheelEvent=new event.constructor(event.type,event);newWheelEvent.__cloned=true;this._scrollContainerElement.dispatchEvent(newWheelEvent);return;} let mouseOffset=event.pageX-this._graphsContainerView.element.totalOffsetLeft;let mousePositionTime=this._currentSettings.scrollStartTime+(mouseOffset*this.secondsPerPixel);let deviceDirection=event.webkitDirectionInvertedFromDevice?1:-1;let delta=event.deltaY*(this.secondsPerPixel/WI.TimelineOverview.ScrollDeltaDenominator)*deviceDirection;if(this._pixelAlignDuration&&(delta<0&&this._mouseWheelDelta>=0||delta>=0&&this._mouseWheelDelta<0)) this._mouseWheelDelta=0;let previousDurationPerPixel=this.secondsPerPixel;this._mouseWheelDelta+=delta;this.secondsPerPixel+=this._mouseWheelDelta;if(this.secondsPerPixel===this._currentSettings.minimumDurationPerPixel&&delta<0||this.secondsPerPixel===this._currentSettings.maximumDurationPerPixel&&delta>=0) this._mouseWheelDelta=0;else this._mouseWheelDelta=previousDurationPerPixel+this._mouseWheelDelta-this.secondsPerPixel;this.scrollStartTime=mousePositionTime-(mouseOffset*this.secondsPerPixel);this.element.classList.toggle("has-scrollbar",this._scrollContainerElement.clientHeight<=1);event.preventDefault();event.stopPropagation();} _handleGestureStart(event) {if(this._handlingGesture){ return;} let mouseOffset=event.pageX-this._graphsContainerView.element.totalOffsetLeft;let mousePositionTime=this._currentSettings.scrollStartTime+(mouseOffset*this.secondsPerPixel);this._handlingGesture=true;this._gestureStartStartTime=mousePositionTime;this._gestureStartDurationPerPixel=this.secondsPerPixel;this.element.classList.toggle("has-scrollbar",this._scrollContainerElement.clientHeight<=1);event.preventDefault();event.stopPropagation();} _handleGestureChange(event) {let scale=Math.max(1/5,event.scale);let mouseOffset=event.pageX-this._graphsContainerView.element.totalOffsetLeft;let newSecondsPerPixel=this._gestureStartDurationPerPixel/scale;this.secondsPerPixel=newSecondsPerPixel;this.scrollStartTime=this._gestureStartStartTime-(mouseOffset*this.secondsPerPixel);event.preventDefault();event.stopPropagation();} _handleGestureEnd(event) {this._handlingGesture=false;this._gestureStartStartTime=NaN;this._gestureStartDurationPerPixel=NaN;} _instrumentAdded(instrumentOrEvent) {let instrument=instrumentOrEvent instanceof WI.Instrument?instrumentOrEvent:instrumentOrEvent.data.instrument;let timeline=this._recording.timelineForInstrument(instrument);let treeElement=new WI.TimelineTreeElement(timeline);let insertionIndex=insertionIndexForObjectInListSortedByFunction(treeElement,this._timelinesTreeOutline.children,this._compareTimelineTreeElements.bind(this));this._timelinesTreeOutline.insertChild(treeElement,insertionIndex);this._treeElementsByTypeMap.set(timeline.type,treeElement);let overviewGraph=WI.TimelineOverviewGraph.createForTimeline(timeline,this);overviewGraph.addEventListener(WI.TimelineOverviewGraph.Event.RecordSelected,this._handleOverviewGraphRecordSelected,this);this._overviewGraphsByTypeMap.set(timeline.type,overviewGraph);this._graphsContainerView.insertSubviewBefore(overviewGraph,this._graphsContainerView.subviews[insertionIndex]);treeElement.element.style.height=overviewGraph.height+"px";if(!this._canShowTimelineType(timeline.type)){overviewGraph.hidden=true;treeElement.hidden=true;} this.needsLayout();} _instrumentRemoved(event) {let instrument=event.data.instrument;let timeline=this._recording.timelineForInstrument(instrument);let overviewGraph=this._overviewGraphsByTypeMap.get(timeline.type);let treeElement=this._treeElementsByTypeMap.get(timeline.type);let shouldSuppressOnDeselect=false;let shouldSuppressSelectSibling=true;this._timelinesTreeOutline.removeChild(treeElement,shouldSuppressOnDeselect,shouldSuppressSelectSibling);overviewGraph.removeEventListener(WI.TimelineOverviewGraph.Event.RecordSelected,this._handleOverviewGraphRecordSelected,this);this._graphsContainerView.removeSubview(overviewGraph);this._overviewGraphsByTypeMap.delete(timeline.type);this._treeElementsByTypeMap.delete(timeline.type);} _markerAdded(event) {this._timelineRuler.addMarker(event.data.marker);} _handleGraphsContainerClick(event) {if(event.__timelineRecordClickEventHandled) return;this._recordSelected(null,null);} _timelineRulerMouseDown(event) {this._timelineRulerSelectionChanged=false;} _timelineRulerMouseClicked(event) {if(this._timelineRulerSelectionChanged) return;for(let overviewGraph of this._overviewGraphsByTypeMap.values()){if(overviewGraph.hidden) continue;let graphRect=overviewGraph.element.getBoundingClientRect();if(!(event.pageX>=graphRect.left&&event.pageX<=graphRect.right&&event.pageY>=graphRect.top&&event.pageY<=graphRect.bottom)) continue;let newClickEvent=new event.constructor(event.type,event);overviewGraph.element.dispatchEvent(newClickEvent);return;}} _timeRangeSelectionChanged(event) {this._timelineRulerSelectionChanged=true;let startTime=this._viewMode===WI.TimelineOverview.ViewMode.Timelines?this._startTime:0;this._currentSettings.selectionStartValueSetting.value=this.selectionStartTime-startTime;this._currentSettings.selectionDurationSetting.value=this.selectionDuration;this.dispatchEventToListeners(WI.TimelineOverview.Event.TimeRangeSelectionChanged);} _handleOverviewGraphRecordSelected(event) {let{record,recordBar}=event.data;if(!record) return;this._recordSelected(record,recordBar);} _recordSelected(record,recordBar) {if(record===this._selectedTimelineRecord) return;if(this._selectedTimelineRecord&&(!record||this._selectedTimelineRecord.type!==record.type)){let timelineOverviewGraph=this._overviewGraphsByTypeMap.get(this._selectedTimelineRecord.type);if(timelineOverviewGraph) timelineOverviewGraph.selectedRecord=null;} this._selectedTimelineRecord=record;if(this._selectedTimelineRecord){let firstRecord=this._selectedTimelineRecord;let lastRecord=this._selectedTimelineRecord;if(recordBar){firstRecord=recordBar.records[0];lastRecord=recordBar.records.lastValue;} let startTime=firstRecord instanceof WI.RenderingFrameTimelineRecord?firstRecord.frameIndex:firstRecord.startTime;let endTime=lastRecord instanceof WI.RenderingFrameTimelineRecord?lastRecord.frameIndex:lastRecord.endTime;if(startTimethis.selectionStartTime+this.selectionDuration)||firstRecord instanceof WI.CPUTimelineRecord){let selectionPadding=this.secondsPerPixel*10;this.selectionStartTime=startTime-selectionPadding;this.selectionDuration=endTime-startTime+(selectionPadding*2);}} this.dispatchEventToListeners(WI.TimelineOverview.Event.RecordSelected,{record:this._selectedTimelineRecord});} _resetSelection() {function reset(settings) {settings.durationPerPixelSetting.reset();settings.selectionStartValueSetting.reset();settings.selectionDurationSetting.reset();} reset(this._timelinesViewModeSettings);if(this._renderingFramesViewModeSettings) reset(this._renderingFramesViewModeSettings);this.secondsPerPixel=this._currentSettings.durationPerPixelSetting.value;this.selectionStartTime=this._currentSettings.selectionStartValueSetting.value;this.selectionDuration=this._currentSettings.selectionDurationSetting.value;} _recordingReset(event) {this._timelineRuler.clearMarkers();this._timelineRuler.addMarker(this._currentTimeMarker);} _canShowTimelineType(type) {let timelineViewMode=WI.TimelineOverview.ViewMode.Timelines;if(type===WI.TimelineRecord.Type.RenderingFrame) timelineViewMode=WI.TimelineOverview.ViewMode.RenderingFrames;return timelineViewMode===this._viewMode;} _viewModeDidChange() {this._stopEditingInstruments();let startTime=0;let isRenderingFramesMode=this._viewMode===WI.TimelineOverview.ViewMode.RenderingFrames;if(isRenderingFramesMode){this._timelineRuler.minimumSelectionDuration=1;this._timelineRuler.snapInterval=1;this._timelineRuler.formatLabelCallback=(value)=>value.maxDecimals(0).toLocaleString();}else{this._timelineRuler.minimumSelectionDuration=0.01;this._timelineRuler.snapInterval=NaN;this._timelineRuler.formatLabelCallback=null;startTime=this._startTime;} this.pixelAlignDuration=isRenderingFramesMode;this.selectionStartTime=this._currentSettings.selectionStartValueSetting.value+startTime;this.selectionDuration=this._currentSettings.selectionDurationSetting.value;for(let[type,overviewGraph]of this._overviewGraphsByTypeMap){let treeElement=this._treeElementsByTypeMap.get(type);let hidden=!this._canShowTimelineType(type);treeElement.hidden=hidden;overviewGraph.hidden=hidden;} this.element.classList.toggle("frames",isRenderingFramesMode);if(this.didInitialLayout) this.updateLayout(WI.View.LayoutReason.Resize);} _createViewModeSettings(viewMode,minimumDurationPerPixel,maximumDurationPerPixel,durationPerPixel,selectionStartValue,selectionDuration) {durationPerPixel=Math.min(maximumDurationPerPixel,Math.max(minimumDurationPerPixel,durationPerPixel));let durationPerPixelSetting=new WI.Setting(viewMode+"-duration-per-pixel",durationPerPixel);let selectionStartValueSetting=new WI.Setting(viewMode+"-selection-start-value",selectionStartValue);let selectionDurationSetting=new WI.Setting(viewMode+"-selection-duration",selectionDuration);return{scrollStartTime:0,minimumDurationPerPixel,maximumDurationPerPixel,durationPerPixelSetting,selectionStartValueSetting,selectionDurationSetting};} get _currentSettings() {return this._viewMode===WI.TimelineOverview.ViewMode.Timelines?this._timelinesViewModeSettings:this._renderingFramesViewModeSettings;} _timelinesTreeSelectionDidChange(event) {let timeline=null;let selectedTreeElement=this._timelinesTreeOutline.selectedTreeElement;if(selectedTreeElement){timeline=selectedTreeElement.representedObject;for(let[type,overviewGraph]of this._overviewGraphsByTypeMap) overviewGraph.selected=type===timeline.type;} this._selectedTimeline=timeline;this.dispatchEventToListeners(WI.TimelineOverview.Event.TimelineSelected);} _toggleEditingInstruments(event) {if(this._editingInstruments) this._stopEditingInstruments();else this._startEditingInstruments();} _editingInstrumentsDidChange() {this.element.classList.toggle(WI.TimelineOverview.EditInstrumentsStyleClassName,this._editingInstruments);this._timelineRuler.enabled=!this._editingInstruments;this._updateWheelAndGestureHandlers();this._updateEditInstrumentsButton();this.dispatchEventToListeners(WI.TimelineOverview.Event.EditingInstrumentsDidChange);} _updateEditInstrumentsButton() {let newLabel=this._editingInstruments?WI.UIString("Done"):WI.UIString("Edit");this._editInstrumentsButton.label=newLabel;this._editInstrumentsButton.activated=this._editingInstruments;this._editInstrumentsButton.enabled=!WI.timelineManager.isCapturing();} _updateWheelAndGestureHandlers() {if(this._editingInstruments){this.element.removeEventListener("wheel",this._handleWheelEventListener);this.element.removeEventListener("gesturestart",this._handleGestureStartEventListener);this.element.removeEventListener("gesturechange",this._handleGestureChangeEventListener);this.element.removeEventListener("gestureend",this._handleGestureEndEventListener);this._handleWheelEventListener=null;this._handleGestureStartEventListener=null;this._handleGestureChangeEventListener=null;this._handleGestureEndEventListener=null;}else{this._handleWheelEventListener=this._handleWheelEvent.bind(this);this._handleGestureStartEventListener=this._handleGestureStart.bind(this);this._handleGestureChangeEventListener=this._handleGestureChange.bind(this);this._handleGestureEndEventListener=this._handleGestureEnd.bind(this);this.element.addEventListener("wheel",this._handleWheelEventListener);this.element.addEventListener("gesturestart",this._handleGestureStartEventListener);this.element.addEventListener("gesturechange",this._handleGestureChangeEventListener);this.element.addEventListener("gestureend",this._handleGestureEndEventListener);}} _startEditingInstruments() {if(this._editingInstruments) return;this._editingInstruments=true;for(let type of this._instrumentTypes){let treeElement=this._treeElementsByTypeMap.get(type);if(!treeElement){let timeline=this._recording.timelines.get(type);const placeholder=true;treeElement=new WI.TimelineTreeElement(timeline,placeholder);let insertionIndex=insertionIndexForObjectInListSortedByFunction(treeElement,this._timelinesTreeOutline.children,this._compareTimelineTreeElements.bind(this));this._timelinesTreeOutline.insertChild(treeElement,insertionIndex);let placeholderGraph=new WI.View;placeholderGraph.element.classList.add("timeline-overview-graph");treeElement[WI.TimelineOverview.PlaceholderOverviewGraph]=placeholderGraph;this._graphsContainerView.insertSubviewBefore(placeholderGraph,this._graphsContainerView.subviews[insertionIndex]);} treeElement.editing=true;treeElement.addEventListener(WI.TimelineTreeElement.Event.EnabledDidChange,this._timelineTreeElementEnabledDidChange,this);} this._editingInstrumentsDidChange();} _stopEditingInstruments() {if(!this._editingInstruments) return;this._editingInstruments=false;let instruments=this._recording.instruments;for(let treeElement of this._treeElementsByTypeMap.values()){if(treeElement.status.checked){treeElement.editing=false;treeElement.removeEventListener(WI.TimelineTreeElement.Event.EnabledDidChange,this._timelineTreeElementEnabledDidChange,this);continue;} let timelineInstrument=instruments.find((instrument)=>instrument.timelineRecordType===treeElement.representedObject.type);this._recording.removeInstrument(timelineInstrument);} let placeholderTreeElements=this._timelinesTreeOutline.children.filter((treeElement)=>treeElement.placeholder);for(let treeElement of placeholderTreeElements){this._timelinesTreeOutline.removeChild(treeElement);let placeholderGraph=treeElement[WI.TimelineOverview.PlaceholderOverviewGraph];this._graphsContainerView.removeSubview(placeholderGraph);if(treeElement.status.checked){let instrument=WI.Instrument.createForTimelineType(treeElement.representedObject.type);this._recording.addInstrument(instrument);}} let instrumentTypes=instruments.map((instrument)=>instrument.timelineRecordType);WI.timelineManager.enabledTimelineTypes=instrumentTypes;this._editingInstrumentsDidChange();} _handleTimelineCapturingStateChanged(event) {switch(WI.timelineManager.capturingState){case WI.TimelineManager.CapturingState.Active:this._editInstrumentsButton.enabled=false;this._stopEditingInstruments();break;case WI.TimelineManager.CapturingState.Inactive:this._editInstrumentsButton.enabled=true;break;}} _recordingImported(event) {let{overviewData}=event.data;if(overviewData.secondsPerPixel!==undefined) this.secondsPerPixel=overviewData.secondsPerPixel;if(overviewData.scrollStartTime!==undefined) this.scrollStartTime=overviewData.scrollStartTime;if(overviewData.selectionStartTime!==undefined) this.selectionStartTime=overviewData.selectionStartTime;if(overviewData.selectionDuration!==undefined){if(overviewData.selectionDuration===Number.MAX_VALUE) this._timelineRuler.selectEntireRange();else this.selectionDuration=overviewData.selectionDuration;} if(overviewData.selectedTimelineType!==undefined){let timeline=this._recording.timelineForRecordType(overviewData.selectedTimelineType);if(timeline) this.selectedTimeline=timeline;}} _compareTimelineTreeElements(a,b) {let aTimelineType=a.representedObject.type;let bTimelineType=b.representedObject.type;if(aTimelineType===WI.TimelineRecord.Type.RenderingFrame) return 1;if(bTimelineType===WI.TimelineRecord.Type.RenderingFrame) return-1;if(a.placeholder!==b.placeholder) return a.placeholder?1:-1;let aTimelineIndex=this._instrumentTypes.indexOf(aTimelineType);let bTimelineIndex=this._instrumentTypes.indexOf(bTimelineType);return aTimelineIndex-bTimelineIndex;} _timelineTreeElementEnabledDidChange(event) {let enabled=this._timelinesTreeOutline.children.some((treeElement)=>{let timelineType=treeElement.representedObject.type;return this._canShowTimelineType(timelineType)&&treeElement.status.checked;});this._editInstrumentsButton.enabled=enabled;}};WI.TimelineOverview.PlaceholderOverviewGraph=Symbol("placeholder-overview-graph");WI.TimelineOverview.ScrollDeltaDenominator=500;WI.TimelineOverview.EditInstrumentsStyleClassName="edit-instruments";WI.TimelineOverview.MinimumDurationPerPixel=0.0001;WI.TimelineOverview.MaximumDurationPerPixel=60;WI.TimelineOverview.ViewMode={Timelines:"timeline-overview-view-mode-timelines",RenderingFrames:"timeline-overview-view-mode-rendering-frames"};WI.TimelineOverview.Event={EditingInstrumentsDidChange:"editing-instruments-did-change",RecordSelected:"timeline-overview-record-selected",TimelineSelected:"timeline-overview-timeline-selected",TimeRangeSelectionChanged:"timeline-overview-time-range-selection-changed"};WI.TimelineRecordTreeElement=class TimelineRecordTreeElement extends WI.GeneralTreeElement {constructor(timelineRecord,subtitleNameStyle,includeDetailsInMainTitle,sourceCodeLocation,representedObject) {sourceCodeLocation=sourceCodeLocation||timelineRecord.sourceCodeLocation||null;let alternateSubtitle=null;if(includeDetailsInMainTitle&&timelineRecord.type===WI.TimelineRecord.Type.Script&&timelineRecord.eventType===WI.ScriptTimelineRecord.EventType.TimerInstalled){let timeoutString=Number.secondsToString(timelineRecord.details.timeout/1000);alternateSubtitle=document.createElement("span");alternateSubtitle.classList.add("alternate-subtitle");if(timelineRecord.details.repeating) alternateSubtitle.textContent=WI.UIString("%s interval").format(timeoutString);else alternateSubtitle.textContent=WI.UIString("%s delay").format(timeoutString);} let subtitle=null;if(sourceCodeLocation){subtitle=document.createElement("span");if(subtitleNameStyle!==WI.SourceCodeLocation.NameStyle.None) sourceCodeLocation.populateLiveDisplayLocationString(subtitle,"textContent",null,subtitleNameStyle);else sourceCodeLocation.populateLiveDisplayLocationString(subtitle,"textContent",null,WI.SourceCodeLocation.NameStyle.None,WI.UIString("line "));} let iconStyleClass=WI.TimelineTabContentView.iconClassNameForRecord(timelineRecord);let title=WI.TimelineTabContentView.displayNameForRecord(timelineRecord);super([iconStyleClass],title,subtitle,representedObject||timelineRecord);this._record=timelineRecord;this._sourceCodeLocation=sourceCodeLocation;if(this._sourceCodeLocation) this.tooltipHandledSeparately=true;if(alternateSubtitle) this.titlesElement.appendChild(alternateSubtitle);} get record() {return this._record;} get filterableData() {var url=this._sourceCodeLocation?this._sourceCodeLocation.sourceCode.url:"";return{text:[this.mainTitle,url||"",this._record.details||""]};} get sourceCodeLocation() {return this._sourceCodeLocation;} onattach() {super.onattach();if(!this.tooltipHandledSeparately) return;var tooltipPrefix=this.mainTitle+"\n";this._sourceCodeLocation.populateLiveDisplayLocationTooltip(this.element,tooltipPrefix);}};WI.TimelineRecordTreeElement.StyleRecordIconStyleClass="style-record";WI.TimelineRecordTreeElement.LayoutRecordIconStyleClass="layout-record";WI.TimelineRecordTreeElement.PaintRecordIconStyleClass="paint-record";WI.TimelineRecordTreeElement.CompositeRecordIconStyleClass="composite-record";WI.TimelineRecordTreeElement.RenderingFrameRecordIconStyleClass="rendering-frame-record";WI.TimelineRecordTreeElement.APIRecordIconStyleClass="api-record";WI.TimelineRecordTreeElement.EvaluatedRecordIconStyleClass="evaluated-record";WI.TimelineRecordTreeElement.EventRecordIconStyleClass="event-record";WI.TimelineRecordTreeElement.TimerRecordIconStyleClass="timer-record";WI.TimelineRecordTreeElement.ProbeRecordIconStyleClass="probe-record";WI.TimelineRecordTreeElement.ConsoleProfileIconStyleClass="console-profile-record";WI.TimelineRecordTreeElement.GarbageCollectionIconStyleClass="garbage-collection-profile-record";WI.TimelineTreeElement=class TimelineTreeElement extends WI.GeneralTreeElement {constructor(timeline,placeholder) {let displayName=WI.TimelineTabContentView.displayNameForTimelineType(timeline.type);let iconClassName=WI.TimelineTabContentView.iconClassNameForTimelineType(timeline.type);let genericClassName=WI.TimelineTabContentView.genericClassNameForTimelineType(timeline.type);super([iconClassName,genericClassName],displayName,"",timeline);this._placeholder=placeholder||false;this.editing=this._placeholder;this.tooltipHandledSeparately=true;} get placeholder() {return this._placeholder;} get editing() {return this._editing;} set editing(x) {if(this._editing===x) return;this._editing=x;this.selectable=!this._editing;this._updateStatusButton();} onattach() {super.onattach();this.listItemElement.addEventListener("click",this._clickHandler.bind(this));} _showCloseButton() {let tooltip=WI.UIString("Close %s timeline view").format(this.mainTitle);let button=new WI.TreeElementStatusButton(WI.ImageUtilities.useSVGSymbol("Images/CloseLarge.svg","close-button",tooltip));button.addEventListener(WI.TreeElementStatusButton.Event.Clicked,function(event){this.deselect();},this);this.status=button.element;} _showCheckbox() {let checkboxElement=document.createElement("input");checkboxElement.type="checkbox";checkboxElement.checked=!this._placeholder;let button=new WI.TreeElementStatusButton(checkboxElement);checkboxElement.addEventListener("change",()=>{this._dispatchEnabledDidChangeEvent();});this.status=checkboxElement;} _updateStatusButton() {if(this._editing) this._showCheckbox();else this._showCloseButton();} _clickHandler() {if(!this._editing) return;this.status.checked=!this.status.checked;this._dispatchEnabledDidChangeEvent();} _dispatchEnabledDidChangeEvent() {this.dispatchEventToListeners(WI.TimelineTreeElement.Event.EnabledDidChange);}};WI.TimelineTreeElement.Event={EnabledDidChange:"timeline-tree-element-enabled-did-change"};WI.GeneralStyleDetailsSidebarPanel=class GeneralStyleDetailsSidebarPanel extends WI.DOMDetailsSidebarPanel {constructor(identifier,displayName,panelConstructor) {super(identifier,displayName);this.element.classList.add("css-style");this._panel=new panelConstructor(this);this._panel.addEventListener(WI.StyleDetailsPanel.Event.NodeChanged,this._handleNodeChanged,this);if(this._panel.supportsToggleCSSClassList&&InspectorBackend.hasCommand("DOM.resolveNode")) this._classListContainerToggledSetting=new WI.Setting(identifier+"-class-list-container-toggled",!!WI.Setting.migrateValue("class-list-container-toggled"));if(this._panel.supportsToggleCSSForcedPseudoClass&&WI.cssManager.canForcePseudoClass()){this._forcedPseudoClassContainerToggledSetting=new WI.Setting(identifier+"-forced-pseudo-class-container-toggled",this._panel.initialToggleCSSForcedPseudoClassState);this._checkboxForForcedPseudoClass=new Map;}} get panel(){return this._panel;} get minimumWidth() {return Math.max(super.minimumWidth,this._panel.minimumWidth||0);} supportsDOMNode(nodeToInspect) {return nodeToInspect.nodeType()===Node.ELEMENT_NODE;} attached() {super.attached();if(!this._panel) return;this._panel.markAsNeedsRefresh(this.domNode);} styleDetailsPanelFocusFilterBar(styleDetailsPanel) {if(this._filterBar) this._filterBar.inputField.focus();} layout() {let domNode=this.domNode;if(!domNode||domNode.destroyed) return;this.contentView.element.scrollTop=0;this._panel.markAsNeedsRefresh(domNode);if(this._forcedPseudoClassContainerToggledSetting) this._updatePseudoClassCheckboxes();if(this._classListContainerToggledSetting) this._populateClassToggles();} addEventListeners() {let effectiveDOMNode=this.domNode.isPseudoElement()?this.domNode.parentNode:this.domNode;if(!effectiveDOMNode) return;if(this._forcedPseudoClassContainerToggledSetting) effectiveDOMNode.addEventListener(WI.DOMNode.Event.EnabledPseudoClassesChanged,this._updatePseudoClassCheckboxes,this);if(this._classListContainerToggledSetting){effectiveDOMNode.addEventListener(WI.DOMNode.Event.AttributeModified,this._handleNodeAttributeModified,this);effectiveDOMNode.addEventListener(WI.DOMNode.Event.AttributeRemoved,this._handleNodeAttributeRemoved,this);}} removeEventListeners() {let effectiveDOMNode=this.domNode.isPseudoElement()?this.domNode.parentNode:this.domNode;if(!effectiveDOMNode) return;if(this._forcedPseudoClassContainerToggledSetting) effectiveDOMNode.removeEventListener(WI.DOMNode.Event.EnabledPseudoClassesChanged,this._updatePseudoClassCheckboxes,this);if(this._classListContainerToggledSetting){effectiveDOMNode.removeEventListener(WI.DOMNode.Event.AttributeModified,this._handleNodeAttributeModified,this);effectiveDOMNode.removeEventListener(WI.DOMNode.Event.AttributeRemoved,this._handleNodeAttributeRemoved,this);}} initialLayout() {this.contentView.addSubview(this._panel);if(this._classListContainerToggledSetting){this._classListContainer=this.element.createChild("div","class-list-container");this._addClassContainer=this._classListContainer.createChild("div","new-class");this._addClassContainer.title=WI.UIString("Add a Class");this._addClassContainer.addEventListener("click",this._addClassContainerClicked.bind(this));this._addClassInput=this._addClassContainer.createChild("input","class-name-input");this._addClassInput.spellcheck=false;this._addClassInput.setAttribute("placeholder",WI.UIString("Add New Class"));this._addClassInput.addEventListener("keypress",this._addClassInputKeyPressed.bind(this));this._addClassInput.addEventListener("blur",this._addClassInputBlur.bind(this));} if(this._forcedPseudoClassContainerToggledSetting){this._forcedPseudoClassContainer=this.element.appendChild(document.createElement("div"));this._forcedPseudoClassContainer.className="forced-pseudo-class-container";for(let pseudoClass of Object.values(WI.CSSManager.ForceablePseudoClass)){if(!WI.cssManager.canForcePseudoClass(pseudoClass)) continue;let labelElement=this._forcedPseudoClassContainer.appendChild(document.createElement("label"));let checkboxElement=labelElement.appendChild(document.createElement("input"));checkboxElement.addEventListener("change",this._forcedPseudoClassCheckboxChanged.bind(this,pseudoClass));checkboxElement.type="checkbox";this._checkboxForForcedPseudoClass.set(pseudoClass,checkboxElement);labelElement.append(WI.CSSManager.displayNameForForceablePseudoClass(pseudoClass));}} let optionsContainer=this.element.createChild("div","options-container");let newRuleButton=optionsContainer.createChild("img","new-rule");newRuleButton.title=WI.UIString("Add new rule");newRuleButton.addEventListener("click",this._newRuleButtonClicked.bind(this));newRuleButton.addEventListener("contextmenu",this._newRuleButtonContextMenu.bind(this));if(typeof this._panel.filterDidChange==="function"){this._filterBar=new WI.FilterBar;this._filterBar.addEventListener(WI.FilterBar.Event.FilterDidChange,this._filterDidChange,this);this._filterBar.inputField.addEventListener("keydown",this._handleFilterBarInputFieldKeyDown.bind(this));this.contentView.element.classList.add("has-filter-bar");optionsContainer.appendChild(this._filterBar.element);} if(this._classListContainerToggledSetting){this._classListToggleButton=optionsContainer.createChild("button","toggle class-list");this._classListToggleButton.textContent=WI.UIString("Classes");this._classListToggleButton.title=WI.UIString("Toggle Classes");this._classListToggleButton.addEventListener("click",this._classListToggleButtonClicked.bind(this));this._updateClassListContainer();} if(this._forcedPseudoClassContainerToggledSetting){this._forcedPseudoClassToggleButton=optionsContainer.appendChild(document.createElement("button"));this._forcedPseudoClassToggleButton.className="toggle forced-pseudo-class";this._forcedPseudoClassToggleButton.textContent=WI.UIString("Pseudo","Pseudo @ Styles details sidebar panel","Label for button that shows controls for toggling CSS pseudo-classes on the selected element.");this._forcedPseudoClassToggleButton.title=WI.UIString("Toggle Pseudo Classes");this._forcedPseudoClassToggleButton.addEventListener("click",this._forcedPseudoClassToggleButtonClicked.bind(this));this._updateForcedPseudoClassContainer();} WI.cssManager.addEventListener(WI.CSSManager.Event.StyleSheetAdded,this._styleSheetAddedOrRemoved,this);WI.cssManager.addEventListener(WI.CSSManager.Event.StyleSheetRemoved,this._styleSheetAddedOrRemoved,this);} sizeDidChange() {super.sizeDidChange();if(this._panel) this._panel.sizeDidChange();} _updateClassListContainer() {let hidden=!this._classListContainerToggledSetting.value;this._classListToggleButton.classList.toggle("selected",!hidden);this._classListContainer.hidden=hidden;this._populateClassToggles();} _updateForcedPseudoClassContainer() {let hidden=!this._forcedPseudoClassContainerToggledSetting.value;this._forcedPseudoClassToggleButton.classList.toggle("selected",!hidden);this._forcedPseudoClassContainer.hidden=hidden;} _handleNodeChanged(event) {this.contentView.element.classList.toggle("supports-new-rule",this._panel.supportsNewRule);this.contentView.element.classList.toggle("supports-toggle-class-list",this._panel.supportsToggleCSSClassList);this.contentView.element.classList.toggle("supports-toggle-forced-pseudo-class",this._panel.supportsToggleCSSForcedPseudoClass);} _forcedPseudoClassCheckboxChanged(pseudoClass,event) {if(!this.domNode) return;let effectiveDOMNode=this.domNode.isPseudoElement()?this.domNode.parentNode:this.domNode;if(!effectiveDOMNode) return;effectiveDOMNode.setPseudoClassEnabled(pseudoClass,event.target.checked);this._checkboxForForcedPseudoClass.get(pseudoClass).focus();} _updatePseudoClassCheckboxes() {if(!this.domNode) return;let effectiveDOMNode=this.domNode.isPseudoElement()?this.domNode.parentNode:this.domNode;if(!effectiveDOMNode) return;let enabledPseudoClasses=effectiveDOMNode.enabledPseudoClasses;for(let[pseudoClass,checkboxElement]of this._checkboxForForcedPseudoClass) checkboxElement.checked=enabledPseudoClasses.includes(pseudoClass);} _handleNodeAttributeModified(event) {if(event&&event.data&&event.data.name==="class") this._populateClassToggles();} _handleNodeAttributeRemoved(event) {if(event&&event.data&&event.data.name==="class") this._populateClassToggles();} _newRuleButtonClicked() {if(this._panel&&typeof this._panel.newRuleButtonClicked==="function") this._panel.newRuleButtonClicked();} _newRuleButtonContextMenu(event) {if(this._panel&&typeof this._panel.newRuleButtonContextMenu==="function") this._panel.newRuleButtonContextMenu(event);} _classListToggleButtonClicked(event) {if(this._forcedPseudoClassContainerToggledSetting){this._forcedPseudoClassContainerToggledSetting.value=false;this._updateForcedPseudoClassContainer();} this._classListContainerToggledSetting.value=!this._classListContainerToggledSetting.value;this._updateClassListContainer();} _forcedPseudoClassToggleButtonClicked(event) {if(this._classListContainerToggledSetting){this._classListContainerToggledSetting.value=false;this._updateClassListContainer();} this._forcedPseudoClassContainerToggledSetting.value=!this._forcedPseudoClassContainerToggledSetting.value;this._updateForcedPseudoClassContainer();} _addClassContainerClicked(event) {this._addClassContainer.classList.add("active");this._addClassInput.focus();} _addClassInputKeyPressed(event) {if(event.keyCode!==WI.KeyboardShortcut.Key.Enter.keyCode) return;this._addClassFromInput();} _addClassInputBlur(event) {this._addClassFromInput();this._addClassContainer.classList.remove("active");} _addClassFromInput() {this.domNode.toggleClass(this._addClassInput.value,true);this._addClassInput.value=null;} _populateClassToggles() {if(!this._classListContainer||this._classListContainer.hidden) return;while(this._classListContainer.children.length>1) this._classListContainer.children[1].remove();let classes=this.domNode.getAttribute("class")||[];let classToggledMap=this.domNode[WI.GeneralStyleDetailsSidebarPanel.ToggledClassesSymbol];if(!classToggledMap) classToggledMap=this.domNode[WI.GeneralStyleDetailsSidebarPanel.ToggledClassesSymbol]=new Map;if(classes&&classes.length){for(let className of classes.split(/\s+/)) classToggledMap.set(className,true);} for(let[className,toggled]of classToggledMap){if((toggled&&!classes.includes(className))||(!toggled&&classes.includes(className))){toggled=!toggled;classToggledMap.set(className,toggled);} this._createToggleForClassName(className);}} _createToggleForClassName(className) {if(!className||!className.length) return;let classToggledMap=this.domNode[WI.GeneralStyleDetailsSidebarPanel.ToggledClassesSymbol];if(!classToggledMap) return;if(!classToggledMap.has(className)) classToggledMap.set(className,true);let toggled=classToggledMap.get(className);let classNameContainer=document.createElement("div");classNameContainer.classList.add("class-toggle");let classNameToggle=classNameContainer.createChild("input");classNameToggle.type="checkbox";classNameToggle.checked=toggled;let classNameTitle=classNameContainer.createChild("span");classNameTitle.textContent=className;classNameTitle.draggable=true;classNameTitle.addEventListener("dragstart",(event)=>{event.dataTransfer.setData(WI.GeneralStyleDetailsSidebarPanel.ToggledClassesDragType,className);event.dataTransfer.effectAllowed="copy";});let classNameToggleChanged=(event)=>{this.domNode.toggleClass(className,classNameToggle.checked);classToggledMap.set(className,classNameToggle.checked);};classNameToggle.addEventListener("click",classNameToggleChanged);classNameTitle.addEventListener("click",(event)=>{classNameToggle.checked=!classNameToggle.checked;classNameToggleChanged();});this._classListContainer.appendChild(classNameContainer);} _filterDidChange() {if(!this._filterBar) return;this.contentView.element.classList.toggle(WI.GeneralStyleDetailsSidebarPanel.FilterInProgressClassName,this._filterBar.hasActiveFilters());this._panel.filterDidChange(this._filterBar);} _handleFilterBarInputFieldKeyDown(event) {if(event.key!=="Tab"||!event.shiftKey) return;if(this._panel.focusLastSection){this._panel.focusLastSection();event.preventDefault();}} _styleSheetAddedOrRemoved() {let domNode=this.domNode;if(!domNode||domNode.destroyed) return;this._panel.markAsNeedsRefresh(domNode);}};WI.GeneralStyleDetailsSidebarPanel.FilterInProgressClassName="filter-in-progress";WI.GeneralStyleDetailsSidebarPanel.FilterMatchingSectionHasLabelClassName="filter-section-has-label";WI.GeneralStyleDetailsSidebarPanel.FilterMatchSectionClassName="filter-matching";WI.GeneralStyleDetailsSidebarPanel.NoFilterMatchInSectionClassName="filter-section-non-matching";WI.GeneralStyleDetailsSidebarPanel.NoFilterMatchInPropertyClassName="filter-property-non-matching";WI.GeneralStyleDetailsSidebarPanel.ToggledClassesSymbol=Symbol("css-style-details-sidebar-panel-toggled-classes-symbol");WI.GeneralStyleDetailsSidebarPanel.ToggledClassesDragType="web-inspector/css-class";WI.RulesStyleDetailsSidebarPanel=class RulesStyleDetailsSidebarPanel extends WI.GeneralStyleDetailsSidebarPanel {constructor() {super("style-rules",WI.UIString("Styles"),WI.SpreadsheetRulesStyleDetailsPanel);} get allowExclusivePresentation() {return WI.settings.enableElementsTabIndependentStylesDetailsSidebarPanel.value;}};WI.ComputedStyleDetailsSidebarPanel=class ComputedStyleDetailsSidebarPanel extends WI.GeneralStyleDetailsSidebarPanel {constructor() {super("style-computed",WI.UIString("Computed"),WI.ComputedStyleDetailsPanel);} computedStyleDetailsPanelShowProperty(property) {let styleRulesPanel=WI.detailsSidebar.sidebarPanels.find((panel)=>panel instanceof WI.RulesStyleDetailsSidebarPanel);if(!styleRulesPanel) return;WI.detailsSidebar.selectedSidebarPanel=styleRulesPanel;styleRulesPanel.panel.scrollToSectionAndHighlightProperty(property);}};WI.StyleDetailsPanel=class StyleDetailsPanel extends WI.View {constructor(delegate,className,identifier,label) {super();this._delegate=delegate||null;this.element.classList.add(className);this._navigationInfo={identifier,label};this._nodeStyles=null;} get navigationInfo() {return this._navigationInfo;} get nodeStyles() {return this._nodeStyles;} get supportsNewRule() {return false;} get supportsToggleCSSClassList() {return false;} get supportsToggleCSSForcedPseudoClass() {return false;} attached() {super.attached();this._refreshNodeStyles();} markAsNeedsRefresh(domNode) {if(!domNode) return;if(!this._nodeStyles||this._nodeStyles.node!==domNode){if(this._nodeStyles){this._nodeStyles.removeEventListener(WI.DOMNodeStyles.Event.Refreshed,this.nodeStylesRefreshed,this);this._nodeStyles.removeEventListener(WI.DOMNodeStyles.Event.NeedsRefresh,this._nodeStylesNeedsRefreshed,this);} this._nodeStyles=WI.cssManager.stylesForNode(domNode);this.dispatchEventToListeners(WI.StyleDetailsPanel.Event.NodeChanged);if(!this._nodeStyles) return;this._nodeStyles.addEventListener(WI.DOMNodeStyles.Event.Refreshed,this.nodeStylesRefreshed,this);this._nodeStyles.addEventListener(WI.DOMNodeStyles.Event.NeedsRefresh,this._nodeStylesNeedsRefreshed,this);this._forceSignificantChange=true;} if(this.isAttached) this._refreshNodeStyles();} refresh(significantChange) {} nodeStylesRefreshed(event) {if(this.isAttached) this._refreshPreservingScrollPosition(event.data.significantChange);} _refreshNodeStyles() {if(!this._nodeStyles) return;this._nodeStyles.refresh();} _refreshPreservingScrollPosition(significantChange) {significantChange=this._forceSignificantChange||significantChange||false;let previousScrollTop=0;if(this.element.parentNode&&this._previousRefreshNodeIdentifier===this._nodeStyles.node.id) previousScrollTop=this.element.parentNode.scrollTop;this.refresh(significantChange);this._previousRefreshNodeIdentifier=this._nodeStyles.node.id;if(this.element.parentNode) this.element.parentNode.scrollTop=previousScrollTop;this._forceSignificantChange=false;} _nodeStylesNeedsRefreshed(event) {if(this.isAttached) this._refreshNodeStyles();}};WI.StyleDetailsPanel.Event={NodeChanged:"style-details-panel-node-changed",};WI.MediaDetailsSidebarPanel=class MediaDetailsSidebarPanel extends WI.DOMDetailsSidebarPanel { static StyleClassName="media"; constructor(delegate) {super("media-details",WI.UIString("Media"));this.#ui.sourceRow=new WI.MediaDetailsSidebarPanel.#Row(WI.UIString("Source","Source @ Media Sidebar","Title for Source row in Media Sidebar"));this.#ui.viewportRow=new WI.MediaDetailsSidebarPanel.#Row(WI.UIString("Viewport","Viewport @ Media Sidebar","Title for Viewport row in Media Sidebar"));this.#ui.framesRow=new WI.MediaDetailsSidebarPanel.#Row(WI.UIString("Frames","Frames @ Media Sidebar Frame Count","Title for Frames row in Media Sidebar"));this.#ui.resolutionRow=new WI.MediaDetailsSidebarPanel.#Row(WI.UIString("Resolution","Resolution @ Media Sidebar","Title for Resolution row in Media Sidebar"));this.#ui.videoFormatRow=new WI.MediaDetailsSidebarPanel.#Row(WI.UIString("Video Format","Video Format @ Media Sidebar","Title for Video Format row in Media Sidebar"));this.#ui.audioFormatRow=new WI.MediaDetailsSidebarPanel.#Row(WI.UIString("Audio Format","Audio Format @ Media Sidebar","Title for Audio Format row in Media Sidebar"));let generalGroup=new WI.DetailsSectionGroup([this.#ui.sourceRow,this.#ui.viewportRow,this.#ui.framesRow,this.#ui.resolutionRow,this.#ui.videoFormatRow,this.#ui.audioFormatRow]);this.#ui.generalSection=new WI.DetailsSection("media-details-general",WI.UIString("General","General @ Media Sidebar","Title for General Section in Media Sidebar"),[generalGroup]);this.#ui.videoCodecRow=new WI.MediaDetailsSidebarPanel.#Row(WI.UIString("Video Codec","Video Codec @ Media Sidebar","Title for Video Codec row in Media Sidebar"));this.#ui.transferRow=new WI.MediaDetailsSidebarPanel.#Row(WI.UIString("Transfer Function","Transfer Function @ Media Sidebar","Title for Transfer Function row in Media Sidebar"));this.#ui.primariesRow=new WI.MediaDetailsSidebarPanel.#Row(WI.UIString("Color Primaries","Color Primaries @ Media Sidebar","Title for Color Primaries row in Media Sidebar"));this.#ui.matrixRow=new WI.MediaDetailsSidebarPanel.#Row(WI.UIString("Matrix Coefficients","Matrix Coefficients @ Media Sidebar","Title for Matrix Coefficients row in Media Sidebar"));this.#ui.fullRangeRow=new WI.MediaDetailsSidebarPanel.#Row(WI.UIString("Color Range","Color Range @ Media Sidebar","Title for Color Range row in Media Sidebar"));let videoGroup=new WI.DetailsSectionGroup([this.#ui.videoCodecRow,this.#ui.primariesRow,this.#ui.transferRow,this.#ui.matrixRow,this.#ui.fullRangeRow]);this.#ui.videoSection=new WI.DetailsSection("media-video-details",WI.UIString("Video Details","Video Details @ Media Sidebar","Title for Video Details section in Media Sidebar"),[videoGroup]);this.#ui.audioCodecRow=new WI.MediaDetailsSidebarPanel.#Row(WI.UIString("Audio Codec","Audio Codec @ Media Sidebar","Title for Audio Codec row in Media Sidebar"));this.#ui.sampleRateRow=new WI.MediaDetailsSidebarPanel.#Row(WI.UIString("Sample Rate","Sample Rate @ Media Sidebar","Title for Sample Rate row in Media Sidebar"));this.#ui.channelsRow=new WI.MediaDetailsSidebarPanel.#Row(WI.UIString("Channels","Channels @ Media Sidebar","Title for Channels row in Media Sidebar"));let audioGroup=new WI.DetailsSectionGroup([this.#ui.audioCodecRow,this.#ui.sampleRateRow,this.#ui.channelsRow]);this.#ui.audioSection=new WI.DetailsSection("media-audio-details",WI.UIString("Audio Details","Audio Details @ Media Sidebar","Title for Audio Details section in Media Sidebar"),[audioGroup]);} layout() {this.#ui.sourceRow.updateValue();this.#ui.viewportRow.updateValue();this.#ui.framesRow.updateValue();this.#ui.resolutionRow.updateValue();this.#ui.videoFormatRow.updateValue();this.#ui.audioFormatRow.updateValue();this.#ui.videoCodecRow.updateValue();this.#ui.transferRow.updateValue();this.#ui.primariesRow.updateValue();this.#ui.matrixRow.updateValue();this.#ui.fullRangeRow.updateValue();this.#ui.audioCodecRow.updateValue();this.#ui.sampleRateRow.updateValue();this.#ui.channelsRow.updateValue();} supportsDOMNode(nodeToInspect) {return nodeToInspect.isMediaElement();} attached() {super.attached();this.#startUpdateTimer();} detached() {super.detached();this.#cancelUpdateTimer();} initialLayout() {super.initialLayout();this.element.appendChild(this.#ui.generalSection.element);this.element.appendChild(this.#ui.videoSection.element);this.element.appendChild(this.#ui.audioSection.element);} static#Row=class MediaDetailsSectionSimpleRow extends WI.DetailsSectionSimpleRow { set pendingValue(value) {this.#pendingValue=value;this.#dirty=true;} updateValue() {if(!this.#dirty) return;this.value=this.#pendingValue;this.#pendingValue=null;this.#dirty=false;} #pendingValue=null;#dirty=null;};#values={source:null,viewport:null,devicePixelRatio:null,quality:null,videoFormat:null,audioFormat:null,video:null,audio:null,};#ui={sourceRow:null,viewportRow:null,framesRow:null,resolutionRow:null,videoFormatRow:null,audioFormatRow:null,generalSection:null,videoCodecRow:null,transferRow:null,primariesRow:null,matrixRow:null,fullRangeRow:null,videoSection:null,audioCodecRow:null,sampleRateRow:null,channelsRow:null,audioSection:null,};#updateTimer=null;#updateTimerInterval=250;#startUpdateTimer() {this.#cancelUpdateTimer();this.#updateTimerFired();}#cancelUpdateTimer() {if(this.#updateTimer) clearTimeout(this.#updateTimer);} async#updateTimerFired() {if(!this.domNode) return;let stats=await this.domNode.getMediaStats();this.#setSource(stats.source);this.#setViewport(stats.viewport);this.#setDevicePixelRatio(stats.devicePixelRatio);this.#setQuality(stats.quality);this.#setVideoFormat(stats.video?.humanReadableCodecString);this.#setAudioFormat(stats.audio?.humanReadableCodecString);this.#setVideo(stats.video);this.#setAudio(stats.audio);if(this.isAttached) this.#updateTimer=setTimeout(()=>this.#updateTimerFired(),this.#updateTimerInterval);}#setSource(source) {if(this.#values.source===source) return;this.#values.source=source;this.#ui.sourceRow.pendingValue=this.#values.source;this.needsLayout();}#setViewport(viewport) {if(Object.shallowEqual(this.#values.viewport,viewport)) return;this.#values.viewport=viewport;this.#updateViewportRow();}#setDevicePixelRatio(devicePixelRatio) {if(this.#values.devicePixelRatio===devicePixelRatio) return;this.#values.devicePixelRatio=devicePixelRatio;this.#updateViewportRow();}#updateViewportRow() {this.#ui.viewportRow.pendingValue=WI.UIString("%dx%d (%dx)").format(this.#values.viewport?.width??0,this.#values.viewport?.height??0,this.#values.devicePixelRatio??1);this.needsLayout();}#setQuality(quality) {if(Object.shallowEqual(this.#values.quality,quality)) return;this.#values.quality=quality;let formatString=WI.UIString("%d dropped of %d","Dropped Frame Format @ Media Sidebar","Format string for Dropped Frame count in Media Sidebar");this.#ui.framesRow.pendingValue=formatString.format(quality?.droppedVideoFrames??0,quality?.totalVideoFrames??0);this.needsLayout();}#setVideoFormat(videoFormat) {if(this.#values.videoFormat===videoFormat) return;this.#values.videoFormat=videoFormat;this.#ui.videoFormatRow.pendingValue=videoFormat;this.needsLayout();}#setAudioFormat(audioFormat) {if(this.#values.audioFormat===audioFormat) return;this.#values.audioFormat=audioFormat;this.#ui.audioFormatRow.pendingValue=audioFormat;this.needsLayout();}#setVideo(video) {if(this.#values.video===video) return;if(this.#values.video?.width===video?.width&&this.#values.video?.height===video?.height&&this.#values.video?.framerate===video?.framerate&&this.#values.video?.codec===video?.codec&&Object.shallowEqual(this.#values.video?.colorSpace,video?.colorSpace)&&this.#values.video?.colorSpace?.primaries===video?.colorSpace?.primaries&&this.#values.video?.colorSpace?.matrix===video?.colorSpace?.matrix&&this.#values.video?.fullRange===video?.fullRange) return;this.#values.video=video;this.#ui.videoSection.element.classList.toggle("hidden",!video);this.#ui.resolutionRow.pendingValue=WI.UIString("%dx%d (%dfps)").format(video?.width??0,video?.height??0,video?.framerate??0);this.#ui.resolutionRow.element.classList.toggle("hidden",!video);this.#ui.videoCodecRow.pendingValue=video?.codec;this.#ui.transferRow.pendingValue=video?.colorSpace?.transfer;this.#ui.primariesRow.pendingValue=video?.colorSpace?.primaries;this.#ui.matrixRow.pendingValue=video?.colorSpace?.matrix;if(video?.fullRange) this.#ui.fullRangeRow.pendingValue=WI.UIString("Full range","Full range @ Media Sidebar","Value string for Full Range color in the Media Sidebar");else this.#ui.fullRangeRow.pendingValue=WI.UIString("Video range","Video range @ Media Sidebar","Value string for Video Range color in the Media Sidebar");this.needsLayout();}#setAudio(audio) {if(Object.shallowEqual(this.#values.audio,audio)) return;this.#values.audio=audio;this.#ui.audioSection.element.classList.toggle("hidden",!audio);this.#ui.audioCodecRow.pendingValue=audio?.codec;this.#ui.sampleRateRow.pendingValue=WI.UIString("%d Hz").format(audio?.sampleRate);switch(audio?.numberOfChannels){case 1:this.#ui.channelsRow.pendingValue=WI.UIString("Mono");break;case 2:this.#ui.channelsRow.pendingValue=WI.UIString("Stereo");break;default:this.#ui.channelsRow.pendingValue=audio?.numberOfChannels;break;} this.needsLayout();}};WI.AuditTabContentView=class AuditTabContentView extends WI.ContentBrowserTabContentView {constructor() {super(AuditTabContentView.tabInfo(),{navigationSidebarPanelConstructor:WI.AuditNavigationSidebarPanel,hideBackForwardButtons:true,});this._startStopShortcut=new WI.KeyboardShortcut(null,WI.KeyboardShortcut.Key.Space,this._handleSpace.bind(this));this._startStopShortcut.implicitlyPreventsDefault=false;this._startStopShortcut.disabled=true;} static tabInfo() {return{identifier:AuditTabContentView.Type,image:"Images/Audit.svg",displayName:WI.UIString("Audit","Audit Tab Name","Name of Audit Tab"),};} static isTabAllowed() {return WI.sharedApp.isWebDebuggable();} get type() {return WI.AuditTabContentView.Type;} get supportsSplitContentBrowser() {return true;} canShowRepresentedObject(representedObject) {return representedObject instanceof WI.AuditTestCase||representedObject instanceof WI.AuditTestGroup||representedObject instanceof WI.AuditTestCaseResult||representedObject instanceof WI.AuditTestGroupResult;} attached() {super.attached();this._startStopShortcut.disabled=false;} detached() {this._startStopShortcut.disabled=true;super.detached();} dropZoneShouldAppearForDragEvent(dropZone,event) {return event.dataTransfer.types.includes("Files");} dropZoneHandleDrop(dropZone,event) {let files=event.dataTransfer.files;if(files.length!==1){InspectorFrontendHost.beep();return;} WI.FileUtilities.readJSON(files,(result)=>WI.auditManager.processJSON(result));} initialLayout() {super.initialLayout();let dropZoneView=new WI.DropZoneView(this);dropZoneView.text=WI.UIString("Import Audit or Result");dropZoneView.targetElement=this.element;this.addSubview(dropZoneView);WI.auditManager.loadStoredTests();} _handleSpace(event) {if(WI.isEventTargetAnEditableField(event)) return;if(WI.auditManager.runningState===WI.AuditManager.RunningState.Inactive) WI.auditManager.start(this.contentBrowser.currentRepresentedObjects);else if(WI.auditManager.runningState===WI.AuditManager.RunningState.Active) WI.auditManager.stop();else return;event.preventDefault();}};WI.AuditTabContentView.Type="audit";WI.ConsoleTabContentView=class ConsoleTabContentView extends WI.ContentBrowserTabContentView {constructor() {super(ConsoleTabContentView.tabInfo(),{hideBackForwardButtons:true,disableBackForwardNavigation:true,flexibleNavigationItem:new WI.NavigationItem,});this._wasShowingSplitConsole=false;} static tabInfo() {return{identifier:ConsoleTabContentView.Type,image:"Images/Console.svg",displayName:WI.UIString("Console","Console Tab Name","Name of Console Tab"),};} get type() {return WI.ConsoleTabContentView.Type;} attached() {super.attached();this._wasShowingSplitConsole=WI.isShowingSplitConsole();if(this._wasShowingSplitConsole) WI.hideSplitConsole();this.contentBrowser.showContentView(WI.consoleContentView);WI.consoleContentView.dispatchEventToListeners(WI.ContentView.Event.NavigationItemsDidChange);WI.consoleContentView.prompt.focus();} detached() {super.detached();if(this._wasShowingSplitConsole) WI.showSplitConsole();} showRepresentedObject(representedObject,cookie) { } canShowRepresentedObject(representedObject) {return representedObject instanceof WI.LogObject;} get supportsSplitContentBrowser() {return false;}};WI.ConsoleTabContentView.Type="console";WI.ElementsTabContentView=class ElementsTabContentView extends WI.ContentBrowserTabContentView {constructor() {let detailsSidebarPanelConstructors=[WI.RulesStyleDetailsSidebarPanel,WI.ComputedStyleDetailsSidebarPanel,];if(InspectorBackend.hasCommand("DOM.showGridOverlay")) detailsSidebarPanelConstructors.push(WI.LayoutDetailsSidebarPanel);if(InspectorBackend.hasCommand("CSS.getFontDataForNode")) detailsSidebarPanelConstructors.push(WI.FontDetailsSidebarPanel);if(InspectorBackend.hasCommand("DOM.getMediaStats")) detailsSidebarPanelConstructors.push(WI.MediaDetailsSidebarPanel) detailsSidebarPanelConstructors.push(WI.ChangesDetailsSidebarPanel,WI.DOMNodeDetailsSidebarPanel);if(InspectorBackend.hasDomain("LayerTree")) detailsSidebarPanelConstructors.push(WI.LayerTreeDetailsSidebarPanel);super(ElementsTabContentView.tabInfo(),{detailsSidebarPanelConstructors,hideBackForwardButtons:true,disableBackForwardNavigation:true});} static tabInfo() {return{identifier:ElementsTabContentView.Type,image:"Images/Elements.svg",displayName:WI.UIString("Elements","Elements Tab Name","Name of Elements Tab"),};} static isTabAllowed() {return InspectorBackend.hasDomain("DOM");} get type() {return WI.ElementsTabContentView.Type;} get supportsSplitContentBrowser() {return true;} get detailsSidebarExpandedByDefault() {return true;} canShowRepresentedObject(representedObject) {return representedObject instanceof WI.DOMTree;} showRepresentedObject(representedObject,cookie) {this._showDOMTreeContentViewIfNeeded();if(!cookie||!cookie.nodeToSelect) return;let domTreeContentView=this.contentBrowser.currentContentView;domTreeContentView.selectAndRevealDOMNode(cookie.nodeToSelect); cookie.nodeToSelect=undefined;} attached() {super.attached();WI.networkManager.addEventListener(WI.NetworkManager.Event.MainFrameDidChange,this._mainFrameDidChange,this);WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);this._showDOMTreeContentViewIfNeeded();} detached() {WI.networkManager.removeEventListener(WI.NetworkManager.Event.MainFrameDidChange,this._mainFrameDidChange,this);WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);super.detached();} initialLayout() {super.initialLayout();this.element.appendChild(WI.ReferencePage.ElementsTab.DOMTree.createLinkElement());} closed() {super.closed();WI.networkManager.removeEventListener(WI.NetworkManager.Event.MainFrameDidChange,this._mainFrameDidChange,this);WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);} get allowMultipleDetailSidebars() {return true;} _showDOMTreeContentViewIfNeeded() {let mainDOMTree=WI.networkManager.mainFrame?.domTree;if(!mainDOMTree) return;if(this.contentBrowser.currentContentView?.representedObject===mainDOMTree) return;this.contentBrowser.showContentViewForRepresentedObject(mainDOMTree);} _mainFrameDidChange(event) {this._showDOMTreeContentViewIfNeeded();} _mainResourceDidChange(event) {if(!event.target.isMainFrame()) return;this._showDOMTreeContentViewIfNeeded();}};WI.ElementsTabContentView.Type="elements";WI.GraphicsTabContentView=class GraphicsTabContentView extends WI.ContentBrowserTabContentView {constructor() {super(GraphicsTabContentView.tabInfo(),{navigationSidebarPanelConstructor:WI.CanvasSidebarPanel,detailsSidebarPanelConstructors:[WI.RecordingStateDetailsSidebarPanel,WI.RecordingTraceDetailsSidebarPanel,WI.CanvasDetailsSidebarPanel,WI.AnimationDetailsSidebarPanel,],hideBackForwardButtons:true,});this._canvasesTreeOutline=new WI.TreeOutline;this._canvasesTreeOutline.allowsRepeatSelection=true;this._canvasesTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._handleOverviewTreeOutlineSelectionDidChange,this);this._canvasesTreeElement=new WI.GeneralTreeElement("canvas-overview",WI.UIString("Overview"),null,{[WI.ContentView.isViewableSymbol]:true});this._canvasesTreeOutline.appendChild(this._canvasesTreeElement);this._savedCanvasRecordingsTreeElement=new WI.FolderTreeElement(WI.UIString("Saved Recordings"));this._savedCanvasRecordingsTreeElement.hidden=true;this._canvasesTreeElement.appendChild(this._savedCanvasRecordingsTreeElement);this._recordShortcut=new WI.KeyboardShortcut(null,WI.KeyboardShortcut.Key.Space,this._handleSpace.bind(this));this._recordShortcut.implicitlyPreventsDefault=false;this._recordShortcut.disabled=true;this._recordSingleFrameShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Shift,WI.KeyboardShortcut.Key.Space,this._handleSpace.bind(this));this._recordSingleFrameShortcut.implicitlyPreventsDefault=false;this._recordSingleFrameShortcut.disabled=true;WI.canvasManager.enable();WI.animationManager.enable();} static tabInfo() {return{identifier:GraphicsTabContentView.Type,image:"Images/Graphics.svg",displayName:WI.UIString("Graphics","Graphics Tab Name","Name of Graphics Tab"),};} static isTabAllowed() {return InspectorBackend.hasDomain("Canvas")||InspectorBackend.hasDomain("Animation");} treeElementForRepresentedObject(representedObject) {return this._canvasesTreeOutline.findTreeElement(representedObject);} get type() {return WI.GraphicsTabContentView.Type;} get supportsSplitContentBrowser() {return true;} get managesNavigationSidebarPanel() {return true;} showRepresentedObject(representedObject,cookie) {if(representedObject instanceof WI.Collection){this.contentBrowser.showContentView(this._overviewContentView);return;} super.showRepresentedObject(representedObject,cookie);} canShowRepresentedObject(representedObject) {return representedObject instanceof WI.CanvasCollection||representedObject instanceof WI.Canvas||representedObject instanceof WI.Recording||representedObject instanceof WI.ShaderProgram||representedObject instanceof WI.AnimationCollection||representedObject instanceof WI.Animation;} closed() {WI.animationManager.disable();WI.canvasManager.disable();super.closed();} restoreStateFromCookie(cookie) {} saveStateToCookie(cookie) {} dropZoneShouldAppearForDragEvent(dropZone,event) {return event.dataTransfer.types.includes("Files");} dropZoneHandleDrop(dropZone,event) {let files=event.dataTransfer.files;if(files.length!==1){InspectorFrontendHost.beep();return;} WI.FileUtilities.readJSON(files,(result)=>WI.canvasManager.processJSON(result));} attached() {super.attached();WI.canvasManager.canvasCollection.addEventListener(WI.Collection.Event.ItemAdded,this._handleCanvasAdded,this);WI.canvasManager.canvasCollection.addEventListener(WI.Collection.Event.ItemRemoved,this._handleCanvasRemoved,this);WI.canvasManager.addEventListener(WI.CanvasManager.Event.RecordingSaved,this._handleRecordingSavedOrStopped,this);WI.Canvas.addEventListener(WI.Canvas.Event.RecordingStopped,this._handleRecordingSavedOrStopped,this);for(let child of this._canvasesTreeElement.children){let canvas=child.representedObject;if(canvas instanceof WI.Canvas&&!WI.canvasManager.canvasCollection.has(canvas)) this._removeCanvas(canvas);} for(let canvas of WI.canvasManager.canvasCollection){if(!this._canvasesTreeOutline.findTreeElement(canvas)) this._addCanvas(canvas);} for(let recording of WI.canvasManager.savedRecordings){if(!this._canvasesTreeOutline.findTreeElement(recording)) this._addRecording(recording,{suppressShowRecording:true});} this._recordShortcut.disabled=false;this._recordSingleFrameShortcut.disabled=false;} detached() {this._recordShortcut.disabled=true;this._recordSingleFrameShortcut.disabled=true;WI.Canvas.removeEventListener(WI.Canvas.Event.RecordingStopped,this._handleRecordingSavedOrStopped,this);WI.canvasManager.removeEventListener(WI.CanvasManager.Event.RecordingSaved,this._handleRecordingSavedOrStopped,this);WI.canvasManager.canvasCollection.removeEventListener(WI.Collection.Event.ItemAdded,this._handleCanvasAdded,this);WI.canvasManager.canvasCollection.removeEventListener(WI.Collection.Event.ItemRemoved,this._handleCanvasRemoved,this);super.detached();} initialLayout() {super.initialLayout();this._overviewContentView=new WI.GraphicsOverviewContentView;setTimeout(()=>{this.contentBrowser.showContentView(this._overviewContentView);});let dropZoneView=new WI.DropZoneView(this);dropZoneView.text=WI.UIString("Import Recording");dropZoneView.targetElement=this.element;this.addSubview(dropZoneView);} _addCanvas(canvas) {this._canvasesTreeElement.appendChild(new WI.CanvasTreeElement(canvas));const options={suppressShowRecording:true,};for(let recording of canvas.recordingCollection) this._addRecording(recording,options);} _removeCanvas(canvas) {let treeElement=this._canvasesTreeOutline.findTreeElement(canvas);const suppressNotification=true;treeElement.deselect(suppressNotification);this._canvasesTreeElement.removeChild(treeElement);let currentContentView=this.contentBrowser.currentContentView;if(currentContentView instanceof WI.CanvasContentView&&canvas===currentContentView.representedObject) WI.showRepresentedObject(WI.canvasManager.canvasCollection);else if(currentContentView instanceof WI.ShaderProgramContentView&&canvas===currentContentView.representedObject.canvas) WI.showRepresentedObject(WI.canvasManager.canvasCollection);else if(currentContentView instanceof WI.RecordingContentView&&canvas.recordingCollection.has(currentContentView.representedObject)) this.contentBrowser.updateHierarchicalPathForCurrentContentView();let navigationSidebarPanel=this.navigationSidebarPanel;if(navigationSidebarPanel instanceof WI.CanvasSidebarPanel&&navigationSidebarPanel.visible) navigationSidebarPanel.updateRepresentedObjects();this.showDetailsSidebarPanels();} _addRecording(recording,options={}) {if(!recording.source){const subtitle=null;let recordingTreeElement=new WI.GeneralTreeElement(["recording"],recording.displayName,subtitle,recording);this._savedCanvasRecordingsTreeElement.hidden=false;this._savedCanvasRecordingsTreeElement.appendChild(recordingTreeElement);} if(!options.suppressShowRecording) this.showRepresentedObject(recording);} _handleCanvasAdded(event) {this._addCanvas(event.data.item);} _handleCanvasRemoved(event) {this._removeCanvas(event.data.item);} _handleOverviewTreeOutlineSelectionDidChange(event) {let selectedElement=this._canvasesTreeOutline.selectedTreeElement;if(!selectedElement) return;switch(selectedElement){case this._canvasesTreeElement:case this._savedCanvasRecordingsTreeElement:this.contentBrowser.showContentView(this._overviewContentView);return;} let representedObject=selectedElement.representedObject;if(!this.canShowRepresentedObject(representedObject)){return;} this.showRepresentedObject(representedObject);} _handleRecordingSavedOrStopped(event) {let{recording,initiatedByUser,imported}=event.data;if(!recording) return;let options={};if(recording.source||!imported) options.suppressShowRecording=!initiatedByUser||this.contentBrowser.currentRepresentedObjects.some((representedObject)=>representedObject instanceof WI.Recording);this._addRecording(recording,options);} _handleSpace(event) {if(WI.isEventTargetAnEditableField(event)) return;if(!this.navigationSidebarPanel) return;let canvas=this.navigationSidebarPanel.canvas;if(!canvas) return;if(canvas.recordingActive) canvas.stopRecording();else{let singleFrame=!!event.shiftKey;canvas.startRecording(singleFrame);} event.preventDefault();}};WI.GraphicsTabContentView.Type="graphics";WI.LayersTabContentView=class LayersTabContentView extends WI.ContentBrowserTabContentView {constructor() {super(LayersTabContentView.tabInfo(),{detailsSidebarPanelConstructors:[WI.LayerDetailsSidebarPanel],hideBackForwardButtons:true,disableBackForwardNavigation:true,});this._layerDetailsSidebarPanel=this.detailsSidebarPanels[0];this._layerDetailsSidebarPanel.addEventListener(WI.LayerDetailsSidebarPanel.Event.SelectedLayerChanged,this._detailsSidebarSelectedLayerChanged,this);this._layers3DContentView=new WI.Layers3DContentView;this._layers3DContentView.addEventListener(WI.Layers3DContentView.Event.SelectedLayerChanged,this._contentViewSelectedLayerChanged,this);} static tabInfo() {return{identifier:LayersTabContentView.Type,image:"Images/Layers.svg",displayName:WI.UIString("Layers","Layers Tab Name","Name of Layers Tab"),};} static isTabAllowed() {return InspectorBackend.hasDomain("LayerTree");} get type(){return WI.LayersTabContentView.Type;} get supportsSplitContentBrowser(){return false;} selectLayerForNode(node) {this._layers3DContentView.selectLayerForNode(node);} attached() {super.attached();this.contentBrowser.showContentView(this._layers3DContentView);} _detailsSidebarSelectedLayerChanged(event) {this._layers3DContentView.selectLayerById(event.data.layerId);} _contentViewSelectedLayerChanged(event) {this._layerDetailsSidebarPanel.selectNodeByLayerId(event.data.layerId);}};WI.LayersTabContentView.Type="layers";WI.ResourceTreeElement=class ResourceTreeElement extends WI.SourceCodeTreeElement {constructor(resource,representedObject,{allowDirectoryAsName,hideOrigin}={}) {const title=null;const subtitle=null;let styleClassNames=["resource",WI.ResourceTreeElement.ResourceIconStyleClassName,...WI.Resource.classNamesForResource(resource)];super(resource,styleClassNames,title,subtitle,representedObject||resource);if(allowDirectoryAsName) this._allowDirectoryAsName=allowDirectoryAsName;if(hideOrigin) this._hideOrigin=hideOrigin;this._updateResource(resource);} static compareResourceTreeElements(a,b) {let resourceA=a.resource||a.representedObject;let resourceB=b.resource||b.representedObject;function resolvedType(resource){if(resource instanceof WI.Resource) return resource.type;if(resource instanceof WI.CSSStyleSheet) return WI.Resource.Type.StyleSheet;if(resource instanceof WI.Script) return WI.Resource.Type.Script;return WI.Resource.Type.Other;} let typeA=resolvedType(resourceA);let typeB=resolvedType(resourceB);var comparisonResult=typeA.extendedLocaleCompare(typeB);if(comparisonResult!==0) return comparisonResult;if(typeA===WI.Resource.Type.XHR||typeA===WI.Resource.Type.Fetch||typeA===WI.Resource.Type.WebSocket) return resourceA.firstTimestamp-resourceB.firstTimestamp||0; comparisonResult=a.subtitle.extendedLocaleCompare(b.subtitle);if(comparisonResult!==0) return comparisonResult;function filenameWithoutExtension(resourceTitle){return resourceTitle.substring(0,resourceTitle.lastIndexOf("."));} let titleA=filenameWithoutExtension(a.mainTitle);let titleB=filenameWithoutExtension(b.mainTitle);comparisonResult=titleA.extendedLocaleCompare(titleB);if(comparisonResult!==0) return comparisonResult;return a.mainTitle.extendedLocaleCompare(b.mainTitle);} static compareFolderAndResourceTreeElements(a,b) {var aIsFolder=a instanceof WI.FolderTreeElement;var bIsFolder=b instanceof WI.FolderTreeElement;if(aIsFolder&&!bIsFolder) return-1;if(!aIsFolder&&bIsFolder) return 1;if(aIsFolder&&bIsFolder) return a.mainTitle.extendedLocaleCompare(b.mainTitle);return WI.ResourceTreeElement.compareResourceTreeElements(a,b);} get resource() {return this._resource;} get filterableData() {let urlComponents=this._resource.urlComponents;return{text:[urlComponents.lastPathComponent,urlComponents.path,this._resource.url]};} ondblclick() {if(this._resource.type===WI.Resource.Type.WebSocket) return;WI.openURL(this._resource.url);} _updateResource(resource) { if(this._resource){this._resource.removeEventListener(WI.Resource.Event.URLDidChange,this._urlDidChange,this);this._resource.removeEventListener(WI.Resource.Event.TypeDidChange,this._typeDidChange,this);this._resource.removeEventListener(WI.Resource.Event.LoadingDidFinish,this.updateStatus,this);this._resource.removeEventListener(WI.Resource.Event.LoadingDidFail,this._loadingDidFail,this);this._resource.removeEventListener(WI.Resource.Event.ResponseReceived,this._responseReceived,this);} this._updateSourceCode(resource);this._resource=resource;resource.addEventListener(WI.Resource.Event.URLDidChange,this._urlDidChange,this);resource.addEventListener(WI.Resource.Event.TypeDidChange,this._typeDidChange,this);resource.addEventListener(WI.Resource.Event.LoadingDidFinish,this.updateStatus,this);resource.addEventListener(WI.Resource.Event.LoadingDidFail,this._loadingDidFail,this);resource.addEventListener(WI.Resource.Event.ResponseReceived,this._responseReceived,this);this._updateTitles();this.updateStatus();this._updateToolTip();this._updateIcon();} get mainTitleText() {return WI.displayNameForURL(this._resource.url,this._resource.urlComponents,{allowDirectoryAsName:this._allowDirectoryAsName,});} _updateTitles() {var frame=this._resource.parentFrame;var target=this._resource.target;var isMainResource=this._resource.isMainResource();var parentResourceHost=target.mainResource?target.mainResource.urlComponents.host:null;if(isMainResource&&frame){parentResourceHost=frame.parentFrame?frame.parentFrame.mainResource.urlComponents.host:null;}else if(frame){parentResourceHost=frame.mainResource.urlComponents.host;} var urlComponents=this._resource.urlComponents;var oldMainTitle=this.mainTitle;this.mainTitle=this.mainTitleText;if(!this._hideOrigin){if(this._resource.localResourceOverride){if(WI.NetworkManager.supportsOverridingRequests()) this.subtitle=this._resource.localResourceOverride.displayType;else{let localResourceOverrideHost=urlComponents.host;let mainFrameHost=(WI.networkManager.mainFrame&&WI.networkManager.mainFrame.mainResource)?WI.networkManager.mainFrame.mainResource.urlComponents.host:null;let subtitle=localResourceOverrideHost!==mainFrameHost?localResourceOverrideHost:null;this.subtitle=this.mainTitle!==subtitle?subtitle:null;}}else{let subtitle=(parentResourceHost!==urlComponents.host||(frame&&frame.isMainFrame()&&isMainResource))?WI.displayNameForHost(urlComponents.host):null;this.subtitle=this.mainTitle!==subtitle?subtitle:null;}} if(oldMainTitle!==this.mainTitle) this.callFirstAncestorFunction("descendantResourceTreeElementMainTitleDidChange",[this,oldMainTitle]);} updateStatus() {super.updateStatus();if(!this._resource) return;if(this._resource.hadLoadingError()) this.addClassName(WI.ResourceTreeElement.FailedStyleClassName);else this.removeClassName(WI.ResourceTreeElement.FailedStyleClassName);if(this._resource.isLoading()){if(!this.status||!this.status[WI.ResourceTreeElement.SpinnerSymbol]){let spinner=new WI.IndeterminateProgressSpinner;if(this.status) this.statusElement.insertAdjacentElement("afterbegin",spinner.element);else this.status=spinner.element;this.status[WI.ResourceTreeElement.SpinnerSymbol]=spinner.element;}}else{if(this.status&&this.status[WI.ResourceTreeElement.SpinnerSymbol]){if(this.status===this.status[WI.ResourceTreeElement.SpinnerSymbol]) this.status=null;else{this.status[WI.ResourceTreeElement.SpinnerSymbol].remove();this.status[WI.ResourceTreeElement.SpinnerSymbol]=null;}}}} populateContextMenu(contextMenu,event) {WI.appendContextMenuItemsForSourceCode(contextMenu,this._resource);super.populateContextMenu(contextMenu,event);} _updateToolTip() {this.tooltip=this._resource.displayURL;} _updateIcon() {let localResourceOverride=this._resource.localResourceOverride||WI.networkManager.localResourceOverridesForURL(this._resource.url).filter((localResourceOverride)=>!localResourceOverride.disabled)[0];let isOverride=!!this._resource.localResourceOverride;let wasOverridden=this._resource.responseSource===WI.Resource.ResponseSource.InspectorOverride;let shouldBeOverridden=this._resource.isLoading()&&localResourceOverride;let shouldBeBlocked=(this._resource.failed||isOverride)&&localResourceOverride?.type===WI.LocalResourceOverride.InterceptType.Block;if(isOverride||wasOverridden||shouldBeOverridden||shouldBeBlocked){this.addClassName("override");if(shouldBeBlocked||localResourceOverride?.type===WI.LocalResourceOverride.InterceptType.ResponseSkippingNetwork) this.addClassName("skip-network");if(localResourceOverride?.localResource.mappedFilePath) this.addClassName("mapped-file");}else{this.removeClassName("override");this.removeClassName("skip-network");this.removeClassName("mapped-file");} if(wasOverridden) this.iconElement.title=WI.UIString("This resource was loaded from a local override");else if(shouldBeBlocked) this.iconElement.title=WI.UIString("This resource was blocked by a local override");else this.iconElement.title="";} _urlDidChange(event) {this._updateTitles();this._updateToolTip();} _typeDidChange(event) {this.removeClassName(event.data.oldType);this.addClassName(this._resource.type);this.callFirstAncestorFunction("descendantResourceTreeElementTypeDidChange",[this,event.data.oldType]);} _loadingDidFail(event) {this.updateStatus();this._updateIcon();} _responseReceived(event) {this._updateIcon();}};WI.ResourceTreeElement.ResourceIconStyleClassName="resource-icon";WI.ResourceTreeElement.FailedStyleClassName="failed";WI.ResourceTreeElement.SpinnerSymbol=Symbol("spinner");WI.ScriptTreeElement=class ScriptTreeElement extends WI.SourceCodeTreeElement {constructor(script,options={}) {let scriptDisplayName=script.displayName;let title=options.mainTitle||scriptDisplayName;let subtitle=null;let tooltip=null;let classNames=["script"];if(script.url&&!script.dynamicallyAddedScriptElement){if(script.urlComponents.scheme!=="web-inspector"){let host=WI.displayNameForHost(script.urlComponents.host);if(host&&title!==host) subtitle=host;else if(scriptDisplayName&&title!==scriptDisplayName) subtitle=scriptDisplayName;tooltip=script.url;} classNames.push(WI.ResourceTreeElement.ResourceIconStyleClassName);classNames.push(WI.Resource.Type.Script);}else classNames.push(WI.ScriptTreeElement.AnonymousScriptIconStyleClassName);if(script.isMainResource()){classNames.push("worker-icon");} super(script,classNames,title,subtitle);this._script=script;if(tooltip) this.tooltip=tooltip;} get script() {return this._script;}};WI.ScriptTreeElement.AnonymousScriptIconStyleClassName="anonymous-script-icon";WI.SearchTabContentView=class SearchTabContentView extends WI.ContentBrowserTabContentView {constructor() {let detailsSidebarPanelConstructors=[WI.ResourceDetailsSidebarPanel,WI.ProbeDetailsSidebarPanel,WI.DOMNodeDetailsSidebarPanel,WI.ComputedStyleDetailsSidebarPanel,WI.RulesStyleDetailsSidebarPanel,];if(InspectorBackend.hasDomain("LayerTree")) detailsSidebarPanelConstructors.push(WI.LayerTreeDetailsSidebarPanel);super(SearchTabContentView.tabInfo(),{navigationSidebarPanelConstructor:WI.SearchSidebarPanel,detailsSidebarPanelConstructors,});this._forcePerformSearch=false;} static tabInfo() {return{identifier:SearchTabContentView.Type,image:"Images/Search.svg",displayName:WI.UIString("Search","Search Tab Name","Name of Search Tab"),title:WI.UIString("Search (%s)","Search Tab Title","Title of Search Tab with keyboard shortcut").format(WI.searchKeyboardShortcut.displayName),};} static shouldPinTab() {return true;} static shouldSaveTab() {return false;} get type() {return WI.SearchTabContentView.Type;} attached() {super.attached();setTimeout(this.focusSearchField.bind(this));} canShowRepresentedObject(representedObject) {if(representedObject instanceof WI.DOMTree) return true;if(!(representedObject instanceof WI.Resource)&&!(representedObject instanceof WI.Script)) return false;return!!this.navigationSidebarPanel.contentTreeOutline.getCachedTreeElement(representedObject);} focusSearchField() {this.navigationSidebarPanel.focusSearchField(this._forcePerformSearch);this._forcePerformSearch=false;} performSearch(searchQuery) {this.navigationSidebarPanel.performSearch(searchQuery);this._forcePerformSearch=false;} handleCopyEvent(event) {let contentTreeOutline=this.navigationSidebarPanel.contentTreeOutline;if(contentTreeOutline.element!==document.activeElement) return;let selectedTreeElement=contentTreeOutline.selectedTreeElement;if(!selectedTreeElement) return;event.clipboardData.setData("text/plain",selectedTreeElement.synthesizedTextValue);event.stopPropagation();event.preventDefault();} initialLayout() {super.initialLayout();this._forcePerformSearch=true;}};WI.SearchTabContentView.Type="search";WI.SettingsTabContentView=class SettingsTabContentView extends WI.TabContentView {constructor() {super(SettingsTabContentView.tabInfo());this._selectedSettingsView=null;this._settingsViews=[];} static tabInfo() {return{identifier:SettingsTabContentView.Type,image:"Images/Gear.svg",displayName:WI.UIString("Settings","Settings Tab Name","Name of Settings Tab"),title:WI.UIString("Settings (%s)","Settings Tab Title","Title of Settings Tab with keyboard shortcut").format(WI.settingsKeyboardShortcut.displayName),};} static shouldPinTab() {return true;} static shouldSaveTab() {return false;} get type(){return WI.SettingsTabContentView.Type;} get supportsSplitContentBrowser() {return false;} get selectedSettingsView() {return this._selectedSettingsView;} set selectedSettingsView(settingsView) {if(this._selectedSettingsView===settingsView) return;if(this._selectedSettingsView) this.replaceSubview(this._selectedSettingsView,settingsView);else this.addSubview(settingsView);this._selectedSettingsView=settingsView;this._selectedSettingsView.updateLayout();let navigationItem=this._navigationBar.findNavigationItem(settingsView.identifier);if(!navigationItem) return;this._navigationBar.selectedNavigationItem=navigationItem;} addSettingsView(settingsView) {if(this._settingsViews.includes(settingsView)){return;} this._settingsViews.push(settingsView);this._navigationBar.addNavigationItem(new WI.RadioButtonNavigationItem(settingsView.identifier,settingsView.displayName));this._updateNavigationBarVisibility();} setSettingsViewVisible(settingsView,visible) {let navigationItem=this._navigationBar.findNavigationItem(settingsView.identifier);if(!navigationItem) return;if(navigationItem.hidden===!visible) return;navigationItem.hidden=!visible;settingsView.element.classList.toggle("hidden",!visible);this._updateNavigationBarVisibility();if(!this.selectedSettingsView){if(visible) this.selectedSettingsView=settingsView;return;} if(this.selectedSettingsView!==settingsView) return;let index=this._settingsViews.indexOf(settingsView);if(index===-1) return;let previousIndex=index;while(--previousIndex>=0){let previousNavigationItem=this._navigationBar.navigationItems[previousIndex];if(!previousNavigationItem||previousNavigationItem.hidden) continue;this.selectedSettingsView=this._settingsViews[previousIndex];return;} let nextIndex=index;while(++nextIndex[level,Number.percentageString(level,0)]);let zoomEditor=generalSettingsView.addGroupWithCustomSetting(WI.UIString("Zoom:"),WI.SettingEditor.Type.Select,{values:zoomValues});zoomEditor.value=WI.getZoomFactor();zoomEditor.addEventListener(WI.SettingEditor.Event.ValueDidChange,function(event){WI.setZoomFactor(this.value);},zoomEditor);WI.settings.zoomFactor.addEventListener(WI.Setting.Event.Changed,function(event){this.value=WI.getZoomFactor().maxDecimals(2);},zoomEditor);this._createReferenceLink(generalSettingsView);this.addSettingsView(generalSettingsView);} _createElementsSettingsView() {if(!InspectorBackend.hasDomain("DOM")) return;let elementsSettingsView=new WI.SettingsView("elements",WI.UIString("Elements"));console.log(InspectorBackend.Enum.CSS);if(InspectorBackend.Enum.CSS?.LayoutFlag?.Rendered){elementsSettingsView.addSetting(WI.UIString("DOM Tree:"),WI.settings.domTreeDeemphasizesNodesThatAreNotRendered,WI.UIString("De-emphasize nodes that are not rendered"));elementsSettingsView.addSeparator();} if(InspectorBackend.hasCommand("DOM.setInspectModeEnabled","showRulers")){let elementSelectionGroup=elementsSettingsView.addGroup(WI.UIString("Element Selection:"));elementSelectionGroup.addSetting(WI.settings.showRulersDuringElementSelection,WI.UIString("Show page rulers and node border lines"));elementSelectionGroup.addSetting(WI.settings.showFlexOverlayDuringElementSelection,WI.UIString("Show grid overlay"));elementSelectionGroup.addSetting(WI.settings.showGridOverlayDuringElementSelection,WI.UIString("Show flexbox overlay"));elementsSettingsView.addSeparator();} elementsSettingsView.addSetting(WI.UIString("Details Sidebars:","Details Sidebars: @ Settings Elements Pane","Category label for detail sidebar settings."),WI.settings.enableElementsTabIndependentStylesDetailsSidebarPanel,WI.UIString("Show independent Styles sidebar","Show independent Styles sidebar @ Settings Elements Pane","Settings tab checkbox label for whether the independent styles sidebar should be shown"));elementsSettingsView.addSeparator();let cssGroup=elementsSettingsView.addGroup(WI.UIString("CSS:"));cssGroup.addSetting(WI.settings.cssChangesPerNode,WI.UIString("Show changes only for selected node"));cssGroup.addSetting(WI.settings.showCSSPropertySyntaxInDocumentationPopover,WI.UIString("Show property syntax in documentation popover"));this._createReferenceLink(elementsSettingsView);this.addSettingsView(elementsSettingsView);} _createSourcesSettingsView() {let sourcesSettingsView=new WI.SettingsView("sources",WI.UIString("Sources"));sourcesSettingsView.addSetting(WI.UIString("Debugging:"),WI.settings.showScopeChainOnPause,WI.UIString("Show Scope Chain on pause"));sourcesSettingsView.addSeparator();sourcesSettingsView.addSetting(WI.UIString("Source Maps:"),WI.settings.sourceMapsEnabled,WI.UIString("Enable source maps"));sourcesSettingsView.addSeparator();sourcesSettingsView.addSetting(WI.UIString("Images:"),WI.settings.showImageGrid,WI.UIString("Show transparency grid","Show transparency grid (settings label)","Settings tab checkbox label for whether the transparency grid is shown by default"));this._createReferenceLink(sourcesSettingsView);this.addSettingsView(sourcesSettingsView);} _createConsoleSettingsView() {let consoleSettingsView=new WI.SettingsView("console",WI.UIString("Console"));if(InspectorBackend.hasCommand("Runtime.setSavedResultAlias")){let consoleSavedResultAliasEditor=consoleSettingsView.addGroupWithCustomEditor(WI.UIString("Saved Result Alias:"));let consoleSavedResultAliasInput=consoleSavedResultAliasEditor.appendChild(document.createElement("input"));consoleSavedResultAliasInput.spellcheck=false;consoleSavedResultAliasInput.value=WI.settings.consoleSavedResultAlias.value;consoleSavedResultAliasInput.placeholder=WI.unlocalizedString("$");consoleSavedResultAliasInput.addEventListener("keydown",(event)=>{if(!/[a-zA-Z0-9_$]/.test(event.key)||(consoleSavedResultAliasInput.selectionStart===0&&/[0-9]/.test(event.key))){event.preventDefault();InspectorFrontendHost.beep();}});consoleSavedResultAliasInput.addEventListener("input",(event)=>{let savedResultAlias=consoleSavedResultAliasInput.value;if(savedResultAlias==="$") savedResultAlias="";WI.settings.consoleSavedResultAlias.value=savedResultAlias;});consoleSettingsView.addSeparator();} consoleSettingsView.addSetting(WI.UIString("Traces:"),WI.settings.consoleAutoExpandTrace,WI.UIString("Auto-expand"));consoleSettingsView.addSetting(WI.UIString("Show:"),WI.settings.showConsoleMessageTimestamps,WI.UIString("Timestamps"));if(WI.ConsoleManager.supportsLogChannels()){consoleSettingsView.addSeparator();const logLevels=[[WI.LoggingChannel.Level.Off,WI.UIString("Off")],[WI.LoggingChannel.Level.Basic,WI.UIString("Basic")],[WI.LoggingChannel.Level.Verbose,WI.UIString("Verbose")],];const editorLabels={[WI.ConsoleMessage.MessageSource.Media]:WI.UIString("Media Logging:"),[WI.ConsoleMessage.MessageSource.MediaSource]:WI.UIString("MSE Logging:"),[WI.ConsoleMessage.MessageSource.WebRTC]:WI.UIString("WebRTC Logging:"),};let channels=WI.consoleManager.customLoggingChannels;for(let channel of channels){let label=editorLabels[channel.source];if(!label) continue;let logEditor=consoleSettingsView.addGroupWithCustomSetting(label,WI.SettingEditor.Type.Select,{values:logLevels});logEditor.value=channel.level;logEditor.addEventListener(WI.SettingEditor.Event.ValueDidChange,function(event){for(let target of WI.targets) target.ConsoleAgent.setLoggingChannelLevel(channel.source,this.value);},logEditor);}} this._createReferenceLink(consoleSettingsView);this.addSettingsView(consoleSettingsView);} _createExperimentalSettingsView() {let experimentalSettingsView=new WI.SettingsView("experimental",WI.UIString("Experimental"));let initialValues=new Map;let consoleGroup=experimentalSettingsView.addGroup(WI.UIString("Console:"));consoleGroup.addSetting(WI.settings.experimentalGroupSourceMapErrors,WI.UIString("Group source map network errors"));experimentalSettingsView.addSeparator();let hasCSSDomain=InspectorBackend.hasDomain("CSS");if(hasCSSDomain){let stylesGroup=experimentalSettingsView.addGroup(WI.UIString("Styles:"));stylesGroup.addSetting(WI.settings.experimentalEnableStylesJumpToEffective,WI.UIString("Show jump to effective property button"));stylesGroup.addSetting(WI.settings.experimentalEnableStylesJumpToVariableDeclaration,WI.UIString("Show jump to variable declaration button"));stylesGroup.addSetting(WI.settings.experimentalCSSSortPropertyNameAutocompletionByUsage,WI.UIString("Suggest property names based on usage"));experimentalSettingsView.addSeparator();} let hasNetworkEmulatedCondition=InspectorBackend.hasCommand("Network.setEmulatedConditions");if(hasNetworkEmulatedCondition){let networkGroup=experimentalSettingsView.addGroup(WI.UIString("Network:"));networkGroup.addSetting(WI.settings.experimentalEnableNetworkEmulatedCondition,WI.UIString("Allow throttling","Label for checkbox that controls whether network throttling functionality is enabled."));experimentalSettingsView.addSeparator();} let sourcesGroup=experimentalSettingsView.addGroup(WI.UIString("Sources:"));sourcesGroup.addSetting(WI.settings.experimentalLimitSourceCodeHighlighting,WI.UIString("Limit syntax highlighting on long lines of code"));experimentalSettingsView.addSeparator();let diagnosticsGroup=experimentalSettingsView.addGroup(WI.UIString("Diagnostics:","Diagnostics: @ Experimental Settings","Category label for experimental settings related to Web Inspector diagnostics."));diagnosticsGroup.addSetting(WI.settings.experimentalAllowInspectingInspector,WI.UIString("Allow Inspecting Web Inspector","Allow Inspecting Web Inspector @ Experimental Settings","Label for setting that allows the user to inspect the Web Inspector user interface."));experimentalSettingsView.addSeparator();let reloadInspectorButton=document.createElement("button");reloadInspectorButton.textContent=WI.UIString("Reload Web Inspector");reloadInspectorButton.addEventListener("click",(event)=>{InspectorFrontendHost.reopen();});let reloadInspectorContainerElement=experimentalSettingsView.addCenteredContainer(reloadInspectorButton,WI.UIString("for changes to take effect"));reloadInspectorContainerElement.classList.add("hidden");function listenForChange(setting){initialValues.set(setting,setting.value);setting.addEventListener(WI.Setting.Event.Changed,function(event){this.classList.toggle("hidden",Array.from(initialValues).every(([setting,initialValue])=>setting.value===initialValue));},reloadInspectorContainerElement);} if(hasCSSDomain){listenForChange(WI.settings.experimentalEnableStylesJumpToEffective);listenForChange(WI.settings.experimentalEnableStylesJumpToVariableDeclaration);} if(hasNetworkEmulatedCondition) listenForChange(WI.settings.experimentalEnableNetworkEmulatedCondition);listenForChange(WI.settings.experimentalLimitSourceCodeHighlighting);this._createReferenceLink(experimentalSettingsView);this.addSettingsView(experimentalSettingsView);} _createEngineeringSettingsView() {let engineeringSettingsView=new WI.SettingsView("engineering",WI.unlocalizedString("Engineering"));let elementsGroup=engineeringSettingsView.addGroup(WI.unlocalizedString("Elements:"));elementsGroup.addSetting(WI.settings.engineeringAllowEditingUserAgentShadowTrees,WI.unlocalizedString("Allow editing UserAgent shadow trees"));engineeringSettingsView.addSeparator();let debuggingGroup=engineeringSettingsView.addGroup(WI.unlocalizedString("Debugging:"));debuggingGroup.addSetting(WI.settings.engineeringShowInternalExecutionContexts,WI.unlocalizedString("Show WebKit-internal execution contexts"));debuggingGroup.addSetting(WI.settings.engineeringShowInternalScripts,WI.unlocalizedString("Show WebKit-internal scripts"));debuggingGroup.addSetting(WI.settings.engineeringPauseForInternalScripts,WI.unlocalizedString("Pause in WebKit-internal scripts"));engineeringSettingsView.addSeparator();let heapSnapshotGroup=engineeringSettingsView.addGroup(WI.unlocalizedString("Heap Snapshot:"));heapSnapshotGroup.addSetting(WI.settings.engineeringShowInternalObjectsInHeapSnapshot,WI.unlocalizedString("Show Internal Objects"));heapSnapshotGroup.addSetting(WI.settings.engineeringShowPrivateSymbolsInHeapSnapshot,WI.unlocalizedString("Show Private Symbols"));this.addSettingsView(engineeringSettingsView);} _createDebugSettingsView() {if(this._debugSettingsView) return;this._debugSettingsView=new WI.SettingsView("debug",WI.unlocalizedString("Debug"));let protocolMessagesGroup=this._debugSettingsView.addGroup(WI.unlocalizedString("Protocol Logging:"));let protocolAutoLogMessagesEditor=protocolMessagesGroup.addSetting(WI.settings.protocolAutoLogMessages,WI.unlocalizedString("Messages"));WI.settings.protocolAutoLogMessages.addEventListener(WI.Setting.Event.Changed,function(event){this.value=InspectorBackend.dumpInspectorProtocolMessages;},protocolAutoLogMessagesEditor);protocolMessagesGroup.addSetting(WI.settings.protocolAutoLogTimeStats,WI.unlocalizedString("Time Stats"));protocolMessagesGroup.addSetting(WI.settings.protocolLogAsText,WI.unlocalizedString("Log as Text"));this._debugSettingsView.addSeparator();let debuggingGroup=this._debugSettingsView.addGroup(WI.unlocalizedString("Debugging:"));debuggingGroup.addSetting(WI.settings.debugShowConsoleEvaluations,WI.unlocalizedString("Show Console Evaluations"));debuggingGroup.addSetting(WI.settings.debugOutlineFocusedElement,WI.unlocalizedString("Outline focused element"));this._debugSettingsView.addSeparator();this._debugSettingsView.addSetting(WI.unlocalizedString("Layout Flashing:"),WI.settings.debugEnableLayoutFlashing,WI.unlocalizedString("Draw borders when a view performs a layout"));this._debugSettingsView.addSeparator();this._debugSettingsView.addSetting(WI.unlocalizedString("Styles:"),WI.settings.debugEnableStyleEditingDebugMode,WI.unlocalizedString("Enable style editing debug mode"));this._debugSettingsView.addSeparator();let diagnosticsGroup=this._debugSettingsView.addGroup(WI.unlocalizedString("Diagnostics:"));diagnosticsGroup.addSetting(WI.settings.debugEnableUncaughtExceptionReporter,WI.unlocalizedString("Report Uncaught Exceptions"));diagnosticsGroup.addSetting(WI.settings.debugEnableDiagnosticLogging,WI.unlocalizedString("Enable Diagnostic Logging"));diagnosticsGroup.addSetting(WI.settings.debugAutoLogDiagnosticEvents,WI.unlocalizedString("Show Diagnostic Events in Console"));this._debugSettingsView.addSeparator();const layoutDirectionValues=[[WI.LayoutDirection.System,WI.unlocalizedString("System Default")],[WI.LayoutDirection.LTR,WI.unlocalizedString("Left to Right (LTR)")],[WI.LayoutDirection.RTL,WI.unlocalizedString("Right to Left (RTL)")],];let layoutDirectionEditor=this._debugSettingsView.addGroupWithCustomSetting(WI.unlocalizedString("Layout Direction:"),WI.SettingEditor.Type.Select,{values:layoutDirectionValues});layoutDirectionEditor.value=WI.settings.debugLayoutDirection.value;layoutDirectionEditor.addEventListener(WI.SettingEditor.Event.ValueDidChange,function(event){WI.setLayoutDirection(this.value);},layoutDirectionEditor);this._debugSettingsView.addSeparator();let extensionsGroup=this._debugSettingsView.addGroup(WI.unlocalizedString("Web Extensions:"));extensionsGroup.addSetting(WI.settings.debugShowMockWebExtensionTab,WI.unlocalizedString("Show Mock Web Extension tab"));this._debugSettingsView.addSeparator();let resetInspectorButton=document.createElement("button");resetInspectorButton.textContent=WI.unlocalizedString("Reset Web Inspector");resetInspectorButton.addEventListener("click",(event)=>{WI.reset();});this._debugSettingsView.addCenteredContainer(resetInspectorButton);this.addSettingsView(this._debugSettingsView);} _createReferenceLink(settingsView) {let link=document.createElement("a");link.href=link.title="https://webkit.org/web-inspector/web-inspector-settings/#"+settingsView.identifier;link.textContent=WI.UIString("Web Inspector Reference");link.appendChild(WI.createGoToArrowButton());let container=settingsView.addCenteredContainer(link);container.classList.add("reference");} _updateNavigationBarVisibility() {let visibleItems=0;for(let item of this._navigationBar.navigationItems){if(!item.hidden&&++visibleItems>1){this._navigationBar.element.classList.remove("invisible");return;}} this._navigationBar.element.classList.add("invisible");} _navigationItemSelected(event) {let navigationItem=event.target.selectedNavigationItem;if(!navigationItem) return;let settingsView=this._settingsViews.find((view)=>view.identifier===navigationItem.identifier);if(!settingsView) return;this.selectedSettingsView=settingsView;} _updateDebugSettingsViewVisibility() {if(WI.isDebugUIEnabled()) this._createDebugSettingsView();if(!this._debugSettingsView) return;this.setSettingsViewVisible(this._debugSettingsView,WI.isDebugUIEnabled());this.needsLayout();}};WI.SettingsTabContentView.Type="settings";WI.SourcesTabContentView=class SourcesTabContentView extends WI.ContentBrowserTabContentView {constructor() {super(SourcesTabContentView.tabInfo(),{navigationSidebarPanelConstructor:WI.SourcesNavigationSidebarPanel,detailsSidebarPanelConstructors:[WI.ResourceDetailsSidebarPanel,WI.ScopeChainDetailsSidebarPanel,WI.ProbeDetailsSidebarPanel,],});this._showScopeChainDetailsSidebarPanel=false;WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.Paused,this._handleDebuggerPaused,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.Resumed,this._handleDebuggerResumed,this);} static tabInfo() {return{identifier:SourcesTabContentView.Type,image:WI.debuggerManager.paused?"Images/SourcesPaused.svg":"Images/Sources.svg",title:WI.debuggerManager.paused?WI.UIString("JavaScript execution is paused"):"",displayName:WI.UIString("Sources","Sources Tab Name","Name of Sources Tab"),};} get type() {return WI.SourcesTabContentView.Type;} get supportsSplitContentBrowser() {return true;} canShowRepresentedObject(representedObject) {return representedObject instanceof WI.Frame||representedObject instanceof WI.FrameCollection||representedObject instanceof WI.Resource||representedObject instanceof WI.ResourceCollection||representedObject instanceof WI.Script||representedObject instanceof WI.ScriptCollection||representedObject instanceof WI.CSSStyleSheet||representedObject instanceof WI.CSSStyleSheetCollection||representedObject instanceof WI.LocalResourceOverride||super.canShowRepresentedObject(representedObject);} showDetailsSidebarPanels() {super.showDetailsSidebarPanels();if(!this._showScopeChainDetailsSidebarPanel) return;let scopeChainDetailsSidebarPanel=this.detailsSidebarPanels.find((item)=>item instanceof WI.ScopeChainDetailsSidebarPanel);if(!scopeChainDetailsSidebarPanel) return;WI.detailsSidebar.selectedSidebarPanel=scopeChainDetailsSidebarPanel;WI.detailsSidebar.collapsed=false;this._showScopeChainDetailsSidebarPanel=false;} showScopeChainDetailsSidebarPanel() {this._showScopeChainDetailsSidebarPanel=true;} revealAndSelectRepresentedObject(representedObject) {let treeElement=this.navigationSidebarPanel.treeElementForRepresentedObject(representedObject);if(treeElement){const omitFocus=false;const selectedByUser=true;treeElement.revealAndSelect(omitFocus,selectedByUser);}} handleCopyEvent(event) {if(this.navigationSidebarPanel.element.contains(WI.currentFocusElement)) this.navigationSidebarPanel.handleCopyEvent(event);} _handleDebuggerPaused(event) {this.tabBarItem.image="Images/SourcesPaused.svg";this.tabBarItem.title=WI.UIString("JavaScript execution is paused");} _handleDebuggerResumed(event) {this.tabBarItem.image="Images/Sources.svg";this.tabBarItem.title="";}};WI.SourcesTabContentView.Type="sources";WI.StorageTabContentView=class StorageTabContentView extends WI.ContentBrowserTabContentView {constructor() {super(StorageTabContentView.tabInfo(),{navigationSidebarPanelConstructor:WI.StorageSidebarPanel,detailsSidebarPanelConstructors:[WI.ApplicationCacheDetailsSidebarPanel,WI.IndexedDatabaseDetailsSidebarPanel,],});WI.applicationCacheManager.enable();WI.databaseManager.enable();WI.domStorageManager.enable();WI.indexedDBManager.enable();} static tabInfo() {return{identifier:StorageTabContentView.Type,image:"Images/Storage.svg",displayName:WI.UIString("Storage","Storage Tab Name","Name of Storage Tab"),};} static isTabAllowed() {return InspectorBackend.hasDomain("ApplicationCache")||InspectorBackend.hasDomain("DOMStorage")||InspectorBackend.hasDomain("Database")||InspectorBackend.hasDomain("IndexedDB");} get type() {return WI.StorageTabContentView.Type;} get supportsSplitContentBrowser() {return true;} canShowRepresentedObject(representedObject) {return representedObject instanceof WI.ApplicationCacheFrame||representedObject instanceof WI.CookieStorageObject||representedObject instanceof WI.DOMStorageObject||representedObject instanceof WI.DatabaseObject||representedObject instanceof WI.DatabaseTableObject||representedObject instanceof WI.IndexedDatabase||representedObject instanceof WI.IndexedDatabaseObjectStore||representedObject instanceof WI.IndexedDatabaseObjectStoreIndex;} get canHandleFindEvent() {return this.contentBrowser.currentContentView.canFocusFilterBar;} handleFindEvent(event) {this.contentBrowser.currentContentView.focusFilterBar();} closed() {WI.applicationCacheManager.disable();WI.databaseManager.disable();WI.domStorageManager.disable();WI.indexedDBManager.disable();super.closed();}};WI.StorageTabContentView.Type="storage";WI.TimelineTabContentView=class TimelineTabContentView extends WI.ContentBrowserTabContentView {constructor() {super(TimelineTabContentView.tabInfo());this._recordingTreeElementMap=new Map;this._recordingsTreeOutline=new WI.TreeOutline;this._recordingsTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._recordingsTreeSelectionDidChange,this);this._toggleRecordingShortcut=new WI.KeyboardShortcut(null,WI.KeyboardShortcut.Key.Space,this._toggleRecordingOnSpacebar.bind(this));this._toggleRecordingShortcut.implicitlyPreventsDefault=false;this._toggleRecordingShortcut.disabled=true;this._toggleNewRecordingShortcut=new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Shift,WI.KeyboardShortcut.Key.Space,this._toggleNewRecordingOnSpacebar.bind(this));this._toggleNewRecordingShortcut.implicitlyPreventsDefault=false;this._toggleNewRecordingShortcut.disabled=true;let toolTip=WI.UIString("Start recording (%s)\nCreate new recording (%s)").format(this._toggleRecordingShortcut.displayName,this._toggleNewRecordingShortcut.displayName);let altToolTip=WI.UIString("Stop recording (%s)").format(this._toggleRecordingShortcut.displayName);this._recordButton=new WI.ToggleButtonNavigationItem("record-start-stop",toolTip,altToolTip,"Images/Record.svg","Images/Stop.svg",13,13);this._recordButton.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._recordButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._recordButtonClicked,this);this._recordStoppingSpinner=new WI.IndeterminateProgressSpinnerNavigationItem("record-stopping",WI.UIString("Stopping recording"));this._recordStoppingSpinner.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._recordStoppingSpinner.hidden=true;this._continueButton=new WI.ButtonNavigationItem("record-continue",WI.UIString("Continue without automatically stopping"),"Images/Resume.svg",13,13);this._continueButton.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._continueButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._continueButtonClicked,this);this._continueButton.hidden=true;this.contentBrowser.navigationBar.insertNavigationItem(this._recordButton,0);this.contentBrowser.navigationBar.insertNavigationItem(this._recordStoppingSpinner,1);this.contentBrowser.navigationBar.insertNavigationItem(this._continueButton,2);if(WI.sharedApp.isWebDebuggable()){let timelinesNavigationItem=new WI.RadioButtonNavigationItem(WI.TimelineOverview.ViewMode.Timelines,WI.UIString("Events"));let renderingFramesNavigationItem=new WI.RadioButtonNavigationItem(WI.TimelineOverview.ViewMode.RenderingFrames,WI.UIString("Frames"));let viewModeGroup=new WI.GroupNavigationItem([timelinesNavigationItem,renderingFramesNavigationItem]);viewModeGroup.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this.contentBrowser.navigationBar.insertNavigationItem(viewModeGroup,3);this.contentBrowser.navigationBar.addEventListener(WI.NavigationBar.Event.NavigationItemSelected,this._viewModeSelected,this);} WI.timelineManager.addEventListener(WI.TimelineManager.Event.CapturingStateChanged,this._handleTimelineCapturingStateChanged,this);WI.timelineManager.addEventListener(WI.TimelineManager.Event.RecordingCreated,this._recordingCreated,this);WI.timelineManager.addEventListener(WI.TimelineManager.Event.RecordingLoaded,this._recordingLoaded,this);WI.notifications.addEventListener(WI.Notification.VisibilityStateDidChange,this._inspectorVisibilityChanged,this);WI.notifications.addEventListener(WI.Notification.GlobalModifierKeysDidChange,this._globalModifierKeysDidChange,this);this._displayedRecording=null;this._displayedContentView=null;this._viewMode=null;this._previousSelectedTimelineType=null;const selectedByUser=false;this._changeViewMode(WI.TimelineOverview.ViewMode.Timelines,selectedByUser);WI.heapManager.enable();WI.memoryManager.enable();WI.timelineManager.enable();} static tabInfo() {return{identifier:TimelineTabContentView.Type,image:"Images/Timeline.svg",displayName:WI.UIString("Timelines","Timelines Tab Name","Name of Timelines Tab"),};} static isTabAllowed() {return InspectorBackend.hasDomain("Timeline")||InspectorBackend.hasDomain("ScriptProfiler");} static displayNameForTimelineType(timelineType) {switch(timelineType){case WI.TimelineRecord.Type.Network:return WI.UIString("Network Requests");case WI.TimelineRecord.Type.Layout:return WI.UIString("Layout & Rendering");case WI.TimelineRecord.Type.Script:return WI.UIString("JavaScript & Events");case WI.TimelineRecord.Type.RenderingFrame:return WI.UIString("Rendering Frames");case WI.TimelineRecord.Type.CPU:return WI.UIString("CPU");case WI.TimelineRecord.Type.Memory:return WI.UIString("Memory");case WI.TimelineRecord.Type.HeapAllocations:return WI.UIString("JavaScript Allocations");case WI.TimelineRecord.Type.Media:if(InspectorBackend.hasDomain("Animation")) return WI.UIString("Media & Animations");return WI.UIString("Media");case WI.TimelineRecord.Type.Screenshots:return WI.UIString("Screenshots");default:console.error("Unknown Timeline type:",timelineType);} return null;} static iconClassNameForTimelineType(timelineType) {switch(timelineType){case WI.TimelineRecord.Type.Network:return"network-icon";case WI.TimelineRecord.Type.Layout:return"layout-icon";case WI.TimelineRecord.Type.CPU:return"cpu-icon";case WI.TimelineRecord.Type.Memory:return"memory-icon";case WI.TimelineRecord.Type.HeapAllocations:return"heap-allocations-icon";case WI.TimelineRecord.Type.Script:return"script-icon";case WI.TimelineRecord.Type.RenderingFrame:return"rendering-frame-icon";case WI.TimelineRecord.Type.Media:return"media-icon";case WI.TimelineRecord.Type.Screenshots:return"screenshots-icon";default:console.error("Unknown Timeline type:",timelineType);} return null;} static genericClassNameForTimelineType(timelineType) {switch(timelineType){case WI.TimelineRecord.Type.Network:return"network";case WI.TimelineRecord.Type.Layout:return"colors";case WI.TimelineRecord.Type.CPU:return"cpu";case WI.TimelineRecord.Type.Memory:return"memory";case WI.TimelineRecord.Type.HeapAllocations:return"heap-allocations";case WI.TimelineRecord.Type.Script:return"script";case WI.TimelineRecord.Type.RenderingFrame:return"rendering-frame";case WI.TimelineRecord.Type.Media:return"media";case WI.TimelineRecord.Type.Screenshots:return"screenshots";default:console.error("Unknown Timeline type:",timelineType);} return null;} static iconClassNameForRecord(timelineRecord) {switch(timelineRecord.type){case WI.TimelineRecord.Type.Layout:switch(timelineRecord.eventType){case WI.LayoutTimelineRecord.EventType.InvalidateStyles:case WI.LayoutTimelineRecord.EventType.RecalculateStyles:return WI.TimelineRecordTreeElement.StyleRecordIconStyleClass;case WI.LayoutTimelineRecord.EventType.InvalidateLayout:case WI.LayoutTimelineRecord.EventType.ForcedLayout:case WI.LayoutTimelineRecord.EventType.Layout:return WI.TimelineRecordTreeElement.LayoutRecordIconStyleClass;case WI.LayoutTimelineRecord.EventType.Paint:return WI.TimelineRecordTreeElement.PaintRecordIconStyleClass;case WI.LayoutTimelineRecord.EventType.Composite:return WI.TimelineRecordTreeElement.CompositeRecordIconStyleClass;default:console.error("Unknown LayoutTimelineRecord eventType: "+timelineRecord.eventType,timelineRecord);} break;case WI.TimelineRecord.Type.Script:switch(timelineRecord.eventType){case WI.ScriptTimelineRecord.EventType.APIScriptEvaluated:return WI.TimelineRecordTreeElement.APIRecordIconStyleClass;case WI.ScriptTimelineRecord.EventType.ScriptEvaluated:return WI.TimelineRecordTreeElement.EvaluatedRecordIconStyleClass;case WI.ScriptTimelineRecord.EventType.MicrotaskDispatched:case WI.ScriptTimelineRecord.EventType.EventDispatched:case WI.ScriptTimelineRecord.EventType.ObserverCallback:return WI.TimelineRecordTreeElement.EventRecordIconStyleClass;case WI.ScriptTimelineRecord.EventType.ProbeSampleRecorded:return WI.TimelineRecordTreeElement.ProbeRecordIconStyleClass;case WI.ScriptTimelineRecord.EventType.ConsoleProfileRecorded:return WI.TimelineRecordTreeElement.ConsoleProfileIconStyleClass;case WI.ScriptTimelineRecord.EventType.GarbageCollected:return WI.TimelineRecordTreeElement.GarbageCollectionIconStyleClass;case WI.ScriptTimelineRecord.EventType.TimerInstalled:return WI.TimelineRecordTreeElement.TimerRecordIconStyleClass;case WI.ScriptTimelineRecord.EventType.TimerFired:case WI.ScriptTimelineRecord.EventType.TimerRemoved:return WI.TimelineRecordTreeElement.TimerRecordIconStyleClass;case WI.ScriptTimelineRecord.EventType.AnimationFrameFired:case WI.ScriptTimelineRecord.EventType.AnimationFrameRequested:case WI.ScriptTimelineRecord.EventType.AnimationFrameCanceled:return"animation-frame-record";default:console.error("Unknown ScriptTimelineRecord eventType: "+timelineRecord.eventType,timelineRecord);} break;case WI.TimelineRecord.Type.RenderingFrame:return WI.TimelineRecordTreeElement.RenderingFrameRecordIconStyleClass;case WI.TimelineRecord.Type.HeapAllocations:return"heap-snapshot-record";case WI.TimelineRecord.Type.Media:switch(timelineRecord.eventType){case WI.MediaTimelineRecord.EventType.CSSAnimation:return"css-animation-record";case WI.MediaTimelineRecord.EventType.CSSTransition:return"css-transition-record";case WI.MediaTimelineRecord.EventType.MediaElement:return"media-element-record";default:console.error("Unknown MediaTimelineRecord eventType: "+timelineRecord.eventType,timelineRecord);} break;case WI.TimelineRecord.Type.CPU:case WI.TimelineRecord.Type.Memory:case WI.TimelineRecord.Type.Screenshots:default:console.error("Unknown TimelineRecord type: "+timelineRecord.type,timelineRecord);} return null;} static displayNameForRecord(timelineRecord,includeDetailsInMainTitle) {switch(timelineRecord.type){case WI.TimelineRecord.Type.Network:return WI.displayNameForURL(timelineRecord.resource.url,timelineRecord.resource.urlComponents);case WI.TimelineRecord.Type.Layout:return WI.LayoutTimelineRecord.displayNameForEventType(timelineRecord.eventType);case WI.TimelineRecord.Type.Script:return WI.ScriptTimelineRecord.EventType.displayName(timelineRecord.eventType,timelineRecord.details,includeDetailsInMainTitle);case WI.TimelineRecord.Type.RenderingFrame:if(timelineRecord.name) return WI.UIString("Frame %d \u2014 %s").format(timelineRecord.frameNumber,timelineRecord.name);return WI.UIString("Frame %d").format(timelineRecord.frameNumber);case WI.TimelineRecord.Type.HeapAllocations:if(timelineRecord.heapSnapshot.imported) return WI.UIString("Imported \u2014 %s").format(timelineRecord.heapSnapshot.title);if(timelineRecord.heapSnapshot.title) return WI.UIString("Snapshot %d \u2014 %s").format(timelineRecord.heapSnapshot.identifier,timelineRecord.heapSnapshot.title);return WI.UIString("Snapshot %d").format(timelineRecord.heapSnapshot.identifier);case WI.TimelineRecord.Type.Media:if(includeDetailsInMainTitle&&timelineRecord.subtitle) return timelineRecord.subtitle;return timelineRecord.displayName;case WI.TimelineRecord.Type.CPU:case WI.TimelineRecord.Type.Memory:case WI.TimelineRecord.Type.Screenshots:default:console.error("Unknown TimelineRecord type: "+timelineRecord.type,timelineRecord);} return null;} get type() {return WI.TimelineTabContentView.Type;} attached() {super.attached();this._toggleRecordingShortcut.disabled=false;this._toggleNewRecordingShortcut.disabled=false;if(WI.visible) WI.timelineManager.autoCaptureOnPageLoad=true;} detached() {this._toggleRecordingShortcut.disabled=true;this._toggleNewRecordingShortcut.disabled=true;WI.timelineManager.autoCaptureOnPageLoad=false;super.detached();} closed() {WI.timelineManager.disable();WI.memoryManager.disable();WI.heapManager.disable();if(WI.sharedApp.isWebDebuggable()) this.contentBrowser.navigationBar.removeEventListener(WI.NavigationBar.Event.NavigationItemSelected,this._viewModeSelected,this);WI.timelineManager.removeEventListener(WI.TimelineManager.Event.CapturingStateChanged,this._handleTimelineCapturingStateChanged,this);WI.timelineManager.removeEventListener(WI.TimelineManager.Event.RecordingCreated,this._recordingCreated,this);WI.timelineManager.removeEventListener(WI.TimelineManager.Event.RecordingLoaded,this._recordingLoaded,this);WI.notifications.removeEventListener(WI.Notification.VisibilityStateDidChange,this._inspectorVisibilityChanged,this);WI.notifications.removeEventListener(WI.Notification.GlobalModifierKeysDidChange,this._globalModifierKeysDidChange,this);super.closed();} canShowRepresentedObject(representedObject) {return representedObject instanceof WI.TimelineRecording;} get canHandleFindEvent() {return this._displayedContentView.canFocusFilterBar;} handleFindEvent(event) {this._displayedContentView.focusFilterBar();} dropZoneShouldAppearForDragEvent(dropZone,event) {return event.dataTransfer.types.includes("Files");} dropZoneHandleDrop(dropZone,event) {let files=event.dataTransfer.files;if(files.length!==1){InspectorFrontendHost.beep();return;} WI.FileUtilities.readJSON(files,(result)=>WI.timelineManager.processJSON(result));} initialLayout() {super.initialLayout();let dropZoneView=new WI.DropZoneView(this);dropZoneView.text=WI.UIString("Import Recording");dropZoneView.targetElement=this.element;this.addSubview(dropZoneView);} restoreFromCookie(cookie) {this._restoredShowingTimelineRecordingContentView=cookie[WI.TimelineTabContentView.ShowingTimelineRecordingContentViewCookieKey];if(!this._restoredShowingTimelineRecordingContentView){if(!this.contentBrowser.currentContentView){if(!this._displayedRecording&&WI.timelineManager.activeRecording) this._recordingLoaded();this._showTimelineViewForType(WI.TimelineTabContentView.OverviewTimelineIdentifierCookieValue);} return;} let selectedTimelineViewIdentifier=cookie[WI.TimelineTabContentView.SelectedTimelineViewIdentifierCookieKey];this._showTimelineViewForType(selectedTimelineViewIdentifier);super.restoreFromCookie(cookie);} saveToCookie(cookie) {cookie[WI.TimelineTabContentView.ShowingTimelineRecordingContentViewCookieKey]=this.contentBrowser.currentContentView instanceof WI.TimelineRecordingContentView;if(this._viewMode===WI.TimelineOverview.ViewMode.RenderingFrames) cookie[WI.TimelineTabContentView.SelectedTimelineViewIdentifierCookieKey]=WI.TimelineRecord.Type.RenderingFrame;else{let selectedTimeline=this._getTimelineForCurrentContentView();if(selectedTimeline) cookie[WI.TimelineTabContentView.SelectedTimelineViewIdentifierCookieKey]=selectedTimeline.type;else cookie[WI.TimelineTabContentView.SelectedTimelineViewIdentifierCookieKey]=WI.TimelineTabContentView.OverviewTimelineIdentifierCookieValue;} super.saveToCookie(cookie);} treeElementForRepresentedObject(representedObject) {if(!this._recordingTreeElementMap) return null;if(representedObject instanceof WI.TimelineRecording) return this._recordingTreeElementMap.get(representedObject);return null;} _showRecordButton() {this._recordButton.hidden=false;this._recordStoppingSpinner.hidden=true;this._continueButton.hidden=true;} _showRecordStoppingSpinner() {this._recordButton.hidden=true;this._recordStoppingSpinner.hidden=false;this._continueButton.hidden=true;} _showContinueButton() {this._recordButton.hidden=true;this._recordStoppingSpinner.hidden=true;this._continueButton.hidden=false;} _updateNavigationBarButtons() {if(WI.timelineManager.capturingState===WI.TimelineManager.CapturingState.Stopping) this._showRecordStoppingSpinner();else if(!WI.modifierKeys.altKey||!WI.timelineManager.willAutoStop()) this._showRecordButton();else this._showContinueButton();} _handleTimelineCapturingStateChanged(event) {let enabled=WI.timelineManager.capturingState===WI.TimelineManager.CapturingState.Active||WI.timelineManager.capturingState===WI.TimelineManager.CapturingState.Inactive;let stopping=WI.timelineManager.capturingState===WI.TimelineManager.CapturingState.Stopping;this._toggleRecordingShortcut.disabled=!enabled||stopping;this._toggleNewRecordingShortcut.disabled=!enabled||stopping;this._recordButton.toggled=WI.timelineManager.isCapturing();this._recordButton.enabled=enabled;this._updateNavigationBarButtons();} _inspectorVisibilityChanged(event) {WI.timelineManager.autoCaptureOnPageLoad=!!this.isAttached&&!!WI.visible;} _globalModifierKeysDidChange(event) {this._updateNavigationBarButtons();} _toggleRecordingOnSpacebar(event) {if(WI.timelineManager.activeRecording.readonly) return;if(WI.isEventTargetAnEditableField(event)) return;this._toggleRecording();event.preventDefault();} _toggleNewRecordingOnSpacebar(event) {if(WI.isEventTargetAnEditableField(event)) return;this._toggleRecording(true);event.preventDefault();} _toggleRecording(shouldCreateRecording) {let isCapturing=WI.timelineManager.isCapturing();this._recordButton.toggled=isCapturing;if(isCapturing) WI.timelineManager.stopCapturing();else{WI.timelineManager.startCapturing(shouldCreateRecording);this._recordingLoaded();}} _recordButtonClicked(event) {let shouldCreateNewRecording=window.event?window.event.shiftKey:false;if(WI.timelineManager.activeRecording.readonly) shouldCreateNewRecording=true;this._recordButton.toggled=!WI.timelineManager.isCapturing();this._toggleRecording(shouldCreateNewRecording);} _continueButtonClicked(event) {WI.timelineManager.relaxAutoStop();this._updateNavigationBarButtons();} _recordingsTreeSelectionDidChange(event) {let treeElement=this._recordingsTreeOutline.selectedTreeElement;if(!treeElement) return;this._recordingSelected(treeElement.representedObject);} _recordingCreated(event) {this._addRecording(event.data.recording);this._recordingCountChanged();} _addRecording(recording) {let recordingTreeElement=new WI.GeneralTreeElement(WI.TimelineTabContentView.StopwatchIconStyleClass,recording.displayName,null,recording);this._recordingTreeElementMap.set(recording,recordingTreeElement);this._recordingsTreeOutline.appendChild(recordingTreeElement);} _recordingCountChanged() {let previousTreeElement=null;for(let treeElement of this._recordingTreeElementMap.values()){if(previousTreeElement){previousTreeElement.nextSibling=treeElement;treeElement.previousSibling=previousTreeElement;} previousTreeElement=treeElement;}} _recordingSelected(recording) {this._displayedRecording=recording;let cookie={};this.saveToCookie(cookie);if(this._displayedContentView) this._displayedContentView.removeEventListener(WI.ContentView.Event.NavigationItemsDidChange,this._displayedContentViewNavigationItemsDidChange,this);let onlyExisting=true;this._displayedContentView=this.contentBrowser.contentViewForRepresentedObject(this._displayedRecording,onlyExisting);if(this._displayedContentView){this._displayedContentView.addEventListener(WI.ContentView.Event.NavigationItemsDidChange,this._displayedContentViewNavigationItemsDidChange,this);let currentTimelineView=this._displayedContentView.currentTimelineView;let timelineType=currentTimelineView&¤tTimelineView.representedObject instanceof WI.Timeline?currentTimelineView.representedObject.type:null;this._showTimelineViewForType(timelineType);return;} onlyExisting=false;this._displayedContentView=this.contentBrowser.contentViewForRepresentedObject(this._displayedRecording,onlyExisting);if(this._displayedContentView) this._displayedContentView.addEventListener(WI.ContentView.Event.NavigationItemsDidChange,this._displayedContentViewNavigationItemsDidChange,this);this.restoreFromCookie(cookie);} _recordingLoaded(event) {this._recordingSelected(WI.timelineManager.activeRecording);} _viewModeSelected(event) {let selectedNavigationItem=event.target.selectedNavigationItem;if(!selectedNavigationItem) return;const selectedByUser=true;this._changeViewMode(selectedNavigationItem.identifier,selectedByUser);} _changeViewMode(mode,selectedByUser) {if(this._viewMode===mode) return;let navigationItemForViewMode=this.contentBrowser.navigationBar.findNavigationItem(mode);if(!navigationItemForViewMode) return;this._viewMode=mode;this.contentBrowser.navigationBar.selectedNavigationItem=navigationItemForViewMode;if(!selectedByUser) return;let timelineType=this._previousSelectedTimelineType;if(this._viewMode===WI.TimelineOverview.ViewMode.RenderingFrames){let timeline=this._getTimelineForCurrentContentView();this._previousSelectedTimelineType=timeline?timeline.type:null;timelineType=WI.TimelineRecord.Type.RenderingFrame;} this._showTimelineViewForType(timelineType);} _showTimelineViewForType(timelineType) {let timeline=timelineType?this._displayedRecording.timelines.get(timelineType):null;if(timeline) this._displayedContentView.showTimelineViewForTimeline(timeline);else this._displayedContentView.showOverviewTimelineView();if(this.contentBrowser.currentContentView!==this._displayedContentView) this.contentBrowser.showContentView(this._displayedContentView);} _displayedContentViewNavigationItemsDidChange(event) {let timeline=this._getTimelineForCurrentContentView();let newViewMode=WI.TimelineOverview.ViewMode.Timelines;if(timeline&&timeline.type===WI.TimelineRecord.Type.RenderingFrame) newViewMode=WI.TimelineOverview.ViewMode.RenderingFrames;const selectedByUser=false;this._changeViewMode(newViewMode,selectedByUser);} _getTimelineForCurrentContentView() {let currentContentView=this.contentBrowser.currentContentView;if(!(currentContentView instanceof WI.TimelineRecordingContentView)) return null;let timelineView=currentContentView.currentTimelineView;return(timelineView&&timelineView.representedObject instanceof WI.Timeline)?timelineView.representedObject:null;}};WI.TimelineTabContentView.Type="timeline";WI.TimelineTabContentView.ShowingTimelineRecordingContentViewCookieKey="timeline-sidebar-panel-showing-timeline-recording-content-view";WI.TimelineTabContentView.SelectedTimelineViewIdentifierCookieKey="timeline-sidebar-panel-selected-timeline-view-identifier";WI.TimelineTabContentView.OverviewTimelineIdentifierCookieValue="overview";WI.TimelineTabContentView.StopwatchIconStyleClass="stopwatch-icon";WI.WebInspectorExtensionTabContentView=class WebInspectorExtensionTabContentView extends WI.TabContentView {constructor(extension,extensionTabID,tabLabel,iconURL,sourceURL) {let tabInfo={identifier:WI.WebInspectorExtensionTabContentView.Type,image:iconURL,displayName:tabLabel,title:tabLabel,};super(tabInfo);this._extension=extension;this._extensionTabID=extensionTabID;this._tabInfo=tabInfo;this._sourceURL=sourceURL;this._whenPageAvailablePromise=new WI.WrappedPromise;this._iframeElement=this.element.appendChild(document.createElement("iframe"));this._iframeElement.src=sourceURL;this._iframeElement.addEventListener("load",this._extensionFrameDidLoad.bind(this));} static shouldSaveTab(){return false;} static shouldNotRemoveFromDOMWhenHidden(){return true;} static isTabAllowed() {return InspectorFrontendHost.supportsWebExtensions;} get extension(){return this._extension;} get extensionTabID(){return this._extensionTabID;} get iframeElement(){return this._iframeElement;} get type() {return WI.WebInspectorExtensionTabContentView.Type;} get supportsSplitContentBrowser() {return true;} get savedTabPositionKey() {return`ExtensionTab-${this._extension.extensionBundleIdentifier}-${this._tabInfo.displayName}`;} set iframeURL(sourceURL) {this._iframeElement.src=sourceURL;} whenPageAvailable() {return this._whenPageAvailablePromise.promise;} attached() {super.attached();this._maybeDispatchDidShowExtensionTab();} detached() {if(InspectorFrontendHost.supportsWebExtensions) InspectorFrontendHost.didHideExtensionTab(this._extension.extensionID,this._extensionTabID);super.detached();} dispose() {this.element?.remove();} tabInfo() {return this._tabInfo;} static shouldSaveTab(){return false;} static shouldNotRemoveFromDOMWhenHidden(){return true;} _extensionFrameDidLoad() {if(!this._whenPageAvailablePromise.settled) this._whenPageAvailablePromise.resolve(this._sourceURL);this._maybeDispatchDidNavigateExtensionTab();} async _maybeDispatchDidNavigateExtensionTab() {if(!this.element.isConnected) return;let payload=await WI.sharedApp.extensionController.evaluateScriptInExtensionTab(this._extensionTabID,"document.location.href");if(InspectorFrontendHost.supportsWebExtensions) InspectorFrontendHost.didNavigateExtensionTab(this._extension.extensionID,this._extensionTabID,payload.result);} _maybeDispatchDidShowExtensionTab() {if(!this.element.isConnected) return;if(InspectorFrontendHost.supportsWebExtensions) InspectorFrontendHost.didShowExtensionTab(this._extension.extensionID,this._extensionTabID,this._iframeElement);}};WI.WebInspectorExtensionTabContentView.Type="web-inspector-extension";WI.NodeOverlayListSection=class NodeOverlayListSection extends WI.View {constructor(id,label) {super();this._label=label;this.element.classList.add("node-overlay-list-section",id);this._nodeSet=new Set;this._checkboxElementByNodeMap=new WeakMap;} set nodeSet(value) {this._nodeSet=value;this.needsLayout();} attached() {super.attached();WI.DOMNode.addEventListener(WI.DOMNode.Event.LayoutOverlayShown,this._handleOverlayStateChanged,this);WI.DOMNode.addEventListener(WI.DOMNode.Event.LayoutOverlayHidden,this._handleOverlayStateChanged,this);} detached() {WI.DOMNode.removeEventListener(WI.DOMNode.Event.LayoutOverlayShown,this._handleOverlayStateChanged,this);WI.DOMNode.removeEventListener(WI.DOMNode.Event.LayoutOverlayHidden,this._handleOverlayStateChanged,this);super.detached();} initialLayout() {super.initialLayout();let listHeading=this.element.appendChild(document.createElement("h2"));listHeading.textContent=this._label;let optionsElement=listHeading.appendChild(WI.ImageUtilities.useSVGSymbol("Images/Gear.svg","options",WI.UIString("Options")));WI.addMouseDownContextMenuHandlers(optionsElement,(contextMenu)=>{let shouldDisable=this._nodeSet.some((domNode)=>domNode.layoutOverlayShowing);contextMenu.appendItem(shouldDisable?WI.UIString("Disable All"):WI.UIString("Enable All"),()=>{for(let node of this._nodeSet){if(shouldDisable) node.hideLayoutOverlay();else node.showLayoutOverlay();}});});this._listElement=this.element.appendChild(document.createElement("ul"));this._listElement.classList.add("node-overlay-list");} layout() {super.layout();this._listElement.removeChildren();for(let domNode of this._nodeSet){let itemElement=this._listElement.appendChild(document.createElement("li"));let itemContainerElement=itemElement.appendChild(document.createElement("span"));itemContainerElement.classList.add("node-overlay-list-item-container");let labelElement=itemContainerElement.appendChild(document.createElement("label"));let nodeDisplayName=labelElement.appendChild(WI.linkifyNodeReference(domNode,{ignoreClick:true}));nodeDisplayName.classList.add("node-display-name");let checkboxElement=labelElement.appendChild(document.createElement("input"));labelElement.insertBefore(checkboxElement,nodeDisplayName);checkboxElement.type="checkbox";checkboxElement.checked=domNode.layoutOverlayShowing;this._checkboxElementByNodeMap.set(domNode,checkboxElement);checkboxElement.addEventListener("change",(event)=>{if(checkboxElement.checked) domNode.showLayoutOverlay({color:swatch?.value});else domNode.hideLayoutOverlay();});let swatch=new WI.InlineSwatch(WI.InlineSwatch.Type.Color,domNode.layoutOverlayColor,{preventChangingColorFormats:true});itemContainerElement.append(swatch.element);swatch.addEventListener(WI.InlineSwatch.Event.ValueChanged,(event)=>{domNode.layoutOverlayColor=event.target.value;},swatch);let buttonElement=itemContainerElement.appendChild(WI.createGoToArrowButton());buttonElement.title=WI.repeatedUIString.revealInDOMTree();WI.bindInteractionsForNodeToElement(domNode,buttonElement);}} _handleOverlayStateChanged(event) {let checkboxElement=this._checkboxElementByNodeMap.get(event.target);if(!checkboxElement) return;checkboxElement.checked=event.target.layoutOverlayShowing;}};WI.SettingEditor=class SettingEditor extends WI.Object {constructor(type,label,options) {super();this._type=type;this._value=null;this._editorElement=this._createEditorElement(options);this._element=document.createElement("div");this._element.classList.add("setting-editor");this._element.append(this._editorElement);this.label=label;} static createForSetting(setting,label,options) {let type;if(typeof setting.value==="boolean") type=WI.SettingEditor.Type.Checkbox;else if(typeof setting.value==="number") type=WI.SettingEditor.Type.Numeric;if(!type) return null;let editor=new WI.SettingEditor(type,label,options);editor.value=setting.value;editor.addEventListener(WI.SettingEditor.Event.ValueDidChange,function(event){this.value=editor.value;},setting);setting.addEventListener(WI.Setting.Event.Changed,function(event){this.value=setting.value;},editor);return editor;} get element(){return this._element;} get type(){return this._type;} get label() {return this._label;} set label(label) {if(label===this._label) return;this._label=label;if(!this._label){if(this._labelElement) this._labelElement.remove();this._editorElement.removeAttribute("id");this._labelElement=null;return;} if(!this._labelElement){this._editorElement.id="setting-editor-"+WI.SettingEditor._nextEditorIdentifier++;this._labelElement=this._element.appendChild(document.createElement("label"));this._labelElement.setAttribute("for",this._editorElement.id);} this._labelElement.textContent=this._label;} get value() {return this._value;} set value(value) {if(this._value===value) return;let oldValue=this._value;this._value=value;if(this._type===WI.SettingEditor.Type.Checkbox) this._editorElement.checked=!!this._value;else this._editorElement.value=this._value;this.dispatchEventToListeners(WI.SettingEditor.Event.ValueDidChange,{oldValue});} _createEditorElement(options) {let editorElement;switch(this._type){case WI.SettingEditor.Type.Checkbox:editorElement=document.createElement("input");editorElement.type="checkbox";editorElement.addEventListener("change",(event)=>{this.value=event.target.checked;});break;case WI.SettingEditor.Type.Numeric:editorElement=document.createElement("input");editorElement.type="number";if(options.min!==undefined) editorElement.min=options.min;if(options.max!==undefined) editorElement.max=options.max;editorElement.addEventListener("change",(event)=>{let currentValue=this._value;let newValue=parseInt(event.target.value);this.value=isNaN(newValue)?currentValue:newValue;});break;case WI.SettingEditor.Type.Select:editorElement=document.createElement("select");var keyValuePairs=[];if(Array.isArray(options.values[0])) keyValuePairs=options.values;else keyValuePairs=options.values.map((value)=>[value,value]);for(let[key,value]of keyValuePairs){if(key===WI.SettingEditor.SelectSpacerKey){editorElement.appendChild(document.createElement("hr"));continue;} let optionElement=editorElement.appendChild(document.createElement("option"));optionElement.value=key;optionElement.textContent=value;} editorElement.addEventListener("change",(event)=>{this.value=event.target.value;});break;default:console.error("Unknown editor type: "+this._type);} return editorElement;}};WI.SettingEditor._nextEditorIdentifier=1;WI.SettingEditor.Type={Checkbox:"setting-editor-type-checkbox",Numeric:"setting-editor-type-numeric",Select:"setting-editor-type-select",};WI.SettingEditor.SelectSpacerKey=Symbol("setting-editor-select-spacer-key");WI.SettingEditor.Event={ValueDidChange:"value-did-change",};WI.SettingsGroup=class SettingsGroup extends WI.Object {constructor(title) {super();this._element=document.createElement("div");this._element.classList.add("settings-group");let titleElement=this._element.appendChild(document.createElement("div"));titleElement.classList.add("title");titleElement.textContent=title;this._editorGroupElement=this._element.appendChild(document.createElement("div"));this._editorGroupElement.classList.add("editor-group");} get element(){return this._element;} addSetting(setting,label,options) {let editor=WI.SettingEditor.createForSetting(setting,label,options);if(!editor) return null;this._editorGroupElement.append(editor.element);return editor;} addCustomSetting(editorType,options) {let editor=new WI.SettingEditor(editorType,options.label,options);if(!editor) return null;this._editorGroupElement.append(editor.element);return editor;} addCustomEditor() {let element=this._editorGroupElement.appendChild(document.createElement("div"));element.classList.add("editor");return element;}};WI.SettingsPopover=class SettingsPopover extends WI.Popover {constructor(delegate) {super(delegate);this._targetElement=null;this.windowResizeHandler=this._presentOverTargetElement.bind(this);} show(targetElement) {this._targetElement=targetElement;this.content=this.createContentElement();this._presentOverTargetElement();} set content(content) {content.classList.add("settings-content");super.content=content;} createContentElement() {throw WI.NotImplementedError.subclassMustOverride();} _presentOverTargetElement() {if(!this._targetElement) return;let targetFrame=WI.Rect.rectFromClientRect(this._targetElement.getBoundingClientRect());const preferredEdges=[WI.RectEdge.MAX_Y,WI.RectEdge.MAX_X];this.present(targetFrame.pad(2),preferredEdges);}};WI.SettingsView=class SettingsView extends WI.View {constructor(identifier,displayName) {super();this._identifier=identifier;this._displayName=displayName;this.element.classList.add("settings-view",identifier);} get identifier(){return this._identifier;} get displayName(){return this._displayName;} addSetting(title,setting,label,options) {let settingsGroup=this.addGroup(title);return settingsGroup.addSetting(setting,label,options);} addGroupWithCustomSetting(title,editorType,options) {let settingsGroup=this.addGroup(title);return settingsGroup.addCustomSetting(editorType,options);} addGroupWithCustomEditor(title,element) {let settingsGroup=this.addGroup(title);return settingsGroup.addCustomEditor();} addGroup(title) {let settingsGroup=new WI.SettingsGroup(title);this.element.append(settingsGroup.element);return settingsGroup;} addSeparator() {if(this.element.lastChild&&this.element.lastChild.classList.contains("separator")) return;let separatorElement=this.element.appendChild(document.createElement("div"));separatorElement.classList.add("separator");} addCenteredContainer(...nodes) {let containerElement=document.createElement("div");containerElement.append(...nodes);containerElement.classList.add("container","centered");this.element.append(containerElement);return containerElement;}};WI.SettingsView.EditorType={Checkbox:"settings-view-editor-type-checkbox",Numeric:"settings-view-editor-type-numeric",Select:"settings-view-editor-type-select",};WI.AuditTestContentView=class AuditTestContentView extends WI.ContentView {constructor(representedObject) {super(representedObject);this.element.classList.add("audit-test");if(this.representedObject.editable) this.element.classList.add("editable");if(WI.FileUtilities.canSave(WI.FileUtilities.SaveMode.FileVariants)) this._saveMode=WI.FileUtilities.SaveMode.FileVariants;else if(WI.FileUtilities.canSave(WI.FileUtilities.SaveMode.SingleFile)) this._saveMode=WI.FileUtilities.SaveMode.SingleFile;else this._saveMode=null;switch(this._saveMode){case WI.FileUtilities.SaveMode.SingleFile:if(this.representedObject instanceof WI.AuditTestBase){this._exportTestButtonNavigationItem=new WI.ButtonNavigationItem("audit-export-test",WI.UIString("Export Audit"),"Images/Export.svg",15,15);this._exportTestButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._exportTestButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._exportTestButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleExportTestButtonNavigationItemClicked,this);} this._exportResultButtonNavigationItem=new WI.ButtonNavigationItem("audit-export-result",WI.UIString("Export Result"),"Images/Export.svg",15,15);this._exportResultButtonNavigationItem.tooltip=WI.UIString("Export result (%s)","Export result (%s) @ Audit Tab","Tooltip for button that exports the most recent result after running an audit.").format(WI.saveKeyboardShortcut.displayName);this._exportResultButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._exportResultButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._exportResultButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleExportResultButtonNavigationItemClicked,this);break;case WI.FileUtilities.SaveMode.FileVariants:this._exportButtonNavigationItem=new WI.ButtonNavigationItem("audit-export",WI.UIString("Export"),"Images/Export.svg",15,15);this._exportButtonNavigationItem.tooltip=WI.UIString("Export (%s)").format(WI.saveKeyboardShortcut.displayName);this._exportButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._exportButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._exportButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleExportButtonNavigationItemClicked,this);break;} this._updateExportNavigationItems();this._headerView=new WI.View(document.createElement("header"));this._contentView=new WI.View(document.createElement("section"));this._placeholderElement=null;this._cachedName=this.representedObject.name;this._nameElement=null;this._descriptionElement=null;this._supportsInputElement=null;this._supportsWarningElement=null;this._shownResult=null;} get navigationItems() {let navigationItems=[];if(this._exportTestButtonNavigationItem) navigationItems.push(this._exportTestButtonNavigationItem);if(this._exportResultButtonNavigationItem) navigationItems.push(this._exportResultButtonNavigationItem);if(this._exportButtonNavigationItem) navigationItems.push(this._exportButtonNavigationItem);return navigationItems;} get headerView(){return this._headerView;} get contentView(){return this._contentView;} get supportsSave() {return!!this._saveMode&&!WI.auditManager.editing&&!!this.representedObject.result;} get saveMode() {return this._saveMode;} get saveData() {return{customSaveHandler:()=>{this._export();}};} get result() {if(this.representedObject instanceof WI.AuditTestBase) return this.representedObject;return this.representedObject.result;} createNameElement(tagName) {this._nameElement=document.createElement(tagName);this._nameElement.textContent=this.representedObject.name;this._nameElement.className="name";if(this.representedObject.editable){this._nameElement.spellcheck=false;this._nameElement.addEventListener("keydown",(event)=>{this._handleEditorKeydown(event,this._descriptionElement);});this._nameElement.addEventListener("input",(event)=>{let name=this._nameElement.textContent;if(!name.trim()){name=this._cachedName;this._nameElement.removeChildren();} this.representedObject.name=name;});} return this._nameElement;} createDescriptionElement(tagName) {this._descriptionElement=document.createElement(tagName);this._descriptionElement.textContent=this.representedObject.description;this._descriptionElement.className="description";if(this.representedObject.editable){this._descriptionElement.spellcheck=false;this._descriptionElement.addEventListener("keydown",(event)=>{this._handleEditorKeydown(event,this._supportsInputElement);});this._descriptionElement.addEventListener("input",(event)=>{let description=this._descriptionElement.textContent;if(!description.trim()){description="";this._descriptionElement.removeChildren();} this.representedObject.description=description;});} return this._descriptionElement;} createControlsTableElement() {let controlsTableElement=document.createElement("table");controlsTableElement.className="controls";let supportsRowElement=controlsTableElement.appendChild(document.createElement("tr"));supportsRowElement.className="supports";let supportsHeaderElement=supportsRowElement.appendChild(document.createElement("th"));supportsHeaderElement.textContent=WI.unlocalizedString("supports");let supportsDataElement=supportsRowElement.appendChild(document.createElement("td"));this._supportsInputElement=supportsDataElement.appendChild(document.createElement("input"));this._supportsInputElement.type="number";this._supportsInputElement.disabled=!this.representedObject.editable;this._supportsInputElement.min=0;this._supportsInputElement.placeholder=Math.min(WI.AuditTestBase.Version,InspectorBackend.hasDomain("Audit")?InspectorBackend.getVersion("Audit"):Infinity);if(!isNaN(this.representedObject.supports)) this._supportsInputElement.value=this.representedObject.supports;if(this.representedObject.editable){this._supportsInputElement.addEventListener("keydown",(event)=>{this._handleEditorKeydown(event,this._setupEditorElement);});} this._supportsWarningElement=supportsDataElement.appendChild(document.createElement("span"));this._supportsWarningElement.className="warning";if(this.representedObject.topLevelTest===this.representedObject){let setupRowElement=controlsTableElement.appendChild(document.createElement("tr"));setupRowElement.className="setup";let setupHeaderElement=setupRowElement.appendChild(document.createElement("th"));setupHeaderElement.textContent=WI.unlocalizedString("setup");let setupDataElement=setupRowElement.appendChild(document.createElement("td"));this._setupEditorElement=setupDataElement.appendChild(document.createElement("div"));} if(this.representedObject.editable){this._supportsInputElement.addEventListener("input",(event)=>{this.representedObject.supports=parseInt(this._supportsInputElement.value);this._updateSupportsInputState();});} return controlsTableElement;} initialLayout() {super.initialLayout();this.addSubview(this._headerView);this.addSubview(this._contentView);} layout() {super.layout();if(this.representedObject instanceof WI.AuditTestBase){this.element.classList.toggle("unsupported",!this.representedObject.supported);this.element.classList.toggle("disabled",this.representedObject.disabled);this.element.classList.toggle("manager-editing",WI.auditManager.editing);if(this.representedObject.editable){let contentEditable=WI.auditManager.editing?"plaintext-only":"inherit";this._nameElement.contentEditable=contentEditable;this._descriptionElement.contentEditable=contentEditable;} if(WI.auditManager.editing){this._cachedName=this.representedObject.name;this._nameElement.dataset.name=this._cachedName;this._updateSupportsInputState();this._createSetupEditor();}else{this._nameElement.textContent||=this._cachedName;this._setupEditorElement?.removeChildren();}} this.hidePlaceholder();this._updateExportNavigationItems();} attached() {super.attached();if(this.representedObject instanceof WI.AuditTestBase){this.representedObject.addEventListener(WI.AuditTestBase.Event.Completed,this._handleTestChanged,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.DisabledChanged,this._handleTestDisabledChanged,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.Progress,this._handleTestChanged,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.ResultChanged,this.handleResultChanged,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.Scheduled,this._handleTestChanged,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.Stopping,this._handleTestChanged,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.SupportedChanged,this._handleTestSupportedChanged,this);WI.auditManager.addEventListener(WI.AuditManager.Event.EditingChanged,this._handleEditingChanged,this);}} detached() {if(this.representedObject instanceof WI.AuditTestBase){this.representedObject.removeEventListener(WI.AuditTestBase.Event.Completed,this._handleTestChanged,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.DisabledChanged,this._handleTestDisabledChanged,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.Progress,this._handleTestChanged,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.ResultChanged,this.handleResultChanged,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.Scheduled,this._handleTestChanged,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.Stopping,this._handleTestChanged,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.SupportedChanged,this._handleTestSupportedChanged,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.EditingChanged,this._handleEditingChanged,this);if(this.representedObject.editable&&WI.auditManager.editing) this.saveEditedData();} super.detached();} handleResultChanged(event) {if(!WI.auditManager.editing) this.needsLayout();} get placeholderElement() {return this._placeholderElement;} set placeholderElement(placeholderElement) {this.hidePlaceholder();this._placeholderElement=placeholderElement;} saveEditedData() {if(this._setupCodeMirror) this.representedObject.setup=this._setupCodeMirror.getValue().trim();} showRunningPlaceholder() {this._showPlaceholder();} showStoppingPlaceholder() {if(!this.placeholderElement||!this.placeholderElement.__placeholderStopping){this.placeholderElement=WI.createMessageTextView(WI.UIString("Stopping the \u201C%s\u201D audit").format(this.representedObject.name));this.placeholderElement.__placeholderStopping=true;let spinner=new WI.IndeterminateProgressSpinner;this.placeholderElement.appendChild(spinner.element);this.placeholderElement.appendChild(WI.ReferencePage.AuditTab.RunningAudits.createLinkElement());} this._showPlaceholder();} showNoResultPlaceholder() {if(!this.placeholderElement||!this.placeholderElement.__placeholderNoResult){this.placeholderElement=WI.createMessageTextView(WI.UIString("No Result"));this.placeholderElement.__placeholderNoResult=true;let startNavigationItem=new WI.ButtonNavigationItem("run-audit",WI.UIString("Start"),"Images/AuditStart.svg",15,15);startNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;startNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,function(event){WI.auditManager.start([this.representedObject]);},this);let importHelpElement=WI.createNavigationItemHelp(WI.UIString("Press %s to start running the audit."),startNavigationItem);this.placeholderElement.appendChild(importHelpElement);this.placeholderElement.appendChild(WI.ReferencePage.AuditTab.RunningAudits.createLinkElement());} this._showPlaceholder();} showNoResultDataPlaceholder() {if(!this.placeholderElement||!this.placeholderElement.__placeholderNoResultData){let result=this.representedObject.result;if(!result){this.showNoResultPlaceholder();return;} let message=null;if(result.didError) message=WI.UIString("The \u201C%s\u201D audit threw an error");else if(result.didFail) message=WI.UIString("The \u201C%s\u201D audit failed");else if(result.didWarn) message=WI.UIString("The \u201C%s\u201D audit resulted in a warning");else if(result.didPass) message=WI.UIString("The \u201C%s\u201D audit passed");else if(result.unsupported) message=WI.UIString("The \u201C%s\u201D audit is unsupported");else{console.error("Unknown result",result);return;} this.placeholderElement=WI.createMessageTextView(message.format(this.representedObject.name),result.didError);this.placeholderElement.__placeholderNoResultData=true;this.placeholderElement.appendChild(WI.ReferencePage.AuditTab.AuditResults.createLinkElement());} this._showPlaceholder();} showFilteredPlaceholder() {if(!this.placeholderElement||!this.placeholderElement.__placeholderFiltered){this.placeholderElement=WI.createMessageTextView(WI.UIString("No Filter Results"));this.placeholderElement.__placeholderFiltered=true;let buttonElement=this.placeholderElement.appendChild(document.createElement("button"));buttonElement.textContent=WI.UIString("Clear Filters");buttonElement.addEventListener("click",()=>{this.resetFilter();this.needsLayout();});this.placeholderElement.appendChild(WI.ReferencePage.AuditTab.createLinkElement());} this._showPlaceholder();} hidePlaceholder() {this.element.classList.remove("showing-placeholder");if(this.placeholderElement) this.placeholderElement.remove();} applyFilter(levels) {let hasMatch=false;for(let view of this.contentView.subviews){let matches=view.applyFilter(levels);view.element.classList.toggle("filtered",!matches);if(matches) hasMatch=true;} this.element.classList.toggle("no-matches",!hasMatch);if(!Array.isArray(levels)) return true;let result=this.representedObject.result;if(!result) return false;if((levels.includes(WI.AuditTestCaseResult.Level.Error)&&result.didError)||(levels.includes(WI.AuditTestCaseResult.Level.Fail)&&result.didFail)||(levels.includes(WI.AuditTestCaseResult.Level.Warn)&&result.didWarn)||(levels.includes(WI.AuditTestCaseResult.Level.Pass)&&result.didPass)||(levels.includes(WI.AuditTestCaseResult.Level.Unsupported)&&result.unsupported)){return true;} return false;} resetFilter() {for(let view of this.contentView.subviews) view.element.classList.remove("filtered");this.element.classList.remove("no-matches");} _export() {let object=this.representedObject;if(this._saveMode===WI.FileUtilities.SaveMode.SingleFile) object=object.result;WI.auditManager.export(this._saveMode,object);} _updateExportNavigationItems() {if(this._exportTestButtonNavigationItem) this._exportTestButtonNavigationItem.enabled=!WI.auditManager.editing;if(this._exportResultButtonNavigationItem) this._exportResultButtonNavigationItem.enabled=!WI.auditManager.editing&&this.representedObject.result;if(this._exportButtonNavigationItem) this._exportButtonNavigationItem.enabled=this._saveMode&&!WI.auditManager.editing;} _updateSupportsInputState() {this._supportsInputElement.autosize(4);this._supportsWarningElement.removeChildren();if(this.representedObject.supports>WI.AuditTestBase.Version) this._supportsWarningElement.textContent=WI.UIString("too new to run in this Web Inspector","too new to run in this Web Inspector @ Audit Tab","Warning text shown if the version number in the 'supports' input is too new.");else if(InspectorBackend.hasDomain("Audit")&&this._supports>InspectorBackend.getVersion("Audit")) this._supportsWarningElement.textContent=WI.UIString("too new to run in the inspected page","too new to run in the inspected page @ Audit Tab","Warning text shown if the version number in the 'supports' input is too new.");} _createSetupEditor() {if(!this._setupEditorElement) return;let setupEditorElement=document.createElement(this._setupEditorElement.nodeName);setupEditorElement.className="editor";setTimeout(()=>{this._setupCodeMirror=WI.CodeMirrorEditor.create(setupEditorElement,{autoCloseBrackets:true,lineNumbers:true,lineWrapping:true,matchBrackets:true,mode:"text/javascript",readOnly:this.representedObject.editable?false:"nocursor",styleSelectedText:true,value:this.representedObject.setup,});});this._setupEditorElement.parentNode.replaceChild(setupEditorElement,this._setupEditorElement);this._setupEditorElement=setupEditorElement;} _showPlaceholder() {this.element.classList.add("showing-placeholder");this.contentView.element.appendChild(this.placeholderElement);} _handleEditorKeydown(event,nextEditor) {switch(event.keyCode){case WI.KeyboardShortcut.Key.Enter.keyCode:if(nextEditor){nextEditor.focus();break;} case WI.KeyboardShortcut.Key.Escape.keyCode:event.target.blur();break;default:return;} event.preventDefault();} _handleExportTestButtonNavigationItemClicked(event) {WI.auditManager.export(WI.FileUtilities.SaveMode.SingleFile,this.representedObject);} _handleExportResultButtonNavigationItemClicked(event) {WI.auditManager.export(WI.FileUtilities.SaveMode.SingleFile,this.representedObject.result);} _handleExportButtonNavigationItemClicked(event) {WI.auditManager.export(WI.FileUtilities.SaveMode.FileVariants,this.representedObject);} _handleTestChanged(event) {this.needsLayout();} _handleTestDisabledChanged(event) {this.element.classList.toggle("disabled",this.representedObject.disabled);} _handleTestSupportedChanged(event) {this.element.classList.toggle("unsupported",!this.representedObject.supported);} _handleEditingChanged(event) {this.needsLayout();if(!WI.auditManager.editing&&this.representedObject.editable) this.saveEditedData();this._updateExportNavigationItems();}};WI.CollectionContentView=class CollectionContentView extends WI.ContentView {constructor(collection,contentViewConstructor,contentPlaceholder) {super(collection);this.element.classList.add("collection");this._contentPlaceholder=contentPlaceholder||collection.displayName;this._contentPlaceholderElement=null;this._contentViewConstructor=contentViewConstructor;this._contentViewMap=new Map;this._selectedItem=null;this._selectionEnabled=false;} get supplementalRepresentedObjects() {if(this._selectedItem) return[this._selectedItem];return[];} get selectionEnabled() {return this._selectionEnabled;} set selectionEnabled(value) {if(this._selectionEnabled===value) return;this._selectionEnabled=value;if(!this._selectionEnabled) this._selectItem(null);} get selectedItem() {return this._selectedItem;} set selectedItem(item) {if(!this._selectionEnabled) return;this._selectItem(item);if(item){let contentView=this._contentViewMap.get(item);if(contentView) contentView.element.scrollIntoViewIfNeeded();}} get contentViewConstructorOptions() {return{};} addContentViewForItem(item) {if(!this._contentViewConstructor) return;if(this._contentViewMap.has(item)){return;} this.hideContentPlaceholder();let contentView=new this._contentViewConstructor(item,this.contentViewConstructorOptions);this._contentViewMap.set(item,contentView);this.addSubview(contentView);this.contentViewAdded(contentView);} removeContentViewForItem(item) {if(!this._contentViewConstructor) return;let contentView=this._contentViewMap.get(item);if(!contentView) return;if(this._selectedItem===item) this._selectItem(null);this.removeSubview(contentView);this._contentViewMap.delete(item);this.contentViewRemoved(contentView);if(!this.subviews.length) this.showContentPlaceholder();} contentViewAdded(contentView) {} contentViewRemoved(contentView) {} showContentPlaceholder() {if(!this._contentPlaceholderElement){if(typeof this._contentPlaceholder==="string") this._contentPlaceholderElement=WI.createMessageTextView(this._contentPlaceholder);else if(this._contentPlaceholder instanceof HTMLElement) this._contentPlaceholderElement=this._contentPlaceholder;} this._contentPlaceholderElement.classList.add("placeholder");if(!this._contentPlaceholderElement.parentNode) this.element.appendChild(this._contentPlaceholderElement);} hideContentPlaceholder() {if(this._contentPlaceholderElement) this._contentPlaceholderElement.remove();} initialLayout() {if(this._contentViewConstructor) this.element.addEventListener("click",this._handleClick.bind(this));if(!this.representedObject.size||!this._contentViewConstructor) this.showContentPlaceholder();} attached() {super.attached();this.representedObject.addEventListener(WI.Collection.Event.ItemAdded,this._handleItemAdded,this);this.representedObject.addEventListener(WI.Collection.Event.ItemRemoved,this._handleItemRemoved,this);for(let item of this._contentViewMap.keys()){if(this.representedObject.has(item)) continue;this.removeContentViewForItem(item);if(this._selectedItem===item) this._selectItem(null);} for(let item of this.representedObject){if(!this._contentViewMap.has(item)) this.addContentViewForItem(item);}} detached() {this.representedObject.removeEventListener(WI.Collection.Event.ItemAdded,this._handleItemAdded,this);this.representedObject.removeEventListener(WI.Collection.Event.ItemRemoved,this._handleItemRemoved,this);super.detached();} _handleItemAdded(event) {let item=event.data.item;if(!item) return;this.addContentViewForItem(item);} _handleItemRemoved(event) {let item=event.data.item;if(!item) return;this.removeContentViewForItem(item);} _handleContentError(event) {if(event&&event.target) this._removeContentViewForItem(event.target.representedObject);} _selectItem(item) {if(this._selectedItem===item) return;if(this._selectedItem){let contentView=this._contentViewMap.get(this._selectedItem);contentView.element.classList.remove("selected");} this._selectedItem=item;if(this._selectedItem){let selectedContentView=this._contentViewMap.get(this._selectedItem);selectedContentView.element.classList.add("selected");} this.dispatchEventToListeners(WI.CollectionContentView.Event.SelectedItemChanged);this.dispatchEventToListeners(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange);} _handleClick(event) {if(event.button!==0||event.ctrlKey) return;for(let[item,contentView]of this._contentViewMap){if(contentView.element.contains(event.target)){if(this._selectionEnabled) this._selectItem(item);else WI.showRepresentedObject(item);return;}} if(this._selectionEnabled) this._selectItem(null);}};WI.CollectionContentView.Event={SelectedItemChanged:"collection-content-view-selected-item-changed",};WI.LocalRemoteObjectContentView=class LocalRemoteObjectContentView extends WI.ContentView {constructor(representedObject) {super(representedObject);this._remoteObject=null;this._spinnerTimeout=undefined;this.element.classList.add("local-remote-object");} get expression() {throw WI.NotImplementedError.subclassMustOverride();} renderRemoteObject(remoteObject) {throw WI.NotImplementedError.subclassMustOverride();} initialLayout() {super.initialLayout();let target=WI.assumingMainTarget();let options={expression:"("+this.expression+")",doNotPauseOnExceptionsAndMuteConsole:true,generatePreview:true,};target.RuntimeAgent.evaluate.invoke(options,(error,result,wasThrown)=>{this._remoteObject=WI.RemoteObject.fromPayload(result);if(this._spinnerTimeout){clearTimeout(this._spinnerTimeout);this._spinnerTimeout=undefined;} this.element.removeChildren();this.renderRemoteObject(this._remoteObject);});} attached() {super.attached();if(this._spinnerTimeout||this._remoteObject) return;this._spinnerTimeout=setTimeout(()=>{let spinner=new WI.IndeterminateProgressSpinner;this.element.appendChild(spinner.element);this._spinnerTimeout=undefined;},100);} closed() {super.closed();if(this._remoteObject){this._remoteObject.release();this._remoteObject=null;}}};WI.ActivateButtonNavigationItem=class ActivateButtonNavigationItem extends WI.ButtonNavigationItem {constructor(identifier,defaultToolTip,activatedToolTip,image,imageWidth,imageHeight,role) {super(identifier,defaultToolTip,image,imageWidth,imageHeight,role);this._defaultToolTip=defaultToolTip;this._activatedToolTip=activatedToolTip||defaultToolTip;} get defaultToolTip() {return this._defaultToolTip;} set defaultToolTip(defaultToolTip) {this._defaultToolTip=defaultToolTip;if(!this.activated) this.tooltip=this._defaultToolTip;} get activatedToolTip() {return this._activatedToolTip;} set activatedToolTip(activatedToolTip) {this._activatedToolTip=activatedToolTip;if(this.activated) this.tooltip=this._activatedToolTip;} get activated() {return this.element.classList.contains(WI.ActivateButtonNavigationItem.ActivatedStyleClassName);} set activated(flag) {flag=!!flag;this.element.classList.toggle(WI.ActivateButtonNavigationItem.ActivatedStyleClassName,flag);this.tooltip=flag?this._activatedToolTip:this._defaultToolTip;this.element.ariaPressed=flag;this.element.ariaLabel=this.tooltip;} get additionalClassNames() {return["activate","button"];}};WI.ActivateButtonNavigationItem.ActivatedStyleClassName="activated";WI.AlignmentEditor=class AlignmentEditor extends WI.Object {constructor() {super();this._alignment=null;this._valueToGlyphElement=new Map;this._element=document.createElement("div");this._element.className="alignment-editor";this._element.role="radiogroup";} static glyphPath(alignment) {let glyphs=WI.AlignmentEditor._glyphsForType(alignment.type);return glyphs?.[alignment.text]||WI.AlignmentEditor.UnknownValueGlyph;} static shouldRotateGlyph(type) { switch(type){case WI.AlignmentData.Type.JustifyContent:case WI.AlignmentData.Type.JustifyItems:case WI.AlignmentData.Type.JustifySelf:return true;case WI.AlignmentData.Type.AlignContent:case WI.AlignmentData.Type.AlignItems:case WI.AlignmentData.Type.AlignSelf:return false;} return false;} static _glyphsForType(type) {switch(type){case WI.AlignmentData.Type.AlignContent:case WI.AlignmentData.Type.JustifyContent:return WI.AlignmentEditor.AlignContentGlyphs;case WI.AlignmentData.Type.AlignItems:case WI.AlignmentData.Type.AlignSelf:case WI.AlignmentData.Type.JustifyItems:case WI.AlignmentData.Type.JustifySelf:return WI.AlignmentEditor.AlignItemsGlyphs;} return null;} get element(){return this._element;} get alignment() {return this._alignment;} set alignment(alignment) {if(this._alignment?.type!==alignment.type){this._valueToGlyphElement.clear();this._element.removeChildren(); let shouldRotate=WI.AlignmentEditor.shouldRotateGlyph(alignment.type) for(let[value,path]of Object.entries(WI.AlignmentEditor._glyphsForType(alignment.type))){let glyphElement=WI.ImageUtilities.useSVGSymbol(path,"glyph",value);glyphElement.role="radio";glyphElement.tabIndex=0;this._element.append(glyphElement);glyphElement.classList.toggle("rotate-left",shouldRotate);glyphElement.addEventListener("click",()=>{this._removePreviouslySelected();this._alignment.text=value;this._updateSelected();this.dispatchEventToListeners(WI.AlignmentEditor.Event.ValueChanged,{alignment:this._alignment});});this._valueToGlyphElement.set(value,glyphElement);}}else this._removePreviouslySelected();this._alignment=alignment;this._updateSelected();} _removePreviouslySelected() {let previousGlyphElement=this._valueToGlyphElement.get(this._alignment.text);previousGlyphElement?.classList.remove("selected");previousGlyphElement?.removeAttribute("aria-checked");} _updateSelected() {let glyphElement=this._valueToGlyphElement.get(this._alignment.text);glyphElement?.classList.add("selected");glyphElement?.setAttribute("aria-checked",true);}};WI.AlignmentEditor.AlignContentGlyphs={"start":"Images/AlignContentStart.svg","center":"Images/AlignContentCenter.svg","end":"Images/AlignContentEnd.svg","space-between":"Images/AlignContentSpaceBetween.svg","space-around":"Images/AlignContentSpaceAround.svg","space-evenly":"Images/AlignContentSpaceEvenly.svg","stretch":"Images/AlignContentStretch.svg",};WI.AlignmentEditor.AlignItemsGlyphs={"start":"Images/AlignItemsStart.svg","center":"Images/AlignItemsCenter.svg","end":"Images/AlignItemsEnd.svg","stretch":"Images/AlignItemsStretch.svg",};WI.AlignmentEditor.UnknownValueGlyph="Images/AlignmentUnknown.svg";WI.AlignmentEditor.Event={ValueChanged:"alignment-editor-value-changed",};WI.AnimationCollectionContentView=class AnimationCollectionContentView extends WI.CollectionContentView {constructor(representedObject) {let contentPlaceholder=document.createElement("div");let descriptionElement=contentPlaceholder.appendChild(document.createElement("div"));descriptionElement.className="description";switch(representedObject.animationType){case WI.Animation.Type.WebAnimation:descriptionElement.textContent=WI.UIString("Waiting for animations created by JavaScript.");break;case WI.Animation.Type.CSSAnimation:descriptionElement.textContent=WI.UIString("Waiting for animations created by CSS.");break;case WI.Animation.Type.CSSTransition:descriptionElement.textContent=WI.UIString("Waiting for transitions created by CSS.");break;} super(representedObject,WI.AnimationContentView,contentPlaceholder);this.selectionEnabled=true;this.element.classList.add("animation-collection");} handleRefreshButtonClicked() {for(let subview of this.subviews){if(subview instanceof WI.AnimationContentView) subview.handleRefreshButtonClicked();}} contentViewAdded(contentView) {contentView.element.addEventListener("mouseenter",this._handleContentViewMouseEnter);contentView.element.addEventListener("mouseleave",this._handleContentViewMouseLeave);} contentViewRemoved(contentView) {contentView.element.removeEventListener("mouseenter",this._handleContentViewMouseEnter);contentView.element.removeEventListener("mouseleave",this._handleContentViewMouseLeave);} detached() {WI.domManager.hideDOMNodeHighlight();super.detached();} _handleContentViewMouseEnter(event) {let contentView=WI.View.fromElement(event.target);if(!(contentView instanceof WI.AnimationContentView)) return;let animation=contentView.representedObject;animation.requestEffectTarget((styleable)=>{if(!styleable.node||!styleable.node.ownerDocument) return;styleable.node.highlight();});} _handleContentViewMouseLeave(event) {WI.domManager.hideDOMNodeHighlight();}};WI.AnimationContentView=class AnimationContentView extends WI.ContentView {constructor(representedObject) {super(representedObject);this._animationTargetDOMNode=null;this._cachedWidth=NaN;this.element.classList.add("animation");} static get previewHeight() {return 40;} handleRefreshButtonClicked() {this._refreshSubtitle();} initialLayout() {super.initialLayout();let headerElement=this.element.appendChild(document.createElement("header"));let titlesContainer=headerElement.appendChild(document.createElement("div"));titlesContainer.className="titles";this._titleElement=titlesContainer.appendChild(document.createElement("span"));this._titleElement.className="title";this._subtitleElement=titlesContainer.appendChild(document.createElement("span"));this._subtitleElement.className="subtitle";let navigationBar=new WI.NavigationBar;let animationTargetButtonNavigationItem=new WI.ButtonNavigationItem("animation-target",WI.UIString("Animation Target"),"Images/Markup.svg",16,16);animationTargetButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;WI.addMouseDownContextMenuHandlers(animationTargetButtonNavigationItem.element,this._populateAnimationTargetButtonContextMenu.bind(this));navigationBar.addNavigationItem(animationTargetButtonNavigationItem);headerElement.append(navigationBar.element);this.addSubview(navigationBar);this._previewContainer=this.element.appendChild(document.createElement("div"));this._previewContainer.className="preview";} layout() {super.layout();this._refreshTitle();this._refreshSubtitle();this._refreshPreview();} sizeDidChange() {super.sizeDidChange();this._cachedWidth=this.element.realOffsetWidth;} attached() {super.attached();this.representedObject.addEventListener(WI.Animation.Event.NameChanged,this._handleNameChanged,this);this.representedObject.addEventListener(WI.Animation.Event.EffectChanged,this._handleEffectChanged,this);this.representedObject.addEventListener(WI.Animation.Event.TargetChanged,this._handleTargetChanged,this);} detached() {this.representedObject.removeEventListener(WI.Animation.Event.TargetChanged,this._handleTargetChanged,this);this.representedObject.removeEventListener(WI.Animation.Event.EffectChanged,this._handleEffectChanged,this);this.representedObject.removeEventListener(WI.Animation.Event.NameChanged,this._handleNameChanged,this);super.detached();} _refreshTitle() {this._titleElement.removeChildren();let displayName=this.representedObject.displayName;let showIdentifierIfDifferent=(cssName)=>{let formatString="";let substitutions=[];if(cssName===displayName) formatString=WI.UIString("(%s)");else{formatString=WI.UIString("%s (%s)");substitutions.push(displayName);} let cssNameWrapper=document.createElement("code");cssNameWrapper.textContent=cssName;substitutions.push(cssNameWrapper);String.format(formatString,substitutions,String.standardFormatters,this._titleElement,function(a,b){a.append(b);return a;});};switch(this.representedObject.animationType){case WI.Animation.Type.WebAnimation:this._titleElement.textContent=this.representedObject.name||WI.UIString("(%s)").format(displayName);break;case WI.Animation.Type.CSSAnimation:showIdentifierIfDifferent(this.representedObject.cssAnimationName);break;case WI.Animation.Type.CSSTransition:showIdentifierIfDifferent(this.representedObject.cssTransitionProperty);break;}} _refreshSubtitle() {this.representedObject.requestEffectTarget((styleable)=>{this._animationTargetDOMNode=styleable.node;this._subtitleElement.removeChildren();if(styleable) this._subtitleElement.appendChild(WI.linkifyStyleable(styleable));});} _refreshPreview() {this._previewContainer.removeChildren();let keyframes=this.representedObject.keyframes;if(!keyframes.length){let span=this._previewContainer.appendChild(document.createElement("span"));span.textContent=WI.UIString("This animation has no keyframes.");return;} let startDelay=this.representedObject.startDelay||0;let iterationDuration=this.representedObject.iterationDuration||0;let endDelay=this.representedObject.endDelay||0;let totalDuration=startDelay+iterationDuration+endDelay;if(totalDuration===0){let span=this._previewContainer.appendChild(document.createElement("span"));span.textContent=WI.UIString("This animation has no duration.");return;} const previewHeight=WI.AnimationContentView.previewHeight;const markerHeadRadius=4;const markerHeadPadding=2;const squeezeXStart=(iterationDuration&&startDelay)?0:markerHeadRadius+markerHeadPadding;const squeezeXEnd=(iterationDuration&&endDelay)?0:markerHeadRadius+markerHeadPadding;const squeezeYStart=markerHeadRadius+(markerHeadPadding*2);const adjustEasingHeight=-1;const adjustEasingBottomY=0.5;let secondsPerPixel=this._cachedWidth/totalDuration;startDelay*=secondsPerPixel;iterationDuration=(iterationDuration*secondsPerPixel)-squeezeXStart-squeezeXEnd;endDelay*=secondsPerPixel;let svg=this._previewContainer.appendChild(createSVGElement("svg"));svg.setAttribute("viewBox",`0 0 ${this._cachedWidth} ${previewHeight}`);function addTitle(parent,title){let titleElement=parent.appendChild(createSVGElement("title"));titleElement.textContent=title;} if(startDelay){let startDelayContainer=svg.appendChild(createSVGElement("g"));startDelayContainer.classList.add("delay","start");let startDelayLine=startDelayContainer.appendChild(createSVGElement("line"));startDelayLine.setAttribute("y1",(previewHeight+squeezeYStart)/2);startDelayLine.setAttribute("x2",startDelay);startDelayLine.setAttribute("y2",(previewHeight+squeezeYStart)/2);let startDelayElement=startDelayContainer.appendChild(createSVGElement("rect"));startDelayElement.setAttribute("width",startDelay);startDelayElement.setAttribute("height",previewHeight);const startDelayTitleFormat=WI.UIString("Start Delay %s","Web Animation Start Delay Tooltip","Tooltip for section of graph representing delay before a web animation begins applying styles");addTitle(startDelayElement,startDelayTitleFormat.format(Number.secondsToString(this.representedObject.startDelay/1000)));} if(endDelay){let endDelayContainer=svg.appendChild(createSVGElement("g"));endDelayContainer.setAttribute("transform",`translate(${startDelay + iterationDuration + squeezeXStart}, 0)`);endDelayContainer.classList.add("delay","end");let endDelayLine=endDelayContainer.appendChild(createSVGElement("line"));endDelayLine.setAttribute("y1",(previewHeight+squeezeYStart)/2);endDelayLine.setAttribute("x2",endDelay);endDelayLine.setAttribute("y2",(previewHeight+squeezeYStart)/2);let endDelayElement=endDelayContainer.appendChild(createSVGElement("rect"));endDelayElement.setAttribute("width",startDelay+iterationDuration+endDelay);endDelayElement.setAttribute("height",previewHeight);const endDelayTitleFormat=WI.UIString("End Delay %s","Web Animation End Delay Tooltip","Tooltip for section of graph representing delay after a web animation finishes applying styles");addTitle(endDelayElement,endDelayTitleFormat.format(Number.secondsToString(this.representedObject.endDelay/1000)));} if(iterationDuration){let timingFunction=this.representedObject.timingFunction;let activeDurationContainer=svg.appendChild(createSVGElement("g"));activeDurationContainer.classList.add("active");activeDurationContainer.setAttribute("transform",`translate(${startDelay + squeezeXStart}, ${squeezeYStart})`);const startY=0;const endY=previewHeight-squeezeYStart;const height=endY-startY;for(let[keyframeA,keyframeB]of keyframes.adjacencies()){let startX=iterationDuration*keyframeA.offset;let endX=iterationDuration*keyframeB.offset;let width=endX-startX;let easing=keyframeA.easing||timingFunction;let easingContainer=activeDurationContainer.appendChild(createSVGElement("g"));easingContainer.classList.add("easing");easingContainer.setAttribute("transform",`translate(${startX}, ${startY})`);let easingPath=easingContainer.appendChild(createSVGElement("path"));let pathSteps=[];if(easing instanceof WI.CubicBezierTimingFunction){pathSteps.push("C");pathSteps.push(easing.inPoint.x*width); pathSteps.push((1-easing.inPoint.y)*(height+adjustEasingHeight)); pathSteps.push(easing.outPoint.x*width); pathSteps.push((1-easing.outPoint.y)*(height+adjustEasingHeight)); pathSteps.push(width); pathSteps.push(0);}else if(easing instanceof WI.LinearTimingFunction){for(let point of easing.points) pathSteps.push("L",width*point.progress,height+adjustEasingHeight-((height+adjustEasingHeight)*point.value));}else if(easing instanceof WI.StepsTimingFunction){let goUpFirst=false;let stepStartAdjust=0;let stepCountAdjust=0;switch(easing.type){case WI.StepsTimingFunction.Type.JumpStart:case WI.StepsTimingFunction.Type.Start:goUpFirst=true;break;case WI.StepsTimingFunction.Type.JumpNone:--stepCountAdjust;break;case WI.StepsTimingFunction.Type.JumpBoth:++stepStartAdjust;++stepCountAdjust;break;} let stepCount=easing.count+stepCountAdjust;let stepX=width/easing.count;let stepY=(height+adjustEasingHeight)/stepCount;for(let i=stepStartAdjust;i<=stepCount;++i){let x=stepX*(i-stepStartAdjust);let y=height+adjustEasingHeight-(stepY*i);if(goUpFirst){if(i) pathSteps.push("H",x);if(i{WI.RemoteObject.resolveAnimation(this.representedObject,WI.RuntimeManager.ConsoleObjectGroup,(remoteObject)=>{if(!remoteObject) return;const text=WI.UIString("Selected Animation","Appears as a label when a given web animation is logged to the Console");WI.consoleLogViewController.appendImmediateExecutionWithResult(text,remoteObject,{addSpecialUserLogClass:true,shouldRevealConsole:true});});});contextMenu.appendSeparator();if(this._animationTargetDOMNode) WI.appendContextMenuItemsForDOMNode(contextMenu,this._animationTargetDOMNode);}};WI.AnimationDetailsSidebarPanel=class AnimationDetailsSidebarPanel extends WI.DetailsSidebarPanel {constructor() {super("animation",WI.UIString("Animation"));this._animation=null;this._codeMirrorSectionMap=new Map;} inspect(objects) {if(!(objects instanceof Array)) objects=[objects];this.animation=objects.find((object)=>object instanceof WI.Animation);return!!this.animation;} get animation() {return this._animation;} set animation(animation) {if(animation===this._animation) return;if(this._animation){this._animation.removeEventListener(WI.Animation.Event.TargetChanged,this._handleAnimationTargetChanged,this);this._animation.removeEventListener(WI.Animation.Event.EffectChanged,this._handleAnimationEffectChanged,this);this._animation.removeEventListener(WI.Animation.Event.NameChanged,this._handleAnimationNameChanged,this);} this._animation=animation||null;if(this._animation){this._animation.addEventListener(WI.Animation.Event.NameChanged,this._handleAnimationNameChanged,this);this._animation.addEventListener(WI.Animation.Event.EffectChanged,this._handleAnimationEffectChanged,this);this._animation.addEventListener(WI.Animation.Event.TargetChanged,this._handleAnimationTargetChanged,this);} this.needsLayout();} initialLayout() {super.initialLayout();this._idRow=new WI.DetailsSectionSimpleRow(WI.UIString("Identifier"));this._typeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Type"));this._cssAnimationNameRow=new WI.DetailsSectionSimpleRow(WI.UIString("Name"));this._cssTransitionPropertyRow=new WI.DetailsSectionSimpleRow(WI.UIString("Property"));this._targetRow=new WI.DetailsSectionSimpleRow(WI.UIString("Target","Web Animation Target Label","Label for the current DOM node target of a web animation"));const identitySectionTitle=WI.UIString("Identity","Web Animation Identity Title","Section title for information about a web animation");let identitySection=new WI.DetailsSection("animation-identity",identitySectionTitle,[new WI.DetailsSectionGroup([this._idRow,this._typeRow,this._cssAnimationNameRow,this._cssTransitionPropertyRow,this._targetRow])]);this.contentView.element.appendChild(identitySection.element);this._iterationCountRow=new WI.DetailsSectionSimpleRow(WI.UIString("Iterations","Web Animation Iteration Count Label","Label for the number of iterations of a web animation"));this._iterationStartRow=new WI.DetailsSectionSimpleRow(WI.UIString("Start","Web Animation Iteration Start Label","Label for the number describing which iteration a web animation should start at"));this._iterationDurationRow=new WI.DetailsSectionSimpleRow(WI.UIString("Duration","Web Animation Iteration Duration Label","Label for the time duration of each iteration of a web animation"));let iterationsGroup=new WI.DetailsSectionGroup([this._iterationCountRow,this._iterationStartRow,this._iterationDurationRow]);this._startDelayRow=new WI.DetailsSectionSimpleRow(WI.UIString("Start Delay","Web Animation Start Delay Label","Label for the start delay time of a web animation "));this._endDelayRow=new WI.DetailsSectionSimpleRow(WI.UIString("End Delay","Web Animation End Delay Label","Label for the end delay time of a web animation "));this._timingFunctionRow=new WI.DetailsSectionSimpleRow(WI.UIString("Easing","Web Animation Easing Label","Label for the cubic-bezier timing function of a web animation"));let timingGroup=new WI.DetailsSectionGroup([this._startDelayRow,this._endDelayRow,this._timingFunctionRow]);this._playbackDirectionRow=new WI.DetailsSectionSimpleRow(WI.UIString("Direction","Web Animation Playback Direction Label","Label for the playback direction of a web animation"));this._fillModeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Fill","Web Animation Fill Mode Label","Label for the fill mode of a web animation"));let fillDirectionGroup=new WI.DetailsSectionGroup([this._playbackDirectionRow,this._fillModeRow]);const effectSectionTitle=WI.UIString("Effect","Web Animation Effect Title","Section title for information about the effect of a web animation");let effectSection=new WI.DetailsSection("animation-effect",effectSectionTitle,[iterationsGroup,timingGroup,fillDirectionGroup]);this.contentView.element.appendChild(effectSection.element);this._keyframesGroup=new WI.DetailsSectionGroup;const keyframesSectionTitle=WI.UIString("Keyframes","Web Animation Keyframes Title","Section title for information about the keyframes of a web animation");let keyframesSection=new WI.DetailsSection("animation-keyframes",keyframesSectionTitle,[this._keyframesGroup]);this.contentView.element.appendChild(keyframesSection.element);const selectable=false;let backtraceTreeOutline=new WI.TreeOutline(selectable);backtraceTreeOutline.disclosureButtons=false;this._backtraceTreeController=new WI.StackTraceTreeController(backtraceTreeOutline);let backtraceRow=new WI.DetailsSectionRow;backtraceRow.element.appendChild(backtraceTreeOutline.element);const backtraceSectionTitle=WI.UIString("Backtrace","Web Animation Backtrace Title","Section title for the JavaScript backtrace of the creation of a web animation");this._backtraceSection=new WI.DetailsSection("animation-backtrace",backtraceSectionTitle,[new WI.DetailsSectionGroup([backtraceRow])]);this._backtraceSection.element.hidden=true;this.contentView.element.appendChild(this._backtraceSection.element);} layout() {super.layout();if(!this._animation) return;this._refreshIdentitySection();this._refreshEffectSection();this._refreshBacktraceSection();for(let codeMirror of this._codeMirrorSectionMap.values()) codeMirror.refresh();} attached() {super.attached();for(let codeMirror of this._codeMirrorSectionMap.values()) codeMirror.refresh();} _refreshIdentitySection() {let animationType=this._animation.animationType;let displayName=this._animation.displayName;let cssAnimationName=this._animation.cssAnimationName;let cssTransitionProperty=this._animation.cssTransitionProperty;switch(animationType){case WI.Animation.Type.WebAnimation:this._idRow.value=this._animation.name;break;case WI.Animation.Type.CSSAnimation:this._idRow.value=cssAnimationName!==displayName?displayName:null;break;case WI.Animation.Type.CSSTransition:this._idRow.value=cssTransitionProperty!==displayName?displayName:null;break;} this._typeRow.value=WI.Animation.displayNameForAnimationType(animationType);this._cssAnimationNameRow.value=cssAnimationName;this._cssTransitionPropertyRow.value=cssTransitionProperty;this._targetRow.value=null;this._animation.requestEffectTarget((styleable)=>{this._targetRow.value=WI.linkifyStyleable(styleable);});} _refreshEffectSection() {for(let section of this._codeMirrorSectionMap.keys()) section.removeEventListener(WI.DetailsSection.Event.CollapsedStateChanged,this._handleDetailsSectionCollapsedStateChanged,this);this._codeMirrorSectionMap.clear();const precision=0;this._iterationCountRow.value=!isNaN(this._animation.iterationCount)?this._animation.iterationCount.toLocaleString():null;this._iterationStartRow.value=!isNaN(this._animation.iterationStart)?this._animation.iterationStart.toLocaleString():null;this._iterationDurationRow.value=!isNaN(this._animation.iterationDuration)?Number.secondsToString(this._animation.iterationDuration/1000):null;this._startDelayRow.value=this._animation.startDelay?Number.secondsToString(this._animation.startDelay/1000):null;this._endDelayRow.value=this._animation.endDelay?Number.secondsToString(this._animation.endDelay/1000):null;this._timingFunctionRow.value=this._animation.timingFunction?this._animation.timingFunction.toString():null;this._playbackDirectionRow.value=this._animation.playbackDirection?WI.Animation.displayNameForPlaybackDirection(this._animation.playbackDirection):null;this._fillModeRow.value=this._animation.fillMode?WI.Animation.displayNameForFillMode(this._animation.fillMode):null;let keyframeSections=[];for(let keyframe of this._animation.keyframes){let rows=[];let keyframeSection=new WI.DetailsSection("animation-keyframe-offset-"+keyframe.offset,Number.percentageString(keyframe.offset,precision));keyframeSection.addEventListener(WI.DetailsSection.Event.CollapsedStateChanged,this._handleDetailsSectionCollapsedStateChanged,this);keyframeSections.push(keyframeSection);if(keyframe.easing){let subtitle=keyframeSection.headerElement.appendChild(document.createElement("span"));subtitle.className="subtitle";subtitle.textContent=` ${emDash} ${keyframe.easing.toString()}`;} if(keyframe.style){let codeMirrorElement=document.createElement("div");let codeMirror=WI.CodeMirrorEditor.create(codeMirrorElement,{mode:"css",readOnly:"nocursor",lineWrapping:true,});codeMirror.setValue(keyframe.style);const range=null;function optionsForType(type){return{allowedTokens:/\btag\b/,callback(marker,valueObject,valueString){let swatch=new WI.InlineSwatch(type,valueObject,{readOnly:true});codeMirror.setUniqueBookmark(marker.range.startPosition().toCodeMirror(),swatch.element);}};} createCodeMirrorColorTextMarkers(codeMirror,range,optionsForType(WI.InlineSwatch.Type.Color));createCodeMirrorGradientTextMarkers(codeMirror,range,optionsForType(WI.InlineSwatch.Type.Gradient));createCodeMirrorCubicBezierTimingFunctionTextMarkers(codeMirror,range,optionsForType(WI.InlineSwatch.Type.CubicBezierTimingFunction));createCodeMirrorLinearTimingFunctionTextMarkers(codeMirror,range,optionsForType(WI.InlineSwatch.Type.LinearTimingFunction));createCodeMirrorSpringTimingFunctionTextMarkers(codeMirror,range,optionsForType(WI.InlineSwatch.Type.SpringTimingFunction));createCodeMirrorStepsTimingFunctionTextMarkers(codeMirror,range,optionsForType(WI.InlineSwatch.Type.StepsTimingFunction));let row=new WI.DetailsSectionRow;row.element.classList.add("styles");row.element.appendChild(codeMirrorElement);rows.push(row);this._codeMirrorSectionMap.set(keyframeSection,codeMirror);} if(!rows.length){let emptyRow=new WI.DetailsSectionRow(WI.UIString("No Styles"));emptyRow.showEmptyMessage();rows.push(emptyRow);} keyframeSection.groups=[new WI.DetailsSectionGroup(rows)];} if(!keyframeSections.length){let emptyRow=new WI.DetailsSectionRow(WI.UIString("No Keyframes"));emptyRow.showEmptyMessage();keyframeSections.push(emptyRow);} this._keyframesGroup.rows=keyframeSections;} _refreshBacktraceSection() {let stackTrace=this._animation.stackTrace;this._backtraceTreeController.stackTrace=stackTrace;this._backtraceSection.element.hidden=!stackTrace?.callFrames.length;} _handleAnimationNameChanged(event) {this._refreshIdentitySection();} _handleAnimationEffectChanged(event) {this._refreshEffectSection();} _handleAnimationTargetChanged(event) {this._refreshIdentitySection();} _handleDetailsSectionCollapsedStateChanged(event) {let codeMirror=this._codeMirrorSectionMap.get(event.target);codeMirror.refresh();}};WI.ApplicationCacheDetailsSidebarPanel=class ApplicationCacheDetailsSidebarPanel extends WI.DetailsSidebarPanel {constructor() {super("application-cache-details",WI.UIString("Storage"));this.element.classList.add("application-cache");this._applicationCacheFrame=null;} inspect(objects) {if(!(objects instanceof Array)) objects=[objects];var applicationCacheFrameToInspect=null;for(var i=0;i!test.disabled&&test.supported);let contentPlaceholder=WI.createMessageTextView(WI.UIString("No audit selected"));contentView.element.appendChild(contentPlaceholder);if(hasEnabledAudit){let descriptionElement=contentPlaceholder.appendChild(document.createElement("div"));descriptionElement.className="description";descriptionElement.textContent=WI.UIString("Select an audit in the navigation sidebar to view its results.");} let importAuditNavigationItem=new WI.ButtonNavigationItem("import-audit",WI.UIString("Import"),"Images/Import.svg",15,15);importAuditNavigationItem.title=WI.UIString("Import audit or result");importAuditNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;importAuditNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleImportButtonNavigationItemClicked,this);let importAuditHelpElement=WI.createNavigationItemHelp(WI.UIString("Press %s to import an audit or a result."),importAuditNavigationItem);importAuditHelpElement.classList.add("import-audit");contentPlaceholder.appendChild(importAuditHelpElement);let startEditingAuditsNavigationItem=new WI.ButtonNavigationItem("start-editing-audits",WI.UIString("Edit"),"Images/Pencil.svg",16,16);startEditingAuditsNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleEditButtonNavigationItemClicked,this);let startEditingAuditsHelpElement=WI.createNavigationItemHelp(hasEnabledAudit?WI.UIString("Press %s to start editing audits."):WI.UIString("Press %s to enable audits."),startEditingAuditsNavigationItem);startEditingAuditsHelpElement.classList.add("start-editing-audits");contentPlaceholder.appendChild(startEditingAuditsHelpElement);} let versionContainer=contentView.element.appendChild(document.createElement("div"));versionContainer.classList.add("audit-version");let version=WI.AuditTestBase.Version;if(InspectorBackend.hasDomain("Audit")) version=Math.min(version,InspectorBackend.getVersion("Audit"));versionContainer.textContent=WI.UIString("Audit version: %s").format(version);versionContainer.appendChild(WI.auditManager.editing?WI.ReferencePage.AuditTab.EditingAudits.createLinkElement():WI.ReferencePage.AuditTab.createLinkElement());this.contentBrowser.showContentView(contentView);} willDismissPopover(popover) {let audit=popover.audit;if(!audit){InspectorFrontendHost.beep();return;} WI.auditManager.addTest(audit,{save:true});WI.showRepresentedObject(audit);} initialLayout() {super.initialLayout();this.contentTreeOutline.allowsRepeatSelection=false;let controlsNavigationBar=new WI.NavigationBar;this._startStopButtonNavigationItem=new WI.ToggleButtonNavigationItem("start-stop-audit",WI.UIString("Start"),WI.UIString("Stop"),"Images/AuditStart.svg","Images/AuditStop.svg",13,13);this._startStopButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._startStopButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleStartStopButtonNavigationItemClicked,this);controlsNavigationBar.addNavigationItem(this._startStopButtonNavigationItem);this._createButtonNavigationItem=new WI.ButtonNavigationItem("create-audit",WI.AuditNavigationSidebarPanel._createNavigationItemTitle(),"Images/Plus15.svg",15,15);this._createButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._createButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleCreateButtonNavigationItemClicked,this);controlsNavigationBar.addNavigationItem(this._createButtonNavigationItem);controlsNavigationBar.addNavigationItem(new WI.DividerNavigationItem);let importButtonNavigationItem=new WI.ButtonNavigationItem("import-audit",WI.UIString("Import"),"Images/Import.svg",15,15);importButtonNavigationItem.title=WI.UIString("Import audit or result");importButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;importButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleImportButtonNavigationItemClicked,this);controlsNavigationBar.addNavigationItem(importButtonNavigationItem);this.addSubview(controlsNavigationBar);this._editButtonNavigationItem=new WI.ActivateButtonNavigationItem("edit-audits",WI.UIString("Edit"),WI.UIString("Done"),"Images/Pencil.svg",16,16);this._editButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleEditButtonNavigationItemClicked,this);this.filterBar.addFilterNavigationItem(this._editButtonNavigationItem);for(let test of WI.auditManager.tests) this._addTest(test);WI.auditManager.results.forEach((result,i)=>{this._addResult(result,i);});this._updateControlNavigationItems();this._updateEditNavigationItems();this._updateNoAuditsPlaceholder();WI.AuditTestGroup.addEventListener(WI.AuditTestGroup.Event.TestRemoved,this._handleAuditTestRemoved,this);WI.auditManager.addEventListener(WI.AuditManager.Event.EditingChanged,this._handleAuditManagerEditingChanged,this);WI.auditManager.addEventListener(WI.AuditManager.Event.RunningStateChanged,this._handleAuditManagerRunningStateChanged,this);WI.auditManager.addEventListener(WI.AuditManager.Event.TestAdded,this._handleAuditTestAdded,this);WI.auditManager.addEventListener(WI.AuditManager.Event.TestCompleted,this._handleAuditTestCompleted,this);WI.auditManager.addEventListener(WI.AuditManager.Event.TestRemoved,this._handleAuditTestRemoved,this);WI.auditManager.addEventListener(WI.AuditManager.Event.TestScheduled,this._handleAuditTestScheduled,this);this.contentTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._treeSelectionDidChange,this);} closed() {super.closed();if(this.didInitialLayout){WI.auditManager.removeEventListener(WI.AuditManager.Event.EditingChanged,this._handleAuditManagerEditingChanged,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.RunningStateChanged,this._handleAuditManagerRunningStateChanged,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.TestAdded,this._handleAuditTestAdded,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.TestCompleted,this._handleAuditTestCompleted,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.TestRemoved,this._handleAuditTestRemoved,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.TestScheduled,this._handleAuditTestScheduled,this);}} updateFilter() {super.updateFilter();if(!this.hasActiveFilters) this._updateNoAuditsPlaceholder();} hasCustomFilters() {return true;} matchTreeElementAgainstCustomFilters(treeElement,flags) {if(WI.auditManager.editing){if(treeElement.representedObject instanceof WI.AuditTestResultBase||treeElement.hasAncestor(this._resultsFolderTreeElement)||treeElement===this._resultsFolderTreeElement) return false;}else{if(treeElement.representedObject instanceof WI.AuditTestBase&&(treeElement.representedObject.disabled||!treeElement.representedObject.supported)) return false;} return super.matchTreeElementAgainstCustomFilters(treeElement,flags);} _addTest(test) {let treeElement=new WI.AuditTreeElement(test);if(this._resultsFolderTreeElement){this.contentTreeOutline.insertChild(treeElement,this.contentTreeOutline.children.indexOf(this._resultsFolderTreeElement));this._resultsFolderTreeElement.hidden=!this._resultsFolderTreeElement.children.length||WI.auditManager.editing;}else this.contentTreeOutline.appendChild(treeElement);} _addResult(result,index) {this.element.classList.add("has-results");if(!this._resultsFolderTreeElement){this._resultsFolderTreeElement=new WI.FolderTreeElement(WI.UIString("Results"));this.contentTreeOutline.appendChild(this._resultsFolderTreeElement);} this._resultsFolderTreeElement.expand();let resultFolderTreeElement=new WI.FolderTreeElement(WI.UIString("Run %d").format(index+1));if(result instanceof WI.AuditTestResultBase){resultFolderTreeElement.subtitle=WI.UIString("Imported");result=[result];} this._resultsFolderTreeElement.appendChild(resultFolderTreeElement);for(let resultItem of result) resultFolderTreeElement.appendChild(new WI.AuditTreeElement(resultItem));} _updateControlNavigationItems() {this._startStopButtonNavigationItem.toggled=WI.auditManager.runningState===WI.AuditManager.RunningState.Active||WI.auditManager.runningState===WI.AuditManager.RunningState.Stopping;this._startStopButtonNavigationItem.enabled=WI.auditManager.tests.some((test)=>!test.disabled&&test.supported)&&(WI.auditManager.runningState===WI.AuditManager.RunningState.Inactive||WI.auditManager.runningState===WI.AuditManager.RunningState.Active);this._startStopButtonNavigationItem.hidden=WI.auditManager.editing;this._createButtonNavigationItem.hidden=!WI.auditManager.editing;} _updateEditNavigationItems() {this._editButtonNavigationItem.label=WI.auditManager.editing?this._editButtonNavigationItem.activatedToolTip:this._editButtonNavigationItem.defaultToolTip;this._editButtonNavigationItem.activated=WI.auditManager.editing;this._editButtonNavigationItem.enabled=WI.auditManager.editing||WI.auditManager.runningState===WI.AuditManager.RunningState.Inactive;} _updateNoAuditsPlaceholder() {if(WI.auditManager.editing||WI.auditManager.tests.some((test)=>!test.disabled&&test.supported)){if(!this.hasActiveFilters) this.hideEmptyContentPlaceholder();return;} let contentPlaceholder=this.showEmptyContentPlaceholder(WI.UIString("No Enabled Audits"));contentPlaceholder.classList.add("no-enabled-audits");if(WI.auditManager.results.length){ this.contentView.element.insertBefore(contentPlaceholder,this.contentView.element.firstChild);}} _handleAuditManagerEditingChanged(event) {let previousSelectedTreeElement=this.contentTreeOutline.selectedTreeElement;if(previousSelectedTreeElement){if(WI.auditManager.editing){if(!(previousSelectedTreeElement.representedObject instanceof WI.AuditTestBase)) previousSelectedTreeElement.deselect();}else{if(previousSelectedTreeElement.representedObject.disabled||!previousSelectedTreeElement.representedObject.supported) previousSelectedTreeElement.deselect();}} this.updateFilter();if(!this.contentTreeOutline.selectedTreeElement) this.showDefaultContentView();this._updateControlNavigationItems();this._updateEditNavigationItems();this._updateNoAuditsPlaceholder();} _handleAuditManagerRunningStateChanged(event) {this._updateControlNavigationItems();this._updateEditNavigationItems();} _handleAuditTestAdded(event) {let{test}=event.data;this._addTest(test);this._updateControlNavigationItems();this._updateNoAuditsPlaceholder();} _handleAuditTestCompleted(event) {let{result,index}=event.data;this._addResult(result,index);this._updateControlNavigationItems();this._updateEditNavigationItems();} _handleAuditTestRemoved(event) {let{test}=event.data;let treeElement=this.treeElementForRepresentedObject(test);treeElement.parent.removeChild(treeElement);this._updateControlNavigationItems();} _handleAuditTestScheduled(event) {this._updateControlNavigationItems();this._updateEditNavigationItems();} _treeSelectionDidChange(event) {if(!this.selected) return;let treeElement=this.contentTreeOutline.selectedTreeElement;if(!treeElement||treeElement instanceof WI.FolderTreeElement){this.showDefaultContentView();return;} let representedObject=treeElement.representedObject;if(representedObject instanceof WI.AuditTestCase||representedObject instanceof WI.AuditTestGroup||representedObject instanceof WI.AuditTestCaseResult||representedObject instanceof WI.AuditTestGroupResult){WI.showRepresentedObject(representedObject);return;} console.error("Unknown tree element",treeElement);} _handleStartStopButtonNavigationItemClicked(event) {if(WI.auditManager.runningState===WI.AuditManager.RunningState.Inactive) WI.auditManager.start();else if(WI.auditManager.runningState===WI.AuditManager.RunningState.Active) WI.auditManager.stop();} _handleCreateButtonNavigationItemClicked(event) {let popover=new WI.CreateAuditPopover(this);popover.show(event.target.element,[WI.RectEdge.MAX_Y,WI.RectEdge.MAX_X,WI.RectEdge.MIN_X]);} _handleImportButtonNavigationItemClicked(event) {WI.FileUtilities.importJSON((result)=>WI.auditManager.processJSON(result),{multiple:true});} _handleEditButtonNavigationItemClicked(event) {WI.auditManager.editing=!WI.auditManager.editing;}};WI.AuditTestCaseContentView=class AuditTestCaseContentView extends WI.AuditTestContentView {constructor(representedObject) {super(representedObject);this.element.classList.add("audit-test-case");this._resultDataGeneralContainer=null;this._resultDataDOMNodesContainer=null;this._resultDataErrorsContainer=null;} initialLayout() {super.initialLayout();let informationContainer=this.headerView.element.appendChild(document.createElement("div"));informationContainer.classList.add("information");let nameContainer=informationContainer.appendChild(document.createElement("h1"));this._resultImageElement=nameContainer.appendChild(document.createElement("img"));nameContainer.appendChild(this.createNameElement("span"));informationContainer.appendChild(this.createDescriptionElement("p"));if(this.representedObject instanceof WI.AuditTestCase) informationContainer.appendChild(this.createControlsTableElement());this._metadataElement=this.headerView.element.appendChild(document.createElement("div"));this._metadataElement.classList.add("metadata");} layout() {if(this.layoutReason!==WI.View.LayoutReason.Dirty) return;super.layout();this._metadataElement.removeChildren();this.contentView.element.removeChildren();if(WI.auditManager.editing){this._resultImageElement.src="Images/Pencil.svg";this._resultImageElement.title=WI.UIString("Editing audit","Editing Audit @ Audit Tab - Test Case","Title of icon indiciating that the selected audit is being edited.");let testEditorElement=this.contentView.element.appendChild(document.createElement("div"));testEditorElement.className="editor";setTimeout(()=>{this._testCodeMirror=WI.CodeMirrorEditor.create(testEditorElement,{autoCloseBrackets:true,lineNumbers:true,lineWrapping:true,matchBrackets:true,mode:"text/javascript",readOnly:this.representedObject.editable?false:"nocursor",styleSelectedText:true,value:this.representedObject.test,});});return;} this._resultImageElement.src="Images/AuditTestNoResult.svg";this._resultImageElement.title=WI.UIString("Not yet run","Not yet run @ Audit Tab - Test Case","Title of icon indicating that the selected audit has not been run yet.");let result=this.representedObject.result;if(!result){if(this.representedObject.runningState===WI.AuditManager.RunningState.Inactive) this.showNoResultPlaceholder();else if(this.representedObject.runningState===WI.AuditManager.RunningState.Active) this.showRunningPlaceholder();else if(this.representedObject.runningState===WI.AuditManager.RunningState.Stopping) this.showStoppingPlaceholder();return;} if(result.didError){this._resultImageElement.src="Images/AuditTestError.svg";this._resultImageElement.title=WI.UIString("Error","Error @ Audit Tab - Test Case","Title of icon indicating that the selected audit threw an error.");}else if(result.didFail){this._resultImageElement.src="Images/AuditTestFail.svg";this._resultImageElement.title=WI.UIString("Fail","Fail @ Audit Tab - Test Case","Title of icon indicating that the selected audit failed.");}else if(result.didWarn){this._resultImageElement.src="Images/AuditTestWarn.svg";this._resultImageElement.title=WI.UIString("Warn","Warn @ Audit Tab - Test Case","Title of icon indicating that the selected audit passed with issues (i.e. warnings).");}else if(result.didPass){this._resultImageElement.src="Images/AuditTestPass.svg";this._resultImageElement.title=WI.UIString("Pass","Pass @ Audit Tab - Test Case","Title of icon indicating that the selected audit passed with no issues.");}else if(result.unsupported){this._resultImageElement.src="Images/AuditTestUnsupported.svg";this._resultImageElement.title=WI.UIString("Unsupported","Unsupported @ Audit Tab - Test Case","Title of icon indicating that the selected audit is not able to be run (i.e. unsupported).");} let metadata=result.metadata;if(metadata){let sourceContainer=this._metadataElement.appendChild(document.createElement("div"));sourceContainer.classList.add("source");if(metadata.startTimestamp){let timeElement=sourceContainer.appendChild(document.createElement("time"));timeElement.datetime=metadata.startTimestamp.toISOString();timeElement.textContent=metadata.startTimestamp.toLocaleString();if(metadata.endTimestamp){let totalDuration=Number.secondsToString((metadata.endTimestamp-metadata.startTimestamp)/1000);let durationElement=this._metadataElement.appendChild(document.createElement("span"));durationElement.classList.add("duration");durationElement.textContent=totalDuration;if(metadata.asyncTimestamp){let evalDuration=Number.secondsToString((metadata.asyncTimestamp-metadata.startTimestamp)/1000);let asyncDuration=Number.secondsToString((metadata.endTimestamp-metadata.asyncTimestamp)/1000);durationElement.classList.add("async");durationElement.title=WI.UIString("%s eval\n%s async").format(evalDuration,asyncDuration);}}} if(metadata.url&&(metadata.url!==WI.networkManager.mainFrame.url||this.representedObject instanceof WI.AuditTestResultBase)){let url=new URL(metadata.url);let origin=url.origin;if(url.pathname.startsWith("/")) origin+="/";let linkElement=WI.linkifyURLAsNode(url.href,origin+url.href.substring(origin.length).truncateStart(20));linkElement.title=url.href;sourceContainer.appendChild(linkElement);}} let resultData=result.data;if(!this._resultDataGeneralContainer){let nonSpecialData=Object.filter(resultData,(key)=>key!=="domNodes"&&key!=="errors");if(!isEmptyObject(nonSpecialData)){this._resultDataGeneralContainer=document.createElement("div");let expression="("+JSON.stringify(nonSpecialData)+")";const options={objectGroup:WI.AuditTestBase.ObjectGroup,doNotPauseOnExceptionsAndMuteConsole:true,};WI.runtimeManager.evaluateInInspectedWindow(expression,options,(nonSpecialDataRemoteObject,wasThrown)=>{if(!nonSpecialDataRemoteObject) return;if(!this.representedObject.result||this.representedObject.result.data!==resultData) return;const propertyPath=null;const forceExpanding=true;let element=WI.FormattedValue.createObjectTreeOrFormattedValueForRemoteObject(nonSpecialDataRemoteObject,propertyPath,forceExpanding);let objectTree=element.__objectTree;if(objectTree){objectTree.showOnlyJSON();objectTree.expand();} this._resultDataGeneralContainer.appendChild(element);this.hidePlaceholder();});}} if(this._resultDataGeneralContainer) this.contentView.element.appendChild(this._resultDataGeneralContainer);if(!this._resultDataDOMNodesContainer&&resultData.domNodes&&resultData.domNodes.length){this._resultDataDOMNodesContainer=document.createElement("div");this._resultDataDOMNodesContainer.classList.add("dom-nodes");let domNodeText=this._resultDataDOMNodesContainer.appendChild(document.createElement("h1"));domNodeText.textContent=WI.UIString("DOM Nodes:");let tableContainer=this._resultDataDOMNodesContainer.appendChild(document.createElement("table"));resultData.domNodes.forEach((domNode,index)=>{domNode=result.resolvedDOMNodes[index]||domNode;let rowElement=tableContainer.appendChild(document.createElement("tr"));let indexElement=rowElement.appendChild(document.createElement("td"));indexElement.textContent=index+1;let dataElement=rowElement.appendChild(document.createElement("td"));if(domNode instanceof WI.DOMNode){let treeOutline=new WI.DOMTreeOutline({selectable:false});treeOutline.setVisible(true);treeOutline.rootDOMNode=domNode;let rootTreeElement=treeOutline.children[0];rootTreeElement.showGoToArrow=true;if(!rootTreeElement.hasChildren) treeOutline.element.classList.add("single-node");if(resultData.domAttributes){for(let domAttribute of resultData.domAttributes){rootTreeElement.highlightAttribute(domAttribute);rootTreeElement.updateTitle();}} dataElement.appendChild(treeOutline.element);}else if(typeof domNode==="string"){let codeMirror=WI.CodeMirrorEditor.create(dataElement.appendChild(document.createElement("code")),{mode:"css",readOnly:true,lineWrapping:true,styleSelectedText:true,});codeMirror.setValue(domNode);if(resultData.domAttributes){for(let domAttribute of resultData.domAttributes){let regex=null;if(domAttribute==="id") regex=/(\#[^\#|\.|\[|\s|$]+)/g;else if(domAttribute==="class") regex=/(\.[^\#|\.|\[|\s|$]+)/g;else regex=new RegExp(`\\[\\s*(${domAttribute})\\s*=`,"g");while(true){let match=regex.exec(domNode);if(!match) break;let start=match.index+match[0].indexOf(match[1]);codeMirror.markText({line:0,ch:start},{line:0,ch:start+match[1].length},{className:"mark"});}}} setTimeout(()=>{codeMirror.refresh();});}});} if(this._resultDataDOMNodesContainer) this.contentView.element.appendChild(this._resultDataDOMNodesContainer);if(!this._resultDataErrorsContainer&&resultData.errors&&resultData.errors.length){this._resultDataErrorsContainer=document.createElement("div");this._resultDataErrorsContainer.classList.add("errors");let errorText=this._resultDataErrorsContainer.appendChild(document.createElement("h1"));errorText.textContent=WI.UIString("Errors:");let tableContainer=this._resultDataErrorsContainer.appendChild(document.createElement("table"));resultData.errors.forEach((error,index)=>{let rowElement=tableContainer.appendChild(document.createElement("tr"));let indexElement=rowElement.appendChild(document.createElement("td"));indexElement.textContent=index+1;let dataElement=rowElement.appendChild(document.createElement("td"));let errorElement=dataElement.appendChild(document.createElement("div"));errorElement.classList.add("error");errorElement.textContent=error;});} if(this._resultDataErrorsContainer) this.contentView.element.appendChild(this._resultDataErrorsContainer);if(!this.contentView.element.children.length) this.showNoResultDataPlaceholder();} handleResultChanged(event) {super.handleResultChanged(event);this._resultDataGeneralContainer=null;this._resultDataDOMNodesContainer=null;this._resultDataErrorsContainer=null;} saveEditedData() {super.saveEditedData();this.representedObject.test=this._testCodeMirror.getValue().trim();} showRunningPlaceholder() {if(!this.placeholderElement||!this.placeholderElement.__placeholderRunning){this.placeholderElement=WI.createMessageTextView(WI.UIString("Running the \u201C%s\u201D audit").format(this.representedObject.name));this.placeholderElement.__placeholderRunning=true;let spinner=new WI.IndeterminateProgressSpinner;this.placeholderElement.appendChild(spinner.element);let stopAuditNavigationItem=new WI.ButtonNavigationItem("stop-audit",WI.UIString("Stop"),"Images/AuditStop.svg",13,13);stopAuditNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;stopAuditNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,function(event){WI.auditManager.stop();},stopAuditNavigationItem);let stopAuditHelpElement=WI.createNavigationItemHelp(WI.UIString("Press %s to stop running."),stopAuditNavigationItem);this.placeholderElement.appendChild(stopAuditHelpElement);this.placeholderElement.appendChild(WI.ReferencePage.AuditTab.RunningAudits.createLinkElement());} super.showRunningPlaceholder();}};WI.AuditTestGroupContentView=class AuditTestGroupContentView extends WI.AuditTestContentView {constructor(representedObject) {super(representedObject);this.element.classList.add("audit-test-group");this._levelScopeBar=null;this._viewForSubobject=new Map;} willDismissPopover(popover) {let audit=popover.audit;if(!audit){InspectorFrontendHost.beep();return;} this.representedObject.addTest(audit);} createControlsTableElement() {let controlsTableElement=super.createControlsTableElement();let actionsRowElement=controlsTableElement.appendChild(document.createElement("tr"));actionsRowElement.className="actions";let actionsHeaderElement=controlsTableElement.appendChild(document.createElement("th"));let actionsDataElement=controlsTableElement.appendChild(document.createElement("td"));let addTestCaseButtonElement=actionsDataElement.appendChild(document.createElement("button"));addTestCaseButtonElement.disabled=!this.representedObject.editable;addTestCaseButtonElement.textContent=WI.UIString("Add Test Case","Add Test Case @ Audit Tab - Group","Text of button to add a new audit test case to the currently shown audit group.");addTestCaseButtonElement.addEventListener("click",(event)=>{let popover=new WI.CreateAuditPopover(this);popover.show(addTestCaseButtonElement,[WI.RectEdge.MAX_Y,WI.RectEdge.MAX_X,WI.RectEdge.MIN_X]);});return controlsTableElement;} initialLayout() {super.initialLayout();let informationContainer=this.headerView.element.appendChild(document.createElement("div"));informationContainer.classList.add("information");let nameContainer=informationContainer.appendChild(document.createElement("h1"));nameContainer.appendChild(this.createNameElement("span"));informationContainer.appendChild(this.createDescriptionElement("p"));if(this.representedObject instanceof WI.AuditTestGroup) informationContainer.appendChild(this.createControlsTableElement());this._levelNavigationBar=new WI.NavigationBar(document.createElement("nav"));this.headerView.addSubview(this._levelNavigationBar);this._percentageContainer=this.headerView.element.appendChild(document.createElement("div"));this._percentageContainer.classList.add("percentage-pass");this._percentageContainer.hidden=true;this._percentageTextElement=document.createElement("span");const format=WI.UIString("%s%%","Percentage (of audits)","The number of tests that passed expressed as a percentage, followed by a literal %.");String.format(format,[this._percentageTextElement],String.standardFormatters,this._percentageContainer,(a,b)=>{a.append(b);return a;});this._updateClassList();} layout() {if(this.layoutReason!==WI.View.LayoutReason.Dirty) return;super.layout();if(WI.auditManager.editing){if(this._levelScopeBar){this._levelNavigationBar.removeNavigationItem(this._levelScopeBar);this._levelScopeBar=null;} this._percentageContainer.hidden=true;this.resetFilter();return;} let result=this.representedObject.result;if(!result){if(this._levelScopeBar){this._levelNavigationBar.removeNavigationItem(this._levelScopeBar);this._levelScopeBar=null;} this._percentageContainer.hidden=true;this._percentageTextElement.textContent="";if(this.representedObject.runningState===WI.AuditManager.RunningState.Inactive) this.showNoResultPlaceholder();else if(this.representedObject.runningState===WI.AuditManager.RunningState.Active) this.showRunningPlaceholder();else if(this.representedObject.runningState===WI.AuditManager.RunningState.Stopping) this.showStoppingPlaceholder();return;} let levelCounts=result.levelCounts;let totalCount=Object.values(levelCounts).reduce((accumulator,current)=>accumulator+current);this._percentageTextElement.textContent=Math.floor(100*levelCounts[WI.AuditTestCaseResult.Level.Pass]/totalCount);this._percentageContainer.hidden=false;if(!this._levelScopeBar){let scopeBarItems=[];let addScopeBarItem=(level,labelSingular,labelPlural)=>{let count=levelCounts[level];if(isNaN(count)||count<=0) return;let label=(labelPlural&&count!==1)?labelPlural:labelSingular;let scopeBarItem=new WI.ScopeBarItem(level,label.format(count),{className:level,exclusive:false,independent:true,});scopeBarItem.selected=true;scopeBarItem.element.insertBefore(document.createElement("img"),scopeBarItem.element.firstChild);scopeBarItems.push(scopeBarItem);};addScopeBarItem(WI.AuditTestCaseResult.Level.Pass,WI.UIString("%d Passed","%d Passed (singular)",""),WI.UIString("%d Passed","%d Passed (plural)",""));addScopeBarItem(WI.AuditTestCaseResult.Level.Warn,WI.UIString("%d Warning"),WI.UIString("%d Warnings"));addScopeBarItem(WI.AuditTestCaseResult.Level.Fail,WI.UIString("%d Failed","%d Failed (singular)",""),WI.UIString("%d Failed","%d Failed (plural)",""));addScopeBarItem(WI.AuditTestCaseResult.Level.Error,WI.UIString("%d Error"),WI.UIString("%d Errors"));addScopeBarItem(WI.AuditTestCaseResult.Level.Unsupported,WI.UIString("%d Unsupported","%d Unsupported (singular)",""),WI.UIString("%d Unsupported","%d Unsupported (plural)",""));this._levelScopeBar=new WI.ScopeBar(null,scopeBarItems);this._levelScopeBar.addEventListener(WI.ScopeBar.Event.SelectionChanged,this._handleLevelScopeBarSelectionChanged,this);this._levelNavigationBar.addNavigationItem(this._levelScopeBar);} if(this.applyFilter()) this.hidePlaceholder();else this.showFilteredPlaceholder();} attached() {super.attached();if(this.representedObject instanceof WI.AuditTestGroup){this.representedObject.addEventListener(WI.AuditTestBase.Event.Progress,this._handleTestGroupProgress,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.Scheduled,this._handleTestGroupScheduled,this);if(this.representedObject.editable){this.representedObject.addEventListener(WI.AuditTestGroup.Event.TestAdded,this._handleTestGroupTestAdded,this);this.representedObject.addEventListener(WI.AuditTestGroup.Event.TestRemoved,this._handleTestGroupTestRemoved,this);}} for(let subobject of this._subobjects()) this._addTest(subobject);} detached() {if(this.representedObject instanceof WI.AuditTestGroup){this.representedObject.removeEventListener(WI.AuditTestBase.Event.Progress,this._handleTestGroupProgress,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.Scheduled,this._handleTestGroupScheduled,this);if(this.representedObject.editable){this.representedObject.removeEventListener(WI.AuditTestGroup.Event.TestAdded,this._handleTestGroupTestAdded,this);this.representedObject.removeEventListener(WI.AuditTestGroup.Event.TestRemoved,this._handleTestGroupTestRemoved,this);}} this.contentView.removeAllSubviews();this._viewForSubobject.clear();super.detached();} applyFilter(levels) {if(this._levelScopeBar&&!levels) levels=this._levelScopeBar.selectedItems.map((item)=>item.id);this._updateLevelScopeBar(levels);return super.applyFilter(levels);} resetFilter() {this._updateLevelScopeBar(Object.values(WI.AuditTestCaseResult.Level));super.resetFilter();} showRunningPlaceholder() {if(!this.placeholderElement||!this.placeholderElement.__placeholderRunning){this.placeholderElement=WI.createMessageTextView(WI.UIString("Running the \u201C%s\u201D audit").format(this.representedObject.name));this.placeholderElement.__placeholderRunning=true;this.placeholderElement.__progress=document.createElement("progress");this.placeholderElement.__progress.value=0;this.placeholderElement.appendChild(this.placeholderElement.__progress);let stopAuditNavigationItem=new WI.ButtonNavigationItem("stop-audit",WI.UIString("Stop"),"Images/AuditStop.svg",13,13);stopAuditNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;stopAuditNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,function(event){WI.auditManager.stop();},stopAuditNavigationItem);let stopAuditHelpElement=WI.createNavigationItemHelp(WI.UIString("Press %s to stop running."),stopAuditNavigationItem);this.placeholderElement.appendChild(stopAuditHelpElement);this.placeholderElement.appendChild(WI.ReferencePage.AuditTab.RunningAudits.createLinkElement());} super.showRunningPlaceholder();} _subobjects() {if(this.representedObject instanceof WI.AuditTestGroup) return this.representedObject.tests;if(this.representedObject instanceof WI.AuditTestGroupResult) return this.representedObject.results;console.error("Unknown representedObject",this.representedObject);return[];} _updateClassList() {let subobjects=this._subobjects();let containsTestGroup=subobjects.some((test)=>test instanceof WI.AuditTestGroup||test instanceof WI.AuditTestGroupResult);this.element.classList.toggle("contains-test-group",containsTestGroup);this.element.classList.toggle("contains-test-case",!containsTestGroup&&subobjects.some((test)=>test instanceof WI.AuditTestCase||test instanceof WI.AuditTestCaseResult));} _updateLevelScopeBar(levels) {if(!this._levelScopeBar) return;for(let item of this._levelScopeBar.items) item.selected=levels.includes(item.id);for(let view of this._viewForSubobject.values()){if(view instanceof WI.AuditTestGroupContentView) view._updateLevelScopeBar(levels);}} _addTest(test) {let view=WI.ContentView.contentViewForRepresentedObject(test);this.contentView.addSubview(view);this._viewForSubobject.set(test,view);} _handleTestGroupProgress(event) {let{index,count}=event.data;if(this.placeholderElement&&this.placeholderElement.__progress) this.placeholderElement.__progress.value=(index+1)/count;} _handleTestGroupScheduled(event) {if(this.placeholderElement&&this.placeholderElement.__progress) this.placeholderElement.__progress.value=0;} _handleTestGroupTestAdded(event) {let{test}=event.data;this._addTest(test);this._updateClassList();} _handleTestGroupTestRemoved(event) {let{test}=event.data;let view=this._viewForSubobject.get(test);this.contentView.removeSubview(view);this._updateClassList();} _handleLevelScopeBarSelectionChanged(event) {this.needsLayout();}};WI.AuditTreeElement=class AuditTreeElement extends WI.GeneralTreeElement {constructor(representedObject) {let isTestCase=representedObject instanceof WI.AuditTestCase;let isTestGroup=representedObject instanceof WI.AuditTestGroup;let isTestCaseResult=representedObject instanceof WI.AuditTestCaseResult;let isTestGroupResult=representedObject instanceof WI.AuditTestGroupResult;let classNames=["audit"];if(isTestCase) classNames.push("test-case");else if(isTestGroup) classNames.push("test-group");else if(isTestCaseResult) classNames.push("test-case-result");else if(isTestGroupResult) classNames.push("test-group-result");let options={hasChildren:isTestGroup||isTestGroupResult,};const subtitle=null;super(classNames,representedObject.name,subtitle,representedObject,options);if(isTestGroup) this._expandedSetting=new WI.Setting(WI.AuditTreeElement.expandedSettingKey(this.representedObject.name),false);} static expandedSettingKey(name) {return`audit-tree-element-${name}-expanded`;} onattach() {super.onattach();if(this.representedObject instanceof WI.AuditTestBase){this.representedObject.addEventListener(WI.AuditTestBase.Event.DisabledChanged,this._handleTestDisabledChanged,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.ResultChanged,this._handleTestResultChanged,this);if(this.representedObject instanceof WI.AuditTestCase) this.representedObject.addEventListener(WI.AuditTestBase.Event.Scheduled,this._handleTestCaseScheduled,this);else if(this.representedObject instanceof WI.AuditTestGroup) this.representedObject.addEventListener(WI.AuditTestBase.Event.Scheduled,this._handleTestGroupScheduled,this);if(this.representedObject.editable){this.representedObject.addEventListener(WI.AuditTestBase.Event.NameChanged,this._handleTestNameChanged,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.SupportedChanged,this._handleTestSupportedChanged,this);if(this.representedObject instanceof WI.AuditTestGroup) this.representedObject.addEventListener(WI.AuditTestGroup.Event.TestAdded,this._handleTestGroupTestAdded,this);} WI.auditManager.addEventListener(WI.AuditManager.Event.EditingChanged,this._handleManagerEditingChanged,this);WI.auditManager.addEventListener(WI.AuditManager.Event.TestScheduled,this._handleAuditManagerTestScheduled,this);WI.auditManager.addEventListener(WI.AuditManager.Event.TestCompleted,this._handleAuditManagerTestCompleted,this);} if(this.representedObject.supported&&this._expandedSetting&&this._expandedSetting.value) this.expand();this._updateStatus();} ondetach() {if(this.representedObject instanceof WI.AuditTestBase){this.representedObject.removeEventListener(WI.AuditTestBase.Event.DisabledChanged,this._handleTestDisabledChanged,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.ResultChanged,this._handleTestResultChanged,this);if(this.representedObject instanceof WI.AuditTestCase) this.representedObject.removeEventListener(WI.AuditTestBase.Event.Scheduled,this._handleTestCaseScheduled,this);else if(this.representedObject instanceof WI.AuditTestGroup) this.representedObject.removeEventListener(WI.AuditTestBase.Event.Scheduled,this._handleTestGroupScheduled,this);if(this.representedObject.editable){this.representedObject.removeEventListener(WI.AuditTestBase.Event.NameChanged,this._handleTestNameChanged,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.SupportedChanged,this._handleTestSupportedChanged,this);if(this.representedObject instanceof WI.AuditTestGroup) this.representedObject.removeEventListener(WI.AuditTestGroup.Event.TestAdded,this._handleTestGroupTestAdded,this);} WI.auditManager.removeEventListener(WI.AuditManager.Event.EditingChanged,this._handleManagerEditingChanged,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.TestScheduled,this._handleAuditManagerTestScheduled,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.TestCompleted,this._handleAuditManagerTestCompleted,this);} super.ondetach();} onpopulate() {super.onpopulate();if(this.children.length&&!this.shouldRefreshChildren) return;this.shouldRefreshChildren=false;this.removeChildren();if(this.representedObject instanceof WI.AuditTestGroup){for(let test of this.representedObject.tests) this.appendChild(new WI.AuditTreeElement(test));}else if(this.representedObject instanceof WI.AuditTestGroupResult){for(let result of this.representedObject.results) this.appendChild(new WI.AuditTreeElement(result));}} onexpand() {if(this._expandedSetting) this._expandedSetting.value=this.expanded;} oncollapse() {if(this._expandedSetting) this._expandedSetting.value=this.expanded;} ondelete() {if(!(this.representedObject instanceof WI.AuditTestBase)) return false;if(!WI.auditManager.editing) return false;this.representedObject.remove();return true;} canSelectOnMouseDown(event) {if(this.representedObject instanceof WI.AuditTestBase&&this.representedObject.supported&&this.status.contains(event.target)) return false;return super.canSelectOnMouseDown(event);} populateContextMenu(contextMenu,event) {let isTest=this.representedObject instanceof WI.AuditTestBase;contextMenu.appendSeparator();if(WI.auditManager.editing){if(isTest){if(this.representedObject.supported){contextMenu.appendItem(this.representedObject.disabled?WI.UIString("Enable Audit"):WI.UIString("Disable Audit"),()=>{this.representedObject.disabled=!this.representedObject.disabled;});} contextMenu.appendItem(WI.UIString("Duplicate Audit"),async()=>{let audit=await this.representedObject.clone();WI.auditManager.addTest(audit,{save:true});});if(this.representedObject.editable){contextMenu.appendItem(WI.UIString("Delete Audit"),()=>{this.representedObject.remove();});}}}else{if(isTest){contextMenu.appendItem(WI.UIString("Start Audit"),()=>{this._start();},WI.auditManager.runningState!==WI.AuditManager.RunningState.Inactive);} contextMenu.appendSeparator();if(WI.FileUtilities.canSave(WI.FileUtilities.SaveMode.FileVariants)){contextMenu.appendItem(WI.UIString("Export"),()=>{WI.auditManager.export(WI.FileUtilities.SaveMode.FileVariants,this.representedObject);});}else if(WI.FileUtilities.canSave(WI.FileUtilities.SaveMode.SingleFile)){if(isTest){contextMenu.appendItem(WI.FileUtilities.SaveMode.SingleFile,WI.UIString("Export Audit"),()=>{WI.auditManager.export(this.representedObject);});} contextMenu.appendItem(WI.FileUtilities.SaveMode.SingleFile,WI.UIString("Export Result"),()=>{WI.auditManager.export(this.representedObject.result);},!this.representedObject.result);} if(isTest&&this.representedObject.editable){contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Edit Audit"),()=>{WI.auditManager.editing=true;WI.showRepresentedObject(this.representedObject);});}} contextMenu.appendSeparator();super.populateContextMenu(contextMenu,event);} _start() {if(WI.auditManager.runningState!==WI.AuditManager.RunningState.Inactive) return;WI.auditManager.start([this.representedObject]);} _updateStatus() {if(this.representedObject instanceof WI.AuditTestBase&&!this.representedObject.supported){this.status=document.createElement("img");this.status.title=WI.UIString("This audit is not supported");this.addClassName("unsupported");return;} if(WI.auditManager.editing){this.status=document.createElement("input");this.status.type="checkbox";this._updateTestGroupDisabled();this.status.addEventListener("change",()=>{this.representedObject.disabled=!this.representedObject.disabled;});this.addClassName("editing-audits");return;} let className="";let result=this.representedObject.result;if(result){if(result.didError) className=WI.AuditTestCaseResult.Level.Error;else if(result.didFail) className=WI.AuditTestCaseResult.Level.Fail;else if(result.didWarn) className=WI.AuditTestCaseResult.Level.Warn;else if(result.didPass) className=WI.AuditTestCaseResult.Level.Pass;else if(result.unsupported) className=WI.AuditTestCaseResult.Level.Unsupported;} this.status=document.createElement("img");if(this.representedObject instanceof WI.AuditTestBase){this.status.title=WI.UIString("Start");this.status.addEventListener("click",this._handleStatusClick.bind(this));if(!className) className="show-on-hover";} this.status.classList.add(className);this.removeClassName("editing-audits");} _showRunningSpinner() {if(this.representedObject.runningState===WI.AuditManager.RunningState.Inactive){this._updateStatus();return;} if(!this.status||!this.status.__spinner){let spinner=new WI.IndeterminateProgressSpinner;this.status=spinner.element;this.status.__spinner=true;}} _showRunningProgress(progress) {if(!this.representedObject.runningState===WI.AuditManager.RunningState.Inactive){this._updateStatus();return;} if(!this.status||!this.status.__progress){this.status=document.createElement("progress");this.status.__progress=true;} this.status.value=progress||0;} _updateTestGroupDisabled() {this.status.checked=!this.representedObject.disabled;if(this.representedObject instanceof WI.AuditTestGroup){let firstSupportedTest=this.representedObject.tests.find((test)=>test.supported);this.status.indeterminate=this.representedObject.tests.some((test)=>test.supported&&test.disabled!==firstSupportedTest.disabled);}} _handleTestCaseCompleted(event) {this.representedObject.removeEventListener(WI.AuditTestBase.Event.Completed,this._handleTestCaseCompleted,this);this._updateStatus();} _handleTestDisabledChanged(event) {if(this.status instanceof HTMLInputElement&&this.status.type==="checkbox") this._updateTestGroupDisabled();} _handleTestResultChanged(event) {this._updateStatus();} _handleTestCaseScheduled(event) {this.representedObject.addEventListener(WI.AuditTestBase.Event.Completed,this._handleTestCaseCompleted,this);this._showRunningSpinner();} _handleTestGroupCompleted(event) {this.representedObject.removeEventListener(WI.AuditTestBase.Event.Completed,this._handleTestGroupCompleted,this);this.representedObject.removeEventListener(WI.AuditTestBase.Event.Progress,this._handleTestGroupProgress,this);this._updateStatus();} _handleTestGroupProgress(event) {let{index,count}=event.data;this._showRunningProgress((index+1)/count);} _handleTestGroupScheduled(event) {this.representedObject.addEventListener(WI.AuditTestBase.Event.Completed,this._handleTestGroupCompleted,this);this.representedObject.addEventListener(WI.AuditTestBase.Event.Progress,this._handleTestGroupProgress,this);this._showRunningProgress();} _handleTestNameChanged(event) {this.mainTitle=this.representedObject.name;if(this.representedObject instanceof WI.AuditTestGroup) this._expandedSetting=new WI.Setting(WI.AuditTreeElement.expandedSettingKey(this.representedObject.name),!!WI.Setting.migrateValue(WI.AuditTreeElement.expandedSettingKey(event.data.oldName)));} _handleTestSupportedChanged(event) {this._updateStatus();} _handleTestGroupTestAdded(event) {let{test}=event.data;this.appendChild(new WI.AuditTreeElement(test));} _handleManagerEditingChanged(event) {this._updateStatus();} _handleAuditManagerTestScheduled(event) {this.addClassName("manager-active");} _handleAuditManagerTestCompleted(event) {this.removeClassName("manager-active");} _handleStatusClick(event) {this._start();}};WI.BannerView=class BannerView extends WI.View {constructor(message,{actionButtonMessage,showDismissButton}={}) {super();this.element.classList.add("banner-view");this.element.appendChild(document.createTextNode(message));if(actionButtonMessage){let actionButtonElement=this.element.appendChild(document.createElement("button"));actionButtonElement.textContent=actionButtonMessage;actionButtonElement.addEventListener("click",this._handleActionButtonClicked.bind(this));} if(showDismissButton){let dismissButtonElement=this.element.appendChild(WI.ImageUtilities.useSVGSymbol("Images/Close.svg","dismiss",WI.UIString("Dismiss","Dismiss @ Banner View","Tooltip for the dismiss button in banner views.")));dismissButtonElement.addEventListener("click",this._handleDismissButtonClicked.bind(this));}} _handleActionButtonClicked(event) {this.dispatchEventToListeners(WI.BannerView.Event.ActionButtonClicked);} _handleDismissButtonClicked(event) {this.dispatchEventToListeners(WI.BannerView.Event.DismissButtonClicked);}};WI.BannerView.Event={ActionButtonClicked:"banner-view-action-button-clicked",DismissButtonClicked:"banner-view-dismiss-button-clicked",};WI.BlackboxSettingsView=class BlackboxSettingsView extends WI.SettingsView {constructor() {super("blackbox",WI.UIString("Blackbox"));this._blackboxPatternCodeMirrorMap=new Map;} selectBlackboxPattern(regex) {let codeMirror=this._blackboxPatternCodeMirrorMap.get(regex);if(!codeMirror) return;codeMirror.focus();} initialLayout() {super.initialLayout();let patternBlackboxExplanationElement=this.element.insertBefore(document.createElement("p"),this.element.lastChild);patternBlackboxExplanationElement.textContent=WI.UIString("If the URL of any script matches one of the regular expression patterns below, any pauses that would have happened in that script will be deferred until execution has continued to outside of that script.");let table=this.element.insertBefore(document.createElement("table"),this.element.lastChild);let tableHead=table.appendChild(document.createElement("thead"));let tableHeadRow=tableHead.appendChild(document.createElement("tr"));let urlHeaderCell=tableHeadRow.appendChild(document.createElement("th"));urlHeaderCell.classList.add("url");urlHeaderCell.textContent=WI.UIString("URL Pattern");let caseSensitiveHeaderCell=tableHeadRow.appendChild(document.createElement("th"));caseSensitiveHeaderCell.classList.add("case-sensitive");caseSensitiveHeaderCell.textContent=WI.UIString("Case Sensitive");let removeBlackboxHeaderCell=tableHeadRow.appendChild(document.createElement("th"));removeBlackboxHeaderCell.classList.add("remove-blackbox");this._tableBody=table.appendChild(document.createElement("tbody"));for(let regex of WI.debuggerManager.blackboxPatterns) this._addRow(regex);if(!this._tableBody.children.length) this._addRow(null);let tableFoot=table.appendChild(document.createElement("tfoot"));let tableFooterRow=tableFoot.appendChild(document.createElement("tr"));let addBlackboxCell=tableFooterRow.appendChild(document.createElement("td"));let addBlackboxButton=addBlackboxCell.appendChild(document.createElement("button"));addBlackboxButton.textContent=WI.UIString("Add Pattern");addBlackboxButton.addEventListener("click",(event)=>{for(let[regex,codeMirror]of this._blackboxPatternCodeMirrorMap){if(!regex){codeMirror.focus();return;}} this._addRow(null);});let individualBlackboxExplanationElement=this.element.insertBefore(document.createElement("p"),this.element.lastChild);let blackboxIconElement=WI.ImageUtilities.useSVGSymbol("Images/Hide.svg#currentColor","toggle-script-blackbox",WI.UIString("Ignore script when debugging"));String.format(WI.UIString("Scripts can also be individually blackboxed by clicking on the %s icon that is shown on hover."),[blackboxIconElement],String.standardFormatters,individualBlackboxExplanationElement,(a,b)=>{a.append(b);return a;});if(WI.DebuggerManager.supportsBlackboxingBreakpointEvaluations()){let blackboxBreakpointEvaluationsExplanationElement=this.element.insertBefore(document.createElement("p"),this.element.lastChild);let blackboxBreakpointEvaluationsExplanationLabel=blackboxBreakpointEvaluationsExplanationElement.appendChild(document.createElement("label"));let blackboxBreakpointEvaluationsExplanationCheckbox=blackboxBreakpointEvaluationsExplanationLabel.appendChild(document.createElement("input"));blackboxBreakpointEvaluationsExplanationCheckbox.type="checkbox";blackboxBreakpointEvaluationsExplanationCheckbox.checked=WI.settings.blackboxBreakpointEvaluations.value;blackboxBreakpointEvaluationsExplanationCheckbox.addEventListener("change",(event)=>{WI.settings.blackboxBreakpointEvaluations.value=blackboxBreakpointEvaluationsExplanationCheckbox.checked;});blackboxBreakpointEvaluationsExplanationLabel.append(WI.UIString("Also defer evaluating breakpoint conditions, ignore counts, and actions until execution has continued outside of the related script instead of at the breakpoint\u2019s location."));}} _addRow(regex) {let tableBodyRow=this._tableBody.appendChild(document.createElement("tr"));let urlBodyCell=tableBodyRow.appendChild(document.createElement("td"));urlBodyCell.classList.add("url");let urlCodeMirror=WI.CodeMirrorEditor.create(urlBodyCell,{extraKeys:{"Tab":false,"Shift-Tab":false},lineWrapping:false,matchBrackets:false,mode:"text/x-regex",placeholder:WI.UIString("Regular Expression"),scrollbarStyle:null,value:regex?regex.source:"",});this._blackboxPatternCodeMirrorMap.set(regex,urlCodeMirror);this.needsLayout();let caseSensitiveBodyCell=tableBodyRow.appendChild(document.createElement("td"));caseSensitiveBodyCell.classList.add("case-sensitive");let caseSensitiveCheckbox=caseSensitiveBodyCell.appendChild(document.createElement("input"));caseSensitiveCheckbox.type="checkbox";caseSensitiveCheckbox.checked=regex?!regex.ignoreCase:true;let removeBlackboxBodyCell=tableBodyRow.appendChild(document.createElement("td"));removeBlackboxBodyCell.classList.add("remove-blackbox");let removeBlackboxButton=removeBlackboxBodyCell.appendChild(WI.ImageUtilities.useSVGSymbol("Images/NavigationItemTrash.svg","remove-blackbox-button",WI.UIString("Delete Blackbox")));removeBlackboxButton.addEventListener("click",(event)=>{if(regex) WI.debuggerManager.setShouldBlackboxPattern(regex,false);regex=null;this._blackboxPatternCodeMirrorMap.delete(regex);tableBodyRow.remove();if(!this._tableBody.children.length) this._addRow(null);});let update=()=>{let url=urlCodeMirror.getValue();if(regex){if(regex.source===url&®ex.ignoreCase!==caseSensitiveCheckbox.checked) return;WI.debuggerManager.setShouldBlackboxPattern(regex,false);} this._blackboxPatternCodeMirrorMap.delete(regex);regex=url?new RegExp(url,!caseSensitiveCheckbox.checked?"i":""):null;if(regex) WI.debuggerManager.setShouldBlackboxPattern(regex,true);this._blackboxPatternCodeMirrorMap.set(regex,urlCodeMirror);};urlCodeMirror.addKeyMap({"Enter":update,"Esc":update,});urlCodeMirror.on("blur",update);caseSensitiveCheckbox.addEventListener("change",update);if(!regex) urlCodeMirror.focus();}};WI.BlackboxedGroupTreeElement=class BlackboxedGroupTreeElement extends WI.GeneralTreeElement {constructor(callFrames,{rememberBlackboxedCallFrameGroupToAutoExpand}={}) {const classNames=["blackboxed-group"];super(classNames,WI.BlackboxedGroupView.generateTitle(callFrames),WI.BlackboxedGroupView.generateSubtitle(callFrames));this.toggleOnClick=true;this._callFrames=callFrames;this._rememberBlackboxedCallFrameGroupToAutoExpand=rememberBlackboxedCallFrameGroupToAutoExpand||false;} get callFrames(){return this._callFrames;} get expandable() {return true;} expand() {if(this._rememberBlackboxedCallFrameGroupToAutoExpand) WI.debuggerManager.rememberBlackboxedCallFrameGroupToAutoExpand(this._callFrames);let index=this.parent.children.indexOf(this);for(let i=this._callFrames.length-1;i>=0;--i) this.parent.insertChild(new WI.CallFrameTreeElement(this._callFrames[i]),index);this.parent.removeChild(this);} onenter() {this.expand();return true;} onspace() {this.expand();return true;} customTitleTooltip() {return WI.BlackboxedGroupView.generateTooltip(this._callFrames);}};WI.BlackboxedGroupView=class BlackboxedGroupView {constructor(callFrames) {let element=document.createElement("div");element.className="blackboxed-group";element.title=WI.BlackboxedGroupView.generateTooltip(callFrames);element.addEventListener("click",(event)=>{const options={showFunctionName:true,indicateIfBlackboxed:true};for(let i=callFrames.length-1;i>=0;--i) element.parentElement.insertBefore(new WI.CallFrameView(callFrames[i],options),element);element.remove();});let titleElement=element.appendChild(document.createElement("span"));titleElement.className="title";let iconElement=titleElement.appendChild(document.createElement("img"));iconElement.className="icon";titleElement.append(WI.BlackboxedGroupView.generateTitle(callFrames));let subtitleElement=element.appendChild(document.createElement("span"));subtitleElement.className="subtitle";let separatorElement=subtitleElement.appendChild(document.createElement("span"));separatorElement.className="separator";separatorElement.textContent=" "+emDash+" ";subtitleElement.append(WI.BlackboxedGroupView.generateSubtitle(callFrames));return element;} static generateTitle(callFrames) {return WI.UIString("Blackboxed","Blackboxed @ Debugger Call Stack","Part of the 'Blackboxed - %d call frames' label shown in the debugger call stack when paused instead of subsequent call frames that have been blackboxed.");} static generateSubtitle(callFrames) {if(callFrames.length===1) return WI.UIString("%d call frame","call frame @ Debugger Call Stack","Part of the 'Blackboxed - %d call frame' label shown in the debugger call stack when paused instead of subsequent call frames that have been blackboxed.").format(callFrames.length);return WI.UIString("%d call frames","call frames @ Debugger Call Stack","Part of the 'Blackboxed - %d call frames' label shown in the debugger call stack when paused instead of subsequent call frames that have been blackboxed.").format(callFrames.length);} static generateTooltip(callFrames) {if(callFrames.length===1) return WI.UIString("Click to show %d blackboxed call frame","Click to show blackboxed call frame @ Debugger Call Stack","Tooltip for the 'Blackboxed - %d call frame' label shown in the debugger call stack when paused instead of subsequent call frames that have been blackboxed.").format(callFrames.length);return WI.UIString("Click to show %d blackboxed call frames","Click to show blackboxed call frames @ Debugger Call Stack","Tooltip for the 'Blackboxed - %d call frames' label shown in the debugger call stack when paused instead of subsequent call frames that have been blackboxed.").format(callFrames.length);}};WI.BootstrapScriptTreeElement=class BootstrapScriptTreeElement extends WI.ScriptTreeElement {constructor(bootstrapScript) {super(bootstrapScript);this.addClassName("bootstrap");} onattach() {super.onattach();WI.NetworkManager.addEventListener(WI.NetworkManager.Event.BootstrapScriptEnabledChanged,this._handleNetworkManagerBootstrapScriptEnabledChanged,this);this.status=document.createElement("input");this.status.type="checkbox";this.status.checked=WI.networkManager.bootstrapScriptEnabled;this.status.addEventListener("change",(event)=>{WI.networkManager.bootstrapScriptEnabled=event.target.checked;});} ondetach() {WI.NetworkManager.removeEventListener(WI.NetworkManager.Event.BootstrapScriptEnabledChanged,this._handleNetworkManagerBootstrapScriptEnabledChanged,this);super.ondetach();} ondelete() {WI.networkManager.destroyBootstrapScript();return true;} onspace() {WI.networkManager.bootstrapScriptEnabled=!WI.networkManager.bootstrapScriptEnabled;return true;} canSelectOnMouseDown(event) {if(this.status.contains(event.target)) return false;return super.canSelectOnMouseDown(event);} populateContextMenu(contextMenu,event) {let toggleEnabledString=WI.networkManager.bootstrapScriptEnabled?WI.UIString("Disable Inspector Bootstrap Script"):WI.UIString("Enable Inspector Bootstrap Script");contextMenu.appendItem(toggleEnabledString,()=>{WI.networkManager.bootstrapScriptEnabled=!WI.networkManager.bootstrapScriptEnabled;});contextMenu.appendItem(WI.UIString("Delete Inspector Bootstrap Script"),()=>{WI.networkManager.destroyBootstrapScript();});super.populateContextMenu(contextMenu,event);} updateStatus() {} _handleNetworkManagerBootstrapScriptEnabledChanged(event) {this.status.checked=WI.networkManager.bootstrapScriptEnabled;}};WI.BoxModelDetailsSectionRow=class BoxModelDetailsSectionRow extends WI.DetailsSectionRow {constructor() {super(WI.UIString("No Box Model Information"));this.element.classList.add("box-model");this._nodeStyles=null;this._outermostBox=null;this._outermostBoxWidth=NaN;} get nodeStyles() {return this._nodeStyles;} set nodeStyles(nodeStyles) {if(this._nodeStyles&&this._nodeStyles.computedStyle) this._nodeStyles.computedStyle.removeEventListener(WI.CSSStyleDeclaration.Event.PropertiesChanged,this._refresh,this);this._nodeStyles=nodeStyles;if(this._nodeStyles&&this._nodeStyles.computedStyle) this._nodeStyles.computedStyle.addEventListener(WI.CSSStyleDeclaration.Event.PropertiesChanged,this._refresh,this);this.element.classList.remove("hovered");this._refresh();} get minimumWidth() {if(isNaN(this._outermostBoxWidth)&&this._outermostBox){const margin=6;this._outermostBoxWidth=this._outermostBox.realOffsetWidth+margin;} return this._outermostBoxWidth||0;} _refresh() {if(this._ignoreNextRefresh){this._ignoreNextRefresh=false;return;} this._updateMetrics();} _getPropertyValue(style,propertyName) {let property=style.propertyForName(propertyName);if(!property) return null;return property.value;} _getPropertyValueAsPx(style,propertyName) {let value=this._getPropertyValue(style,propertyName);if(!value) return 0;return Number(value.replace(/px$/,"")||0);} _getBox(computedStyle,componentName) {let prefix=this._getComponentPrefix(componentName);let suffix=this._getComponentSuffix(componentName);let left=this._getPropertyValueAsPx(computedStyle,prefix+"-left"+suffix);let top=this._getPropertyValueAsPx(computedStyle,prefix+"-top"+suffix);let right=this._getPropertyValueAsPx(computedStyle,prefix+"-right"+suffix);let bottom=this._getPropertyValueAsPx(computedStyle,prefix+"-bottom"+suffix);return{left,top,right,bottom};} _getComponentPrefix(componentName) {return componentName==="border-radius"?"border":componentName;} _getComponentSuffix(componentName) {switch(componentName){case"border":return"-width";case"border-radius":return"-radius";} return"";} _highlightDOMNode(showHighlight,mode,event) {event.stopPropagation();let node=showHighlight?this.nodeStyles.node:null;if(node){if(this._highlightMode===mode) return;this._highlightMode=mode;node.highlight(this._highlightMode);}else{this._highlightMode=null;WI.domManager.hideDOMNodeHighlight();} for(var i=0;this._boxElements&&i{function inspectedPage_node_toggleInlineStyleProperty(styleProperty,userInput,setBorderStyleProperty){if(setBorderStyleProperty) this.style.setProperty(setBorderStyleProperty,"solid","important");this.style.setProperty(styleProperty,userInput,"important");} let didToggle=()=>{this._nodeStyles.refresh();};object.callFunction(inspectedPage_node_toggleInlineStyleProperty,[styleProperty,userInput,setBorderStyleProperty],false,didToggle);object.release();});} _editingCommitted(element,userInput,previousContent,context) {this._editingEnded(element,context);this._applyUserInput(element,userInput,previousContent,context,true);}};WI.BoxShadowEditor=class BoxShadowEditor extends WI.Object {constructor() {super();this._element=document.createElement("div");this._element.classList.add("box-shadow-editor");let tableElement=this._element.appendChild(document.createElement("table"));function createInputRow(identifier,label){let id=`box-shadow-editor-${identifier}-input`;let rowElement=tableElement.appendChild(document.createElement("tr"));rowElement.className=identifier;let headerElement=rowElement.appendChild(document.createElement("th"));let labelElement=headerElement.appendChild(document.createElement("label"));labelElement.setAttribute("for",id);labelElement.textContent=label;let dataElement=rowElement.appendChild(document.createElement("td"));let inputElement=dataElement.appendChild(document.createElement("input"));inputElement.type="text";inputElement.id=id;return{rowElement,inputElement};} function createSlider(rowElement,min,max){let dataElement=rowElement.appendChild(document.createElement("td"));let rangeElement=dataElement.appendChild(document.createElement("input"));rangeElement.type="range";rangeElement.min=min;rangeElement.max=max;return rangeElement;} let offsetXRow=createInputRow("offset-x",WI.UIString("Offset X","Offset X @ Box Shadow Editor","Input label for the x-axis of the offset of a CSS box shadow"));this._offsetXInput=offsetXRow.inputElement;this._offsetXInput.spellcheck=false;this._offsetXInput.addEventListener("input",this._handleOffsetXInputInput.bind(this));this._offsetXInput.addEventListener("keydown",this._handleOffsetXInputKeyDown.bind(this));let offsetSliderDataElement=offsetXRow.rowElement.appendChild(document.createElement("td"));offsetSliderDataElement.setAttribute("rowspan",3);this._offsetSliderKnobRadius=5;this._offsetSliderAreaSize=100;const offsetSliderContainerSize=this._offsetSliderAreaSize+(this._offsetSliderKnobRadius*2);this._offsetSliderSVG=offsetSliderDataElement.appendChild(createSVGElement("svg"));this._offsetSliderSVG.setAttribute("tabindex",0);this._offsetSliderSVG.setAttribute("width",offsetSliderContainerSize);this._offsetSliderSVG.setAttribute("height",offsetSliderContainerSize);this._offsetSliderSVG.addEventListener("mousedown",this);this._offsetSliderSVG.addEventListener("keydown",this);this._offsetSliderSVGMouseDownPoint=null;let offsetSliderGroup=this._offsetSliderSVG.appendChild(createSVGElement("g"));offsetSliderGroup.setAttribute("transform",`translate(${this._offsetSliderKnobRadius}, ${this._offsetSliderKnobRadius})`);let offsetSliderXAxisLine=offsetSliderGroup.appendChild(createSVGElement("line"));offsetSliderXAxisLine.classList.add("axis");offsetSliderXAxisLine.setAttribute("x1",this._offsetSliderAreaSize/2);offsetSliderXAxisLine.setAttribute("y1",0);offsetSliderXAxisLine.setAttribute("x2",this._offsetSliderAreaSize/2);offsetSliderXAxisLine.setAttribute("y2",this._offsetSliderAreaSize);let offsetSliderYAxisLine=offsetSliderGroup.appendChild(createSVGElement("line"));offsetSliderYAxisLine.classList.add("axis");offsetSliderYAxisLine.setAttribute("x1",0);offsetSliderYAxisLine.setAttribute("y1",this._offsetSliderAreaSize/2);offsetSliderYAxisLine.setAttribute("x2",this._offsetSliderAreaSize);offsetSliderYAxisLine.setAttribute("y2",this._offsetSliderAreaSize/2);this._offsetSliderLine=offsetSliderGroup.appendChild(createSVGElement("line"));this._offsetSliderLine.setAttribute("x1",this._offsetSliderAreaSize/2);this._offsetSliderLine.setAttribute("y1",this._offsetSliderAreaSize/2);this._offsetSliderKnob=offsetSliderGroup.appendChild(createSVGElement("circle"));let offsetYRow=createInputRow("offset-y",WI.UIString("Offset Y","Offset Y @ Box Shadow Editor","Input label for the y-axis of the offset of a CSS box shadow"));this._offsetYInput=offsetYRow.inputElement;this._offsetYInput.spellcheck=false;this._offsetYInput.addEventListener("input",this._handleOffsetYInputInput.bind(this));this._offsetYInput.addEventListener("keydown",this._handleOffsetYInputKeyDown.bind(this));let insetRow=createInputRow("inset",WI.UIString("Inset","Inset @ Box Shadow Editor","Checkbox label for the inset of a CSS box shadow."));this._insetCheckbox=insetRow.inputElement;this._insetCheckbox.type="checkbox";this._insetCheckbox.addEventListener("change",this._handleInsetCheckboxChange.bind(this));let blurRadiusRow=createInputRow("blur-radius",WI.UIString("Blur","Blur @ Box Shadow Editor","Input label for the blur radius of a CSS box shadow"));this._blurRadiusInput=blurRadiusRow.inputElement;this._blurRadiusInput.spellcheck=false;this._blurRadiusInput.addEventListener("input",this._handleBlurRadiusInputInput.bind(this));this._blurRadiusInput.addEventListener("keydown",this._handleBlurRadiusInputKeyDown.bind(this));this._blurRadiusInput.min=0;this._blurRadiusSlider=createSlider(blurRadiusRow.rowElement,0,100);this._blurRadiusSlider.addEventListener("input",this._handleBlurRadiusSliderInput.bind(this));let spreadRadiusRow=createInputRow("spread-radius",WI.UIString("Spread","Spread @ Box Shadow Editor","Input label for the spread radius of a CSS box shadow"));this._spreadRadiusInput=spreadRadiusRow.inputElement;this._spreadRadiusInput.spellcheck=false;this._spreadRadiusInput.addEventListener("input",this._handleSpreadRadiusInputInput.bind(this));this._spreadRadiusInput.addEventListener("keydown",this._handleSpreadRadiusInputKeyDown.bind(this));this._spreadRadiusSlider=createSlider(spreadRadiusRow.rowElement,-50,50);this._spreadRadiusSlider.addEventListener("input",this._handleSpreadRadiusSliderInput.bind(this));this._colorPicker=new WI.ColorPicker;this._colorPicker.addEventListener(WI.ColorPicker.Event.ColorChanged,this._handleColorChanged,this);this._element.appendChild(this._colorPicker.element);this.boxShadow=new WI.BoxShadow;WI.addWindowKeydownListener(this);} get element(){return this._element;} get boxShadow() {return this._boxShadow;} set boxShadow(boxShadow) {this._boxShadow=boxShadow;let offsetX=this._boxShadow?.offsetX||{value:0,unit:""};let offsetY=this._boxShadow?.offsetY||{value:0,unit:""};this._offsetXInput.value=offsetX.value+offsetX.unit;this._offsetYInput.value=offsetY.value+offsetY.unit;let offsetSliderCenter=this._offsetSliderAreaSize/2;let offsetSliderX=Number.constrain(offsetX.value+offsetSliderCenter,0,this._offsetSliderAreaSize);let offsetSliderY=Number.constrain(offsetY.value+offsetSliderCenter,0,this._offsetSliderAreaSize);this._offsetSliderLine.setAttribute("x2",offsetSliderX);this._offsetSliderKnob.setAttribute("cx",offsetSliderX);this._offsetSliderLine.setAttribute("y2",offsetSliderY);this._offsetSliderKnob.setAttribute("cy",offsetSliderY);let blurRadius=this._boxShadow?.blurRadius||{value:0,unit:""};this._blurRadiusInput.value=blurRadius.value+blurRadius.unit;this._blurRadiusSlider.value=blurRadius.value;let spreadRadius=this._boxShadow?.spreadRadius||{value:0,unit:""};this._spreadRadiusInput.value=spreadRadius.value+spreadRadius.unit;this._spreadRadiusSlider.value=spreadRadius.value;let inset=this._boxShadow?.inset||false;this._insetCheckbox.checked=inset;let color=this._boxShadow?.color||WI.Color.fromString("transparent");this._colorPicker.color=color;} handleEvent(event) {switch(event.type){case"keydown":this._handleOffsetSliderSVGKeyDown(event);return;case"mousedown":this._handleOffsetSliderSVGMouseDown(event);return;case"mousemove":this._handleWindowMouseMove(event);return;case"mouseup":this._handleWindowMouseUp(event);return;}} _updateBoxShadow({offsetX,offsetY,blurRadius,spreadRadius,inset,color}) {let change=false;if(!offsetX) offsetX=this._boxShadow.offsetX;else if(!Object.shallowEqual(offsetX,this._boxShadow.offsetX)) change=true;if(!offsetY) offsetY=this._boxShadow.offsetY;else if(!Object.shallowEqual(offsetY,this._boxShadow.offsetY)) change=true;if(!blurRadius) blurRadius=this._boxShadow.blurRadius;else if(!Object.shallowEqual(blurRadius,this._boxShadow.blurRadius)) change=true;if(!spreadRadius) spreadRadius=this._boxShadow.spreadRadius;else if(!Object.shallowEqual(spreadRadius,this._boxShadow.spreadRadius)) change=true;if(inset===undefined) inset=this._boxShadow.inset;else if(inset!==this._boxShadow.inset) change=true;if(!color) color=this._boxShadow.color;else if(color.toString()!==this._boxShadow.color?.toString()) change=true;if(!change) return;this.boxShadow=new WI.BoxShadow(offsetX,offsetY,blurRadius,spreadRadius,inset,color);this.dispatchEventToListeners(WI.BoxShadowEditor.Event.BoxShadowChanged,{boxShadow:this._boxShadow});} _updateBoxShadowOffsetFromSliderMouseEvent(event,saveMouseDownPoint) {let point=WI.Point.fromEventInElement(event,this._offsetSliderSVG);point.x=Number.constrain(point.x-this._offsetSliderKnobRadius,0,this._offsetSliderAreaSize);point.y=Number.constrain(point.y-this._offsetSliderKnobRadius,0,this._offsetSliderAreaSize);if(saveMouseDownPoint) this._offsetSliderSVGMouseDownPoint=point;if(event.shiftKey&&this._offsetSliderSVGMouseDownPoint){if(Math.abs(this._offsetSliderSVGMouseDownPoint.x-point.x)>Math.abs(this._offsetSliderSVGMouseDownPoint.y-point.y)) point.y=this._offsetSliderSVGMouseDownPoint.y;else point.x=this._offsetSliderSVGMouseDownPoint.x;} let offsetSliderCenter=this._offsetSliderAreaSize/2;this._updateBoxShadow({offsetX:{value:point.x-offsetSliderCenter,unit:this._boxShadow.offsetX.unit,},offsetY:{value:point.y-offsetSliderCenter,unit:this._boxShadow.offsetY.unit,},});} _determineShiftForEvent(event) {let shift=0;if(event.key==="ArrowUp") shift=1;else if(event.key==="ArrowDown") shift=-1;if(!shift) return NaN;if(event.metaKey) shift*=100;else if(event.shiftKey) shift*=10;else if(event.altKey) shift/=10;event.preventDefault();return shift;} _handleOffsetSliderSVGKeyDown(event){let shiftX=0;let shiftY=0;switch(event.keyCode){case WI.KeyboardShortcut.Key.Up.keyCode:shiftY=-1;break;case WI.KeyboardShortcut.Key.Right.keyCode:shiftX=1;break;case WI.KeyboardShortcut.Key.Down.keyCode:shiftY=1;break;case WI.KeyboardShortcut.Key.Left.keyCode:shiftX=-1;break;} if(!shiftX&&!shiftY) return false;let multiplier=1;if(event.shiftKey) multiplier=10;else if(event.altKey) multiplier=0.1;shiftX*=multiplier;shiftY*=multiplier;let offsetValueLimit=this._offsetSliderAreaSize/2;this._updateBoxShadow({offsetX:{value:Number.constrain(this._boxShadow.offsetX.value+shiftX,-1*offsetValueLimit,offsetValueLimit).maxDecimals(1),unit:this._boxShadow.offsetX.unit,},offsetY:{value:Number.constrain(this._boxShadow.offsetY.value+shiftY,-1*offsetValueLimit,offsetValueLimit).maxDecimals(1),unit:this._boxShadow.offsetY.unit,},});} _handleOffsetSliderSVGMouseDown(event) {if(event.button!==0) return;event.stop();this._offsetSliderSVG.focus();window.addEventListener("mousemove",this,true);window.addEventListener("mouseup",this,true);this._updateBoxShadowOffsetFromSliderMouseEvent(event,true);} _handleWindowMouseMove(event) {this._updateBoxShadowOffsetFromSliderMouseEvent(event);} _handleWindowMouseUp(event) {this._offsetSliderSVGMouseDownPoint=null;window.removeEventListener("mousemove",this,true);window.removeEventListener("mouseup",this,true);} _handleOffsetXInputInput(event) {this._updateBoxShadow({offsetX:WI.BoxShadow.parseNumberComponent(this._offsetXInput.value),});} _handleOffsetXInputKeyDown(event) {let shift=this._determineShiftForEvent(event);if(isNaN(shift)) return;this._updateBoxShadow({offsetX:{value:(this._boxShadow.offsetX.value+shift).maxDecimals(1),unit:this._boxShadow.offsetX.unit,},});} _handleOffsetYInputInput(event) {this._updateBoxShadow({offsetY:WI.BoxShadow.parseNumberComponent(this._offsetYInput.value),});} _handleOffsetYInputKeyDown(event) {let shift=this._determineShiftForEvent(event);if(isNaN(shift)) return;this._updateBoxShadow({offsetY:{value:(this._boxShadow.offsetY.value+shift).maxDecimals(1),unit:this._boxShadow.offsetY.unit,},});} _handleBlurRadiusInputInput(event) {this._updateBoxShadow({blurRadius:WI.BoxShadow.parseNumberComponent(this._blurRadiusInput.value),});} _handleBlurRadiusInputKeyDown(event) {let shift=this._determineShiftForEvent(event);if(isNaN(shift)) return;this._updateBoxShadow({blurRadius:{value:(this._boxShadow.blurRadius.value+shift).maxDecimals(1),unit:this._boxShadow.blurRadius.unit,}});} _handleBlurRadiusSliderInput(event) {this._updateBoxShadow({blurRadius:{value:this._blurRadiusSlider.valueAsNumber,unit:this._boxShadow.blurRadius.unit,}});} _handleSpreadRadiusInputInput(event) {this._updateBoxShadow({spreadRadius:WI.BoxShadow.parseNumberComponent(this._spreadRadiusInput.value),});} _handleSpreadRadiusInputKeyDown(event) {let shift=this._determineShiftForEvent(event);if(isNaN(shift)) return;this._updateBoxShadow({spreadRadius:{value:(this._boxShadow.spreadRadius.value+shift).maxDecimals(1),unit:this._boxShadow.spreadRadius.unit,}});} _handleSpreadRadiusSliderInput(event) {this._updateBoxShadow({spreadRadius:{value:this._spreadRadiusSlider.valueAsNumber,unit:this._boxShadow.spreadRadius.unit,}});} _handleInsetCheckboxChange(event) {this._updateBoxShadow({inset:!!this._insetCheckbox.checked,});} _handleColorChanged(event) {this._updateBoxShadow({color:this._colorPicker.color,});}};WI.BoxShadowEditor.Event={BoxShadowChanged:"box-shadow-editor-box-shadow-changed"};WI.BreakpointActionView=class BreakpointActionView extends WI.Object {constructor(action,delegate,{omitFocus}={}) {super();this._action=action;this._delegate=delegate;this._element=document.createElement("div");this._element.className="breakpoint-action-block";var header=this._element.appendChild(document.createElement("div"));header.className="breakpoint-action-block-header";var picker=header.appendChild(document.createElement("select"));picker.addEventListener("change",this._pickerChanged.bind(this));for(var key in WI.BreakpointAction.Type){var type=WI.BreakpointAction.Type[key];var option=document.createElement("option");option.textContent=WI.BreakpointActionView.displayStringForType(type);option.selected=this._action.type===type;option.value=type;picker.add(option);} let buttonContainerElement=header.appendChild(document.createElement("div"));buttonContainerElement.classList.add("breakpoint-action-button-container");let appendActionButton=buttonContainerElement.appendChild(document.createElement("button"));appendActionButton.className="breakpoint-action-append-button";appendActionButton.addEventListener("click",this._appendActionButtonClicked.bind(this));appendActionButton.title=WI.UIString("Add new breakpoint action after this action");let removeActionButton=buttonContainerElement.appendChild(document.createElement("button"));removeActionButton.className="breakpoint-action-remove-button";removeActionButton.addEventListener("click",this._removeAction.bind(this));removeActionButton.title=WI.UIString("Delete this breakpoint action");this._bodyElement=this._element.appendChild(document.createElement("div"));this._bodyElement.className="breakpoint-action-block-body";this._updateBody(omitFocus);} static displayStringForType(type) {switch(type){case WI.BreakpointAction.Type.Log:return WI.UIString("Log Message");case WI.BreakpointAction.Type.Evaluate:return WI.UIString("Evaluate JavaScript");case WI.BreakpointAction.Type.Sound:return WI.UIString("Play Sound");case WI.BreakpointAction.Type.Probe:return WI.UIString("Probe Expression");default:return"";}} get action() {return this._action;} get element() {return this._element;} _pickerChanged(event) {this._action.type=event.target.value;this._updateBody();this._delegate.breakpointActionViewResized(this);} _appendActionButtonClicked(event) {this._delegate.breakpointActionViewAppendActionView(this,new WI.BreakpointAction(this._action.type));} _removeAction() {this._delegate.breakpointActionViewRemoveActionView(this);} _updateBody(omitFocus) {this._bodyElement.removeChildren();let createOptionsElements=()=>{let optionsElement=document.createElement("div");let emulateUserGestureLabel=optionsElement.appendChild(document.createElement("label"));this._emulateUserGestureCheckbox=emulateUserGestureLabel.appendChild(document.createElement("input"));this._emulateUserGestureCheckbox.type="checkbox";this._emulateUserGestureCheckbox.checked=this._action.emulateUserGesture;this._emulateUserGestureCheckbox.addEventListener("change",this._handleEmulateUserGestureCheckboxChange.bind(this));emulateUserGestureLabel.appendChild(document.createTextNode(WI.UIString("Emulate User Gesture","Emulate User Gesture @ breakpoint action configuration","Checkbox shown when configuring log/evaluate/probe breakpoint actions to cause it to be evaluated as though it was in response to user interaction.")));return optionsElement;};switch(this._action.type){case WI.BreakpointAction.Type.Log:this._bodyElement.hidden=false;var input=this._bodyElement.appendChild(document.createElement("input"));input.placeholder=WI.UIString("Message");input.addEventListener("input",this._handleLogInputInput.bind(this));input.value=this._action.data||"";input.spellcheck=false;if(!omitFocus) setTimeout(function(){input.focus();},0);var flexWrapper=this._bodyElement.appendChild(document.createElement("div"));flexWrapper.className="flex";if(WI.BreakpointAction.supportsEmulateUserAction()) flexWrapper.appendChild(createOptionsElements());var descriptionElement=flexWrapper.appendChild(document.createElement("div"));descriptionElement.classList.add("description");descriptionElement.setAttribute("dir","ltr");descriptionElement.textContent=WI.UIString("${expr} = expression");break;case WI.BreakpointAction.Type.Evaluate:case WI.BreakpointAction.Type.Probe:this._bodyElement.hidden=false;var editorElement=this._bodyElement.appendChild(document.createElement("div"));editorElement.classList.add("breakpoint-action-eval-editor");editorElement.classList.add(WI.SyntaxHighlightedStyleClassName);this._codeMirror=WI.CodeMirrorEditor.create(editorElement,{lineWrapping:true,mode:"text/javascript",matchBrackets:true,value:this._action.data||"",});this._codeMirrorClientHeight=NaN;this._codeMirror.on("changes",this._handleJavaScriptCodeMirrorChanges.bind(this));var completionController=new WI.CodeMirrorCompletionController(this._delegate.breakpointActionViewCodeMirrorCompletionControllerMode(this,this._codeMirror),this._codeMirror);completionController.addExtendedCompletionProvider("javascript",WI.javaScriptRuntimeCompletionProvider);if(WI.BreakpointAction.supportsEmulateUserAction()) this._bodyElement.appendChild(createOptionsElements());setTimeout(()=>{this._codeMirror.refresh();if(!omitFocus) this._codeMirror.focus();},0);break;case WI.BreakpointAction.Type.Sound:this._bodyElement.hidden=true;break;default:this._bodyElement.hidden=true;break;}} _handleLogInputInput(event) {this._action.data=event.target.value;} _handleJavaScriptCodeMirrorChanges(codeMirror,changes) {this._action.data=this._codeMirror.getValue().trim();let{clientHeight}=this._codeMirror.getScrollInfo();if(clientHeight!==this._codeMirrorClientHeight){this._codeMirrorClientHeight=clientHeight;this._delegate.breakpointActionViewResized(this);}} _handleEmulateUserGestureCheckboxChange(event) {this._action.emulateUserGesture=this._emulateUserGestureCheckbox.checked;}};WI.BreakpointInlineWidget=class BreakpointInlineWidget {constructor(breakpointOrSourceCodeLocation) {if(breakpointOrSourceCodeLocation instanceof WI.JavaScriptBreakpoint){this._breakpoint=breakpointOrSourceCodeLocation;this._sourceCodeLocation=this._breakpoint.sourceCodeLocation;this._addBreakpointEventListeners();}else{this._sourceCodeLocation=breakpointOrSourceCodeLocation;this._breakpoint=null;} this._element=document.createElement("span");this._element.classList.add("inline-widget","breakpoint");this._element.addEventListener("click",this._handleClick.bind(this));this._element.addEventListener("contextmenu",this._handleContextmenu.bind(this));WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BreakpointsEnabledDidChange,this._handleBreakpointsEnabledDidChange,this);this._update();} get element(){return this._element;} get sourceCodeLocation(){return this._sourceCodeLocation;} get breakpoint(){return this._breakpoint;} _update() {this._element.classList.toggle("placeholder",!this._breakpoint);this._element.classList.toggle("resolved",this._breakpoint?.resolved||WI.debuggerManager.breakpointsEnabled);this._element.classList.toggle("disabled",!!this._breakpoint?.disabled);this._element.classList.toggle("auto-continue",!!this._breakpoint?.autoContinue);} _createBreakpoint(){this._breakpoint=new WI.JavaScriptBreakpoint(this._sourceCodeLocation,{resolved:true});WI.debuggerManager.addBreakpoint(this._breakpoint);this._addBreakpointEventListeners();this._update();} _addBreakpointEventListeners() {this._breakpoint.addEventListener(WI.Breakpoint.Event.DisabledStateDidChange,this._handleBreakpointDisabledStateChanged,this);this._breakpoint.addEventListener(WI.Breakpoint.Event.AutoContinueDidChange,this._handleBreakpointAutoContinueChanged,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BreakpointRemoved,this._handleBreakpointRemoved,this);} _handleClick(event) {if(this._breakpoint){this._breakpoint.disabled=!this._breakpoint.disabled;return;} this._createBreakpoint();} _handleContextmenu(event) {let contextMenu=WI.ContextMenu.createFromEvent(event);if(!this._breakpoint){contextMenu.appendItem(WI.UIString("Add Breakpoint"),()=>{this._createBreakpoint();});return;} WI.BreakpointPopover.appendContextMenuItems(contextMenu,this._breakpoint,this._element);if(!WI.isShowingSourcesTab()){contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Reveal in Sources Tab"),()=>{WI.showSourcesTab({representedObjectToSelect:this._breakpoint,initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});}} _handleBreakpointsEnabledDidChange(event) {this._update();} _handleBreakpointDisabledStateChanged(event) {this._update();} _handleBreakpointAutoContinueChanged(event) {this._update();} _handleBreakpointRemoved(event) {let{breakpoint}=event.data;if(breakpoint!==this._breakpoint) return;this._breakpoint.removeEventListener(WI.Breakpoint.Event.DisabledStateDidChange,this._handleBreakpointDisabledStateChanged,this);this._breakpoint.removeEventListener(WI.Breakpoint.Event.AutoContinueDidChange,this._handleBreakpointAutoContinueChanged,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.BreakpointRemoved,this._handleBreakpointRemoved,this);this._breakpoint=null;this._update();}};WI.BreakpointPopover=class BreakpointPopover extends WI.Popover {constructor(delegate,breakpoint) {super(delegate);this._breakpoint=breakpoint||null;this._contentElement=null;this._conditionCodeMirror=null;this._ignoreCountInputElement=null;this._actionsContainerElement=null;this._actionViews=[];this._optionsRowElement=null;this._autoContinueCheckboxElement=null;this._targetElement=null;this.windowResizeHandler=this._presentOverTargetElement.bind(this);} static show(breakpoint,targetElement) {const delegate=null;let popover;if(breakpoint instanceof WI.EventBreakpoint) popover=new WI.EventBreakpointPopover(delegate,breakpoint);else if(breakpoint instanceof WI.URLBreakpoint) popover=new WI.URLBreakpointPopover(delegate,breakpoint);else if(breakpoint instanceof WI.SymbolicBreakpoint) popover=new WI.SymbolicBreakpointPopover(delegate,breakpoint);else popover=new WI.BreakpointPopover(delegate,breakpoint);popover.show(targetElement);} static appendContextMenuItems(contextMenu,breakpoint,targetElement) {if(breakpoint.editable&&targetElement){contextMenu.appendItem(WI.UIString("Edit Breakpoint\u2026"),()=>{WI.BreakpointPopover.show(breakpoint,targetElement);});} if(!breakpoint.disabled){contextMenu.appendItem(WI.UIString("Disable Breakpoint"),()=>{breakpoint.disabled=!breakpoint.disabled;});if(breakpoint.editable&&breakpoint.autoContinue){contextMenu.appendItem(WI.UIString("Cancel Automatic Continue"),()=>{breakpoint.autoContinue=!breakpoint.autoContinue;});}}else{contextMenu.appendItem(WI.UIString("Enable Breakpoint"),()=>{breakpoint.disabled=!breakpoint.disabled;});} if(breakpoint.editable&&!breakpoint.autoContinue&&!breakpoint.disabled&&breakpoint.actions.length){contextMenu.appendItem(WI.UIString("Set to Automatically Continue"),()=>{breakpoint.autoContinue=!breakpoint.autoContinue;});} if(breakpoint.removable){contextMenu.appendItem(WI.UIString("Delete Breakpoint"),()=>{breakpoint.remove();});}else{contextMenu.appendItem(WI.UIString("Reset Breakpoint","Reset Breakpoint @ Breakpoint Context Menu","Context menu action for resetting the breakpoint to its initial configuration."),()=>{breakpoint.reset();});} if(breakpoint instanceof WI.JavaScriptBreakpoint&&breakpoint.sourceCodeLocation.hasMappedLocation()){contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Reveal in Original Resource"),()=>{const options={ignoreNetworkTab:true,ignoreSearchTab:true,};WI.showOriginalOrFormattedSourceCodeLocation(breakpoint.sourceCodeLocation,options);});}} get breakpoint(){return this._breakpoint;} show(targetElement) {this._targetElement=targetElement;this._contentElement=document.createElement("div");this._contentElement.classList.add("edit-breakpoint-popover-content");if(this._breakpoint){let toggleLabelElement=this._contentElement.appendChild(document.createElement("label"));toggleLabelElement.className="toggle";let toggleCheckboxElement=toggleLabelElement.appendChild(document.createElement("input"));toggleCheckboxElement.type="checkbox";toggleCheckboxElement.checked=!this._breakpoint.disabled;toggleCheckboxElement.addEventListener("change",this._handleEnabledCheckboxChange.bind(this));toggleLabelElement.appendChild(document.createTextNode(this._breakpoint.displayName));} this._tableElement=this._contentElement.appendChild(document.createElement("table"));if(!this._breakpoint) this.populateContent();if(this._breakpoint?.editable||this.constructor.supportsEditing){let conditionLabelElement=document.createElement("label");conditionLabelElement.textContent=WI.UIString("Condition");let conditionEditorElement=document.createElement("div");conditionEditorElement.classList.add("editor",WI.SyntaxHighlightedStyleClassName);this._conditionCodeMirror=WI.CodeMirrorEditor.create(conditionEditorElement,{extraKeys:{Tab:false},lineWrapping:false,mode:"text/javascript",matchBrackets:true,placeholder:WI.UIString("Conditional expression"),scrollbarStyle:null,value:this._breakpoint?.condition||"",});let conditionCodeMirrorInputField=this._conditionCodeMirror.getInputField();conditionCodeMirrorInputField.id="edit-breakpoint-popover-content-condition";conditionLabelElement.setAttribute("for",conditionCodeMirrorInputField.id);this.addRow("condition",conditionLabelElement,conditionEditorElement);this._conditionCodeMirror.addKeyMap({"Enter":()=>{this.dismiss();},"Esc":()=>{this.dismiss();},});this._conditionCodeMirror.on("beforeChange",this._handleConditionCodeMirrorBeforeChange.bind(this));if(this._breakpoint) this._conditionCodeMirror.on("change",this._handleConditionCodeMirrorChange.bind(this));let completionController=new WI.CodeMirrorCompletionController(this.codeMirrorCompletionControllerMode,this._conditionCodeMirror,this);completionController.addExtendedCompletionProvider("javascript",WI.javaScriptRuntimeCompletionProvider);let ignoreCountLabelElement=document.createElement("label");ignoreCountLabelElement.textContent=WI.UIString("Ignore");let ignoreCountContentFragment=document.createDocumentFragment();this._ignoreCountInputElement=ignoreCountContentFragment.appendChild(document.createElement("input"));this._ignoreCountInputElement.id="edit-breakpoint-popover-ignore-count";this._ignoreCountInputElement.type="number";this._ignoreCountInputElement.min=0;this._ignoreCountInputElement.value=this._breakpoint?.ignoreCount||0;this._ignoreCountInputElement.addEventListener("change",this._handleIgnoreCountInputChange.bind(this));this._ignoreCountText=ignoreCountContentFragment.appendChild(document.createElement("label"));this._updateIgnoreCountText();ignoreCountLabelElement.setAttribute("for",this._ignoreCountInputElement.id);this._ignoreCountText.setAttribute("for",this._ignoreCountInputElement.id);this.addRow("ignore-count",ignoreCountLabelElement,ignoreCountContentFragment);let actionsLabelElement=document.createElement("label");actionsLabelElement.textContent=WI.UIString("Action");this._actionsContainerElement=document.createElement("div");if(!this._breakpoint?.actions.length) this._createAddActionButton();else{this._contentElement.classList.add("wide");for(let i=0;i{this._conditionCodeMirror.refresh();if(this._breakpoint) this._conditionCodeMirror.focus();this.update();});} let referencePage=this._breakpoint?.constructor.ReferencePage||this.constructor.ReferencePage;if(this._breakpoint) referencePage=referencePage.Configuration;this._contentElement.appendChild(referencePage.createLinkElement());this.content=this._contentElement;this._presentOverTargetElement();} dismiss() {this._breakpoint??=this.createBreakpoint({condition:this._conditionCodeMirror?this._conditionCodeMirror.getValue().trim():"",actions:this._actionViews.map((breakpointActionView)=>breakpointActionView.action),ignoreCount:this._ignoreCountInputElement?this._parseIgnoreCountNumber():0,autoContinue:this._autoContinueCheckboxElement?this._autoContinueCheckboxElement.checked:false,});let emptyActions=this._breakpoint?.actions.filter(function(action){if(action.type===WI.BreakpointAction.Type.Sound) return false;return!action.data?.trim();})||[];for(let action of emptyActions) this._breakpoint.removeAction(action);super.dismiss();} completionControllerShouldAllowEscapeCompletion() {return false;} breakpointActionViewCodeMirrorCompletionControllerMode(breakpointActionView,codeMirror) {return this.codeMirrorCompletionControllerMode;} breakpointActionViewAppendActionView(breakpointActionView,newBreakpointAction) {this._breakpoint?.addAction(newBreakpointAction,{precedingAction:breakpointActionView.action});let newBreakpointActionView=new WI.BreakpointActionView(newBreakpointAction,this);let index=this._actionViews.indexOf(breakpointActionView)+1;this._insertBreakpointActionView(newBreakpointActionView,index);this._optionsRowElement.classList.remove("hidden");this.update();} breakpointActionViewRemoveActionView(breakpointActionView) {this._breakpoint?.removeAction(breakpointActionView.action);breakpointActionView.element.remove();this._actionViews.remove(breakpointActionView);if(!this._actionViews.length){this._createAddActionButton();this._optionsRowElement.classList.add("hidden");this._autoContinueCheckboxElement.checked=false;} this.update();} breakpointActionViewResized(breakpointActionView) {this.update();} get codeMirrorCompletionControllerMode() {if(this._breakpoint===WI.debuggerManager.allExceptionsBreakpoint||this._breakpoint===WI.debuggerManager.uncaughtExceptionsBreakpoint) return WI.CodeMirrorCompletionController.Mode.ExceptionBreakpoint;return WI.CodeMirrorCompletionController.Mode.Basic;} populateContent() {throw WI.NotImplementedError.subclassMustOverride();} addRow(className,label,content) {let rowElement=this._tableElement.appendChild(document.createElement("tr"));rowElement.className=className;let headerElement=rowElement.appendChild(document.createElement("th"));headerElement.append(label);let dataElement=rowElement.appendChild(document.createElement("td"));dataElement.append(content);return rowElement;} createBreakpoint(options={}) {throw WI.NotImplementedError.subclassMustOverride();} _presentOverTargetElement() {if(!this._targetElement) return;let targetFrame=WI.Rect.rectFromClientRect(this._targetElement.getBoundingClientRect());this.present(targetFrame.pad(2),[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);} _parseIgnoreCountNumber() {let ignoreCount=0;if(this._ignoreCountInputElement.value){ignoreCount=parseInt(this._ignoreCountInputElement.value,10);if(isNaN(ignoreCount)||ignoreCount<0) ignoreCount=0;} return ignoreCount;} _updateIgnoreCountText() {if(this._parseIgnoreCountNumber()===1) this._ignoreCountText.textContent=WI.UIString("time before stopping");else this._ignoreCountText.textContent=WI.UIString("times before stopping");} _createAddActionButton() {this._contentElement.classList.remove("wide");this._actionsContainerElement.removeChildren();let addActionButton=this._actionsContainerElement.appendChild(document.createElement("button"));addActionButton.textContent=WI.UIString("Add Action");addActionButton.addEventListener("click",this._handleAddActionButtonClick.bind(this));} _insertBreakpointActionView(breakpointActionView,index=this._actionViews.length) {if(index>=this._actionViews.length){this._actionsContainerElement.appendChild(breakpointActionView.element);this._actionViews.push(breakpointActionView);}else{this._actionsContainerElement.insertBefore(breakpointActionView.element,this._actionViews[index].element);this._actionViews.splice(index,0,breakpointActionView)}} _handleEnabledCheckboxChange(event) {this._breakpoint.disabled=!event.target.checked;} _handleConditionCodeMirrorBeforeChange(codeMirror,change) {if(change.update){let newText=change.text.join("").replace(/\n/g,"");change.update(change.from,change.to,[newText]);} return true;} _handleConditionCodeMirrorChange(codeMirror,change) {this._breakpoint.condition=this._conditionCodeMirror.getValue().trim();} _handleIgnoreCountInputChange(event) {let ignoreCount=this._parseIgnoreCountNumber();this._ignoreCountInputElement.value=ignoreCount;if(this._breakpoint) this._breakpoint.ignoreCount=ignoreCount;this._updateIgnoreCountText();} _handleAddActionButtonClick(event) {this._contentElement.classList.add("wide");this._actionsContainerElement.removeChildren();let action=new WI.BreakpointAction(WI.BreakpointAction.Type.Evaluate);this._breakpoint?.addAction(action);let breakpointActionView=new WI.BreakpointActionView(action,this);this._insertBreakpointActionView(breakpointActionView);this._optionsRowElement.classList.remove("hidden");setTimeout(()=>{this.update();});} _handleAutoContinueCheckboxChange(event) {if(this._breakpoint) this._breakpoint.autoContinue=this._autoContinueCheckboxElement.checked;}};WI.BreakpointTreeElement=class BreakpointTreeElement extends WI.GeneralTreeElement {constructor(breakpoint,{classNames,title,subtitle}={}) {if(!Array.isArray(classNames)) classNames=[];classNames.push("breakpoint");super(classNames,title,subtitle,breakpoint);this._breakpoint=breakpoint;this._probeSet=null;this.status=WI.ImageUtilities.useSVGSymbol("Images/Breakpoint.svg");this.status.className="status-image";this.status.addEventListener("mousedown",this._statusImageElementMouseDown.bind(this));this.status.addEventListener("click",this._statusImageElementClicked.bind(this));this.status.addEventListener("dblclick",this._handleStatusImageElementDoubleClicked.bind(this));this.updateStatus();this._iconAnimationLayerElement=document.createElement("span");this.iconElement.appendChild(this._iconAnimationLayerElement);this.tooltipHandledSeparately=true;} get breakpoint() {return this._breakpoint;} ondelete() { this.__deletedViaDeleteKeyboardShortcut=true;if(this._breakpoint.removable){this._breakpoint.remove();return true;} if(this._breakpoint.disabled) InspectorFrontendHost.beep();else{this._breakpoint.disabled=true;this._breakpoint.reset();} return false;} onenter() {this._breakpoint.disabled=!this._breakpoint.disabled;return true;} onspace() {this._breakpoint.disabled=!this._breakpoint.disabled;return true;} onattach() {super.onattach();this._breakpoint.addEventListener(WI.Breakpoint.Event.DisabledStateDidChange,this.updateStatus,this);this._breakpoint.addEventListener(WI.Breakpoint.Event.AutoContinueDidChange,this.updateStatus,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BreakpointsEnabledDidChange,this.updateStatus,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ProbeSetAdded,this._probeSetAdded,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ProbeSetRemoved,this._probeSetRemoved,this);for(var probeSet of WI.debuggerManager.probeSets) if(probeSet.breakpoint===this._breakpoint) this._addProbeSet(probeSet);} ondetach() {super.ondetach();this._breakpoint.removeEventListener(WI.Breakpoint.Event.DisabledStateDidChange,this.updateStatus,this);this._breakpoint.removeEventListener(WI.Breakpoint.Event.AutoContinueDidChange,this.updateStatus,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.BreakpointsEnabledDidChange,this.updateStatus,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ProbeSetAdded,this._probeSetAdded,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ProbeSetRemoved,this._probeSetRemoved,this);if(this._probeSet) this._removeProbeSet(this._probeSet);} populateContextMenu(contextMenu,event) {WI.BreakpointPopover.appendContextMenuItems(contextMenu,this._breakpoint,this.status);super.populateContextMenu(contextMenu,event);} updateStatus() {if(!this.status) return;this.status.classList.toggle("resolved",this._breakpoint.resolved);this.status.classList.toggle("disabled",this._breakpoint.disabled);if(this._breakpoint.editable) this.status.classList.toggle("auto-continue",this._breakpoint.autoContinue);} _addProbeSet(probeSet) {this._probeSet=probeSet;probeSet.addEventListener(WI.ProbeSet.Event.SamplesCleared,this._samplesCleared,this);probeSet.dataTable.addEventListener(WI.ProbeSetDataTable.Event.FrameInserted,this._dataUpdated,this);} _removeProbeSet(probeSet) {probeSet.removeEventListener(WI.ProbeSet.Event.SamplesCleared,this._samplesCleared,this);probeSet.dataTable.removeEventListener(WI.ProbeSetDataTable.Event.FrameInserted,this._dataUpdated,this);this._probeSet=null;} _probeSetAdded(event) {var probeSet=event.data.probeSet;if(probeSet.breakpoint===this._breakpoint) this._addProbeSet(probeSet);} _probeSetRemoved(event) {var probeSet=event.data.probeSet;if(probeSet.breakpoint===this._breakpoint) this._removeProbeSet(probeSet);} _samplesCleared(event) {var oldTable=event.data.oldTable;oldTable.removeEventListener(WI.ProbeSetDataTable.Event.FrameInserted,this._dataUpdated,this);this._probeSet.dataTable.addEventListener(WI.ProbeSetDataTable.Event.FrameInserted,this._dataUpdated,this);} _dataUpdated() {if(this.element.classList.contains("data-updated")){clearTimeout(this._removeIconAnimationTimeoutIdentifier);this.element.classList.remove("data-updated");window.requestAnimationFrame(this._dataUpdated.bind(this));return;} this.element.classList.add("data-updated");this._removeIconAnimationTimeoutIdentifier=setTimeout(()=>{this.element.classList.remove("data-updated");},WI.BreakpointTreeElement.ProbeDataUpdatedAnimationDuration);} _statusImageElementMouseDown(event) {event.stopPropagation();} _statusImageElementClicked(event) {this._breakpoint.disabled=!this._breakpoint.disabled;} _handleStatusImageElementDoubleClicked(event) {WI.BreakpointPopover.show(this._breakpoint,this.status);}};WI.BreakpointTreeElement.ProbeDataUpdatedAnimationDuration=400;WI.CPUTimelineOverviewGraph=class CPUTimelineOverviewGraph extends WI.TimelineOverviewGraph {constructor(timeline,timelineOverview) {super(timelineOverview);this.element.classList.add("cpu");this._cpuTimeline=timeline;this._cpuTimeline.addEventListener(WI.Timeline.Event.RecordAdded,this._cpuTimelineRecordAdded,this);let size=new WI.Size(0,this.height);this._chart=new WI.StackedColumnChart(size);this._chart.initializeSections(["main-thread-usage","worker-thread-usage","total-usage"]);this.addSubview(this._chart);this.element.appendChild(this._chart.element);this._chart.element.addEventListener("click",this._handleChartClick.bind(this));this._legendElement=this.element.appendChild(document.createElement("div"));this._legendElement.classList.add("legend");this._lastSelectedRecordInLayout=null;this.reset();for(let record of this._cpuTimeline.records) this._processRecord(record);} get height() {return 60;} reset() {super.reset();this._maxUsage=0;this._cachedMaxUsage=undefined;this._lastSelectedRecordInLayout=null;this._updateLegend();this._chart.clear();this._chart.needsLayout();} layout() {super.layout();if(this.hidden) return;this._updateLegend();this._chart.clear();let graphWidth=this.timelineOverview.scrollContainerWidth;if(isNaN(graphWidth)) return;this._lastSelectedRecordInLayout=this.selectedRecord;if(this._chart.size.width!==graphWidth||this._chart.size.height!==this.height) this._chart.size=new WI.Size(graphWidth,this.height);let graphStartTime=this.startTime;let visibleEndTime=Math.min(this.endTime,this.currentTime);let secondsPerPixel=this.timelineOverview.secondsPerPixel;let maxCapacity=Math.max(20,this._maxUsage*1.05);function xScale(time){return(time-graphStartTime)/secondsPerPixel;} let height=this.height;function yScale(size){return(size/maxCapacity)*height;} let visibleRecords=this._cpuTimeline.recordsInTimeRange(graphStartTime,visibleEndTime,{includeRecordBeforeStart:true,});if(!visibleRecords.length) return;const minimumDisplayHeight=4;for(let record of visibleRecords){let additionalClass=record===this.selectedRecord?"selected":undefined;let w=(record.endTime-record.startTime)/secondsPerPixel;let x=xScale(record.startTime);let h1=Math.max(minimumDisplayHeight,yScale(record.mainThreadUsage));let h2=Math.max(minimumDisplayHeight,yScale(record.mainThreadUsage+record.workerThreadUsage));let h3=Math.max(minimumDisplayHeight,yScale(record.usage));this._chart.addColumnSet(x,height,w,[h1,h2,h3],additionalClass);}} updateSelectedRecord() {super.updateSelectedRecord();if(this._lastSelectedRecordInLayout!==this.selectedRecord){ this.needsLayout();}} _updateLegend() {if(this._cachedMaxUsage===this._maxUsage) return;this._cachedMaxUsage=this._maxUsage;if(!this._maxUsage){this._legendElement.hidden=true;this._legendElement.textContent="";}else{this._legendElement.hidden=false;this._legendElement.textContent=WI.UIString("Maximum CPU Usage: %s").format(Number.percentageString(this._maxUsage/100));}} _graphPositionForMouseEvent(event) {let elements=document.elementsFromPoint(event.pageX,event.pageY);let rectElement=elements.find((x)=>x.localName==="rect");if(!rectElement) return NaN;let chartElement=rectElement.closest(".stacked-column-chart");if(!chartElement) return NaN;let rect=chartElement.getBoundingClientRect();let position=event.pageX-rect.left;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL) return rect.width-position;return position;} _handleChartClick(event) {let position=this._graphPositionForMouseEvent(event);if(isNaN(position)) return;let secondsPerPixel=this.timelineOverview.secondsPerPixel;let graphClickTime=position*secondsPerPixel;let graphStartTime=this.startTime;let clickTime=graphStartTime+graphClickTime;let record=this._cpuTimeline.closestRecordTo(clickTime);if(!record) return;event.__timelineRecordClickEventHandled=true;this.selectedRecord=record;this.needsLayout();} _cpuTimelineRecordAdded(event) {let cpuTimelineRecord=event.data.record;this._processRecord(cpuTimelineRecord);this.needsLayout();} _processRecord(cpuTimelineRecord) {this._maxUsage=Math.max(this._maxUsage,cpuTimelineRecord.usage);}};WI.CPUTimelineView=class CPUTimelineView extends WI.TimelineView {constructor(timeline,extraArguments) {super(timeline,extraArguments);this._recording=extraArguments.recording;this.element.classList.add("cpu");this._sectionLimit=CPUTimelineView.defaultSectionLimit;this._statisticsData=null;this._secondsPerPixelInLayout=undefined;this._visibleRecordsInLayout=[];this._discontinuitiesInLayout=[];this._stickingOverlay=false;this._overlayRecord=null;this._overlayTime=NaN;timeline.addEventListener(WI.Timeline.Event.RecordAdded,this._cpuTimelineRecordAdded,this);} static displayNameForSampleType(type) {switch(type){case CPUTimelineView.SampleType.JavaScript:return WI.UIString("JavaScript");case CPUTimelineView.SampleType.Layout:return WI.repeatedUIString.timelineRecordLayout();case CPUTimelineView.SampleType.Paint:return WI.repeatedUIString.timelineRecordPaint();case CPUTimelineView.SampleType.Style:return WI.UIString("Styles");} console.error("Unknown sample type",type);} static get cpuUsageViewHeight(){return 135;} static get threadCPUUsageViewHeight(){return 65;} static get indicatorViewHeight(){return 15;} static get lowEnergyThreshold(){return 3;} static get mediumEnergyThreshold(){return 30;} static get highEnergyThreshold(){return 100;} static get lowEnergyGraphBoundary(){return 10;} static get mediumEnergyGraphBoundary(){return 70;} static get highEnergyGraphBoundary(){return 100;} static get defaultSectionLimit(){return 5;} attached() {super.attached();this._timelineRuler?.needsLayout(WI.View.LayoutReason.Resize);} closed() {this.representedObject.removeEventListener(WI.Timeline.Event.RecordAdded,this._cpuTimelineRecordAdded,this);} reset() {super.reset();this._resetSourcesFilters();this.clear();} clear() {if(!this.didInitialLayout) return;this._breakdownChart.clear();this._breakdownChart.needsLayout();this._clearBreakdownLegend();this._energyChart.clear();this._energyChart.needsLayout();this._clearEnergyImpactText();this._clearStatistics();this._clearSources();function clearUsageView(view){view.clear();let markersElement=view.chart.element.querySelector(".markers");if(markersElement) markersElement.remove();} clearUsageView(this._cpuUsageView);clearUsageView(this._mainThreadUsageView);clearUsageView(this._webkitThreadUsageView);clearUsageView(this._unknownThreadUsageView);this._removeWorkerThreadViews();this._sectionLimit=CPUTimelineView.defaultSectionLimit;this._statisticsData=null;this._secondsPerPixelInLayout=undefined;this._visibleRecordsInLayout=[];this._discontinuitiesInLayout=[];this._stickingOverlay=false;this._hideGraphOverlay();} get showsFilterBar(){return false;} get scrollableElements() {return[this.element];} initialLayout() {super.initialLayout();this.element.style.setProperty("--cpu-usage-combined-view-height",CPUTimelineView.cpuUsageViewHeight+"px");this.element.style.setProperty("--cpu-usage-view-height",CPUTimelineView.threadCPUUsageViewHeight+"px");this.element.style.setProperty("--cpu-usage-indicator-view-height",CPUTimelineView.indicatorViewHeight+"px");let contentElement=this.element.appendChild(document.createElement("div"));contentElement.classList.add("content");let overviewElement=contentElement.appendChild(document.createElement("div"));overviewElement.classList.add("overview");function createChartContainer(parentElement,subtitle,tooltip){let chartElement=parentElement.appendChild(document.createElement("div"));chartElement.classList.add("chart");let chartSubtitleElement=chartElement.appendChild(document.createElement("div"));chartSubtitleElement.classList.add("subtitle");chartSubtitleElement.textContent=subtitle;if(tooltip) chartSubtitleElement.title=tooltip;let chartFlexContainerElement=chartElement.appendChild(document.createElement("div"));chartFlexContainerElement.classList.add("container");return chartFlexContainerElement;} function appendLegendRow(legendElement,sampleType){let rowElement=legendElement.appendChild(document.createElement("div"));rowElement.classList.add("row");let swatchElement=rowElement.appendChild(document.createElement("div"));swatchElement.classList.add("swatch",sampleType);let valueContainer=rowElement.appendChild(document.createElement("div"));let labelElement=valueContainer.appendChild(document.createElement("div"));labelElement.classList.add("label");labelElement.textContent=WI.CPUTimelineView.displayNameForSampleType(sampleType);let sizeElement=valueContainer.appendChild(document.createElement("div"));sizeElement.classList.add("size");return sizeElement;} let breakdownChartContainerElement=createChartContainer(overviewElement,WI.UIString("Main Thread"),WI.UIString("Breakdown of time spent on the main thread"));this._breakdownChart=new WI.CircleChart({size:120,innerRadiusRatio:0.5});this._breakdownChart.segments=Object.values(WI.CPUTimelineView.SampleType);this.addSubview(this._breakdownChart);breakdownChartContainerElement.appendChild(this._breakdownChart.element);this._breakdownLegendElement=breakdownChartContainerElement.appendChild(document.createElement("div"));this._breakdownLegendElement.classList.add("legend");this._breakdownLegendScriptElement=appendLegendRow(this._breakdownLegendElement,CPUTimelineView.SampleType.JavaScript);this._breakdownLegendLayoutElement=appendLegendRow(this._breakdownLegendElement,CPUTimelineView.SampleType.Layout);this._breakdownLegendPaintElement=appendLegendRow(this._breakdownLegendElement,CPUTimelineView.SampleType.Paint);this._breakdownLegendStyleElement=appendLegendRow(this._breakdownLegendElement,CPUTimelineView.SampleType.Style);let dividerElement=overviewElement.appendChild(document.createElement("div"));dividerElement.classList.add("divider");let energyContainerElement=createChartContainer(overviewElement,WI.UIString("Energy Impact"),WI.UIString("Estimated energy impact."));energyContainerElement.classList.add("energy");let energyChartElement=energyContainerElement.parentElement;let energySubtitleElement=energyChartElement.firstChild;let energyInfoElement=energySubtitleElement.appendChild(document.createElement("span"));energyInfoElement.classList.add("info",WI.Popover.IgnoreAutoDismissClassName);energyInfoElement.textContent="?";this._energyInfoPopover=null;this._energyInfoPopoverContentElement=null;energyInfoElement.addEventListener("click",(event)=>{if(!this._energyInfoPopover) this._energyInfoPopover=new WI.Popover;if(!this._energyInfoPopoverContentElement){this._energyInfoPopoverContentElement=document.createElement("div");this._energyInfoPopoverContentElement.className="energy-info-popover-content";const precision=0;let lowPercent=Number.percentageString(CPUTimelineView.lowEnergyThreshold/100,precision);let p1=this._energyInfoPopoverContentElement.appendChild(document.createElement("p"));p1.textContent=WI.UIString("Periods of high CPU utilization will rapidly drain battery. Strive to keep idle pages under %s average CPU utilization.").format(lowPercent);let p2=this._energyInfoPopoverContentElement.appendChild(document.createElement("p"));p2.textContent=WI.UIString("There is an incurred energy penalty each time the page enters script. This commonly happens with timers, event handlers, and observers.");let p3=this._energyInfoPopoverContentElement.appendChild(document.createElement("p"));p3.textContent=WI.UIString("To improve CPU utilization reduce or batch workloads when the page is not visible or during times when the page is not being interacted with.");} let isRTL=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL;let preferredEdges=isRTL?[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_X]:[WI.RectEdge.MAX_Y,WI.RectEdge.MAX_X];let calculateTargetFrame=()=>WI.Rect.rectFromClientRect(energyInfoElement.getBoundingClientRect()).pad(3);this._energyInfoPopover.presentNewContentWithFrame(this._energyInfoPopoverContentElement,calculateTargetFrame(),preferredEdges);this._energyInfoPopover.windowResizeHandler=()=>{this._energyInfoPopover.present(calculateTargetFrame(),preferredEdges);};});this._energyChart=new WI.GaugeChart({height:110,strokeWidth:20,segments:[{className:"low",limit:CPUTimelineView.lowEnergyGraphBoundary},{className:"medium",limit:CPUTimelineView.mediumEnergyGraphBoundary},{className:"high",limit:CPUTimelineView.highEnergyGraphBoundary},]});this.addSubview(this._energyChart);energyContainerElement.appendChild(this._energyChart.element);let energyTextContainerElement=energyContainerElement.appendChild(document.createElement("div"));this._energyImpactLabelElement=energyTextContainerElement.appendChild(document.createElement("div"));this._energyImpactLabelElement.className="energy-impact";this._energyImpactNumberElement=energyTextContainerElement.appendChild(document.createElement("div"));this._energyImpactNumberElement.className="energy-impact-number";this._energyImpactDurationElement=energyTextContainerElement.appendChild(document.createElement("div"));this._energyImpactDurationElement.className="energy-impact-number";let detailsContainerElement=contentElement.appendChild(document.createElement("div"));detailsContainerElement.classList.add("details");this._timelineRuler=new WI.TimelineRuler;this._timelineRuler.zeroTime=this.zeroTime;this._timelineRuler.startTime=this.startTime;this._timelineRuler.endTime=this.endTime;this.addSubview(this._timelineRuler);detailsContainerElement.appendChild(this._timelineRuler.element); this._timelineRuler.updateLayout(WI.View.LayoutReason.Resize);let detailsSubtitleElement=detailsContainerElement.appendChild(document.createElement("div"));detailsSubtitleElement.classList.add("subtitle");detailsSubtitleElement.textContent=WI.UIString("CPU Usage");this._cpuUsageView=new WI.CPUUsageCombinedView(WI.UIString("Total"));this.addSubview(this._cpuUsageView);detailsContainerElement.appendChild(this._cpuUsageView.element);this._cpuUsageView.rangeChart.element.addEventListener("click",this._handleIndicatorClick.bind(this));this._threadsDetailsElement=detailsContainerElement.appendChild(document.createElement("details"));this._threadsDetailsElement.open=WI.settings.cpuTimelineThreadDetailsExpanded.value;this._threadsDetailsElement.addEventListener("toggle",(event)=>{WI.settings.cpuTimelineThreadDetailsExpanded.value=this._threadsDetailsElement.open;if(this._threadsDetailsElement.open) this.updateLayout(WI.CPUTimelineView.LayoutReason.Internal);});let threadsSubtitleElement=this._threadsDetailsElement.appendChild(document.createElement("summary"));threadsSubtitleElement.classList.add("subtitle","threads","expandable");threadsSubtitleElement.textContent=WI.UIString("Threads");this._mainThreadUsageView=new WI.CPUUsageView(WI.UIString("Main Thread"));this._mainThreadUsageView.element.classList.add("main-thread");this.addSubview(this._mainThreadUsageView);this._threadsDetailsElement.appendChild(this._mainThreadUsageView.element);this._webkitThreadUsageView=new WI.CPUUsageView(WI.UIString("WebKit Threads"));this.addSubview(this._webkitThreadUsageView);this._threadsDetailsElement.appendChild(this._webkitThreadUsageView.element);this._unknownThreadUsageView=new WI.CPUUsageView(WI.UIString("Other Threads"));this.addSubview(this._unknownThreadUsageView);this._threadsDetailsElement.appendChild(this._unknownThreadUsageView.element);this._workerViews=[];this._sourcesFilter={timer:new Set,event:new Set,observer:new Set,};let bottomOverviewElement=contentElement.appendChild(document.createElement("div"));bottomOverviewElement.classList.add("overview");let statisticsContainerElement=createChartContainer(bottomOverviewElement,WI.UIString("Statistics"));statisticsContainerElement.classList.add("stats");this._statisticsTable=statisticsContainerElement.appendChild(document.createElement("table"));this._statisticsRows=[];{let{headerCell,numberCell}=this._createTableRow(this._statisticsTable);headerCell.textContent=WI.UIString("Network Requests:");this._networkRequestsNumberElement=numberCell;} {let{headerCell,numberCell}=this._createTableRow(this._statisticsTable);headerCell.textContent=WI.UIString("Script Entries:");this._scriptEntriesNumberElement=numberCell;} this._clearStatistics();let bottomDividerElement=bottomOverviewElement.appendChild(document.createElement("div"));bottomDividerElement.classList.add("divider");let sourcesContainerElement=createChartContainer(bottomOverviewElement,WI.UIString("Sources"));sourcesContainerElement.classList.add("stats");this._sourcesTable=sourcesContainerElement.appendChild(document.createElement("table"));this._sourcesRows=[];{let{row,headerCell,numberCell,labelCell}=this._createTableRow(this._sourcesTable);headerCell.textContent=WI.UIString("Filter:");this._sourcesFilterRow=row;this._sourcesFilterRow.hidden=true;this._sourcesFilterNumberElement=numberCell;this._sourcesFilterLabelElement=labelCell;let filterClearElement=numberCell.appendChild(document.createElement("span"));filterClearElement.className="filter-clear";filterClearElement.textContent=multiplicationSign;filterClearElement.addEventListener("click",(event)=>{this._resetSourcesFilters();this._layoutStatisticsAndSources();});} {let{row,headerCell,numberCell,labelCell}=this._createTableRow(this._sourcesTable);headerCell.textContent=WI.UIString("Timers:");this._timerInstallationsRow=row;this._timerInstallationsNumberElement=numberCell;this._timerInstallationsLabelElement=labelCell;} {let{row,headerCell,numberCell,labelCell}=this._createTableRow(this._sourcesTable);headerCell.textContent=WI.UIString("Event Handlers:");this._eventHandlersRow=row;this._eventHandlersNumberElement=numberCell;this._eventHandlersLabelElement=labelCell;} {let{row,headerCell,numberCell,labelCell}=this._createTableRow(this._sourcesTable);headerCell.textContent=WI.UIString("Observer Handlers:");this._observerHandlersRow=row;this._observerHandlersNumberElement=numberCell;this._observerHandlersLabelElement=labelCell;} this._clearSources();this.element.addEventListener("click",this._handleGraphClick.bind(this));this.element.addEventListener("mousemove",this._handleGraphMouseMove.bind(this));this._overlayMarker=new WI.TimelineMarker(-1,WI.TimelineMarker.Type.TimeStamp);this._timelineRuler.addMarker(this._overlayMarker);} layout() {if(this.layoutReason===WI.View.LayoutReason.Resize) return;if(this.layoutReason!==WI.CPUTimelineView.LayoutReason.Internal) this._sectionLimit=CPUTimelineView.defaultSectionLimit;this._timelineRuler.zeroTime=this.zeroTime;this._timelineRuler.startTime=this.startTime;this._timelineRuler.endTime=this.endTime;let secondsPerPixel=this._timelineRuler.secondsPerPixel;if(!secondsPerPixel) return;let graphStartTime=this.startTime;let graphEndTime=this.endTime;let visibleEndTime=Math.min(this.endTime,this.currentTime)||this.endTime;let visibleDuration=visibleEndTime-graphStartTime;let discontinuities=this._recording.discontinuitiesInTimeRange(graphStartTime,visibleEndTime);let originalDiscontinuities=discontinuities.slice();let visibleRecords=this.representedObject.recordsInTimeRange(graphStartTime,visibleEndTime,{includeRecordBeforeStart:!discontinuities.length||discontinuities[0].startTime>graphStartTime,includeRecordAfterEnd:true,});if(!visibleRecords.length||(visibleRecords.length===1&&visibleRecords[0].endTimeworkerMax) workerMax=workerData.max;} if(discontinuities.length) visibleEndTime=discontinuities[0].startTime;function bestThreadLayoutMax(value){if(value>100) return Math.ceil(value);return(Math.floor(value/25)+1)*25;} function removeGreaterThan(arr,max){return arr.filter((x)=>x<=max);} function markerValuesForMaxValue(max){if(max<1) return[0.5];if(max<7) return removeGreaterThan([1,3,5],max);if(max<12.5) return removeGreaterThan([5,10],max);if(max<20) return removeGreaterThan([5,10,15],max);if(max<30) return removeGreaterThan([10,20,30],max);if(max<50) return removeGreaterThan([15,30,45],max);if(max<100) return removeGreaterThan([25,50,75],max);if(max<200) return removeGreaterThan([50,100,150],max);if(max>=200){let hundreds=Math.floor(max/100);let even=(hundreds%2)===0;if(even){let top=hundreds*100;let bottom=top/2;return[bottom,top];} let top=hundreds*100;let bottom=100;let mid=(top+bottom)/2;return[bottom,mid,top];}} function layoutView(view,property,graphHeight,layoutMax,{dataPoints,min,max,average}){if(min===Infinity) min=0;if(max===-Infinity) max=0;if(layoutMax===-Infinity) layoutMax=0;let isAllThreadsGraph=property===null;let graphMax=layoutMax*1.05;function xScale(time){return(time-graphStartTime)/secondsPerPixel;} let size=new WI.Size(xScale(graphEndTime),graphHeight);function yScale(value){return size.height-((value/graphMax)*size.height);} view.updateChart(dataPoints,size,visibleEndTime,min,max,average,xScale,yScale,property);let markersElement=view.chart.element.querySelector(".markers");if(!markersElement){markersElement=view.chart.element.appendChild(document.createElement("div"));markersElement.className="markers";} markersElement.removeChildren();let markerValues;if(isAllThreadsGraph) markerValues=markerValuesForMaxValue(max);else{const minimumMarkerTextHeight=17;let percentPerPixel=1/(graphHeight/layoutMax);if(layoutMax<5){let minimumDisplayablePercentByTwo=Math.ceil((minimumMarkerTextHeight*percentPerPixel)/2)*2;markerValues=[Math.max(minimumDisplayablePercentByTwo,Math.floor(max))];}else{let minimumDisplayablePercentByFive=Math.ceil((minimumMarkerTextHeight*percentPerPixel)/5)*5;markerValues=[Math.max(minimumDisplayablePercentByFive,Math.floor(max))];}} for(let value of markerValues){let marginTop=yScale(value);let markerElement=markersElement.appendChild(document.createElement("div"));markerElement.style.marginTop=marginTop.toFixed(2)+"px";let labelElement=markerElement.appendChild(document.createElement("span"));labelElement.classList.add("label");const precision=0;labelElement.innerText=Number.percentageString(value/100,precision);}} this._layoutMax=max;this._threadLayoutMax=bestThreadLayoutMax(Math.max(mainThreadMax,webkitThreadMax,unknownThreadMax,workerMax));layoutView(this._cpuUsageView,null,CPUTimelineView.cpuUsageViewHeight,this._layoutMax,{dataPoints,min,max,average});if(this._threadsDetailsElement.open){layoutView(this._mainThreadUsageView,"mainThreadUsage",CPUTimelineView.threadCPUUsageViewHeight,this._threadLayoutMax,{dataPoints,min:mainThreadMin,max:mainThreadMax,average:mainThreadAverage});layoutView(this._webkitThreadUsageView,"webkitThreadUsage",CPUTimelineView.threadCPUUsageViewHeight,this._threadLayoutMax,{dataPoints,min:webkitThreadMin,max:webkitThreadMax,average:webkitThreadAverage});layoutView(this._unknownThreadUsageView,"unknownThreadUsage",CPUTimelineView.threadCPUUsageViewHeight,this._threadLayoutMax,{dataPoints,min:unknownThreadMin,max:unknownThreadMax,average:unknownThreadAverage});this._removeWorkerThreadViews();for(let[workerId,workerData]of workersDataMap){let worker=WI.targetManager.targetForIdentifier(workerId);let displayName=worker?worker.displayName:WI.UIString("Worker Thread");let workerView=new WI.CPUUsageView(displayName);workerView.element.classList.add("worker-thread");workerView.__workerId=workerId;this.addSubview(workerView);this._threadsDetailsElement.insertBefore(workerView.element,this._webkitThreadUsageView.element);this._workerViews.push(workerView);layoutView(workerView,"usage",CPUTimelineView.threadCPUUsageViewHeight,this._threadLayoutMax,{dataPoints:workerData.dataPoints,min:workerData.min,max:workerData.max,average:workerData.average});}} function xScaleIndicatorRange(sampleIndex){return(sampleIndex/1000)/secondsPerPixel;} let graphWidth=(graphEndTime-graphStartTime)/secondsPerPixel;let size=new WI.Size(graphWidth,CPUTimelineView.indicatorViewHeight);this._cpuUsageView.updateMainThreadIndicator(this._statisticsData.samples,size,visibleEndTime,xScaleIndicatorRange);this._layoutEnergyChart(average,visibleDuration);this._updateGraphOverlay();} _layoutBreakdownChart() {let{samples,samplesScript,samplesLayout,samplesPaint,samplesStyle,samplesIdle}=this._statisticsData;let nonIdleSamplesCount=samples.length-samplesIdle;if(!nonIdleSamplesCount){this._breakdownChart.clear();this._breakdownChart.needsLayout();this._clearBreakdownLegend();return;} let percentScript=samplesScript/nonIdleSamplesCount;let percentLayout=samplesLayout/nonIdleSamplesCount;let percentPaint=samplesPaint/nonIdleSamplesCount;let percentStyle=samplesStyle/nonIdleSamplesCount;this._breakdownLegendScriptElement.textContent=`${Number.percentageString(percentScript)} (${samplesScript})`;this._breakdownLegendLayoutElement.textContent=`${Number.percentageString(percentLayout)} (${samplesLayout})`;this._breakdownLegendPaintElement.textContent=`${Number.percentageString(percentPaint)} (${samplesPaint})`;this._breakdownLegendStyleElement.textContent=`${Number.percentageString(percentStyle)} (${samplesStyle})`;this._breakdownChart.values=[percentScript*100,percentLayout*100,percentPaint*100,percentStyle*100];this._breakdownChart.needsLayout();let centerElement=this._breakdownChart.centerElement;let samplesElement=centerElement.firstChild;if(!samplesElement){samplesElement=centerElement.appendChild(document.createElement("div"));samplesElement.classList.add("samples");samplesElement.title=WI.UIString("Time spent on the main thread");} let millisecondsStringNoDecimal=WI.UIString("%.0fms").format(nonIdleSamplesCount);samplesElement.textContent=millisecondsStringNoDecimal;} _layoutStatisticsAndSources() {this._layoutStatisticsSection();this._layoutSourcesSection();} _layoutStatisticsSection() {let statistics=this._statisticsData;this._clearStatistics();this._networkRequestsNumberElement.textContent=statistics.networkRequests;this._scriptEntriesNumberElement.textContent=statistics.scriptEntries;let createFilterElement=(type,name)=>{let span=document.createElement("span");span.className="filter";span.textContent=name;span.addEventListener("mouseup",(event)=>{if(span.classList.contains("active")) this._removeSourcesFilter(type,name);else this._addSourcesFilter(type,name);this._layoutStatisticsAndSources();});span.classList.toggle("active",this._sourcesFilter[type].has(name));return span;};let expandAllSections=()=>{this._sectionLimit=Infinity;this._layoutStatisticsAndSources();};function createEllipsisElement(){let span=document.createElement("span");span.className="show-more";span.role="button";span.textContent=ellipsis;span.addEventListener("click",(event)=>{expandAllSections();});return span;} function sortMapByEntryCount(map){let entries=Array.from(map);entries.sort((entryA,entryB)=>entryB[1]-entryA[1]);return new Map(entries);} if(statistics.timerTypes.size){let i=0;let sorted=sortMapByEntryCount(statistics.timerTypes);for(let[timerType,count]of sorted){let headerValue=i===0?WI.UIString("Timers:"):"";let timerTypeElement=createFilterElement("timer",timerType);this._insertTableRow(this._statisticsTable,this._statisticsRows,{headerValue,numberValue:count,labelValue:timerTypeElement});if(++i===this._sectionLimit&&sorted.size>this._sectionLimit){this._insertTableRow(this._statisticsTable,this._statisticsRows,{labelValue:createEllipsisElement()});break;}}} if(statistics.eventTypes.size){let i=0;let sorted=sortMapByEntryCount(statistics.eventTypes);for(let[eventType,count]of sorted){let headerValue=i===0?WI.UIString("Events:"):"";let eventTypeElement=createFilterElement("event",eventType);this._insertTableRow(this._statisticsTable,this._statisticsRows,{headerValue,numberValue:count,labelValue:eventTypeElement});if(++i===this._sectionLimit&&sorted.size>this._sectionLimit){this._insertTableRow(this._statisticsTable,this._statisticsRows,{labelValue:createEllipsisElement()});break;}}} if(statistics.observerTypes.size){let i=0;let sorted=sortMapByEntryCount(statistics.observerTypes);for(let[observerType,count]of sorted){let headerValue=i===0?WI.UIString("Observers:"):"";let observerTypeElement=createFilterElement("observer",observerType);this._insertTableRow(this._statisticsTable,this._statisticsRows,{headerValue,numberValue:count,labelValue:observerTypeElement});if(++i===this._sectionLimit&&sorted.size>this._sectionLimit){this._insertTableRow(this._statisticsTable,this._statisticsRows,{labelValue:createEllipsisElement()});break;}}}} _layoutSourcesSection() {let statistics=this._statisticsData;this._clearSources();const unknownLocationKey="unknown";function keyForSourceCodeLocation(sourceCodeLocation){if(!sourceCodeLocation) return unknownLocationKey;return sourceCodeLocation.sourceCode.url+":"+sourceCodeLocation.lineNumber+":"+sourceCodeLocation.columnNumber;} function labelForLocation(key,sourceCodeLocation,functionName){if(key===unknownLocationKey){let span=document.createElement("span");span.className="unknown";span.textContent=WI.UIString("Unknown Location");return span;} const options={nameStyle:WI.SourceCodeLocation.NameStyle.Short,columnStyle:WI.SourceCodeLocation.ColumnStyle.Shown,dontFloat:true,ignoreNetworkTab:true,ignoreSearchTab:true,};return WI.createSourceCodeLocationLink(sourceCodeLocation,options);} let timerFilters=this._sourcesFilter.timer;let eventFilters=this._sourcesFilter.event;let observerFilters=this._sourcesFilter.observer;let hasFilters=(timerFilters.size||eventFilters.size||observerFilters.size);let sectionLimit=this._sectionLimit;if(isFinite(sectionLimit)&&hasFilters) sectionLimit=CPUTimelineView.defaultSectionLimit*2;let expandAllSections=()=>{this._sectionLimit=Infinity;this._layoutStatisticsAndSources();};function createEllipsisElement(){let span=document.createElement("span");span.className="show-more";span.role="button";span.textContent=ellipsis;span.addEventListener("click",(event)=>{expandAllSections();});return span;} let timerMap=new Map;let eventHandlerMap=new Map;let observerCallbackMap=new Map;let seenTimers=new Set;if(!hasFilters||timerFilters.size){for(let record of statistics.timerInstallationRecords){if(timerFilters.size){if(record.eventType===WI.ScriptTimelineRecord.EventType.AnimationFrameRequested&&!timerFilters.has("requestAnimationFrame")) continue;if(record.eventType===WI.ScriptTimelineRecord.EventType.TimerInstalled&&!timerFilters.has("setTimeout")) continue;} let callFrame=record.initiatorCallFrame;let sourceCodeLocation=callFrame?callFrame.sourceCodeLocation:record.sourceCodeLocation;let functionName=callFrame?callFrame.functionName:"";let key=keyForSourceCodeLocation(sourceCodeLocation);let entry=timerMap.getOrInitialize(key,{sourceCodeLocation,functionName,count:0,repeating:false});if(record.details){let timerIdentifier=record.details.timerId;let repeatingEntry=statistics.repeatingTimers.get(timerIdentifier);let count=repeatingEntry?repeatingEntry.count:1;entry.count+=count;if(record.details.repeating) entry.repeating=true;seenTimers.add(timerIdentifier);}else entry.count+=1;} if(!hasFilters||timerFilters.has("setTimeout")){for(let[timerId,repeatingEntry]of statistics.repeatingTimers){if(seenTimers.has(timerId)) continue; let sourceCodeLocation=repeatingEntry.record.sourceCodeLocation;let key=keyForSourceCodeLocation(sourceCodeLocation);let entry=timerMap.getOrInitialize(key,{sourceCodeLocation,count:0,repeating:false});entry.count+=repeatingEntry.count;entry.repeating=true;}}} if(!hasFilters||eventFilters.size){for(let record of statistics.eventHandlerRecords){if(eventFilters.size&&!eventFilters.has(record.details)) continue;let sourceCodeLocation=record.sourceCodeLocation;let key=keyForSourceCodeLocation(sourceCodeLocation);let entry=eventHandlerMap.getOrInitialize(key,{sourceCodeLocation,count:0});entry.count+=1;}} if(!hasFilters||observerFilters.size){for(let record of statistics.observerCallbackRecords){if(observerFilters.size&&!observerFilters.has(record.details)) continue;let sourceCodeLocation=record.sourceCodeLocation;let key=keyForSourceCodeLocation(record.sourceCodeLocation);let entry=observerCallbackMap.getOrInitialize(key,{sourceCodeLocation,count:0});entry.count+=1;}} const headerValue="";function sortMapByEntryCountProperty(map){let entries=Array.from(map);entries.sort((entryA,entryB)=>entryB[1].count-entryA[1].count);return new Map(entries);} if(timerMap.size){let i=0;let sorted=sortMapByEntryCountProperty(timerMap);for(let[key,entry]of sorted){let numberValue=entry.repeating?WI.UIString("~%s","Approximate Number","Approximate count of events").format(entry.count):entry.count;let sourceCodeLocation=entry.callFrame?entry.callFrame.sourceCodeLocation:entry.sourceCodeLocation;let labelValue=labelForLocation(key,sourceCodeLocation);let followingRow=this._eventHandlersRow;let row;if(i===0){row=this._timerInstallationsRow;this._timerInstallationsNumberElement.textContent=numberValue;this._timerInstallationsLabelElement.append(labelValue);}else row=this._insertTableRow(this._sourcesTable,this._sourcesRows,{headerValue,numberValue,labelValue,followingRow});if(entry.functionName) row.querySelector(".label").append(` ${enDash} ${entry.functionName}`);if(++i===sectionLimit&&sorted.size>sectionLimit){this._insertTableRow(this._sourcesTable,this._sourcesRows,{labelValue:createEllipsisElement(),followingRow});break;}}} if(eventHandlerMap.size){let i=0;let sorted=sortMapByEntryCountProperty(eventHandlerMap);for(let[key,entry]of sorted){let numberValue=entry.count;let labelValue=labelForLocation(key,entry.sourceCodeLocation);let followingRow=this._observerHandlersRow;if(i===0){this._eventHandlersNumberElement.textContent=numberValue;this._eventHandlersLabelElement.append(labelValue);}else this._insertTableRow(this._sourcesTable,this._sourcesRows,{headerValue,numberValue,labelValue,followingRow});if(++i===sectionLimit&&sorted.size>sectionLimit){this._insertTableRow(this._sourcesTable,this._sourcesRows,{labelValue:createEllipsisElement(),followingRow});break;}}} if(observerCallbackMap.size){let i=0;let sorted=sortMapByEntryCountProperty(observerCallbackMap);for(let[key,entry]of sorted){let numberValue=entry.count;let labelValue=labelForLocation(key,entry.sourceCodeLocation);if(i===0){this._observerHandlersNumberElement.textContent=numberValue;this._observerHandlersLabelElement.append(labelValue);}else this._insertTableRow(this._sourcesTable,this._sourcesRows,{headerValue,numberValue,labelValue});if(++i===sectionLimit&&sorted.size>sectionLimit){this._insertTableRow(this._sourcesTable,this._sourcesRows,{labelValue:createEllipsisElement()});break;}}}} _layoutEnergyChart(average,visibleDuration) {function mapWithBias(value,rangeLow,rangeHigh,outputRangeLow,outputRangeHigh,bias){let percentInRange=(value-rangeLow)/(rangeHigh-rangeLow);let skewedPercent=Math.pow(percentInRange,bias);let valueInOutputRange=(skewedPercent*(outputRangeHigh-outputRangeLow))+outputRangeLow;return valueInOutputRange;} this._clearEnergyImpactText();if(average<=CPUTimelineView.lowEnergyThreshold){this._energyImpactLabelElement.textContent=WI.UIString("Low","Low @ Timeline Energy Impact","Energy Impact: Low");this._energyImpactLabelElement.classList.add("low");this._energyChart.value=mapWithBias(average,0,CPUTimelineView.lowEnergyThreshold,0,CPUTimelineView.lowEnergyGraphBoundary,0.85);}else if(average<=CPUTimelineView.mediumEnergyThreshold){this._energyImpactLabelElement.textContent=WI.UIString("Medium","Medium @ Timeline Energy Impact","Energy Impact: Medium") this._energyImpactLabelElement.classList.add("medium");this._energyChart.value=mapWithBias(average,CPUTimelineView.lowEnergyThreshold,CPUTimelineView.mediumEnergyThreshold,CPUTimelineView.lowEnergyGraphBoundary,CPUTimelineView.mediumEnergyGraphBoundary,0.6);}else if(average{switch(record.eventType){case WI.ScriptTimelineRecord.EventType.ScriptEvaluated:case WI.ScriptTimelineRecord.EventType.APIScriptEvaluated:scriptEntries++;return true;case WI.ScriptTimelineRecord.EventType.ObserverCallback:incrementTypeCount(observerTypes,record.details);observerCallbackRecords.push(record);scriptEntries++;return true;case WI.ScriptTimelineRecord.EventType.EventDispatched:incrementTypeCount(eventTypes,record.details);eventHandlerRecords.push(record);scriptEntries++;return true;case WI.ScriptTimelineRecord.EventType.MicrotaskDispatched: return true;case WI.ScriptTimelineRecord.EventType.TimerFired:incrementTypeCount(timerTypes,"setTimeout");if(possibleRepeatingTimers.has(record.details)){let entry=repeatingTimers.get(record.details);if(entry) entry.count+=1;else repeatingTimers.set(record.details,{record,count:1});}else possibleRepeatingTimers.add(record.details);scriptEntries++;return true;case WI.ScriptTimelineRecord.EventType.AnimationFrameFired:incrementTypeCount(timerTypes,"requestAnimationFrame");scriptEntries++;return true;case WI.ScriptTimelineRecord.EventType.AnimationFrameRequested:case WI.ScriptTimelineRecord.EventType.TimerInstalled:timerInstallationRecords.push(record);return false;case WI.ScriptTimelineRecord.EventType.AnimationFrameCanceled:case WI.ScriptTimelineRecord.EventType.TimerRemoved:case WI.ScriptTimelineRecord.EventType.ProbeSampleRecorded:case WI.ScriptTimelineRecord.EventType.ConsoleProfileRecorded:case WI.ScriptTimelineRecord.EventType.GarbageCollected:return false;default:console.error("Unhandled ScriptTimelineRecord.EventType",record.eventType);return false;}});let layoutTimeline=this._recording.timelineForRecordType(WI.TimelineRecord.Type.Layout);let layoutRecords=layoutTimeline?layoutTimeline.recordsInTimeRange(startTime,endTime,{includeRecordBeforeStart:true}):[];layoutRecords=layoutRecords.filter((record)=>{switch(record.eventType){case WI.LayoutTimelineRecord.EventType.RecalculateStyles:case WI.LayoutTimelineRecord.EventType.ForcedLayout:case WI.LayoutTimelineRecord.EventType.Layout:case WI.LayoutTimelineRecord.EventType.Paint:case WI.LayoutTimelineRecord.EventType.Composite:return true;case WI.LayoutTimelineRecord.EventType.InvalidateStyles:case WI.LayoutTimelineRecord.EventType.InvalidateLayout:return false;default:console.error("Unhandled LayoutTimelineRecord.EventType",record.eventType);return false;}});let networkTimeline=this._recording.timelineForRecordType(WI.TimelineRecord.Type.Network);let networkRecords=networkTimeline?networkTimeline.recordsInTimeRange(startTime,endTime):[];let networkRequests=networkRecords.length;let millisecondStartTime=Math.round(startTime*1000);let millisecondEndTime=Math.round(endTime*1000);let millisecondDuration=millisecondEndTime-millisecondStartTime;let samples=new Array(millisecondDuration);function markRecordEntries(records,callback){for(let record of records){let recordStart=Math.round(record.startTime*1000);let recordEnd=Math.round(record.endTime*1000);if(recordStart>millisecondEndTime) continue;if(recordEnd{return CPUTimelineView.SampleType.JavaScript;});markRecordEntries(layoutRecords,(record)=>{switch(record.eventType){case WI.LayoutTimelineRecord.EventType.RecalculateStyles:return CPUTimelineView.SampleType.Style;case WI.LayoutTimelineRecord.EventType.ForcedLayout:case WI.LayoutTimelineRecord.EventType.Layout:return CPUTimelineView.SampleType.Layout;case WI.LayoutTimelineRecord.EventType.Paint:case WI.LayoutTimelineRecord.EventType.Composite:return CPUTimelineView.SampleType.Paint;}});let samplesIdle=0;let samplesScript=0;let samplesLayout=0;let samplesPaint=0;let samplesStyle=0;for(let i=0;i{let span=document.createElement("span");span.className="filter active";span.textContent=name;span.addEventListener("mouseup",(event)=>{this._removeSourcesFilter(type,name);this._layoutStatisticsAndSources();});return span;};this._sourcesFilterRow.hidden=false;this._sourcesFilterLabelElement.removeChildren();for(let name of timerFilters) this._sourcesFilterLabelElement.appendChild(createActiveFilterElement("timer",name));for(let name of eventFilters) this._sourcesFilterLabelElement.appendChild(createActiveFilterElement("event",name));for(let name of observerFilters) this._sourcesFilterLabelElement.appendChild(createActiveFilterElement("observer",name));this._timerInstallationsRow.hidden=!timerFilters.size;this._eventHandlersRow.hidden=!eventFilters.size;this._observerHandlersRow.hidden=!observerFilters.size;} _createTableRow(table) {let row=table.appendChild(document.createElement("tr"));let headerCell=row.appendChild(document.createElement("th"));let numberCell=row.appendChild(document.createElement("td"));numberCell.className="number";let labelCell=row.appendChild(document.createElement("td"));labelCell.className="label";return{row,headerCell,numberCell,labelCell};} _insertTableRow(table,rowList,{headerValue,numberValue,labelValue,followingRow}) {let{row,headerCell,numberCell,labelCell}=this._createTableRow(table);rowList.push(row);if(followingRow) table.insertBefore(row,followingRow);if(headerValue) headerCell.textContent=headerValue;if(numberValue) numberCell.textContent=numberValue;if(labelValue) labelCell.append(labelValue);return row;} _clearStatistics() {this._networkRequestsNumberElement.textContent=emDash;this._scriptEntriesNumberElement.textContent=emDash;for(let row of this._statisticsRows) row.remove();this._statisticsRows=[];} _clearSources() {this._timerInstallationsNumberElement.textContent=emDash;this._timerInstallationsLabelElement.textContent="";this._eventHandlersNumberElement.textContent=emDash;this._eventHandlersLabelElement.textContent="";this._observerHandlersNumberElement.textContent=emDash;this._observerHandlersLabelElement.textContent="";for(let row of this._sourcesRows) row.remove();this._sourcesRows=[];} _clearEnergyImpactText() {this._energyImpactLabelElement.classList.remove("low","medium","high");this._energyImpactLabelElement.textContent=emDash;this._energyImpactNumberElement.textContent="";this._energyImpactDurationElement.textContent="";} _clearBreakdownLegend() {this._breakdownLegendScriptElement.textContent=emDash;this._breakdownLegendLayoutElement.textContent=emDash;this._breakdownLegendPaintElement.textContent=emDash;this._breakdownLegendStyleElement.textContent=emDash;this._breakdownChart.centerElement.removeChildren();} _cpuTimelineRecordAdded(event) {let cpuTimelineRecord=event.data.record;if(cpuTimelineRecord.startTime>=this.startTime&&cpuTimelineRecord.endTime<=this.endTime) this.needsLayout();} _graphPositionForMouseEvent(event) {let chartElement=event.target.closest(".area-chart, .stacked-area-chart, .range-chart");if(!chartElement) return NaN;let rect=chartElement.getBoundingClientRect();let position=event.pageX-rect.left;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL) return rect.width-position;return position;} _handleIndicatorClick(event) {let clickPosition=this._graphPositionForMouseEvent(event);if(isNaN(clickPosition)) return;let secondsPerPixel=this._timelineRuler.secondsPerPixel;let graphClickTime=clickPosition*secondsPerPixel;let graphStartTime=this.startTime;let clickStartTime=graphStartTime+graphClickTime;let clickEndTime=clickStartTime+secondsPerPixel;if(event.target.localName==="rect"){if(this._attemptSelectIndicatatorTimelineRecord(clickStartTime,clickEndTime)) return;} for(let i=1,delta=0;i<=4;++i){delta+=secondsPerPixel;if(this._attemptSelectIndicatatorTimelineRecord(clickStartTime-delta,clickStartTime)) return;if(this._attemptSelectIndicatatorTimelineRecord(clickEndTime,clickEndTime+delta)) return;}} _attemptSelectIndicatatorTimelineRecord(startTime,endTime) {let layoutTimeline=this._recording.timelineForRecordType(WI.TimelineRecord.Type.Layout);let layoutRecords=layoutTimeline?layoutTimeline.recordsInTimeRange(startTime,endTime,{includeRecordBeforeStart:true}):[];layoutRecords=layoutRecords.filter((record)=>{switch(record.eventType){case WI.LayoutTimelineRecord.EventType.RecalculateStyles:case WI.LayoutTimelineRecord.EventType.ForcedLayout:case WI.LayoutTimelineRecord.EventType.Layout:case WI.LayoutTimelineRecord.EventType.Paint:case WI.LayoutTimelineRecord.EventType.Composite:return true;case WI.LayoutTimelineRecord.EventType.InvalidateStyles:case WI.LayoutTimelineRecord.EventType.InvalidateLayout:return false;default:console.error("Unhandled LayoutTimelineRecord.EventType",record.eventType);return false;}});if(layoutRecords.length){this._selectTimelineRecord(layoutRecords[0]);return true;} let scriptTimeline=this._recording.timelineForRecordType(WI.TimelineRecord.Type.Script);let scriptRecords=scriptTimeline?scriptTimeline.recordsInTimeRange(startTime,endTime,{includeRecordBeforeStart:true}):[];scriptRecords=scriptRecords.filter((record)=>{switch(record.eventType){case WI.ScriptTimelineRecord.EventType.ScriptEvaluated:case WI.ScriptTimelineRecord.EventType.APIScriptEvaluated:case WI.ScriptTimelineRecord.EventType.ObserverCallback:case WI.ScriptTimelineRecord.EventType.EventDispatched:case WI.ScriptTimelineRecord.EventType.MicrotaskDispatched:case WI.ScriptTimelineRecord.EventType.TimerFired:case WI.ScriptTimelineRecord.EventType.AnimationFrameFired:return true;case WI.ScriptTimelineRecord.EventType.AnimationFrameRequested:case WI.ScriptTimelineRecord.EventType.AnimationFrameCanceled:case WI.ScriptTimelineRecord.EventType.TimerInstalled:case WI.ScriptTimelineRecord.EventType.TimerRemoved:case WI.ScriptTimelineRecord.EventType.ProbeSampleRecorded:case WI.ScriptTimelineRecord.EventType.ConsoleProfileRecorded:case WI.ScriptTimelineRecord.EventType.GarbageCollected:return false;default:console.error("Unhandled ScriptTimelineRecord.EventType",record.eventType);return false;}});if(scriptRecords.length){this._selectTimelineRecord(scriptRecords[0]);return true;} return false;} _selectTimelineRecord(record) {this.dispatchEventToListeners(WI.TimelineView.Event.RecordWasSelected,{record});} _handleGraphClick(event) {let mousePosition=this._graphPositionForMouseEvent(event);if(isNaN(mousePosition)) return;this._stickingOverlay=!this._stickingOverlay;if(!this._stickingOverlay) this._handleGraphMouseMove(event);} _handleGraphMouseMove(event) {let mousePosition=this._graphPositionForMouseEvent(event);if(isNaN(mousePosition)){this._hideGraphOverlay();this.dispatchEventToListeners(WI.TimelineView.Event.ScannerHide);return;} let secondsPerPixel=this._timelineRuler.secondsPerPixel;let time=this.startTime+(mousePosition*secondsPerPixel);if(!this._stickingOverlay) this._showGraphOverlayNearTo(time);this.dispatchEventToListeners(WI.TimelineView.Event.ScannerShow,{time});} _showGraphOverlayNearTo(time) {let nearestRecord=null;let nearestDistance=Infinity;for(let record of this._visibleRecordsInLayout){let distance=Math.abs(time-record.timestamp);if(distancex.__workerId===targetId);if(workerView){workerView.updateLegend(usage);addOverlayPoint(workerView,CPUTimelineView.threadCPUUsageViewHeight,this._threadLayoutMax,usage);}}}}} _clearOverlayMarkers() {function clearGraphOverlayElement(view){view.clearLegend();view.chart.clearPointMarkers();view.chart.needsLayout();} clearGraphOverlayElement(this._cpuUsageView);clearGraphOverlayElement(this._mainThreadUsageView);clearGraphOverlayElement(this._webkitThreadUsageView);clearGraphOverlayElement(this._unknownThreadUsageView);for(let workerView of this._workerViews) clearGraphOverlayElement(workerView);} _hideGraphOverlay() {if(this._stickingOverlay) return;this._overlayRecord=null;this._overlayTime=NaN;this._overlayMarker.time=-1;this._clearOverlayMarkers();}};WI.CPUTimelineView.LayoutReason={Internal:Symbol("cpu-timeline-view-internal-layout"),};WI.CPUTimelineView.SampleType={JavaScript:"sample-type-javascript",Layout:"sample-type-layout",Paint:"sample-type-paint",Style:"sample-type-style",};WI.CPUTimelineView.ReferencePage=WI.ReferencePage.TimelinesTab.CPUTimeline;WI.CPUUsageCombinedView=class CPUUsageCombinedView extends WI.View {constructor(displayName) {super();this.element.classList.add("cpu-usage-combined-view");this._detailsElement=this.element.appendChild(document.createElement("div"));this._detailsElement.classList.add("details");let detailsNameElement=this._detailsElement.appendChild(document.createElement("span"));detailsNameElement.classList.add("name");detailsNameElement.textContent=displayName;this._detailsElement.appendChild(document.createElement("br"));this._detailsAverageElement=this._detailsElement.appendChild(document.createElement("span"));this._detailsElement.appendChild(document.createElement("br"));this._detailsMaxElement=this._detailsElement.appendChild(document.createElement("span"));this._detailsElement.appendChild(document.createElement("br"));this._detailsElement.appendChild(document.createElement("br"));this._updateDetails(NaN,NaN);this._graphElement=this.element.appendChild(document.createElement("div"));this._graphElement.classList.add("graph");this._chart=new WI.StackedAreaChart;this._chart.initializeSections(["main-thread-usage","worker-thread-usage","total-usage"]);this.addSubview(this._chart);this._graphElement.appendChild(this._chart.element);this._rangeChart=new WI.RangeChart;this.addSubview(this._rangeChart);this._graphElement.appendChild(this._rangeChart.element);function appendLegendRow(legendElement,className){let rowElement=legendElement.appendChild(document.createElement("div"));rowElement.classList.add("row");let swatchElement=rowElement.appendChild(document.createElement("div"));swatchElement.classList.add("swatch",className);let labelElement=rowElement.appendChild(document.createElement("div"));labelElement.classList.add("label");return labelElement;} this._legendElement=this._detailsElement.appendChild(document.createElement("div"));this._legendElement.classList.add("legend-container");this._legendMainThreadElement=appendLegendRow(this._legendElement,"main-thread");this._legendWorkerThreadsElement=appendLegendRow(this._legendElement,"worker-threads");this._legendOtherThreadsElement=appendLegendRow(this._legendElement,"other-threads");this._legendTotalThreadsElement=appendLegendRow(this._legendElement,"total");this.clearLegend();} get graphElement(){return this._graphElement;} get chart(){return this._chart;} get rangeChart(){return this._rangeChart;} clear() {this._cachedAverageSize=undefined;this._cachedMaxSize=undefined;this._updateDetails(NaN,NaN);this.clearLegend();this._chart.clear();this._chart.needsLayout();this._rangeChart.clear();this._rangeChart.needsLayout();} updateChart(dataPoints,size,visibleEndTime,min,max,average,xScale,yScale) {this._updateDetails(max,average);this._chart.clearPoints();this._chart.size=size;this._chart.needsLayout();if(!dataPoints.length) return;if(!max) return;let firstX=0;let firstY1=yScale(dataPoints[0].mainThreadUsage);let firstY2=yScale(dataPoints[0].mainThreadUsage+dataPoints[0].workerThreadUsage);let firstY3=yScale(dataPoints[0].usage);this._chart.addPointSet(firstX,[firstY1,firstY2,firstY3]);for(let dataPoint of dataPoints){let x=xScale(dataPoint.time);let y1=yScale(dataPoint.mainThreadUsage);let y2=yScale(dataPoint.mainThreadUsage+dataPoint.workerThreadUsage);let y3=yScale(dataPoint.usage);this._chart.addPointSet(x,[y1,y2,y3]);} let lastDataPoint=dataPoints.lastValue;let lastX=Math.floor(xScale(visibleEndTime));let lastY1=yScale(lastDataPoint.mainThreadUsage);let lastY2=yScale(lastDataPoint.mainThreadUsage+lastDataPoint.workerThreadUsage);let lastY3=yScale(lastDataPoint.usage);this._chart.addPointSet(lastX,[lastY1,lastY2,lastY3]);} updateMainThreadIndicator(samples,size,visibleEndTime,xScale) {this._rangeChart.clear();this._rangeChart.size=size;this._rangeChart.needsLayout();if(!samples.length) return;let ranges=[];let currentRange=null;let currentSampleType=undefined;for(let i=0;i=20) detailsNameElement.title=displayName;this._detailsElement.appendChild(document.createElement("br"));} this._detailsAverageElement=this._detailsElement.appendChild(document.createElement("span"));this._detailsElement.appendChild(document.createElement("br"));this._detailsUsageElement=this._detailsElement.appendChild(document.createElement("span"));this.clearLegend();this._updateDetails(NaN);this._graphElement=this.element.appendChild(document.createElement("div"));this._graphElement.classList.add("graph");this._chart=new WI.AreaChart;this.addSubview(this._chart);this._graphElement.appendChild(this._chart.element);} get graphElement(){return this._graphElement;} get chart(){return this._chart;} clear() {this._cachedAverageSize=undefined;this._updateDetails(NaN);this.clearLegend();this._chart.clear();this._chart.needsLayout();} updateChart(dataPoints,size,visibleEndTime,min,max,average,xScale,yScale,property) {this._updateDetails(average);this._chart.clearPoints();this._chart.size=size;this._chart.needsLayout();if(!dataPoints.length) return;if(!max) return;let firstX=0;let firstY=yScale(dataPoints[0][property]);this._chart.addPoint(firstX,firstY);for(let dataPoint of dataPoints){let x=xScale(dataPoint.time);let y=yScale(dataPoint[property]);this._chart.addPoint(x,y);} let lastDataPoint=dataPoints.lastValue;let lastX=Math.floor(xScale(visibleEndTime));let lastY=yScale(lastDataPoint[property]);this._chart.addPoint(lastX,lastY);} clearLegend() {this._detailsUsageElement.hidden=true;this._detailsUsageElement.textContent=emDash;} updateLegend(value) {let usage=Number.isFinite(value)?Number.percentageString(value/100):emDash;this._detailsUsageElement.hidden=false;this._detailsUsageElement.textContent=WI.UIString("Usage: %s").format(usage);} _updateDetails(averageSize) {if(this._cachedAverageSize===averageSize) return;this._cachedAverageSize=averageSize;this._detailsAverageElement.hidden=!Number.isFinite(averageSize);this._detailsAverageElement.textContent=WI.UIString("Average: %s").format(Number.isFinite(averageSize)?Number.percentageString(averageSize/100):emDash);}};WI.CSSStyleSheetTreeElement=class CSSStyleSheetTreeElement extends WI.SourceCodeTreeElement {constructor(styleSheet) {const title=null;const subtitle=null;super(styleSheet,["style-sheet","style-sheet-icon"],title,subtitle);this.mainTitle=styleSheet.displayName;if(styleSheet.url){if(styleSheet.urlComponents.scheme==="web-inspector") this.tooltip=this.mainTitle;else{let host=WI.displayNameForHost(styleSheet.urlComponents.host);this.subtitle=this.mainTitle!==host?host:null;this.tooltip=styleSheet.url;}}}};WI.CallFrameTreeElement=class CallFrameTreeElement extends WI.GeneralTreeElement {constructor(callFrame,{isAsyncBoundaryCallFrame,isTruncatedBoundaryCallFrame}={}) {let className=WI.CallFrameView.iconClassNameForCallFrame(callFrame);let title=callFrame.displayName;const subtitle=null;super(["call-frame",className],title,subtitle,callFrame);this._callFrame=callFrame;this._isActiveCallFrame=false;this._isAsyncBoundaryCallFrame=isAsyncBoundaryCallFrame||false;if(this._isAsyncBoundaryCallFrame){this.addClassName("async-boundary");this.selectable=false;} this._isTruncatedBoundaryCallFrame=!!isTruncatedBoundaryCallFrame;if(this._isTruncatedBoundaryCallFrame){this.addClassName("truncated-boundary");this.selectable=false;} if(this._callFrame.nativeCode||!this._callFrame.sourceCodeLocation){this.subtitle="";this.selectable=false;return;} let displayScriptURL=this._callFrame.sourceCodeLocation.displaySourceCode.url;if(displayScriptURL){this.subtitle=document.createElement("span");this._callFrame.sourceCodeLocation.populateLiveDisplayLocationString(this.subtitle,"textContent");this.tooltipHandledSeparately=true;} if(this._callFrame.blackboxed){this.addClassName("blackboxed");this.tooltipHandledSeparately=true;}} get callFrame(){return this._callFrame;} get isAsyncBoundaryCallFrame(){return this._isAsyncBoundaryCallFrame;} get isActiveCallFrame() {return this._isActiveCallFrame;} set isActiveCallFrame(x) {if(this._isActiveCallFrame===x) return;this._isActiveCallFrame=x;this._updateStatus();} onattach() {super.onattach();if(this.tooltipHandledSeparately){let tailCallSuffix="";if(this._callFrame.isTailDeleted) tailCallSuffix=" "+WI.UIString("(Tail Call)");let tooltipPrefix=this.mainTitle+tailCallSuffix+"\n";let tooltipSuffix="";if(this._callFrame.blackboxed) tooltipSuffix+="\n\n"+WI.UIString("Script ignored due to blackbox");this._callFrame.sourceCodeLocation.populateLiveDisplayLocationTooltip(this.element,tooltipPrefix,tooltipSuffix);} this._updateStatus();} populateContextMenu(contextMenu,event) {if(this._callFrame.sourceCodeLocation) WI.appendContextMenuItemsForSourceCode(contextMenu,this._callFrame.sourceCodeLocation);super.populateContextMenu(contextMenu,event);} _updateStatus() {if(!this.element) return;if(!this._isActiveCallFrame){this.status=null;return;} if(!this._statusImageElement) this._statusImageElement=WI.ImageUtilities.useSVGSymbol("Images/ActiveCallFrame.svg","status-image");this.status=this._statusImageElement;}};WI.CallFrameView=class CallFrameView extends WI.Object {constructor(callFrame,{showFunctionName,indicateIfBlackboxed,isAsyncBoundaryCallFrame,isTruncatedBoundaryCallFrame}={}) {var callFrameElement=document.createElement("div");callFrameElement.classList.add("call-frame",WI.CallFrameView.iconClassNameForCallFrame(callFrame));if(isAsyncBoundaryCallFrame) callFrameElement.classList.add("async-boundary");if(isTruncatedBoundaryCallFrame) callFrameElement.classList.add("truncated-boundary");var subtitleElement=document.createElement("span");subtitleElement.classList.add("subtitle");var sourceCodeLocation=callFrame.sourceCodeLocation;if(sourceCodeLocation){if(indicateIfBlackboxed) callFrameElement.classList.toggle("blackboxed",callFrame.blackboxed);WI.linkifyElement(callFrameElement,sourceCodeLocation,{ignoreNetworkTab:true,ignoreSearchTab:true,});var linkElement=document.createElement("a");linkElement.classList.add("source-link");linkElement.href=sourceCodeLocation.sourceCode.url;if(showFunctionName){var separatorElement=document.createElement("span");separatorElement.classList.add("separator");separatorElement.textContent=` ${emDash} `;subtitleElement.append(separatorElement);} subtitleElement.append(linkElement);sourceCodeLocation.populateLiveDisplayLocationTooltip(linkElement);sourceCodeLocation.populateLiveDisplayLocationString(linkElement,"textContent");} var titleElement=document.createElement("span");titleElement.classList.add("title");if(showFunctionName){var imgElement=document.createElement("img");imgElement.classList.add("icon");titleElement.append(imgElement,callFrame.displayName);} callFrameElement.append(titleElement,subtitleElement);return callFrameElement;} static iconClassNameForCallFrame(callFrame) {if(callFrame.isTailDeleted) return WI.CallFrameView.TailDeletedIcon;if(callFrame.programCode) return WI.CallFrameView.ProgramIconStyleClassName; if(callFrame.functionName&&callFrame.functionName.startsWith("on")&&callFrame.functionName.length>=5) return WI.CallFrameView.EventListenerIconStyleClassName;if(callFrame.nativeCode) return WI.CallFrameView.NativeIconStyleClassName;return WI.CallFrameView.FunctionIconStyleClassName;}};WI.CallFrameView.ProgramIconStyleClassName="program-icon";WI.CallFrameView.FunctionIconStyleClassName="function-icon";WI.CallFrameView.EventListenerIconStyleClassName="event-listener-icon";WI.CallFrameView.NativeIconStyleClassName="native-icon";WI.CallFrameView.TailDeletedIcon="tail-deleted";WI.CanvasContentView=class CanvasContentView extends WI.ContentView {constructor(representedObject) {super(representedObject);this.element.classList.add("canvas");this._progressView=null;this._previewContainerElement=null;this._previewImageElement=null;this._errorElement=null;this._memoryCostElement=null;this._pendingContent=null;this._pixelSizeElement=null;this._canvasNode=null;this._refreshButtonNavigationItem=new WI.ButtonNavigationItem("refresh",WI.UIString("Refresh"),"Images/ReloadFull.svg",13,13);this._refreshButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._refreshButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this.handleRefreshButtonClicked,this);this._showGridButtonNavigationItem=new WI.ActivateButtonNavigationItem("show-grid",WI.repeatedUIString.showTransparencyGridTooltip(),WI.UIString("Hide transparency grid"),"Images/NavigationItemCheckers.svg",13,13);this._showGridButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._showGridButtonClicked,this);this._showGridButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._showGridButtonNavigationItem.activated=!!WI.settings.showImageGrid.value;} get navigationItems() {return[this._refreshButtonNavigationItem,this._showGridButtonNavigationItem];} refreshPreview() {this._pendingContent=null;this.representedObject.requestContent().then((content)=>{this._pendingContent=content;if(!this._pendingContent){this._showError();return;} this.needsLayout();});} handleRefreshButtonClicked() {this.refreshPreview();} initialLayout() {super.initialLayout();let isCard=!this._refreshButtonNavigationItem.parentNavigationBar;if(isCard){let header=this.element.appendChild(document.createElement("header"));header.addEventListener("click",(event)=>{event.stopPropagation();});let titles=header.appendChild(document.createElement("div"));titles.className="titles";let title=titles.appendChild(document.createElement("span"));title.className="title";title.textContent=this.representedObject.displayName;let subtitle=titles.appendChild(document.createElement("span"));subtitle.className="subtitle";subtitle.textContent=WI.Canvas.displayNameForContextType(this.representedObject.contextType);if(this.representedObject.contextAttributes.colorSpace){let subtitle=titles.appendChild(document.createElement("span"));subtitle.className="color-space";subtitle.textContent="("+WI.Canvas.displayNameForColorSpace(this.representedObject.contextAttributes.colorSpace)+")";} let navigationBar=new WI.NavigationBar;if(this.representedObject.supportsRecording){const toolTip=WI.UIString("Start recording canvas actions.\nShift-click to record a single frame.");const altToolTip=WI.UIString("Stop recording canvas actions");this._recordButtonNavigationItem=new WI.ToggleButtonNavigationItem("record-start-stop",toolTip,altToolTip,"Images/Record.svg","Images/Stop.svg",13,13);this._recordButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._recordButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._toggleRecording,this);navigationBar.addNavigationItem(this._recordButtonNavigationItem);} let canvasElementButtonNavigationItem=new WI.ButtonNavigationItem("canvas-element",WI.UIString("Canvas Element"),"Images/Markup.svg",16,16);canvasElementButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;WI.addMouseDownContextMenuHandlers(canvasElementButtonNavigationItem.element,this._populateCanvasElementButtonContextMenu.bind(this));navigationBar.addNavigationItem(canvasElementButtonNavigationItem);navigationBar.addNavigationItem(this._refreshButtonNavigationItem);header.append(navigationBar.element);} this._previewContainerElement=this.element.appendChild(document.createElement("div"));this._previewContainerElement.className="preview";if(isCard){let footer=this.element.appendChild(document.createElement("footer"));footer.addEventListener("click",(event)=>{event.stopPropagation();});this._viewRelatedItemsContainer=footer.appendChild(document.createElement("div"));this._viewRelatedItemsContainer.classList.add("view-related-items");this._viewShaderButton=document.createElement("img");this._viewShaderButton.classList.add("view-shader");this._viewShaderButton.title=WI.UIString("View Shader");WI.addMouseDownContextMenuHandlers(this._viewShaderButton,this._populateViewShaderButtonContextMenu.bind(this));this._viewRecordingButton=document.createElement("img");this._viewRecordingButton.classList.add("view-recording");this._viewRecordingButton.title=WI.UIString("View Recording");WI.addMouseDownContextMenuHandlers(this._viewRecordingButton,this._populateViewRecordingButtonContextMenu.bind(this));this._updateViewRelatedItems();let flexibleSpaceElement=footer.appendChild(document.createElement("div"));flexibleSpaceElement.className="flexible-space";let metrics=footer.appendChild(document.createElement("div"));this._pixelSizeElement=metrics.appendChild(document.createElement("span"));this._pixelSizeElement.className="pixel-size";this._memoryCostElement=metrics.appendChild(document.createElement("span"));this._memoryCostElement.className="memory-cost";} if(this._errorElement) this._showError();if(isCard) this._updateSize();} layout() {super.layout();if(this._pendingContent){if(this._errorElement){this._errorElement.remove();this._errorElement=null;} if(!this._previewImageElement){this._previewImageElement=document.createElement("img");this._previewImageElement.addEventListener("error",this._showError.bind(this));} this._previewImageElement.src=this._pendingContent;this._pendingContent=null;if(!this._previewImageElement.parentNode) this._previewContainerElement.appendChild(this._previewImageElement);} this._updateRecordNavigationItem();this._updateProgressView();this._updateViewRelatedItems();this._updateMemoryCost();this._updateImageGrid();} attached() {super.attached();this.representedObject.addEventListener(WI.Canvas.Event.SizeChanged,this._updateSize,this);this.representedObject.addEventListener(WI.Canvas.Event.MemoryChanged,this._updateMemoryCost,this);this.representedObject.addEventListener(WI.Canvas.Event.RecordingStarted,this.needsLayout,this);this.representedObject.addEventListener(WI.Canvas.Event.RecordingProgress,this.needsLayout,this);this.representedObject.addEventListener(WI.Canvas.Event.RecordingStopped,this.needsLayout,this);this.representedObject.shaderProgramCollection.addEventListener(WI.Collection.Event.ItemAdded,this.needsLayout,this);this.representedObject.shaderProgramCollection.addEventListener(WI.Collection.Event.ItemRemoved,this.needsLayout,this);this.representedObject.requestNode().then((node)=>{if(!node) return;if(this._canvasNode===node) return;this._canvasNode=node;});WI.settings.showImageGrid.addEventListener(WI.Setting.Event.Changed,this._updateImageGrid,this);this.refreshPreview();} detached() {this.representedObject.removeEventListener(WI.Canvas.Event.SizeChanged,this._updateSize,this);this.representedObject.removeEventListener(WI.Canvas.Event.MemoryChanged,this._updateMemoryCost,this);this.representedObject.removeEventListener(WI.Canvas.Event.RecordingStarted,this.needsLayout,this);this.representedObject.removeEventListener(WI.Canvas.Event.RecordingProgress,this.needsLayout,this);this.representedObject.removeEventListener(WI.Canvas.Event.RecordingStopped,this.needsLayout,this);this.representedObject.shaderProgramCollection.removeEventListener(WI.Collection.Event.ItemAdded,this.needsLayout,this);this.representedObject.shaderProgramCollection.removeEventListener(WI.Collection.Event.ItemRemoved,this.needsLayout,this);this._canvasNode=null;WI.settings.showImageGrid.removeEventListener(WI.Setting.Event.Changed,this._updateImageGrid,this);super.detached();} _showError() {if(this._previewImageElement) this._previewImageElement.remove();if(!this._errorElement){let isError=WI.Canvas.supportsRequestContentForContextType(this.representedObject.contextType);this._errorElement=WI.createMessageTextView(WI.UIString("No Preview Available"),isError);} if(this._previewContainerElement) this._previewContainerElement.appendChild(this._errorElement);} _toggleRecording(event) {if(this.representedObject.recordingActive) this.representedObject.stopRecording();else{let singleFrame=event.data.nativeEvent.shiftKey;this.representedObject.startRecording(singleFrame);}} _populateCanvasElementButtonContextMenu(contextMenu) {contextMenu.appendItem(WI.UIString("Log Canvas Context"),()=>{WI.RemoteObject.resolveCanvasContext(this.representedObject,WI.RuntimeManager.ConsoleObjectGroup).then((remoteObject)=>{if(!remoteObject) return;const text=WI.UIString("Selected Canvas Context");WI.consoleLogViewController.appendImmediateExecutionWithResult(text,remoteObject,{addSpecialUserLogClass:true,shouldRevealConsole:true});});});contextMenu.appendSeparator();if(this._canvasNode) WI.appendContextMenuItemsForDOMNode(contextMenu,this._canvasNode);} _showGridButtonClicked() {WI.settings.showImageGrid.value=!this._showGridButtonNavigationItem.activated;} _updateImageGrid() {let activated=WI.settings.showImageGrid.value;this._showGridButtonNavigationItem.activated=activated;if(this._previewImageElement) this._previewImageElement.classList.toggle("show-grid",activated);} _updateSize() {if(this._pixelSizeElement){let size=this.representedObject.size;if(size) this._pixelSizeElement.textContent=`${size.width} ${multiplicationSign} ${size.height}`;else this._pixelSizeElement.textContent=emDash;} this.refreshPreview();} _updateMemoryCost() {if(!this._memoryCostElement) return;let memoryCost=this.representedObject.memoryCost;if(isNaN(memoryCost)) this._memoryCostElement.textContent=emDash;else{const higherResolution=false;let bytesString=Number.bytesToString(memoryCost,higherResolution);this._memoryCostElement.textContent=`(${bytesString})`;}} _updateRecordNavigationItem() {if(!this._recordButtonNavigationItem) return;let recordingActive=this.representedObject.recordingActive;this._recordButtonNavigationItem.toggled=recordingActive;this._refreshButtonNavigationItem.enabled=!recordingActive;this.element.classList.toggle("recording-active",recordingActive);} _updateProgressView() {if(!this._previewContainerElement) return;if(!this.representedObject.recordingActive){if(this._progressView&&this._progressView.parentView){this.removeSubview(this._progressView);this._progressView=null;} return;} if(!this._progressView){this._progressView=new WI.ProgressView;this.element.insertBefore(this._progressView.element,this._previewContainerElement);this.addSubview(this._progressView);} let title=null;if(this.representedObject.recordingFrameCount){let formatString=this.representedObject.recordingFrameCount===1?WI.UIString("%d Frame"):WI.UIString("%d Frames");title=formatString.format(this.representedObject.recordingFrameCount);}else title=WI.UIString("Waiting for frames\u2026");this._progressView.title=title;this._progressView.subtitle=this.representedObject.recordingBufferUsed?Number.bytesToString(this.representedObject.recordingBufferUsed):"";} _updateViewRelatedItems() {if(!this._viewRelatedItemsContainer) return;this._viewRelatedItemsContainer.removeChildren();if(this.representedObject.shaderProgramCollection.size) this._viewRelatedItemsContainer.appendChild(this._viewShaderButton);if(this.representedObject.recordingCollection.size) this._viewRelatedItemsContainer.appendChild(this._viewRecordingButton);} _populateViewShaderButtonContextMenu(contextMenu,event) {let shaderPrograms=this.representedObject.shaderProgramCollection;if(!shaderPrograms.size) return;if(event.button===0&&shaderPrograms.size===1){WI.showRepresentedObject(Array.from(shaderPrograms)[0]);return;} for(let shaderProgram of shaderPrograms){contextMenu.appendItem(shaderProgram.displayName,()=>{WI.showRepresentedObject(shaderProgram);});}} _populateViewRecordingButtonContextMenu(contextMenu,event) {let recordings=this.representedObject.recordingCollection;if(!recordings.size) return;if(event.button===0&&recordings.size===1){WI.showRepresentedObject(Array.from(recordings)[0]);return;} for(let recording of recordings){contextMenu.appendItem(recording.displayName,()=>{WI.showRepresentedObject(recording);});}}};WI.CanvasDetailsSidebarPanel=class CanvasDetailsSidebarPanel extends WI.DetailsSidebarPanel {constructor() {super("canvas",WI.UIString("Canvas"));this.element.classList.add("canvas");this._canvas=null;this._node=null;this._sections=[];this._emptyContentPlaceholder=null;} inspect(objects) {if(!(objects instanceof Array)) objects=[objects];objects=objects.map((object)=>{if(object instanceof WI.Recording) return object.source;if(object instanceof WI.ShaderProgram) return object.canvas;return object;});this.canvas=objects.find((object)=>object instanceof WI.Canvas);return!!this.canvas;} get canvas() {return this._canvas;} set canvas(canvas) {if(canvas===this._canvas) return;if(this._node){this._node.removeEventListener(WI.DOMNode.Event.AttributeModified,this._refreshSourceSection,this);this._node.removeEventListener(WI.DOMNode.Event.AttributeRemoved,this._refreshSourceSection,this);this._node=null;} if(this._canvas){this._canvas.removeEventListener(WI.Canvas.Event.MemoryChanged,this._canvasMemoryChanged,this);this._canvas.removeEventListener(WI.Canvas.Event.ExtensionEnabled,this._refreshExtensionsSection,this);this._canvas.removeEventListener(WI.Canvas.Event.ClientNodesChanged,this._refreshClientsSection,this);} this._canvas=canvas||null;if(this._canvas){this._canvas.addEventListener(WI.Canvas.Event.MemoryChanged,this._canvasMemoryChanged,this);this._canvas.addEventListener(WI.Canvas.Event.ExtensionEnabled,this._refreshExtensionsSection,this);this._canvas.addEventListener(WI.Canvas.Event.ClientNodesChanged,this._refreshClientsSection,this);} this.needsLayout();} initialLayout() {super.initialLayout();this._nameRow=new WI.DetailsSectionSimpleRow(WI.UIString("Name"));this._typeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Type"));this._memoryRow=new WI.DetailsSectionSimpleRow(WI.UIString("Memory"));this._memoryRow.tooltip=WI.UIString("Memory usage of this canvas");let identitySection=new WI.DetailsSection("canvas-details",WI.UIString("Identity"));identitySection.groups=[new WI.DetailsSectionGroup([this._nameRow,this._typeRow,this._memoryRow])];this._sections.push(identitySection);this._nodeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Node"));this._cssCanvasRow=new WI.DetailsSectionSimpleRow(WI.UIString("CSS Canvas"));this._widthRow=new WI.DetailsSectionSimpleRow(WI.UIString("Width"));this._heightRow=new WI.DetailsSectionSimpleRow(WI.UIString("Height"));this._detachedRow=new WI.DetailsSectionSimpleRow(WI.UIString("Detached"));let sourceSection=new WI.DetailsSection("canvas-source",WI.UIString("Source"));sourceSection.groups=[new WI.DetailsSectionGroup([this._nodeRow,this._cssCanvasRow,this._widthRow,this._heightRow,this._detachedRow])];this._sections.push(sourceSection);this._attributesDataGridRow=new WI.DetailsSectionDataGridRow(null,WI.UIString("No Attributes"));this._attributesSection=new WI.DetailsSection("canvas-attributes",WI.UIString("Attributes"));this._attributesSection.groups=[new WI.DetailsSectionGroup([this._attributesDataGridRow])];this._attributesSection.element.hidden=true;this._sections.push(this._attributesSection);this._extensionsSection=new WI.DetailsSection("canvas-extensions",WI.UIString("Extensions"));this._extensionsSection.element.hidden=true;this._sections.push(this._extensionsSection);this._clientNodesRow=new WI.DetailsSectionSimpleRow(WI.UIString("Nodes"));this._clientsSection=new WI.DetailsSection("canvas-clients",WI.UIString("Clients"));this._clientsSection.groups=[new WI.DetailsSectionGroup([this._clientNodesRow])];this._clientsSection.element.hidden=true;this._sections.push(this._clientsSection);const selectable=false;let backtraceTreeOutline=new WI.TreeOutline(selectable);backtraceTreeOutline.disclosureButtons=false;this._backtraceTreeController=new WI.StackTraceTreeController(backtraceTreeOutline);let backtraceRow=new WI.DetailsSectionRow;backtraceRow.element.appendChild(backtraceTreeOutline.element);this._backtraceSection=new WI.DetailsSection("canvas-backtrace",WI.UIString("Backtrace"));this._backtraceSection.groups=[new WI.DetailsSectionGroup([backtraceRow])];this._backtraceSection.element.hidden=true;this._sections.push(this._backtraceSection);this._emptyContentPlaceholder=WI.createMessageTextView(WI.UIString("No Canvas Selected"));} layout() {super.layout();this.contentView.element.removeChildren();if(!this._canvas){this.contentView.element.appendChild(this._emptyContentPlaceholder);return;} this.contentView.element.append(...this._sections.map(section=>section.element));this._refreshIdentitySection();this._refreshSourceSection();this._refreshAttributesSection();this._refreshExtensionsSection();this._refreshClientsSection();this._refreshBacktraceSection();} sizeDidChange() {super.sizeDidChange(); this._attributesDataGridRow.sizeDidChange();} _refreshIdentitySection() {this._nameRow.value=this._canvas.displayName;this._typeRow.value=WI.Canvas.displayNameForContextType(this._canvas.contextType);this._formatMemoryRow();} _refreshSourceSection() {if(!this.didInitialLayout) return;let hideNode=this._canvas.cssCanvasName||this._canvas.contextType===WI.Canvas.ContextType.WebGPU;this._nodeRow.value=hideNode?null:emDash;this._cssCanvasRow.value=this._canvas.cssCanvasName||null;this._widthRow.value=emDash;this._heightRow.value=emDash;this._detachedRow.value=null;this._canvas.requestNode().then((node)=>{if(!node){this._nodeRow.value=null;return;} if(node!==this._node){if(this._node){this._node.removeEventListener(WI.DOMNode.Event.AttributeModified,this._refreshSourceSection,this);this._node.removeEventListener(WI.DOMNode.Event.AttributeRemoved,this._refreshSourceSection,this);this._node=null;} this._node=node;this._node.addEventListener(WI.DOMNode.Event.AttributeModified,this._refreshSourceSection,this);this._node.addEventListener(WI.DOMNode.Event.AttributeRemoved,this._refreshSourceSection,this);} if(!hideNode){this._nodeRow.value=WI.linkifyNodeReference(this._node);if(!this._node.parentNode) this._detachedRow.value=WI.UIString("Yes");} let setRowValueIfValidAttributeValue=(row,attribute)=>{let value=Number(this._node.getAttribute(attribute));if(!Number.isInteger(value)||value<0) return false;row.value=value;return true;};let validWidth=setRowValueIfValidAttributeValue(this._widthRow,"width");let validHeight=setRowValueIfValidAttributeValue(this._heightRow,"height");if(!validWidth||!validHeight){ WI.RemoteObject.resolveNode(node).then((remoteObject)=>{function setRowValueToPropertyValue(row,property){remoteObject.getProperty(property,(error,result,wasThrown)=>{if(!error&&result.type==="number") row.value=`${result.value}px`;});} setRowValueToPropertyValue(this._widthRow,"width");setRowValueToPropertyValue(this._heightRow,"height");remoteObject.release();});}});} _refreshAttributesSection() {let hasAttributes=!isEmptyObject(this._canvas.contextAttributes);this._attributesSection.element.hidden=!hasAttributes;if(!hasAttributes) return;let dataGrid=this._attributesDataGridRow.dataGrid;if(!dataGrid){dataGrid=this._attributesDataGridRow.dataGrid=new WI.DataGrid({name:{title:WI.UIString("Name")},value:{title:WI.UIString("Value"),width:"30%"},});} dataGrid.removeChildren();for(let attribute in this._canvas.contextAttributes){let data={name:attribute,value:this._canvas.contextAttributes[attribute]};let dataGridNode=new WI.DataGridNode(data);dataGrid.appendChild(dataGridNode);} dataGrid.updateLayoutIfNeeded();} _refreshExtensionsSection() {let hasEnabledExtensions=this._canvas.extensions.size>0;this._extensionsSection.element.hidden=!hasEnabledExtensions;if(!hasEnabledExtensions) return;let element=document.createElement("ul");for(let extension of this._canvas.extensions){let listElement=element.appendChild(document.createElement("li"));listElement.textContent=extension;} this._extensionsSection.groups=[{element}];} _refreshClientsSection() {if(!this.didInitialLayout) return;if(!this._canvas.cssCanvasName&&this._canvas.contextType!==WI.Canvas.ContextType.WebGPU){this._clientsSection.element.hidden=true;return;} this._clientNodesRow.value=emDash;this._clientsSection.element.hidden=false;this._canvas.requestClientNodes((clientNodes)=>{if(!clientNodes.length) return;let fragment=document.createDocumentFragment();for(let clientNode of clientNodes) fragment.appendChild(WI.linkifyNodeReference(clientNode));this._clientNodesRow.value=fragment;});} _refreshBacktraceSection() {let stackTrace=this._canvas.stackTrace;this._backtraceTreeController.stackTrace=stackTrace;this._backtraceSection.element.hidden=!stackTrace?.callFrames.length;} _formatMemoryRow() {if(!this.didInitialLayout) return;if(!this._canvas.memoryCost||isNaN(this._canvas.memoryCost)){this._memoryRow.value=emDash;return;} this._memoryRow.value=Number.bytesToString(this._canvas.memoryCost);} _canvasMemoryChanged(event) {this._formatMemoryRow();}};WI.CanvasOverviewContentView=class CanvasOverviewContentView extends WI.CollectionContentView {constructor(representedObject) {let contentPlaceholder=WI.animationManager.supported?document.createElement("div"):WI.createMessageTextView(WI.UIString("No Canvas Contexts"));let descriptionElement=contentPlaceholder.appendChild(document.createElement("div"));descriptionElement.className="description";descriptionElement.textContent=WI.UIString("Waiting for canvas contexts created by script or CSS.");let importNavigationItem=new WI.ButtonNavigationItem("import-recording",WI.UIString("Import"),"Images/Import.svg",15,15);importNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;let importHelpElement=WI.createNavigationItemHelp(WI.UIString("Press %s to load a recording from file."),importNavigationItem);contentPlaceholder.appendChild(importHelpElement);super(representedObject,WI.CanvasContentView,contentPlaceholder);this.element.classList.add("canvas-overview");if(WI.CanvasManager.supportsRecordingAutoCapture()){this._recordingAutoCaptureFrameCountInputElement=document.createElement("input");this._recordingAutoCaptureFrameCountInputElement.type="number";this._recordingAutoCaptureFrameCountInputElement.min=0;this._recordingAutoCaptureFrameCountInputElement.addEventListener("input",this._handleRecordingAutoCaptureInput.bind(this));this._recordingAutoCaptureFrameCountInputElementValue=WI.settings.canvasRecordingAutoCaptureFrameCount.value;const label=null;this._recordingAutoCaptureNavigationItem=new WI.CheckboxNavigationItem("canvas-recording-auto-capture",label,!!WI.settings.canvasRecordingAutoCaptureEnabled.value);this._recordingAutoCaptureNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._recordingAutoCaptureNavigationItem.addEventListener(WI.CheckboxNavigationItem.Event.CheckedDidChange,this._handleRecordingAutoCaptureCheckedDidChange,this);let frameCount=this._updateRecordingAutoCaptureInputElementSize();this._setRecordingAutoCaptureFrameCount(frameCount);this._updateRecordingAutoCaptureCheckboxLabel(frameCount);} importNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleImportButtonNavigationItemClicked,this);this._savedRecordingsContentView=null;this._savedRecordingsTreeOutline=null;} get navigationItems() {let navigationItems=[];if(this._recordingAutoCaptureNavigationItem) navigationItems.push(this._recordingAutoCaptureNavigationItem);return navigationItems;} handleRefreshButtonClicked() {for(let subview of this.subviews){if(subview instanceof WI.CanvasContentView) subview.handleRefreshButtonClicked();}} contentViewAdded(contentView) {contentView.element.addEventListener("mouseenter",this._contentViewMouseEnter);contentView.element.addEventListener("mouseleave",this._contentViewMouseLeave);if(this._savedRecordingsContentView){this.removeSubview(this._savedRecordingsContentView);this.addSubview(this._savedRecordingsContentView);}} contentViewRemoved(contentView) {contentView.element.removeEventListener("mouseenter",this._contentViewMouseEnter);contentView.element.removeEventListener("mouseleave",this._contentViewMouseLeave);} attached() {super.attached();WI.settings.canvasRecordingAutoCaptureEnabled.addEventListener(WI.Setting.Event.Changed,this._handleCanvasRecordingAutoCaptureEnabledChanged,this);WI.settings.canvasRecordingAutoCaptureFrameCount.addEventListener(WI.Setting.Event.Changed,this._handleCanvasRecordingAutoCaptureFrameCountChanged,this);WI.canvasManager.addEventListener(WI.CanvasManager.Event.RecordingSaved,this._handleRecordingSaved,this);if(this._savedRecordingsTreeOutline) this._savedRecordingsTreeOutline.removeChildren();for(let recording of WI.canvasManager.savedRecordings) this._addSavedRecording(recording);for(let subview of this.subviews){if(subview instanceof WI.CanvasContentView) subview.refreshPreview();}} detached() {WI.domManager.hideDOMNodeHighlight();WI.canvasManager.removeEventListener(WI.CanvasManager.Event.RecordingSaved,this._handleRecordingSaved,this);WI.settings.canvasRecordingAutoCaptureFrameCount.removeEventListener(WI.Setting.Event.Changed,this._handleCanvasRecordingAutoCaptureFrameCountChanged,this);WI.settings.canvasRecordingAutoCaptureEnabled.removeEventListener(WI.Setting.Event.Changed,this._handleCanvasRecordingAutoCaptureEnabledChanged,this);super.detached();} _contentViewMouseEnter(event) {let contentView=WI.View.fromElement(event.target);if(!(contentView instanceof WI.CanvasContentView)) return;let canvas=contentView.representedObject;if(canvas.cssCanvasName||canvas.contextType===WI.Canvas.ContextType.WebGPU){canvas.requestClientNodes((clientNodes)=>{WI.domManager.highlightDOMNodeList(clientNodes);});return;} canvas.requestNode().then((node)=>{if(!node||!node.ownerDocument) return;node.highlight();});} _contentViewMouseLeave(event) {WI.domManager.hideDOMNodeHighlight();} _setRecordingAutoCaptureFrameCount(frameCount) {if(this._recordingAutoCaptureNavigationItem.checked) frameCount=Math.max(1,frameCount);let enabled=frameCount>0&&!!this._recordingAutoCaptureNavigationItem.checked;WI.canvasManager.setRecordingAutoCaptureFrameCount(enabled,frameCount);} _updateRecordingAutoCaptureCheckboxLabel(frameCount) {let active=document.activeElement===this._recordingAutoCaptureFrameCountInputElement;let selectionStart=this._recordingAutoCaptureFrameCountInputElement.selectionStart;let selectionEnd=this._recordingAutoCaptureFrameCountInputElement.selectionEnd;let direction=this._recordingAutoCaptureFrameCountInputElement.direction;let label=frameCount===1?WI.UIString("Record first %s frame"):WI.UIString("Record first %s frames");let fragment=document.createDocumentFragment();String.format(label,[this._recordingAutoCaptureFrameCountInputElement],String.standardFormatters,fragment,(a,b)=>{a.append(b);return a;});this._recordingAutoCaptureNavigationItem.label=fragment;if(active){this._recordingAutoCaptureFrameCountInputElement.selectionStart=selectionStart;this._recordingAutoCaptureFrameCountInputElement.selectionEnd=selectionEnd;this._recordingAutoCaptureFrameCountInputElement.direction=direction;}} get _recordingAutoCaptureFrameCountInputElementValue() {return parseInt(this._recordingAutoCaptureFrameCountInputElement.value);} set _recordingAutoCaptureFrameCountInputElementValue(frameCount) {if(this._recordingAutoCaptureFrameCountInputElement.value||frameCount) this._recordingAutoCaptureFrameCountInputElement.value=frameCount;this._recordingAutoCaptureFrameCountInputElement.placeholder=frameCount;} _updateRecordingAutoCaptureInputElementSize() {let frameCount=this._recordingAutoCaptureFrameCountInputElementValue;if(isNaN(frameCount)||frameCount<0){frameCount=0;this._recordingAutoCaptureFrameCountInputElementValue=frameCount;} this._recordingAutoCaptureFrameCountInputElement.autosize();return frameCount;} _addSavedRecording(recording) {if(!this._savedRecordingsContentView){this._savedRecordingsContentView=new WI.ContentView;this._savedRecordingsContentView.element.classList.add("canvas","saved-recordings");this.addSubview(this._savedRecordingsContentView);let header=this._savedRecordingsContentView.element.appendChild(document.createElement("header"));header.textContent=WI.UIString("Saved Recordings");this.hideContentPlaceholder();} if(!this._savedRecordingsTreeOutline){const selectable=false;this._savedRecordingsTreeOutline=new WI.TreeOutline(selectable);this._savedRecordingsTreeOutline.addEventListener(WI.TreeOutline.Event.ElementClicked,this._handleSavedRecordingClicked,this);this._savedRecordingsContentView.element.appendChild(this._savedRecordingsTreeOutline.element);} let recordingTreeElement=new WI.GeneralTreeElement(["recording"],recording.displayName,WI.Recording.displayNameForRecordingType(recording.type),recording);recordingTreeElement.selectable=false;this._savedRecordingsTreeOutline.appendChild(recordingTreeElement);} _handleRecordingAutoCaptureInput(event) {let frameCount=this._updateRecordingAutoCaptureInputElementSize();this._recordingAutoCaptureNavigationItem.checked=!!frameCount;this._setRecordingAutoCaptureFrameCount(frameCount);} _handleRecordingAutoCaptureCheckedDidChange(event) {this._setRecordingAutoCaptureFrameCount(this._recordingAutoCaptureFrameCountInputElementValue||0);} _handleCanvasRecordingAutoCaptureEnabledChanged(event) {this._recordingAutoCaptureNavigationItem.checked=WI.settings.canvasRecordingAutoCaptureEnabled.value;} _handleCanvasRecordingAutoCaptureFrameCountChanged(event) {if(this._recordingAutoCaptureFrameCountInputElementValue!==WI.settings.canvasRecordingAutoCaptureFrameCount.value) this._recordingAutoCaptureFrameCountInputElementValue=WI.settings.canvasRecordingAutoCaptureFrameCount.value;this._updateRecordingAutoCaptureCheckboxLabel(WI.settings.canvasRecordingAutoCaptureFrameCount.value);} _handleImportButtonNavigationItemClicked(event) {WI.FileUtilities.importJSON((result)=>WI.canvasManager.processJSON(result),{multiple:true});} _handleRecordingSaved(event) {this._addSavedRecording(event.data.recording);} _handleSavedRecordingClicked(event) {WI.showRepresentedObject(event.data.treeElement.representedObject);}};WI.CanvasSidebarPanel=class CanvasSidebarPanel extends WI.NavigationSidebarPanel {constructor() {super("canvas",WI.UIString("Canvas"));this._canvas=null;this._recording=null;this._navigationBar=new WI.NavigationBar;this._scopeBar=null;this._placeholderScopeBarItem=null;const toolTip=WI.UIString("Start recording canvas actions.\nShift-click to record a single frame.");const altToolTip=WI.UIString("Stop recording canvas actions");this._recordButtonNavigationItem=new WI.ToggleButtonNavigationItem("record-start-stop",toolTip,altToolTip,"Images/Record.svg","Images/Stop.svg",13,13);this._recordButtonNavigationItem.enabled=false;this._recordButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;this._recordButtonNavigationItem.label=WI.UIString("Start");this._recordButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._toggleRecording,this);this._navigationBar.addNavigationItem(this._recordButtonNavigationItem);this._navigationBar.addNavigationItem(new WI.DividerNavigationItem);let importButtonNavigationItem=new WI.ButtonNavigationItem("import-recording",WI.UIString("Import"),"Images/Import.svg",15,15);importButtonNavigationItem.buttonStyle=WI.ButtonNavigationItem.Style.ImageAndText;importButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;importButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleImportButtonNavigationItemClicked,this);this._navigationBar.addNavigationItem(importButtonNavigationItem);this.addSubview(this._navigationBar);this._canvasTreeOutline=this.createContentTreeOutline({suppressFiltering:true});this._canvasTreeOutline.element.classList.add("canvas");this._recordingNavigationBar=new WI.NavigationBar;this._recordingNavigationBar.element.classList.add("hidden");this.contentView.addSubview(this._recordingNavigationBar);this._recordingContentContainer=this.contentView.element.appendChild(document.createElement("div"));this._recordingContentContainer.className="recording-content";this._recordingTreeOutline=this.contentTreeOutline;this._recordingContentContainer.appendChild(this._recordingTreeOutline.element);this._recordingTreeOutline.customIndent=true;this._recordingTreeOutline.registerScrollVirtualizer(this._recordingContentContainer,20);this._canvasTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._treeSelectionDidChange,this);this._recordingTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._treeSelectionDidChange,this);this._recordingProcessingOptionsContainer=null;this._selectedRecordingActionIndex=NaN;} get canvas() {return this._canvas;} set canvas(canvas) {if(this._canvas===canvas) return;if(this._canvas){this._canvas.removeEventListener(WI.Canvas.Event.RecordingStarted,this._updateRecordNavigationItem,this);this._canvas.removeEventListener(WI.Canvas.Event.RecordingStopped,this._updateRecordNavigationItem,this);this._canvas.recordingCollection.removeEventListener(WI.Collection.Event.ItemAdded,this._recordingAdded,this);this._canvas.recordingCollection.removeEventListener(WI.Collection.Event.ItemRemoved,this._recordingRemoved,this);} this._canvas=canvas;if(this._canvas){this._canvas.addEventListener(WI.Canvas.Event.RecordingStarted,this._updateRecordNavigationItem,this);this._canvas.addEventListener(WI.Canvas.Event.RecordingStopped,this._updateRecordNavigationItem,this);this._canvas.recordingCollection.addEventListener(WI.Collection.Event.ItemAdded,this._recordingAdded,this);this._canvas.recordingCollection.addEventListener(WI.Collection.Event.ItemRemoved,this._recordingRemoved,this);} this._canvasChanged();this._updateRecordNavigationItem();this._updateRecordingScopeBar();} set recording(recording) {if(recording===this._recording) return;if(this._recording&&!this._recording.ready){this._recording.removeEventListener(WI.Recording.Event.ProcessedAction,this._handleRecordingProcessedAction,this);this._recording.removeEventListener(WI.Recording.Event.StartProcessingFrame,this._handleRecordingStartProcessingFrame,this);} if(recording) this.canvas=recording.source;this._recording=recording;if(this._recording&&!this._recording.ready){this._recording.addEventListener(WI.Recording.Event.ProcessedAction,this._handleRecordingProcessedAction,this);this._recording.addEventListener(WI.Recording.Event.StartProcessingFrame,this._handleRecordingStartProcessingFrame,this);} this._updateRecordNavigationItem();this._updateRecordingScopeBar();this._recordingChanged();} set action(action) {if(!this._recording) return;if(action===this._recording.actions[this._selectedRecordingActionIndex]) return;let selectedTreeElement=this._recordingTreeOutline.selectedTreeElement;if(!action){if(selectedTreeElement) selectedTreeElement.deselect();return;} if(selectedTreeElement&&selectedTreeElement instanceof WI.FolderTreeElement){let lastActionTreeElement=selectedTreeElement.children.lastValue;if(action===lastActionTreeElement.representedObject) return;} let treeElement=this._recordingTreeOutline.findTreeElement(action);if(!treeElement) return;this._recording[WI.CanvasSidebarPanel.SelectedActionSymbol]=action;const omitFocus=false;const selectedByUser=false;treeElement.revealAndSelect(omitFocus,selectedByUser);this._selectedRecordingActionIndex=this._recording.actions.indexOf(action);} updateRepresentedObjects() {let objects=this.contentBrowser.currentRepresentedObjects;let canvas=objects.find((object)=>object instanceof WI.Canvas);if(canvas){this.canvas=canvas;let treeElement=this._canvasTreeOutline.findTreeElement(canvas);const omitFocus=false;const selectedByUser=false;treeElement.revealAndSelect(omitFocus,selectedByUser);return;} let shaderProgram=objects.find((object)=>object instanceof WI.ShaderProgram);if(shaderProgram){this.canvas=shaderProgram.canvas;let treeElement=this._canvasTreeOutline.findTreeElement(shaderProgram);const omitFocus=false;const selectedByUser=false;treeElement.revealAndSelect(omitFocus,selectedByUser);return;} let recording=objects.find((object)=>object instanceof WI.Recording);if(recording){this.canvas=recording.source;this.recording=recording;let recordingAction=objects.find((object)=>object instanceof WI.RecordingAction);if(recordingAction!==recording[WI.CanvasSidebarPanel.SelectedActionSymbol]) this.action=recordingAction;return;} this.canvas=null;this.recording=null;} attached() {super.attached();this.contentBrowser.addEventListener(WI.ContentBrowser.Event.CurrentRepresentedObjectsDidChange,this.updateRepresentedObjects,this);this.updateRepresentedObjects();if(this._recording){this._recordingTreeOutline.updateVirtualizedElementsDebouncer.force();let action=this._recording[WI.CanvasSidebarPanel.SelectedActionSymbol];let treeElement=this._recordingTreeOutline.findTreeElement(action);if(treeElement){const omitFocus=false;const selectedByUser=false;treeElement.revealAndSelect(omitFocus,selectedByUser);}}} detached() {this.contentBrowser.removeEventListener(WI.ContentBrowser.Event.CurrentRepresentedObjectsDidChange,this.updateRepresentedObjects,this);super.detached();} canShowRepresentedObject(representedObject) {return representedObject instanceof WI.Canvas||representedObject instanceof WI.ShaderProgram||representedObject instanceof WI.Recording;} get scrollElement() {return this._recordingContentContainer;} hasCustomFilters() {return true;} matchTreeElementAgainstCustomFilters(treeElement) {if(treeElement instanceof WI.FolderTreeElement) return true;if(treeElement instanceof WI.RecordingActionTreeElement&&treeElement.representedObject instanceof WI.RecordingInitialStateAction) return true;return super.matchTreeElementAgainstCustomFilters(treeElement);} initialLayout() {super.initialLayout();let filterFunction=(treeElement)=>{if(!(treeElement.representedObject instanceof WI.RecordingAction)) return false;return treeElement.representedObject.isVisual||treeElement.representedObject instanceof WI.RecordingInitialStateAction;};const activatedByDefault=false;const defaultToolTip=WI.UIString("Only show visual actions");const activatedToolTip=WI.UIString("Show all actions");this.filterBar.addFilterBarButton("recording-show-visual-only",filterFunction,activatedByDefault,defaultToolTip,activatedToolTip,"Images/Paint.svg",15,15);} _recordingAdded(event) {this.recording=event.data.item;} _recordingRemoved(event) {this._updateRecordingScopeBar();let recording=event.data.item;if(recording===this.recording) this.recording=this._canvas?Array.from(this._canvas.recordingCollection).lastValue:null;} _scopeBarSelectionChanged() {let selectedScopeBarItem=this._scopeBar.selectedItems[0];this.recording=selectedScopeBarItem.__recording||null;} _toggleRecording(event) {if(!this._canvas) return;if(this._canvas.recordingActive) this._canvas.stopRecording();else{let singleFrame=event.data.nativeEvent.shiftKey;this._canvas.startRecording(singleFrame);}} _handleImportButtonNavigationItemClicked(event) {WI.FileUtilities.importJSON((result)=>WI.canvasManager.processJSON(result),{multiple:true});} _treeSelectionDidChange(event) {let treeElement=event.target.selectedTreeElement;if(!treeElement) return;if((treeElement instanceof WI.CanvasTreeElement)||(treeElement instanceof WI.ShaderProgramTreeElement)){if(this._placeholderScopeBarItem) this._placeholderScopeBarItem.selected=true;this.showDefaultContentViewForTreeElement(treeElement);return;} if(treeElement instanceof WI.FolderTreeElement) treeElement=treeElement.children.lastValue;if(!(treeElement instanceof WI.RecordingActionTreeElement)) return;this._recording[WI.CanvasSidebarPanel.SelectedActionSymbol]=treeElement.representedObject;const onlyExisting=true;let recordingContentView=this.contentBrowser.contentViewForRepresentedObject(this._recording,onlyExisting);if(!recordingContentView) return;this.contentBrowser.showContentView(recordingContentView);this._selectedRecordingActionIndex=treeElement.index;recordingContentView.updateActionIndex(this._selectedRecordingActionIndex);} _canvasChanged() {this._canvasTreeOutline.removeChildren();if(!this._canvas){this._recordingNavigationBar.element.classList.add("hidden");return;} const showRecordings=false;let canvasTreeElement=new WI.CanvasTreeElement(this._canvas,showRecordings);canvasTreeElement.expanded=true;this._canvasTreeOutline.appendChild(canvasTreeElement);const omitFocus=false;const selectedByUser=false;canvasTreeElement.revealAndSelect(omitFocus,selectedByUser);if(this._canvas.supportsRecording) this._recordButtonNavigationItem.enabled=true;this.recording=null;} _recordingChanged() {this._recordingTreeOutline.removeChildren();this._selectedRecordingActionIndex=NaN;if(this._recordingProcessingOptionsContainer){this._recordingProcessingOptionsContainer.remove();this._recordingProcessingOptionsContainer=null;} if(!this._recording) return;if(!this._recording.ready){if(!this._recording.processing) this._recording.startProcessing();if(!this._recordingProcessingOptionsContainer){this._recordingProcessingOptionsContainer=this._recordingContentContainer.appendChild(document.createElement("div"));this._recordingProcessingOptionsContainer.classList.add("recording-processing-options");let createPauseButton=()=>{let spinner=new WI.IndeterminateProgressSpinner;this._recordingProcessingOptionsContainer.appendChild(spinner.element);let pauseButton=this._recordingProcessingOptionsContainer.appendChild(document.createElement("button"));pauseButton.textContent=WI.UIString("Pause Processing");pauseButton.addEventListener("click",(event)=>{this._recording.stopProcessing();spinner.element.remove();pauseButton.remove();createResumeButton();});};let createResumeButton=()=>{let resumeButton=this._recordingProcessingOptionsContainer.appendChild(document.createElement("button"));resumeButton.textContent=WI.UIString("Resume Processing");resumeButton.addEventListener("click",(event)=>{this._recording.startProcessing();resumeButton.remove();createPauseButton();});};if(this._recording.processing) createPauseButton();else createResumeButton();}} this.contentBrowser.showContentViewForRepresentedObject(this._recording);if(this._scopeBar){let scopeBarItem=this._scopeBar.item(this._recording.displayName);scopeBarItem.selected=true;} let initialStateAction=this._recording.actions[0];if(initialStateAction.ready&&!this._recordingTreeOutline.getCachedTreeElement(initialStateAction)){this._recordingTreeOutline.appendChild(new WI.RecordingActionTreeElement(initialStateAction,0,this._recording.type));if(!this._recording[WI.CanvasSidebarPanel.SelectedActionSymbol]) this.action=initialStateAction;} let cumulativeActionIndex=0;this._recording.frames.forEach((frame,frameIndex)=>{if(!frame.actions[0].ready) return;let folder=this._recordingTreeOutline.getCachedTreeElement(frame);if(!folder) folder=this._createRecordingFrameTreeElement(frame,frameIndex,this._recordingTreeOutline);for(let action of frame.actions){++cumulativeActionIndex;if(!action.ready||this._recordingTreeOutline.getCachedTreeElement(action)) break;this._createRecordingActionTreeElement(action,cumulativeActionIndex,folder);}});} _updateRecordNavigationItem() {if(!this._canvas?.supportsRecording){this._recordButtonNavigationItem.enabled=false;return;} this._recordButtonNavigationItem.toggled=this._canvas.recordingActive;this._recordButtonNavigationItem.label=this._recordButtonNavigationItem.toggled?WI.UIString("Stop"):WI.UIString("Start");} _updateRecordingScopeBar() {if(this._scopeBar){this._placeholderScopeBarItem=null;this._recordingNavigationBar.removeNavigationItem(this._scopeBar);this._scopeBar=null;} this._recordingNavigationBar.element.classList.toggle("hidden",!this._canvas);let hasRecordings=this._recording||(this._canvas&&this._canvas.recordingCollection.size);this.element.classList.toggle("has-recordings",hasRecordings);this.element.classList.toggle("showing-recording",!!this._recording);if(!hasRecordings) return;let scopeBarItems=[];let selectedScopeBarItem=null;let createScopeBarItem=(recording)=>{let scopeBarItem=new WI.ScopeBarItem(recording.displayName,recording.displayName);if(recording===this._recording) selectedScopeBarItem=scopeBarItem;else scopeBarItem.selected=false;scopeBarItem.__recording=recording;scopeBarItems.push(scopeBarItem);};if(this._canvas&&this._canvas.recordingCollection){for(let recording of this._canvas.recordingCollection) createScopeBarItem(recording);} if(this._recording&&(!this._canvas||!this._canvas.recordingCollection.has(this._recording))) createScopeBarItem(this._recording);if(!selectedScopeBarItem){selectedScopeBarItem=scopeBarItems[0];this._placeholderScopeBarItem=new WI.ScopeBarItem("canvas-recording-scope-bar-item-placeholder",WI.UIString("Recordings"),{exclusive:true,hidden:true});this._placeholderScopeBarItem.selected=true;scopeBarItems.unshift(this._placeholderScopeBarItem);} this._scopeBar=new WI.ScopeBar("canvas-recording-scope-bar",scopeBarItems,selectedScopeBarItem,true);this._scopeBar.addEventListener(WI.ScopeBar.Event.SelectionChanged,this._scopeBarSelectionChanged,this);this._recordingNavigationBar.insertNavigationItem(this._scopeBar,0);} _createRecordingFrameTreeElement(frame,index,parent) {let folder=new WI.FolderTreeElement(WI.UIString("Frame %d").format((index+1).toLocaleString()),frame);if(!isNaN(frame.duration)){const higherResolution=true;folder.status=Number.secondsToString(frame.duration/1000,higherResolution);} parent.appendChild(folder);return folder;} _createRecordingActionTreeElement(action,index,parent) {let treeElement=new WI.RecordingActionTreeElement(action,index,this._recording.type);parent.appendChild(treeElement);if(parent instanceof WI.FolderTreeElement&&parent.representedObject instanceof WI.RecordingFrame){if(action!==parent.representedObject.actions.lastValue){parent.addClassName("processing");if(!(parent.subtitle instanceof HTMLProgressElement)) parent.subtitle=document.createElement("progress");if(parent.statusElement) parent.subtitle.style.setProperty("width",`calc(100% - ${parent.statusElement.offsetWidth + 4}px`);parent.subtitle.value=parent.representedObject.actions.indexOf(action)/parent.representedObject.actions.length;}else{parent.removeClassName("processing");if(parent.representedObject.incomplete) parent.subtitle=WI.UIString("Incomplete");else parent.subtitle="";}} if(action===this._recording[WI.CanvasSidebarPanel.SelectedActionSymbol]) this.action=action;return treeElement;} _handleRecordingProcessedAction(event) {let{action,index}=event.data;this._recordingTreeOutline.element.dataset.indent=Number.countDigits(index);let isInitialStateAction=!index;this._createRecordingActionTreeElement(action,index,isInitialStateAction?this._recordingTreeOutline:this._recordingTreeOutline.children.lastValue);if(!this._recording[WI.CanvasSidebarPanel.SelectedActionSymbol]){this.action=this._recording.actions[0];} if(this._recording.ready){this._recording.removeEventListener(WI.Recording.Event.ProcessedAction,this._handleRecordingProcessedAction,this);this._recording.removeEventListener(WI.Recording.Event.StartProcessingFrame,this._handleRecordingStartProcessingFrame,this);if(this._recordingProcessingOptionsContainer){this._recordingProcessingOptionsContainer.remove();this._recordingProcessingOptionsContainer=null;}}} _handleRecordingStartProcessingFrame(event) {let{frame,index}=event.data;this._createRecordingFrameTreeElement(frame,index,this._recordingTreeOutline);}};WI.CanvasSidebarPanel.SelectedActionSymbol=Symbol("selected-action");WI.CanvasTreeElement=class CanvasTreeElement extends WI.FolderizedTreeElement {constructor(representedObject,showRecordings=true) {let subtitle=WI.Canvas.displayNameForContextType(representedObject.contextType);super(["canvas",representedObject.contextType],representedObject.displayName,subtitle,representedObject);this.registerFolderizeSettings("shader-programs",WI.UIString("Shader Programs"),this.representedObject.shaderProgramCollection,WI.ShaderProgramTreeElement);this.representedObject.addEventListener(WI.Canvas.Event.RecordingStarted,this._updateStatus,this);this.representedObject.addEventListener(WI.Canvas.Event.RecordingStopped,this._updateStatus,this);this.representedObject.shaderProgramCollection.addEventListener(WI.Collection.Event.ItemAdded,this._handleItemAdded,this);this.representedObject.shaderProgramCollection.addEventListener(WI.Collection.Event.ItemRemoved,this._handleItemRemoved,this);this._showRecordings=showRecordings;if(this._showRecordings){function createRecordingTreeElement(recording){return new WI.GeneralTreeElement(["recording"],recording.displayName,null,recording);} this.registerFolderizeSettings("recordings",WI.UIString("Recordings"),this.representedObject.recordingCollection,createRecordingTreeElement);this.representedObject.recordingCollection.addEventListener(WI.Collection.Event.ItemAdded,this._handleItemAdded,this);this.representedObject.recordingCollection.addEventListener(WI.Collection.Event.ItemRemoved,this._handleItemRemoved,this);}} onattach() {super.onattach();this.element.addEventListener("mouseover",this._handleMouseOver.bind(this));this.element.addEventListener("mouseout",this._handleMouseOut.bind(this));this.onpopulate();} onpopulate() {super.onpopulate();if(this.children.length&&!this.shouldRefreshChildren) return;this.shouldRefreshChildren=false;this.removeChildren();for(let program of this.representedObject.shaderProgramCollection) this.addChildForRepresentedObject(program);if(this._showRecordings){for(let recording of this.representedObject.recordingCollection) this.addChildForRepresentedObject(recording);}} populateContextMenu(contextMenu,event) {super.populateContextMenu(contextMenu,event);contextMenu.appendItem(WI.UIString("Log Canvas Context"),()=>{WI.RemoteObject.resolveCanvasContext(this.representedObject,WI.RuntimeManager.ConsoleObjectGroup,(remoteObject)=>{if(!remoteObject) return;const text=WI.UIString("Selected Canvas Context");WI.consoleLogViewController.appendImmediateExecutionWithResult(text,remoteObject,{addSpecialUserLogClass:true,shouldRevealConsole:true});});});contextMenu.appendSeparator();} _handleItemAdded(event) {this.addChildForRepresentedObject(event.data.item);} _handleItemRemoved(event) {this.removeChildForRepresentedObject(event.data.item);} _handleMouseOver(event) {if(this.representedObject.cssCanvasName||this.representedObject.contextType===WI.Canvas.ContextType.WebGPU){this.representedObject.requestClientNodes((clientNodes)=>{WI.domManager.highlightDOMNodeList(clientNodes);});}else{this.representedObject.requestNode((node)=>{if(!node||!node.ownerDocument) return;node.highlight();});}} _handleMouseOut(event) {WI.domManager.hideDOMNodeHighlight();} _updateStatus() {if(this.representedObject.recordingActive){if(!this.status||!this.status.__showingSpinner){let spinner=new WI.IndeterminateProgressSpinner;this.status=spinner.element;this.status.__showingSpinner=true;}}else{if(this.status&&this.status.__showingSpinner) this.status="";}}};WI.ChangesDetailsSidebarPanel=class ChangesDetailsSidebarPanel extends WI.DOMDetailsSidebarPanel {constructor() {super("changes-details",WI.UIString("Changes"));this.element.classList.add("changes-panel");this.element.dir="ltr";} supportsDOMNode(nodeToInspect) {return nodeToInspect.nodeType()===Node.ELEMENT_NODE;} attached() {super.attached();WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);WI.CSSManager.addEventListener(WI.CSSManager.Event.ModifiedStylesChanged,this.needsLayout,this);} detached() {WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);WI.CSSManager.removeEventListener(WI.CSSManager.Event.ModifiedStylesChanged,this.needsLayout,this);super.detached();} layout() {super.layout();this.element.removeChildren();let modifiedStyles=WI.cssManager.modifiedStyles;if(WI.settings.cssChangesPerNode.value){if(this.domNode){let stylesForNode=WI.cssManager.stylesForNode(this.domNode);modifiedStyles=modifiedStyles.filter((style)=>{if(style.node===this.domNode) return true;if(style.ownerRule) return stylesForNode.matchedRules.some((matchedRule)=>style.ownerRule.isEqualTo(matchedRule));return false;});}else modifiedStyles=[];} this.element.classList.toggle("empty",!modifiedStyles.length);if(!modifiedStyles.length){this.element.textContent=WI.UIString("No CSS Changes");return;} let declarationsForStyleSheet=new Map();for(let style of modifiedStyles){let styleDeclarations=declarationsForStyleSheet.get(style.ownerStyleSheet);if(!styleDeclarations){styleDeclarations=[];declarationsForStyleSheet.set(style.ownerStyleSheet,styleDeclarations);} styleDeclarations.push(style);} for(let[styleSheet,styles]of declarationsForStyleSheet){let resourceSection=this.element.appendChild(document.createElement("section"));resourceSection.classList.add("resource-section");let resourceHeader=resourceSection.appendChild(document.createElement("div"));resourceHeader.classList.add("header");resourceHeader.append(styleSheet.isInlineStyleAttributeStyleSheet()?styles[0].selectorText:this._createLocationLink(styleSheet));for(let style of styles) resourceSection.append(this._createRuleElement(style));}} _createRuleElement(style) {let ruleElement=document.createElement("div");ruleElement.classList.add("css-rule");let selectorLineElement=ruleElement.appendChild(document.createElement("div"));selectorLineElement.className="selector-line";let selectorElement=selectorLineElement.appendChild(document.createElement("span"));selectorElement.className="selector";if(style.type===WI.CSSStyleDeclaration.Type.Inline){selectorElement.textContent=WI.UIString("Style Attribute");selectorElement.classList.add("style-attribute");}else selectorElement.textContent=style.ownerRule.selectorText;selectorLineElement.append(" {\n");function onEach(cssProperty,action){let className="";if(action===1) className="added";else if(action===-1) className="removed";else className="unchanged";let propertyLineElement=ruleElement.appendChild(document.createElement("div"));propertyLineElement.classList.add("css-property-line",className);const delegate=null;let stylePropertyView=new WI.SpreadsheetStyleProperty(delegate,cssProperty,{readOnly:true,hideDocumentation:true});propertyLineElement.append(WI.indentString(),stylePropertyView.element,"\n");} function comparator(a,b){return a.equals(b);} Array.diffArrays(style.initialState.visibleProperties,style.visibleProperties,onEach,comparator);let closeBraceElement=document.createElement("span");closeBraceElement.className="close-brace";closeBraceElement.textContent="}";ruleElement.append(closeBraceElement,"\n");return ruleElement;} _createLocationLink(styleSheet) {const options={nameStyle:WI.SourceCodeLocation.NameStyle.Short,columnStyle:WI.SourceCodeLocation.ColumnStyle.Hidden,dontFloat:true,ignoreNetworkTab:true,ignoreSearchTab:true,};const lineNumber=0;const columnNumber=0;let sourceCodeLocation=styleSheet.createSourceCodeLocation(lineNumber,columnNumber);return WI.createSourceCodeLocationLink(sourceCodeLocation,options);} _mainResourceDidChange(event) {if(!event.target.isMainFrame()) return;this.needsLayout();}};WI.ChartDetailsSectionRow=class ChartDetailsSectionRow extends WI.DetailsSectionRow {constructor(delegate,chartSize,innerRadiusRatio) {super(WI.UIString("No Chart Available"));innerRadiusRatio=innerRadiusRatio||0;this.element.classList.add("chart");this._titleElement=document.createElement("div");this._titleElement.className="title";this.element.appendChild(this._titleElement);let chartContentElement=document.createElement("div");chartContentElement.className="chart-content";this.element.appendChild(chartContentElement);this._chartElement=createSVGElement("svg");chartContentElement.appendChild(this._chartElement);this._legendElement=document.createElement("div");this._legendElement.className="legend";chartContentElement.appendChild(this._legendElement);this._delegate=delegate;this._items=new Map;this._title="";this._chartSize=chartSize;this._radius=(this._chartSize/2)-1;this._innerRadius=innerRadiusRatio?Math.floor(this._radius*innerRadiusRatio):0;this._total=0;this._svgFiltersElement=document.createElement("svg");this._svgFiltersElement.classList.add("defs-only");this.element.append(this._svgFiltersElement);this._checkboxStyleElement=document.createElement("style");this._checkboxStyleElement.id="checkbox-styles";document.getElementsByTagName("head")[0].append(this._checkboxStyleElement);function createEmptyChartPathData(c,r1,r2) {const a1=0;const a2=Math.PI*1.9999;let x1=c+Math.cos(a1)*r1,y1=c+Math.sin(a1)*r1,x2=c+Math.cos(a2)*r1,y2=c+Math.sin(a2)*r1,x3=c+Math.cos(a2)*r2,y3=c+Math.sin(a2)*r2,x4=c+Math.cos(a1)*r2,y4=c+Math.sin(a1)*r2;return["M",x1,y1,"A",r1,r1,0,1,1,x2,y2,"Z","M",x3,y3,"A",r2,r2,0,1,0,x4,y4,"Z"].join(" ");} this._emptyChartPath=createSVGElement("path");this._emptyChartPath.setAttribute("d",createEmptyChartPathData(this._chartSize/2,this._radius,this._innerRadius));this._emptyChartPath.classList.add("empty-chart");this._chartElement.appendChild(this._emptyChartPath);} get chartSize() {return this._chartSize;} set title(title) {if(this._title===title) return;this._title=title;this._titleElement.textContent=title;} get total() {return this._total;} addItem(id,label,value,color,checkbox,checked) {if(this._items.has(id)) return;if(value<0) return;this._items.set(id,{label,value,color,checkbox,checked});this._total+=value;this._needsLayout();} setItemValue(id,value) {let item=this._items.get(id);if(!item) return;if(value<0) return;if(item.value===value) return;this._total+=value-item.value;item.value=value;this._needsLayout();} clearItems() {for(let item of this._items.values()){let path=item[WI.ChartDetailsSectionRow.ChartSegmentPathSymbol];if(path) path.remove();} this._total=0;this._items.clear();this._needsLayout();} _addCheckboxColorFilter(id,r,g,b) {for(let i=0;i .content > .group > .row.chart > .chart-content > .legend > .legend-item > label > input[type=checkbox]."+id+" { filter: grayscale(1) url(#"+id+") }",0);} _updateLegend() {if(!this._items.size){this._legendElement.removeChildren();return;} function formatItemValue(item) {if(this._delegate&&typeof this._delegate.formatChartValue==="function") return this._delegate.formatChartValue(item.value);return item.value;} for(let[id,item]of this._items){if(item[WI.ChartDetailsSectionRow.LegendItemValueElementSymbol]){let valueElement=item[WI.ChartDetailsSectionRow.LegendItemValueElementSymbol];valueElement.textContent=formatItemValue.call(this,item);continue;} let labelElement=document.createElement("label");let keyElement;if(item.checkbox){let className=id.toLowerCase();let rgb=item.color.substring(4,item.color.length-1).replace(/ /g,"").split(",");if(rgb[0]===rgb[1]&&rgb[1]===rgb[2]) rgb[0]=rgb[1]=rgb[2]=Math.min(160,rgb[0]);keyElement=document.createElement("input");keyElement.type="checkbox";keyElement.classList.add(className);keyElement.checked=item.checked;keyElement[WI.ChartDetailsSectionRow.DataItemIdSymbol]=id;keyElement.addEventListener("change",this._legendItemCheckboxValueChanged.bind(this));this._addCheckboxColorFilter(className,rgb[0],rgb[1],rgb[2]);}else{keyElement=document.createElement("div");keyElement.classList.add("color-key");keyElement.style.backgroundColor=item.color;} labelElement.append(keyElement,item.label);let valueElement=document.createElement("div");valueElement.classList.add("value");valueElement.textContent=formatItemValue.call(this,item);item[WI.ChartDetailsSectionRow.LegendItemValueElementSymbol]=valueElement;let legendItemElement=document.createElement("div");legendItemElement.classList.add("legend-item");legendItemElement.append(labelElement,valueElement);this._legendElement.append(legendItemElement);}} _legendItemCheckboxValueChanged(event) {let checkbox=event.target;let id=checkbox[WI.ChartDetailsSectionRow.DataItemIdSymbol];this.dispatchEventToListeners(WI.ChartDetailsSectionRow.Event.LegendItemChecked,{id,checked:checkbox.checked});} _needsLayout() {if(this._scheduledLayoutUpdateIdentifier) return;this._scheduledLayoutUpdateIdentifier=requestAnimationFrame(this._updateLayout.bind(this));} _updateLayout() {if(this._scheduledLayoutUpdateIdentifier){cancelAnimationFrame(this._scheduledLayoutUpdateIdentifier);this._scheduledLayoutUpdateIdentifier=undefined;} this._updateLegend();this._chartElement.setAttribute("width",this._chartSize);this._chartElement.setAttribute("height",this._chartSize);this._chartElement.setAttribute("viewbox","0 0 "+this._chartSize+" "+this._chartSize);function createSegmentPathData(c,a1,a2,r1,r2) {const largeArcFlag=((a2-a1)%(Math.PI*2))>Math.PI?1:0;let x1=c+Math.cos(a1)*r1,y1=c+Math.sin(a1)*r1,x2=c+Math.cos(a2)*r1,y2=c+Math.sin(a2)*r1,x3=c+Math.cos(a2)*r2,y3=c+Math.sin(a2)*r2,x4=c+Math.cos(a1)*r2,y4=c+Math.sin(a1)*r2;return["M",x1,y1,"A",r1,r1,0,largeArcFlag,1,x2,y2,"L",x3,y3,"A",r2,r2,0,largeArcFlag,0,x4,y4,"Z"].join(" ");} const minimumDisplayValue=this._total*0.015;let items=[];for(let item of this._items.values()){item.displayValue=item.value?Math.max(minimumDisplayValue,item.value):0;if(item.displayValue) items.push(item);} if(items.length>1){items.sort(function(a,b){return a.value-b.value;});let largeItemCount=items.length;let totalAdjustedValue=0;for(let item of items){if(item.value=minimumDisplayValue){item.displayValue-=donatedValue;totalAdjustedValue-=donatedValue;} largeItemCount--;}} const center=this._chartSize/2;let startAngle=-Math.PI/2;let endAngle=0;for(let[id,item]of this._items){let path=item[WI.ChartDetailsSectionRow.ChartSegmentPathSymbol];if(!path){path=createSVGElement("path");path.classList.add("chart-segment");path.setAttribute("fill",item.color);this._chartElement.appendChild(path);item[WI.ChartDetailsSectionRow.ChartSegmentPathSymbol]=path;} if(!item.value){path.classList.add("hidden");continue;} const angle=(item.displayValue/this._total)*Math.PI*2;endAngle=startAngle+angle;path.setAttribute("d",createSegmentPathData(center,startAngle,endAngle,this._radius,this._innerRadius));path.classList.remove("hidden");startAngle=endAngle;}}};WI.ChartDetailsSectionRow.DataItemIdSymbol=Symbol("chart-details-section-row-data-item-id");WI.ChartDetailsSectionRow.ChartSegmentPathSymbol=Symbol("chart-details-section-row-chart-segment-path");WI.ChartDetailsSectionRow.LegendItemValueElementSymbol=Symbol("chart-details-section-row-legend-item-value-element");WI.ChartDetailsSectionRow.Event={LegendItemChecked:"chart-details-section-row-legend-item-checked"};WI.CheckboxNavigationItem=class CheckboxNavigationItem extends WI.NavigationItem {constructor(identifier,label,checked) {super(identifier,"checkbox");this._checkboxElement=this.element.appendChild(document.createElement("input"));this._checkboxElement.checked=checked;this._checkboxElement.id="checkbox-navigation-item-"+identifier;this._checkboxElement.type="checkbox";this._checkboxElement.addEventListener("change",this._checkboxChanged.bind(this));this._checkboxLabel=this.element.appendChild(document.createElement("label"));this._checkboxLabel.className="toggle";this._checkboxLabel.setAttribute("for",this._checkboxElement.id);this._checkboxLabel.addEventListener("click",this._handleLabelClick.bind(this));this.label=label;} get checked() {return this._checkboxElement.checked;} set checked(flag) {this._checkboxElement.checked=flag;} set label(label) {this._checkboxLabel.removeChildren();if(label) this._checkboxLabel.append(label);} get additionalClassNames() {return["checkbox","button"];} _checkboxChanged(event) {this.dispatchEventToListeners(WI.CheckboxNavigationItem.Event.CheckedDidChange);} _handleLabelClick(event) {if(WI.isEventTargetAnEditableField(event)) event.stop();}};WI.CheckboxNavigationItem.Event={CheckedDidChange:"checkbox-navigation-item-checked-did-change",}; WI.CircleChart=class CircleChart extends WI.View {constructor({size,innerRadiusRatio}) {super();this._data=[];this._size=size;this._radius=(size/2)-1;this._innerRadius=innerRadiusRatio?Math.floor(this._radius*innerRadiusRatio):0;this.element.classList.add("circle-chart");this._chartElement=this.element.appendChild(createSVGElement("svg"));this._chartElement.setAttribute("width",size);this._chartElement.setAttribute("height",size);this._chartElement.setAttribute("viewBox",`0 0 ${size} ${size}`);this._pathElements=[];this._values=[];this._total=0;let backgroundPath=this._chartElement.appendChild(createSVGElement("path"));backgroundPath.setAttribute("d",this._createCompleteCirclePathData(this._size/2,this._radius,this._innerRadius));backgroundPath.classList.add("background");} get size(){return this._size;} get centerElement() {if(!this._centerElement){this._centerElement=this.element.appendChild(document.createElement("div"));this._centerElement.classList.add("center");this._centerElement.style.width=this._centerElement.style.height=this._radius+"px";this._centerElement.style.top=this._centerElement.style.left=(this._radius-this._innerRadius)+"px";} return this._centerElement;} get segments() {return this._segments;} set segments(segmentClassNames) {for(let pathElement of this._pathElements) pathElement.remove();this._pathElements=[];for(let className of segmentClassNames){let pathElement=this._chartElement.appendChild(createSVGElement("path"));pathElement.classList.add("segment",className);this._pathElements.push(pathElement);}} get values() {return this._values;} set values(values) {this._values=values;this._total=0;for(let value of values) this._total+=value;} clear() {this.values=new Array(this._values.length).fill(0);} layout() {super.layout();if(this.layoutReason===WI.View.LayoutReason.Resize) return;if(!this._values.length) return;const center=this._size/2;let startAngle=-Math.PI/2;let endAngle=0;for(let i=0;iMath.PI?1:0;let x1=c+Math.cos(a1)*r1,y1=c+Math.sin(a1)*r1,x2=c+Math.cos(a2)*r1,y2=c+Math.sin(a2)*r1,x3=c+Math.cos(a2)*r2,y3=c+Math.sin(a2)*r2,x4=c+Math.cos(a1)*r2,y4=c+Math.sin(a1)*r2;return["M",x1,y1,"A",r1,r1,0,largeArcFlag,1,x2,y2,"L",x3,y3,"A",r2,r2,0,largeArcFlag,0,x4,y4,"Z"].join(" ");}};WI.ClusterContentView=class ClusterContentView extends WI.ContentView {constructor(representedObject) {super(representedObject);this.element.classList.add("cluster");this._contentViewContainer=new WI.ContentViewContainer;this._contentViewContainer.addEventListener(WI.ContentViewContainer.Event.CurrentContentViewDidChange,this._currentContentViewDidChange,this);this.addSubview(this._contentViewContainer);WI.ContentView.addEventListener(WI.ContentView.Event.SelectionPathComponentsDidChange,this._contentViewSelectionPathComponentDidChange,this);WI.ContentView.addEventListener(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange,this._contentViewSupplementalRepresentedObjectsDidChange,this);WI.ContentView.addEventListener(WI.ContentView.Event.NumberOfSearchResultsDidChange,this._contentViewNumberOfSearchResultsDidChange,this);} get navigationItems() {var currentContentView=this._contentViewContainer.currentContentView;return currentContentView?currentContentView.navigationItems:[];} get contentViewContainer() {return this._contentViewContainer;} get supportsSplitContentBrowser() {if(this._contentViewContainer.currentContentView) return this._contentViewContainer.currentContentView.supportsSplitContentBrowser;return super.supportsSplitContentBrowser;} get shouldSaveStateWhenHidden() {return true;} closed() {super.closed();this._contentViewContainer.closeAllContentViews();WI.ContentView.removeEventListener(WI.ContentView.Event.SelectionPathComponentsDidChange,this._contentViewSelectionPathComponentDidChange,this);WI.ContentView.removeEventListener(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange,this._contentViewSupplementalRepresentedObjectsDidChange,this);WI.ContentView.removeEventListener(WI.ContentView.Event.NumberOfSearchResultsDidChange,this._contentViewNumberOfSearchResultsDidChange,this);} canGoBack() {return this._contentViewContainer.canGoBack();} canGoForward() {return this._contentViewContainer.canGoForward();} goBack() {this._contentViewContainer.goBack();} goForward() {this._contentViewContainer.goForward();} get scrollableElements() {if(!this._contentViewContainer.currentContentView) return[];return this._contentViewContainer.currentContentView.scrollableElements;} get selectionPathComponents() {if(!this._contentViewContainer.currentContentView) return[];return this._contentViewContainer.currentContentView.selectionPathComponents;} get supplementalRepresentedObjects() {if(!this._contentViewContainer.currentContentView) return[];return this._contentViewContainer.currentContentView.supplementalRepresentedObjects;} get handleCopyEvent() {var currentContentView=this._contentViewContainer.currentContentView;return currentContentView&&typeof currentContentView.handleCopyEvent==="function"?currentContentView.handleCopyEvent.bind(currentContentView):null;} get supportsSave() {return!!this._contentViewContainer.currentContentView?.supportsSave;} get saveMode() {return this._contentViewContainer.currentContentView?.saveMode;} get saveData() {return this._contentViewContainer.currentContentView?.saveData;} get supportsSearch() {return true;} get numberOfSearchResults() {var currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView||!currentContentView.supportsSearch) return null;return currentContentView.numberOfSearchResults;} get hasPerformedSearch() {var currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView||!currentContentView.supportsSearch) return false;return currentContentView.hasPerformedSearch;} set automaticallyRevealFirstSearchResult(reveal) {var currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView||!currentContentView.supportsSearch) return;currentContentView.automaticallyRevealFirstSearchResult=reveal;} performSearch(query) {this._searchQuery=query;var currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView||!currentContentView.supportsSearch) return;currentContentView.performSearch(query);} searchCleared() {this._searchQuery=null;var currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView||!currentContentView.supportsSearch) return;currentContentView.searchCleared();} searchQueryWithSelection() {var currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView||!currentContentView.supportsSearch) return null;return currentContentView.searchQueryWithSelection();} revealPreviousSearchResult(changeFocus) {var currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView||!currentContentView.supportsSearch) return;currentContentView.revealPreviousSearchResult(changeFocus);} revealNextSearchResult(changeFocus) {var currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView||!currentContentView.supportsSearch) return;currentContentView.revealNextSearchResult(changeFocus);} _currentContentViewDidChange(event) {var currentContentView=this._contentViewContainer.currentContentView;if(currentContentView&¤tContentView.supportsSearch){if(this._searchQuery) currentContentView.performSearch(this._searchQuery);else currentContentView.searchCleared();} this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);this.dispatchEventToListeners(WI.ContentView.Event.NavigationItemsDidChange);} _contentViewSelectionPathComponentDidChange(event) {if(event.target!==this._contentViewContainer.currentContentView) return;this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);} _contentViewSupplementalRepresentedObjectsDidChange(event) {if(event.target!==this._contentViewContainer.currentContentView) return;this.dispatchEventToListeners(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange);} _contentViewNumberOfSearchResultsDidChange(event) {if(event.target!==this._contentViewContainer.currentContentView) return;this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);}};(function(){ function tokenizeLinkString(stream,state) {if(state._linkQuoteCharacter) stream.eatWhile(new RegExp("[^"+state._linkQuoteCharacter+"]"));else stream.eatWhile(/[^\s\u00a0=<>\"\']/);if(!stream.eol()) state._linkTokenize=tokenizeEndOfLinkString;return"link";} function tokenizeEndOfLinkString(stream,state) {if(state._linkQuoteCharacter) stream.eat(state._linkQuoteCharacter);var style=state._linkBaseStyle;delete state._linkTokenize;delete state._linkQuoteCharacter;delete state._linkBaseStyle;delete state._srcSetTokenizeState;return style;} function tokenizeSrcSetString(stream,state) {if(state._srcSetTokenizeState==="link"){if(state._linkQuoteCharacter) stream.eatWhile(new RegExp("[^\\s,"+state._linkQuoteCharacter+"]"));else stream.eatWhile(/[^\s,\u00a0=<>\"\']/);}else{stream.eatSpace();if(state._linkQuoteCharacter) stream.eatWhile(new RegExp("[^,"+state._linkQuoteCharacter+"]"));else stream.eatWhile(/[^\s\u00a0=<>\"\']/);stream.eatWhile(/[\s,]/);} if(stream.eol()||(!state._linkQuoteCharacter||stream.peek()===state._linkQuoteCharacter)) state._linkTokenize=tokenizeEndOfLinkString;if(state._srcSetTokenizeState==="link"){state._srcSetTokenizeState="descriptor";return"link";} state._srcSetTokenizeState="link";return state._linkBaseStyle;} function extendedXMLToken(stream,state) {if(state._linkTokenize){var style=state._linkTokenize(stream,state);return style&&(style+" m-"+this.name);} var startPosition=stream.pos;var style=this._token(stream,state);if(style==="attribute"){ var text=stream.current().toLowerCase();if(text==="src"||/\bhref\b/.test(text)) state._expectLink=true;else if(text==="srcset") state._expectSrcSet=true;else{delete state._expectLink;delete state._expectSrcSet;}}else if(state._expectLink&&style==="string"){var current=stream.current(); if(current!=="\"\""&¤t!=="''"){delete state._expectLink;state._linkTokenize=tokenizeLinkString;state._linkBaseStyle=style;var quote=current[0];state._linkQuoteCharacter=quote==="'"||quote==="\""?quote:null;stream.pos=startPosition; if(state._linkQuoteCharacter) stream.eat(state._linkQuoteCharacter);}}else if(state._expectSrcSet&&style==="string"){var current=stream.current(); if(current!=="\"\""&¤t!=="''"){delete state._expectSrcSet;state._srcSetTokenizeState="link";state._linkTokenize=tokenizeSrcSetString;state._linkBaseStyle=style;var quote=current[0];state._linkQuoteCharacter=quote==="'"||quote==="\""?quote:null;stream.pos=startPosition; if(state._linkQuoteCharacter) stream.eat(state._linkQuoteCharacter);}}else if(style){ delete state._expectLink;delete state._expectSrcSet;} return style&&(style+" m-"+this.name);} function tokenizeCSSURLString(stream,state) {if(state._unquotedURLString&&stream.eatSpace()) return null;var ch=null;var escaped=false;var reachedEndOfURL=false;var lastNonWhitespace=stream.pos;var quote=state._urlQuoteCharacter;while((ch=stream.next())!=null){if(ch===quote&&!escaped){reachedEndOfURL=true;break;} escaped=!escaped&&ch==="\\";if(!/[\s\u00a0]/.test(ch)) lastNonWhitespace=stream.pos;} if(state._unquotedURLString) stream.pos=lastNonWhitespace;if(reachedEndOfURL){if(!state._unquotedURLString) stream.backUp(1);this._urlTokenize=tokenizeEndOfCSSURLString;} return"link";} function tokenizeEndOfCSSURLString(stream,state) {if(!state._unquotedURLString) stream.eat(state._urlQuoteCharacter);var style=state._urlBaseStyle;delete state._urlTokenize;delete state._urlQuoteCharacter;delete state._urlBaseStyle;return style;} function extendedCSSToken(stream,state) {var hexColorRegex=/#(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{3,4})\b/g;if(state._urlTokenize){var style=state._urlTokenize(stream,state);return style&&(style+" m-"+(this.alternateName||this.name));} var startPosition=stream.pos;var style=this._token(stream,state);if(style){if(style==="atom"){if(stream.current()==="url"){state._expectLink=true;}else if(hexColorRegex.test(stream.current())) style=style+" hex-color";}else if(style==="error"){if(state.state==="atBlock"||state.state==="atBlock_parens"){switch(stream.current()){case"prefers-color-scheme":case"light":case"dark":case"prefers-reduced-motion":case"reduce":case"no-preference":case"inverted-colors":case"inverted":case"color-gamut":case"p3":case"rec2020":case"display-mode":case"fullscreen":case"standalone":case"minimal-ui":case"browser":case"video-playable-inline":case"transform-2d":case"transform-3d":style="property";break;}}}else if(state._expectLink){delete state._expectLink;if(style==="string"){state._urlTokenize=tokenizeCSSURLString;state._urlBaseStyle=style;var quote=stream.current()[0];state._urlQuoteCharacter=quote==="'"||quote==="\""?quote:")";state._unquotedURLString=state._urlQuoteCharacter===")";stream.pos=startPosition; if(!state._unquotedURLString) stream.eat(state._urlQuoteCharacter);}}} return style&&(style+" m-"+(this.alternateName||this.name));} function extendedJavaScriptToken(stream,state) {var style=this._token(stream,state);if(style==="number"&&stream.current().endsWith("n")) style+=" bigint";return style&&(style+" m-"+(this.alternateName||this.name));} function scrollCursorIntoView(codeMirror,event) { event.preventDefault();function delayedWork() {if(!codeMirror.getWrapperElement().classList.contains("CodeMirror-focused")) return;var cursorElement=codeMirror.getScrollerElement().getElementsByClassName("CodeMirror-cursor")[0];if(cursorElement) cursorElement.scrollIntoViewIfNeeded(false);} setTimeout(delayedWork,0);} CodeMirror.extendMode("css",{token:extendedCSSToken});CodeMirror.extendMode("xml",{token:extendedXMLToken});CodeMirror.extendMode("javascript",{token:extendedJavaScriptToken});CodeMirror.defineInitHook(function(codeMirror){codeMirror.on("scrollCursorIntoView",scrollCursorIntoView);});let whitespaceStyleElement=null;let whitespaceCountsWithStyling=new Set;CodeMirror.defineOption("showWhitespaceCharacters",false,function(cm,value,old){if(!value||(old&&old!==CodeMirror.Init)){cm.removeOverlay("whitespace");return;} cm.addOverlay({name:"whitespace",token(stream){if(stream.peek()===" "){let count=0;while(stream.peek()===" "){++count;stream.next();} if(!whitespaceCountsWithStyling.has(count)){whitespaceCountsWithStyling.add(count);if(!whitespaceStyleElement) whitespaceStyleElement=document.head.appendChild(document.createElement("style"));const middleDot="\\00B7";let styleText=whitespaceStyleElement.textContent;styleText+=`.show-whitespace-characters .CodeMirror .cm-whitespace-${count}::before {`;styleText+=`content: "${middleDot.repeat(count)}";`;styleText+=`}`;whitespaceStyleElement.textContent=styleText;} return`whitespace whitespace-${count}`;} while(!stream.eol()&&stream.peek()!==" ") stream.next();return null;}});});CodeMirror.defineExtension("hasLineClass",function(line,where,className){var classProperty=where==="text"?"textClass":(where==="background"?"bgClass":"wrapClass");var lineInfo=this.lineInfo(line);if(!lineInfo) return false;if(!lineInfo[classProperty]) return false;if(lineInfo[classProperty]===className) return true;var index=lineInfo[classProperty].indexOf(className);if(index===-1) return false;var paddedClass=" "+lineInfo[classProperty]+" ";return paddedClass.indexOf(" "+className+" ",index)!==-1;});CodeMirror.defineExtension("setUniqueBookmark",function(position,options){var marks=this.findMarksAt(position);for(var i=0;i=0;--i){var character=line.charAt(i);if(character==="."){if(foundPeriod) break;foundPeriod=true;}else if(character!=="-"&&character!=="+"&&isNaN(parseInt(character))){if(i===startPosition.ch){end=i;continue;} break;} start=i;} if(isNaN(end)){for(var i=startPosition.ch+1;ifrom.ch) selectionStart.ch+=diff;if(selectionEnd.ch>from.ch) selectionEnd.ch+=diff;} this.setSelection(selectionStart,selectionEnd);} return true;});function alterNumber(amount,codeMirror) {function findNumberToken(position) { var token=codeMirror.getTokenAt(position);if(token&&token.type&&/\bnumber\b/.test(token.type)) return token;return null;} var position=codeMirror.getCursor("head");var token=findNumberToken(position);if(!token){ position.ch+=1;token=findNumberToken(position);} if(!token) return CodeMirror.Pass;var foundNumber=codeMirror.alterNumberInRange(amount,{ch:token.start,line:position.line},{ch:token.end,line:position.line},true);if(!foundNumber) return CodeMirror.Pass;} CodeMirror.defineExtension("rectsForRange",function(range){var lineRects=[];for(var line=range.start.line;line<=range.end.line;++line){var lineContent=this.getLine(line);var startChar=line===range.start.line?range.start.ch:(lineContent.length-lineContent.trimLeft().length);var endChar=line===range.end.line?range.end.ch:lineContent.length;var firstCharCoords=this.cursorCoords({ch:startChar,line});var endCharCoords=this.cursorCoords({ch:endChar,line});if(firstCharCoords.bottom!==endCharCoords.bottom){var maxY=-Number.MAX_VALUE;for(var ch=startChar;ch<=endChar;++ch){var coords=this.cursorCoords({ch,line});if(coords.bottom>maxY){if(ch>startChar){var maxX=Math.ceil(this.cursorCoords({ch:ch-1,line}).right);lineRects.push(new WI.Rect(minX,minY,maxX-minX,maxY-minY));} var minX=Math.floor(coords.left);var minY=Math.floor(coords.top);maxY=Math.ceil(coords.bottom);}} maxX=Math.ceil(coords.right);lineRects.push(new WI.Rect(minX,minY,maxX-minX,maxY-minY));}else{var minX=Math.floor(firstCharCoords.left);var minY=Math.floor(firstCharCoords.top);var maxX=Math.ceil(endCharCoords.right);var maxY=Math.ceil(endCharCoords.bottom);lineRects.push(new WI.Rect(minX,minY,maxX-minX,maxY-minY));}} return lineRects;});let mac=WI.Platform.name==="mac";CodeMirror.keyMap["default"]={"Alt-Up":alterNumber.bind(null,1),"Ctrl-Alt-Up":alterNumber.bind(null,0.1),"Shift-Alt-Up":alterNumber.bind(null,10),"Alt-PageUp":alterNumber.bind(null,10),"Shift-Alt-PageUp":alterNumber.bind(null,100),"Alt-Down":alterNumber.bind(null,-1),"Ctrl-Alt-Down":alterNumber.bind(null,-0.1),"Shift-Alt-Down":alterNumber.bind(null,-10),"Alt-PageDown":alterNumber.bind(null,-10),"Shift-Alt-PageDown":alterNumber.bind(null,-100),"Cmd-/":"toggleComment","Cmd-D":"selectNextOccurrence","Shift-Tab":"indentLess",fallthrough:mac?"macDefault":"pcDefault"};{let original=CodeMirror.commands.insertTab;CodeMirror.commands.insertTab=function(cm){if(cm.options.indentWithTabs) original(cm);else CodeMirror.commands.insertSoftTab(cm);};} var extraXMLTypes=["text/xml","text/xsl"];extraXMLTypes.forEach(function(type){CodeMirror.defineMIME(type,"xml");});var extraHTMLTypes=["application/xhtml+xml","image/svg+xml"];extraHTMLTypes.forEach(function(type){CodeMirror.defineMIME(type,"htmlmixed");});var extraJavaScriptTypes=["text/ecmascript","application/javascript","application/ecmascript","application/x-javascript","text/x-javascript","text/javascript1.1","text/javascript1.2","text/javascript1.3","text/jscript","text/livescript"];extraJavaScriptTypes.forEach(function(type){CodeMirror.defineMIME(type,"javascript");});var extraJSONTypes=["application/x-json","text/x-json","application/vnd.api+json"];extraJSONTypes.forEach(function(type){CodeMirror.defineMIME(type,{name:"javascript",json:true});});CodeMirror.defineMIME("x-pipeline/x-compute",CodeMirror.resolveMode("x-shader/x-vertex"));CodeMirror.defineMIME("x-pipeline/x-render",CodeMirror.resolveMode("x-shader/x-vertex"));})();WI.compareCodeMirrorPositions=function(a,b) {var lineCompare=a.line-b.line;if(lineCompare!==0) return lineCompare;var aColumn="ch"in a?a.ch:Number.MAX_VALUE;var bColumn="ch"in b?b.ch:Number.MAX_VALUE;return aColumn-bColumn;};WI.walkTokens=function(cm,mode,initialPosition,callback) {let state=CodeMirror.copyState(mode,cm.getTokenAt(initialPosition).state);if(state.localState) state=state.localState;let lineCount=cm.lineCount();let abort=false;for(let lineNumber=initialPosition.line;!abort&&lineNumber{codeMirror.scrollIntoView({line:0,ch:0});},"End":()=>{codeMirror.scrollIntoView({line:codeMirror.lineCount()-1,ch:null});},});} new WI.CodeMirrorTextKillController(codeMirror);return codeMirror;}};CodeMirror.defineMode("local-override-url",function(){function tokenBase(stream,state){if(state.parsedURL&&stream.sol()){stream.skipToEnd();return null;} let url=stream.string;if(!state.parsedURL){try{state.parsedURL=new URL(url);let indexOfFragment=-1;if(state.parsedURL.hash) indexOfFragment=url.lastIndexOf(state.parsedURL.hash);else if(url.endsWith("#")) indexOfFragment=url.length-1;state.indexOfFragment=indexOfFragment;}catch{stream.skipToEnd();return null;}} if(stream.posmaximum) return"error";return"regex-quantifier";} if(ch==="["){state.tokenize=characterSetTokenizer;return state.pushContext(stream,"regex-character-set");} if(/[.^$|]/.test(ch)) return"regex-special";return null;} return{startState:function(){let contextStack=[];return{currentContext:function(){return contextStack.length?contextStack[contextStack.length-1]:null;},pushContext:function(stream,data,type){let context={data,type};contextStack.push(context);return data;},popContext:function(){return contextStack.pop().data;},tokenize:tokenBase,};},token:function(stream,state){return state.tokenize(stream,state);}};});CodeMirror.defineMIME("text/x-regex","regex");function createCodeMirrorTextMarkers({codeMirror,range,type,pattern,matchFunction,allowedTokens,callback}) {var createdMarkers=[];var start=range instanceof WI.TextRange?range.startLine:0;var end=range instanceof WI.TextRange?range.endLine+1:codeMirror.lineCount();for(var lineNumber=start;lineNumber0) break;--index;if(index<0) break;} if(/(repeating-)?(linear|radial|conic)-gradient$/.test(lineContent.substring(0,index))) return false;return!(match.index>0&&/[-.\"\']/.test(lineContent[match.index-1]));} return createCodeMirrorTextMarkers({codeMirror,range,type:"Color",pattern,matchFunction,...options});} function createCodeMirrorGradientTextMarkers(codeMirror,range,options={}) {var createdMarkers=[];var start=range instanceof WI.TextRange?range.startLine:0;var end=range instanceof WI.TextRange?range.endLine+1:codeMirror.lineCount();var gradientRegex=/(repeating-)?(linear|radial|conic)-gradient\s*\(\s*/g;for(var lineNumber=start;lineNumber=lineContent.length){lineNumber++;endChar=0;lineContent=codeMirror.getLine(lineNumber);if(!lineContent) break;}} if(openParentheses!==-1){match=gradientRegex.exec(lineContent);continue;} var from={line:startLine,ch:startChar};var to={line:lineNumber,ch:endChar};var gradientString=codeMirror.getRange(from,to);var gradient=WI.Gradient.fromString(gradientString);if(!gradient){match=gradientRegex.exec(lineContent);continue;} var marker=new WI.TextMarker(codeMirror.markText(from,to),WI.TextMarker.Type.Gradient);createdMarkers.push(marker);if(typeof callback==="function") options.callback(marker,gradient,gradientString);match=gradientRegex.exec(lineContent);}} return createdMarkers;} function createCodeMirrorCubicBezierTimingFunctionTextMarkers(codeMirror,range,options={}) {const pattern=/(cubic-bezier\([^)]+\)|\b\w+\b(?:-\b\w+\b){0,2})/g;return createCodeMirrorTextMarkers({codeMirror,range,type:"CubicBezierTimingFunction",pattern,...options});} function createCodeMirrorLinearTimingFunctionTextMarkers(codeMirror,range,options={}) {const pattern=/(linear\([^)]+\))/g;return createCodeMirrorTextMarkers({codeMirror,range,type:"LinearTimingFunction",pattern,...options});} function createCodeMirrorSpringTimingFunctionTextMarkers(codeMirror,range,options={}) {const pattern=/(spring\([^)]+\))/g;return createCodeMirrorTextMarkers({codeMirror,range,type:"SpringTimingFunction",pattern,...options});} function createCodeMirrorStepsTimingFunctionTextMarkers(codeMirror,range,options={}) {const pattern=/(steps\([^)]+\))/g;return createCodeMirrorTextMarkers({codeMirror,range,type:"StepsTimingFunction",pattern,...options});} WI.ColorPicker=class ColorPicker extends WI.Object {constructor({preventChangingColorFormats,colorVariables}={}) {super();this._preventChangingColorFormats=!!preventChangingColorFormats;this._colorSquare=new WI.ColorSquare(this,200);this._hueSlider=new WI.Slider;this._hueSlider.delegate=this;this._hueSlider.element.classList.add("hue");this._opacitySlider=new WI.Slider;this._opacitySlider.delegate=this;this._opacitySlider.element.classList.add("opacity");this._colorInputs=[];this._colorInputsFormat=null;this._colorInputsHasAlpha=null;this._colorInputsContainerElement=document.createElement("div");this._colorInputsContainerElement.classList.add("color-inputs");this._colorInputsContainerElement.addEventListener("input",this._handleColorInputsContainerInput.bind(this));this._element=document.createElement("div");this._element.classList.add("color-picker");let wrapper=this._element.appendChild(document.createElement("div"));wrapper.className="wrapper";wrapper.appendChild(this._colorSquare.element);wrapper.appendChild(this._hueSlider.element);wrapper.appendChild(this._opacitySlider.element);let colorInputsWrapperElement=this._element.appendChild(document.createElement("div"));colorInputsWrapperElement.classList.add("color-inputs-wrapper");colorInputsWrapperElement.appendChild(this._colorInputsContainerElement);if(InspectorFrontendHost.canPickColorFromScreen()){let pickColorElement=WI.ImageUtilities.useSVGSymbol("Images/Pipette.svg","pick-color-from-screen",WI.UIString("Pick color from screen","Color picker view tooltip for picking a color from the screen."));pickColorElement.role="button";pickColorElement.addEventListener("click",async(event)=>{pickColorElement.classList.add("active");let pickedColor=await WI.ColorPicker.pickColorFromScreen({suggestedFormat:this.color.format,suggestedGamut:this.color.gamut,forceSuggestedFormatAndGamut:this._preventChangingColorFormats,});pickColorElement.classList.remove("active");if(!pickedColor) return;this.color=pickedColor;this.dispatchEventToListeners(WI.ColorPicker.Event.ColorChanged,{color:this._color});});colorInputsWrapperElement.appendChild(pickColorElement);} this._opacity=0;this._opacityPattern="url(Images/Checkers.svg)";this.color=WI.Color.fromString("white");if(colorVariables?.length){let variableColorSwatchesContainer=this._element.appendChild(document.createElement("div"));variableColorSwatchesContainer.classList.add("variable-color-swatches");let swatchesTitle=variableColorSwatchesContainer.appendChild(document.createElement("h2"));swatchesTitle.textContent=WI.UIString("Variables","Variables @ Color Picker","Title of swatches section in Color Picker");let variableColorSwatchesListElement=variableColorSwatchesContainer.appendChild(document.createElement("ul"));let sortedColorVariables=WI.ColorPicker.sortColorVariables(colorVariables);for(let variable of sortedColorVariables){let computedColor=WI.Color.fromString(variable.value) let swatch=new WI.InlineSwatch(WI.InlineSwatch.Type.Color,computedColor,{readOnly:true,tooltip:variable.name});swatch.element.addEventListener("click",(event)=>{this._updateColorForVariable(computedColor,variable.name);});variableColorSwatchesListElement.appendChild(document.createElement("li")).appendChild(swatch.element);}} this._dontUpdateColor=false;} static async pickColorFromScreen({suggestedFormat,suggestedGamut,forceSuggestedFormatAndGamut}={}) { document.body.inert=true;let pickedColorCSSString=null;try{pickedColorCSSString=await InspectorFrontendHost.pickColorFromScreen();}catch(error){WI.reportInternalError(error);} document.body.inert=false;if(!pickedColorCSSString) return null;return WI.Color.fromStringBestMatchingSuggestedFormatAndGamut(pickedColorCSSString,{suggestedFormat,suggestedGamut,forceSuggestedFormatAndGamut});} static sortColorVariables(colorVariables) {const rotation=2;const weights=[Math.E/11.279,Math.E/3.934,Math.E/39.975];function visualAppeal(variable){let color=WI.Color.fromString(variable.value);let[h,s,l]=color.hsl;let luminosity=Math.floor(color.rgb.reduce((total,component,i)=>total+component*weights[i]));let[modifiedH,modifiedLuminosity,modifiedLight]=[h,luminosity,l].map((component)=>Math.floor(component*rotation));if(modifiedH%2===1){modifiedLight=rotation-modifiedLight;luminosity=rotation-luminosity;} return{lightScore:modifiedLight,luminosityScore:luminosity,hueScore:modifiedH};} let colorVariableVisualAppealScores=new Map(colorVariables.map((variable)=>[variable,visualAppeal(variable)]));return colorVariables.sort((variableA,variableB)=>{let appealA=colorVariableVisualAppealScores.get(variableA);let appealB=colorVariableVisualAppealScores.get(variableB);return appealB.hueScore-appealA.hueScore||appealB.luminosityScore-appealA.luminosityScore||appealB.lightScore-appealA.lightScore;});} get element(){return this._element;} get colorSquare(){return this._colorSquare;} set opacity(opacity) {if(opacity===this._opacity) return;this._opacity=opacity;this._updateColor();} get color() {return this._color;} set color(color) {this._dontUpdateColor=true;this._color=color;this._colorSquare.tintedColor=this._color;this._hueSlider.value=this._color.hsl[0]/360;this._opacitySlider.value=this._color.alpha;this._updateOpacitySlider();this._showColorComponentInputs();this._updateColorGamut();this._dontUpdateColor=false;} focus() {this._colorSquare.element.focus();} colorSquareColorDidChange(colorSquare) {this._updateColor();this._updateOpacitySlider();} sliderValueDidChange(slider,value) {if(slider===this._opacitySlider) this.opacity=value;else if(slider===this._hueSlider){this._colorSquare.hue=value*360;this._updateColor();this._updateOpacitySlider();}} _updateColor() {if(this._dontUpdateColor) return;let opacity=Math.round(this._opacity*100)/100;let format=this._color.format;let gamut=this._color.gamut;let components=null;if(format===WI.Color.Format.HSL||format===WI.Color.Format.HSLA){components=this._colorSquare.tintedColor.hsl.concat(opacity);if(opacity!==1) format=WI.Color.Format.HSLA;}else if(format===WI.Color.Format.ColorFunction) components=this._colorSquare.tintedColor.normalizedRGB.concat(opacity);else{components=this._colorSquare.tintedColor.rgb.concat(opacity);if(opacity!==1&&format===WI.Color.Format.RGB) format=WI.Color.Format.RGBA;} this._color=new WI.Color(format,components,gamut);this._showColorComponentInputs();this.dispatchEventToListeners(WI.ColorPicker.Event.ColorChanged,{color:this._color});this._updateColorGamut();} _updateOpacitySlider() {let color=this._colorSquare.tintedColor;let rgb=color.format===WI.Color.Format.ColorFunction?color.normalizedRGB:color.rgb;let gamut=color.gamut;let format=gamut===WI.Color.Gamut.DisplayP3?WI.Color.Format.ColorFunction:WI.Color.Format.RGBA;let opaque=new WI.Color(format,rgb.concat(1),gamut).toString();let transparent=new WI.Color(format,rgb.concat(0),gamut).toString();this._opacitySlider.element.style.setProperty("background-image","linear-gradient(0deg, "+transparent+", "+opaque+"), "+this._opacityPattern);} _updateColorGamut() {this._element.classList.toggle("gamut-p3",this._color.gamut===WI.Color.Gamut.DisplayP3);} _createColorInputsIfNeeded() {let hasAlpha=this._color.alpha!==1;if((this._color.format===this._colorInputsFormat)&&(hasAlpha===this._colorInputsHasAlpha)) return;this._colorInputsFormat=this._color.format;this._colorInputsHasAlpha=hasAlpha;this._colorInputs=[];this._colorInputsContainerElement.removeChildren();let createColorInput=(label,{max,step,units}={})=>{let containerElement=this._colorInputsContainerElement.createChild("div");containerElement.append(label);let numberInputElement=containerElement.createChild("input");numberInputElement.type="number";numberInputElement.min=0;numberInputElement.max=max;numberInputElement.step=step||1;this._colorInputs.push(numberInputElement);if(units&&units.length) containerElement.append(units);};switch(this._color.format){case WI.Color.Format.RGB:case WI.Color.Format.RGBA:case WI.Color.Format.HEX:case WI.Color.Format.ShortHEX:case WI.Color.Format.HEXAlpha:case WI.Color.Format.ShortHEXAlpha:case WI.Color.Format.Keyword:createColorInput("R",{max:255});createColorInput("G",{max:255});createColorInput("B",{max:255});break;case WI.Color.Format.HSL:case WI.Color.Format.HSLA:createColorInput("H",{max:360});createColorInput("S",{max:100,units:"%"});createColorInput("L",{max:100,units:"%"});break;case WI.Color.Format.ColorFunction:createColorInput("R",{max:1,step:0.01});createColorInput("G",{max:1,step:0.01});createColorInput("B",{max:1,step:0.01});break;default:console.error(`Unknown color format: ${this._color.format}`);return;} if(this._color.alpha!==1||this._color.format===WI.Color.Format.RGBA||this._color.format===WI.Color.Format.HSLA||this._color.format===WI.Color.Format.HEXAlpha||this._color.format===WI.Color.Format.ShortHEXAlpha){createColorInput("A",{max:1,step:0.01});}} _showColorComponentInputs() {this._createColorInputsIfNeeded();let components=[];switch(this._color.format){case WI.Color.Format.RGB:case WI.Color.Format.RGBA:case WI.Color.Format.HEX:case WI.Color.Format.ShortHEX:case WI.Color.Format.HEXAlpha:case WI.Color.Format.ShortHEXAlpha:case WI.Color.Format.Keyword:components=this._color.rgb.map((value)=>Math.round(value));break;case WI.Color.Format.HSL:case WI.Color.Format.HSLA:components=this._color.hsl.map((value)=>value.maxDecimals(2));break;case WI.Color.Format.ColorFunction:components=this._color.normalizedRGB.map((value)=>value.maxDecimals(4));break;default:console.error(`Unknown color format: ${this._color.format}`);} if(this._color.alpha!==1) components.push(this._color.alpha);for(let i=0;i{return isNaN(input.valueAsNumber)?0:input.valueAsNumber;});this.color=new WI.Color(this._color.format,components,this._color.gamut);this.dispatchEventToListeners(WI.ColorPicker.Event.ColorChanged,{color:this._color});} _updateColorForVariable(resolvedColor,variableName) {this.color=resolvedColor;this.dispatchEventToListeners(WI.ColorPicker.Event.ColorChanged,{color:this._color,variableName});}};WI.ColorPicker.Event={ColorChanged:"css-color-picker-color-changed",};WI.ColorSquare=class ColorSquare {constructor(delegate,dimension) {this._delegate=delegate;this._hue=0;this._x=0;this._y=0;this._gamut=null;this._crosshairPosition=null;this._element=document.createElement("div");this._element.className="color-square";this._element.tabIndex=0;let saturationGradientElement=this._element.appendChild(document.createElement("div"));saturationGradientElement.className="saturation-gradient fill";let lightnessGradientElement=this._element.appendChild(document.createElement("div"));lightnessGradientElement.className="lightness-gradient fill";this._srgbLabelElement=null;this._svgElement=null;this._polylineElement=null;this._element.addEventListener("mousedown",this);this._element.addEventListener("keydown",this._handleKeyDown.bind(this));this._crosshairElement=this._element.appendChild(document.createElement("div"));this._crosshairElement.className="crosshair";this.dimension=dimension;} get element(){return this._element;} set dimension(dimension) {if(dimension===this._dimension) return;this._dimension=dimension;this._element.style.width=this.element.style.height=`${this._dimension}px`;this._updateBaseColor();} get hue() {return this._hue;} set hue(hue) {this._hue=hue;this._updateBaseColor();} get tintedColor() {if(this._crosshairPosition){if(this._gamut===WI.Color.Gamut.DisplayP3){let rgb=WI.Color.hsv2rgb(this._hue,this._saturation,this._brightness);rgb=rgb.map(((x)=>Math.roundTo(x,0.001)));return new WI.Color(WI.Color.Format.ColorFunction,rgb,this._gamut);} let hsl=WI.Color.hsv2hsl(this._hue,this._saturation,this._brightness);return new WI.Color(WI.Color.Format.HSL,hsl);} return new WI.Color(WI.Color.Format.HSLA,[0,0,0,0]);} set tintedColor(tintedColor) {this._gamut=tintedColor.gamut;let[hue,saturation,value]=WI.Color.rgb2hsv(...tintedColor.normalizedRGB);let x=saturation/100*this._dimension;let y=(1-(value/100))*this._dimension;if(this._gamut===WI.Color.Gamut.DisplayP3) this._drawSRGBOutline();this._setCrosshairPosition(new WI.Point(x,y));this._updateBaseColor();} handleEvent(event) {switch(event.type){case"mousedown":this._handleMousedown(event);break;case"mousemove":this._handleMousemove(event);break;case"mouseup":this._handleMouseup(event);break;}} get _saturation() {let saturation=this._x/this._dimension;return Number.constrain(saturation,0,1)*100;} get _brightness() {let brightness=1-(this._y/this._dimension);return Number.constrain(brightness,0,1)*100;} _handleMousedown(event) {if(event.button!==0||event.ctrlKey) return;window.addEventListener("mousemove",this,true);window.addEventListener("mouseup",this,true);this._updateColorForMouseEvent(event);event.stop();this._element.focus();} _handleMousemove(event) {this._updateColorForMouseEvent(event);} _handleMouseup(event) {window.removeEventListener("mousemove",this,true);window.removeEventListener("mouseup",this,true);} _handleKeyDown(event) {let dx=0;let dy=0;let step=event.shiftKey?10:1;switch(event.keyIdentifier){case"Right":dx+=step;break;case"Left":dx-=step;break;case"Down":dy+=step;break;case"Up":dy-=step;break;} if(dx||dy){event.preventDefault();this._setCrosshairPosition(new WI.Point(this._x+dx,this._y+dy));if(this._delegate&&this._delegate.colorSquareColorDidChange) this._delegate.colorSquareColorDidChange(this);}} _updateColorForMouseEvent(event) {let rect=this._element.getBoundingClientRect();this._setCrosshairPosition({x:event.pageX-rect.x,y:event.pageY-rect.y,});if(this._delegate&&this._delegate.colorSquareColorDidChange) this._delegate.colorSquareColorDidChange(this);} _setCrosshairPosition(point) {this._crosshairPosition=point;this._x=Number.constrain(Math.round(point.x),0,this._dimension);this._y=Number.constrain(Math.round(point.y),0,this._dimension);this._crosshairElement.style.setProperty("transform",`translate(${this._x}px, ${this._y}px)`);this._updateCrosshairBackground();} _updateBaseColor() {if(this._gamut===WI.Color.Gamut.DisplayP3){let[r,g,b]=WI.Color.hsl2rgb(this._hue,100,50);this._element.style.backgroundColor=`color(display-p3 ${r / 255} ${g / 255} ${b / 255})`;}else this._element.style.backgroundColor=`hsl(${this._hue}, 100%, 50%)`;this._updateCrosshairBackground();if(this._gamut===WI.Color.Gamut.DisplayP3) this._drawSRGBOutline();} _updateCrosshairBackground() {this._crosshairElement.style.backgroundColor=this.tintedColor.toString();} _drawSRGBOutline() {if(!this._svgElement){this._srgbLabelElement=this._element.appendChild(document.createElement("span"));this._srgbLabelElement.className="srgb-label";this._srgbLabelElement.textContent=WI.unlocalizedString("sRGB");this._srgbLabelElement.title=WI.UIString("Edge of sRGB color space","Label for a guide within the color picker");const svgNamespace="http://www.w3.org/2000/svg";this._svgElement=this._element.appendChild(document.createElementNS(svgNamespace,"svg"));this._svgElement.classList.add("svg-root");this._polylineElement=this._svgElement.appendChild(document.createElementNS(svgNamespace,"polyline"));this._polylineElement.classList.add("srgb-edge");} let points=[];let step=1/window.devicePixelRatio;let x=0;for(let y=0;yvalue<0||value>1)){points.push({x,y});break;}}} if(points.lastValue.y{let clientRect=element.getBoundingClientRect();if(clientRect.x!==initialClientRect.x||clientRect.y!==initialClientRect.y) this.hide();},200);} update(completions,selectedIndex) {this._containerElement.removeChildren();this._completions=completions;if(typeof selectedIndex==="number") this._selectedIndex=selectedIndex;for(let[index,completion]of completions.entries()){var itemElement=document.createElement("div");itemElement.classList.add("item");itemElement.classList.toggle("selected",index===this._selectedIndex);if(typeof completion==="string") itemElement.textContent=completion;else if(completion instanceof WI.QueryResult) itemElement.appendChild(this._createMatchedCompletionFragment(completion.value,completion.matchingTextRanges));this._containerElement.appendChild(itemElement);this._delegate?.completionSuggestionsViewCustomizeCompletionElement?.(this,itemElement,completion);}} get _selectedItemElement() {if(isNaN(this._selectedIndex)) return null;var element=this._containerElement.children[this._selectedIndex]||null;return element;} _createMatchedCompletionFragment(completionText,matchingTextRanges) {let completionFragment=document.createDocumentFragment();let lastIndex=0;for(let textRange of matchingTextRanges){if(textRange.startColumn>lastIndex) completionFragment.append(completionText.substring(lastIndex,textRange.startColumn));let matchedSpan=document.createElement("span");matchedSpan.classList.add("matched");matchedSpan.append(completionText.substring(textRange.startColumn,textRange.endColumn));completionFragment.append(matchedSpan);lastIndex=textRange.endColumn;} if(lastIndex{contextMenu.appendCheckboxItem(WI.UIString("Show All"),()=>{this._computedStyleShowAllSetting.value=!this._computedStyleShowAllSetting.value;propertyFiltersElement.classList.toggle("active",this._computedStyleShowAllSetting.value||this._computedStylePreferShorthandsSetting.value);},this._computedStyleShowAllSetting.value);contextMenu.appendCheckboxItem(WI.UIString("Prefer Shorthands"),()=>{this._computedStylePreferShorthandsSetting.value=!this._computedStylePreferShorthandsSetting.value;propertyFiltersElement.classList.toggle("active",this._computedStyleShowAllSetting.value||this._computedStylePreferShorthandsSetting.value);},this._computedStylePreferShorthandsSetting.value);});this._computedStyleSection=new WI.ComputedStyleSection(this);this._computedStyleSection.addEventListener(WI.ComputedStyleSection.Event.FilterApplied,this._handleEditorFilterApplied,this);this._computedStyleSection.showsImplicitProperties=this._computedStyleShowAllSetting.value;this._computedStyleSection.propertyVisibilityMode=WI.ComputedStyleSection.PropertyVisibilityMode.HideVariables;this._computedStyleSection.showsShorthandsInsteadOfLonghands=this._computedStylePreferShorthandsSetting.value;this._computedStyleSection.alwaysShowPropertyNames=["display","width","height"];this._computedStyleSection.hideFilterNonMatchingProperties=true;let propertiesRow=new WI.DetailsSectionRow;let propertiesGroup=new WI.DetailsSectionGroup([propertiesRow]);this._propertiesSection=new WI.DetailsSection("computed-style-properties",WI.UIString("Properties"),[propertiesGroup],propertyFiltersElement);this._propertiesSection.addEventListener(WI.DetailsSection.Event.CollapsedStateChanged,this._handleDetailsSectionCollapsedStateChanged,this);this.addSubview(this._computedStyleSection);propertiesRow.element.appendChild(this._computedStyleSection.element);this._detailsSectionByStyleSectionMap.set(this._computedStyleSection,this._propertiesSection);let variablesGroupingModeScopeBarItems=[new WI.ScopeBarItem(WI.ComputedStyleDetailsPanel.VariablesGroupingMode.Ungrouped,WI.UIString("Ungrouped","Ungrouped @ Computed Style variables grouping mode","Label for button to show CSS variables ungrouped")),new WI.ScopeBarItem(WI.ComputedStyleDetailsPanel.VariablesGroupingMode.ByType,WI.UIString("By Type","By Type @ Computed Style variables grouping mode","Label for button to show CSS variables grouped by type"))];const shouldGroupNonExclusiveItems=true;this._variablesGroupingModeScopeBar=new WI.ScopeBar("computed-style-variables-grouping-mode",variablesGroupingModeScopeBarItems,variablesGroupingModeScopeBarItems[0],shouldGroupNonExclusiveItems);this._variablesGroupingModeScopeBar.addEventListener(WI.ScopeBar.Event.SelectionChanged,this._handleVariablesGroupingModeScopeBarSelectionChanged,this);this._variablesRow=new WI.DetailsSectionRow;let variablesGroup=new WI.DetailsSectionGroup([this._variablesRow]);this._variablesSection=new WI.DetailsSection("computed-style-variables",WI.UIString("Variables"),[variablesGroup],this._variablesGroupingModeScopeBar.element);this._variablesSection.addEventListener(WI.DetailsSection.Event.CollapsedStateChanged,this._handleDetailsSectionCollapsedStateChanged,this);this.element.appendChild(this._propertiesSection.element);this.element.appendChild(this._variablesSection.element);this._computedStyleShowAllSetting.addEventListener(WI.Setting.Event.Changed,this._handleShowAllSettingChanged,this);this._computedStylePreferShorthandsSetting.addEventListener(WI.Setting.Event.Changed,this._handleUseShorthandsSettingChanged,this);} layout() {super.layout();for(let[styleSection,detailsSection]of this._detailsSectionByStyleSectionMap){if(styleSection===this._computedStyleSection) continue;this._removeVariablesStyleSection(styleSection);} if(!this.nodeStyles.computedStyle) return;switch(this.variablesGroupingMode){case WI.ComputedStyleDetailsPanel.VariablesGroupingMode.Ungrouped:this._createVariablesStyleSection(WI.CSSStyleDeclaration.VariablesGroupType.Ungrouped);break;case WI.ComputedStyleDetailsPanel.VariablesGroupingMode.ByType:for(let type of Object.values(WI.CSSStyleDeclaration.VariablesGroupType)){if(type===WI.CSSStyleDeclaration.VariablesGroupType.Ungrouped) continue;this._createVariablesStyleSection(type,WI.ComputedStyleDetailsPanel.displayNameForVariablesGroupType(type));} break;} if(this._filterText) this.applyFilter(this._filterText);} didLayoutSubtree() {super.didLayoutSubtree();for(let[styleSection,detailsSection]of this._detailsSectionByStyleSectionMap) detailsSection.element.classList.toggle("hidden",styleSection.isEmpty);let areVariableSectionsAllEmpty=Array.from(this._variablesStyleSectionForGroupTypeMap.values()).every((styleSection)=>styleSection.isEmpty);this._variablesSection.element.classList.toggle("hidden",areVariableSectionsAllEmpty);} filterDidChange(filterBar) {this.applyFilter(filterBar.filters.text);} _createVariablesStyleSection(variablesGroupType,label) {let variablesStyleSection=new WI.ComputedStyleSection(this,{variablesGroupType});variablesStyleSection.propertyVisibilityMode=WI.ComputedStyleSection.PropertyVisibilityMode.HideNonVariables;variablesStyleSection.hideFilterNonMatchingProperties=true;variablesStyleSection.addEventListener(WI.ComputedStyleSection.Event.FilterApplied,this._handleEditorFilterApplied,this);variablesStyleSection.element.dir="ltr";variablesStyleSection.style=this.nodeStyles.computedStyle;this.addSubview(variablesStyleSection);let detailsSectionRow=new WI.DetailsSectionRow;let detailsSectionGroup=new WI.DetailsSectionGroup([detailsSectionRow]);let detailsSection=new WI.DetailsSection(`computed-style-variables-group-${variablesGroupType}`,label,[detailsSectionGroup]);detailsSection.addEventListener(WI.DetailsSection.Event.CollapsedStateChanged,this._handleDetailsSectionCollapsedStateChanged,this);detailsSectionRow.element.appendChild(variablesStyleSection.element);this._variablesRow.element.appendChild(detailsSection.element);this._detailsSectionByStyleSectionMap.set(variablesStyleSection,detailsSection);this._variablesStyleSectionForGroupTypeMap.set(variablesGroupType,variablesStyleSection);} _removeVariablesStyleSection(styleSection) {let detailsSection=this._detailsSectionByStyleSectionMap.take(styleSection);let variablesStyleSection=this._variablesStyleSectionForGroupTypeMap.take(styleSection.variablesGroupType);this.removeSubview(styleSection);styleSection.removeEventListener(WI.ComputedStyleSection.Event.FilterApplied,this._handleEditorFilterApplied,this);detailsSection.element.remove();detailsSection.removeEventListener(WI.DetailsSection.Event.CollapsedStateChanged,this._handleDetailsSectionCollapsedStateChanged,this);} _computePropertyTraces(orderedDeclarations) {let result=new Map();for(let rule of orderedDeclarations){for(let property of rule.properties){let properties=result.get(property.name);if(!properties){properties=[];result.set(property.name,properties);} properties.push(property);}} return result;} _handleEditorFilterApplied(event) {let section=this._detailsSectionByStyleSectionMap.get(event.target);section?.element.classList.toggle("hidden",!event.data.matches);} _handleDetailsSectionCollapsedStateChanged(event) {if(event.data.collapsed) return;for(let[styleSection,detailsSection]of this._detailsSectionByStyleSectionMap){if(event.target===detailsSection){styleSection.needsLayout();return;}}} _handleShowAllSettingChanged(event) {this._computedStyleSection.showsImplicitProperties=this._computedStyleShowAllSetting.value;} _handleUseShorthandsSettingChanged(event) {this._computedStyleSection.showsShorthandsInsteadOfLonghands=this._computedStylePreferShorthandsSetting.value;} _handleVariablesGroupingModeScopeBarSelectionChanged(event) {this.needsLayout();}};WI.ComputedStyleDetailsPanel.StyleClassName="computed";WI.ComputedStyleDetailsPanel.VariablesGroupingMode={Ungrouped:"ungrouped",ByType:"by-type",};WI.ComputedStyleSection=class ComputedStyleSection extends WI.View {constructor(delegate,{variablesGroupType}={}) {super();this.element.classList.add(WI.ComputedStyleSection.StyleClassName);this.element.dir="ltr";this._delegate=delegate;this._style=null;this._styleTraces=null;this._propertyViews=[];this._showsImplicitProperties=false;this._showsShorthandsInsteadOfLonghands=false;this._alwaysShowPropertyNames=new Set;this._propertyVisibilityMode=WI.ComputedStyleSection.PropertyVisibilityMode.ShowAll;this._hideFilterNonMatchingProperties=false;this._filterText=null;this._filterCleared=false;this._variablesGroupType=variablesGroupType||null;} get variablesGroupType(){return this._variablesGroupType;} get style() {return this._style;} set style(style) {if(this._style===style) return;if(this._style) this._style.removeEventListener(WI.CSSStyleDeclaration.Event.PropertiesChanged,this._handlePropertiesChanged,this);this._style=style||null;if(this._style) this._style.addEventListener(WI.CSSStyleDeclaration.Event.PropertiesChanged,this._handlePropertiesChanged,this);this.needsLayout();} get styleTraces() {return this._styleTraces;} set styleTraces(styleTraces) {if(Array.shallowEqual(this._styleTraces,styleTraces)) return;this._styleTraces=styleTraces||null;this.needsLayout();} set showsImplicitProperties(value) {if(value===this._showsImplicitProperties) return;this._showsImplicitProperties=value;this.needsLayout();} set showsShorthandsInsteadOfLonghands(value) {if(value===this._showsShorthandsInsteadOfLonghands) return;this._showsShorthandsInsteadOfLonghands=value;this.needsLayout();} set alwaysShowPropertyNames(propertyNames) {this._alwaysShowPropertyNames=new Set(propertyNames);this.needsLayout();} set propertyVisibilityMode(propertyVisibilityMode) {if(this._propertyVisibilityMode===propertyVisibilityMode) return;this._propertyVisibilityMode=propertyVisibilityMode;this.needsLayout();} set hideFilterNonMatchingProperties(value) {if(value===this._hideFilterNonMatchingProperties) return;this._hideFilterNonMatchingProperties=value;this.needsLayout();} get isEmpty() {return!this._propertyViews.length;} get properties() {if(this._variablesGroupType&&this._variablesGroupType!==WI.CSSStyleDeclaration.VariablesGroupType.Ungrouped) return this._style.variablesForType(this._variablesGroupType);if(this._style.styleSheetTextRange) return this._style.visibleProperties;return this._style.properties;} get propertiesToRender() {let properties=[];if(!this._style) return properties;properties=this.properties||[];let propertyNameMap=new Map(properties.map((property)=>[property.canonicalName,property]));function hasNonImplicitLonghand(property){if(property.canonicalName==="all") return false;let longhandPropertyNames=WI.CSSKeywordCompletions.LonghandNamesForShorthandProperty.get(property.canonicalName);if(!longhandPropertyNames) return false;for(let longhandPropertyName of longhandPropertyNames){let property=propertyNameMap.get(longhandPropertyName);if(property&&!property.implicit) return true;} return false;} let hideVariables=this._propertyVisibilityMode===ComputedStyleSection.PropertyVisibilityMode.HideVariables;let hideNonVariables=this._propertyVisibilityMode===ComputedStyleSection.PropertyVisibilityMode.HideNonVariables;properties=properties.filter((property)=>{if(this._alwaysShowPropertyNames.has(property.canonicalName)) return true;if(property.implicit&&!this._showsImplicitProperties){if(!(this._showsShorthandsInsteadOfLonghands&&property.isShorthand&&hasNonImplicitLonghand(property))) return false;} if(this._showsShorthandsInsteadOfLonghands){if(property.shorthandPropertyNames.length) return false;}else if(property.isShorthand) return false;if(property.isVariable&&hideVariables) return false;if(!property.isVariable&&hideNonVariables) return false;return true;});properties.sort((a,b)=>WI.CSSProperty.sortPreferringNonPrefixed(a.name,b.name));return properties;} layout() {super.layout();this.element.removeChildren();this._propertyViews=[];let properties=this.propertiesToRender;for(let i=0;i0) traceElement=this._createTrace(propertyTrace);let expandableView=new WI.ExpandableView(property.name,propertyView.element,traceElement);expandableView.element.classList.add("computed-property-item");this.element.append(expandableView.element);} if(this._filterText||this._filterCleared) this.dispatchEventToListeners(WI.ComputedStyleSection.Event.FilterApplied,{matches:!this.isEmpty});this._filterCleared=false;} detached() {super.detached();this._propertiesChangedDebouncer?.cancel();for(let propertyView of this._propertyViews) propertyView.detached();} applyFilter(filterText) {if(this._filterText&&!filterText) this._filterCleared=true;this._filterText=filterText;if(!this.didInitialLayout) return;this.needsLayout();} spreadsheetStylePropertyShowProperty(propertyView,property) {if(this._delegate.spreadsheetCSSStyleDeclarationEditorShowProperty) this._delegate.spreadsheetCSSStyleDeclarationEditorShowProperty(this,property);} _createTrace(propertyTrace) {let traceElement=document.createElement("ul");traceElement.className="property-traces";for(let property of propertyTrace){let traceItemElement=document.createElement("li");traceItemElement.className="property-trace-item";let leftElement=document.createElement("div");leftElement.className="property-trace-item-left";let rightElement=document.createElement("div");rightElement.className="property-trace-item-right";traceItemElement.append(leftElement,rightElement);let propertyView=new WI.SpreadsheetStyleProperty(this,property,{readOnly:true});let selectorText="";let ownerStyle=property.ownerStyle;if(ownerStyle){let ownerRule=ownerStyle.ownerRule;if(ownerRule) selectorText=ownerRule.selectorText;} let selectorElement=document.createElement("span");selectorElement.textContent=selectorText.truncateMiddle(24);selectorElement.className="selector";leftElement.append(propertyView.element,selectorElement);if(property.ownerStyle){let styleOriginView=new WI.StyleOriginView();styleOriginView.update(property.ownerStyle);rightElement.append(styleOriginView.element);} traceElement.append(traceItemElement);} return traceElement;} _handlePropertiesChanged(event) {this._propertiesChangedDebouncer||=new Debouncer(this.needsLayout.bind(this));this._propertiesChangedDebouncer.delayForTime(250);}};WI.ComputedStyleSection.Event={FilterApplied:"computed-style-section-filter-applied",};WI.ComputedStyleSection.StyleClassName="computed-style-section";WI.ComputedStyleSection.PropertyVisibilityMode={ShowAll:Symbol("variable-visibility-show-all"),HideVariables:Symbol("variable-visibility-hide-variables"),HideNonVariables:Symbol("variable-visibility-hide-non-variables"),};WI.ConsoleDrawer=class ConsoleDrawer extends WI.ContentBrowser {constructor(element) {const delegate=null;super(element,delegate,{hideBackForwardButtons:true,disableBackForwardNavigation:true,disableFindBanner:true,flexibleNavigationItem:new WI.NavigationItem,});this.element.classList.add("console-drawer");this._drawerHeightSetting=new WI.Setting("console-drawer-height",150);this.navigationBar.element.addEventListener("mousedown",this._consoleResizerMouseDown.bind(this));this._toggleDrawerButton=new WI.ToggleButtonNavigationItem("toggle-drawer",WI.UIString("Hide Console"),WI.UIString("Show Console"),"Images/HideConsoleDrawer.svg","Images/ShowConsoleDrawer.svg");this._toggleDrawerButton.visibilityPriority=WI.NavigationItem.VisibilityPriority.High;this._toggleDrawerButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,function(event){WI.toggleSplitConsole();},this._toggleDrawerButton);this.navigationBar.insertNavigationItem(this._toggleDrawerButton,0);this.collapsed=true;WI.TabBrowser.addEventListener(WI.TabBrowser.Event.SelectedTabContentViewDidChange,this._selectedTabContentViewDidChange,this);} toggleButtonShortcutTooltip(keyboardShortcut) {this._toggleDrawerButton.defaultToolTip=WI.UIString("Hide Console (%s)").format(keyboardShortcut.displayName);} get collapsed() {return this._collapsed;} set collapsed(flag) {if(flag===this._collapsed) return;this._collapsed=flag||false;this._toggleDrawerButton.toggled=this._collapsed;this.element.classList.toggle("hidden",this._collapsed); this._didMoveToParent(this._collapsed?null:WI.View.rootView());this.dispatchEventToListeners(WI.ConsoleDrawer.Event.CollapsedStateChanged);} get height() {return this.element.offsetHeight;} attached() {super.attached();this._restoreDrawerHeight();} sizeDidChange() {super.sizeDidChange();if(this._collapsed) return;let height=this.height;this._restoreDrawerHeight();if(height!==this.height) this.dispatchEventToListeners(WI.ConsoleDrawer.Event.Resized);} _consoleResizerMouseDown(event) {if(event.button!==0||event.ctrlKey) return;if(event.target!==this.navigationBar.element&&!event.target.classList.contains("flexible-space")) return;let resizerElement=event.target;let quickConsoleHeight=window.innerHeight-(this.element.totalOffsetTop+this.height);let mouseOffset=quickConsoleHeight-(event.pageY-resizerElement.totalOffsetTop);function dockedResizerDrag(event) {let height=window.innerHeight-event.pageY-mouseOffset;this._drawerHeightSetting.value=height;this._updateDrawerHeight(height);this.collapsed=false;} function dockedResizerDragEnd(event) {if(event.button!==0) return;WI.elementDragEnd(event);} WI.elementDragStart(resizerElement,dockedResizerDrag.bind(this),dockedResizerDragEnd.bind(this),event,"row-resize");} _restoreDrawerHeight() {this._updateDrawerHeight(this._drawerHeightSetting.value);} _updateDrawerHeight(height) {const minimumHeight=64;const maximumHeight=this.element.parentNode.offsetHeight-100;let heightCSSValue=Number.constrain(height,minimumHeight,maximumHeight)+"px";if(this.element.style.height===heightCSSValue) return;this.element.style.height=heightCSSValue;this.dispatchEventToListeners(WI.ConsoleDrawer.Event.Resized);} _selectedTabContentViewDidChange() {if(WI.doesCurrentTabSupportSplitContentBrowser()) return;this.element.classList.add("hidden");}};WI.ConsoleDrawer.Event={CollapsedStateChanged:"console-drawer-collapsed-state-changed",Resized:"console-drawer-resized",};WI.ConsoleGroup=class ConsoleGroup extends WI.Object {constructor(parentGroup) {super();this._parentGroup=parentGroup;this._element=null;} get element(){return this._element;} get parentGroup() {return this._parentGroup;} render(messageView) {var groupElement=document.createElement("div");groupElement.className="console-group";this._element=groupElement;var titleElement=messageView.element;titleElement.classList.add(WI.LogContentView.ItemWrapperStyleClassName);titleElement.addEventListener("click",this._titleClicked.bind(this));titleElement.addEventListener("mousedown",this._titleMouseDown.bind(this));if(groupElement&&messageView.message.type===WI.ConsoleMessage.MessageType.StartGroupCollapsed) groupElement.classList.add("collapsed");groupElement.appendChild(titleElement);var messagesElement=document.createElement("div");this._messagesElement=messagesElement;messagesElement.className="console-group-messages";groupElement.appendChild(messagesElement);return groupElement;} addMessageView(messageView) {var element=messageView.element;element.classList.add(WI.LogContentView.ItemWrapperStyleClassName);this.append(element);} append(messageOrGroupElement) {this._messagesElement.appendChild(messageOrGroupElement);} setMessageLevel(messageLevel) {switch(messageLevel){case WI.ConsoleMessage.MessageLevel.Log:this._element.classList.add("console-log-level");this._element.setAttribute("data-labelprefix",WI.UIString("Log: "));break;case WI.ConsoleMessage.MessageLevel.Info:this._element.classList.add("console-info-level");this._element.setAttribute("data-labelprefix",WI.UIString("Info: "));break;case WI.ConsoleMessage.MessageLevel.Debug:this._element.classList.add("console-debug-level");this._element.setAttribute("data-labelprefix",WI.UIString("Debug: "));break;case WI.ConsoleMessage.MessageLevel.Warning:this._element.classList.add("console-warning-level");this._element.setAttribute("data-labelprefix",WI.UIString("Warning: "));break;case WI.ConsoleMessage.MessageLevel.Error:this._element.classList.add("console-error-level");this._element.setAttribute("data-labelprefix",WI.UIString("Error: "));break;}} _titleMouseDown(event) {event.preventDefault();} _titleClicked(event) {var groupTitleElement=event.target.closest(".console-group-title");if(groupTitleElement){var groupElement=groupTitleElement.closest(".console-group");if(groupElement) groupElement.classList.toggle("collapsed");groupTitleElement.scrollIntoViewIfNeeded(true);}}};WI.ConsolePrompt=class ConsolePrompt extends WI.View {constructor(delegate,mimeType) {super();mimeType=parseMIMEType(mimeType).type;this.element.classList.add("console-prompt",WI.SyntaxHighlightedStyleClassName);this.element.appendChild(WI.ImageUtilities.useSVGSymbol("Images/UserInputPrompt.svg","glyph"));this._delegate=delegate||null;this._codeMirror=WI.CodeMirrorEditor.create(this.element,{lineWrapping:true,mode:{name:mimeType,globalVars:true},matchBrackets:true});var keyMap={"Up":this._handlePreviousKey.bind(this),"Down":this._handleNextKey.bind(this),"Ctrl-P":this._handlePreviousKey.bind(this),"Ctrl-N":this._handleNextKey.bind(this),"Enter":this._handleEnterKey.bind(this),"Cmd-Enter":this._handleCommandEnterKey.bind(this),"Tab":this._handleTabKey.bind(this),"Esc":this._handleEscapeKey.bind(this)};this._codeMirror.addKeyMap(keyMap);this._completionController=new WI.CodeMirrorCompletionController(WI.CodeMirrorCompletionController.Mode.PausedConsoleCommandLineAPI,this._codeMirror,this);this._completionController.addExtendedCompletionProvider("javascript",WI.javaScriptRuntimeCompletionProvider);let textarea=this._codeMirror.getInputField();if(textarea) textarea.ariaLabel=WI.UIString("Console prompt");this._history=[{}];this._historyIndex=0;} get delegate() {return this._delegate;} set delegate(delegate) {this._delegate=delegate||null;} set escapeKeyHandlerWhenEmpty(handler) {this._escapeKeyHandlerWhenEmpty=handler;} get text() {return this._codeMirror.getValue();} set text(text) {this._codeMirror.setValue(text||"");this._codeMirror.clearHistory();this._codeMirror.markClean();} get history() {this._history[this._historyIndex]=this._historyEntryForCurrentText();return this._history;} set history(history) {this._history=history instanceof Array?history.slice(0,WI.ConsolePrompt.MaximumHistorySize):[{}];this._historyIndex=0;this._restoreHistoryEntry(0);} get focused() {return this._codeMirror.getWrapperElement().classList.contains("CodeMirror-focused");} focus() {this._codeMirror.focus();} updateCompletions(completions,implicitSuffix) {this._completionController.updateCompletions(completions,implicitSuffix);} pushHistoryItem(text) {this._commitHistoryEntry({text});} completionControllerCompletionsNeeded(completionController,prefix,defaultCompletions,base,suffix,forced) {if(this.delegate&&typeof this.delegate.consolePromptCompletionsNeeded==="function") this.delegate.consolePromptCompletionsNeeded(this,defaultCompletions,base,prefix,suffix,forced);else this._completionController.updateCompletions(defaultCompletions);} completionControllerShouldAllowEscapeCompletion(completionController) { return!!this.text;} sizeDidChange() {super.sizeDidChange();if(this.text) this._codeMirror.refresh();} _handleTabKey(codeMirror) {var cursor=codeMirror.getCursor();var line=codeMirror.getLine(cursor.line);if(!line.trim().length) return CodeMirror.Pass;var firstNonSpace=line.search(/[^\s]/);if(cursor.ch<=firstNonSpace) return CodeMirror.Pass;this._completionController.completeAtCurrentPositionIfNeeded().then(function(result){if(result===WI.CodeMirrorCompletionController.UpdatePromise.NoCompletionsFound) InspectorFrontendHost.beep();});} _handleEscapeKey(codeMirror) {if(this.text) return CodeMirror.Pass;if(!this._escapeKeyHandlerWhenEmpty) return CodeMirror.Pass;this._escapeKeyHandlerWhenEmpty();} _handlePreviousKey(codeMirror) {if(this._codeMirror.somethingSelected()) return CodeMirror.Pass;if(this._codeMirror.getCursor().line) return CodeMirror.Pass;var historyEntry=this._history[this._historyIndex+1];if(!historyEntry) return CodeMirror.Pass;this._rememberCurrentTextInHistory();++this._historyIndex;this._restoreHistoryEntry(this._historyIndex);} _handleNextKey(codeMirror) {if(this._codeMirror.somethingSelected()) return CodeMirror.Pass;if(this._codeMirror.getCursor().line!==this._codeMirror.lastLine()) return CodeMirror.Pass;var historyEntry=this._history[this._historyIndex-1];if(!historyEntry) return CodeMirror.Pass;this._rememberCurrentTextInHistory();--this._historyIndex;this._restoreHistoryEntry(this._historyIndex);} _handleEnterKey(codeMirror,forceCommit,keepCurrentText) {var currentText=this.text;if(!currentText.trim()) return;var cursor=this._codeMirror.getCursor();var lastLine=this._codeMirror.lastLine();var lastLineLength=this._codeMirror.getLine(lastLine).length;var cursorIsAtLastPosition=positionsEqual(cursor,{line:lastLine,ch:lastLineLength});function positionsEqual(a,b) {return a.line===b.line&&a.ch===b.ch;} function commitTextOrInsertNewLine(commit) {if(!commit){if(positionsEqual(cursor,this._codeMirror.getCursor())) CodeMirror.commands.newlineAndIndent(this._codeMirror);return;} this._commitHistoryEntry(this._historyEntryForCurrentText());if(!keepCurrentText){this._codeMirror.setValue("");this._codeMirror.clearHistory();} if(this.delegate&&typeof this.delegate.consolePromptHistoryDidChange==="function") this.delegate.consolePromptHistoryDidChange(this);if(this.delegate&&typeof this.delegate.consolePromptTextCommitted==="function") this.delegate.consolePromptTextCommitted(this,currentText);} if(!forceCommit&&this.delegate&&typeof this.delegate.consolePromptShouldCommitText==="function"){this.delegate.consolePromptShouldCommitText(this,currentText,cursorIsAtLastPosition,commitTextOrInsertNewLine.bind(this));return;} commitTextOrInsertNewLine.call(this,true);} _commitHistoryEntry(historyEntry) {if(this._history[1]&&(!this._history[1].text||this._history[1].text===historyEntry.text)){this._history[1]=historyEntry;this._history[0]={};}else{this._history[0]=historyEntry;this._history.unshift({});if(this._history.length>WI.ConsolePrompt.MaximumHistorySize) this._history=this._history.slice(0,WI.ConsolePrompt.MaximumHistorySize);} this._historyIndex=0;} _handleCommandEnterKey(codeMirror) {this._handleEnterKey(codeMirror,true,true);} _restoreHistoryEntry(index) {var historyEntry=this._history[index];this._codeMirror.setValue(historyEntry.text||"");if(historyEntry.undoHistory) this._codeMirror.setHistory(historyEntry.undoHistory);else this._codeMirror.clearHistory();this._codeMirror.setCursor(historyEntry.cursor||{line:0});} _historyEntryForCurrentText() {return{text:this.text,undoHistory:this._codeMirror.getHistory(),cursor:this._codeMirror.getCursor()};} _rememberCurrentTextInHistory() {this._history[this._historyIndex]=this._historyEntryForCurrentText();if(this.delegate&&typeof this.delegate.consolePromptHistoryDidChange==="function") this.delegate.consolePromptHistoryDidChange(this);}};WI.ConsolePrompt.MaximumHistorySize=30;WI.ConsoleSession=class ConsoleSession extends WI.Object {constructor(data) {super();this._hasMessages=false;let element=document.createElement("div");element.className="console-session";let header=document.createElement("div");header.classList.add("console-session-header");let headerText="";switch(data.newSessionReason){case WI.ConsoleSession.NewSessionReason.PageReloaded:headerText=WI.UIString("Page reloaded at %s");break;case WI.ConsoleSession.NewSessionReason.PageNavigated:headerText=WI.UIString("Page navigated at %s");break;case WI.ConsoleSession.NewSessionReason.ConsoleCleared:headerText=WI.UIString("Console cleared at %s");break;default:headerText=WI.UIString("Console opened at %s");break;} let timestamp=data.timestamp||Date.now();header.textContent=headerText.format(new Date(timestamp).toLocaleTimeString());element.append(header);this.element=element;this._messagesElement=element;} addMessageView(messageView) {var messageElement=messageView.element;messageElement.classList.add(WI.LogContentView.ItemWrapperStyleClassName);this.append(messageElement);} append(messageOrGroupElement) {this._hasMessages=true;this._messagesElement.append(messageOrGroupElement);} hasMessages() {return this._hasMessages;}};WI.ConsoleSession.NewSessionReason={PageReloaded:Symbol("Page reloaded"),PageNavigated:Symbol("Page navigated"),ConsoleCleared:Symbol("Console cleared"),};WI.ConsoleSourceMapMessageGroup=class ConsoleSourceMapMessageGroup extends WI.ConsoleGroup {constructor() {super();this._messageCount=0; let titleConsoleMessage=new WI.ConsoleMessage(WI.mainTarget,WI.ConsoleMessage.MessageSource.Other,WI.ConsoleMessage.MessageLevel.Error,WI.UIString("Source Map loading errors"),WI.ConsoleMessage.MessageType.StartGroupCollapsed);this._titleConsoleMessageView=new WI.ConsoleMessageView(titleConsoleMessage);this._titleConsoleMessageView.render();this.render(this._titleConsoleMessageView);this.setMessageLevel(WI.ConsoleMessage.MessageLevel.Error);} addMessageView(messageView) {super.addMessageView(messageView);this._messageCount++;this._titleConsoleMessageView.repeatCount=this._messageCount;}};WI.ConsoleSnippetTreeElement=class ConsoleSnippetTreeElement extends WI.ScriptTreeElement {constructor(consoleSnippet) {super(consoleSnippet);this.addClassName("console-snippet");} onattach() {super.onattach();this.status=document.createElement("img");this.status.title=WI.UIString("Run");this.status.addEventListener("click",(event)=>{this.representedObject.run();});} ondelete() {WI.consoleManager.removeSnippet(this.representedObject);return true;} onenter() {this.representedObject.run();return true;} onspace() {this.representedObject.run();return true;} canSelectOnMouseDown(event) {if(this.status.contains(event.target)) return false;return super.canSelectOnMouseDown(event);} populateContextMenu(contextMenu,event) {contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Run Console Snippet"),()=>{this.representedObject.run();});contextMenu.appendSeparator();super.populateContextMenu(contextMenu,event);} updateStatus() {}};WI.ContentViewContainer=class ContentViewContainer extends WI.View {constructor({disableBackForwardNavigation}={}) {super();this._disableBackForwardNavigation=!!disableBackForwardNavigation;this.element.classList.add("content-view-container");this._backForwardList=[];this._currentIndex=-1;} get currentIndex() {return this._currentIndex;} get backForwardList() {return this._backForwardList;} get currentContentView() {if(this._currentIndex<0||this._currentIndex>this._backForwardList.length-1) return null;return this._backForwardList[this._currentIndex].contentView;} get currentBackForwardEntry() {if(this._currentIndex<0||this._currentIndex>this._backForwardList.length-1) return null;return this._backForwardList[this._currentIndex];} contentViewForRepresentedObject(representedObject,onlyExisting,extraArguments) {return WI.ContentView.contentViewForRepresentedObject(representedObject,onlyExisting,extraArguments);} showContentViewForRepresentedObject(representedObject,extraArguments) {var contentView=this.contentViewForRepresentedObject(representedObject,false,extraArguments);if(!contentView) return null;this.showContentView(contentView);return contentView;} showContentView(contentView,cookie) {if(this._disableBackForwardNavigation&&this.currentContentView){this.replaceContentView(this.currentContentView,contentView,cookie);return;} if(!(contentView instanceof WI.ContentView)) return null;if(contentView===this.currentContentView&&!cookie) return contentView; if(contentView.parentContainer!==this) this._takeOwnershipOfContentView(contentView);let currentEntry=this.currentBackForwardEntry; let provisionalEntry=null;for(let i=this._backForwardList.length-1;i>=0;--i){if(this._backForwardList[i].contentView===contentView){provisionalEntry=this._backForwardList[i].makeCopy(cookie);break;}} if(!provisionalEntry) provisionalEntry=new WI.BackForwardEntry(contentView,cookie);if(provisionalEntry.isEqual(currentEntry)){currentEntry.prepareToShow();return currentEntry.contentView;} let newIndex=this._currentIndex+1;let removedEntries=this._backForwardList.splice(newIndex,this._backForwardList.length-newIndex,provisionalEntry);for(let i=0;iexistingEntry.contentView===removedEntries[i].contentView);if(shouldDissociateContentView) this._disassociateFromContentView(removedEntries[i].contentView,removedEntries[i].tombstone);} contentView._parentContainer=this;this.showBackForwardEntryForIndex(newIndex);return contentView;} showBackForwardEntryForIndex(index) {if(index<0||index>this._backForwardList.length-1) return;if(this._currentIndex===index) return;var previousEntry=this.currentBackForwardEntry;this._currentIndex=index;var currentEntry=this.currentBackForwardEntry;if(previousEntry&&(!currentEntry.contentView.isAttached||previousEntry.contentView!==currentEntry.contentView)) this._hideEntry(previousEntry);this._showEntry(currentEntry);this.dispatchEventToListeners(WI.ContentViewContainer.Event.CurrentContentViewDidChange);} replaceContentView(oldContentView,newContentView,newCookie) {if(!(oldContentView instanceof WI.ContentView)) return;if(!(newContentView instanceof WI.ContentView)) return;if(oldContentView.parentContainer!==this) return;if(newContentView.parentContainer&&newContentView.parentContainer!==this) return;var currentlyShowing=this.currentContentView===oldContentView;if(currentlyShowing) this._hideEntry(this.currentBackForwardEntry);this._disassociateFromContentView(oldContentView,false);newContentView._parentContainer=this;for(var i=0;i=0;--i){if(this._backForwardList[i].contentView!==contentViewToClose){allSameContentView=false;break;}} if(allSameContentView){this.closeAllContentViews();return;} var visibleContentView=this.currentContentView;var backForwardListDidChange=false;for(var i=this._backForwardList.length-1;i>=0;--i){var entry=this._backForwardList[i];if(entry.contentView!==contentViewToClose) continue;if(entry.contentView===visibleContentView) this._hideEntry(entry);if(this._currentIndex>=i){ --this._currentIndex;} this._disassociateFromContentView(entry.contentView,entry.tombstone);this._backForwardList.splice(i,1);backForwardListDidChange=true;} if(backForwardListDidChange) this._removeIdenticalAdjacentBackForwardEntries();var currentEntry=this.currentBackForwardEntry;if(currentEntry&¤tEntry.contentView!==visibleContentView||backForwardListDidChange){this._showEntry(currentEntry);this.dispatchEventToListeners(WI.ContentViewContainer.Event.CurrentContentViewDidChange);}} closeAllContentViews(filter) {if(!this._backForwardList.length){return;} var visibleContentView=this.currentContentView;for(let i=0;i0;} canGoForward() {return this._currentIndex=0;--i){let entry=this._backForwardList[i];if(!entry.isEqual(previousEntry)){previousEntry=entry;continue;} if(this._currentIndex>=i){ --this._currentIndex;} this._backForwardList.splice(i,1);}}};WI.ContentViewContainer.Event={CurrentContentViewDidChange:"content-view-container-current-content-view-did-change"};WI.ContentViewContainer.TombstoneContentViewContainersSymbol=Symbol("content-view-container-tombstone-content-view-containers");WI.ContextMenuItem=class ContextMenuItem extends WI.Object {constructor(topLevelMenu,type,label,disabled,checked) {super();this._type=type;this._label=label;this._disabled=disabled;this._checked=checked;this._contextMenu=topLevelMenu||this;if(type==="item"||type==="checkbox") this._id=topLevelMenu.nextId();} id() {return this._id;} type() {return this._type;} isEnabled() {return!this._disabled;} setEnabled(enabled) {this._disabled=!enabled;} _buildDescriptor() {switch(this._type){case"item":return{type:"item",id:this._id,label:this._label,enabled:!this._disabled};case"separator":return{type:"separator"};case"checkbox":return{type:"checkbox",id:this._id,label:this._label,checked:!!this._checked,enabled:!this._disabled};}}};WI.ContextSubMenuItem=class ContextSubMenuItem extends WI.ContextMenuItem {constructor(topLevelMenu,label,disabled) {super(topLevelMenu,"subMenu",label,disabled);this._items=[];} appendItem(label,handler,disabled) {let item=new WI.ContextMenuItem(this._contextMenu,"item",label,disabled);this.pushItem(item);this._contextMenu._setHandler(item.id(),handler);return item;} appendSubMenuItem(label,disabled) {let item=new WI.ContextSubMenuItem(this._contextMenu,label,disabled);this.pushItem(item);return item;} appendCheckboxItem(label,handler,checked,disabled) {let item=new WI.ContextMenuItem(this._contextMenu,"checkbox",label,disabled,checked);this.pushItem(item);this._contextMenu._setHandler(item.id(),handler);return item;} appendHeader(label) {return this.appendItem(label,()=>{},true);} appendSeparator() {if(this._items.length) this._pendingSeparator=true;} pushItem(item) {if(this._pendingSeparator){this._items.push(new WI.ContextMenuItem(this._contextMenu,"separator"));this._pendingSeparator=null;} this._items.push(item);} isEmpty() {return!this._items.length;} _buildDescriptor() {if(this.isEmpty()) return null;let subItems=this._items.map((item)=>item._buildDescriptor()).filter((item)=>!!item);return{type:"subMenu",label:this._label,enabled:!this._disabled,subItems};}};WI.ContextMenu=class ContextMenu extends WI.ContextSubMenuItem {constructor(event) {super(null,"");this._event=event;this._handlers={};this._id=0;this._beforeShowCallbacks=[];} static createFromEvent(event,onlyExisting=false) {if(!event[WI.ContextMenu.ProposedMenuSymbol]&&!onlyExisting) event[WI.ContextMenu.ProposedMenuSymbol]=new WI.ContextMenu(event);return event[WI.ContextMenu.ProposedMenuSymbol]||null;} static contextMenuItemSelected(id) {if(WI.ContextMenu._lastContextMenu) WI.ContextMenu._lastContextMenu._itemSelected(id);} static contextMenuCleared() { } nextId() {return this._id++;} show() {let menuObject=this._buildDescriptor();if(menuObject.length){WI.ContextMenu._lastContextMenu=this;if(this._event.type!=="contextmenu"&&typeof InspectorFrontendHost.dispatchEventAsContextMenuEvent==="function"){this._menuObject=menuObject;this._event.target.addEventListener("contextmenu",this,true);InspectorFrontendHost.dispatchEventAsContextMenuEvent(this._event);}else InspectorFrontendHost.showContextMenu(this._event,menuObject);} if(this._event) this._event.stopImmediatePropagation();} addBeforeShowCallback(callback) {this._beforeShowCallbacks.push(callback);} handleEvent(event) {for(let callback of this._beforeShowCallbacks) callback(this);this._event.target.removeEventListener("contextmenu",this,true);InspectorFrontendHost.showContextMenu(event,this._menuObject);this._menuObject=null;event.stopImmediatePropagation();} _setHandler(id,handler) {if(handler) this._handlers[id]=handler;} _buildDescriptor() {return this._items.map((item)=>item._buildDescriptor()).filter((item)=>!!item);} _itemSelected(id) {try{if(this._handlers[id]) this._handlers[id].call(this);}catch(e){WI.reportInternalError(e);}}};WI.ContextMenu.ProposedMenuSymbol=Symbol("context-menu-proposed-menu");WI.addMouseDownContextMenuHandlers=function(element,populateContextMenuCallback) {let ignoreMouseDown=false;element.addEventListener("mousedown",(event)=>{if(event.button!==0) return;event.stop();if(ignoreMouseDown) return;let contextMenu=WI.ContextMenu.createFromEvent(event);contextMenu.addBeforeShowCallback(()=>{ignoreMouseDown=false;});populateContextMenuCallback(contextMenu,event);ignoreMouseDown=!contextMenu.isEmpty();contextMenu.show();});element.addEventListener("contextmenu",(event)=>{let contextMenu=WI.ContextMenu.createFromEvent(event);populateContextMenuCallback(contextMenu,event);});};WI.appendContextMenuItemsForSourceCode=function(contextMenu,sourceCodeOrLocation) {if(!(contextMenu instanceof WI.ContextMenu)) return;let sourceCode=sourceCodeOrLocation;let location=null;if(sourceCodeOrLocation instanceof WI.SourceCodeLocation){sourceCode=sourceCodeOrLocation.sourceCode;location=sourceCodeOrLocation;} if(!(sourceCode instanceof WI.SourceCode)) return;if(contextMenu.__domBreakpointItemsAdded) return;if(!contextMenu.__localOverrideItemsAdded&&WI.NetworkManager.supportsOverridingResponses()){contextMenu.__localOverrideItemsAdded=true;if(WI.networkManager.canBeOverridden(sourceCode)){contextMenu.appendSeparator();if(WI.NetworkManager.supportsOverridingRequests()){contextMenu.appendItem(WI.UIString("Create Request Local Override"),async()=>{let localResourceOverride=await sourceCode.createLocalResourceOverride(WI.LocalResourceOverride.InterceptType.Request);WI.networkManager.addLocalResourceOverride(localResourceOverride);WI.showLocalResourceOverride(localResourceOverride,{overriddenResource:sourceCode,initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});} contextMenu.appendItem(WI.UIString("Create Response Local Override"),async()=>{let localResourceOverride=await sourceCode.createLocalResourceOverride(WI.LocalResourceOverride.InterceptType.Response);WI.networkManager.addLocalResourceOverride(localResourceOverride);WI.showLocalResourceOverride(localResourceOverride,{overriddenResource:sourceCode,initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});if(WI.NetworkManager.supportsBlockingRequests()){contextMenu.appendItem(WI.UIString("Block Request URL"),async()=>{let localResourceOverride=await sourceCode.createLocalResourceOverride(WI.LocalResourceOverride.InterceptType.Block);WI.networkManager.addLocalResourceOverride(localResourceOverride);});}}else{let localResourceOverride=WI.networkManager.localResourceOverridesForURL(sourceCode.url)[0];if(localResourceOverride){contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Reveal Local Override"),()=>{WI.showLocalResourceOverride(localResourceOverride,{overriddenResource:sourceCode,initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});contextMenu.appendItem(localResourceOverride.disabled?WI.UIString("Enable Local Override"):WI.UIString("Disable Local Override"),()=>{localResourceOverride.disabled=!localResourceOverride.disabled;});contextMenu.appendItem(WI.UIString("Delete Local Override"),()=>{WI.networkManager.removeLocalResourceOverride(localResourceOverride);});}}} contextMenu.appendSeparator();if(location&&(sourceCode instanceof WI.Script||(sourceCode instanceof WI.Resource&&sourceCode.type===WI.Resource.Type.Script&&!sourceCode.localResourceOverride))){let existingJavaScriptBreakpoint=WI.debuggerManager.breakpointForSourceCodeLocation(location);if(existingJavaScriptBreakpoint){contextMenu.appendItem(WI.UIString("Delete JavaScript Breakpoint"),()=>{WI.debuggerManager.removeBreakpoint(existingJavaScriptBreakpoint);});}else{contextMenu.appendItem(WI.UIString("Add JavaScript Breakpoint"),()=>{WI.debuggerManager.addBreakpoint(new WI.JavaScriptBreakpoint(location));});}} if(sourceCode?.initiatorStackTrace){let existingURLBreakpoints=WI.domDebuggerManager.urlBreakpointsMatchingURL(sourceCode.url);if(existingURLBreakpoints.length){contextMenu.appendItem(existingURLBreakpoints.length===1?WI.UIString("Delete URL Breakpoint"):WI.UIString("Delete URL Breakpoints"),()=>{for(let urlBreakpoint of existingURLBreakpoints) WI.domDebuggerManager.removeURLBreakpoint(urlBreakpoint);});}else{contextMenu.appendItem(WI.UIString("Add URL Breakpoint"),()=>{WI.domDebuggerManager.addURLBreakpoint(new WI.URLBreakpoint(WI.URLBreakpoint.Type.Text,sourceCode.url));});}} if(sourceCode.supportsScriptBlackboxing){let blackboxData=WI.debuggerManager.blackboxDataForSourceCode(sourceCode);if(blackboxData&&blackboxData.type===WI.DebuggerManager.BlackboxType.Pattern){contextMenu.appendItem(WI.UIString("Reveal Blackbox Pattern"),()=>{WI.showSettingsTab({blackboxPatternToSelect:blackboxData.regex,initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});}else{contextMenu.appendItem(blackboxData?WI.UIString("Unblackbox Script"):WI.UIString("Blackbox Script"),()=>{WI.debuggerManager.setShouldBlackboxScript(sourceCode,!blackboxData);});}} contextMenu.appendSeparator();WI.appendContextMenuItemsForURL(contextMenu,sourceCode.url,{sourceCode,location});if(sourceCode instanceof WI.Resource&&!sourceCode.localResourceOverride&&sourceCode.hasMetadata){if(sourceCode.urlComponents.scheme!=="data"){contextMenu.appendItem(WI.UIString("Copy as fetch","Copy the URL, method, headers, etc. of the given network request in the format of a JS fetch expression."),()=>{InspectorFrontendHost.copyText(sourceCode.generateFetchCode());});contextMenu.appendItem(WI.UIString("Copy as cURL"),()=>{InspectorFrontendHost.copyText(sourceCode.generateCURLCommand());});contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Copy HTTP Request"),()=>{InspectorFrontendHost.copyText(sourceCode.stringifyHTTPRequest());});if(sourceCode.hasResponse()){contextMenu.appendItem(WI.UIString("Copy HTTP Response"),()=>{InspectorFrontendHost.copyText(sourceCode.stringifyHTTPResponse());});}}} if(WI.FileUtilities.canSave(WI.FileUtilities.SaveMode.SingleFile)){contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Save File"),()=>{sourceCode.requestContent().then(()=>{let saveData={url:sourceCode.url,content:sourceCode.content,base64Encoded:sourceCode.base64Encoded,};if(sourceCode.urlComponents.path==="/"){let extension=WI.fileExtensionForMIMEType(sourceCode.mimeType);if(extension) saveData.suggestedName=`index.${extension}`;} WI.FileUtilities.save(WI.FileUtilities.SaveMode.SingleFile,saveData);});});} contextMenu.appendSeparator();};WI.appendContextMenuItemsForURL=function(contextMenu,url,options={}) {if(!url) return;function showResourceWithOptions(options){options.initiatorHint=WI.TabBrowser.TabNavigationInitiator.ContextMenu;if(options.location) WI.showSourceCodeLocation(options.location,options);else if(options.sourceCode) WI.showSourceCode(options.sourceCode,options);else WI.openURL(url,options);} if(!url.startsWith("javascript:")&&!url.startsWith("data:")){contextMenu.appendItem(WI.UIString("Open in New Window","Open in New Window @ Context Menu Item","Context menu item for opening the target item in a new window."),()=>{WI.openURL(url,{alwaysOpenExternally:true});});} if(WI.networkManager.resourcesForURL(url).size){if(!WI.isShowingSourcesTab()){contextMenu.appendItem(WI.UIString("Reveal in Sources Tab"),()=>{showResourceWithOptions({preferredTabType:WI.SourcesTabContentView.Type});});} if(!WI.isShowingNetworkTab()){contextMenu.appendItem(WI.UIString("Reveal in Network Tab"),()=>{showResourceWithOptions({preferredTabType:WI.NetworkTabContentView.Type});});}} contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Copy Link"),()=>{InspectorFrontendHost.copyText(url);});};WI.appendContextMenuItemsForDOMNode=function(contextMenu,domNode,options={}) {if(!(contextMenu instanceof WI.ContextMenu)) return;if(!(domNode instanceof WI.DOMNode)) return;let copySubMenu=options.copySubMenu||contextMenu.appendSubMenuItem(WI.UIString("Copy"));let isElement=domNode.nodeType()===Node.ELEMENT_NODE;let attached=domNode.attached;if(isElement&&attached){copySubMenu.appendItem(WI.UIString("Selector Path"),()=>{let cssPath=WI.cssPath(domNode);InspectorFrontendHost.copyText(cssPath);});} if(!domNode.isPseudoElement()&&attached){copySubMenu.appendItem(WI.UIString("XPath"),()=>{let xpath=WI.xpath(domNode);InspectorFrontendHost.copyText(xpath);});} contextMenu.appendSeparator();if(!options.usingLocalDOMNode){if(domNode.isCustomElement()){contextMenu.appendItem(WI.UIString("Jump to Definition"),()=>{function didGetFunctionDetails(error,response){if(error) return;let location=response.location;let sourceCode=WI.debuggerManager.scriptForIdentifier(location.scriptId,WI.mainTarget);if(!sourceCode) return;let sourceCodeLocation=sourceCode.createSourceCodeLocation(location.lineNumber,location.columnNumber||0);WI.showSourceCodeLocation(sourceCodeLocation,{ignoreNetworkTab:true,ignoreSearchTab:true,});} WI.RemoteObject.resolveNode(domNode).then((remoteObject)=>{remoteObject.getProperty("constructor",(error,result,wasThrown)=>{if(error) return;if(result.type==="function") remoteObject.target.DebuggerAgent.getFunctionDetails(result.objectId,didGetFunctionDetails);result.release();});remoteObject.release();});});contextMenu.appendSeparator();} if(!options.disallowEditing&&WI.cssManager.canForcePseudoClass()&&domNode.attached){contextMenu.appendSeparator();let pseudoSubMenu=contextMenu.appendSubMenuItem(WI.UIString("Forced Pseudo-Classes","A context menu item to force (override) a DOM node's pseudo-classes"));let enabledPseudoClasses=domNode.enabledPseudoClasses;for(let pseudoClass of Object.values(WI.CSSManager.ForceablePseudoClass)){if(!WI.cssManager.canForcePseudoClass(pseudoClass)) continue;let enabled=enabledPseudoClasses.includes(pseudoClass);pseudoSubMenu.appendCheckboxItem(WI.CSSManager.displayNameForForceablePseudoClass(pseudoClass),()=>{domNode.setPseudoClassEnabled(pseudoClass,!enabled);},enabled);}} if(WI.domDebuggerManager.supported&&isElement&&!domNode.isPseudoElement()&&attached){contextMenu.appendSeparator();WI.appendContextMenuItemsForDOMNodeBreakpoints(contextMenu,domNode,options);} contextMenu.appendSeparator();let canLogShadowTree=!domNode.isInUserAgentShadowTree()||WI.DOMManager.supportsEditingUserAgentShadowTrees({frontendOnly:true});if(!options.excludeLogElement&&canLogShadowTree&&!domNode.destroyed&&!domNode.isPseudoElement()){let label=isElement?WI.UIString("Log Element","Log (print) DOM element to Console"):WI.UIString("Log Node","Log (print) DOM node to Console");contextMenu.appendItem(label,()=>{WI.RemoteObject.resolveNode(domNode,WI.RuntimeManager.ConsoleObjectGroup).then((remoteObject)=>{let text=isElement?WI.UIString("Selected Element","Selected DOM element"):WI.UIString("Selected Node","Selected DOM node");WI.consoleLogViewController.appendImmediateExecutionWithResult(text,remoteObject,{addSpecialUserLogClass:true,shouldRevealConsole:true});});});} if(!options.excludeRevealElement&&InspectorBackend.hasDomain("DOM")&&attached){contextMenu.appendItem(WI.repeatedUIString.revealInDOMTree(),()=>{WI.domManager.inspectElement(domNode.id,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});} if(InspectorBackend.hasDomain("LayerTree")&&attached){contextMenu.appendItem(WI.UIString("Reveal in Layers Tab","Open Layers tab and select the layer corresponding to this node"),()=>{WI.showLayersTab({nodeToSelect:domNode,initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});} if(WI.FileUtilities.canSave(WI.FileUtilities.SaveMode.SingleFile)&&InspectorBackend.hasCommand("Page.snapshotNode")&&attached){contextMenu.appendItem(WI.UIString("Capture Screenshot","Capture screenshot of the selected DOM node"),()=>{let target=WI.assumingMainTarget();target.PageAgent.snapshotNode(domNode.id,(error,dataURL)=>{if(error){const target=WI.mainTarget;const source=WI.ConsoleMessage.MessageSource.Other;const level=WI.ConsoleMessage.MessageLevel.Error;let consoleMessage=new WI.ConsoleMessage(target,source,level,error);consoleMessage.shouldRevealConsole=true;WI.consoleLogViewController.appendConsoleMessage(consoleMessage);return;} WI.FileUtilities.save(WI.FileUtilities.SaveMode.SingleFile,{content:parseDataURL(dataURL).data,base64Encoded:true,suggestedName:WI.FileUtilities.screenshotString()+".png",});});});} if(isElement&&attached){contextMenu.appendItem(WI.UIString("Scroll into View","Scroll selected DOM node into view on the inspected web page"),()=>{domNode.scrollIntoView();});} contextMenu.appendSeparator();}};WI.appendContextMenuItemsForDOMNodeBreakpoints=function(contextMenu,domNode,options={}) {if(contextMenu.__domBreakpointItemsAdded) return;contextMenu.__domBreakpointItemsAdded=true;let breakpoints=WI.domDebuggerManager.domBreakpointsForNode(domNode);contextMenu.appendSeparator();let subMenu=contextMenu.appendSubMenuItem(WI.UIString("Break on"));for(let type of Object.values(WI.DOMBreakpoint.Type)){let label=WI.DOMBreakpoint.displayNameForType(type);let breakpoint=breakpoints.find((breakpoint)=>breakpoint.type===type);subMenu.appendCheckboxItem(label,function(){if(breakpoint) WI.domDebuggerManager.removeDOMBreakpoint(breakpoint);else WI.domDebuggerManager.addDOMBreakpoint(new WI.DOMBreakpoint(domNode,type));},!!breakpoint);} if(breakpoints.length&&!WI.isShowingSourcesTab()){contextMenu.appendItem(breakpoints.length===1?WI.UIString("Reveal Breakpoint in Sources Tab"):WI.UIString("Reveal Breakpoints in Sources Tab"),()=>{WI.showSourcesTab({representedObjectToSelect:breakpoints.length===1?breakpoints[0]:domNode,});});} contextMenu.appendSeparator();if(breakpoints.length===1) WI.BreakpointPopover.appendContextMenuItems(contextMenu,breakpoints[0],options.popoverTargetElement);else if(breakpoints.length){let shouldEnable=breakpoints.some((breakpoint)=>breakpoint.disabled);contextMenu.appendItem(shouldEnable?WI.UIString("Enable Breakpoints"):WI.UIString("Disable Breakpoints"),()=>{for(let breakpoint of breakpoints) breakpoint.disabled=!shouldEnable;});contextMenu.appendItem(WI.UIString("Delete Breakpoints"),()=>{for(let breakpoint of breakpoints) WI.domDebuggerManager.removeDOMBreakpoint(breakpoint);});contextMenu.appendSeparator();} let subtreeBreakpoints=WI.domDebuggerManager.domBreakpointsInSubtree(domNode);if(subtreeBreakpoints.length){if(options.revealDescendantBreakpointsMenuItemHandler) contextMenu.appendItem(WI.UIString("Reveal Descendant Breakpoints"),options.revealDescendantBreakpointsMenuItemHandler);let subtreeShouldEnable=subtreeBreakpoints.some((breakpoint)=>breakpoint.disabled);contextMenu.appendItem(subtreeShouldEnable?WI.UIString("Enable Descendant Breakpoints"):WI.UIString("Disable Descendant Breakpoints"),()=>{for(let subtreeBreakpoint of subtreeBreakpoints) subtreeBreakpoint.disabled=!subtreeShouldEnable;});contextMenu.appendItem(WI.UIString("Delete Descendant Breakpoints"),()=>{for(let subtreeBreakpoint of subtreeBreakpoints) WI.domDebuggerManager.removeDOMBreakpoint(subtreeBreakpoint);});contextMenu.appendSeparator();}};WI.CSSDocumentationPopover=class CSSDocumentationPopover extends WI.Popover {constructor(cssProperty,delegate) {super(delegate);this._cssProperty=cssProperty;this._targetElement=null;this.windowResizeHandler=this._presentOverTargetElement.bind(this);} show(targetElement) {this._targetElement=targetElement;let documentationDetails=this._getDocumentationDetails(this._cssProperty);let documentationElement=this._createDocumentationElement(documentationDetails);this.content=documentationElement;this._presentOverTargetElement();} _presentOverTargetElement() {if(!this._targetElement) return;let targetFrame=WI.Rect.rectFromClientRect(this._targetElement.getBoundingClientRect());this.present(targetFrame.pad(2),[WI.RectEdge.MIN_X,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_Y]);} _getDocumentationDetails(property) {let propertyName="";if(property.canonicalName in CSSDocumentation) propertyName=property.canonicalName;else if(property.name in CSSDocumentation) propertyName=property.name;let propertyDocumentation=CSSDocumentation[propertyName];return{name:propertyName,description:propertyDocumentation.description,syntax:propertyDocumentation.syntax,url:propertyDocumentation.url,};} _createDocumentationElement(details) {let documentationElement=document.createElement("div");documentationElement.className="documentation-popover-content";let nameElement=documentationElement.appendChild(document.createElement("p"));nameElement.className="name-header";nameElement.textContent=details.name;let descriptionElement=documentationElement.appendChild(document.createElement("p"));descriptionElement.textContent=details.description;if(details.syntax&&WI.settings.showCSSPropertySyntaxInDocumentationPopover.value){let syntaxElement=documentationElement.appendChild(document.createElement("p"));syntaxElement.className="syntax";let syntaxTitleElement=syntaxElement.appendChild(document.createElement("span"));syntaxTitleElement.className="syntax-title";syntaxTitleElement.textContent=details.name;let syntaxBodyElement=syntaxElement.appendChild(document.createElement("span"));syntaxBodyElement.textContent=`: ${details.syntax}`;} if(details.url){let referenceLinkElement=documentationElement.appendChild(document.createElement("a"));referenceLinkElement.className="reference-link";referenceLinkElement.textContent=WI.unlocalizedString("MDN Reference");referenceLinkElement.href=details.url;} return documentationElement;}};WI.CookiePopover=class CookiePopover extends WI.Popover {constructor(delegate) {super(delegate);this._nameInputElement=null;this._valueInputElement=null;this._domainInputElement=null;this._pathInputElement=null;this._sessionCheckboxElement=null;this._expiresInputElement=null;this._httpOnlyCheckboxElement=null;this._secureCheckboxElement=null;this._sameSiteSelectElement=null;this._serializedDataWhenShown=null;this.windowResizeHandler=this._presentOverTargetElement.bind(this);} get serializedData() {if(!this._targetElement) return null;let name=this._nameInputElement.value;if(!name) return null;let domain=this._domainInputElement.value||this._domainInputElement.placeholder;if(!domain) return null;let path=this._pathInputElement.value||this._pathInputElement.placeholder;if(!path) return null;let session=this._sessionCheckboxElement.checked;let expires=this._parseExpires();if(!session&&isNaN(expires)) return null;try{let url=new URL(domain);domain=url.hostname;}catch{} if(!path.startsWith("/")) path="/"+path;let data={name,value:this._valueInputElement.value,domain,path,httpOnly:this._httpOnlyCheckboxElement.checked,secure:this._secureCheckboxElement.checked,sameSite:this._sameSiteSelectElement.value,};if(session) data.session=true;else data.expires=expires;if(JSON.stringify(data)===JSON.stringify(this._serializedDataWhenShown)) return null;return data;} show(cookie,targetElement,preferredEdges,options={}) {this._targetElement=targetElement;this._preferredEdges=preferredEdges;function formatDate(date){function pad(number){return String(number).padStart(2,"0");} return[date.getFullYear(),"-",pad(date.getMonth()+1),"-",pad(date.getDate()),"T",pad(date.getHours()),":",pad(date.getMinutes()),":",pad(date.getSeconds()),].join("");} let data={};if(cookie){data.name=cookie.name;data.value=cookie.value;data.domain=cookie.domain;data.path=cookie.path;data.expires=formatDate(cookie.expires||this._defaultExpires());data.session=cookie.session;data.httpOnly=cookie.httpOnly;data.secure=cookie.secure;data.sameSite=cookie.sameSite;}else{let urlComponents=WI.networkManager.mainFrame.mainResource.urlComponents;data.name="";data.value="";data.domain=urlComponents.host;data.path=urlComponents.path;data.expires=formatDate(this._defaultExpires());data.session=true;data.httpOnly=false;data.secure=false;data.sameSite=WI.Cookie.SameSiteType.None;} let popoverContentElement=document.createElement("div");popoverContentElement.className="cookie-popover-content";let tableElement=popoverContentElement.appendChild(document.createElement("table"));function createRow(id,label,editorElement){let domId=`cookie-popover-${id}-editor`;let rowElement=tableElement.appendChild(document.createElement("tr"));let headerElement=rowElement.appendChild(document.createElement("th"));let labelElement=headerElement.appendChild(document.createElement("label"));labelElement.setAttribute("for",domId);labelElement.textContent=label;let dataElement=rowElement.appendChild(document.createElement("td"));editorElement.id=domId;dataElement.appendChild(editorElement);if(id===options.focusField){setTimeout(()=>{editorElement.focus();editorElement.select?.();});} return{rowElement};} let boundHandleInputKeyDown=this._handleInputKeyDown.bind(this);function createInputRow(id,label,type,value){let inputElement=document.createElement("input");inputElement.type=type;if(type==="checkbox") inputElement.checked=value;else{if(cookie) inputElement.value=value;inputElement.placeholder=value;inputElement.spellcheck=false;inputElement.addEventListener("keydown",boundHandleInputKeyDown);} let rowElement=createRow(id,label,inputElement).rowElement;return{inputElement,rowElement};} this._nameInputElement=createInputRow("name",WI.UIString("Name"),"text",data.name).inputElement;this._nameInputElement.required=true;this._valueInputElement=createInputRow("value",WI.UIString("Value"),"text",data.value).inputElement;this._domainInputElement=createInputRow("domain",WI.unlocalizedString("Domain"),"text",data.domain).inputElement;this._pathInputElement=createInputRow("path",WI.unlocalizedString("Path"),"text",data.path).inputElement;this._sessionCheckboxElement=createInputRow("session",WI.unlocalizedString("Session"),"checkbox",data.session).inputElement;let expiresInputRow=createInputRow("expires",WI.unlocalizedString("Expires"),"datetime-local",data.expires);this._expiresInputElement=expiresInputRow.inputElement;this._expiresInputElement.step=1;this._expiresInputElement.addEventListener("input",(event)=>{this._expiresInputElement.classList.toggle("invalid",isNaN(this._parseExpires()));});this._httpOnlyCheckboxElement=createInputRow("http-only",WI.unlocalizedString("HttpOnly"),"checkbox",data.httpOnly).inputElement;this._secureCheckboxElement=createInputRow("secure",WI.unlocalizedString("Secure"),"checkbox",data.secure).inputElement;this._sameSiteSelectElement=document.createElement("select");for(let sameSiteType of Object.values(WI.Cookie.SameSiteType)){let optionElement=this._sameSiteSelectElement.appendChild(document.createElement("option"));optionElement.value=sameSiteType;optionElement.textContent=WI.Cookie.displayNameForSameSiteType(sameSiteType);} this._sameSiteSelectElement.value=data.sameSite;createRow("same-site",WI.unlocalizedString("SameSite"),this._sameSiteSelectElement);let toggleExpiresRow=()=>{expiresInputRow.rowElement.hidden=this._sessionCheckboxElement.checked;this.update();};this._sessionCheckboxElement.addEventListener("change",(event)=>{toggleExpiresRow();});toggleExpiresRow();this._serializedDataWhenShown=this.serializedData;this.content=popoverContentElement;this._presentOverTargetElement();} _presentOverTargetElement() {if(!this._targetElement) return;let targetFrame=WI.Rect.rectFromClientRect(this._targetElement.getBoundingClientRect());this.present(targetFrame.pad(2),this._preferredEdges);} _defaultExpires() {return new Date(Date.now()+(1000*60*60*24));} _parseExpires() {let timestamp=Date.parse(this._expiresInputElement.value||this._expiresInputElement.placeholder);if(timestamp{this._showCookiePopover(cell,this._filteredCookies[rowIndex],column.identifier);});} contextMenu.appendItem(WI.UIString("Copy"),()=>{let rowIndexes;if(table.isRowSelected(rowIndex)) rowIndexes=table.selectedRows;else rowIndexes=[rowIndex];let cookies=this._cookiesAtIndexes(rowIndexes);InspectorFrontendHost.copyText(this._formatCookiesAsText(cookies));});if(InspectorBackend.hasCommand("Page.deleteCookie")){contextMenu.appendItem(WI.UIString("Delete"),()=>{if(table.isRowSelected(rowIndex)) table.removeSelectedRows();else table.removeRow(rowIndex);});} contextMenu.appendSeparator();} tableDidRemoveRows(table,rowIndexes) {if(!rowIndexes.length) return;for(let i=rowIndexes.length-1;i>=0;--i){let rowIndex=rowIndexes[i];let cookie=this._filteredCookies[rowIndex];if(!cookie) continue;this._filteredCookies.splice(rowIndex,1);this._cookies.remove(cookie);let target=WI.assumingMainTarget();target.PageAgent.deleteCookie(cookie.name,cookie.url);}} tablePopulateCell(table,cell,column,rowIndex) {let cookie=this._filteredCookies[rowIndex];cell.textContent=this._formatCookiePropertyForColumn(cookie,column);if(!this._knownCells.has(cell)){this._knownCells.add(cell);cell.addEventListener("dblclick",(event)=>{if(column.identifier==="size"){InspectorFrontendHost.beep();return;} this._showCookiePopover(cell,cookie,column.identifier);});} return cell;} willDismissPopover(popover) {if(popover instanceof WI.CookiePopover){this._willDismissCookiePopover(popover);return;}} initialLayout() {super.initialLayout();this._table=new WI.Table("cookies-table",this,this,20);this._table.allowsMultipleSelection=true;this._nameColumn=new WI.TableColumn("name",WI.UIString("Name"),{minWidth:70,maxWidth:300,initialWidth:200,resizeType:WI.TableColumn.ResizeType.Locked,});this._valueColumn=new WI.TableColumn("value",WI.UIString("Value"),{minWidth:100,maxWidth:600,initialWidth:200,hideable:false,});this._domainColumn=new WI.TableColumn("domain",WI.unlocalizedString("Domain"),{minWidth:100,maxWidth:200,initialWidth:120,});this._pathColumn=new WI.TableColumn("path",WI.unlocalizedString("Path"),{minWidth:50,maxWidth:300,initialWidth:100,});this._expiresColumn=new WI.TableColumn("expires",WI.unlocalizedString("Expires"),{minWidth:100,maxWidth:200,initialWidth:150,});this._sizeColumn=new WI.TableColumn("size",WI.UIString("Size"),{minWidth:50,maxWidth:80,initialWidth:65,align:"right",});this._secureColumn=new WI.TableColumn("secure",WI.unlocalizedString("Secure"),{minWidth:70,maxWidth:70,align:"center",});this._httpOnlyColumn=new WI.TableColumn("httpOnly",WI.unlocalizedString("HttpOnly"),{minWidth:80,maxWidth:80,align:"center",});this._sameSiteColumn=new WI.TableColumn("sameSite",WI.unlocalizedString("SameSite"),{minWidth:40,maxWidth:80,initialWidth:70,align:"center",});this._table.addColumn(this._nameColumn);this._table.addColumn(this._valueColumn);this._table.addColumn(this._domainColumn);this._table.addColumn(this._pathColumn);this._table.addColumn(this._expiresColumn);this._table.addColumn(this._sizeColumn);this._table.addColumn(this._secureColumn);this._table.addColumn(this._httpOnlyColumn);this._table.addColumn(this._sameSiteColumn);if(!this._table.sortColumnIdentifier){this._table.sortOrder=WI.Table.SortOrder.Ascending;this._table.sortColumnIdentifier="name";} this.addSubview(this._table);this._table.element.addEventListener("keydown",this._handleTableKeyDown.bind(this));this._reloadCookies();} _getCookiesForHost(cookies,host) {let resourceMatchesStorageDomain=(resource)=>{let urlComponents=resource.urlComponents;return urlComponents&&urlComponents.host&&urlComponents.host===host;};let allResources=[];for(let frame of WI.networkManager.frames){allResources.push(frame.mainResource,...frame.resourceCollection);} let resourcesForDomain=allResources.filter(resourceMatchesStorageDomain);let cookiesForDomain=cookies.filter((cookie)=>{return resourcesForDomain.some((resource)=>{return WI.CookieStorageObject.cookieMatchesResourceURL(cookie,resource.url);});});return cookiesForDomain;} _generateSortComparator() {let sortColumnIdentifier=this._table.sortColumnIdentifier;if(!sortColumnIdentifier){this._sortComparator=null;return;} let comparator=null;switch(sortColumnIdentifier){case"name":case"value":case"domain":case"path":case"sameSite":comparator=(a,b)=>(a[sortColumnIdentifier]||"").extendedLocaleCompare(b[sortColumnIdentifier]||"");break;case"size":case"httpOnly":case"secure":comparator=(a,b)=>a[sortColumnIdentifier]-b[sortColumnIdentifier];break;case"expires":comparator=(a,b)=>{if(!a.expires) return 1;if(!b.expires) return-1;return a.expires-b.expires;};break;default:return;} let reverseFactor=this._table.sortOrder===WI.Table.SortOrder.Ascending?1:-1;this._sortComparator=(a,b)=>reverseFactor*comparator(a,b);} _showCookiePopover(targetElement,cookie,columnIdentifier){this._editingCookie=cookie;let options={};if(columnIdentifier){switch(columnIdentifier){case"name":case"value":case"domain":case"path":case"secure":options.focusField=columnIdentifier;break;case"expires":options.focusField=this._editingCookie.session?"session":"expires";break;case"httpOnly":options.focusField="http-only";break;case"sameSite":options.focusField="same-site";break;default:break;}} let popover=new WI.CookiePopover(this);popover.show(this._editingCookie,targetElement,[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MIN_X,WI.RectEdge.MAX_X],options);} async _willDismissCookiePopover(popover) {let editingCookie=this._editingCookie;this._editingCookie=null;let serializedData=popover.serializedData;if(!serializedData){InspectorFrontendHost.beep();return;} let cookieToSet=WI.Cookie.fromPayload(serializedData);let cookieProtocolPayload=cookieToSet.toProtocol();if(!cookieProtocolPayload){InspectorFrontendHost.beep();return;} let target=WI.assumingMainTarget();let promises=[];if(editingCookie) promises.push(target.PageAgent.deleteCookie(editingCookie.name,editingCookie.url));promises.push(target.PageAgent.setCookie(cookieProtocolPayload));promises.push(this._reloadCookies());await Promise.all(promises);let index=this._filteredCookies.findIndex((existingCookie)=>cookieToSet.equals(existingCookie));if(index>=0) this._table.selectRow(index);} _handleFilterBarFilterDidChange(event) {this._updateFilteredCookies();this._updateEmptyFilterResultsMessage();this._table.reloadData();} _handleSetCookieButtonClick(event) {this._showCookiePopover(this._setCookieButtonNavigationItem.element,null,"name");} _refreshButtonClicked(event) {this._reloadCookies();} _handleClearNavigationItemClicked(event) {let target=WI.assumingMainTarget();for(let cookie of this._cookies) target.PageAgent.deleteCookie(cookie.name,cookie.url);this._reloadCookies();} _reloadCookies() {let target=WI.assumingMainTarget();if(!target.hasCommand("Page.getCookies")) return;target.PageAgent.getCookies().then((payload)=>{this._cookies=this._getCookiesForHost(payload.cookies.map(WI.Cookie.fromPayload),this.representedObject.host);this._updateSort();this._updateFilteredCookies();this._updateEmptyFilterResultsMessage();this._table.reloadData();}).catch((error)=>{console.error("Could not fetch cookies: ",error);});} _updateSort() {if(!this._sortComparator) return;this._cookies.sort(this._sortComparator);} _updateFilteredCookies() {this._filteredCookies=this._cookies;let filterBar=this._filterBarNavigationItem.filterBar;filterBar.invalid=false;let filterText=filterBar.filters.text;if(!filterText) return;let regex=WI.SearchUtilities.filterRegExpForString(filterText,WI.SearchUtilities.defaultSettings);if(!regex){filterBar.invalid=true;return;} this._filteredCookies=this._filteredCookies.filter((cookie)=>{for(let column of this._table.columns){let text=this._formatCookiePropertyForColumn(cookie,column);if(text&®ex.test(text)) return true;} return false;});} _updateEmptyFilterResultsMessage() {if(this._filteredCookies.length||!this._filterBarNavigationItem.filterBar.filters.text){if(this._emptyFilterResultsMessageElement) this._emptyFilterResultsMessageElement.remove();this._emptyFilterResultsMessageElement=null;}else{if(!this._emptyFilterResultsMessageElement){let buttonElement=document.createElement("button");buttonElement.textContent=WI.UIString("Clear Filters");buttonElement.addEventListener("click",(event)=>{this._filterBarNavigationItem.filterBar.clear();});this._emptyFilterResultsMessageElement=WI.createMessageTextView(WI.UIString("No Filter Results"));this._emptyFilterResultsMessageElement.appendChild(buttonElement);} this.element.appendChild(this._emptyFilterResultsMessageElement);}} _handleTableKeyDown(event) {if(event.keyCode===WI.KeyboardShortcut.Key.Backspace.keyCode||event.keyCode===WI.KeyboardShortcut.Key.Delete.keyCode){if(InspectorBackend.hasCommand("Page.deleteCookie")) this._table.removeSelectedRows();else InspectorFrontendHost.beep();}} _cookiesAtIndexes(indexes) {if(!this._filteredCookies.length) return[];return indexes.map((index)=>this._filteredCookies[index]);} _formatCookiesAsText(cookies) {let visibleColumns=this._table.columns.filter((column)=>!column.hidden);if(!visibleColumns.length) return"";let lines=cookies.map((cookie)=>{const usePunctuation=false;let values=visibleColumns.map((column)=>this._formatCookiePropertyForColumn(cookie,column,usePunctuation));return values.join("\t");});return lines.join("\n");} _formatCookiePropertyForColumn(cookie,column,usePunctuation=true) {const checkmark="\u2713";const missingValue=usePunctuation?emDash:"";const missingCheckmark=usePunctuation?zeroWidthSpace:"";switch(column.identifier){case"name":return cookie.name;case"value":return cookie.value;case"domain":return cookie.domain||missingValue;case"path":return cookie.path||missingValue;case"expires":return(!cookie.session&&cookie.expires)?cookie.expires.toLocaleString():WI.UIString("Session");case"size":return Number.bytesToString(cookie.size);case"secure":return cookie.secure?checkmark:missingCheckmark;case"httpOnly":return cookie.httpOnly?checkmark:missingCheckmark;case"sameSite":return cookie.sameSite===WI.Cookie.SameSiteType.None?missingValue:WI.Cookie.displayNameForSameSiteType(cookie.sameSite);} return"";}};WI.CookieType={Request:0,Response:1};WI.CookieStorageTreeElement=class CookieStorageTreeElement extends WI.StorageTreeElement {constructor(representedObject) {super("cookie-icon",WI.displayNameForHost(representedObject.host),representedObject);} get name() {return WI.displayNameForHost(this.representedObject.host);} get categoryName() {return WI.UIString("Cookies");}};WI.CreateAuditPopover=class CreateAuditPopover extends WI.Popover {constructor(delegate) {super(delegate);this._audit=null;this._targetElement=null;this._preferredEdges=null;this.windowResizeHandler=this._presentOverTargetElement.bind(this);} get audit(){return this._audit;} show(targetElement,preferredEdges) {this._targetElement=targetElement;this._preferredEdges=preferredEdges;let contentElement=document.createElement("div");contentElement.classList.add("create-audit-content");let label=contentElement.appendChild(document.createElement("div"));label.classList.add("label");label.textContent=WI.UIString("Create audit:");let editorWrapper=contentElement.appendChild(document.createElement("div"));editorWrapper.classList.add("editor-wrapper");this._typeSelectElement=editorWrapper.appendChild(document.createElement("select"));let createOption=(text,value)=>{let optionElement=this._typeSelectElement.appendChild(document.createElement("option"));optionElement.textContent=text;optionElement.value=value;return optionElement;};createOption(WI.UIString("Test Case","Test Case @ Audit Tab Navigation Sidebar","Dropdown option inside the popover used to creating an audit test case."),"test-case");createOption(WI.UIString("Group","Group @ Audit Tab Navigation Sidebar","Dropdown option inside the popover used to creating an audit group."),"group");this._nameInputElement=editorWrapper.appendChild(document.createElement("input"));this._nameInputElement.placeholder=WI.UIString("Name");this._nameInputElement.addEventListener("keydown",(event)=>{if(event.keyCode===WI.KeyboardShortcut.Key.Enter.keyCode||event.keyCode===WI.KeyboardShortcut.Key.Escape.keyCode){event.stop();this.dismiss();}});editorWrapper.appendChild(WI.ReferencePage.AuditTab.CreatingAudits.createLinkElement());this.content=contentElement;this._presentOverTargetElement();} dismiss() {const placeholderTestFunctionString=WI.DefaultAudits.newAuditPlaceholder.toString();let type=this._typeSelectElement.value;let name=this._nameInputElement.value;if(type&&name){switch(type){case"test-case":this._audit=new WI.AuditTestCase(name,placeholderTestFunctionString);break;case"group":this._audit=new WI.AuditTestGroup(name,[new WI.AuditTestCase(WI.unlocalizedString("test-case"),placeholderTestFunctionString)]);break;}} super.dismiss();} _presentOverTargetElement() {if(!this._targetElement) return;let targetFrame=WI.Rect.rectFromClientRect(this._targetElement.getBoundingClientRect());this.present(targetFrame.pad(2),this._preferredEdges);}};WI.CubicBezierTimingFunctionEditor=class CubicBezierTimingFunctionEditor extends WI.Object {constructor() {super();this._element=document.createElement("div");this._element.classList.add("cubic-bezier-timing-function-editor");this._element.dir="ltr";var editorWidth=184;var editorHeight=200;this._padding=25;this._controlHandleRadius=7;this._previewWidth=editorWidth-(this._controlHandleRadius*2);this._previewHeight=editorHeight-(this._controlHandleRadius*2)-(this._padding*2);this._previewContainer=this._element.createChild("div","preview");this._previewContainer.title=WI.UIString("Restart animation");this._previewContainer.addEventListener("mousedown",this._resetPreviewAnimation.bind(this));this._previewElement=this._previewContainer.createChild("div");this._timingElement=this._element.createChild("div","timing");this._curveContainer=this._element.appendChild(createSVGElement("svg"));this._curveContainer.setAttribute("width",editorWidth);this._curveContainer.setAttribute("height",editorHeight);this._curveContainer.classList.add("curve");let svgGroup=this._curveContainer.appendChild(createSVGElement("g"));svgGroup.setAttribute("transform","translate(0, "+this._padding+")");let linearCurveElement=svgGroup.appendChild(createSVGElement("line"));linearCurveElement.classList.add("linear");linearCurveElement.setAttribute("x1",this._controlHandleRadius);linearCurveElement.setAttribute("y1",this._previewHeight+this._controlHandleRadius);linearCurveElement.setAttribute("x2",this._previewWidth+this._controlHandleRadius);linearCurveElement.setAttribute("y2",this._controlHandleRadius);this._cubicBezierCurveElement=svgGroup.appendChild(createSVGElement("path"));this._cubicBezierCurveElement.classList.add("cubic-bezier");function createControl(x1,y1) {x1+=this._controlHandleRadius;y1+=this._controlHandleRadius;let line=svgGroup.appendChild(createSVGElement("line"));line.classList.add("control-line");line.setAttribute("x1",x1);line.setAttribute("y1",y1);line.setAttribute("x2",x1);line.setAttribute("y2",y1);let handle=svgGroup.appendChild(createSVGElement("circle"));handle.classList.add("control-handle");return{point:null,line,handle};} this._inControl=createControl.call(this,0,this._previewHeight);this._outControl=createControl.call(this,this._previewWidth,0);this._numberInputContainer=this._element.createChild("div","number-input-container");function createCoordinateInput(id,{min,max}={}) {let key="_"+id+"Input";this[key]=this._numberInputContainer.createChild("input");this[key].type="number";this[key].step=0.01;if(!isNaN(min)) this[key].min=min;if(!isNaN(max)) this[key].max=max;this[key].addEventListener("input",this._handleNumberInputInput.bind(this));this[key].addEventListener("keydown",this._handleNumberInputKeydown.bind(this));} createCoordinateInput.call(this,"inX",{min:0,max:1});createCoordinateInput.call(this,"inY");createCoordinateInput.call(this,"outX",{min:0,max:1});createCoordinateInput.call(this,"outY");this._selectedControl=null;this._mouseDownPosition=null;this._curveContainer.addEventListener("mousedown",this);WI.addWindowKeydownListener(this);} get element() {return this._element;} set cubicBezierTimingFunction(cubicBezierTimingFunction) {if(!cubicBezierTimingFunction) return;var isCubicBezier=cubicBezierTimingFunction instanceof WI.CubicBezierTimingFunction;if(!isCubicBezier) return;this._cubicBezierTimingFunction=cubicBezierTimingFunction;this._updatePreview();} get cubicBezierTimingFunction() {return this._cubicBezierTimingFunction;} removeListeners() {WI.removeWindowKeydownListener(this);} handleEvent(event) {switch(event.type){case"mousedown":this._handleMousedown(event);break;case"mousemove":this._handleMousemove(event);break;case"mouseup":this._handleMouseup(event);break;}} handleKeydownEvent(event) {if(!this._selectedControl||!this._element.parentNode) return false;let horizontal=0;let vertical=0;switch(event.keyCode){case WI.KeyboardShortcut.Key.Up.keyCode:vertical=-1;break;case WI.KeyboardShortcut.Key.Right.keyCode:horizontal=1;break;case WI.KeyboardShortcut.Key.Down.keyCode:vertical=1;break;case WI.KeyboardShortcut.Key.Left.keyCode:horizontal=-1;break;default:return false;} if(event.shiftKey){horizontal*=10;vertical*=10;} vertical*=this._previewWidth/100;horizontal*=this._previewHeight/100;this._selectedControl.point.x=Number.constrain(this._selectedControl.point.x+horizontal,0,this._previewWidth);this._selectedControl.point.y+=vertical;this._updateControl(this._selectedControl);this._updateCubicBezierTimingFunction();return true;} _handleMousedown(event) {if(event.button!==0) return;event.stop();window.addEventListener("mousemove",this,true);window.addEventListener("mouseup",this,true);this._previewContainer.classList.remove("animate");this._timingElement.classList.remove("animate");this._updateControlPointsForMouseEvent(event,true);} _handleMousemove(event) {this._updateControlPointsForMouseEvent(event);} _handleMouseup(event) {this._selectedControl.handle.classList.remove("selected");this._mouseDownPosition=null;this._triggerPreviewAnimation();window.removeEventListener("mousemove",this,true);window.removeEventListener("mouseup",this,true);} _updateControlPointsForMouseEvent(event,calculateSelectedControlPoint) {var point=WI.Point.fromEventInElement(event,this._curveContainer);point.x=Number.constrain(point.x-this._controlHandleRadius,0,this._previewWidth);point.y-=this._controlHandleRadius+this._padding;if(calculateSelectedControlPoint){this._mouseDownPosition=point;if(this._inControl.point.distance(point)Math.abs(this._mouseDownPosition.y-point.y)) point.y=this._mouseDownPosition.y;else point.x=this._mouseDownPosition.x;} this._selectedControl.point=point;this._selectedControl.handle.classList.add("selected");this._updateCubicBezierTimingFunction();} _updateCubicBezierTimingFunction() {function round(num) {return Math.round(num*100)/100;} var inValueX=round(this._inControl.point.x/this._previewWidth);var inValueY=round(1-(this._inControl.point.y/this._previewHeight));var outValueX=round(this._outControl.point.x/this._previewWidth);var outValueY=round(1-(this._outControl.point.y/this._previewHeight));this._cubicBezierTimingFunction=new WI.CubicBezierTimingFunction(inValueX,inValueY,outValueX,outValueY);this._updateCoordinateInputs();this.dispatchEventToListeners(WI.CubicBezierTimingFunctionEditor.Event.CubicBezierTimingFunctionChanged,{cubicBezierTimingFunction:this._cubicBezierTimingFunction});} _updateCoordinateInputs() {var r=this._controlHandleRadius;var inControlX=this._inControl.point.x+r;var inControlY=this._inControl.point.y+r;var outControlX=this._outControl.point.x+r;var outControlY=this._outControl.point.y+r;var path=`M ${r} ${this._previewHeight + r} C ${inControlX} ${inControlY} ${outControlX} ${outControlY} ${this._previewWidth + r} ${r}`;this._cubicBezierCurveElement.setAttribute("d",path);this._updateControl(this._inControl);this._updateControl(this._outControl);this._inXInput.value=this._cubicBezierTimingFunction.inPoint.x;this._inYInput.value=this._cubicBezierTimingFunction.inPoint.y;this._outXInput.value=this._cubicBezierTimingFunction.outPoint.x;this._outYInput.value=this._cubicBezierTimingFunction.outPoint.y;} _updateControl(control) {control.handle.setAttribute("cx",control.point.x+this._controlHandleRadius);control.handle.setAttribute("cy",control.point.y+this._controlHandleRadius);control.line.setAttribute("x2",control.point.x+this._controlHandleRadius);control.line.setAttribute("y2",control.point.y+this._controlHandleRadius);} _updatePreview() {this._inControl.point=new WI.Point(this._cubicBezierTimingFunction.inPoint.x*this._previewWidth,(1-this._cubicBezierTimingFunction.inPoint.y)*this._previewHeight);this._outControl.point=new WI.Point(this._cubicBezierTimingFunction.outPoint.x*this._previewWidth,(1-this._cubicBezierTimingFunction.outPoint.y)*this._previewHeight);this._updateCoordinateInputs();this._triggerPreviewAnimation();} _triggerPreviewAnimation() {this._previewElement.style.animationTimingFunction=this._cubicBezierTimingFunction.toString();this._previewContainer.classList.add("animate");this._timingElement.classList.add("animate");} _resetPreviewAnimation() {var parent=this._previewElement.parentNode;parent.removeChild(this._previewElement);parent.appendChild(this._previewElement);this._element.removeChild(this._timingElement);this._element.appendChild(this._timingElement);} _handleNumberInputInput(event) {this._changeCoordinateForInput(event.target,event.target.value);} _handleNumberInputKeydown(event) {let shift=0;if(event.keyIdentifier==="Up") shift=0.01;else if(event.keyIdentifier==="Down") shift=-0.01;if(!shift) return;if(event.shiftKey) shift*=10;event.preventDefault();this._changeCoordinateForInput(event.target,parseFloat(event.target.value)+shift);} _changeCoordinateForInput(target,value) {value=Math.round(value*100)/100;switch(target){case this._inXInput:this._cubicBezierTimingFunction.inPoint.x=Number.constrain(value,0,1);break;case this._inYInput:this._cubicBezierTimingFunction.inPoint.y=value;break;case this._outXInput:this._cubicBezierTimingFunction.outPoint.x=Number.constrain(value,0,1);break;case this._outYInput:this._cubicBezierTimingFunction.outPoint.y=value;break;default:return;} this._updatePreview();this.dispatchEventToListeners(WI.CubicBezierTimingFunctionEditor.Event.CubicBezierTimingFunctionChanged,{cubicBezierTimingFunction:this._cubicBezierTimingFunction});}};WI.CubicBezierTimingFunctionEditor.Event={CubicBezierTimingFunctionChanged:"cubic-bezier-timing-function-editor-cubic-bezier-timing-function-changed"};WI.DOMBreakpointTreeElement=class DOMBreakpointTreeElement extends WI.BreakpointTreeElement {constructor(breakpoint,{classNames,title}={}) {if(!Array.isArray(classNames)) classNames=[];classNames.push("dom",breakpoint.type);if(!title) title=breakpoint.displayName;super(breakpoint,{classNames,title});}};WI.DOMEventsBreakdownView=class DOMEventsBreakdownView extends WI.View {constructor(domNodeOrEvents,{includeGraph}={}) {super();if(domNodeOrEvents instanceof WI.DOMNode){this._domNode=domNodeOrEvents;this._domNode.addEventListener(WI.DOMNode.Event.DidFireEvent,this._handleDOMNodeDidFireEvent,this);if(this._domNode.canEnterPowerEfficientPlaybackState()) this._domNode.addEventListener(WI.DOMNode.Event.PowerEfficientPlaybackStateChanged,this._handleDOMNodePowerEfficientPlaybackStateChanged,this);this._domEvents=null;}else{this._domNode=null;this._domEvents=domNodeOrEvents;} this._includeGraph=includeGraph||false;this._tableBodyElement=null;this.element.classList.add("dom-events-breakdown");} initialLayout() {super.initialLayout();let tableElement=this.element.appendChild(document.createElement("table"));let headElement=tableElement.appendChild(document.createElement("thead"));let headRowElement=headElement.appendChild(document.createElement("tr"));let eventHeadCell=headRowElement.appendChild(document.createElement("th"));eventHeadCell.textContent=WI.UIString("Event");if(this._includeGraph) headRowElement.appendChild(document.createElement("th"));let timeHeadCell=headRowElement.appendChild(document.createElement("th"));timeHeadCell.classList.add("time");timeHeadCell.textContent=WI.UIString("Time");let originatorHeadCell=headRowElement.appendChild(document.createElement("th"));originatorHeadCell.classList.add("originator");originatorHeadCell.textContent=WI.UIString("Originator");this._tableBodyElement=tableElement.appendChild(document.createElement("tbody"));} layout() {if(this.layoutReason!==WI.View.LayoutReason.Dirty) return;this._tableBodyElement.removeChildren();let domEvents=this._domEvents||this._domNode.domEvents;let startTimestamp=domEvents[0].timestamp;let endTimestamp=domEvents.lastValue.timestamp;let totalTime=endTimestamp-startTimestamp;let styleAttribute=WI.resolvedLayoutDirection()===WI.LayoutDirection.LTR?"left":"right";function percentOfTotalTime(time){return time/totalTime*100;} let fullscreenRanges=[];let fullscreenDOMEvents=WI.DOMNode.getFullscreenDOMEvents(domEvents);for(let fullscreenDOMEvent of fullscreenDOMEvents){let{enabled}=fullscreenDOMEvent.data;if(enabled||!fullscreenRanges.length){fullscreenRanges.push({startTimestamp:enabled?fullscreenDOMEvent.timestamp:startTimestamp,});} fullscreenRanges.lastValue.endTimestamp=(enabled&&fullscreenDOMEvent===fullscreenDOMEvents.lastValue)?endTimestamp:fullscreenDOMEvent.timestamp;if(fullscreenDOMEvent.originator) fullscreenRanges.lastValue.originator=fullscreenDOMEvent.originator;} let powerEfficientPlaybackRanges=this._domNode?this._domNode.powerEfficientPlaybackRanges:[];for(let domEvent of domEvents){let rowElement=this._tableBodyElement.appendChild(document.createElement("tr"));let nameCell=rowElement.appendChild(document.createElement("td"));nameCell.classList.add("name");nameCell.textContent=domEvent.eventName;if(this._includeGraph){let graphCell=rowElement.appendChild(document.createElement("td"));graphCell.classList.add("graph");let fullscreenRange=fullscreenRanges.find((range)=>domEvent.timestamp>=range.startTimestamp&&domEvent.timestamp<=range.endTimestamp);if(fullscreenRange){let fullscreenArea=graphCell.appendChild(document.createElement("div"));fullscreenArea.classList.add("area","fullscreen");fullscreenArea.style.setProperty(styleAttribute,percentOfTotalTime(fullscreenRange.startTimestamp-startTimestamp)+"%");fullscreenArea.style.setProperty("width",percentOfTotalTime(fullscreenRange.endTimestamp-fullscreenRange.startTimestamp)+"%");if(fullscreenRange.originator) fullscreenArea.title=WI.UIString("Full-Screen from \u201C%s\u201D").format(fullscreenRange.originator.displayName);else fullscreenArea.title=WI.UIString("Full-Screen");} let powerEfficientPlaybackRange=powerEfficientPlaybackRanges.find((range)=>domEvent.timestamp>=range.startTimestamp&&domEvent.timestamp<=range.endTimestamp);if(powerEfficientPlaybackRange){let powerEfficientPlaybackArea=graphCell.appendChild(document.createElement("div"));powerEfficientPlaybackArea.classList.add("area","power-efficient-playback");powerEfficientPlaybackArea.title=WI.UIString("Power Efficient Playback");powerEfficientPlaybackArea.style.setProperty(styleAttribute,percentOfTotalTime(powerEfficientPlaybackRange.startTimestamp-startTimestamp)+"%");powerEfficientPlaybackArea.style.setProperty("width",percentOfTotalTime(powerEfficientPlaybackRange.endTimestamp-powerEfficientPlaybackRange.startTimestamp)+"%");} let graphImage=graphCell.appendChild(document.createElement("img"));graphImage.style.setProperty(styleAttribute,`calc(${percentOfTotalTime(domEvent.timestamp - startTimestamp)}% - (var(--img-size) / 2))`);if(WI.DOMNode.isPlayEvent(domEvent.eventName)) graphImage.src="Images/EventPlay.svg";else if(WI.DOMNode.isPauseEvent(domEvent.eventName)) graphImage.src="Images/EventPause.svg";else if(WI.DOMNode.isStopEvent(domEvent.eventName)) graphImage.src="Images/EventStop.svg";else graphImage.src="Images/EventProcessing.svg";} let timeCell=rowElement.appendChild(document.createElement("td"));timeCell.classList.add("time");const higherResolution=true;timeCell.textContent=Number.secondsToString(domEvent.timestamp,higherResolution);let originatorCell=rowElement.appendChild(document.createElement("td"));originatorCell.classList.add("originator");if(domEvent.originator){originatorCell.appendChild(WI.linkifyNodeReference(domEvent.originator));rowElement.classList.add("inherited");this.element.classList.add("has-inherited");}}} _handleDOMNodeDidFireEvent(event) {this.needsLayout();} _handleDOMNodePowerEfficientPlaybackStateChanged(event) {this.needsLayout();}};WI.DOMNodeDetailsSidebarPanel=class DOMNodeDetailsSidebarPanel extends WI.DOMDetailsSidebarPanel {constructor() {super("dom-node-details",WI.UIString("Node"));this._eventListenerGroupingMethodSetting=new WI.Setting("dom-node-event-listener-grouping-method",WI.DOMNodeDetailsSidebarPanel.EventListenerGroupingMethod.Event);this.element.classList.add("dom-node");this._nodeRemoteObject=null;} closed() {if(this.didInitialLayout){WI.domManager.removeEventListener(WI.DOMManager.Event.AttributeModified,this._attributesChanged,this);WI.domManager.removeEventListener(WI.DOMManager.Event.AttributeRemoved,this._attributesChanged,this);WI.domManager.removeEventListener(WI.DOMManager.Event.CharacterDataModified,this._characterDataModified,this);WI.domManager.removeEventListener(WI.DOMManager.Event.CustomElementStateChanged,this._customElementStateChanged,this);} super.closed();} initialLayout() {super.initialLayout();WI.domManager.addEventListener(WI.DOMManager.Event.AttributeModified,this._attributesChanged,this);WI.domManager.addEventListener(WI.DOMManager.Event.AttributeRemoved,this._attributesChanged,this);WI.domManager.addEventListener(WI.DOMManager.Event.CharacterDataModified,this._characterDataModified,this);WI.domManager.addEventListener(WI.DOMManager.Event.CustomElementStateChanged,this._customElementStateChanged,this);this._identityNodeTypeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Type"));this._identityNodeNameRow=new WI.DetailsSectionSimpleRow(WI.UIString("Name"));this._identityNodeValueRow=new WI.DetailsSectionSimpleRow(WI.UIString("Value"));this._identityNodeContentSecurityPolicyHashRow=new WI.DetailsSectionSimpleRow(WI.UIString("CSP Hash"));var identityGroup=new WI.DetailsSectionGroup([this._identityNodeTypeRow,this._identityNodeNameRow,this._identityNodeValueRow,this._identityNodeContentSecurityPolicyHashRow]);var identitySection=new WI.DetailsSection("dom-node-identity",WI.UIString("Identity"),[identityGroup]);this.contentView.element.appendChild(identitySection.element);this._attributesDataGridRow=new WI.DetailsSectionDataGridRow(null,WI.UIString("No Attributes"));var attributesGroup=new WI.DetailsSectionGroup([this._attributesDataGridRow]);var attributesSection=new WI.DetailsSection("dom-node-attributes",WI.UIString("Attributes"),[attributesGroup]);this.contentView.element.appendChild(attributesSection.element);if(InspectorBackend.hasCommand("DOM.resolveNode")){this._propertiesRow=new WI.DetailsSectionRow;let propertiesGroup=new WI.DetailsSectionGroup([this._propertiesRow]);let propertiesSection=new WI.DetailsSection("dom-node-properties",WI.UIString("Properties"),[propertiesGroup]);this.contentView.element.appendChild(propertiesSection.element);} let eventListenersFilterElement=WI.ImageUtilities.useSVGSymbol("Images/Filter.svg","filter",WI.UIString("Grouping Method"));WI.addMouseDownContextMenuHandlers(eventListenersFilterElement,this._populateEventListenersFilterContextMenu.bind(this));this._eventListenersSectionGroup=new WI.DetailsSectionGroup;let eventListenersSection=new WI.DetailsSection("dom-node-event-listeners",WI.UIString("Event Listeners"),[this._eventListenersSectionGroup],eventListenersFilterElement);this.contentView.element.appendChild(eventListenersSection.element);if(InspectorBackend.hasCommand("DOM.getDataBindingsForNode")){this._dataBindingsSection=new WI.DetailsSection("dom-node-data-bindings",WI.UIString("Data Bindings"),[]);this.contentView.element.appendChild(this._dataBindingsSection.element);} if(InspectorBackend.hasCommand("DOM.getAssociatedDataForNode")){this._associatedDataGrid=new WI.DetailsSectionRow(WI.UIString("No Associated Data"));let associatedDataGroup=new WI.DetailsSectionGroup([this._associatedDataGrid]);let associatedSection=new WI.DetailsSection("dom-node-associated-data",WI.UIString("Associated Data"),[associatedDataGroup]);this.contentView.element.appendChild(associatedSection.element);} if(this._accessibilitySupported()){this._accessibilityEmptyRow=new WI.DetailsSectionRow(WI.UIString("No Accessibility Information"));this._accessibilityNodeActiveDescendantRow=new WI.DetailsSectionSimpleRow(WI.UIString("Shared Focus"));this._accessibilityNodeBusyRow=new WI.DetailsSectionSimpleRow(WI.UIString("Busy"));this._accessibilityNodeCheckedRow=new WI.DetailsSectionSimpleRow(WI.UIString("Checked"));this._accessibilityNodeChildrenRow=new WI.DetailsSectionSimpleRow(WI.UIString("Children"));this._accessibilityNodeControlsRow=new WI.DetailsSectionSimpleRow(WI.UIString("Controls"));this._accessibilityNodeCurrentRow=new WI.DetailsSectionSimpleRow(WI.UIString("Current"));this._accessibilityNodeDisabledRow=new WI.DetailsSectionSimpleRow(WI.UIString("Disabled"));this._accessibilityNodeExpandedRow=new WI.DetailsSectionSimpleRow(WI.UIString("Expanded"));this._accessibilityNodeFlowsRow=new WI.DetailsSectionSimpleRow(WI.UIString("Flows"));this._accessibilityNodeFocusedRow=new WI.DetailsSectionSimpleRow(WI.UIString("Focused"));this._accessibilityNodeHeadingLevelRow=new WI.DetailsSectionSimpleRow(WI.UIString("Heading Level"));this._accessibilityNodehierarchyLevelRow=new WI.DetailsSectionSimpleRow(WI.UIString("Hierarchy Level"));this._accessibilityNodeIgnoredRow=new WI.DetailsSectionSimpleRow(WI.UIString("Ignored"));this._accessibilityNodeInvalidRow=new WI.DetailsSectionSimpleRow(WI.UIString("Invalid"));this._accessibilityNodeLiveRegionStatusRow=new WI.DetailsSectionSimpleRow(WI.UIString("Live"));this._accessibilityNodeMouseEventRow=new WI.DetailsSectionSimpleRow("");this._accessibilityNodeLabelRow=new WI.DetailsSectionSimpleRow(WI.UIString("Label"));this._accessibilityNodeOwnsRow=new WI.DetailsSectionSimpleRow(WI.UIString("Owns"));this._accessibilityNodeParentRow=new WI.DetailsSectionSimpleRow(WI.UIString("Parent"));this._accessibilityNodePressedRow=new WI.DetailsSectionSimpleRow(WI.UIString("Pressed"));this._accessibilityNodeReadonlyRow=new WI.DetailsSectionSimpleRow(WI.UIString("Readonly"));this._accessibilityNodeRequiredRow=new WI.DetailsSectionSimpleRow(WI.UIString("Required"));this._accessibilityNodeRoleRow=new WI.DetailsSectionSimpleRow(WI.UIString("Role"));this._accessibilityNodeSelectedRow=new WI.DetailsSectionSimpleRow(WI.UIString("Selected"));this._accessibilityNodeSelectedChildrenRow=new WI.DetailsSectionSimpleRow(WI.UIString("Selected Items"));this._accessibilityGroup=new WI.DetailsSectionGroup([this._accessibilityEmptyRow]);var accessibilitySection=new WI.DetailsSection("dom-node-accessibility",WI.UIString("Accessibility"),[this._accessibilityGroup]);this.contentView.element.appendChild(accessibilitySection.element);}} layout() {super.layout();if(!this.domNode||this.domNode.destroyed) return;this._refreshIdentity();this._refreshAttributes();this._refreshProperties();this._refreshEventListeners();this._refreshDataBindings();this._refreshAssociatedData();this._refreshAccessibility();} sizeDidChange() {super.sizeDidChange(); this._attributesDataGridRow.sizeDidChange();} attached() {super.attached();WI.DOMNode.addEventListener(WI.DOMNode.Event.EventListenersChanged,this._eventListenersChanged,this);} detached() {WI.DOMNode.removeEventListener(WI.DOMNode.Event.EventListenersChanged,this._eventListenersChanged,this);super.detached();} _accessibilitySupported() {return InspectorBackend.hasCommand("DOM.getAccessibilityPropertiesForNode");} _refreshIdentity() {const domNode=this.domNode;this._identityNodeTypeRow.value=this._nodeTypeDisplayName();this._identityNodeNameRow.value=domNode.nodeNameInCorrectCase();this._identityNodeValueRow.value=domNode.nodeValue();this._identityNodeContentSecurityPolicyHashRow.value=domNode.contentSecurityPolicyHash();} _refreshAttributes() {let domNode=this.domNode;if(!domNode||!domNode.hasAttributes()){this._attributesDataGridRow.dataGrid=null;return;} let dataGrid=this._attributesDataGridRow.dataGrid;if(!dataGrid){const columns={name:{title:WI.UIString("Name"),width:"30%"},value:{title:WI.UIString("Value")},};dataGrid=this._attributesDataGridRow.dataGrid=new WI.DataGrid(columns);} dataGrid.removeChildren();let attributes=domNode.attributes();attributes.sort((a,b)=>a.name.extendedLocaleCompare(b.name));for(let attribute of attributes){let dataGridNode=new WI.EditableDataGridNode(attribute);dataGridNode.addEventListener(WI.EditableDataGridNode.Event.ValueChanged,this._attributeNodeValueChanged,this);dataGrid.appendChild(dataGridNode);} dataGrid.updateLayoutIfNeeded();} _refreshProperties() {if(!this._propertiesRow) return;if(this._nodeRemoteObject){this._nodeRemoteObject.release();this._nodeRemoteObject=null;} let target=WI.assumingMainTarget();const objectGroup="dom-node-details-sidebar-properties-object-group";target.RuntimeAgent.releaseObjectGroup(objectGroup);let domNode=this.domNode;WI.RemoteObject.resolveNode(domNode,objectGroup).then((object)=>{if(this.domNode!==domNode) return;this._nodeRemoteObject=object;function inspectedPage_node_collectPrototypes() { var prototype=this;var result=[];var counter=1;while(prototype){result[counter++]=prototype;prototype=prototype.__proto__;} return result;} const args=undefined;const generatePreview=false;object.callFunction(inspectedPage_node_collectPrototypes,args,generatePreview,nodePrototypesReady.bind(this));}).catch((error)=>{if(this.domNode!==domNode) return;});function nodePrototypesReady(error,object,wasThrown) {if(error||wasThrown||!object) return;if(this.domNode!==domNode) return;object.getPropertyDescriptors(fillSection.bind(this),{ownProperties:true});} function fillSection(prototypes) {if(!prototypes) return;if(this.domNode!==domNode) return;let element=this._propertiesRow.element;element.removeChildren();let propertyPath=new WI.PropertyPath(this._nodeRemoteObject,"node");let initialSection=true;for(let i=0;i{if(this.domNode!==domNode) return;if(!dataBindings.length){let emptyRow=new WI.DetailsSectionRow(WI.UIString("No Data Bindings"));emptyRow.showEmptyMessage();this._dataBindingsSection.groups=[new WI.DetailsSectionGroup([emptyRow])];return;} let groups=[];for(let{binding,type,value}of dataBindings){groups.push(new WI.DetailsSectionGroup([new WI.DetailsSectionSimpleRow(WI.UIString("Binding"),binding),new WI.DetailsSectionSimpleRow(WI.UIString("Type"),type),new WI.DetailsSectionSimpleRow(WI.UIString("Value"),value),]));} this._dataBindingsSection.groups=groups;});} _refreshAssociatedData() {if(!this._associatedDataGrid) return;let target=WI.assumingMainTarget();const objectGroup="dom-node-details-sidebar-associated-data-object-group";target.RuntimeAgent.releaseObjectGroup(objectGroup);let domNode=this.domNode;if(!domNode) return;target.DOMAgent.getAssociatedDataForNode(domNode.id).then(({associatedData})=>{if(this.domNode!==domNode) return;if(!associatedData){this._associatedDataGrid.showEmptyMessage();return;} let expression=associatedData;const options={objectGroup,doNotPauseOnExceptionsAndMuteConsole:true,};WI.runtimeManager.evaluateInInspectedWindow(expression,options,(result,wasThrown)=>{if(!result){this._associatedDataGrid.showEmptyMessage();return;} this._associatedDataGrid.hideEmptyMessage();const propertyPath=null;const forceExpanding=true;let element=WI.FormattedValue.createObjectTreeOrFormattedValueForRemoteObject(result,propertyPath,forceExpanding);let objectTree=element.__objectTree;if(objectTree){objectTree.showOnlyJSON();objectTree.expand();} this._associatedDataGrid.element.appendChild(element);});});} _refreshAccessibility() {if(!this._accessibilitySupported()) return;var domNode=this.domNode;if(!domNode) return;var properties={};function booleanValueToLocalizedStringIfTrue(property){if(properties[property]) return WI.UIString("Yes");return"";} function booleanValueToLocalizedStringIfPropertyDefined(property){if(properties[property]!==undefined){if(properties[property]) return WI.UIString("Yes");else return WI.UIString("No");} return"";} function linkForNodeId(nodeId){var link=null;if(nodeId!==undefined&&typeof nodeId==="number"){var node=WI.domManager.nodeForId(nodeId);if(node) link=WI.linkifyAccessibilityNodeReference(node);} return link;} function linkListForNodeIds(nodeIds){if(!nodeIds) return null;const itemsToShow=5;let hasLinks=false;let listItemCount=0;let container=document.createElement("div");container.classList.add("list-container");let linkList=container.createChild("ul","node-link-list");let initiallyHiddenItems=[];for(let nodeId of nodeIds){let node=WI.domManager.nodeForId(nodeId);if(!node) continue;let link=WI.linkifyAccessibilityNodeReference(node);hasLinks=true;let li=linkList.createChild("li");li.appendChild(link);if(listItemCount>=itemsToShow){li.hidden=true;initiallyHiddenItems.push(li);} listItemCount++;} container.appendChild(linkList);if(listItemCount>itemsToShow){let moreNodesButton=container.createChild("button","expand-list-button");moreNodesButton.textContent=WI.UIString("%d More\u2026").format(listItemCount-itemsToShow);moreNodesButton.addEventListener("click",()=>{initiallyHiddenItems.forEach((element)=>{element.hidden=false;});moreNodesButton.remove();});} if(hasLinks) return container;return null;} function accessibilityPropertiesCallback(accessibilityProperties){if(this.domNode!==domNode) return;properties=accessibilityProperties;if(accessibilityProperties&&accessibilityProperties.exists){var activeDescendantLink=linkForNodeId(accessibilityProperties.activeDescendantNodeId);var busy=booleanValueToLocalizedStringIfPropertyDefined("busy");var checked="";if(accessibilityProperties.checked!==undefined){if(accessibilityProperties.checked===InspectorBackend.Enum.DOM.AccessibilityPropertiesChecked.True) checked=WI.UIString("Yes");else if(accessibilityProperties.checked===InspectorBackend.Enum.DOM.AccessibilityPropertiesChecked.Mixed) checked=WI.UIString("Mixed");else checked=WI.UIString("No");} var childNodeLinkList=linkListForNodeIds(accessibilityProperties.childNodeIds);var controlledNodeLinkList=linkListForNodeIds(accessibilityProperties.controlledNodeIds);var current="";switch(accessibilityProperties.current){case InspectorBackend.Enum.DOM.AccessibilityPropertiesCurrent.True:current=WI.UIString("True");break;case InspectorBackend.Enum.DOM.AccessibilityPropertiesCurrent.Page:current=WI.UIString("Page");break;case InspectorBackend.Enum.DOM.AccessibilityPropertiesCurrent.Location:current=WI.UIString("Location");break;case InspectorBackend.Enum.DOM.AccessibilityPropertiesCurrent.Step:current=WI.UIString("Step");break;case InspectorBackend.Enum.DOM.AccessibilityPropertiesCurrent.Date:current=WI.UIString("Date");break;case InspectorBackend.Enum.DOM.AccessibilityPropertiesCurrent.Time:current=WI.UIString("Time");break;default:current="";} var disabled=booleanValueToLocalizedStringIfTrue("disabled");var expanded=booleanValueToLocalizedStringIfPropertyDefined("expanded");var flowedNodeLinkList=linkListForNodeIds(accessibilityProperties.flowedNodeIds);var focused=booleanValueToLocalizedStringIfPropertyDefined("focused");var ignored="";if(accessibilityProperties.ignored){ignored=WI.UIString("Yes");if(accessibilityProperties.hidden) ignored=WI.UIString("%s (hidden)").format(ignored);else if(accessibilityProperties.ignoredByDefault) ignored=WI.UIString("%s (default)").format(ignored);} var invalid="";if(accessibilityProperties.invalid===InspectorBackend.Enum.DOM.AccessibilityPropertiesInvalid.True) invalid=WI.UIString("Yes");else if(accessibilityProperties.invalid===InspectorBackend.Enum.DOM.AccessibilityPropertiesInvalid.Grammar) invalid=WI.UIString("Grammar");else if(accessibilityProperties.invalid===InspectorBackend.Enum.DOM.AccessibilityPropertiesInvalid.Spelling) invalid=WI.UIString("Spelling");var label=accessibilityProperties.label;var liveRegionStatus="";var liveRegionStatusNode=null;var liveRegionStatusToken=accessibilityProperties.liveRegionStatus;switch(liveRegionStatusToken){case InspectorBackend.Enum.DOM.AccessibilityPropertiesLiveRegionStatus.Assertive:liveRegionStatus=WI.UIString("Assertive");break;case InspectorBackend.Enum.DOM.AccessibilityPropertiesLiveRegionStatus.Polite:liveRegionStatus=WI.UIString("Polite");break;default:liveRegionStatus="";} if(liveRegionStatus){var liveRegionRelevant=accessibilityProperties.liveRegionRelevant;if(liveRegionRelevant&&liveRegionRelevant.length){if(liveRegionRelevant.length===3&&liveRegionRelevant[0]===InspectorBackend.Enum.DOM.LiveRegionRelevant.Additions&&liveRegionRelevant[1]===InspectorBackend.Enum.DOM.LiveRegionRelevant.Removals&&liveRegionRelevant[2]===InspectorBackend.Enum.DOM.LiveRegionRelevant.Text) liveRegionRelevant=[WI.UIString("All Changes")];else{liveRegionRelevant=liveRegionRelevant.map(function(value){switch(value){case InspectorBackend.Enum.DOM.LiveRegionRelevant.Additions:return WI.UIString("Additions");case InspectorBackend.Enum.DOM.LiveRegionRelevant.Removals:return WI.UIString("Removals");case InspectorBackend.Enum.DOM.LiveRegionRelevant.Text:return WI.UIString("Text");default:return"\""+value+"\"";}});} liveRegionStatus+=" ("+liveRegionRelevant.join(", ")+")";} if(accessibilityProperties.liveRegionAtomic){liveRegionStatusNode=document.createElement("div");liveRegionStatusNode.className="value-with-clarification";liveRegionStatusNode.setAttribute("role","text");liveRegionStatusNode.append(liveRegionStatus);var clarificationNode=document.createElement("div");clarificationNode.className="clarification";clarificationNode.append(WI.UIString("Region announced in its entirety."));liveRegionStatusNode.appendChild(clarificationNode);}} var mouseEventNodeId=accessibilityProperties.mouseEventNodeId;var mouseEventTextValue="";var mouseEventNodeLink=null;if(mouseEventNodeId){if(mouseEventNodeId===accessibilityProperties.nodeId) mouseEventTextValue=WI.UIString("Yes");else mouseEventNodeLink=linkForNodeId(mouseEventNodeId);} var ownedNodeLinkList=linkListForNodeIds(accessibilityProperties.ownedNodeIds);var parentNodeLink=linkForNodeId(accessibilityProperties.parentNodeId);var pressed=booleanValueToLocalizedStringIfPropertyDefined("pressed");var readonly=booleanValueToLocalizedStringIfTrue("readonly");var required=booleanValueToLocalizedStringIfPropertyDefined("required");var role=accessibilityProperties.role;let hasPopup=accessibilityProperties.isPopupButton;let roleType=null;let buttonType=null;let buttonTypePopupString=WI.UIString("popup");let buttonTypeToggleString=WI.UIString("toggle");let buttonTypePopupToggleString=WI.UIString("popup, toggle");if(role===""||role==="unknown") role=WI.UIString("No matching ARIA role");else if(role){if(role==="button"){if(pressed) buttonType=buttonTypeToggleString; if(hasPopup) buttonType=buttonType?buttonTypePopupToggleString:buttonTypePopupString;} if(!domNode.getAttribute("role")) roleType=WI.UIString("default");else if(buttonType||domNode.getAttribute("role")!==role) roleType=WI.UIString("computed");if(buttonType&&roleType) role=WI.UIString("%s (%s, %s)").format(role,buttonType,roleType);else if(roleType||buttonType){let extraInfo=roleType||buttonType;role=WI.UIString("%s (%s)").format(role,extraInfo);}} var selected=booleanValueToLocalizedStringIfTrue("selected");var selectedChildNodeLinkList=linkListForNodeIds(accessibilityProperties.selectedChildNodeIds);var headingLevel=accessibilityProperties.headingLevel;var hierarchyLevel=accessibilityProperties.hierarchyLevel;this._accessibilityNodeActiveDescendantRow.value=activeDescendantLink||"";this._accessibilityNodeBusyRow.value=busy;this._accessibilityNodeCheckedRow.value=checked;this._accessibilityNodeChildrenRow.value=childNodeLinkList||"";this._accessibilityNodeControlsRow.value=controlledNodeLinkList||"";this._accessibilityNodeCurrentRow.value=current;this._accessibilityNodeDisabledRow.value=disabled;this._accessibilityNodeExpandedRow.value=expanded;this._accessibilityNodeFlowsRow.value=flowedNodeLinkList||"";this._accessibilityNodeFocusedRow.value=focused;this._accessibilityNodeHeadingLevelRow.value=headingLevel||"";this._accessibilityNodehierarchyLevelRow.value=hierarchyLevel||"";this._accessibilityNodeIgnoredRow.value=ignored;this._accessibilityNodeInvalidRow.value=invalid;this._accessibilityNodeLabelRow.value=label;this._accessibilityNodeLiveRegionStatusRow.value=liveRegionStatusNode||liveRegionStatus;this._accessibilityNodeMouseEventRow.label=mouseEventNodeLink?WI.UIString("Click Listener"):WI.UIString("Clickable");this._accessibilityNodeMouseEventRow.value=mouseEventNodeLink||mouseEventTextValue;this._accessibilityNodeOwnsRow.value=ownedNodeLinkList||"";this._accessibilityNodeParentRow.value=parentNodeLink||"";this._accessibilityNodePressedRow.value=pressed;this._accessibilityNodeReadonlyRow.value=readonly;this._accessibilityNodeRequiredRow.value=required;this._accessibilityNodeRoleRow.value=role;this._accessibilityNodeSelectedRow.value=selected;this._accessibilityNodeSelectedChildrenRow.label=WI.UIString("Selected Items");this._accessibilityNodeSelectedChildrenRow.value=selectedChildNodeLinkList||"";if(selectedChildNodeLinkList&&accessibilityProperties.selectedChildNodeIds.length===1) this._accessibilityNodeSelectedChildrenRow.label=WI.UIString("Selected Item");this._accessibilityGroup.rows=[this._accessibilityNodeIgnoredRow,this._accessibilityNodeRoleRow,this._accessibilityNodeLabelRow,this._accessibilityNodeParentRow,this._accessibilityNodeActiveDescendantRow,this._accessibilityNodeSelectedChildrenRow,this._accessibilityNodeChildrenRow,this._accessibilityNodeOwnsRow,this._accessibilityNodeControlsRow,this._accessibilityNodeFlowsRow,this._accessibilityNodeMouseEventRow,this._accessibilityNodeFocusedRow,this._accessibilityNodeHeadingLevelRow,this._accessibilityNodehierarchyLevelRow,this._accessibilityNodeBusyRow,this._accessibilityNodeLiveRegionStatusRow,this._accessibilityNodeCurrentRow,this._accessibilityNodeDisabledRow,this._accessibilityNodeInvalidRow,this._accessibilityNodeRequiredRow,this._accessibilityNodeCheckedRow,this._accessibilityNodeExpandedRow,this._accessibilityNodePressedRow,this._accessibilityNodeReadonlyRow,this._accessibilityNodeSelectedRow];this._accessibilityEmptyRow.hideEmptyMessage();}else{this._accessibilityGroup.rows=[this._accessibilityEmptyRow];this._accessibilityEmptyRow.showEmptyMessage();}} domNode.accessibilityProperties(accessibilityPropertiesCallback.bind(this));} _populateEventListenersFilterContextMenu(contextMenu) {let addGroupingMethodCheckboxItem=(label,groupingMethod)=>{contextMenu.appendCheckboxItem(label,()=>{this._eventListenerGroupingMethodSetting.value=groupingMethod;this._refreshEventListeners();},this._eventListenerGroupingMethodSetting.value===groupingMethod);};addGroupingMethodCheckboxItem(WI.UIString("Group by Event","Group by Event @ Node Event Listeners","Group DOM event listeners by DOM event"),WI.DOMNodeDetailsSidebarPanel.EventListenerGroupingMethod.Event);addGroupingMethodCheckboxItem(WI.UIString("Group by Target","Group by Target @ Node Event Listeners","Group DOM event listeners by DOM node"),WI.DOMNodeDetailsSidebarPanel.EventListenerGroupingMethod.Target);} _eventListenersChanged(event) {if(event.target===this.domNode||event.target.isAncestor(this.domNode)) this._refreshEventListeners();} _attributesChanged(event) {if(event.data.node!==this.domNode) return;this._refreshAttributes();this._refreshAccessibility();this._refreshDataBindings();} _attributeNodeValueChanged(event) {let change=event.data;let data=event.target.data;if(change.columnIdentifier==="name"){this.domNode.removeAttribute(data[change.columnIdentifier],(error)=>{this.domNode.setAttribute(change.value,`${change.value}="${data.value}"`);});}else if(change.columnIdentifier==="value") this.domNode.setAttributeValue(data.name,change.value);} _characterDataModified(event) {if(event.data.node!==this.domNode) return;this._identityNodeValueRow.value=this.domNode.nodeValue();} _customElementStateChanged(event) {if(event.data.node!==this.domNode) return;this._refreshIdentity();} _nodeTypeDisplayName() {switch(this.domNode.nodeType()){case Node.ELEMENT_NODE:{const nodeName=WI.UIString("Element");const state=this._customElementState();return state===null?nodeName:`${nodeName} (${state})`;} case Node.TEXT_NODE:return WI.UIString("Text Node");case Node.COMMENT_NODE:return WI.UIString("Comment");case Node.DOCUMENT_NODE:return WI.UIString("Document");case Node.DOCUMENT_TYPE_NODE:return WI.UIString("Document Type");case Node.DOCUMENT_FRAGMENT_NODE:return WI.UIString("Document Fragment");case Node.CDATA_SECTION_NODE:return WI.UIString("Character Data");case Node.PROCESSING_INSTRUCTION_NODE:return WI.UIString("Processing Instruction");default:console.error("Unknown DOM node type: ",this.domNode.nodeType());return this.domNode.nodeType();}} _customElementState() {const state=this.domNode.customElementState();switch(state){case WI.DOMNode.CustomElementState.Builtin:return null;case WI.DOMNode.CustomElementState.Custom:return WI.UIString("Custom");case WI.DOMNode.CustomElementState.Waiting:return WI.UIString("Undefined custom element");case WI.DOMNode.CustomElementState.Failed:return WI.UIString("Failed to upgrade");} console.error("Unknown DOM custom element state: ",state);return null;}};WI.DOMNodeDetailsSidebarPanel.EventListenerGroupingMethod={Event:"event",Target:"target",};WI.DOMNodeEventsContentView=class DOMNodeEventsContentView extends WI.ContentView {constructor(domNode) {const representedObject=null;super(representedObject);this._domNode=domNode;this.element.classList.add("dom-node-details","dom-events");this._breakdownView=null;} initialLayout() {super.initialLayout();this._breakdownView=new WI.DOMEventsBreakdownView(this._domNode,{includeGraph:true,});this.addSubview(this._breakdownView);}};WI.DOMNodeTreeElement=class DOMNodeTreeElement extends WI.GeneralTreeElement {constructor(domNode) {const subtitle=null;super("dom-node",domNode.displayName,subtitle,domNode,{hasChildren:true});this.status=WI.linkifyNodeReferenceElement(domNode,WI.createGoToArrowButton());this.tooltipHandledSeparately=true;} ondelete() { this.__deletedViaDeleteKeyboardShortcut=true;WI.domDebuggerManager.removeDOMBreakpointsForNode(this.representedObject);WI.domManager.removeEventListenerBreakpointsForNode(this.representedObject);return true;} populateContextMenu(contextMenu,event) {contextMenu.appendSeparator();WI.appendContextMenuItemsForDOMNodeBreakpoints(contextMenu,this.representedObject);contextMenu.appendSeparator();contextMenu.appendItem(WI.repeatedUIString.revealInDOMTree(),()=>{WI.domManager.inspectElement(this.representedObject.id,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});}};WI.DOMStorageContentView=class DOMStorageContentView extends WI.ContentView {constructor(representedObject) {super(representedObject);this.element.classList.add("dom-storage");representedObject.addEventListener(WI.DOMStorageObject.Event.ItemsCleared,this.itemsCleared,this);representedObject.addEventListener(WI.DOMStorageObject.Event.ItemAdded,this.itemAdded,this);representedObject.addEventListener(WI.DOMStorageObject.Event.ItemRemoved,this.itemRemoved,this);representedObject.addEventListener(WI.DOMStorageObject.Event.ItemUpdated,this.itemUpdated,this);let columns={};columns.key={title:WI.UIString("Key"),sortable:true};columns.displayValue={title:WI.UIString("Value"),sortable:true};this._dataGrid=new WI.DataGrid(columns,{beforeEditCallback:this._beforeEditCallback.bind(this),afterEditCallback:this._afterEditCallback.bind(this),copyCallback:this._dataGridCopy.bind(this),deleteCallback:this._deleteCallback.bind(this),});this._dataGrid.sortOrder=WI.DataGrid.SortOrder.Ascending;this._dataGrid.sortColumnIdentifier="key";this._dataGrid.allowsMultipleSelection=true;this._dataGrid.createSettings("dom-storage-content-view");this._dataGrid.addEventListener(WI.DataGrid.Event.SortChanged,this._sortDataGrid,this);this.addSubview(this._dataGrid);this._filterBarNavigationItem=new WI.FilterBarNavigationItem;this._filterBarNavigationItem.filterBar.addEventListener(WI.FilterBar.Event.FilterDidChange,this._handleFilterBarFilterDidChange,this);let clearButtonLabel=representedObject.isLocalStorage()?WI.UIString("Clear Local Storage"):WI.UIString("Clear Session Storage");this._clearButtonNavigationItem=new WI.ButtonNavigationItem("dom-storage-clear",clearButtonLabel,"Images/NavigationItemTrash.svg",15,15);this._clearButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._clearButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleClearNavigationItemClicked,this);this._populate();} get navigationItems() {return[this._filterBarNavigationItem,new WI.DividerNavigationItem,this._clearButtonNavigationItem,];} saveToCookie(cookie) {cookie.type=WI.ContentViewCookieType.DOMStorage;cookie.isLocalStorage=this.representedObject.isLocalStorage();cookie.host=this.representedObject.host;} get scrollableElements() {return[this._dataGrid.scrollContainer];} get canFocusFilterBar() {return true;} focusFilterBar() {this._filterBarNavigationItem.filterBar.focus();} itemsCleared(event) {this._dataGrid.removeChildren();this._dataGrid.addPlaceholderNode();} itemRemoved(event) {for(let node of this._dataGrid.children){if(node.data.key===event.data.key) return this._dataGrid.removeChild(node);} return null;} itemAdded(event) {let{key,value}=event.data;let displayValue=this._truncateValue(value);for(let node of this._dataGrid.children){if(node.data.key===key) return;} this._dataGrid.appendChild(new WI.DataGridNode({key,value,displayValue}));this._sortDataGrid();} itemUpdated(event) {let{key,newValue:value}=event.data;let displayValue=this._truncateValue(value);let keyFound=false;for(let childNode of this._dataGrid.children){if(childNode.data.key===key){if(keyFound){this._dataGrid.removeChild(childNode);continue;} keyFound=true;childNode.data.value=value;childNode.data.displayValue=displayValue;childNode.refresh();}} this._sortDataGrid();} _truncateValue(value) {return value.truncate(200);} _populate() {this.representedObject.getEntries(function(error,entries){if(error) return;for(let[key,value]of entries){if(!key||!value) continue;let displayValue=this._truncateValue(value);let node=new WI.DataGridNode({key,value,displayValue});this._dataGrid.appendChild(node);} this._dataGrid.addPlaceholderNode();this._sortDataGrid();}.bind(this));} _sortDataGrid() {let sortColumnIdentifier=this._dataGrid.sortColumnIdentifier||"key";function comparator(a,b) {return a.data[sortColumnIdentifier].extendedLocaleCompare(b.data[sortColumnIdentifier]);} this._dataGrid.sortNodesImmediately(comparator);} _deleteCallback() {for(let dataGridNode of this._dataGrid.selectedDataGridNodes){if(dataGridNode.isPlaceholderNode) continue;this._dataGrid.removeChild(dataGridNode);this.representedObject.removeItem(dataGridNode.data["key"]);}} _beforeEditCallback(editingNode,columnIdentifier) {switch(columnIdentifier){case"displayValue":editingNode.data.displayValue=editingNode.data.value;editingNode.refresh();break;}} _afterEditCallback(editingNode,columnIdentifier,oldText,newText,moveDirection) {var key=editingNode.data["key"].trim().removeWordBreakCharacters();var value=editingNode.data["displayValue"].trim().removeWordBreakCharacters();var previousValue=oldText.trim().removeWordBreakCharacters();var enteredValue=newText.trim().removeWordBreakCharacters();var hasUncommittedEdits=editingNode.__hasUncommittedEdits;var hasChange=previousValue!==enteredValue;var isEditingKey=columnIdentifier==="key";var isEditingValue=!isEditingKey;var domStorage=this.representedObject;if(isEditingValue){editingNode.data.value=value;editingNode.data.displayValue=this._truncateValue(value);editingNode.needsRefresh();} if(!hasChange&&!hasUncommittedEdits) return;if(hasChange&&!editingNode.__hasUncommittedEdits){editingNode.__hasUncommittedEdits=true;editingNode.__originalKey=isEditingKey?previousValue:key;editingNode.__originalValue=isEditingValue?previousValue:value;} function cleanup() {editingNode.element.classList.remove(WI.DOMStorageContentView.MissingKeyStyleClassName);editingNode.element.classList.remove(WI.DOMStorageContentView.MissingValueStyleClassName);editingNode.element.classList.remove(WI.DOMStorageContentView.DuplicateKeyStyleClassName);editingNode.__hasUncommittedEdits=undefined;editingNode.__originalKey=undefined;editingNode.__originalValue=undefined;} if(isEditingKey){if(key.length) editingNode.element.classList.remove(WI.DOMStorageContentView.MissingKeyStyleClassName);else editingNode.element.classList.add(WI.DOMStorageContentView.MissingKeyStyleClassName);}else if(isEditingValue){if(value.length) editingNode.element.classList.remove(WI.DOMStorageContentView.MissingValueStyleClassName);else editingNode.element.classList.add(WI.DOMStorageContentView.MissingValueStyleClassName);} var keyChanged=key!==editingNode.__originalKey;if(keyChanged){if(domStorage.entries.has(key)) editingNode.element.classList.add(WI.DOMStorageContentView.DuplicateKeyStyleClassName);else editingNode.element.classList.remove(WI.DOMStorageContentView.DuplicateKeyStyleClassName);} var columnIndex=this._dataGrid.orderedColumns.indexOf(columnIdentifier);var mayMoveToNextRow=moveDirection==="forward"&&columnIndex===this._dataGrid.orderedColumns.length-1;var mayMoveToPreviousRow=moveDirection==="backward"&&columnIndex===0;var doneEditing=mayMoveToNextRow||mayMoveToPreviousRow||!moveDirection;if(!doneEditing) return;if(!key.length&&!value.length&&!editingNode.isPlaceholderNode){this._dataGrid.removeChild(editingNode);domStorage.removeItem(editingNode.__originalKey);return;} var isDuplicate=editingNode.element.classList.contains(WI.DOMStorageContentView.DuplicateKeyStyleClassName);if(!key.length||!value.length||isDuplicate) return;if(keyChanged&&!editingNode.isPlaceholderNode) domStorage.removeItem(editingNode.__originalKey);if(editingNode.isPlaceholderNode) this._dataGrid.addPlaceholderNode();cleanup();domStorage.setItem(key,value);} _dataGridCopy(node,columnIdentifier,text) {if(columnIdentifier==="displayValue"&&node.data.value) return node.data.value;return text;} _handleFilterBarFilterDidChange(event) {this._dataGrid.filterText=this._filterBarNavigationItem.filterBar.filters.text||"";} _handleClearNavigationItemClicked(event) {this.representedObject.clear();}};WI.DOMStorageContentView.DuplicateKeyStyleClassName="duplicate-key";WI.DOMStorageContentView.MissingKeyStyleClassName="missing-key";WI.DOMStorageContentView.MissingValueStyleClassName="missing-value";WI.DOMStorageTreeElement=class DOMStorageTreeElement extends WI.StorageTreeElement {constructor(representedObject) {if(representedObject.isLocalStorage()) var className=WI.DOMStorageTreeElement.LocalStorageIconStyleClassName;else var className=WI.DOMStorageTreeElement.SessionStorageIconStyleClassName;super(className,WI.displayNameForHost(representedObject.host),representedObject);} get name() {return WI.displayNameForHost(this.representedObject.host);} get categoryName() {if(this.representedObject.isLocalStorage()) return WI.UIString("Local Storage");return WI.UIString("Session Storage");}};WI.DOMStorageTreeElement.LocalStorageIconStyleClassName="local-storage-icon";WI.DOMStorageTreeElement.SessionStorageIconStyleClassName="session-storage-icon";WI.DOMTreeElement=class DOMTreeElement extends WI.TreeElement {constructor(node,elementCloseTag,{showBadges}={}) {super("",node);this._elementCloseTag=elementCloseTag;this.hasChildren=!elementCloseTag&&this._hasVisibleChildren();if(this.representedObject.nodeType()===Node.ELEMENT_NODE&&!elementCloseTag) this._canAddAttributes=true;this._searchQuery=null;this._expandedChildrenLimit=WI.DOMTreeElement.InitialChildrenLimit;this._breakpointStatus=WI.DOMTreeElement.BreakpointStatus.None;this._animatingHighlight=false;this._shouldHighlightAfterReveal=false;this._boundHighlightAnimationEnd=this._highlightAnimationEnd.bind(this);this._subtreeBreakpointTreeElements=null;this._showGoToArrow=false;this._highlightedAttributes=new Set;this._recentlyModifiedAttributes=new Map;this._closeTagTreeElement=null;this._showBadges=!!showBadges;this._elementForBadgeType=new Map;node.addEventListener(WI.DOMNode.Event.EnabledPseudoClassesChanged,this._updatePseudoClassIndicator,this);this._ignoreSingleTextChild=false;this._forceUpdateTitle=false;} static shadowRootTypeDisplayName(type) {switch(type){case WI.DOMNode.ShadowRootType.UserAgent:return WI.UIString("User Agent");case WI.DOMNode.ShadowRootType.Open:return WI.UIString("Open");case WI.DOMNode.ShadowRootType.Closed:return WI.UIString("Closed");}} get statusImageElement(){return this._statusImageElement;} get hasBreakpoint() {return this._breakpointStatus!==WI.DOMTreeElement.BreakpointStatus.None||(this._subtreeBreakpointTreeElements&&this._subtreeBreakpointTreeElements.size);} get breakpointStatus() {return this._breakpointStatus;} set breakpointStatus(status) {if(this._breakpointStatus===status) return;let increment;if(this._breakpointStatus===WI.DOMTreeElement.BreakpointStatus.None) increment=1;else if(status===WI.DOMTreeElement.BreakpointStatus.None) increment=-1;this._breakpointStatus=status;this._updateBreakpointStatus();if(!increment) return;let parentElement=this.parent;while(parentElement&&!parentElement.root){parentElement._subtreeBreakpointChanged(this);parentElement=parentElement.parent;}} bindRevealDescendantBreakpointsMenuItemHandler() {if(!this._subtreeBreakpointTreeElements||!this._subtreeBreakpointTreeElements.size) return null;let subtreeBreakpointTreeElements=Array.from(this._subtreeBreakpointTreeElements);return()=>{for(let subtreeBreakpointTreeElement of subtreeBreakpointTreeElements) subtreeBreakpointTreeElement.reveal();};} get closeTagTreeElement(){return this._closeTagTreeElement;} revealAndHighlight() {if(this._animatingHighlight) return;this._shouldHighlightAfterReveal=true;this.reveal();} isCloseTag() {return this._elementCloseTag;} highlightSearchResults(searchQuery) {if(this._searchQuery!==searchQuery){this._updateSearchHighlight(false);this._highlightResult=undefined;} this._searchQuery=searchQuery;this._searchHighlightsVisible=true;this.updateTitle(true);} hideSearchHighlights() {this._searchHighlightsVisible=false;this._updateSearchHighlight(false);} emphasizeSearchHighlight() {var highlightElement=this.title.querySelector("."+WI.DOMTreeElement.SearchHighlightStyleClassName);if(!highlightElement) return;if(this._bouncyHighlightElement) this._bouncyHighlightElement.remove();this._bouncyHighlightElement=document.createElement("div");this._bouncyHighlightElement.className=WI.DOMTreeElement.BouncyHighlightStyleClassName;this._bouncyHighlightElement.textContent=highlightElement.textContent;var highlightElementRect=highlightElement.getBoundingClientRect();var treeOutlineRect=this.treeOutline.element.getBoundingClientRect();this._bouncyHighlightElement.style.top=(highlightElementRect.top-treeOutlineRect.top)+"px";this._bouncyHighlightElement.style.left=(highlightElementRect.left-treeOutlineRect.left)+"px";this.title.appendChild(this._bouncyHighlightElement);function animationEnded() {if(!this._bouncyHighlightElement) return;this._bouncyHighlightElement.remove();this._bouncyHighlightElement=null;} this._bouncyHighlightElement.addEventListener("animationend",animationEnded.bind(this));} _updateSearchHighlight(show) {if(!this._highlightResult) return;function updateEntryShow(entry) {switch(entry.type){case"added":entry.parent.insertBefore(entry.node,entry.nextSibling);break;case"changed":entry.node.textContent=entry.newText;break;}} function updateEntryHide(entry) {switch(entry.type){case"added":entry.node.remove();break;case"changed":entry.node.textContent=entry.oldText;break;}} var updater=show?updateEntryShow:updateEntryHide;for(var i=0,size=this._highlightResult.length;i=this.expandedChildrenLimit){this._expandedChildrenLimit=index+1;this._updateChildren(true);} return this.children[index];} toggleElementVisibility(forceHidden) {let effectiveNode=this.representedObject;if(effectiveNode.isPseudoElement()){effectiveNode=effectiveNode.parentNode;if(!effectiveNode) return;} if(effectiveNode.nodeType()!==Node.ELEMENT_NODE) return;function inspectedPage_node_injectStyleAndToggleClass(hiddenClassName,force){let root=this.getRootNode()||document;let styleElement=root.getElementById(hiddenClassName);if(!styleElement){styleElement=document.createElement("style");styleElement.id=hiddenClassName;styleElement.textContent=`.${hiddenClassName} { visibility: hidden !important; }`;if(root instanceof HTMLDocument) root.head.appendChild(styleElement);else root.insertBefore(styleElement,root.firstChild);} this.classList.toggle(hiddenClassName,force);} WI.RemoteObject.resolveNode(effectiveNode).then((object)=>{object.callFunction(inspectedPage_node_injectStyleAndToggleClass,[WI.DOMTreeElement.HideElementStyleSheetIdOrClassName,forceHidden],false);object.release();});} _createTooltipForNode() {var node=this.representedObject;if(!node.nodeName()||node.nodeName().toLowerCase()!=="img") return;function setTooltip(error,result,wasThrown) {if(error||wasThrown||!result||result.type!=="string") return;try{var properties=JSON.parse(result.description);var offsetWidth=properties[0];var offsetHeight=properties[1];var naturalWidth=properties[2];var naturalHeight=properties[3];if(offsetHeight===naturalHeight&&offsetWidth===naturalWidth) this.tooltip=WI.UIString("%d \xd7 %d pixels").format(offsetWidth,offsetHeight);else this.tooltip=WI.UIString("%d \xd7 %d pixels (Natural: %d \xd7 %d pixels)").format(offsetWidth,offsetHeight,naturalWidth,naturalHeight);}catch(e){console.error(e);}} WI.RemoteObject.resolveNode(node).then((object)=>{function inspectedPage_node_dimensions(){return"["+this.offsetWidth+","+this.offsetHeight+","+this.naturalWidth+","+this.naturalHeight+"]";} object.callFunction(inspectedPage_node_dimensions,undefined,false,setTooltip.bind(this));object.release();});} updateSelectionArea() {let listItemElement=this.listItemElement;if(!listItemElement) return;let indicatesTreeOutlineState=this.treeOutline&&(this.treeOutline.dragOverTreeElement===this||this.selected||this._animatingHighlight);if(!this.hovered&&!indicatesTreeOutlineState){if(this._selectionElement){this._selectionElement.remove();this._selectionElement=null;} return;} if(!this._selectionElement){this._selectionElement=document.createElement("div");this._selectionElement.className="selection-area";listItemElement.insertBefore(this._selectionElement,listItemElement.firstChild);} this._selectionElement.style.height=listItemElement.offsetHeight+"px";} onattach() {if(this.hovered) this.listItemElement.classList.add("hovered");this.updateTitle();if(this.editable){this.listItemElement.draggable=true;this.listItemElement.addEventListener("dragstart",this);} WI.settings.enabledDOMTreeBadgeTypes.addEventListener(WI.Setting.Event.Changed,this._handleShownDOMTreeBadgesChanged,this);this.representedObject.addEventListener(WI.DOMNode.Event.LayoutFlagsChanged,this._handleLayoutFlagsChanged,this);this._handleLayoutFlagsChanged();} ondetach() {if(this._elementForBadgeType.size){this.representedObject.removeEventListener(WI.DOMNode.Event.LayoutOverlayShown,this._updateBadges,this);this.representedObject.removeEventListener(WI.DOMNode.Event.LayoutOverlayHidden,this._updateBadges,this);} this.representedObject.removeEventListener(WI.DOMNode.Event.LayoutFlagsChanged,this._handleLayoutFlagsChanged,this);WI.settings.enabledDOMTreeBadgeTypes.removeEventListener(WI.Setting.Event.Changed,this._handleShownDOMTreeBadgesChanged,this);} onpopulate() {if(this.children.length||!this._hasVisibleChildren()||this._elementCloseTag) return;this.updateChildren();} expandRecursively() {this.representedObject.getSubtree(-1,super.expandRecursively.bind(this,Number.MAX_VALUE));} updateChildren(fullRefresh) {if(this._elementCloseTag) return;this.representedObject.getChildNodes(this._updateChildren.bind(this,fullRefresh));} insertChildElement(child,index,closingTag) {var newElement=new WI.DOMTreeElement(child,closingTag,{showBadges:this._showBadges});newElement.selectable=this.treeOutline.selectable;this.insertChild(newElement,index);return newElement;} moveChild(child,targetIndex) {if(this.children[targetIndex]===child) return;var originalSelectedChild=this.treeOutline.selectedTreeElement;this.removeChild(child);this.insertChild(child,targetIndex);if(originalSelectedChild!==this.treeOutline.selectedTreeElement) originalSelectedChild.select();} _updateChildren(fullRefresh) {if(this._updateChildrenInProgress||!this.treeOutline._visible) return;this._closeTagTreeElement=null;this._updateChildrenInProgress=true;var node=this.representedObject;var selectedNode=this.treeOutline.selectedDOMNode();var originalScrollTop=0;var hasVisibleChildren=this._hasVisibleChildren();if(fullRefresh||!hasVisibleChildren){var treeOutlineContainerElement=this.treeOutline.element.parentNode;originalScrollTop=treeOutlineContainerElement.scrollTop;var selectedTreeElement=this.treeOutline.selectedTreeElement;if(selectedTreeElement&&selectedTreeElement.hasAncestor(this)) this.select();this.removeChildren();if(!hasVisibleChildren){this.hasChildren=false;this.updateTitle();this._updateChildrenInProgress=false;return;}} if(!this.hasChildren){this.hasChildren=true;this.updateTitle();} var existingChildTreeElements=new Map;for(var i=this.children.length-1;i>=0;--i){var currentChildTreeElement=this.children[i];var currentNode=currentChildTreeElement.representedObject;var currentParentNode=currentNode.parentNode;if(currentParentNode===node){existingChildTreeElements.set(currentNode,currentChildTreeElement);continue;} this.removeChildAtIndex(i);} var elementToSelect=null;var visibleChildren=this._visibleChildren();for(var i=0;ithis.expandedChildrenLimit) this.expandedChildrenLimit++;} this.adjustCollapsedRange();var lastChild=this.children.lastValue;if(node.nodeType()===Node.ELEMENT_NODE&&(!lastChild||!lastChild._elementCloseTag)) this._closeTagTreeElement=this.insertChildElement(this.representedObject,this.children.length,true);if(fullRefresh&&elementToSelect){elementToSelect.select();if(treeOutlineContainerElement&&originalScrollTop<=treeOutlineContainerElement.scrollHeight) treeOutlineContainerElement.scrollTop=originalScrollTop;} this._updateChildrenInProgress=false;} adjustCollapsedRange() { if(this.expandAllButtonElement&&this.expandAllButtonElement.__treeElement.parent) this.removeChild(this.expandAllButtonElement.__treeElement);if(!this._hasVisibleChildren()) return;var visibleChildren=this._visibleChildren();var totalChildrenCount=visibleChildren.length;for(var i=this.expandedChildCount,limit=Math.min(this.expandedChildrenLimit,totalChildrenCount);ithis.expandedChildCount){var targetButtonIndex=expandedChildCount;if(!this.expandAllButtonElement){var button=document.createElement("button");button.className="show-all-nodes";button.value="";var item=new WI.TreeElement(button,null,false);item.selectable=false;item.expandAllButton=true;this.insertChild(item,targetButtonIndex);this.expandAllButtonElement=button;this.expandAllButtonElement.__treeElement=item;this.expandAllButtonElement.addEventListener("click",this.handleLoadAllChildren.bind(this),false);}else if(!this.expandAllButtonElement.__treeElement.parent) this.insertChild(this.expandAllButtonElement.__treeElement,targetButtonIndex);this.expandAllButtonElement.textContent=WI.UIString("Show All Nodes (%d More)").format(totalChildrenCount-expandedChildCount);}else if(this.expandAllButtonElement) this.expandAllButtonElement=null;} handleLoadAllChildren() {var visibleChildren=this._visibleChildren();this.expandedChildrenLimit=Math.max(visibleChildren.length,this.expandedChildrenLimit+WI.DOMTreeElement.InitialChildrenLimit);} reveal({skipExpandingAncestors}={}) {if(!skipExpandingAncestors){let currentElement=this;while(currentElement.parent&&!currentElement.parent.root){if(!currentElement.parent.expanded) currentElement.parent.expand(); currentElement.parent.showChildNode(currentElement);currentElement=currentElement.parent;}} super.reveal({skipExpandingAncestors:true});} onexpand() {if(this._elementCloseTag) return;if(!this.listItemElement) return;this.updateTitle();for(let treeElement of this.children){if(treeElement instanceof WI.DOMTreeElement) treeElement.updateSelectionArea();}} oncollapse() {if(this._elementCloseTag) return;this.updateTitle();} onreveal() {let listItemElement=this.listItemElement;if(!listItemElement) return;let tagSpans=listItemElement.getElementsByClassName("html-tag-name");if(tagSpans.length) tagSpans[0].scrollIntoViewIfNeeded(false);else listItemElement.scrollIntoViewIfNeeded(false);if(!this._shouldHighlightAfterReveal) return;this._shouldHighlightAfterReveal=false;this._animatingHighlight=true;this.updateSelectionArea();listItemElement.addEventListener("animationend",this._boundHighlightAnimationEnd);listItemElement.classList.add(WI.DOMTreeElement.HighlightStyleClassName);} onenter() {if(!this.editable) return false; if(this.treeOutline.editing) return false;this._startEditing(); return true;} canSelectOnMouseDown(event) {if(this._editing) return false;if(event.detail>=2){event.preventDefault();return false;} return true;} ondblclick(event) {if(!this.editable) return false;if(this._editing||this._elementCloseTag) return;if(this._startEditingTarget(event.target)) return;if(this.hasChildren&&!this.expanded) this.expand();} _insertInLastAttributePosition(tag,node) {if(tag.getElementsByClassName("html-attribute").length>0) tag.insertBefore(node,tag.lastChild);else{let tagNameElement=tag.querySelector(".html-tag-name");tagNameElement.parentNode.insertBefore(node,tagNameElement.nextSibling);} this.updateSelectionArea();} _startEditingTarget(eventTarget) {if(this.treeOutline.selectedDOMNode()!==this.representedObject) return false;if(this.representedObject.isShadowRoot()) return false;if(this.representedObject.isInUserAgentShadowTree()&&!WI.DOMManager.supportsEditingUserAgentShadowTrees()) return false;if(this.representedObject.isPseudoElement()) return false;if(this.representedObject.nodeType()!==Node.ELEMENT_NODE&&this.representedObject.nodeType()!==Node.TEXT_NODE) return false;var textNode=eventTarget.closest(".html-text-node");if(textNode) return this._startEditingTextNode(textNode);var attribute=eventTarget.closest(".html-attribute");if(attribute) return this._startEditingAttribute(attribute,eventTarget);var tagName=eventTarget.closest(".html-tag-name");if(tagName) return this._startEditingTagName(tagName);return false;} populateDOMNodeContextMenu(contextMenu,subMenus,event) {let attributeNode=event.target.closest(".html-attribute");let textNode=event.target.closest(".html-text-node");let attributeName=null;if(attributeNode){let attributeNameElement=attributeNode.getElementsByClassName("html-attribute-name")[0];if(attributeNameElement) attributeName=attributeNameElement.textContent.trim();} if(event.target&&event.target.tagName==="A") WI.appendContextMenuItemsForURL(contextMenu,event.target.href,{frame:this.representedObject.frame});contextMenu.appendSeparator();let isEditableNode=this.representedObject.nodeType()===Node.ELEMENT_NODE&&this.editable;let isNonShadowEditable=isEditableNode&&(!this.representedObject.isInUserAgentShadowTree()||WI.DOMManager.supportsEditingUserAgentShadowTrees());let alreadyEditingHTML=this._htmlEditElement&&WI.isBeingEdited(this._htmlEditElement);if(isEditableNode){if(!DOMTreeElement.ForbiddenClosingTagElements.has(this.representedObject.nodeNameInCorrectCase())){subMenus.add.appendItem(WI.UIString("Child","A submenu item of 'Add' to append DOM nodes to the selected DOM node"),()=>{this._addHTML();},alreadyEditingHTML);} subMenus.add.appendItem(WI.UIString("Previous Sibling","A submenu item of 'Add' to add DOM nodes before the selected DOM node"),()=>{this._addPreviousSibling();},alreadyEditingHTML);subMenus.add.appendItem(WI.UIString("Next Sibling","A submenu item of 'Add' to add DOM nodes after the selected DOM node"),()=>{this._addNextSibling();},alreadyEditingHTML);} if(isNonShadowEditable){subMenus.add.appendItem(WI.UIString("Attribute"),()=>{this._addNewAttribute();});} if(this.editable){subMenus.edit.appendItem(WI.UIString("HTML"),()=>{this._editAsHTML();},alreadyEditingHTML);} if(isNonShadowEditable){if(attributeName){subMenus.edit.appendItem(WI.UIString("Attribute"),()=>{this._startEditingAttribute(attributeNode,event.target);},WI.isBeingEdited(attributeNode));} if(InspectorBackend.hasCommand("DOM.setNodeName")&&!DOMTreeElement.UneditableTagNames.has(this.representedObject.nodeNameInCorrectCase())){let tagNameNode=event.target.closest(".html-tag-name");subMenus.edit.appendItem(WI.UIString("Tag","A submenu item of 'Edit' to change DOM element's tag name"),()=>{this._startEditingTagName(tagNameNode);},WI.isBeingEdited(tagNameNode));}} if(textNode&&this.editable){subMenus.edit.appendItem(WI.UIString("Text"),()=>{this._startEditingTextNode(textNode);},WI.isBeingEdited(textNode));} if(!this.representedObject.destroyed&&!this.representedObject.isPseudoElement()){subMenus.copy.appendItem(WI.UIString("HTML"),()=>{this.representedObject.getOuterHTML().then((outerHTML)=>{InspectorFrontendHost.copyText(outerHTML);});});} if(attributeName){subMenus.copy.appendItem(WI.UIString("Attribute"),()=>{let text=attributeName;let attributeValue=this.representedObject.getAttribute(attributeName);if(attributeValue) text+="=\""+attributeValue.replace(/"/g,"\\\"")+"\"";InspectorFrontendHost.copyText(text);});} if(textNode&&textNode.textContent.length){subMenus.copy.appendItem(WI.UIString("Text"),()=>{InspectorFrontendHost.copyText(textNode.textContent);});} if(this.editable&&(!this.selected||this.treeOutline.selectedTreeElements.length===1)){subMenus.delete.appendItem(WI.UIString("Node"),()=>{this.remove();});} if(attributeName&&isNonShadowEditable){subMenus.delete.appendItem(WI.UIString("Attribute"),()=>{this.representedObject.removeAttribute(attributeName);});} for(let subMenu of Object.values(subMenus)) contextMenu.pushItem(subMenu);if(this.treeOutline.editable){if(this.selected&&this.treeOutline&&this.treeOutline.selectedTreeElements.length>1){let forceHidden=!this.treeOutline.selectedTreeElements.every((treeElement)=>treeElement.isNodeHidden);let label=forceHidden?WI.UIString("Hide Elements"):WI.UIString("Show Elements");contextMenu.appendItem(label,()=>{this.treeOutline.toggleSelectedElementsVisibility(forceHidden);});}else if(isEditableNode){contextMenu.appendItem(WI.UIString("Toggle Visibility"),()=>{this.toggleElementVisibility();});}}} _startEditing() {if(this.treeOutline.selectedDOMNode()!==this.representedObject) return false;if(!this.editable) return false;var listItem=this.listItemElement;if(this._canAddAttributes){var attribute=listItem.getElementsByClassName("html-attribute")[0];if(attribute) return this._startEditingAttribute(attribute,attribute.getElementsByClassName("html-attribute-value")[0]);return this._addNewAttribute();} if(this.representedObject.nodeType()===Node.TEXT_NODE){var textNode=listItem.getElementsByClassName("html-text-node")[0];if(textNode) return this._startEditingTextNode(textNode);return false;}} _addNewAttribute() { var container=document.createElement("span");this._buildAttributeDOM(container," ","");var attr=container.firstChild;attr.style.marginLeft="2px"; attr.style.marginRight="2px"; var tag=this.listItemElement.getElementsByClassName("html-tag")[0];this._insertInLastAttributePosition(tag,attr);return this._startEditingAttribute(attr,attr);} _triggerEditAttribute(attributeName) {var attributeElements=this.listItemElement.getElementsByClassName("html-attribute-name");for(var i=0,len=attributeElements.length;i";} function editingComitted(element,newTagName) {tagNameElement.removeEventListener("keyup",keyupListener,false);this._tagNameEditingCommitted.apply(this,arguments);} function editingCancelled() {if(closingTagElement) closingTagElement.textContent=originalClosingTagTextContent;tagNameElement.removeEventListener("keyup",keyupListener,false);this._editingCancelled.apply(this,arguments);} tagNameElement.addEventListener("keyup",keyupListener,false);var config=new WI.EditingConfig(editingComitted.bind(this),editingCancelled.bind(this),tagName);this._editing=WI.startEditing(tagNameElement,config);window.getSelection().setBaseAndExtent(tagNameElement,0,tagNameElement,1);return true;} _startEditingAsHTML(commitCallback,options={}) {if(this._htmlEditElement&&WI.isBeingEdited(this._htmlEditElement)) return;if(options.hideExistingElements){let child=this.listItemElement.firstChild;while(child){child.style.display="none";child=child.nextSibling;} if(this._childrenListNode) this._childrenListNode.style.display="none";} let positionInside=options.position==="afterbegin"||options.position==="beforeend";if(positionInside&&this._childrenListNode){this._htmlEditElement=document.createElement("li");let referenceNode=options.position==="afterbegin"?this._childrenListNode.firstElementChild:this._childrenListNode.lastElementChild;this._childrenListNode.insertBefore(this._htmlEditElement,referenceNode);}else if(options.position&&!positionInside){this._htmlEditElement=document.createElement("li");let targetNode=(options.position==="afterend"&&this._childrenListNode)?this._childrenListNode:this.listItemElement;targetNode.insertAdjacentElement(options.position,this._htmlEditElement);}else{this._htmlEditElement=document.createElement("div");this.listItemElement.appendChild(this._htmlEditElement);} if(options.initialValue) this._htmlEditElement.textContent=options.initialValue;this.updateSelectionArea();function commit() {commitCallback(this._htmlEditElement.textContent);dispose.call(this);} function dispose() {this._editing=false;this._htmlEditElement.remove();this._htmlEditElement=null;if(options.hideExistingElements){if(this._childrenListNode) this._childrenListNode.style.removeProperty("display");let child=this.listItemElement.firstChild;while(child){child.style.removeProperty("display");child=child.nextSibling;}} this.updateSelectionArea();} var config=new WI.EditingConfig(commit.bind(this),dispose.bind(this));config.setMultiline(true);this._editing=WI.startEditing(this._htmlEditElement,config);if(options.initialValue&&!isNaN(options.startPosition)){let range=document.createRange();range.setStart(this._htmlEditElement.firstChild,options.startPosition);range.collapse(true);let selection=window.getSelection();selection.removeAllRanges();selection.addRange(range);}} _attributeEditingCommitted(element,newText,oldText,attributeName,moveDirection) {this._editing=false;if(!newText.trim()) element.remove();if(!moveDirection&&newText===oldText) return;const nbspRegex=/\xA0/g;newText=newText.replace(nbspRegex," ");var treeOutline=this.treeOutline;function moveToNextAttributeIfNeeded(error) {if(error) this._editingCancelled(element,attributeName);if(!moveDirection) return;treeOutline._updateModifiedNodes();var attributes=this.representedObject.attributes();for(var i=0;i1) this._triggerEditAttribute(attributes[attributes.length-2].name);}}else if(moveDirection==="forward"){if(!/^\s*$/.test(newText)) this._addNewAttribute();else this._startEditingTagName();}} this.representedObject.setAttribute(attributeName,newText,moveToNextAttributeIfNeeded.bind(this));} _attributeNumberEditingCommitted(element,newText,oldText,attributeName,moveDirection) {if(newText===oldText) return;this.representedObject.setAttribute(attributeName,newText);} _tagNameEditingCommitted(element,newText,oldText,tagName,moveDirection) {this._editing=false;var self=this;function cancel() {var closingTagElement=self._distinctClosingTagElement();if(closingTagElement) closingTagElement.textContent="";self._editingCancelled(element,tagName);moveToNextAttributeIfNeeded.call(self);} function moveToNextAttributeIfNeeded() {if(moveDirection!=="forward"){this._addNewAttribute();return;} var attributes=this.representedObject.attributes();if(attributes.length>0) this._triggerEditAttribute(attributes[0].name);else this._addNewAttribute();} newText=newText.trim();if(newText===oldText){cancel();return;} var treeOutline=this.treeOutline;var wasExpanded=this.expanded;function changeTagNameCallback(error,nodeId) {if(error||!nodeId){cancel();return;} var node=WI.domManager.nodeForId(nodeId);treeOutline._updateModifiedNodes();treeOutline.selectDOMNode(node,true);var newTreeItem=treeOutline.findTreeElement(node);if(wasExpanded) newTreeItem.expand();moveToNextAttributeIfNeeded.call(newTreeItem);} this.representedObject.setNodeName(newText,changeTagNameCallback);} _textNodeEditingCommitted(element,newText) {this._editing=false;var textNode;if(this.representedObject.nodeType()===Node.ELEMENT_NODE){ textNode=this.representedObject.firstChild;}else if(this.representedObject.nodeType()===Node.TEXT_NODE) textNode=this.representedObject;textNode.setNodeValue(newText,this.updateTitle.bind(this));} _editingCancelled(element,context) {this._editing=false;this.updateTitle();} _distinctClosingTagElement() { if(this.expanded){var closers=this._childrenListNode.querySelectorAll(".close");return closers[closers.length-1];} var tags=this.listItemElement.getElementsByClassName("html-tag");return tags.length===1?null:tags[tags.length-1];} updateTitle(onlySearchQueryChanged) {if(this._editing&&!this._forceUpdateTitle) return;if(onlySearchQueryChanged){if(this._highlightResult) this._updateSearchHighlight(false);}else{this.title=document.createElement("span");this.title.appendChild(this._nodeTitleInfo().titleDOM);this._highlightResult=undefined;} this._createBadges(); this._selectionElement=null;this.updateSelectionArea();this._highlightSearchResults();this._updatePseudoClassIndicator();this._updateBreakpointStatus();} _buildAttributeDOM(parentElement,name,value,node) {let hasText=value.length>0;let attrSpanElement=parentElement.createChild("span","html-attribute");let attrNameElement=attrSpanElement.createChild("span","html-attribute-name");attrNameElement.textContent=name;let attrValueElement=null;if(hasText) attrSpanElement.append("=\u200B\"");if(name==="src"||/\bhref\b/.test(name)){let baseURL=node.frame?node.frame.url:null;let rewrittenURL=absoluteURL(value,baseURL);value=value.insertWordBreakCharacters();if(!rewrittenURL){attrValueElement=attrSpanElement.createChild("span","html-attribute-value");attrValueElement.textContent=value;}else{if(value.startsWith("data:")) value=value.truncateMiddle(60);attrValueElement=document.createElement("a");attrValueElement.href=rewrittenURL;attrValueElement.textContent=value;attrSpanElement.appendChild(attrValueElement);}}else if(name==="srcset"){let baseURL=node.frame?node.frame.url:null;attrValueElement=attrSpanElement.createChild("span","html-attribute-value");let groups=value.split(/\s*,\s*/);for(let i=0;i");parentElement.append("\u200B");if(this._showGoToArrow&&node.nodeType()===Node.ELEMENT_NODE&&willRenderCloseTagInline===isClosingTag){let goToArrowElement=parentElement.appendChild(WI.createGoToArrowButton());goToArrowElement.title=WI.UIString("Reveal in Elements Tab");goToArrowElement.addEventListener("click",(event)=>{WI.domManager.inspectElement(this.representedObject.id,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.LinkClick,});});}} _nodeTitleInfo() {var node=this.representedObject;var info={titleDOM:document.createDocumentFragment(),hasChildren:this.hasChildren};function trimedNodeValue() { return node.nodeValue().replace(/^[\n\r]*/,"").replace(/\s*$/,"");} switch(node.nodeType()){case Node.DOCUMENT_FRAGMENT_NODE:var fragmentElement=info.titleDOM.createChild("span","html-fragment");if(node.shadowRootType()){fragmentElement.textContent=WI.UIString("Shadow Content (%s)").format(WI.DOMTreeElement.shadowRootTypeDisplayName(node.shadowRootType()));this.listItemElement.classList.add("shadow");}else if(node.parentNode&&node.parentNode.templateContent()===node){fragmentElement.textContent=WI.UIString("Template Content");this.listItemElement.classList.add("template");}else{fragmentElement.textContent=WI.UIString("Document Fragment");this.listItemElement.classList.add("fragment");} break;case Node.ATTRIBUTE_NODE:var value=node.value||"\u200B";this._buildAttributeDOM(info.titleDOM,node.name,value);break;case Node.ELEMENT_NODE:if(node.isPseudoElement()){var pseudoElement=info.titleDOM.createChild("span","html-pseudo-element");pseudoElement.textContent="::"+node.pseudoType();info.titleDOM.appendChild(document.createTextNode("\u200B"));info.hasChildren=false;break;} var tagName=node.nodeNameInCorrectCase();if(this._elementCloseTag){this._buildTagDOM({parentElement:info.titleDOM,tagName,isClosingTag:true,isDistinctTreeElement:true,willRenderCloseTagInline:false,});info.hasChildren=false;break;} var textChild=this._singleTextChild(node);var showInlineText=textChild&&textChild.nodeValue().length");break;case Node.DOCUMENT_TYPE_NODE:var docTypeElement=info.titleDOM.createChild("span","html-doctype");docTypeElement.append("");break;case Node.CDATA_SECTION_NODE:var cdataElement=info.titleDOM.createChild("span","html-text-node");cdataElement.append("");break;case Node.PROCESSING_INSTRUCTION_NODE:var processingInstructionElement=info.titleDOM.createChild("span","html-processing-instruction");var data=node.nodeValue();var dataString=data.length?" "+data:"";var title="";processingInstructionElement.append(title);break;default:info.titleDOM.append(node.nodeNameInCorrectCase().collapseWhitespace());} return info;} _singleTextChild(node) {if(!node||this._ignoreSingleTextChild) return null;var firstChild=node.firstChild;if(!firstChild||firstChild.nodeType()!==Node.TEXT_NODE) return null;if(node.hasShadowRoots()) return null;if(node.templateContent()) return null;if(node.hasPseudoElements()) return null;var sibling=firstChild.nextSibling;return sibling?null:firstChild;} _showInlineText(node) {if(node.nodeType()===Node.ELEMENT_NODE){var textChild=this._singleTextChild(node);if(textChild&&textChild.nodeValue().length{this._ignoreSingleTextChild=false;if(!value.length){if(!hasChildren){this._forceUpdateTitle=true;this.hasChildren=false;this._forceUpdateTitle=false;} return;} this.representedObject.insertAdjacentHTML(position,value);};if(position==="afterbegin"||position==="beforeend"){this._ignoreSingleTextChild=true;this.hasChildren=true;this.expand();} this._startEditingAsHTML(commitCallback,{...options,position});} _addHTML(event) {let options={};switch(this.representedObject.nodeNameInCorrectCase()){case"ul":case"ol":options.initialValue="
  • ";options.startPosition=4;break;case"table":case"thead":case"tbody":case"tfoot":options.initialValue="";options.startPosition=4;break;case"tr":options.initializing="";options.startPosition=4;break;} this._insertAdjacentHTML("beforeend",options);} _addPreviousSibling(event) {let options={};let nodeName=this.representedObject.nodeNameInCorrectCase();if(nodeName==="li"||nodeName==="tr"||nodeName==="th"||nodeName==="td"){options.initialValue=`<${nodeName}>`;options.startPosition=nodeName.length+2;} this._insertAdjacentHTML("beforebegin",options);} _addNextSibling(event) {let options={};let nodeName=this.representedObject.nodeNameInCorrectCase();if(nodeName==="li"||nodeName==="tr"||nodeName==="th"||nodeName==="td"){options.initialValue=`<${nodeName}>`;options.startPosition=nodeName.length+2;} this._insertAdjacentHTML("afterend",options);} _editAsHTML() {var treeOutline=this.treeOutline;var node=this.representedObject;var parentNode=node.parentNode;var index=node.index;var wasExpanded=this.expanded;function selectNode(error,nodeId) {if(error) return;treeOutline._updateModifiedNodes();var newNode=parentNode?parentNode.children[index]||parentNode:null;if(!newNode) return;treeOutline.selectDOMNode(newNode,true);if(wasExpanded){var newTreeItem=treeOutline.findTreeElement(newNode);if(newTreeItem) newTreeItem.expand();}} function commitChange(value) {node.setOuterHTML(value,selectNode);} node.getOuterHTML((error,initialValue)=>{if(error) return;this._startEditingAsHTML(commitChange,{initialValue,hideExistingElements:true,});});} _highlightSearchResults() {if(!this.title||!this._searchQuery||!this._searchHighlightsVisible) return;if(this._highlightResult){this._updateSearchHighlight(true);return;} let searchRegex=WI.SearchUtilities.searchRegExpForString(this._searchQuery,WI.SearchUtilities.defaultSettings);if(!searchRegex){this.hideSearchHighlights();this.dispatchEventToListeners(WI.TextEditor.Event.NumberOfSearchResultsDidChange);return;} var text=this.title.textContent;var match=searchRegex.exec(text);var matchRanges=[];while(match){matchRanges.push({offset:match.index,length:match[0].length});match=searchRegex.exec(text);} if(!matchRanges.length) matchRanges.push({offset:0,length:text.length});this._highlightResult=[];WI.highlightRangesWithStyleClass(this.title,matchRanges,WI.DOMTreeElement.SearchHighlightStyleClassName,this._highlightResult);} _createModifiedAnimation(key,value,element) {let existing=this._recentlyModifiedAttributes.get(key);if(!existing) return;if(existing.element){if(existing.listener) existing.element.removeEventListener("animationend",existing.listener);existing.element.classList.remove("node-state-changed");existing.element.style.removeProperty("animation-delay");} existing.listener=(event)=>{element.classList.remove("node-state-changed");element.style.removeProperty("animation-delay");this._recentlyModifiedAttributes.delete(key);};element.classList.remove("node-state-changed");element.style.removeProperty("animation-delay");if(existing.value===value) element.style.setProperty("animation-delay","-"+(performance.now()-existing.timestamp)+"ms");else existing.timestamp=performance.now();existing.value=value;existing.element=element;element.addEventListener("animationend",existing.listener,{once:true});element.classList.add("node-state-changed");} get isNodeHidden() {let classes=this.representedObject.getAttribute("class");return classes&&classes.includes(WI.DOMTreeElement.HideElementStyleSheetIdOrClassName);} _updatePseudoClassIndicator() {if(!this.listItemElement||this._elementCloseTag) return;if(this.representedObject.enabledPseudoClasses.length){if(!this._pseudoClassIndicatorElement){this._pseudoClassIndicatorElement=document.createElement("div");this._pseudoClassIndicatorElement.classList.add("pseudo-class-indicator");} this.listItemElement.insertBefore(this._pseudoClassIndicatorElement,this.listItemElement.firstChild);}else{if(this._pseudoClassIndicatorElement){this._pseudoClassIndicatorElement.remove();this._pseudoClassIndicatorElement=null;}}} handleEvent(event) {if(event.type==="dragstart"&&this._editing) event.preventDefault();} _subtreeBreakpointChanged(treeElement) {if(treeElement.hasBreakpoint){if(!this._subtreeBreakpointTreeElements) this._subtreeBreakpointTreeElements=new Set;this._subtreeBreakpointTreeElements.add(treeElement);}else{this._subtreeBreakpointTreeElements.delete(treeElement);if(!this._subtreeBreakpointTreeElements.size) this._subtreeBreakpointTreeElements=null;} this._updateBreakpointStatus();} _updateBreakpointStatus() {let listItemElement=this.listItemElement;if(!listItemElement) return;let hasBreakpoint=this._breakpointStatus!==WI.DOMTreeElement.BreakpointStatus.None;let hasSubtreeBreakpoints=this._subtreeBreakpointTreeElements&&this._subtreeBreakpointTreeElements.size;if(!hasBreakpoint&&!hasSubtreeBreakpoints){if(this._statusImageElement) this._statusImageElement.remove();return;} if(!this._statusImageElement){this._statusImageElement=WI.ImageUtilities.useSVGSymbol("Images/DOMBreakpoint.svg","status-image");this._statusImageElement.classList.add("breakpoint");this._statusImageElement.addEventListener("click",this._statusImageClicked.bind(this));this._statusImageElement.addEventListener("contextmenu",this._statusImageContextmenu.bind(this));this._statusImageElement.addEventListener("mousedown",(event)=>{event.stopPropagation();});} this._statusImageElement.classList.toggle("subtree",!hasBreakpoint&&hasSubtreeBreakpoints);this.listItemElement.insertBefore(this._statusImageElement,this.listItemElement.firstChild);let disabled=this._breakpointStatus===WI.DOMTreeElement.BreakpointStatus.DisabledBreakpoint;this._statusImageElement.classList.toggle("disabled",disabled);} _statusImageClicked(event) {if(this._breakpointStatus===WI.DOMTreeElement.BreakpointStatus.None) return;if(event.button!==0||event.ctrlKey) return;let breakpoints=WI.domDebuggerManager.domBreakpointsForNode(this.representedObject);if(!breakpoints||!breakpoints.length) return;let shouldEnable=breakpoints.some((breakpoint)=>breakpoint.disabled);breakpoints.forEach((breakpoint)=>{breakpoint.disabled=!shouldEnable});} _statusImageContextmenu(event) {if(!this.hasBreakpoint) return;let contextMenu=WI.ContextMenu.createFromEvent(event);WI.appendContextMenuItemsForDOMNodeBreakpoints(contextMenu,this.representedObject,{popoverTargetElement:event.target,revealDescendantBreakpointsMenuItemHandler:this.bindRevealDescendantBreakpointsMenuItemHandler(),});} _highlightAnimationEnd() {let listItemElement=this.listItemElement;if(!listItemElement) return;listItemElement.removeEventListener("animationend",this._boundHighlightAnimationEnd);listItemElement.classList.remove(WI.DOMTreeElement.HighlightStyleClassName);this._animatingHighlight=false;} _createBadge(badgeType) {if(!badgeType||!WI.settings.enabledDOMTreeBadgeTypes.value.includes(badgeType)) return;let text="";let handleClick=null;switch(badgeType){case WI.DOMTreeElement.BadgeType.Scrollable:text=WI.UIString("Scroll","Title for a badge applied to DOM nodes that are a scrollable container.");handleClick=this._handleScrollableBadgeClicked.bind(this);break;case WI.DOMTreeElement.BadgeType.Flex:text=WI.unlocalizedString("flex");handleClick=this._layoutBadgeClicked.bind(this);break;case WI.DOMTreeElement.BadgeType.Grid:text=WI.unlocalizedString("grid");handleClick=this._layoutBadgeClicked.bind(this);break;case WI.DOMTreeElement.BadgeType.Event:text=WI.UIString("Event");handleClick=this._handleEventBadgeClicked.bind(this);break;} let badgeElement=this.title.appendChild(document.createElement("span"));badgeElement.className="badge";badgeElement.textContent=text;if(handleClick){badgeElement.addEventListener("click",handleClick,true);badgeElement.addEventListener("dblclick",this._handleBadgeDoubleClicked,true);} this._elementForBadgeType.set(badgeType,badgeElement);} _createBadges() {if(!this._showBadges||!this.listItemElement||this._elementCloseTag) return;let hadBadge=this._elementForBadgeType.size;for(let badgeElement of this._elementForBadgeType.values()) badgeElement.remove();this._elementForBadgeType.clear();for(let layoutFlag of this.representedObject.layoutFlags){switch(layoutFlag){case WI.DOMNode.LayoutFlag.Scrollable:this._createBadge(WI.DOMTreeElement.BadgeType.Scrollable);break;case WI.DOMNode.LayoutFlag.Grid:this._createBadge(WI.DOMTreeElement.BadgeType.Grid);break;case WI.DOMNode.LayoutFlag.Flex:this._createBadge(WI.DOMTreeElement.BadgeType.Flex);break;case WI.DOMNode.LayoutFlag.Event:this._createBadge(WI.DOMTreeElement.BadgeType.Event);break;}} if(!this._elementForBadgeType.size){if(hadBadge){this.representedObject.removeEventListener(WI.DOMNode.Event.LayoutOverlayShown,this._updateBadges,this);this.representedObject.removeEventListener(WI.DOMNode.Event.LayoutOverlayHidden,this._updateBadges,this);} return;} if(!hadBadge){this.representedObject.addEventListener(WI.DOMNode.Event.LayoutOverlayShown,this._updateBadges,this);this.representedObject.addEventListener(WI.DOMNode.Event.LayoutOverlayHidden,this._updateBadges,this);} this._updateBadges();} _layoutBadgeClicked(event) {if(event.button!==0||event.ctrlKey) return;event.stop();if(this.representedObject.layoutOverlayShowing) this.representedObject.hideLayoutOverlay();else this.representedObject.showLayoutOverlay();} async _handleEventBadgeClicked(event) {if(this._eventBadgePopover) return;let{listeners}=await this.representedObject.getEventListeners({includeAncestors:false});const preferredEdges=[WI.RectEdge.MAX_X,WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y];let calculateTargetFrame=()=>{return WI.Rect.rectFromClientRect(this._elementForBadgeType.get(WI.DOMTreeElement.BadgeType.Event).getBoundingClientRect()).pad(2);};this._eventBadgePopover=new WI.Popover(this);this._eventBadgePopover.windowResizeHandler=(event)=>{this._eventBadgePopover.present(calculateTargetFrame(),preferredEdges,{updateContent:true,shouldAnimate:false});};let sections=WI.EventListenerSectionGroup.groupIntoSectionsByEvent(listeners,{hideTarget:true});for(let section of sections){section.addEventListener(WI.DetailsSection.Event.CollapsedStateChanged,function(event){const shouldAnimate=false;this.update(shouldAnimate);},this._eventBadgePopover);} const title="";let detailsSection=new WI.DetailsSection("event-listeners",title,sections);let contentElement=document.createElement("div");contentElement.className="event-badge-popover-content";contentElement.appendChild(detailsSection.element);this._eventBadgePopover.presentNewContentWithFrame(contentElement,calculateTargetFrame(),preferredEdges);} _handleScrollableBadgeClicked(event) {this.representedObject.scrollIntoView();} _handleBadgeDoubleClicked(event) {event.stop();} _updateBadges() {for(let[badgeType,badgeElement]of this._elementForBadgeType){switch(badgeType){case WI.DOMTreeElement.BadgeType.Grid:case WI.DOMTreeElement.BadgeType.Flex:{let layoutOverlayShowing=this.representedObject.layoutOverlayShowing;badgeElement.classList.toggle("activated",layoutOverlayShowing);if(layoutOverlayShowing){let color=this.representedObject.layoutOverlayColor;let hue=color.hsl[0];badgeElement.style.borderColor=color.toString();badgeElement.style.backgroundColor=`hsl(${hue}, 90%, 95%)`;badgeElement.style.setProperty("color",`hsl(${hue}, 55%, 40%)`);}else badgeElement.removeAttribute("style");break;}}}} _handleLayoutFlagsChanged(event) {this.listItemElement?.classList.toggle("rendered",this.representedObject.layoutFlags.includes(WI.DOMNode.LayoutFlag.Rendered));this._createBadges();} _handleShownDOMTreeBadgesChanged(event) {this._createBadges();} didDismissPopover(popover) {if(popover===this._eventBadgePopover) this._eventBadgePopover=null;}};WI.DOMTreeElement.InitialChildrenLimit=500;WI.DOMTreeElement.MaximumInlineTextChildLength=80; WI.DOMTreeElement.ForbiddenClosingTagElements=new Set(["area","base","basefont","br","canvas","col","command","embed","frame","hr","img","input","keygen","link","meta","param","source","wbr","track","menuitem"]);WI.DOMTreeElement.UneditableTagNames=new Set(["html","head","body"]);WI.DOMTreeElement.BreakpointStatus={None:Symbol("none"),Breakpoint:Symbol("breakpoint"),DisabledBreakpoint:Symbol("disabled-breakpoint"),};WI.DOMTreeElement.BadgeType={Scrollable:"scrollable",Flex:"flex",Grid:"grid",Event:"event",};WI.settings.enabledDOMTreeBadgeTypes=new WI.Setting("enabled-dom-tree-badge-types",[WI.DOMTreeElement.BadgeType.Flex,WI.DOMTreeElement.BadgeType.Grid,WI.DOMTreeElement.BadgeType.Event,WI.DOMTreeElement.BadgeType.Scrollable]);WI.DOMTreeElement.HighlightStyleClassName="highlight";WI.DOMTreeElement.SearchHighlightStyleClassName="search-highlight";WI.DOMTreeElement.BouncyHighlightStyleClassName="bouncy-highlight";WI.DOMTreeElement.HideElementStyleSheetIdOrClassName="__WebInspectorHideElement__";WI.DOMTreeElementPathComponent=class DOMTreeElementPathComponent extends WI.HierarchicalPathComponent {constructor(domTreeElement,representedObject) {var node=domTreeElement.representedObject;var title=null;switch(node.nodeType()){case Node.ELEMENT_NODE:if(node.isPseudoElement()){title="::"+node.pseudoType();}else{title=node.displayName;} break;case Node.TEXT_NODE:title="\""+node.nodeValue().truncateEnd(32)+"\"";break;case Node.COMMENT_NODE:title="";break;case Node.DOCUMENT_TYPE_NODE:title="";break;case Node.DOCUMENT_NODE:title=node.nodeNameInCorrectCase();break;case Node.CDATA_SECTION_NODE:title="";break;case Node.DOCUMENT_FRAGMENT_NODE: if(node.shadowRootType()) title=WI.UIString("Shadow Content");else title=node.displayName;break;case Node.PROCESSING_INSTRUCTION_NODE:title=node.nodeNameInCorrectCase();break;default:console.error("Unknown DOM node type: ",node.nodeType());title=node.nodeNameInCorrectCase();} super(title,DOMTreeElementPathComponent.iconClassNameForNode(node),representedObject||domTreeElement.representedObject);this._domTreeElement=domTreeElement;} static iconClassNameForNode(domNode) {switch(domNode.nodeType()){case Node.ELEMENT_NODE:if(domNode.isPseudoElement()) return WI.DOMTreeElementPathComponent.DOMPseudoElementIconStyleClassName;return WI.DOMTreeElementPathComponent.DOMElementIconStyleClassName;case Node.TEXT_NODE:return WI.DOMTreeElementPathComponent.DOMTextNodeIconStyleClassName;case Node.COMMENT_NODE:return WI.DOMTreeElementPathComponent.DOMCommentIconStyleClassName;case Node.DOCUMENT_TYPE_NODE:return WI.DOMTreeElementPathComponent.DOMDocumentTypeIconStyleClassName;case Node.DOCUMENT_NODE:return WI.DOMTreeElementPathComponent.DOMDocumentIconStyleClassName;case Node.CDATA_SECTION_NODE:return WI.DOMTreeElementPathComponent.DOMCharacterDataIconStyleClassName;case Node.DOCUMENT_FRAGMENT_NODE: return WI.DOMTreeElementPathComponent.DOMDocumentTypeIconStyleClassName;case Node.PROCESSING_INSTRUCTION_NODE:return WI.DOMTreeElementPathComponent.DOMDocumentTypeIconStyleClassName;} console.error("Unknown DOM node type: ",domNode.nodeType());return WI.DOMTreeElementPathComponent.DOMNodeIconStyleClassName;} get domTreeElement() {return this._domTreeElement;} get previousSibling() {if(!this._domTreeElement.previousSibling) return null;return new WI.DOMTreeElementPathComponent(this._domTreeElement.previousSibling);} get nextSibling() {if(!this._domTreeElement.nextSibling) return null;if(this._domTreeElement.nextSibling.isCloseTag()) return null;return new WI.DOMTreeElementPathComponent(this._domTreeElement.nextSibling);} mouseOver() {let node=this._domTreeElement.representedObject;node.highlight();} mouseOut() {WI.domManager.hideDOMNodeHighlight();}};WI.DOMTreeElementPathComponent.DOMElementIconStyleClassName="dom-element-icon";WI.DOMTreeElementPathComponent.DOMPseudoElementIconStyleClassName="dom-pseudo-element-icon";WI.DOMTreeElementPathComponent.DOMTextNodeIconStyleClassName="dom-text-node-icon";WI.DOMTreeElementPathComponent.DOMCommentIconStyleClassName="dom-comment-icon";WI.DOMTreeElementPathComponent.DOMDocumentTypeIconStyleClassName="dom-document-type-icon";WI.DOMTreeElementPathComponent.DOMDocumentIconStyleClassName="dom-document-icon";WI.DOMTreeElementPathComponent.DOMCharacterDataIconStyleClassName="dom-character-data-icon";WI.DOMTreeElementPathComponent.DOMNodeIconStyleClassName="dom-node-icon";WI.DOMTreeOutline=class DOMTreeOutline extends WI.TreeOutline {constructor({selectable,omitRootDOMNode,excludeRevealElementContextMenu,showInspectedNode,showBadges}={}) {super(selectable);this.element.addEventListener("mousedown",this._onmousedown.bind(this),false);this.element.addEventListener("mousemove",this._onmousemove.bind(this),false);this.element.addEventListener("mouseout",this._onmouseout.bind(this),false);this.element.addEventListener("dragstart",this._ondragstart.bind(this),false);this.element.addEventListener("dragover",this._ondragover.bind(this),false);this.element.addEventListener("dragleave",this._ondragleave.bind(this),false);this.element.addEventListener("drop",this._ondrop.bind(this),false);this.element.addEventListener("dragend",this._ondragend.bind(this),false);this.element.classList.add("dom",WI.SyntaxHighlightedStyleClassName);this.element.dir="ltr";this.element.role="tree";this._includeRootDOMNode=!omitRootDOMNode;this._excludeRevealElementContextMenu=excludeRevealElementContextMenu;this._rootDOMNode=null;this._selectedDOMNode=null;this._treeElementsToRemove=null;this._editable=false;this._editing=false;this._visible=false;this._usingLocalDOMNode=false;this._hideElementsKeyboardShortcut=new WI.KeyboardShortcut(null,"H",this._hideElements.bind(this),this.element);this._hideElementsKeyboardShortcut.implicitlyPreventsDefault=false;this._showInspectedNode=!!showInspectedNode;if(this._showInspectedNode) WI.domManager.addEventListener(WI.DOMManager.Event.InspectedNodeChanged,this._handleInspectedNodeChanged,this);this._showBadges=!!showBadges;} wireToDomAgent() {this._elementsTreeUpdater=new WI.DOMTreeUpdater(this);} close() {if(this._elementsTreeUpdater){this._elementsTreeUpdater.close();this._elementsTreeUpdater=null;}} setVisible(visible,omitFocus) {this._visible=visible;if(!this._visible) return;this._updateModifiedNodes();if(this._selectedDOMNode) this._revealAndSelectNode(this._selectedDOMNode,omitFocus);this.update();} get rootDOMNode() {return this._rootDOMNode;} set rootDOMNode(x) {if(this._rootDOMNode===x) return;this._rootDOMNode=x;this._isXMLMimeType=x&&x.isXMLNode();this.update();} get isXMLMimeType() {return this._isXMLMimeType;} markAsUsingLocalDOMNode() {this._editable=false;this._usingLocalDOMNode=true;} selectedDOMNode() {return this._selectedDOMNode;} selectDOMNode(node,focus) {if(this._selectedDOMNode===node){this._revealAndSelectNode(node,!focus);return;} this._selectedDOMNode=node;this._revealAndSelectNode(node,!focus); if(!node||this._selectedDOMNode===node) this._selectedNodeChanged();} get editable() {return this._editable&&this.rootDOMNode&&!this.rootDOMNode.destroyed;} set editable(x) {this._editable=x;} get editing() {return this._editing;} update() {if(!this.rootDOMNode) return;let selectedTreeElements=this.selectedTreeElements;this.removeChildren();const elementCloseTag=false;var treeElement;if(this._includeRootDOMNode){treeElement=new WI.DOMTreeElement(this.rootDOMNode,elementCloseTag,{showBadges:this._showBadges});treeElement.selectable=this.selectable;this.appendChild(treeElement);}else{ var node=this.rootDOMNode.firstChild;while(node){treeElement=new WI.DOMTreeElement(node,elementCloseTag,{showBadges:this._showBadges});treeElement.selectable=this.selectable;this.appendChild(treeElement);node=node.nextSibling;if(treeElement.expandable&&!treeElement.expanded) treeElement.expand();}} if(this._showInspectedNode&&WI.domManager.inspectedNode){let inspectedNodeTreeElement=this.findTreeElement(WI.domManager.inspectedNode);if(inspectedNodeTreeElement){inspectedNodeTreeElement.reveal();inspectedNodeTreeElement.listItemElement.classList.add("inspected-node");}} if(!selectedTreeElements.length) return; selectedTreeElements=selectedTreeElements.map((oldTreeElement)=>{let treeElement=this.findTreeElement(oldTreeElement.representedObject);if(treeElement&&oldTreeElement.isCloseTag()){if(treeElement.closeTagTreeElement) treeElement=treeElement.closeTagTreeElement;} return treeElement;});selectedTreeElements=selectedTreeElements.filter((x)=>!!x);if(!selectedTreeElements.length) return;this.selectTreeElements(selectedTreeElements);if(this.selectedTreeElement) this.selectedTreeElement.reveal();} updateSelectionArea() { let selectedTreeElements=this.selectedTreeElements;for(let treeElement of selectedTreeElements) treeElement.updateSelectionArea();} toggleSelectedElementsVisibility(forceHidden) {for(let treeElement of this.selectedTreeElements) treeElement.toggleElementVisibility(forceHidden);} _selectedNodeChanged() {this.dispatchEventToListeners(WI.DOMTreeOutline.Event.SelectedNodeChanged);} findTreeElement(node) {let isAncestorNode=(ancestor,node)=>ancestor.isAncestor(node);let parentNode=(node)=>node.parentNode;let treeElement=super.findTreeElement(node,isAncestorNode,parentNode);if(!treeElement&&node.nodeType()===Node.TEXT_NODE){treeElement=super.findTreeElement(node.parentNode,isAncestorNode,parentNode);} return treeElement;} createTreeElementFor(node) {var treeElement=this.findTreeElement(node);if(treeElement) return treeElement;if(!node.parentNode) return null;treeElement=this.createTreeElementFor(node.parentNode);if(!treeElement) return null;return treeElement.showChildNode(node);} set suppressRevealAndSelect(x) {if(this._suppressRevealAndSelect===x) return;this._suppressRevealAndSelect=x;} populateContextMenu(contextMenu,event,treeElement) {let subMenus={add:new WI.ContextSubMenuItem(contextMenu,WI.UIString("Add")),edit:new WI.ContextSubMenuItem(contextMenu,WI.UIString("Edit")),copy:new WI.ContextSubMenuItem(contextMenu,WI.UIString("Copy")),delete:new WI.ContextSubMenuItem(contextMenu,WI.UIString("Delete")),};if(this.editable&&treeElement.selected&&this.selectedTreeElements.length>1){subMenus.delete.appendItem(WI.UIString("Nodes"),()=>{this.ondelete();});} if(treeElement.populateDOMNodeContextMenu) treeElement.populateDOMNodeContextMenu(contextMenu,subMenus,event,subMenus);let options={disallowEditing:!this.editable,usingLocalDOMNode:this._usingLocalDOMNode,excludeRevealElement:this._excludeRevealElementContextMenu,copySubMenu:subMenus.copy,popoverTargetElement:treeElement.statusImageElement,};if(treeElement.bindRevealDescendantBreakpointsMenuItemHandler) options.revealDescendantBreakpointsMenuItemHandler=treeElement.bindRevealDescendantBreakpointsMenuItemHandler();WI.appendContextMenuItemsForDOMNode(contextMenu,treeElement.representedObject,options);super.populateContextMenu(contextMenu,event,treeElement);} adjustCollapsedRange() {} ondelete() {if(!this.editable) return false;this._treeElementsToRemove=this.selectedTreeElements; for(let treeElement of this._treeElementsToRemove) treeElement.reveal();this._selectionController.removeSelectedItems();let levelMap=new Map;function getLevel(treeElement){let level=levelMap.get(treeElement);if(isNaN(level)){level=0;let current=treeElement;while(current=current.parent) level++;levelMap.set(treeElement,level);} return level;} this._treeElementsToRemove.sort((a,b)=>getLevel(b)-getLevel(a)); let removedDOMNodes=new Set;for(let treeElement of this._treeElementsToRemove){if(removedDOMNodes.has(treeElement.representedObject)) continue;removedDOMNodes.add(treeElement.representedObject);treeElement.remove();} this._treeElementsToRemove=null;if(this.selectedTreeElement&&!this.selectedTreeElement.isCloseTag()){this.selectedTreeElement.reveal();} return true;} selectionControllerPreviousSelectableItem(controller,item) {let treeElement=this.getCachedTreeElement(item);if(!treeElement) return null;if(this._treeElementsToRemove){ if(!treeElement.previousSelectableSibling&&treeElement.nextSelectableSibling) return null;} return super.selectionControllerPreviousSelectableItem(controller,item);} canSelectTreeElement(treeElement) {if(!super.canSelectTreeElement(treeElement)) return false;let willRemoveAncestorOrSelf=false;if(this._treeElementsToRemove){while(treeElement&&!willRemoveAncestorOrSelf){willRemoveAncestorOrSelf=this._treeElementsToRemove.includes(treeElement);treeElement=treeElement.parent;}} return!willRemoveAncestorOrSelf;} objectForSelection(treeElement) {if(treeElement instanceof WI.DOMTreeElement&&treeElement.isCloseTag()){ if(!treeElement.__closeTagProxyObject) treeElement.__closeTagProxyObject={__proxyObjectTreeElement:treeElement};return treeElement.__closeTagProxyObject;} return super.objectForSelection(treeElement);} _revealAndSelectNode(node,omitFocus) {if(!node||this._suppressRevealAndSelect) return;var treeElement=this.createTreeElementFor(node);if(!treeElement) return;treeElement.revealAndSelect(omitFocus);} _onmousedown(event) {let element=this.treeElementFromEvent(event);if(!element||element.isEventWithinDisclosureTriangle(event)){event.preventDefault();return;}} _onmousemove(event) {if(this._usingLocalDOMNode) return;let element=this.treeElementFromEvent(event);if(element&&this._previousHoveredElement===element) return;if(this._previousHoveredElement){this._previousHoveredElement.hovered=false;this._previousHoveredElement=null;} if(element instanceof WI.DOMTreeElement){element.hovered=true;this._previousHoveredElement=element;if(element.representedObject){if(!element.tooltip&&element._createTooltipForNode) element._createTooltipForNode();element.representedObject.highlight();}else WI.domManager.hideDOMNodeHighlight();}else WI.domManager.hideDOMNodeHighlight();} _onmouseout(event) {if(this._usingLocalDOMNode) return;var nodeUnderMouse=document.elementFromPoint(event.pageX,event.pageY);if(nodeUnderMouse&&this.element.contains(nodeUnderMouse)) return;if(this._previousHoveredElement){this._previousHoveredElement.hovered=false;this._previousHoveredElement=null;} WI.domManager.hideDOMNodeHighlight();} _ondragstart(event) {if(!this.editable) return false;let treeElement=this.treeElementFromEvent(event);if(!treeElement) return false;event.dataTransfer.effectAllowed="copyMove";event.dataTransfer.setData(DOMTreeOutline.DOMNodeIdDragType,treeElement.representedObject.id);if(!this._isValidDragSourceOrTarget(treeElement)) return false;if(treeElement.representedObject.nodeName()==="BODY"||treeElement.representedObject.nodeName()==="HEAD") return false;event.dataTransfer.setData("text/plain",treeElement.listItemElement.textContent);this._nodeBeingDragged=treeElement.representedObject;WI.domManager.hideDOMNodeHighlight();return true;} _ondragover(event) {if(!this.editable) return false;if(event.dataTransfer.types.includes(WI.GeneralStyleDetailsSidebarPanel.ToggledClassesDragType)){event.preventDefault();event.dataTransfer.dropEffect="copy";return false;} if(!this._nodeBeingDragged) return false;let treeElement=this.treeElementFromEvent(event);if(!this._isValidDragSourceOrTarget(treeElement)) return false;let node=treeElement.representedObject;while(node){if(node===this._nodeBeingDragged) return false;node=node.parentNode;} this.dragOverTreeElement=treeElement;treeElement.listItemElement.classList.add("elements-drag-over");treeElement.updateSelectionArea();event.preventDefault();event.dataTransfer.dropEffect="move";return false;} _ondragleave(event) {if(!this.editable) return false;this._clearDragOverTreeElementMarker();event.preventDefault();return false;} _isValidDragSourceOrTarget(treeElement) {if(!treeElement) return false;var node=treeElement.representedObject;if(!(node instanceof WI.DOMNode)) return false;if(!node.parentNode||node.parentNode.nodeType()!==Node.ELEMENT_NODE) return false;return true;} _ondrop(event) {if(!this.editable) return;event.preventDefault();function callback(error,newNodeId) {if(error) return;this._updateModifiedNodes();var newNode=WI.domManager.nodeForId(newNodeId);if(newNode) this.selectDOMNode(newNode,true);} let treeElement=this.treeElementFromEvent(event);if(this._nodeBeingDragged&&treeElement){let parentNode=null;let anchorNode=null;if(treeElement._elementCloseTag){parentNode=treeElement.representedObject;}else{let dragTargetNode=treeElement.representedObject;parentNode=dragTargetNode.parentNode;anchorNode=dragTargetNode;} this._nodeBeingDragged.moveTo(parentNode,anchorNode,callback.bind(this));}else{let className=event.dataTransfer.getData(WI.GeneralStyleDetailsSidebarPanel.ToggledClassesDragType);if(className&&treeElement) treeElement.representedObject.toggleClass(className,true);} delete this._nodeBeingDragged;} _ondragend(event) {if(!this.editable) return;event.preventDefault();this._clearDragOverTreeElementMarker();delete this._nodeBeingDragged;} _clearDragOverTreeElementMarker() {if(this.dragOverTreeElement){let element=this.dragOverTreeElement;this.dragOverTreeElement=null;element.listItemElement.classList.remove("elements-drag-over");element.updateSelectionArea();}} _updateModifiedNodes() {if(this._elementsTreeUpdater) this._elementsTreeUpdater._updateModifiedNodes();} _handleInspectedNodeChanged(event) {let{lastInspectedNode}=event.data;if(lastInspectedNode){let lastInspectedNodeTreeElement=this.findTreeElement(lastInspectedNode);if(lastInspectedNodeTreeElement) lastInspectedNodeTreeElement.listItemElement.classList.remove("inspected-node");} let inspectedNodeTreeElement=this.findTreeElement(WI.domManager.inspectedNode);if(inspectedNodeTreeElement) inspectedNodeTreeElement.listItemElement.classList.add("inspected-node");} _hideElements(event,keyboardShortcut) {if(!this.editable) return;if(!this.selectedTreeElement||WI.isEditingAnyField()) return;event.preventDefault();let forceHidden=!this.selectedTreeElements.every((treeElement)=>treeElement.isNodeHidden);this.toggleSelectedElementsVisibility(forceHidden);}};WI.DOMTreeOutline.Event={SelectedNodeChanged:"dom-tree-outline-selected-node-changed"};WI.DOMTreeOutline.DOMNodeIdDragType="web-inspector/dom-node-id";WI.DOMTreeUpdater=function(treeOutline) {WI.domManager.addEventListener(WI.DOMManager.Event.NodeInserted,this._nodeInserted,this);WI.domManager.addEventListener(WI.DOMManager.Event.NodeRemoved,this._nodeRemoved,this);WI.domManager.addEventListener(WI.DOMManager.Event.AttributeModified,this._attributesUpdated,this);WI.domManager.addEventListener(WI.DOMManager.Event.AttributeRemoved,this._attributesUpdated,this);WI.domManager.addEventListener(WI.DOMManager.Event.CharacterDataModified,this._characterDataModified,this);WI.domManager.addEventListener(WI.DOMManager.Event.DocumentUpdated,this._documentUpdated,this);WI.domManager.addEventListener(WI.DOMManager.Event.ChildNodeCountUpdated,this._childNodeCountUpdated,this);this._treeOutline=treeOutline;this._recentlyInsertedNodes=new Map;this._recentlyDeletedNodes=new Map;this._recentlyModifiedNodes=new Set;this._recentlyModifiedAttributes=new Map;this._textContentAttributeSymbol=Symbol("text-content-attribute");this._updateModifiedNodesDebouncer=new Debouncer(()=>{this._updateModifiedNodes();});};WI.DOMTreeUpdater.prototype={close:function() {WI.domManager.removeEventListener(WI.DOMManager.Event.NodeInserted,this._nodeInserted,this);WI.domManager.removeEventListener(WI.DOMManager.Event.NodeRemoved,this._nodeRemoved,this);WI.domManager.removeEventListener(WI.DOMManager.Event.AttributeModified,this._attributesUpdated,this);WI.domManager.removeEventListener(WI.DOMManager.Event.AttributeRemoved,this._attributesUpdated,this);WI.domManager.removeEventListener(WI.DOMManager.Event.CharacterDataModified,this._characterDataModified,this);WI.domManager.removeEventListener(WI.DOMManager.Event.DocumentUpdated,this._documentUpdated,this);WI.domManager.removeEventListener(WI.DOMManager.Event.ChildNodeCountUpdated,this._childNodeCountUpdated,this);},_documentUpdated:function(event) {this._reset();},_attributesUpdated:function(event) {let{node,name}=event.data;this._nodeAttributeModified(node,name);},_characterDataModified:function(event) {let{node}=event.data;this._nodeAttributeModified(node,this._textContentAttributeSymbol);},_nodeAttributeModified:function(node,attribute) {if(!this._recentlyModifiedAttributes.has(attribute)) this._recentlyModifiedAttributes.set(attribute,new Set);this._recentlyModifiedAttributes.get(attribute).add(node);this._recentlyModifiedNodes.add(node);if(this._treeOutline._visible) this._updateModifiedNodesDebouncer.delayForFrame();},_nodeInserted:function(event) {this._recentlyInsertedNodes.set(event.data.node,{parent:event.data.parent});if(this._treeOutline._visible) this._updateModifiedNodesDebouncer.delayForFrame();},_nodeRemoved:function(event) {let parent=event.data.parent;if(!parent) return;this._recentlyDeletedNodes.set(event.data.node,{parent});if(this._treeOutline._visible) this._updateModifiedNodesDebouncer.delayForFrame();},_childNodeCountUpdated:function(event) {var treeElement=this._treeOutline.findTreeElement(event.data);if(treeElement) treeElement.hasChildren=event.data.hasChildNodes();},_updateModifiedNodes:function() {let documentNeedsUpdated=false; let parentElementsToUpdate=new Set;let markNodeParentForUpdate=(value,key,map)=>{if(documentNeedsUpdated) return;let parentNode=value.parent;if(parentNode.nodeType()===Node.DOCUMENT_NODE){documentNeedsUpdated=true;return;} let parentTreeElement=this._treeOutline.findTreeElement(parentNode);if(parentTreeElement) parentElementsToUpdate.add(parentTreeElement);};this._recentlyInsertedNodes.forEach(markNodeParentForUpdate);this._recentlyDeletedNodes.forEach(markNodeParentForUpdate);if(documentNeedsUpdated) this._treeOutline.update();else{for(let parentTreeElement of parentElementsToUpdate){if(parentTreeElement.treeOutline&&parentTreeElement.listItemElement){parentTreeElement.updateTitle();parentTreeElement.updateChildren();}} for(let node of this._recentlyModifiedNodes.values()){let nodeTreeElement=this._treeOutline.findTreeElement(node);if(!nodeTreeElement) continue;for(let[attribute,nodes]of this._recentlyModifiedAttributes.entries()){if(attribute===this._textContentAttributeSymbol) continue;if(nodes.has(node)) nodeTreeElement.attributeDidChange(attribute);} nodeTreeElement.updateTitle();}} this._recentlyInsertedNodes.clear();this._recentlyDeletedNodes.clear();this._recentlyModifiedNodes.clear();this._recentlyModifiedAttributes.clear();},_reset:function() {WI.domManager.hideDOMNodeHighlight();this._recentlyInsertedNodes.clear();this._recentlyDeletedNodes.clear();this._recentlyModifiedNodes.clear();this._recentlyModifiedAttributes.clear();}};WI.DatabaseContentView=class DatabaseContentView extends WI.ContentView {constructor(representedObject) {super(representedObject);this.database=representedObject;this.element.classList.add("storage-view","query","monospace");this._prompt=new WI.ConsolePrompt(this,"text/x-sql");this.addSubview(this._prompt);this.element.addEventListener("click",this._messagesClicked.bind(this),true);} saveToCookie(cookie) {cookie.type=WI.ContentViewCookieType.Database;cookie.host=this.representedObject.host;cookie.name=this.representedObject.name;} consolePromptCompletionsNeeded(prompt,defaultCompletions,base,prefix,suffix) {let results=[];prefix=prefix.toLowerCase();function accumulateMatches(textArray) {for(let text of textArray){if(text.toLowerCase().startsWith(prefix)) results.push(text);}} function tableNamesCallback(tableNames) {accumulateMatches(tableNames);accumulateMatches(["SELECT","FROM","WHERE","LIMIT","DELETE FROM","CREATE","DROP","TABLE","INDEX","UPDATE","INSERT INTO","VALUES"]);this._prompt.updateCompletions(results," ");} this.database.getTableNames(tableNamesCallback.bind(this));} consolePromptTextCommitted(prompt,query) {this.database.executeSQL(query,this._queryFinished.bind(this,query),this._queryError.bind(this,query));} _messagesClicked() {this._prompt.focus();} _queryFinished(query,columnNames,values) {let trimmedQuery=query.trim();let queryView=new WI.DatabaseUserQuerySuccessView(trimmedQuery,columnNames,values);this.insertSubviewBefore(queryView,this._prompt);if(queryView.dataGrid) queryView.dataGrid.autoSizeColumns(5);this._prompt.element.scrollIntoView(false);if(trimmedQuery.match(/^create /i)||trimmedQuery.match(/^drop table /i)) this.dispatchEventToListeners(WI.DatabaseContentView.Event.SchemaUpdated,this.database);} _queryError(query,error) {let message;if(error.message) message=error.message;else if(error.code===2) message=WI.UIString("Database no longer has expected version.");else message=WI.UIString("An unexpected error %s occurred.").format(error.code);let queryView=new WI.DatabaseUserQueryErrorView(query,message);this.insertSubviewBefore(queryView,this._prompt);this._prompt.element.scrollIntoView(false);}};WI.DatabaseContentView.Event={SchemaUpdated:"SchemaUpdated"};WI.DatabaseHostTreeElement=class DatabaseHostTreeElement extends WI.StorageTreeElement {constructor(host) {super(WI.FolderTreeElement.FolderIconStyleClassName,WI.displayNameForHost(host),null);this._host=host;this.hasChildren=true;this.expanded=true;} get name() {return WI.displayNameForHost(this._host);} get categoryName() {return WI.UIString("Databases");}};WI.DatabaseTableContentView=class DatabaseTableContentView extends WI.ContentView {constructor(representedObject) {super(representedObject);this.element.classList.add("database-table");this._refreshButtonNavigationItem=new WI.ButtonNavigationItem("database-table-refresh",WI.UIString("Refresh"),"Images/ReloadFull.svg",13,13);this._refreshButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._refreshButtonClicked,this);this._messageTextViewElement=null;this.update();} get navigationItems() {return[this._refreshButtonNavigationItem];} update() {this.representedObject.database.executeSQL("SELECT * FROM \""+this._escapeTableName(this.representedObject.name)+"\"",this._queryFinished.bind(this),this._queryError.bind(this));} saveToCookie(cookie) {cookie.type=WI.ContentViewCookieType.DatabaseTable;cookie.host=this.representedObject.host;cookie.name=this.representedObject.name;cookie.database=this.representedObject.database.name;} get scrollableElements() {if(!this._dataGrid) return[];return[this._dataGrid.scrollContainer];} _escapeTableName(name) {return name.replace(/"/g,"\"\"");} _queryFinished(columnNames,values) { if(this._dataGrid){this.removeSubview(this._dataGrid);this._dataGrid=null;} if(this._messageTextViewElement) this._messageTextViewElement.remove();if(columnNames.length){this._dataGrid=WI.DataGrid.createSortableDataGrid(columnNames,values);this.addSubview(this._dataGrid);this._dataGrid.updateLayout();return;} this._messageTextViewElement=WI.createMessageTextView(WI.UIString("The \u201C%s\u201D\ntable is empty.").format(this.representedObject.name),false);this.element.appendChild(this._messageTextViewElement);} _queryError(error) {if(this._dataGrid){this.removeSubview(this._dataGrid);this._dataGrid=null;} if(this._messageTextViewElement) this._messageTextViewElement.remove();this._messageTextViewElement=WI.createMessageTextView(WI.UIString("An error occurred trying to read the \u201C%s\u201D table.").format(this.representedObject.name),true);this.element.appendChild(this._messageTextViewElement);} _refreshButtonClicked() {this.update();}};WI.DatabaseTableTreeElement=class DatabaseTableTreeElement extends WI.GeneralTreeElement {constructor(representedObject) {const subtitle=null;super("database-table-icon",representedObject.name,subtitle,representedObject);}};WI.DatabaseTreeElement=class DatabaseTreeElement extends WI.GeneralTreeElement {constructor(representedObject) {const subtitle=null;super("database-icon",representedObject.name,subtitle,representedObject,{hasChildren:true});this.hasChildren=false; this.onpopulate();} oncollapse() {this.shouldRefreshChildren=true;} onpopulate() {if(this.children.length&&!this.shouldRefreshChildren) return;this.shouldRefreshChildren=false;this.removeChildren();function tableNamesCallback(tableNames) {for(var i=0;iwordRange.startOffset+nonNumberInWord.index&&nonNumberEndOffset{if(!properties||this._hasStackTrace) return;let stackProperty=properties.find((property)=>property.name==="stack");if(!stackProperty) return;this._buildStackTrace(stackProperty.value.value);this._hasStackTrace=true;},options);} expand() {if(this._expanded) return;this._expanded=true;this._element.classList.add("expanded");this.update();} collapse() {if(!this._expanded) return;this._expanded=false;this._element.classList.remove("expanded");} appendTitleSuffix(suffixElement) {this._element.insertBefore(suffixElement,this._outlineElement);} _handlePreviewOrTitleElementClick(event) {if(!this._expanded) this.expand();else this.collapse();event.stopPropagation();} _buildStackTrace(stackString) {let stackTrace=WI.StackTrace.fromString(this._object.target,stackString);let stackTraceElement=new WI.StackTraceView(stackTrace);this._outlineElement.appendChild(stackTraceElement);}};WI.EventBreakpointPopover=class EventBreakpointPopover extends WI.BreakpointPopover {constructor(delegate,breakpoint) {super(delegate,breakpoint);} static get supportsEditing() {return WI.EventBreakpoint.supportsEditing;} completionControllerCompletionsNeeded(completionController,prefix,defaultCompletions,base,suffix,forced) {let eventName=prefix.toLowerCase();WI.domManager.getSupportedEventNames().then((supportedEventNames)=>{this._domEventNameCompletionController.updateCompletions(Array.from(supportedEventNames).filter((supportedEventName)=>supportedEventName.toLowerCase().startsWith(eventName)));});} get codeMirrorCompletionControllerMode() {return WI.CodeMirrorCompletionController.Mode.EventBreakpoint;} populateContent() {let content=document.createDocumentFragment();let eventLabelElement=document.createElement("label");eventLabelElement.textContent=WI.UIString("Event");let domEventNameEditorElement=content.appendChild(document.createElement("div"));domEventNameEditorElement.classList.add("editor");this._domEventNameCodeMirror=WI.CodeMirrorEditor.create(domEventNameEditorElement,{extraKeys:{"Tab":false,"Shift-Tab":false},lineWrapping:false,mode:"text/plain",matchBrackets:true,scrollbarStyle:null,});this._domEventNameCompletionController=new WI.CodeMirrorCompletionController(WI.CodeMirrorCompletionController.Mode.Basic,this._domEventNameCodeMirror,this);this._domEventNameCodeMirror.addKeyMap({"Enter":()=>{this._domEventNameCompletionController.commitCurrentCompletion();this.dismiss();},"Shift-Enter":()=>{this._domEventNameCompletionController.commitCurrentCompletion();this.dismiss();},"Esc":()=>{this.dismiss();},});let domEventNameInputElement=this._domEventNameCodeMirror.getInputField();domEventNameInputElement.id="edit-breakpoint-popover-content-event-name";eventLabelElement.setAttribute("for",domEventNameInputElement.id);if(WI.EventBreakpoint.supportsCaseSensitive){let caseSensitiveLabel=content.appendChild(document.createElement("label"));caseSensitiveLabel.className="case-sensitive";this._caseSensitiveCheckboxElement=caseSensitiveLabel.appendChild(document.createElement("input"));this._caseSensitiveCheckboxElement.type="checkbox";this._caseSensitiveCheckboxElement.checked=true;caseSensitiveLabel.append(WI.UIString("Case Sensitive"));} if(WI.EventBreakpoint.supportsIsRegex){let isRegexLabel=content.appendChild(document.createElement("label"));isRegexLabel.className="is-regex";this._isRegexCheckboxElement=isRegexLabel.appendChild(document.createElement("input"));this._isRegexCheckboxElement.type="checkbox";this._isRegexCheckboxElement.checked=false;this._isRegexCheckboxElement.addEventListener("change",(event)=>{this._updateDOMEventNameCodeMirrorMode();});this._updateDOMEventNameCodeMirrorMode();isRegexLabel.append(WI.UIString("Regular Expression"));} this.addRow("event",eventLabelElement,content);setTimeout(()=>{this._domEventNameCodeMirror.refresh();this._domEventNameCodeMirror.focus();this._domEventNameCodeMirror.setCursor(this._domEventNameCodeMirror.lineCount(),0);this.update();});} createBreakpoint(options={}) {options.eventName=this._domEventNameCodeMirror.getValue();if(!options.eventName) return null;if(this._caseSensitiveCheckboxElement) options.caseSensitive=this._caseSensitiveCheckboxElement.checked;if(this._isRegexCheckboxElement) options.isRegex=this._isRegexCheckboxElement.checked;return new WI.EventBreakpoint(WI.EventBreakpoint.Type.Listener,options);} _updateDOMEventNameCodeMirrorMode() {let isRegex=this._isRegexCheckboxElement?.checked;this._domEventNameCodeMirror.setOption("mode",isRegex?"text/x-regex":"text/plain");}};WI.EventBreakpointPopover.ReferencePage=WI.ReferencePage.EventBreakpoints;WI.EventBreakpointTreeElement=class EventBreakpointTreeElement extends WI.BreakpointTreeElement {constructor(breakpoint,{classNames,title}={}) {if(!Array.isArray(classNames)) classNames=[];classNames.push("event",breakpoint.type);if(!title) title=breakpoint.displayName;super(breakpoint,{classNames,title});}};WI.EventListenerSectionGroup=class EventListenerSectionGroup extends WI.DetailsSectionGroup {constructor(eventListener,options={}) {super();this._eventListener=eventListener;var rows=[];if(!options.hideType) rows.push(new WI.DetailsSectionSimpleRow(WI.UIString("Event"),this._eventListener.type));if(!options.hideTarget) rows.push(new WI.DetailsSectionSimpleRow(WI.UIString("Target"),this._targetTextOrLink()));rows.push(new WI.DetailsSectionSimpleRow(WI.UIString("Function"),this._functionTextOrLink()));if(this._eventListener.useCapture) rows.push(new WI.DetailsSectionSimpleRow(WI.UIString("Capturing"),WI.UIString("Yes")));else rows.push(new WI.DetailsSectionSimpleRow(WI.UIString("Bubbling"),WI.UIString("Yes")));if(this._eventListener.isAttribute) rows.push(new WI.DetailsSectionSimpleRow(WI.UIString("Attribute"),WI.UIString("Yes")));if(this._eventListener.passive) rows.push(new WI.DetailsSectionSimpleRow(WI.UIString("Passive"),WI.UIString("Yes")));if(this._eventListener.once) rows.push(new WI.DetailsSectionSimpleRow(WI.UIString("Once"),WI.UIString("Yes")));this._eventListenerEnabledToggleElement=document.createElement("input");this._eventListenerEnabledToggleElement.type="checkbox";this._updateDisabledToggle();this._eventListenerEnabledToggleElement.addEventListener("change",(event)=>{this.isEventListenerDisabled=!this._eventListenerEnabledToggleElement.checked;this.hasEventListenerBreakpoint=false;});let toggleLabel=document.createElement("span");toggleLabel.textContent=WI.UIString("Enabled");toggleLabel.addEventListener("click",(event)=>{this._eventListenerEnabledToggleElement.click();});rows.push(new WI.DetailsSectionSimpleRow(toggleLabel,this._eventListenerEnabledToggleElement));if(WI.DOMManager.supportsEventListenerBreakpoints()){let toggleContainer=document.createElement("span");this._eventListenerBreakpointToggleElement=toggleContainer.appendChild(document.createElement("input"));this._eventListenerBreakpointToggleElement.type="checkbox";this._updateBreakpointToggle();this._eventListenerBreakpointToggleElement.addEventListener("change",(event)=>{this.isEventListenerDisabled=false;this.hasEventListenerBreakpoint=!!this._eventListenerBreakpointToggleElement.checked;});if(WI.DOMManager.supportsEventListenerBreakpointConfiguration()){let revealBreakpointGoToArrow=toggleContainer.appendChild(WI.createGoToArrowButton());revealBreakpointGoToArrow.title=WI.UIString("Reveal in Sources Tab");revealBreakpointGoToArrow.addEventListener("click",(event)=>{WI.showSourcesTab({representedObjectToSelect:WI.domManager.breakpointForEventListenerId(this._eventListener.eventListenerId),});});} let toggleLabel=document.createElement("span");toggleLabel.textContent=WI.UIString("Breakpoint");toggleLabel.addEventListener("click",(event)=>{this._eventListenerBreakpointToggleElement.click();});rows.push(new WI.DetailsSectionSimpleRow(toggleLabel,toggleContainer));} this.rows=rows;} static groupIntoSectionsByEvent(eventListeners,options={}) {let eventListenerTypes=new Map;for(let eventListener of eventListeners){if(eventListener.nodeId) eventListener.node=WI.domManager.nodeForId(eventListener.nodeId);let eventListenersForType=eventListenerTypes.get(eventListener.type);if(!eventListenersForType) eventListenerTypes.set(eventListener.type,eventListenersForType=[]);eventListenersForType.push(eventListener);} let rows=[];let types=Array.from(eventListenerTypes.keys());types.sort();for(let type of types) rows.push(WI.EventListenerSectionGroup._createEventListenerSection(type,eventListenerTypes.get(type),{...options,hideType:true}));return rows;} static groupIntoSectionsByTarget(eventListeners,domNode,options={}) {const windowTargetIdentifier=Symbol("window");let eventListenerTargets=new Map;for(let eventListener of eventListeners){if(eventListener.nodeId) eventListener.node=WI.domManager.nodeForId(eventListener.nodeId);let target=eventListener.onWindow?windowTargetIdentifier:eventListener.node;let eventListenersForTarget=eventListenerTargets.get(target);if(!eventListenersForTarget) eventListenerTargets.set(target,eventListenersForTarget=[]);eventListenersForTarget.push(eventListener);} let rows=[];function generateSectionForTarget(target){let eventListenersForTarget=eventListenerTargets.get(target);if(!eventListenersForTarget) return;eventListenersForTarget.sort((a,b)=>a.type.toLowerCase().extendedLocaleCompare(b.type.toLowerCase()));let title=target===windowTargetIdentifier?WI.unlocalizedString("window"):target.displayName;let identifier=target===windowTargetIdentifier?WI.unlocalizedString("window"):target.unescapedSelector;let section=WI.EventListenerSectionGroup._createEventListenerSection(title,eventListenersForTarget,{...options,hideTarget:true,identifier});if(target instanceof WI.DOMNode) WI.bindInteractionsForNodeToElement(target,section.titleElement,{ignoreClick:true});rows.push(section);} let currentNode=domNode;do{generateSectionForTarget(currentNode);}while(currentNode=currentNode.parentNode);generateSectionForTarget(windowTargetIdentifier);return rows;} static _createEventListenerSection(title,eventListeners,options={}) {let groups=eventListeners.map((eventListener)=>new WI.EventListenerSectionGroup(eventListener,options));let optionsElement=WI.ImageUtilities.useSVGSymbol("Images/Gear.svg","event-listener-options",WI.UIString("Options"));WI.addMouseDownContextMenuHandlers(optionsElement,(contextMenu)=>{let shouldDisable=groups.some((eventListener)=>!eventListener.isEventListenerDisabled);contextMenu.appendItem(shouldDisable?WI.UIString("Disable Event Listeners"):WI.UIString("Enable Event Listeners"),()=>{for(let group of groups) group.isEventListenerDisabled=shouldDisable;});if(WI.DOMManager.supportsEventListenerBreakpoints()){let shouldBreakpoint=groups.some((eventListener)=>!eventListener.hasEventListenerBreakpoint);contextMenu.appendItem(shouldBreakpoint?WI.UIString("Add Breakpoints"):WI.UIString("Delete Breakpoints"),()=>{for(let group of groups) group.hasEventListenerBreakpoint=shouldBreakpoint;});}});const defaultCollapsedSettingValue=true;let identifier=`${options.identifier ?? title}-event-listener-section`;let section=new WI.DetailsSection(identifier,title,groups,optionsElement,defaultCollapsedSettingValue);section.element.classList.add("event-listener-section");return section;} get isEventListenerDisabled() {return this._eventListener.disabled;} set isEventListenerDisabled(disabled) {if(this._eventListener.disabled===disabled) return;this._eventListener.disabled=disabled;this._updateDisabledToggle();WI.domManager.setEventListenerDisabled(this._eventListener,this._eventListener.disabled);} get hasEventListenerBreakpoint() {return this._eventListener.hasBreakpoint;} set hasEventListenerBreakpoint(hasBreakpoint) {if(this._eventListener.hasBreakpoint===hasBreakpoint) return;this._eventListener.hasBreakpoint=hasBreakpoint;this._updateBreakpointToggle();if(this._eventListener.hasBreakpoint) WI.domManager.setBreakpointForEventListener(this._eventListener);else WI.domManager.removeBreakpointForEventListener(this._eventListener);} _targetTextOrLink() {if(this._eventListener.onWindow) return WI.unlocalizedString("window");let node=this._eventListener.node;if(node) return WI.linkifyNodeReference(node);return"";} _functionTextOrLink() {let anonymous=false;let functionName=this._eventListener.handlerName;if(!functionName&&this._eventListener.handlerBody){let match=this._eventListener.handlerBody.match(/function ([^\(]+?)\(/);if(match) functionName=match[1];} if(!functionName){anonymous=true;functionName=WI.UIString("(anonymous function)");} if(!this._eventListener.location) return functionName;var sourceCode=WI.debuggerManager.scriptForIdentifier(this._eventListener.location.scriptId,WI.mainTarget);if(!sourceCode) return functionName;var sourceCodeLocation=sourceCode.createSourceCodeLocation(this._eventListener.location.lineNumber,this._eventListener.location.columnNumber||0);const options={dontFloat:anonymous,ignoreNetworkTab:true,ignoreSearchTab:true,};let linkElement=WI.createSourceCodeLocationLink(sourceCodeLocation,options);if(anonymous) return linkElement;var fragment=document.createDocumentFragment();fragment.append(linkElement,functionName);return fragment;} _updateDisabledToggle() {this._eventListenerEnabledToggleElement.checked=!this._eventListener.disabled;this._eventListenerEnabledToggleElement.title=this._eventListener.disabled?WI.UIString("Enable Event Listener"):WI.UIString("Disable Event Listener");} _updateBreakpointToggle() {this._eventListenerBreakpointToggleElement.checked=this._eventListener.hasBreakpoint;this._eventListenerBreakpointToggleElement.title=this._eventListener.hasBreakpoint?WI.UIString("Delete Breakpoint"):WI.UIString("Add Breakpoint");}};WI.ExpandableView=class ExpandableView {constructor(key,titleElement,childElement) {this._element=document.createElement("div");if(childElement){this._disclosureButton=this._element.createChild("button","disclosure-button");this._disclosureButton.addEventListener("click",this._onDisclosureButtonClick.bind(this));this._disclosureButton.addEventListener("keydown",this._handleDisclosureButtonKeyDown.bind(this));} this._element.append(titleElement);this._expandedSetting=new WI.Setting("expanded-"+key,false);if(childElement) this._element.append(childElement);this._update();} get element() {return this._element;} _onDisclosureButtonClick(event) {this._expandedSetting.value=!this._expandedSetting.value;this._update();} _handleDisclosureButtonKeyDown(event) {if(event.code!=="ArrowRight"&&event.code!=="ArrowLeft") return;event.preventDefault();let collapsed=event.code==="ArrowLeft";if(WI.resolveLayoutDirectionForElement(this._disclosureButton)===WI.LayoutDirection.RTL) collapsed=!collapsed;this._expandedSetting.value=!collapsed;this._update();} _update() {let isExpanded=this._expandedSetting.value;this._element.classList.toggle("expanded",isExpanded);this._disclosureButton?.setAttribute("aria-expanded",isExpanded);}};WI.FilterBar=class FilterBar extends WI.Object {constructor(element) {super();this._element=element||document.createElement("div");this._element.classList.add("filter-bar");this._filterFunctionsMap=new Map;this._inputField=document.createElement("input");this._inputField.type="search";this._inputField.placeholder=WI.UIString("Filter");this._inputField.spellcheck=false;this._handleFilterInputThrottler=new Throttler(this._handleFilterInput.bind(this),250);this._inputField.addEventListener("input",(event)=>{if(this._inputField.value) this._handleFilterInputThrottler.fire(event);else this._handleFilterInputThrottler.force(event);});this._element.appendChild(this._inputField);this._filtersNavigationBar=new WI.NavigationBar;this._element.appendChild(this._filtersNavigationBar.element);this._lastFilterValue=this.filters;this._invalid=false;} get element() {return this._element;} get inputField() {return this._inputField;} get placeholder() {return this._inputField.placeholder;} set placeholder(text) {this._inputField.placeholder=text;} get invalid() {return this._invalid;} set invalid(invalid) {this._invalid=!!invalid;this._element.classList.toggle("invalid",this._invalid);} get filters() {return{text:this._inputField.value,functions:[...this._filterFunctionsMap.values()]};} set filters(filters) {filters=filters||{};var oldTextValue=this._inputField.value;this._inputField.value=filters.text||"";if(oldTextValue!==this._inputField.value) this._handleFilterInput();} focus() {if(!this._inputField.value.length) this._inputField.focus();else this._inputField.select();} clear() {this._filterFunctionsMap.clear();this.filters=null; for(let navigationItem of this._filtersNavigationBar.navigationItems){if(navigationItem instanceof WI.FilterBarButton) navigationItem.toggle(false);} this._inputField.value=null;this.invalid=false;} addFilterNavigationItem(navigationItem) {this._filtersNavigationBar.addNavigationItem(navigationItem);} addFilterBarButton(identifier,filterFunction,activatedByDefault,defaultToolTip,activatedToolTip,image,imageWidth,imageHeight) {var filterBarButton=new WI.FilterBarButton(identifier,filterFunction,activatedByDefault,defaultToolTip,activatedToolTip,image,imageWidth,imageHeight);filterBarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleFilterBarButtonClicked,this);filterBarButton.addEventListener(WI.FilterBarButton.Event.ActivatedStateToggled,this._handleFilterButtonToggled,this);this.addFilterNavigationItem(filterBarButton);if(filterBarButton.activated){this._filterFunctionsMap.set(filterBarButton.identifier,filterBarButton.filterFunction);this._handleFilterInput();}} hasActiveFilters() {return!!this._inputField.value||!!this._filterFunctionsMap.size;} hasFilterChanged() {var currentFunctions=this.filters.functions;if(this._lastFilterValue.text!==this._inputField.value||this._lastFilterValue.functions.length!==currentFunctions.length) return true;for(var i=0;i{this._inputFieldInputThrottler.fire(event);},false);this.element.appendChild(this._inputField);this._previousResultButton=document.createElement("button");this._previousResultButton.classList.add("segmented","previous-result");this._previousResultButton.disabled=true;this._previousResultButton.title=WI.UIString("Find Previous (%s)").format(WI.findPreviousKeyboardShortcut.displayName);this._previousResultButton.addEventListener("click",this._previousResultButtonClicked.bind(this));this.element.appendChild(this._previousResultButton);let previousResultButtonGlyphElement=document.createElement("div");previousResultButtonGlyphElement.classList.add(WI.FindBanner.SegmentGlyphStyleClassName);this._previousResultButton.appendChild(previousResultButtonGlyphElement);this._nextResultButton=document.createElement("button");this._nextResultButton.classList.add("segmented","next-result");this._nextResultButton.disabled=true;this._nextResultButton.title=WI.UIString("Find Next (%s)").format(WI.findNextKeyboardShortcut.displayName);this._nextResultButton.addEventListener("click",this._nextResultButtonClicked.bind(this));this.element.appendChild(this._nextResultButton);let nextResultButtonGlyphElement=document.createElement("div");nextResultButtonGlyphElement.classList.add(WI.FindBanner.SegmentGlyphStyleClassName);this._nextResultButton.appendChild(nextResultButtonGlyphElement);if(this._alwaysShowing){this.element.classList.add(WI.FindBanner.ShowingStyleClassName);this._clearAndBlurKeyboardShortcut=new WI.KeyboardShortcut(null,WI.KeyboardShortcut.Key.Escape,this.clearAndBlur.bind(this),this.element);}else{let doneButtonElement=document.createElement("button");doneButtonElement.textContent=WI.UIString("Done");doneButtonElement.addEventListener("click",this._doneButtonClicked.bind(this));this.element.appendChild(doneButtonElement);this._hideKeyboardShortcut=new WI.KeyboardShortcut(null,WI.KeyboardShortcut.Key.Escape,this.hide.bind(this),this.element);} this._numberOfResults=null;this._previousSearchValue="";} get delegate(){return this._delegate;} set delegate(newDelegate){this._delegate=newDelegate||null;} get inputField(){return this._inputField;} get searchQuery(){return this._inputField.value||"";} set searchQuery(query){this._inputField.value=query||"";} get numberOfResults(){return this._numberOfResults;} set numberOfResults(numberOfResults) {if(numberOfResults===undefined||isNaN(numberOfResults)) numberOfResults=null;this._numberOfResults=numberOfResults;this._previousResultButton.disabled=this._nextResultButton.disabled=numberOfResults<=0;if(numberOfResults===null) this._resultCountLabel.textContent="";else if(numberOfResults<=0) this._resultCountLabel.textContent=WI.UIString("Not found");else if(numberOfResults===1) this._resultCountLabel.textContent=WI.UIString("1 match");else if(numberOfResults>1) this._resultCountLabel.textContent=WI.UIString("%d matches").format(numberOfResults);} get targetElement() {return this._targetElement;} set targetElement(element) {function delayedWork() {oldTargetElement.classList.remove(WI.FindBanner.NoTransitionStyleClassName);this.element.classList.remove(WI.FindBanner.NoTransitionStyleClassName);} if(this._targetElement){var oldTargetElement=this._targetElement;this._targetElement.classList.add(WI.FindBanner.NoTransitionStyleClassName);this._targetElement.classList.remove(WI.FindBanner.SupportsFindBannerStyleClassName);this._targetElement.classList.remove(WI.FindBanner.ShowingFindBannerStyleClassName);this.element.classList.add(WI.FindBanner.NoTransitionStyleClassName);if(!this._alwaysShowing) this.element.classList.remove(WI.FindBanner.ShowingStyleClassName);setTimeout(delayedWork.bind(this),0);} this._targetElement=element||null;if(this._targetElement) this._targetElement.classList.add(WI.FindBanner.SupportsFindBannerStyleClassName);} get showing() {return this.element.classList.contains(WI.FindBanner.ShowingStyleClassName);} focus() {if(!this._inputField.value.length) this._inputField.focus();else this._inputField.select();} clearAndBlur() {this.numberOfResults=null;this._inputField.value="";this._previousSearchValue="";if(this._delegate.findBannerSearchCleared) this._delegate.findBannerSearchCleared();if(this._delegate.findBannerWantsToClearAndBlur) this._delegate.findBannerWantsToClearAndBlur();} show() {if(!this._targetElement) return;if(!this._targetElement.parentNode) return;if(this.element.parentNode!==this._targetElement.parentNode) this._targetElement.parentNode.insertBefore(this.element,this._targetElement);function delayedWork() {this._targetElement.classList.add(WI.FindBanner.ShowingFindBannerStyleClassName);this.element.classList.add(WI.FindBanner.ShowingStyleClassName);this._inputField.select();} setTimeout(delayedWork.bind(this),0);this.dispatchEventToListeners(WI.FindBanner.Event.DidShow);} hide() {if(!this._targetElement) return;this._inputField.blur();this._targetElement.classList.remove(WI.FindBanner.ShowingFindBannerStyleClassName);if(!this._alwaysShowing) this.element.classList.remove(WI.FindBanner.ShowingStyleClassName);this.dispatchEventToListeners(WI.FindBanner.Event.DidHide);} _inputFieldKeyDown(event) {if(event.keyIdentifier==="Enter"){if(this._numberOfResults>0){if(event.shiftKey) this._delegate?.findBannerRevealPreviousResult?.(this);else this._delegate?.findBannerRevealNextResult?.(this);}}} _inputFieldInput(event) {if(this._inputField.value){if(this._previousSearchValue!==this.searchQuery){if(this._delegate&&typeof this._delegate.findBannerPerformSearch==="function") this._delegate.findBannerPerformSearch(this,this.searchQuery);}}else{this.numberOfResults=null;if(this._delegate&&typeof this._delegate.findBannerSearchCleared==="function") this._delegate.findBannerSearchCleared(this);} this._previousSearchValue=this.searchQuery;} _previousResultButtonClicked(event) {if(this._delegate&&typeof this._delegate.findBannerRevealPreviousResult==="function") this._delegate.findBannerRevealPreviousResult(this);} _nextResultButtonClicked(event) {if(this._delegate&&typeof this._delegate.findBannerRevealNextResult==="function") this._delegate.findBannerRevealNextResult(this);} _doneButtonClicked(event) {this.hide();}};WI.FindBanner.SupportsFindBannerStyleClassName="supports-find-banner";WI.FindBanner.ShowingFindBannerStyleClassName="showing-find-banner";WI.FindBanner.NoTransitionStyleClassName="no-find-banner-transition";WI.FindBanner.ShowingStyleClassName="showing";WI.FindBanner.SegmentGlyphStyleClassName="glyph";WI.FindBanner.Event={DidShow:"find-banner-did-show",DidHide:"find-banner-did-hide"};WI.FlexibleSpaceNavigationItem=class FlexibleSpaceNavigationItem extends WI.NavigationItem {constructor(navigationItem,alignItem) {super();this._navigationItem=navigationItem||null;if(this._navigationItem){this._navigationItem=navigationItem;this.element.classList.add(alignItem||WI.FlexibleSpaceNavigationItem.Align.Start);}} get additionalClassNames() {return["flexible-space"];} update(options={}) {super.update(options);if(!this._navigationItem) return;if(!options.expandOnly) return;let flexibleWidth=this.width;if(!flexibleWidth) return;this.element.appendChild(this._navigationItem.element);this._navigationItem.update(options);let itemWidth=this._navigationItem.width;let remainingWidth=flexibleWidth-itemWidth;if(remainingWidth<=0) this.element.removeChild(this._navigationItem.element);}};WI.FlexibleSpaceNavigationItem.Align={Start:"align-start",End:"align-end",};WI.FontDetailsPanel=class FontDetailsPanel extends WI.StyleDetailsPanel {constructor(delegate) {const className="font";const identifier="font";const label=WI.UIString("Font","Font @ Font Details Sidebar Title","Title for the Font details sidebar.");super(delegate,className,identifier,label);this._fontStyles=null;this._fontVariationRowsMap=new Map;this._basicPropertyRowsMap=new Map;this._basicPropertyNames=["font-size","font-style","font-weight","font-stretch"];this._abortController=new AbortController;this._throttledUpdate=new Throttler(()=>{this.update()},100);this._debouncedUpdate=new Debouncer(()=>{this._skipNextUpdate=false;this.update();});this._skipNextUpdate=false;} refresh(significantChange) {super.refresh(significantChange);if(!this._fontStyles||this._fontStyles.significantChangeSinceLastRefresh){this._throttledUpdate.force();return;} this._throttledUpdate.fire();} update() {if(this._skipNextUpdate) return;this._fontStyles?.refresh();if(!this._fontStyles||this._fontStyles.significantChangeSinceLastRefresh) this.updateLayout(); for(let propertyName of this._basicPropertyNames){let row=this._basicPropertyRowsMap.get(propertyName);let fontProperty=this._fontPropertiesMap.get(propertyName);if(row instanceof WI.DetailsSectionSimpleRow){row.value=this._formatPropertyValue(propertyName,fontProperty.value);if(propertyName==="font-style") if(this.nodeStyles.computedPrimaryFont?.synthesizedOblique) if(fontProperty.value==="italic") row.warningMessage=WI.UIString("Font was synthesized to be oblique because no italic font is available.","A warning that is shown in the Font Details Sidebar when the font had to be synthesized to support the provided style.");else row.warningMessage=WI.UIString("Font was synthesized to be oblique because no oblique font is available.","A warning that is shown in the Font Details Sidebar when the font had to be synthesized to support the provided style.");else row.warningMessage=null;if(propertyName==="font-weight") row.warningMessage=this.nodeStyles.computedPrimaryFont?.synthesizedBold?WI.UIString("Font was synthesized to be bold because no bold font is available.","A warning that is shown in the Font Details Sidebar when the font had to be synthesized to support the provided weight."):null;} if(row instanceof WI.FontVariationDetailsSectionRow){let fontVariationAxis=fontProperty.variations.values().next().value;row.value=fontVariationAxis.value?fontVariationAxis.value:WI.FontStyles.fontPropertyValueToAxisValue(fontVariationAxis.tag,fontProperty.value);}} this._fontNameRow.value=this.nodeStyles.computedPrimaryFont.name; this._fontVariantLigaturesRow.value=this._formatLigatureValue(this._fontPropertiesMap.get("font-variant-ligatures"));this._fontVariantPositionRow.value=this._formatPositionValue(this._fontPropertiesMap.get("font-variant-position"));this._fontVariantCapsRow.value=this._formatCapitalsValue(this._fontPropertiesMap.get("font-variant-caps"));this._fontVariantNumericRow.value=this._formatNumericValue(this._fontPropertiesMap.get("font-variant-numeric"));this._fontVariantAlternatesRow.value=this._formatAlternatesValue(this._fontPropertiesMap.get("font-variant-alternates"));this._fontVariantEastAsianRow.value=this._formatEastAsianValue(this._fontPropertiesMap.get("font-variant-east-asian"));let featureRows=[];for(let[key,value]of this._fontFeaturesMap) featureRows.push(new WI.DetailsSectionSimpleRow(key,value));this._fontAdditionalFeaturesGroup.rows=featureRows;this._fontAdditionalFeaturesGroup.hidden=!featureRows.length; for(let[tag,fontVariationAxis]of this._fontVariationsMap){let variationRow=this._fontVariationRowsMap.get(tag);variationRow.value=fontVariationAxis.value??fontVariationAxis.defaultValue;} if(!this._fontVariationRowsMap.size){let emptyRow=new WI.DetailsSectionRow(WI.UIString("No additional variation axes.","No additional variation axes. @ Font Details Sidebar","Message shown when there are no additional variation axes to show."));emptyRow.showEmptyMessage();this._fontVariationsGroup.rows=[emptyRow];}} detached() {super.detached();this._fontStyles=null;this._abortController?.abort();this._abortController=null;} layout() {if(this.layoutReason===WI.View.LayoutReason.Resize) return;if(!this.nodeStyles.computedStyle||!this.nodeStyles.computedPrimaryFont){this._fontStyles=null;return;} this._abortController?.abort();this._abortController=new AbortController();this._fontStyles=new WI.FontStyles(this.nodeStyles);for(let propertyName of this._basicPropertyNames){let row=this._basicPropertyRowsMap.get(propertyName);if(row) row.element.remove();this._basicPropertyRowsMap.set(propertyName,this._createDetailsSectionRowForProperty(propertyName));} this._basicPropertiesGroup.rows=[...this._basicPropertyRowsMap.values()].sort((rowA,rowB)=>{if(rowA instanceof WI.DetailsSectionSimpleRow&&rowB instanceof WI.FontVariationDetailsSectionRow) return-1;if(rowA instanceof WI.FontVariationDetailsSectionRow&&rowB instanceof WI.DetailsSectionSimpleRow) return 1;return 0;});for(let[tag,variationRow]of this._fontVariationRowsMap){variationRow.element.remove();variationRow.removeEventListener(WI.FontVariationDetailsSectionRow.Event.VariationValueChanged,this._handleFontVariationValueChanged,this);this._fontVariationRowsMap.delete(tag);} for(let[tag,fontVariationAxis]of this._fontVariationsMap){let variationRow=new WI.FontVariationDetailsSectionRow(fontVariationAxis,this._abortController.signal);variationRow.addEventListener(WI.FontVariationDetailsSectionRow.Event.VariationValueChanged,this._handleFontVariationValueChanged,this);this._fontVariationRowsMap.set(tag,variationRow);} this._fontVariationsGroup.rows=[...this._fontVariationRowsMap.values()];} initialLayout() {super.initialLayout(); this._fontNameRow=new WI.DetailsSectionSimpleRow(WI.UIString("Name","Name @ Font Details Sidebar Property","Property title for the family name of the font."));let previewGroup=new WI.DetailsSectionGroup([this._fontNameRow]);let fontNameSection=new WI.DetailsSection("font-identity",WI.UIString("Identity","Identity @ Font Details Sidebar Section","Section title for font identity information."),[previewGroup]);this.element.appendChild(fontNameSection.element); this._basicPropertiesGroup=new WI.DetailsSectionGroup();let fontBasicPropertiesSection=new WI.DetailsSection("font-basic-properties",WI.UIString("Basic Properties","Basic Properties @ Font Details Sidebar Section","Section title for basic font properties."),[this._basicPropertiesGroup]);this.element.appendChild(fontBasicPropertiesSection.element); this._fontVariantLigaturesRow=new WI.DetailsSectionSimpleRow(WI.UIString("Ligatures","Ligatures @ Font Details Sidebar Property","Property title for `font-variant-ligatures`."));this._fontVariantPositionRow=new WI.DetailsSectionSimpleRow(WI.UIString("Position","Position @ Font Details Sidebar Property","Property title for `font-variant-position`."));this._fontVariantCapsRow=new WI.DetailsSectionSimpleRow(WI.UIString("Capitals","Capitals @ Font Details Sidebar Property","Property title for `font-variant-caps`."));this._fontVariantNumericRow=new WI.DetailsSectionSimpleRow(WI.UIString("Numeric","Numeric @ Font Details Sidebar Property","Property title for `font-variant-numeric`."));this._fontVariantAlternatesRow=new WI.DetailsSectionSimpleRow(WI.UIString("Alternate Glyphs","Alternate Glyphs @ Font Details Sidebar Property","Property title for `font-variant-alternates`."));this._fontVariantEastAsianRow=new WI.DetailsSectionSimpleRow(WI.UIString("East Asian","East Asian @ Font Details Sidebar Property","Property title for `font-variant-east-asian`."));let featurePropertiesGroup=new WI.DetailsSectionGroup([this._fontVariantLigaturesRow,this._fontVariantPositionRow,this._fontVariantCapsRow,this._fontVariantNumericRow,this._fontVariantAlternatesRow,this._fontVariantEastAsianRow]);this._fontAdditionalFeaturesGroup=new WI.DetailsSectionGroup;let fontFeaturePropertiesSection=new WI.DetailsSection("font-feature-properties",WI.UIString("Feature Properties","Feature Properties @ Font Details Sidebar Section","Section title for font feature properties."),[featurePropertiesGroup,this._fontAdditionalFeaturesGroup]);this.element.appendChild(fontFeaturePropertiesSection.element); this._fontVariationsGroup=new WI.DetailsSectionGroup;let fontVariationPropertiesSection=new WI.DetailsSection("font-variation-properties",WI.UIString("Variation Properties","Variation Properties @ Font Details Sidebar Section","Section title for font variation properties."),[this._fontVariationsGroup]);this.element.appendChild(fontVariationPropertiesSection.element);} get _fontPropertiesMap() {return this._fontStyles?.propertiesMap??new Map;} get _fontVariationsMap() {return this._fontStyles?.variationsMap??new Map;} get _fontFeaturesMap() {return this._fontStyles?.featuresMap??new Map;} _createDetailsSectionRowForProperty(propertyName) {let fontProperty=this._fontPropertiesMap.get(propertyName);const labelForTag={"ital":WI.UIString("Italic","Italic @ Font Details Sidebar Property Value","Property title for `font-style` italic and `ital` variation axis."),"slnt":WI.UIString("Oblique","Oblique @ Font Details Sidebar Property Value","Property title for `font-style` oblique and `slnt` variation axis."),"opsz":WI.UIString("Optical Sizing","Optical Sizing @ Font Details Sidebar Property Value","Property title for `font-optical-sizing` and `opzs` variation axis."),"wght":WI.UIString("Weight","Weight @ Font Details Sidebar Property","Property title for `font-weight` and `wght` variation axis."),"wdth":WI.UIString("Width","Width @ Font Details Sidebar Property","Property title for `font-stretch` and `wdth` variation axis."),} let fontVariationAxis=fontProperty.variations?.values().next().value;if(fontVariationAxis){fontVariationAxis.name??=labelForTag[fontVariationAxis.tag];let variationRow=new WI.FontVariationDetailsSectionRow(fontVariationAxis,this._abortController.signal);variationRow.addEventListener(WI.FontVariationDetailsSectionRow.Event.VariationValueChanged,this._handleFontVariationValueChanged,this);return variationRow;} switch(propertyName){case"font-size":return new WI.DetailsSectionSimpleRow(WI.UIString("Size","Size @ Font Details Sidebar Property","Property title for `font-size`."));break;case"font-style":return new WI.DetailsSectionSimpleRow(WI.UIString("Style","Style @ Font Details Sidebar Property","Property title for `font-style`."));break;case"font-weight":return new WI.DetailsSectionSimpleRow(WI.UIString("Weight","Weight @ Font Details Sidebar Property","Property title for `font-weight` and `wght` variation axis."));break;case"font-stretch":return new WI.DetailsSectionSimpleRow(WI.UIString("Stretch","Stretch @ Font Details Sidebar Property","Property title for `font-stretch`."));break;}} _formatPropertyValue(propertyName,propertyValue) {switch(propertyName){case"font-size":return propertyValue;case"font-style":return propertyValue==="normal"?WI.UIString("Normal","Normal @ Font Details Sidebar Property Value","Property value for any `normal` CSS value."):propertyValue;default:return this._formatAxisValueAsString(propertyValue);}} _formatAxisValueAsString(value) {const options={minimumFractionDigits:0,maximumFractionDigits:2,useGrouping:false,} return value.toLocaleString(undefined,options);} _formatSimpleFeatureValues(property,features,noMatchesResult) {let valueParts=property.value.match(WI.FontStyles.SettingPattern);let results=[];let resultGroups=new Set;for(let feature of features){if((!feature.group||!resultGroups.has(feature.group))&&this._featureIsEnabled(property,feature.tag,valueParts.includes(feature.name))){results.push(feature.result);resultGroups.add(feature.group);}} if(results.length) return results.join(WI.UIString(", "));return noMatchesResult;} _formatLigatureValue(property) {let valueParts=property.value.match(WI.FontStyles.SettingPattern);let results=[];if(!this._featureIsEnabled(property,WI.unlocalizedString("clig"),!valueParts.includes(WI.unlocalizedString("no-common-ligatures")))) results.push(WI.UIString("Disabled Common","Disabled Common @ Font Details Sidebar Property Value","Property value for `font-variant-ligatures: no-common-ligatures`."));else results.push(WI.UIString("Common","Common @ Font Details Sidebar Property Value","Property value for `font-variant-ligatures: common-ligatures`."));let otherResults=this._formatSimpleFeatureValues(property,[{tag:WI.unlocalizedString("dlig"),name:WI.unlocalizedString("discretionary-ligatures"),result:WI.UIString("Discretionary","Discretionary @ Font Details Sidebar Property Value","Property value for `font-variant-ligatures: discretionary-ligatures`."),},{tag:WI.unlocalizedString("hlig"),name:WI.unlocalizedString("historical-ligatures"),result:WI.UIString("Historical","Historical @ Font Details Sidebar Property Value","Property value for `font-variant-ligatures: historical-ligatures`."),},{tag:WI.unlocalizedString("calt"),name:WI.unlocalizedString("contextual"),result:WI.UIString("Contextual Alternates","Contextual Alternates @ Font Details Sidebar Property Value","Property value for `font-variant-ligatures: contextual`."),},]);if(otherResults) results.push(otherResults);return results.join(WI.UIString(", "));} _formatPositionValue(property) {return this._formatSimpleFeatureValues(property,[{tag:WI.unlocalizedString("subs"),name:WI.unlocalizedString("sub"),result:WI.UIString("Subscript","Subscript @ Font Details Sidebar Property Value","Property value for `font-variant-position: sub`."),group:"position",},{tag:WI.unlocalizedString("sups"),name:WI.unlocalizedString("super"),result:WI.UIString("Superscript","Superscript @ Font Details Sidebar Property Value","Property value for `font-variant-position: super`."),group:"position",},],WI.UIString("Normal","Normal @ Font Details Sidebar Property Value","Property value for any `normal` CSS value."));} _formatCapitalsValue(property) {return this._formatSimpleFeatureValues(property,[{tag:WI.unlocalizedString("c2sc"),name:WI.unlocalizedString("all-small-caps"),result:WI.UIString("All Small Capitals","All Small Capitals @ Font Details Sidebar Property Value","Property value for `font-variant-capitals: all-small-caps`."),group:"capitals",},{tag:WI.unlocalizedString("smcp"),name:WI.unlocalizedString("small-caps"),result:WI.UIString("Small Capitals","Small Capitals @ Font Details Sidebar Property Value","Property value for `font-variant-capitals: small-caps`."),group:"capitals",},{tag:WI.unlocalizedString("c2pc"),name:WI.unlocalizedString("all-petite-caps"),result:WI.UIString("All Petite Capitals","All Petite Capitals @ Font Details Sidebar Property Value","Property value for `font-variant-capitals: all-petite-caps`."),group:"capitals",},{tag:WI.unlocalizedString("pcap"),name:WI.unlocalizedString("petite-caps"),result:WI.UIString("Petite Capitals","Petite Capitals @ Font Details Sidebar Property Value","Property value for `font-variant-capitals: petite-caps`."),group:"capitals",},{tag:WI.unlocalizedString("unic"),name:WI.unlocalizedString("unicase"),result:WI.UIString("Unicase","Unicase @ Font Details Sidebar Property Value","Property value for `font-variant-capitals: unicase`."),group:"capitals",},{tag:WI.unlocalizedString("titl"),name:WI.unlocalizedString("titling-caps"),result:WI.UIString("Titling Capitals","Titling Capitals @ Font Details Sidebar Property Value","Property value for `font-variant-capitals: titling-caps`."),group:"capitals",},],WI.UIString("Normal","Normal @ Font Details Sidebar Property Value","Property value for any `normal` CSS value."));} _formatNumericValue(property) {return this._formatSimpleFeatureValues(property,[{tag:WI.unlocalizedString("lnum"),name:WI.unlocalizedString("lining-nums"),result:WI.UIString("Lining Numerals","Lining Numerals @ Font Details Sidebar Property Value","Property value for `font-variant-numeric: lining-nums`."),group:"figures",},{tag:WI.unlocalizedString("onum"),name:WI.unlocalizedString("oldstyle-nums"),result:WI.UIString("Old-Style Numerals","Old-Style Numerals @ Font Details Sidebar Property Value","Property value for `font-variant-numeric: oldstyle-nums`."),group:"figures",},{tag:WI.unlocalizedString("pnum"),name:WI.unlocalizedString("proportional-nums"),result:WI.UIString("Proportional Numerals","Proportional Numerals @ Font Details Sidebar Property Value","Property value for `font-variant-numeric: proportional-nums`."),group:"spacing",},{tag:WI.unlocalizedString("tnum"),name:WI.unlocalizedString("tabular-nums"),result:WI.UIString("Tabular Numerals","Tabular Numerals @ Font Details Sidebar Property Value","Property value for `font-variant-numeric: tabular-nums`."),group:"spacing",},{tag:WI.unlocalizedString("frac"),name:WI.unlocalizedString("diagonal-fractions"),result:WI.UIString("Diagonal Fractions","Diagonal Fractions @ Font Details Sidebar Property Value","Property value for `font-variant-numeric: diagonal-fractions`."),group:"fractions",},{tag:WI.unlocalizedString("afrc"),name:WI.unlocalizedString("stacked-fractions"),result:WI.UIString("Stacked Fractions","Stacked Fractions @ Font Details Sidebar Property Value","Property value for `font-variant-numeric: stacked-fractions`."),group:"fractions",},{tag:WI.unlocalizedString("ordn"),name:WI.unlocalizedString("ordinal"),result:WI.UIString("Ordinal Letter Forms","Ordinal Letter Forms @ Font Details Sidebar Property Value","Property value for `font-variant-numeric: ordinal`."),},{tag:WI.unlocalizedString("zero"),name:WI.unlocalizedString("slashed-zero"),result:WI.UIString("Slashed Zeros","Slashed Zeros @ Font Details Sidebar Property Value","Property value for `font-variant-numeric: slashed-zero`."),},],WI.UIString("Normal","Normal @ Font Details Sidebar Property Value","Property value for any `normal` CSS value."));} _formatAlternatesValue(property) {return this._formatSimpleFeatureValues(property,[{tag:WI.unlocalizedString("hist"),name:WI.unlocalizedString("historical-forms"),result:WI.UIString("Historical Forms","Historical Forms @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: historical-forms`."),},],WI.UIString("Normal","Normal @ Font Details Sidebar Property Value","Property value for any `normal` CSS value."));} _formatEastAsianValue(property) {return this._formatSimpleFeatureValues(property,[{tag:WI.unlocalizedString("jp78"),name:WI.unlocalizedString("jis78"),result:WI.UIString("JIS78 Forms","JIS78 Forms @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: jis78`."),group:"forms",},{tag:WI.unlocalizedString("jp83"),name:WI.unlocalizedString("jis83"),result:WI.UIString("JIS83 Forms","JIS83 Forms @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: jis83`."),group:"forms",},{tag:WI.unlocalizedString("jp90"),name:WI.unlocalizedString("jis90"),result:WI.UIString("JIS90 Forms","JIS90 Forms @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: jis90`."),group:"forms",},{tag:WI.unlocalizedString("jp04"),name:WI.unlocalizedString("jis04"),result:WI.UIString("JIS2004 Forms","JIS2004 Forms @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: jis04`."),group:"forms",},{tag:WI.unlocalizedString("smpl"),name:WI.unlocalizedString("simplified"),result:WI.UIString("Simplified Forms","Simplified Forms @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: simplified`."),group:"forms",},{tag:WI.unlocalizedString("trad"),name:WI.unlocalizedString("traditional"),result:WI.UIString("Traditional Forms","Traditional Forms @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: traditional`."),group:"forms",},{tag:WI.unlocalizedString("fwid"),name:WI.unlocalizedString("full-width"),result:WI.UIString("Full-Width Variants","Full-Width Variants @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: full-width`."),group:"width",},{tag:WI.unlocalizedString("pwid"),name:WI.unlocalizedString("proportional-width"),result:WI.UIString("Proportional-Width Variants","Proportional-Width Variants @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: proportional-width`."),group:"width",},{tag:WI.unlocalizedString("ruby"),name:WI.unlocalizedString("ruby"),result:WI.UIString("Ruby Glyphs","Ruby Glyphs @ Font Details Sidebar Property Value","Property value for `font-variant-alternates: ruby`."),},],WI.UIString("Normal","Normal @ Font Details Sidebar Property Value","Property value for any `normal` CSS value."));} _featureIsEnabled(property,featureTag,tagNotPresentCondition) {let featureValue=property.features?.get(featureTag);if(featureValue||featureValue===0) return!!featureValue;return tagNotPresentCondition;} _handleFontVariationValueChanged(event) {this._skipNextUpdate=true;this._debouncedUpdate.delayForTime(100);this._fontStyles.writeFontVariation(event.data.tag,event.data.value);}};WI.FontDetailsSidebarPanel=class FontDetailsSidebarPanel extends WI.GeneralStyleDetailsSidebarPanel {constructor() {super("style-font",WI.UIString("Font"),WI.FontDetailsPanel);} supportsDOMNode(nodeToInspect) {if(nodeToInspect.isMediaElement()) return false;return super.supportsDOMNode(nodeToInspect);}};WI.FontResourceContentView=class FontResourceContentView extends WI.ResourceContentView {constructor(resource) {super(resource,"font");this._styleElement=null;this._previewElement=null;this._previewContainer=null;} sizeToFit() {if(!this._previewElement) return;for(var fontSize=WI.FontResourceContentView.MaximumFontSize;fontSize>=WI.FontResourceContentView.MinimumFontSize;fontSize-=5){this._previewElement.style.fontSize=fontSize+"px";if(this._previewElement.offsetWidth<=this.element.offsetWidth) break;}} contentAvailable(content,base64Encoded) {this._fontObjectURL=this.resource.createObjectURL();if(!this._fontObjectURL){this.showGenericErrorMessage();return;} this.removeLoadingIndicator();this._previewContainer=this.element.appendChild(document.createElement("div"));this._previewContainer.className="preview-container";this._updatePreviewElement();if(WI.NetworkManager.supportsOverridingResponses()){let dropZoneView=new WI.DropZoneView(this);dropZoneView.targetElement=this._previewContainer;this.addSubview(dropZoneView);if(this.resource.localResourceOverride) this.resource.addEventListener(WI.SourceCode.Event.ContentDidChange,this._handleLocalResourceContentDidChange,this);}} attached() {super.attached();if(this._styleElement) document.head.appendChild(this._styleElement);} detached() {if(this._styleElement) this._styleElement.remove();super.detached();} closed() { if(this._fontObjectURL) URL.revokeObjectURL(this._fontObjectURL);super.closed();} layout() {this.sizeToFit();} dropZoneShouldAppearForDragEvent(dropZone,event) {let existingOverrides=WI.networkManager.localResourceOverridesForURL(this.resource.url);if(existingOverrides.length>1) return false;let localResourceOverride=this.resource.localResourceOverride||existingOverrides[0];if(localResourceOverride&&!localResourceOverride.canMapToFile) return false;return event.dataTransfer.types.includes("Files");} dropZoneHandleDragEnter(dropZone,event) {if(this.resource.localResourceOverride) dropZone.text=WI.UIString("Update Font");else if(WI.networkManager.localResourceOverridesForURL(this.resource.url).length) dropZone.text=WI.UIString("Update Local Override");else dropZone.text=WI.UIString("Create Local Override");} dropZoneHandleDrop(dropZone,event) {let files=event.dataTransfer.files;if(files.length!==1){InspectorFrontendHost.beep();return;} WI.FileUtilities.readData(files,async({dataURL,mimeType,base64Encoded,content})=>{let localResourceOverride=this.resource.localResourceOverride||WI.networkManager.localResourceOverridesForURL(this.resource.url)[0];if(!localResourceOverride){localResourceOverride=await this.resource.createLocalResourceOverride(WI.LocalResourceOverride.InterceptType.Response);WI.networkManager.addLocalResourceOverride(localResourceOverride);} let revision=localResourceOverride.localResource.editableRevision;revision.updateRevisionContent(content,{base64Encoded,mimeType});if(!this.resource.localResourceOverride) WI.showLocalResourceOverride(localResourceOverride,{overriddenResource:this.resource});});} _updatePreviewElement() {if(this._styleElement) this._styleElement.remove();if(this._previewElement) this._previewElement.remove();const uniqueFontName="WebInspectorFontPreview"+(++WI.FontResourceContentView._uniqueFontIdentifier);let format="";if(this.resource.mimeTypeComponents.type==="image/svg+xml") format=" format(\"svg\")";this._styleElement=document.createElement("style");this._styleElement.textContent=`@font-face { font-family: "${uniqueFontName}"; src: url(${this._fontObjectURL}) ${format}; }`;if(this.isAttached) document.head.appendChild(this._styleElement);this._previewElement=document.createElement("div");this._previewElement.className="preview";this._previewElement.style.fontFamily=uniqueFontName;function createMetricElement(className){let metricElement=document.createElement("div");metricElement.className="metric "+className;return metricElement;} for(let line of WI.FontResourceContentView.PreviewLines){let lineElement=document.createElement("div");lineElement.className="line";lineElement.appendChild(createMetricElement("top"));lineElement.appendChild(createMetricElement("xheight"));lineElement.appendChild(createMetricElement("middle"));lineElement.appendChild(createMetricElement("baseline"));lineElement.appendChild(createMetricElement("bottom"));let contentElement=document.createElement("div");contentElement.className="content";contentElement.textContent=line;lineElement.appendChild(contentElement);this._previewElement.appendChild(lineElement);} this._previewContainer.appendChild(this._previewElement);this.sizeToFit();} _handleLocalResourceContentDidChange(event) {this._fontObjectURL=this.resource.createObjectURL();this._updatePreviewElement();}};WI.FontResourceContentView._uniqueFontIdentifier=0;WI.FontResourceContentView.PreviewLines=["ABCDEFGHIJKLM","NOPQRSTUVWXYZ","abcdefghijklm","nopqrstuvwxyz","1234567890"];WI.FontResourceContentView.MaximumFontSize=72;WI.FontResourceContentView.MinimumFontSize=12;WI.FontVariationDetailsSectionRow=class FontVariationDetailsSectionRow extends WI.DetailsSectionRow {constructor(fontVariationAxis,abortSignal) {super();this.element.classList.add("font-variation");let{name,tag,value,defaultValue,minimumValue,maximumValue}=fontVariationAxis;this._tag=tag;this._minimumValue=minimumValue;this._maximumValue=maximumValue;this._step=this._getAxisResolution();this._labelElement=this.element.appendChild(document.createElement("div"));this._labelElement.className="label";this._tagElement=this.element.appendChild(document.createElement("div"));this._tagElement.className="tag";this._tagElement.textContent=this._tag;this._tagElement.tooltip=WI.UIString("Variation axis tag","Tag tooltip @ Font Details Sidebar","Tooltip for a variation axis tag that explains what the 4-character label represents.");this._variationRangeElement=this.element.appendChild(document.createElement("div"));this._variationRangeElement.className="variation-range";this._valueSliderElement=this._variationRangeElement.appendChild(document.createElement("input"));this._valueSliderElement.type="range";this._valueSliderElement.name=tag;this._valueSliderElement.min=minimumValue;this._valueSliderElement.max=maximumValue;this._valueSliderElement.step=this._step;this._variationMinValueElement=this._variationRangeElement.appendChild(document.createElement("div"));this._variationMinValueElement.className="variation-minvalue";this._variationMinValueElement.textContent=this._formatAxisValueAsString(minimumValue);this._variationMinValueElement.tooltip=WI.UIString("Minimum value of variation axis","Min axis value @ Font Details Sidebar");this._variationMaxValueElement=this._variationRangeElement.appendChild(document.createElement("div"));this._variationMaxValueElement.className="variation-maxvalue";this._variationMaxValueElement.textContent=this._formatAxisValueAsString(maximumValue);this._variationMinValueElement.tooltip=WI.UIString("Maximum value of variation axis","Max axis value @ Font Details Sidebar");this._valueTextFieldElement=this.element.appendChild(document.createElement("input"));this._valueTextFieldElement.type="text";this._valueTextFieldElement.name=tag;this._valueTextFieldElement.className="value";this._valueTextFieldElement.addEventListener("keydown",this._handleValueTextFieldKeydown.bind(this),{signal:abortSignal});this._valueTextFieldElement.addEventListener("input",this._handleValueTextFieldInput.bind(this),{signal:abortSignal});this._valueTextFieldElement.addEventListener("blur",this._handleValueTextFieldBlur.bind(this),{signal:abortSignal});this._valueSliderElement.addEventListener("input",this._handleValueSliderInput.bind(this),{signal:abortSignal});this.label=name;this.value=value??defaultValue;this._defaultValue=defaultValue;this._hasValidValue=true;this._skipUpdatingInputValue=false;} get tag() {return this._tag;} set tag(value) {this._tag=value;this._tagElement.textContent=value;} get label() {return this._label;} set label(label) {this._label=label||"";if(this._label instanceof Node){this._labelElement.removeChildren();this._labelElement.appendChild(this._label);}else this._labelElement.textContent=this._label;} get value() {return this._value;} set value(value) {this._value=value??this._defaultValue;this._valueSliderElement.value=this._value;if(!this._hasValidValue&&window.document.activeElement===this._valueTextFieldElement) return;this._valueTextFieldElement.value=this._formatAxisValueAsString(this._value);this._hasValidValue=this._minimumValue<=this._value&&this._value<=this._maximumValue;this._showValidity();} _formatAxisValueAsString(value) {const options={minimumFractionDigits:0,maximumFractionDigits:2,useGrouping:false,} return value.toLocaleString(undefined,options);} _getAxisResolution() {if(this._tag==="ital"&&this._minimumValue===0&&this._maximumValue===1) return 1;let delta=this._maximumValue-this._minimumValue;if(delta<=1) return 0.01;if(delta<=10) return 0.1;return 1;} _showValidity() {if(!this._hasValidValue) this.warningMessage=WI.UIString("Axis value outside of supported range: %s – %s","A warning that is shown in the Font Details Sidebar when the value for a variation axis is outside of the supported range of values").format(this._formatAxisValueAsString(this._minimumValue),this._formatAxisValueAsString(this._maximumValue));else this.warningMessage=null;} _handleValueTextFieldBlur(event) {this.value=this._value;} _handleValueTextFieldInput(event) {let valueAsString=event.target.value;let valueAsNumber=parseFloat(event.target.value);if(!/^\-?\d+(\.\d+)?$/.test(valueAsString)){this._hasValidValue=false;if(valueAsString!==""||valueAsString!=="-") this._showValidity();this.dispatchEventToListeners(WI.FontVariationDetailsSectionRow.Event.VariationValueChanged,{tag:this._tag,value:this._defaultValue});return;} if(valueAsNumberthis._maximumValue){this._hasValidValue=false;this._showValidity();this.dispatchEventToListeners(WI.FontVariationDetailsSectionRow.Event.VariationValueChanged,{tag:this._tag,value:Number.constrain(valueAsNumber,this._minimumValue,this._maximumValue)});return;} this._hasValidValue=true;this.value=valueAsNumber;this.dispatchEventToListeners(WI.FontVariationDetailsSectionRow.Event.VariationValueChanged,{tag:this._tag,value:valueAsNumber});} _handleValueTextFieldKeydown(event) {if(event.key.length===1&&!/[0-9\.\-]/.test(event.key)){event.preventDefault();return;} let valueAsNumber=parseFloat(event.target.value);let step=this._step;if(isNaN(valueAsNumber)) return;if(event.shiftKey&&event.altKey) step=this._step;else if(event.shiftKey) step=this._step*10;else if(event.altKey) step=this._step/10;if(event.key==="ArrowUp"){this.value=Number.constrain(valueAsNumber+step,this._minimumValue,this._maximumValue);this.dispatchEventToListeners(WI.FontVariationDetailsSectionRow.Event.VariationValueChanged,{tag:this._tag,value:this.value});event.preventDefault();} if(event.key==="ArrowDown"){this.value=Number.constrain(valueAsNumber-step,this._minimumValue,this._maximumValue);this.dispatchEventToListeners(WI.FontVariationDetailsSectionRow.Event.VariationValueChanged,{tag:this._tag,value:this.value});event.preventDefault();}} _handleValueSliderInput(event) {this.value=event.target.valueAsNumber;this.dispatchEventToListeners(WI.FontVariationDetailsSectionRow.Event.VariationValueChanged,{tag:this._tag,value:this._value});}};WI.FontVariationDetailsSectionRow.Event={VariationValueChanged:"font-variation-value-changed",};WI.FormattedValue={};WI.FormattedValue.MaxPreviewStringLength=140;WI.FormattedValue.isSimpleString=function(string) {return string.length<=WI.FormattedValue.MaxPreviewStringLength&&!string.slice(0,WI.FormattedValue.MaxPreviewStringLength).includes("\n");};WI.FormattedValue.hasSimpleDisplay=function(object) {switch(object.type){case"boolean":case"number":case"symbol":case"bigint":case"undefined":return true;case"string":return WI.FormattedValue.isSimpleString(object.description);case"function":return false;case"object":var subtype=object.subtype;return subtype==="null"||subtype==="regexp"||subtype==="date";} return false;};WI.FormattedValue.classNameForTypes=function(type,subtype) {return"formatted-"+(subtype?subtype:type);};WI.FormattedValue.classNameForObject=function(object) {return WI.FormattedValue.classNameForTypes(object.type,object.subtype);};WI.FormattedValue.createLinkifiedElementString=function(string) {var span=document.createElement("span");span.className="formatted-string";span.append("\"",WI.linkifyStringAsFragment(string.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")),"\"");return span;};WI.FormattedValue.createElementForNode=function(object) {var span=document.createElement("span");span.className="formatted-node";object.pushNodeToFrontend(function(nodeId){if(!nodeId){span.textContent=object.description;return;} var treeOutline=new WI.DOMTreeOutline;treeOutline.setVisible(true);treeOutline.rootDOMNode=WI.domManager.nodeForId(nodeId);if(!treeOutline.children[0].hasChildren) treeOutline.element.classList.add("single-node");span.appendChild(treeOutline.element);});return span;};WI.FormattedValue.createElementForError=function(object) {var span=document.createElement("span");span.classList.add("formatted-error");span.textContent=object.description;if(!object.preview) return span;function previewToObject(preview) {var result={};for(var property of preview.propertyPreviews) result[property.name]=property.value;return result;} var preview=previewToObject(object.preview);if(!preview.sourceURL) return span;var sourceLinkWithPrefix=WI.ErrorObjectView.makeSourceLinkWithPrefix(preview.sourceURL,preview.line,preview.column);span.append(sourceLinkWithPrefix);return span;};WI.FormattedValue.createElementForNodePreview=function(preview,{remoteObjectAccessor}={}) {var value=preview.value||preview.description;var span=document.createElement("span");span.className="formatted-node-preview syntax-highlighted";if(remoteObjectAccessor){let domNode=null;span.addEventListener("mouseenter",(event)=>{if(domNode){domNode.highlight();return;} remoteObjectAccessor((remoteObject)=>{remoteObject.pushNodeToFrontend((nodeId)=>{domNode=WI.domManager.nodeForId(nodeId);if(domNode) domNode.highlight();});});});span.addEventListener("mouseleave",(event)=>{WI.domManager.hideDOMNodeHighlight();});span.addEventListener("contextmenu",(event)=>{if(!domNode) return;let contextMenu=WI.ContextMenu.createFromEvent(event);WI.appendContextMenuItemsForDOMNode(contextMenu,domNode);});} if(value.startsWith("0) snapshot.context.restore();};if(!snapshot){snapshot=this._snapshots[snapshotIndex]={};snapshot.index=snapshotIndex*WI.RecordingContentView.SnapshotInterval;while(snapshot.index&&actions[snapshot.index].name!=="beginPath") --snapshot.index;snapshot.context=this.representedObject.createContext();snapshot.element=snapshot.context.canvas;let lastSnapshotIndex=snapshotIndex;while(--lastSnapshotIndex>=0){if(this._snapshots[lastSnapshotIndex]) break;} let startIndex=0;if(lastSnapshotIndex<0){snapshot.content=this._initialContent;snapshot.states=actions[0].states;snapshot.attributes=Object.shallowCopy(initialState.attributes);}else{let lastSnapshot=this._snapshots[lastSnapshotIndex];snapshot.content=lastSnapshot.content;snapshot.states=lastSnapshot.states;snapshot.attributes={};for(let attribute in initialState.attributes) snapshot.attributes[attribute]=lastSnapshot.element[attribute];startIndex=lastSnapshot.index;} applyActions(startIndex,snapshot.index-1);if(snapshot.index>0) snapshot.states=actions[snapshot.index-1].states;snapshot.content=new Image;snapshot.content.src=snapshot.element.toDataURL();snapshot.content.addEventListener("load",imageLoad);return;} this._previewContainer.removeChildren();if(WI.settings.showCanvasPath.value){indexOfLastBeginPathAction=this._index;while(indexOfLastBeginPathAction>snapshot.index&&actions[indexOfLastBeginPathAction].name!=="beginPath") --indexOfLastBeginPathAction;} applyActions(snapshot.index,this._index);this._previewContainer.insertAdjacentElement("afterbegin",snapshot.element);this._updateImageGrid();} _generateContentFromSnapshot(index) {let imageLoad=(event)=>{if(index!==this._index) return;this._generateContentFromSnapshot(index);};let initialState=this.representedObject.initialState;if(initialState.content&&!this._initialContent){this._initialContent=new Image;this._initialContent.src=initialState.content;this._initialContent.addEventListener("load",imageLoad);return;} let actions=this.representedObject.actions;let visualIndex=index;while(!actions[visualIndex].isVisual&&!(actions[visualIndex]instanceof WI.RecordingInitialStateAction)) visualIndex--;let snapshot=this._snapshots[visualIndex];if(!snapshot){if(actions[visualIndex].snapshot){snapshot=this._snapshots[visualIndex]={element:new Image};snapshot.element.src=actions[visualIndex].snapshot;snapshot.element.addEventListener("load",imageLoad);return;} if(actions[visualIndex]instanceof WI.RecordingInitialStateAction) snapshot=this._snapshots[visualIndex]={element:this._initialContent};} if(snapshot){this._previewContainer.removeChildren();this._previewContainer.appendChild(snapshot.element);this._updateImageGrid();}} _updateExportButton() {if(this._saveMode!==WI.FileUtilities.SaveMode.SingleFile) return;if(this.representedObject.isCanvas2D&&this.representedObject.ready) this._exportButtonNavigationItem.tooltip=WI.UIString("Export recording (%s)\nShift-click to export a HTML reduction").format(WI.saveKeyboardShortcut.displayName);else this._exportButtonNavigationItem.tooltip=WI.UIString("Export recording (%s)").format(WI.saveKeyboardShortcut.displayName);} _updateCanvasPath() {let activated=WI.settings.showCanvasPath.value;if(this._showPathButtonNavigationItem.activated!==activated) this._generateContentCanvas2D(this._index);this._showPathButtonNavigationItem.activated=activated;} _updateImageGrid() {let activated=WI.settings.showImageGrid.value;this._showGridButtonNavigationItem.activated=activated;if(this.didInitialLayout&&!isNaN(this._index)) this._previewContainer.firstElementChild.classList.toggle("show-grid",activated);} _updateSliderValue() {if(!this._sliderElement) return;let visualActionIndexes=this.representedObject.visualActionIndexes;let visualActionIndex=0;if(this._index>0){while(visualActionIndexobject instanceof WI.Recording&&object.isCanvas2D);this.action=objects.find((object)=>object instanceof WI.RecordingAction);return this._recording&&this._action;} set recording(recording) {if(recording===this._recording) return;this._recording=recording;this._action=null;for(let subview of this.contentView.subviews) this.contentView.removeSubview(subview);this._dataGrids=[];} set action(action) {if(!this._recording||action===this._action) return;this._action=action;if(this._action&&this._recording.isCanvas2D) this._generateDetailsCanvas2D(this._action);this.updateLayoutIfNeeded();} get scrollElement() {if(this._dataGrids.length===1) return this._dataGrids[0].scrollContainer;return super.scrollElement;} sizeDidChange() {super.sizeDidChange();if(this._dataGrids.length===1) return; for(let dataGrid of this._dataGrids) dataGrid.sizeDidChange();} _generateDetailsCanvas2D(action) {if(this._dataGrids.length===1) this.contentView.removeSubview(this._dataGrids[0]);this.contentView.element.removeChildren();this._dataGrids=[];let currentState=action.states.lastValue;if(!currentState) return;let createStateDataGrid=(state)=>{let dataGrid=new WI.DataGrid({name:{title:WI.UIString("Name")},value:{title:WI.UIString("Value")},});this._dataGrids.push(dataGrid);for(let[name,value]of state){if(name==="setPath") continue;if(typeof value==="object"){let isGradient=value instanceof CanvasGradient;let isPattern=value instanceof CanvasPattern;if(isGradient||isPattern){let textElement=document.createElement("span");textElement.classList.add("unavailable");let image=null;if(isGradient){textElement.textContent=WI.unlocalizedString("CanvasGradient");image=WI.ImageUtilities.imageFromCanvasGradient(value,100,100);}else if(isPattern){textElement.textContent=WI.unlocalizedString("CanvasPattern");image=value.__image;} let fragment=document.createDocumentFragment();if(image){let swatch=new WI.InlineSwatch(WI.InlineSwatch.Type.Image,image);fragment.appendChild(swatch.element);} fragment.appendChild(textElement);value=fragment;}else{if(value instanceof DOMMatrix) value=[value.a,value.b,value.c,value.d,value.e,value.f];value=JSON.stringify(value);}}else if(name==="fillStyle"||name==="strokeStyle"||name==="shadowColor"){let color=WI.Color.fromString(value);let swatch=new WI.InlineSwatch(WI.InlineSwatch.Type.Color,color,{readOnly:true});value=document.createElement("span");value.append(swatch.element,color.toString());} let classNames=[];if(state===currentState&&!action.isGetter&&action.stateModifiers.has(name)) classNames.push("modified");if(name.startsWith("webkit")) classNames.push("non-standard");dataGrid.appendChild(new WI.DataGridNode({name,value},{classNames}));} dataGrid.updateLayoutIfNeeded();return dataGrid;};let createStateSection=(state,index=NaN)=>{let isCurrentState=isNaN(index);let dataGrid=createStateDataGrid(state);let row=new WI.DetailsSectionDataGridRow(dataGrid);let group=new WI.DetailsSectionGroup([row]);let identifier=isCurrentState?"recording-current-state":`recording-saved-state-${index + 1}`;const title=null;const optionsElement=null;let defaultCollapsedSettingValue=!isCurrentState;let section=new WI.DetailsSection(identifier,title,[group],optionsElement,defaultCollapsedSettingValue);if(isCurrentState) section.title=WI.UIString("Current State");else{section.title=WI.UIString("Save %d").format(index+1);if(state.source){let sourceIndex=this._recording.actions.indexOf(state.source);if(sourceIndex>=0){let sourceElement=section.titleElement.appendChild(document.createElement("span"));sourceElement.classList.add("source");sourceElement.textContent=WI.UIString("(Action %s)").format(sourceIndex);}}} return section;};if(action.states.length===1){this.contentView.addSubview(createStateDataGrid(currentState));return;} let currentStateSection=createStateSection(currentState);this.contentView.element.appendChild(currentStateSection.element);let savedStateSections=[];for(let i=action.states.length-2;i>=0;--i){let savedStateSection=createStateSection(action.states[i],i);savedStateSections.push(savedStateSection);} let savedStatesGroup=new WI.DetailsSectionGroup(savedStateSections);let savedStatesSection=new WI.DetailsSection("recording-saved-states",WI.UIString("Saved States"),[savedStatesGroup]);this.contentView.element.appendChild(savedStatesSection.element);}};WI.RecordingTraceDetailsSidebarPanel=class RecordingTraceDetailsSidebarPanel extends WI.DetailsSidebarPanel {constructor() {super("recording-trace",WI.UIString("Trace"));const selectable=false;this._backtraceTreeOutline=new WI.TreeOutline(selectable);this._backtraceTreeOutline.disclosureButtons=false;this._backtraceTreeController=new WI.StackTraceTreeController(this._backtraceTreeOutline);this._recording=null;this._action=null;} inspect(objects) {if(!(objects instanceof Array)) objects=[objects];this.recording=objects.find((object)=>object instanceof WI.Recording);this.action=objects.find((object)=>object instanceof WI.RecordingAction);return this._recording&&this._action;} set recording(recording) {if(recording===this._recording) return;this._recording=recording;this._action=null;this.contentView.element.removeChildren();} set action(action) {if(!this._recording||action===this._action) return;this._action=action;this.contentView.element.removeChildren();if(!this._action) return;let stackTrace=this._action.stackTrace;this._backtraceTreeController.stackTrace=stackTrace;if(!stackTrace?.callFrames.length){let noStackTraceContainerElement=this.contentView.element.appendChild(document.createElement("div"));noStackTraceContainerElement.classList.add("no-stack-trace");let noStackTraceMessageElement=noStackTraceContainerElement.appendChild(document.createElement("div"));noStackTraceMessageElement.classList.add("message");noStackTraceMessageElement.textContent=WI.UIString("Call Stack Unavailable");return;} this.contentView.element.appendChild(this._backtraceTreeOutline.element);}};WI.RenderingFrameTimelineDataGridNode=class RenderingFrameTimelineDataGridNode extends WI.TimelineDataGridNode {constructor(record,options={}) {super([record],options);} get data() {if(this._cachedData) return this._cachedData;this._cachedData=super.data;this._cachedData.name=WI.TimelineTabContentView.displayNameForRecord(this.record);this._cachedData.startTime=this.record.startTime-(this.graphDataSource?this.graphDataSource.zeroTime:0);this._cachedData.totalTime=this.record.duration;this._cachedData.scriptTime=this.record.durationForTask(WI.RenderingFrameTimelineRecord.TaskType.Script);this._cachedData.layoutTime=this.record.durationForTask(WI.RenderingFrameTimelineRecord.TaskType.Layout);this._cachedData.paintTime=this.record.durationForTask(WI.RenderingFrameTimelineRecord.TaskType.Paint);this._cachedData.otherTime=this.record.durationForTask(WI.RenderingFrameTimelineRecord.TaskType.Other);return this._cachedData;} createCellContent(columnIdentifier,cell) {const higherResolution=true;var value=this.data[columnIdentifier];switch(columnIdentifier){case"name":cell.classList.add(...this.iconClassNames());return value;case"startTime":return isNaN(value)?emDash:Number.secondsToString(value,higherResolution);case"scriptTime":case"layoutTime":case"paintTime":case"otherTime":case"totalTime":return(isNaN(value)||value===0)?emDash:Number.secondsToString(value,higherResolution);} return super.createCellContent(columnIdentifier,cell);}};WI.RenderingFrameTimelineOverviewGraph=class RenderingFrameTimelineOverviewGraph extends WI.TimelineOverviewGraph {constructor(timeline,timelineOverview) {super(timelineOverview);this.element.classList.add("rendering-frame");this.element.addEventListener("click",this._mouseClicked.bind(this));this._renderingFrameTimeline=timeline;this._renderingFrameTimeline.addEventListener(WI.Timeline.Event.RecordAdded,this._timelineRecordAdded,this);this._selectedFrameMarker=document.createElement("div");this._selectedFrameMarker.classList.add("frame-marker");this._timelineRecordFrames=[];this._selectedTimelineRecordFrame=null;this._graphHeightSeconds=NaN;this._framesPerSecondDividerMap=new Map;this.reset();} get graphHeightSeconds() {if(!isNaN(this._graphHeightSeconds)) return this._graphHeightSeconds;var maximumFrameDuration=this._renderingFrameTimeline.records.reduce(function(previousValue,currentValue){return Math.max(previousValue,currentValue.duration);},0);this._graphHeightSeconds=maximumFrameDuration*1.1;this._graphHeightSeconds=Math.min(this._graphHeightSeconds,WI.RenderingFrameTimelineOverviewGraph.MaximumGraphHeightSeconds);this._graphHeightSeconds=Math.max(this._graphHeightSeconds,WI.RenderingFrameTimelineOverviewGraph.MinimumGraphHeightSeconds);return this._graphHeightSeconds;} reset() {super.reset();this.element.removeChildren();this.selectedRecord=null;this._framesPerSecondDividerMap.clear();} recordWasFiltered(record,filtered) {super.recordWasFiltered(record,filtered);if(!(record instanceof WI.RenderingFrameTimelineRecord)) return;record[WI.RenderingFrameTimelineOverviewGraph.RecordWasFilteredSymbol]=filtered;const startIndex=Math.floor(this.startTime);const endIndex=Math.min(Math.floor(this.endTime),this._renderingFrameTimeline.records.length-1);if(record.frameIndexendIndex) return;const frameIndex=record.frameIndex-startIndex;this._timelineRecordFrames[frameIndex].filtered=filtered;} get height() {return 108;} layout() {super.layout();if(this.hidden) return;if(!this._renderingFrameTimeline.records.length) return;let records=this._renderingFrameTimeline.records;let startIndex=Math.floor(this.startTime);let endIndex=Math.min(Math.floor(this.endTime),records.length-1);let recordFrameIndex=0;for(let i=startIndex;i<=endIndex;++i){let record=records[i];let timelineRecordFrame=this._timelineRecordFrames[recordFrameIndex];if(!timelineRecordFrame) timelineRecordFrame=this._timelineRecordFrames[recordFrameIndex]=new WI.TimelineRecordFrame(this,record);else timelineRecordFrame.record=record;timelineRecordFrame.refresh(this);if(!timelineRecordFrame.element.parentNode) this.element.appendChild(timelineRecordFrame.element);timelineRecordFrame.filtered=record[WI.RenderingFrameTimelineOverviewGraph.RecordWasFilteredSymbol]||false;++recordFrameIndex;} for(;recordFrameIndex=this.timelineOverview.scrollStartTime+visibleDuration){var scrollStartTime=frameIndex;if(!this._selectedTimelineRecordFrame||Math.abs(this._selectedTimelineRecordFrame.record.frameIndex-this.selectedRecord.frameIndex)>1){scrollStartTime-=Math.floor(visibleDuration/2);scrollStartTime=Math.max(Math.min(scrollStartTime,this.timelineOverview.endTime),this.timelineOverview.startTime);} this.timelineOverview.scrollStartTime=scrollStartTime;return;} this._updateFrameMarker();} _timelineRecordAdded(event) {this._graphHeightSeconds=NaN;this.needsLayout();} _updateDividers() {if(this.graphHeightSeconds===0) return;let overviewGraphHeight=this.height;function createDividerAtPosition(framesPerSecond) {var secondsPerFrame=1/framesPerSecond;var dividerTop=1-secondsPerFrame/this.graphHeightSeconds;if(dividerTop<0.01||dividerTop>=1) return;var divider=this._framesPerSecondDividerMap.get(framesPerSecond);if(!divider){divider=document.createElement("div");divider.classList.add("divider");var label=document.createElement("div");label.classList.add("label");label.innerText=WI.UIString("%d FPS").format(framesPerSecond);divider.appendChild(label);this.element.appendChild(divider);this._framesPerSecondDividerMap.set(framesPerSecond,divider);} divider.style.marginTop=(dividerTop*overviewGraphHeight).toFixed(2)+"px";} createDividerAtPosition.call(this,60);createDividerAtPosition.call(this,30);} _updateFrameMarker() {if(this._selectedTimelineRecordFrame){this._selectedTimelineRecordFrame.selected=false;this._selectedTimelineRecordFrame=null;} if(!this.selectedRecord){if(this._selectedFrameMarker.parentElement) this.element.removeChild(this._selectedFrameMarker);return;} var frameWidth=1/this.timelineOverview.secondsPerPixel;this._selectedFrameMarker.style.width=frameWidth+"px";var markerLeftPosition=this.selectedRecord.frameIndex-this.startTime;let property=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"right":"left";this._selectedFrameMarker.style.setProperty(property,((markerLeftPosition/this.timelineOverview.visibleDuration)*100).toFixed(2)+"%");if(!this._selectedFrameMarker.parentElement) this.element.appendChild(this._selectedFrameMarker);var index=this._timelineRecordFrames.binaryIndexOf(this.selectedRecord,function(record,frame){return frame.record?record.frameIndex-frame.record.frameIndex:-1;});if(index<0||index>=this._timelineRecordFrames.length) return;this._selectedTimelineRecordFrame=this._timelineRecordFrames[index];this._selectedTimelineRecordFrame.selected=true;} _mouseClicked(event) {let position=0;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL) position=this.element.totalOffsetRight-event.pageX;else position=event.pageX-this.element.totalOffsetLeft;var frameIndex=Math.floor(position*this.timelineOverview.secondsPerPixel+this.startTime);if(frameIndex<0||frameIndex>=this._renderingFrameTimeline.records.length) return;var newSelectedRecord=this._renderingFrameTimeline.records[frameIndex];if(newSelectedRecord[WI.RenderingFrameTimelineOverviewGraph.RecordWasFilteredSymbol]) return;event.__timelineRecordClickEventHandled=true;if(this.selectedRecord===newSelectedRecord) return;if(frameIndex>=this.timelineOverview.selectionStartTime&&frameIndex=records.length) return Infinity;return records[startIndex].startTime;} get filterEndTime() {let records=this.representedObject.records;let endIndex=this.endTime-1;if(endIndex>=records.length) return Infinity;return records[endIndex].endTime;} reset() {super.reset();this._dataGrid.reset();this._pendingRecords=[];} dataGridNodePathComponentSelected(event) {let dataGridNode=event.data.pathComponent.timelineDataGridNode;dataGridNode.revealAndSelect();} matchDataGridNodeAgainstCustomFilters(node) {if(!super.matchDataGridNodeAgainstCustomFilters(node)) return false;let selectedScopeBarItem=this._scopeBar.selectedItems[0];if(!selectedScopeBarItem||selectedScopeBarItem.id===WI.RenderingFrameTimelineView.DurationFilter.All) return true;while(node&&!(node.record instanceof WI.RenderingFrameTimelineRecord)) node=node.parent;if(!node) return false;let minimumDuration=selectedScopeBarItem.id===WI.RenderingFrameTimelineView.DurationFilter.OverOneMillisecond?0.001:0.015;return node.record.duration>minimumDuration;} layout() {this._processPendingRecords();} _processPendingRecords() {if(!this._pendingRecords.length) return;for(let renderingFrameTimelineRecord of this._pendingRecords){let dataGridNode=new WI.RenderingFrameTimelineDataGridNode(renderingFrameTimelineRecord,{graphDataSource:this,});this._dataGrid.addRowInSortOrder(dataGridNode);let stack=[{children:renderingFrameTimelineRecord.children,parentDataGridNode:dataGridNode,index:0}];while(stack.length){let entry=stack.lastValue;if(entry.index>=entry.children.length){stack.pop();continue;} let childRecord=entry.children[entry.index];let childDataGridNode=null;if(childRecord.type===WI.TimelineRecord.Type.Layout){childDataGridNode=new WI.LayoutTimelineDataGridNode(childRecord,{graphDataSource:this,});this._dataGrid.addRowInSortOrder(childDataGridNode,entry.parentDataGridNode);}else if(childRecord.type===WI.TimelineRecord.Type.Script){let rootNodes=[];if(childRecord.profile){rootNodes=childRecord.profile.topDownRootNodes;} childDataGridNode=new WI.ScriptTimelineDataGridNode(childRecord,{graphDataSource:this,});this._dataGrid.addRowInSortOrder(childDataGridNode,entry.parentDataGridNode);for(let profileNode of rootNodes){let profileNodeDataGridNode=new WI.ProfileNodeDataGridNode(profileNode,{graphDataSource:this,});this._dataGrid.addRowInSortOrder(profileNodeDataGridNode,childDataGridNode);}} if(childDataGridNode&&childRecord.children.length) stack.push({children:childRecord.children,parentDataGridNode:childDataGridNode,index:0});++entry.index;}} this._pendingRecords=[];} _renderingFrameTimelineRecordAdded(event) {let renderingFrameTimelineRecord=event.data.record;this._processRecord(renderingFrameTimelineRecord);this.needsLayout();} _processRecord(renderingFrameTimelineRecord) {this._pendingRecords.push(renderingFrameTimelineRecord);} _scopeBarSelectionDidChange() {this._dataGrid.filterDidChange();}};WI.RenderingFrameTimelineView.DurationFilter={All:"rendering-frame-timeline-view-duration-filter-all",OverOneMillisecond:"rendering-frame-timeline-view-duration-filter-over-1-ms",OverFifteenMilliseconds:"rendering-frame-timeline-view-duration-filter-over-15-ms"};WI.RenderingFrameTimelineView.ReferencePage=WI.ReferencePage.TimelinesTab.FramesView;WI.Resizer=class Resizer extends WI.Object {constructor(ruleOrientation,delegate) {super();this._delegate=delegate;this._orientation=ruleOrientation;this._element=document.createElement("div");this._element.classList.add("resizer");if(this._orientation===WI.Resizer.RuleOrientation.Horizontal) this._element.classList.add("horizontal-rule");else if(this._orientation===WI.Resizer.RuleOrientation.Vertical) this._element.classList.add("vertical-rule");this._element.addEventListener("mousedown",this._resizerMouseDown.bind(this),false);this._resizerMouseMovedEventListener=this._resizerMouseMoved.bind(this);this._resizerMouseUpEventListener=this._resizerMouseUp.bind(this);} get element() {return this._element;} get orientation() {return this._orientation;} get initialPosition() {return this._resizerMouseDownPosition||NaN;} _currentPosition() {if(this._orientation===WI.Resizer.RuleOrientation.Vertical) return event.pageX;if(this._orientation===WI.Resizer.RuleOrientation.Horizontal) return event.pageY;} _resizerMouseDown(event) {if(event.button!==0||event.ctrlKey) return;this._resizerMouseDownPosition=this._currentPosition();var delegateRequestedAbort=false;if(typeof this._delegate.resizerDragStarted==="function") delegateRequestedAbort=this._delegate.resizerDragStarted(this,event.target);if(delegateRequestedAbort){delete this._resizerMouseDownPosition;return;} if(this._orientation===WI.Resizer.RuleOrientation.Vertical) document.body.style.cursor="col-resize";else{document.body.style.cursor="row-resize";} document.addEventListener("mousemove",this._resizerMouseMovedEventListener,false);document.addEventListener("mouseup",this._resizerMouseUpEventListener,false);event.preventDefault();event.stopPropagation();if(WI._elementDraggingGlassPane) WI._elementDraggingGlassPane.remove();var glassPaneElement=document.createElement("div");glassPaneElement.className="glass-pane-for-drag";document.body.appendChild(glassPaneElement);WI._elementDraggingGlassPane=glassPaneElement;} _resizerMouseMoved(event) {event.preventDefault();event.stopPropagation();if(typeof this._delegate.resizerDragging==="function") this._delegate.resizerDragging(this,this._resizerMouseDownPosition-this._currentPosition());} _resizerMouseUp(event) {if(event.button!==0||event.ctrlKey) return;document.body.style.removeProperty("cursor");if(WI._elementDraggingGlassPane){WI._elementDraggingGlassPane.remove();delete WI._elementDraggingGlassPane;} document.removeEventListener("mousemove",this._resizerMouseMovedEventListener,false);document.removeEventListener("mouseup",this._resizerMouseUpEventListener,false);event.preventDefault();event.stopPropagation();if(typeof this._delegate.resizerDragEnded==="function") this._delegate.resizerDragEnded(this);delete this._resizerMouseDownPosition;}};WI.Resizer.RuleOrientation={Horizontal:Symbol("resizer-rule-orientation-horizontal"),Vertical:Symbol("resizer-rule-orientation-vertical"),};WI.ResourceClusterContentView=class ResourceClusterContentView extends WI.ClusterContentView {constructor(resource,{disableDropZone}={}) {super(resource);this._resource=resource;this._resource.addEventListener(WI.Resource.Event.TypeDidChange,this._resourceTypeDidChange,this);this._resource.addEventListener(WI.Resource.Event.LoadingDidFinish,this._resourceLoadingDidFinish,this);this._disableDropZone=disableDropZone||false;this._responsePathComponent=this._createPathComponent({displayName:WI.UIString("Response"),identifier:ResourceClusterContentView.Identifier.Response,styleClassNames:["response-icon"],});if(this._canShowRequestContentView()){this._requestPathComponent=this._createPathComponent({displayName:WI.UIString("Request"),identifier:ResourceClusterContentView.Identifier.Request,styleClassNames:["request-icon"],nextSibling:this._responsePathComponent,});this._tryEnableCustomRequestContentViews();} this._currentContentViewSetting=new WI.Setting("resource-current-view-"+this._resource.url.hash,ResourceClusterContentView.Identifier.Response);this._tryEnableCustomResponseContentViews();} get resource(){return this._resource;} get selectionPathComponents() {let currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView) return[];if(!this._canShowRequestContentView()&&!this._canShowCustomRequestContentView()&&!this._canShowCustomResponseContentView()) return currentContentView.selectionPathComponents;let components=[this._pathComponentForContentView(currentContentView)];return components.concat(currentContentView.selectionPathComponents);} attached() {super.attached();if(this._shownInitialContent) return;this._showContentViewForIdentifier(this._currentContentViewSetting.value);} closed() {super.closed();this._shownInitialContent=false;} restoreFromCookie(cookie) {let contentView=this._showContentViewForIdentifier(cookie[WI.ResourceClusterContentView.ContentViewIdentifierCookieKey]);if(contentView.revealPosition){let textRangeToSelect=null;if(!isNaN(cookie.startLine)&&!isNaN(cookie.startColumn)&&!isNaN(cookie.endLine)&&!isNaN(cookie.endColumn)) textRangeToSelect=new WI.TextRange(cookie.startLine,cookie.startColumn,cookie.endLine,cookie.endColumn);let position=null;if(!isNaN(cookie.lineNumber)&&!isNaN(cookie.columnNumber)) position=new WI.SourceCodePosition(cookie.lineNumber,cookie.columnNumber);else if(textRangeToSelect) position=textRangeToSelect.startPosition();let scrollOffset=null;if(!isNaN(cookie.scrollOffsetX)&&!isNaN(cookie.scrollOffsetY)) scrollOffset=new WI.Point(cookie.scrollOffsetX,cookie.scrollOffsetY);if(position) contentView.revealPosition(position,{...cookie,textRangeToSelect,scrollOffset});}} showRequest() {this._shownInitialContent=true;return this._showContentViewForIdentifier(ResourceClusterContentView.Identifier.Request);} showResponse() {this._shownInitialContent=true;return this._showContentViewForIdentifier(ResourceClusterContentView.Identifier.Response);} get requestContentView() {if(!this._canShowRequestContentView()) return null;if(this._requestContentView) return this._requestContentView;this._requestContentView=new WI.TextContentView(this._resource.requestData||"",this._resource.requestDataContentType);return this._requestContentView;} get responseContentView() {if(this._responseContentView) return this._responseContentView;let typeFromMIMEType=WI.Resource.typeFromMIMEType(this._resource.mimeType);if(typeFromMIMEType===WI.Resource.Type.Image&&this._resource.type===WI.Resource.Type.Document) return this._contentViewForResourceType(WI.Resource.Type.Image);this._responseContentView=this._contentViewForResourceType(this._resource.type);if(this._responseContentView) return this._responseContentView;this._responseContentView=this._contentViewForResourceType(typeFromMIMEType);if(this._responseContentView) return this._responseContentView;if(WI.shouldTreatMIMETypeAsText(this._resource.mimeType)){this._responseContentView=new WI.TextResourceContentView(this._resource);return this._responseContentView;} this._responseContentView=new WI.GenericResourceContentView(this._resource);return this._responseContentView;} get customRequestDOMContentView() {if(!this._customRequestDOMContentView&&this._customRequestDOMContentViewInitializer) this._customRequestDOMContentView=this._customRequestDOMContentViewInitializer();return this._customRequestDOMContentView;} get customRequestJSONContentView() {if(!this._customRequestJSONContentView&&this._customRequestJSONContentViewInitializer) this._customRequestJSONContentView=this._customRequestJSONContentViewInitializer();return this._customRequestJSONContentView;} get customResponseDOMContentView() {if(!this._customResponseDOMContentView&&this._customResponseDOMContentViewInitializer) this._customResponseDOMContentView=this._customResponseDOMContentViewInitializer();return this._customResponseDOMContentView;} get customResponseJSONContentView() {if(!this._customResponseJSONContentView&&this._customResponseJSONContentViewInitializer) this._customResponseJSONContentView=this._customResponseJSONContentViewInitializer();return this._customResponseJSONContentView;} get customResponseTextContentView() {if(!this._customResponseTextContentView&&this._customResponseTextContentViewInitializer) this._customResponseTextContentView=this._customResponseTextContentViewInitializer();return this._customResponseTextContentView;} _createPathComponent({displayName,styleClassNames,identifier,previousSibling,nextSibling}) {const textOnly=false;const showSelectorArrows=true;let pathComponent=new WI.HierarchicalPathComponent(displayName,styleClassNames,identifier,textOnly,showSelectorArrows);pathComponent.comparisonData=this._resource;if(previousSibling){previousSibling.nextSibling=pathComponent;pathComponent.previousSibling=previousSibling;} if(nextSibling){nextSibling.previousSibling=pathComponent;pathComponent.nextSibling=nextSibling;} pathComponent.addEventListener(WI.HierarchicalPathComponent.Event.SiblingWasSelected,this._pathComponentSelected,this);return pathComponent;} _canShowRequestContentView() {let requestData=this._resource.requestData;if(!requestData) return false;if(this._resource.hasRequestFormParameters()) return false;return true;} _canShowCustomRequestContentView() {return!!(this._customRequestDOMContentViewInitializer||this._customRequestJSONContentViewInitializer);} _canShowCustomResponseContentView() {return!!(this._customResponseDOMContentViewInitializer||this._customResponseJSONContentViewInitializer||this._customResponseTextContentViewInitializer);} _contentViewForResourceType(type) {switch(type){case WI.Resource.Type.Document:case WI.Resource.Type.Script:case WI.Resource.Type.StyleSheet:return new WI.TextResourceContentView(this._resource);case WI.Resource.Type.Image:return new WI.ImageResourceContentView(this._resource,{disableDropZone:this._disableDropZone});case WI.Resource.Type.Font:return new WI.FontResourceContentView(this._resource);case WI.Resource.Type.WebSocket:return new WI.WebSocketContentView(this._resource);default:return null;}} _pathComponentForContentView(contentView) {switch(contentView){case this._requestContentView:return this._requestPathComponent;case this._customRequestDOMContentView:return this._customRequestDOMPathComponent;case this._customRequestJSONContentView:return this._customRequestJSONPathComponent;case this._responseContentView:return this._responsePathComponent;case this._customResponseDOMContentView:return this._customResponseDOMPathComponent;case this._customResponseJSONContentView:return this._customResponseJSONPathComponent;case this._customResponseTextContentView:return this._customResponseTextPathComponent;} console.error("Unknown contentView",contentView);return null;} _identifierForContentView(contentView) {switch(contentView){case this._requestContentView:return ResourceClusterContentView.Identifier.Request;case this._customRequestDOMContentView:return ResourceClusterContentView.Identifier.RequestDOM;case this._customRequestJSONContentView:return ResourceClusterContentView.Identifier.RequestJSON;case this._responseContentView:return ResourceClusterContentView.Identifier.Response;case this._customResponseDOMContentView:return ResourceClusterContentView.Identifier.ResponseDOM;case this._customResponseJSONContentView:return ResourceClusterContentView.Identifier.ResponseJSON;case this._customResponseTextContentView:return ResourceClusterContentView.Identifier.ResponseText;} console.error("Unknown contentView",contentView);return null;} _showContentViewForIdentifier(identifier) {let contentViewToShow=null;switch(identifier){case ResourceClusterContentView.Identifier.RequestDOM:contentViewToShow=this.customRequestDOMContentView;if(contentViewToShow) break; case ResourceClusterContentView.Identifier.RequestJSON:contentViewToShow=this.customRequestJSONContentView;if(contentViewToShow) break; case ResourceClusterContentView.Identifier.Request:contentViewToShow=this.requestContentView;if(contentViewToShow) break; case ResourceClusterContentView.Identifier.ResponseDOM:contentViewToShow=this.customResponseDOMContentView;if(contentViewToShow) break; case ResourceClusterContentView.Identifier.ResponseJSON:contentViewToShow=this.customResponseJSONContentView;if(contentViewToShow) break; case ResourceClusterContentView.Identifier.ResponseText:contentViewToShow=this.customResponseTextContentView;if(contentViewToShow) break; case ResourceClusterContentView.Identifier.Response:default:contentViewToShow=this.responseContentView;break;} this._currentContentViewSetting.value=this._identifierForContentView(contentViewToShow);return this.contentViewContainer.showContentView(contentViewToShow);} _pathComponentSelected(event) {this._showContentViewForIdentifier(event.data.pathComponent.representedObject);} _resourceTypeDidChange(event) { let currentResponseContentView=this._responseContentView;if(!currentResponseContentView) return;this._responseContentView=null;this.contentViewContainer.replaceContentView(currentResponseContentView,this.responseContentView);} _resourceLoadingDidFinish(event) {this._tryEnableCustomResponseContentViews();} _canUseJSONContentViewForContent(content) {return typeof content==="string"&&content.isJSON((json)=>json&&(typeof json==="object"||Array.isArray(json)));} _canUseDOMContentViewForContent(content,mimeType) {if(typeof content!=="string") return false;switch(mimeType){case"text/html":return true;case"text/xml":case"application/xml":case"application/xhtml+xml":case"image/svg+xml":try{let dom=(new DOMParser).parseFromString(content,mimeType);return!dom.querySelector("parsererror");}catch{} return false;} return false;} _normalizeMIMETypeForDOM(mimeType) {mimeType=parseMIMEType(mimeType).type;if(!mimeType) return mimeType;if(mimeType.endsWith("/html")||mimeType.endsWith("+html")) return"text/html";if(mimeType.endsWith("/xml")||mimeType.endsWith("+xml")){if(mimeType!=="application/xhtml+xml"&&mimeType!=="image/svg+xml") return"application/xml";} if(mimeType.endsWith("/xhtml")||mimeType.endsWith("+xhtml")) return"application/xhtml+xml";if(mimeType.endsWith("/svg")||mimeType.endsWith("+svg")) return"image/svg+xml";return mimeType;} _tryEnableCustomRequestContentViews() {let content=this._resource.requestData;if(this._canUseJSONContentViewForContent(content)){this._customRequestJSONContentViewInitializer=()=>new WI.LocalJSONContentView(content,this._resource);this._customRequestJSONPathComponent=this._createPathComponent({displayName:WI.UIString("Request (Object Tree)"),styleClassNames:["object-icon"],identifier:ResourceClusterContentView.Identifier.RequestJSON,previousSibling:this._requestPathComponent,nextSibling:this._responsePathComponent,});this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);return;} let mimeType=this._normalizeMIMETypeForDOM(this._resource.requestDataContentType);if(this._canUseDOMContentViewForContent(content,mimeType)){this._customRequestDOMContentViewInitializer=()=>new WI.LocalDOMContentView(content,mimeType,this._resource);this._customRequestDOMPathComponent=this._createPathComponent({displayName:WI.UIString("Request (DOM Tree)"),styleClassNames:["dom-document-icon"],identifier:ResourceClusterContentView.Identifier.RequestDOM,previousSibling:this._requestPathComponent,nextSibling:this._responsePathComponent,});this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);return;}} _tryEnableCustomResponseContentViews() {if(!this._resource.hasResponse()) return;if(this._resource instanceof WI.WebSocketResource) return;this._resource.requestContent().then(({error,content})=>{if(error||typeof content!=="string") return;if(this._canUseJSONContentViewForContent(content)){this._customResponseJSONContentViewInitializer=()=>new WI.LocalJSONContentView(content,this._resource);this._customResponseJSONPathComponent=this._createPathComponent({displayName:WI.UIString("Response (Object Tree)"),styleClassNames:["object-icon"],identifier:ResourceClusterContentView.Identifier.ResponseJSON,previousSibling:this._responsePathComponent,});this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);return;} let mimeType=this._normalizeMIMETypeForDOM(this._resource.mimeType);if(this._canUseDOMContentViewForContent(content,mimeType)){if(mimeType==="image/svg+xml"){this._customResponseTextContentViewInitializer=()=>new WI.TextContentView(content,mimeType,this._resource);this._customResponseTextPathComponent=this._createPathComponent({displayName:WI.UIString("Response (Text)"),styleClassNames:["source-icon"],identifier:ResourceClusterContentView.Identifier.ResponseText,previousSibling:this._responsePathComponent,});} this._customResponseDOMContentViewInitializer=()=>new WI.LocalDOMContentView(content,mimeType,this._resource);this._customResponseDOMPathComponent=this._createPathComponent({displayName:WI.UIString("Response (DOM Tree)"),styleClassNames:["dom-document-icon"],identifier:ResourceClusterContentView.Identifier.ResponseDOM,previousSibling:this._customResponseTextPathComponent||this._responsePathComponent,});this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);return;}});}};WI.ResourceClusterContentView.ContentViewIdentifierCookieKey="resource-cluster-content-view-identifier";WI.ResourceClusterContentView.Identifier={Request:"request",RequestDOM:"request-dom",RequestJSON:"request-json",Response:"response",ResponseDOM:"response-dom",ResponseJSON:"response-json",ResponseText:"response-text",};WI.ResourceCollectionContentView=class ResourceCollectionContentView extends WI.CollectionContentView {constructor(collection) {let contentViewConstructor=null;if(collection.resourceType===WI.Resource.Type.Image) contentViewConstructor=WI.ImageResourceContentView;super(collection,contentViewConstructor);this.element.classList.add("resource-collection");if(collection.resourceType===WI.Resource.Type.Image){this._showGridButtonNavigationItem=new WI.ActivateButtonNavigationItem("show-grid",WI.repeatedUIString.showTransparencyGridTooltip(),WI.UIString("Hide transparency grid"),"Images/NavigationItemCheckers.svg",13,13);this._showGridButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleShowGridButtonClicked,this);this._showGridButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._showGridButtonNavigationItem.activated=!!WI.settings.showImageGrid.value;let allItem=new WI.ScopeBarItem("all",WI.UIString("All"));let items=[allItem];this._scopeBarItemTypeMap={};let addItem=(key,label)=>{let item=new WI.ScopeBarItem(key,label);items.push(item);this._scopeBarItemTypeMap[key]=item;};addItem("bmp",WI.UIString("BMP"));addItem("gif",WI.UIString("GIF"));addItem("ico",WI.UIString("ICO"));addItem("jp2",WI.UIString("JP2"));addItem("jpg",WI.UIString("JPEG"));addItem("pdf",WI.UIString("PDF"));addItem("png",WI.UIString("PNG"));addItem("svg",WI.UIString("SVG"));addItem("tiff",WI.UIString("TIFF"));addItem("webp",WI.UIString("WebP"));addItem("xbm",WI.UIString("XBM"));const shouldGroupNonExclusiveItems=true;this._imageTypeScopeBar=new WI.ScopeBar("resource-collection-image-type-scope-bar",items,allItem,shouldGroupNonExclusiveItems);this._imageTypeScopeBar.addEventListener(WI.ScopeBar.Event.SelectionChanged,this._handleImageTypeSelectionChanged,this);}} get navigationItems() {let navigationItems=[];if(this._imageTypeScopeBar) navigationItems.push(this._imageTypeScopeBar);if(this._showGridButtonNavigationItem) navigationItems.push(this._showGridButtonNavigationItem);navigationItems.pushAll(super.navigationItems);return navigationItems;} attached() {super.attached();WI.settings.showImageGrid.addEventListener(WI.Setting.Event.Changed,this._handleShowImageGridSettingChanged,this);} detached() {WI.settings.showImageGrid.removeEventListener(WI.Setting.Event.Changed,this._handleShowImageGridSettingChanged,this);super.detached();} get contentViewConstructorOptions() {let contentViewConstructorOptions=super.contentViewConstructorOptions;if(this.representedObject.resourceType===WI.Resource.Type.Image) contentViewConstructorOptions.disableInteractions=true;return contentViewConstructorOptions;} contentViewAdded(contentView) {let resource=contentView.representedObject;this._updateImageTypeScopeBar();contentView.addEventListener(WI.ResourceContentView.Event.ContentError,this._handleContentError,this);contentView.element.title=WI.displayNameForURL(resource.url,resource.urlComponents);} contentViewRemoved(contentView) {this._updateImageTypeScopeBar();contentView.removeEventListener(WI.ResourceContentView.Event.ContentError,this._handleContentError,this);} _updateImageTypeScopeBar() {let extensions=new Set;let visibleExtensions=0;for(let resource of this.representedObject) extensions.add(WI.fileExtensionForMIMEType(resource.mimeType));for(let[key,item]of Object.entries(this._scopeBarItemTypeMap)){let hidden=!extensions.has(key);item.hidden=hidden;if(hidden&&item.selected) item.selected=false;if(!item.hidden) ++visibleExtensions;} this._imageTypeScopeBar.hidden=visibleExtensions<=1;this.dispatchEventToListeners(WI.ContentView.Event.NavigationItemsDidChange);} _handleShowGridButtonClicked(event) {WI.settings.showImageGrid.value=!this._showGridButtonNavigationItem.activated;} _handleImageTypeSelectionChanged() {let selectedTypes=this._imageTypeScopeBar.selectedItems.map((item)=>item.id);let allTypesAllowed=selectedTypes.length===1&&selectedTypes[0]==="all";for(let view of this.subviews){let hidden=!allTypesAllowed;if(hidden&&view instanceof WI.ResourceContentView) hidden=!selectedTypes.includes(WI.fileExtensionForMIMEType(view.representedObject.mimeType));view.element.hidden=hidden;}} _handleShowImageGridSettingChanged(event) {let activated=WI.settings.showImageGrid.value;this._showGridButtonNavigationItem.activated=activated;} _handleContentError(event) {if(event&&event.target) this.removeContentViewForItem(event.target.representedObject);}};WI.ResourceCookiesContentView=class ResourceCookiesContentView extends WI.ContentView {constructor(resource) {super(null);this._resource=resource;this._resource.addEventListener(WI.Resource.Event.RequestHeadersDidChange,this._resourceRequestHeadersDidChange,this);this._resource.addEventListener(WI.Resource.Event.ResponseReceived,this._resourceResponseReceived,this);this.element.classList.add("resource-details","resource-cookies");} tableNumberOfRows(table) {return this._dataSourceForTable(table).length;} tableSortChanged(table) {let sortComparator=this._generateSortComparator(table);if(!sortComparator) return;let dataSource=this._dataSourceForTable(table);dataSource.sort(sortComparator);table.reloadData();} tableIndexForRepresentedObject(table,object) {let cookies=this._dataSourceForTable(table);let index=cookies.indexOf(object);return index;} tableRepresentedObjectForIndex(table,index) {let cookies=this._dataSourceForTable(table);return cookies[index];} tableShouldSelectRow(table,cell,column,rowIndex) {return false;} tablePopulateCell(table,cell,column,rowIndex) {let cookie=this._dataSourceForTable(table)[rowIndex];const checkmark="\u2713";switch(column.identifier){case"name":cell.textContent=cookie.name;break;case"value":cell.textContent=cookie.value;break;case"domain":cell.textContent=cookie.domain||emDash;break;case"path":cell.textContent=cookie.path||emDash;break;case"expires":cell.textContent=(!cookie.session&&cookie.expires)?cookie.expires.toLocaleString():WI.UIString("Session");break;case"maxAge":cell.textContent=cookie.maxAge||emDash;break;case"secure":cell.textContent=cookie.secure?checkmark:zeroWidthSpace;break;case"httpOnly":cell.textContent=cookie.httpOnly?checkmark:zeroWidthSpace;break;case"sameSite":cell.textContent=cookie.sameSite===WI.Cookie.SameSiteType.None?emDash:WI.Cookie.displayNameForSameSiteType(cookie.sameSite);break;} return cell;} initialLayout() {super.initialLayout();this._requestCookiesSection=new WI.ResourceDetailsSection(WI.UIString("Request Cookies"));this.element.appendChild(this._requestCookiesSection.element);this._refreshRequestCookiesSection();this._responseCookiesSection=new WI.ResourceDetailsSection(WI.UIString("Response Cookies"));this.element.appendChild(this._responseCookiesSection.element);this._refreshResponseCookiesSection();} _dataSourceForTable(table) {return table===this._requestCookiesTable?this._requestCookiesDataSource:this._responseCookiesDataSource;} _generateSortComparator(table) {let sortColumnIdentifier=table.sortColumnIdentifier;if(!sortColumnIdentifier) return null;let comparator;switch(sortColumnIdentifier){case"name":case"value":case"domain":case"path":case"sameSite":comparator=(a,b)=>(a[sortColumnIdentifier]||"").extendedLocaleCompare(b[sortColumnIdentifier]||"");break;case"maxAge":comparator=(a,b)=>{let aValue=a[sortColumnIdentifier];if(isNaN(aValue)) return 1;let bValue=b[sortColumnIdentifier];if(isNaN(bValue)) return-1;return aValue-bValue;};break;case"httpOnly":case"secure":comparator=(a,b)=>a[sortColumnIdentifier]-b[sortColumnIdentifier];break;case"expires":comparator=(a,b)=>{let aExpires=a.expires;if(!aExpires) return 1;let bExpires=b.expires;if(!bExpires) return-1;return aExpires.getTime()-bExpires.getTime();};break;default:return null;} let reverseFactor=table.sortOrder===WI.Table.SortOrder.Ascending?1:-1;return(a,b)=>reverseFactor*comparator(a,b);} _refreshRequestCookiesSection() {let detailsElement=this._requestCookiesSection.detailsElement;detailsElement.removeChildren();if(this._resource.responseSource===WI.Resource.ResponseSource.MemoryCache){this._requestCookiesSection.markIncompleteSectionWithMessage(WI.UIString("No request, served from the memory cache."));return;} this._requestCookiesDataSource=this._resource.requestCookies;if(!this._requestCookiesTable){this._requestCookiesTable=new WI.Table("request-cookies",this,this,20);this._requestCookiesTable.addColumn(new WI.TableColumn("name",WI.UIString("Name"),{minWidth:150,maxWidth:300,initialWidth:200,resizeType:WI.TableColumn.ResizeType.Locked}));this._requestCookiesTable.addColumn(new WI.TableColumn("value",WI.UIString("Value"),{minWidth:150,hideable:false}));if(!this._requestCookiesTable.sortColumnIdentifier){this._requestCookiesTable.sortOrder=WI.Table.SortOrder.Ascending;this._requestCookiesTable.sortColumnIdentifier="name";}} if(!this._requestCookiesDataSource.length){if(this._requestCookiesTable.isAttached) this.removeSubview(this._requestCookiesTable);this._requestCookiesSection.markIncompleteSectionWithMessage(WI.UIString("No request cookies."));}else{this._requestCookiesSection.toggleIncomplete(false);this._requestCookiesTable.element.style.height=this._sizeForTable(this._requestCookiesTable)+"px";this.addSubview(this._requestCookiesTable);detailsElement.classList.add("has-table");detailsElement.appendChild(this._requestCookiesTable.element);}} _refreshResponseCookiesSection() {let detailsElement=this._responseCookiesSection.detailsElement;detailsElement.removeChildren();if(!this._resource.hasResponse()){this._responseCookiesSection.markIncompleteSectionWithLoadingIndicator();return;} this._responseCookiesDataSource=this._resource.responseCookies;if(!this._responseCookiesTable){this._responseCookiesTable=new WI.Table("request-cookies",this,this,20);this._responseCookiesTable.addColumn(new WI.TableColumn("name",WI.UIString("Name"),{minWidth:150,maxWidth:300,initialWidth:200,resizeType:WI.TableColumn.ResizeType.Locked}));this._responseCookiesTable.addColumn(new WI.TableColumn("value",WI.UIString("Value"),{minWidth:150,hideable:false}));this._responseCookiesTable.addColumn(new WI.TableColumn("domain",WI.unlocalizedString("Domain"),{}));this._responseCookiesTable.addColumn(new WI.TableColumn("path",WI.unlocalizedString("Path"),{}));this._responseCookiesTable.addColumn(new WI.TableColumn("expires",WI.unlocalizedString("Expires"),{maxWidth:150}));this._responseCookiesTable.addColumn(new WI.TableColumn("maxAge",WI.unlocalizedString("Max-Age"),{maxWidth:90,align:"right"}));this._responseCookiesTable.addColumn(new WI.TableColumn("secure",WI.unlocalizedString("Secure"),{minWidth:55,maxWidth:65,align:"center"}));this._responseCookiesTable.addColumn(new WI.TableColumn("httpOnly",WI.unlocalizedString("HttpOnly"),{minWidth:55,maxWidth:65,align:"center"}));this._responseCookiesTable.addColumn(new WI.TableColumn("sameSite",WI.unlocalizedString("SameSite"),{minWidth:55,maxWidth:65}));if(!this._responseCookiesTable.sortColumnIdentifier){this._responseCookiesTable.sortOrder=WI.Table.SortOrder.Ascending;this._responseCookiesTable.sortColumnIdentifier="name";}} if(!this._responseCookiesDataSource.length){if(this._responseCookiesTable.isAttached) this.removeSubview(this._responseCookiesTable);this._responseCookiesSection.markIncompleteSectionWithMessage(WI.UIString("No response cookies."));}else{this._responseCookiesSection.toggleIncomplete(false);this._responseCookiesTable.element.style.height=this._sizeForTable(this._responseCookiesTable)+"px";this.addSubview(this._responseCookiesTable);detailsElement.classList.add("has-table");detailsElement.appendChild(this._responseCookiesTable.element);}} _sizeForTable(table) {const headerHeight=28;const borderHeight=3;let rowsHeight=this._dataSourceForTable(table).length*table.rowHeight;return rowsHeight+headerHeight+borderHeight;} _resourceRequestHeadersDidChange(event) {this._refreshRequestCookiesSection();} _resourceResponseReceived(event) {this._refreshResponseCookiesSection();}};WI.ResourceCookiesContentView.ReferencePage=WI.ReferencePage.NetworkTab.CookiesPane;WI.ResourceDetailsSection=class ResourceDetailsSection {constructor(title,className) {this._element=document.createElement("section");if(className) this._element.className=className;this._titleElement=this._element.appendChild(document.createElement("div"));this._titleElement.className="title";this._titleElement.textContent=title;this._detailsElement=this._element.appendChild(document.createElement("div"));this._detailsElement.className="details";this._element.appendChild(document.createElement("br"));} get element(){return this._element;} get titleElement(){return this._titleElement;} get detailsElement(){return this._detailsElement;} toggleIncomplete(isIncomplete) {this.element.classList.toggle("incomplete",isIncomplete);} toggleError(isError) {this.element.classList.toggle("error",isError);} markIncompleteSectionWithMessage(message) {this.toggleIncomplete(true);let p=this._detailsElement.appendChild(document.createElement("p"));p.textContent=message;} markIncompleteSectionWithLoadingIndicator() {this.toggleIncomplete(true);let p=this._detailsElement.appendChild(document.createElement("p"));let spinner=new WI.IndeterminateProgressSpinner;p.appendChild(spinner.element);} appendKeyValuePair(key,value,className) {let p=this._detailsElement.appendChild(document.createElement("p"));p.className="pair";if(className) p.classList.add(className);let keyElement=p.appendChild(document.createElement("span"));keyElement.className="key";if(key instanceof Node) keyElement.appendChild(key);else{keyElement.textContent=key+(value?": ":"");let valueElement=p.appendChild(document.createElement("bdi"));valueElement.className="value";valueElement.append(value||"");} return p;}};WI.ResourceDetailsSidebarPanel=class ResourceDetailsSidebarPanel extends WI.DetailsSidebarPanel {constructor() {super("resource-details",WI.UIString("Resource"));this.element.classList.add("resource");this._resource=null;this._needsToApplyResourceEventListeners=false;this._needsToRemoveResourceEventListeners=false;} inspect(objects) {if(!(objects instanceof Array)) objects=[objects];var resourceToInspect=null;for(let object of objects){if(object instanceof WI.Resource){resourceToInspect=object;break;} if(object instanceof WI.Frame){resourceToInspect=object.mainResource;break;} if(object instanceof WI.Script&&object.isMainResource()&&object.resource){resourceToInspect=object.resource;break;}} this.resource=resourceToInspect;return!!this._resource;} get resource() {return this._resource;} set resource(resource) {if(resource===this._resource) return;if(this._resource&&this._needsToRemoveResourceEventListeners){this._resource.removeEventListener(WI.Resource.Event.URLDidChange,this._refreshURL,this);this._resource.removeEventListener(WI.Resource.Event.MIMETypeDidChange,this._refreshMIMEType,this);this._resource.removeEventListener(WI.Resource.Event.TypeDidChange,this._refreshResourceType,this);this._resource.removeEventListener(WI.Resource.Event.LoadingDidFail,this._refreshErrorReason,this);this._resource.removeEventListener(WI.Resource.Event.RequestHeadersDidChange,this._refreshRequestHeaders,this);this._resource.removeEventListener(WI.Resource.Event.ResponseReceived,this._refreshRequestAndResponse,this);this._resource.removeEventListener(WI.Resource.Event.CacheStatusDidChange,this._refreshRequestAndResponse,this);this._resource.removeEventListener(WI.Resource.Event.MetricsDidChange,this._refreshRequestAndResponse,this);this._resource.removeEventListener(WI.Resource.Event.SizeDidChange,this._refreshDecodedSize,this);this._resource.removeEventListener(WI.Resource.Event.TransferSizeDidChange,this._refreshTransferSize,this);this._resource.removeEventListener(WI.Resource.Event.InitiatedResourcesDidChange,this._handleResourceInitiatedResourcesDidChange,this);this._refreshRelatedResourcesSectionThrottler.cancel();this._needsToRemoveResourceEventListeners=false;} this._resource=resource;if(this._resource){if(this.didInitialLayout) this._applyResourceEventListeners();else this._needsToApplyResourceEventListeners=true;} this.needsLayout();} initialLayout() {super.initialLayout();this._typeMIMETypeRow=new WI.DetailsSectionSimpleRow(WI.UIString("MIME Type"));this._typeResourceTypeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Resource Type"));this._typeSection=new WI.DetailsSection("resource-type",WI.UIString("Type"));this._typeSection.groups=[new WI.DetailsSectionGroup([this._typeMIMETypeRow,this._typeResourceTypeRow])];this._locationFullURLRow=new WI.DetailsSectionSimpleRow(WI.UIString("Full URL"));this._locationSchemeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Scheme"));this._locationHostRow=new WI.DetailsSectionSimpleRow(WI.UIString("Host"));this._locationPortRow=new WI.DetailsSectionSimpleRow(WI.UIString("Port"));this._locationPathRow=new WI.DetailsSectionSimpleRow(WI.UIString("Path"));this._locationQueryStringRow=new WI.DetailsSectionSimpleRow(WI.UIString("Query String"));this._locationFragmentRow=new WI.DetailsSectionSimpleRow(WI.UIString("Fragment"));this._locationFilenameRow=new WI.DetailsSectionSimpleRow(WI.UIString("Filename"));this._initiatorRow=new WI.DetailsSectionSimpleRow(WI.UIString("Initiator"));this._initiatedRow=new WI.DetailsSectionSimpleRow(WI.UIString("Initiated"));var firstGroup=[this._locationFullURLRow];var secondGroup=[this._locationSchemeRow,this._locationHostRow,this._locationPortRow,this._locationPathRow,this._locationQueryStringRow,this._locationFragmentRow,this._locationFilenameRow];var thirdGroup=[this._initiatorRow,this._initiatedRow];this._fullURLGroup=new WI.DetailsSectionGroup(firstGroup);this._locationURLComponentsGroup=new WI.DetailsSectionGroup(secondGroup);this._relatedResourcesGroup=new WI.DetailsSectionGroup(thirdGroup);this._locationSection=new WI.DetailsSection("resource-location",WI.UIString("Location"),[this._fullURLGroup,this._locationURLComponentsGroup,this._relatedResourcesGroup]);this._queryParametersRow=new WI.DetailsSectionDataGridRow(null,WI.UIString("No Query Parameters"));this._queryParametersSection=new WI.DetailsSection("resource-query-parameters",WI.UIString("Query Parameters"));this._queryParametersSection.groups=[new WI.DetailsSectionGroup([this._queryParametersRow])];this._requestDataSection=new WI.DetailsSection("resource-request-data",WI.UIString("Request Data"));this._requestMethodRow=new WI.DetailsSectionSimpleRow(WI.UIString("Method"));this._protocolRow=new WI.DetailsSectionSimpleRow(WI.UIString("Protocol"));this._priorityRow=new WI.DetailsSectionSimpleRow(WI.UIString("Priority"));this._cachedRow=new WI.DetailsSectionSimpleRow(WI.UIString("Cached"));this._statusTextRow=new WI.DetailsSectionSimpleRow(WI.UIString("Status"));this._statusCodeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Code"));this._errorReasonRow=new WI.DetailsSectionSimpleRow(WI.UIString("Error"));this._remoteAddressRow=new WI.DetailsSectionSimpleRow(WI.UIString("IP Address"));this._connectionIdentifierRow=new WI.DetailsSectionSimpleRow(WI.UIString("Connection ID"));this._encodedSizeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Encoded"));this._decodedSizeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Decoded"));this._transferSizeRow=new WI.DetailsSectionSimpleRow(WI.UIString("Transferred"));this._compressedRow=new WI.DetailsSectionSimpleRow(WI.UIString("Compressed"));this._compressionRow=new WI.DetailsSectionSimpleRow(WI.UIString("Compression"));let requestGroup=new WI.DetailsSectionGroup([this._requestMethodRow,this._protocolRow,this._priorityRow,this._cachedRow]);let statusGroup=new WI.DetailsSectionGroup([this._statusTextRow,this._statusCodeRow,this._errorReasonRow]);let connectionGroup=new WI.DetailsSectionGroup([this._remoteAddressRow,this._connectionIdentifierRow]);let sizeGroup=new WI.DetailsSectionGroup([this._encodedSizeRow,this._decodedSizeRow,this._transferSizeRow]);let compressionGroup=new WI.DetailsSectionGroup([this._compressedRow,this._compressionRow]);this._requestAndResponseSection=new WI.DetailsSection("resource-request-response",WI.UIString("Request & Response"));this._requestAndResponseSection.groups=[requestGroup,statusGroup,connectionGroup,sizeGroup,compressionGroup];this._requestHeadersRow=new WI.DetailsSectionDataGridRow(null,WI.UIString("No Request Headers"));this._requestHeadersSection=new WI.DetailsSection("resource-request-headers",WI.UIString("Request Headers"));this._requestHeadersSection.groups=[new WI.DetailsSectionGroup([this._requestHeadersRow])];this._responseHeadersRow=new WI.DetailsSectionDataGridRow(null,WI.UIString("No Response Headers"));this._responseHeadersSection=new WI.DetailsSection("resource-response-headers",WI.UIString("Response Headers"));this._responseHeadersSection.groups=[new WI.DetailsSectionGroup([this._responseHeadersRow])];this._imageWidthRow=new WI.DetailsSectionSimpleRow(WI.UIString("Width"));this._imageHeightRow=new WI.DetailsSectionSimpleRow(WI.UIString("Height"));this._imageSizeSection=new WI.DetailsSection("resource-type",WI.UIString("Image Size"));this._imageSizeSection.groups=[new WI.DetailsSectionGroup([this._imageWidthRow,this._imageHeightRow])];this.contentView.element.appendChild(this._typeSection.element);this.contentView.element.appendChild(this._locationSection.element);this.contentView.element.appendChild(this._requestAndResponseSection.element);this.contentView.element.appendChild(this._requestHeadersSection.element);this.contentView.element.appendChild(this._responseHeadersSection.element);if(this._needsToApplyResourceEventListeners){this._applyResourceEventListeners();this._needsToApplyResourceEventListeners=false;}} layout() {super.layout();if(!this._resource) return;this._refreshURL();this._refreshMIMEType();this._refreshResourceType();this._refreshRequestAndResponse();this._refreshDecodedSize();this._refreshTransferSize();this._refreshRequestHeaders();this._refreshImageSizeSection();this._refreshRequestDataSection();this._refreshRelatedResourcesSectionThrottler.force();} sizeDidChange() {super.sizeDidChange(); this._queryParametersRow.sizeDidChange();this._requestHeadersRow.sizeDidChange();this._responseHeadersRow.sizeDidChange();} _refreshURL() {if(!this._resource) return;this._locationFullURLRow.value=this._resource.displayURL.insertWordBreakCharacters();var urlComponents=this._resource.urlComponents;if(urlComponents.scheme){this._locationSection.groups=[this._fullURLGroup,this._locationURLComponentsGroup,this._relatedResourcesGroup];this._locationSchemeRow.value=urlComponents.scheme?urlComponents.scheme:null;this._locationHostRow.value=urlComponents.host?urlComponents.host:null;this._locationPortRow.value=urlComponents.port?urlComponents.port:null;this._locationPathRow.value=urlComponents.path?urlComponents.path.insertWordBreakCharacters():null;this._locationQueryStringRow.value=urlComponents.queryString?urlComponents.queryString.insertWordBreakCharacters():null;this._locationFragmentRow.value=urlComponents.fragment?urlComponents.fragment.insertWordBreakCharacters():null;this._locationFilenameRow.value=urlComponents.lastPathComponent?urlComponents.lastPathComponent.insertWordBreakCharacters():null;}else{this._locationSection.groups=[this._fullURLGroup,this._relatedResourcesGroup];} if(urlComponents.queryString){this.contentView.element.insertBefore(this._queryParametersSection.element,this._requestAndResponseSection.element.nextSibling);this._queryParametersRow.dataGrid=this._createNameValueDataGrid(parseQueryString(urlComponents.queryString,true));}else{var queryParametersSectionElement=this._queryParametersSection.element;if(queryParametersSectionElement.parentNode) queryParametersSectionElement.parentNode.removeChild(queryParametersSectionElement);}} _refreshRelatedResourcesSection() {let groups=this._locationSection.groups;let isSectionVisible=groups.includes(this._relatedResourcesGroup);if(!this._resource.initiatorSourceCodeLocation&&!this._resource.initiatedResources.length){if(isSectionVisible){groups.remove(this._relatedResourcesGroup);this._locationSection.groups=groups;} return;} if(!isSectionVisible){groups.push(this._relatedResourcesGroup);this._locationSection.groups=groups;} let initiatorLocation=this._resource.initiatorSourceCodeLocation;if(initiatorLocation){const options={dontFloat:true,ignoreSearchTab:true,};this._initiatorRow.value=WI.createSourceCodeLocationLink(initiatorLocation,options);}else this._initiatorRow.value=null;let initiatedResources=this._resource.initiatedResources;if(initiatedResources.length){let resourceLinkContainer=document.createElement("div");for(let resource of initiatedResources) resourceLinkContainer.appendChild(WI.createResourceLink(resource));this._initiatedRow.value=resourceLinkContainer;}else this._initiatedRow.value=null;} _refreshResourceType() {if(!this._resource) return;this._typeResourceTypeRow.value=WI.Resource.displayNameForType(this._resource.type);} _refreshMIMEType() {if(!this._resource) return;this._typeMIMETypeRow.value=this._resource.mimeType;} _refreshErrorReason() {if(!this._resource) return;if(!this._resource.hadLoadingError()){this._errorReasonRow.value=null;return;} if(this._resource.failureReasonText) this._errorReasonRow.value=this._resource.failureReasonText;else if(this._resource.statusCode>=400) this._errorReasonRow.value=WI.UIString("Failure status code");else if(this._resource.canceled) this._errorReasonRow.value=WI.UIString("Load cancelled");else this._errorReasonRow.value=WI.UIString("Unknown error");} _refreshRequestAndResponse() {if(!this._resource) return;this._requestMethodRow.value=this._resource.requestMethod||emDash;let protocolDisplayName=WI.Resource.displayNameForProtocol(this._resource.protocol);this._protocolRow.value=protocolDisplayName||emDash;this._protocolRow.tooltip=protocolDisplayName?this._resource.protocol:"";this._priorityRow.value=WI.Resource.displayNameForPriority(this._resource.priority)||emDash;this._remoteAddressRow.value=this._resource.displayRemoteAddress||emDash;this._connectionIdentifierRow.value=this._resource.connectionIdentifier||emDash;this._cachedRow.value=this._cachedRowValue();this._statusCodeRow.value=this._resource.statusCode||emDash;this._statusTextRow.value=this._resource.statusText||emDash;this._refreshErrorReason();this._refreshResponseHeaders();this._refreshCompressed();} _valueForSize(size) {return size>0?Number.bytesToString(size):emDash;} _refreshCompressed() {if(this._resource.compressed){this._compressedRow.value=WI.UIString("Yes");if(!this._resource.size) this._compressionRow.value=emDash;else if(!isNaN(this._resource.networkEncodedSize)) this._compressionRow.value=this._resource.networkEncodedSize?WI.UIString("%.2f\u00d7").format(this._resource.size/this._resource.networkEncodedSize):emDash;else this._compressionRow.value=this._resource.estimatedNetworkEncodedSize?WI.UIString("%.2f\u00d7").format(this._resource.size/this._resource.estimatedNetworkEncodedSize):emDash;}else{this._compressedRow.value=WI.UIString("No");this._compressionRow.value=null;}} _refreshDecodedSize() {if(!this._resource) return;let encodedSize=!isNaN(this._resource.networkEncodedSize)?this._resource.networkEncodedSize:this._resource.estimatedNetworkEncodedSize;let decodedSize=!isNaN(this._resource.networkDecodedSize)?this._resource.networkDecodedSize:this._resource.size;this._encodedSizeRow.value=this._valueForSize(encodedSize);this._decodedSizeRow.value=this._valueForSize(decodedSize);this._refreshCompressed();} _refreshTransferSize() {if(!this._resource) return;let encodedSize=!isNaN(this._resource.networkEncodedSize)?this._resource.networkEncodedSize:this._resource.estimatedNetworkEncodedSize;let transferSize=!isNaN(this._resource.networkTotalTransferSize)?this._resource.networkTotalTransferSize:this._resource.estimatedTotalTransferSize;this._encodedSizeRow.value=this._valueForSize(encodedSize);this._transferSizeRow.value=this._valueForSize(transferSize);this._refreshCompressed();} _refreshRequestHeaders() {if(!this._resource) return;this._requestHeadersRow.dataGrid=this._createNameValueDataGrid(this._resource.requestHeaders);} _refreshResponseHeaders() {if(!this._resource) return;this._responseHeadersRow.dataGrid=this._createNameValueDataGrid(this._resource.responseHeaders);} _createNameValueDataGrid(data) {if(!data||data instanceof Array?!data.length:isEmptyObject(data)) return null;var dataGrid=new WI.DataGrid({name:{title:WI.UIString("Name"),width:"30%",sortable:true},value:{title:WI.UIString("Value"),sortable:true}});dataGrid.copyTextDelimiter=": ";function addDataGridNode(nodeValue) {var node=new WI.DataGridNode({name:nodeValue.name,value:nodeValue.value||""});dataGrid.appendChild(node);} if(data instanceof Array){for(var i=0;i{if(size){this._imageWidthRow.value=WI.UIString("%dpx").format(size.width);this._imageHeightRow.value=WI.UIString("%dpx").format(size.height);}else hideImageSection.call(this);});} _cachedRowValue() {let responseSource=this._resource.responseSource;if(responseSource===WI.Resource.ResponseSource.MemoryCache||responseSource===WI.Resource.ResponseSource.DiskCache){let span=document.createElement("span");let cacheType=document.createElement("span");cacheType.classList="cache-type";cacheType.textContent=responseSource===WI.Resource.ResponseSource.MemoryCache?WI.UIString("(Memory)"):WI.UIString("(Disk)");span.append(WI.UIString("Yes")," ",cacheType);return span;} return this._resource.cached?WI.UIString("Yes"):WI.UIString("No");} _goToRequestDataClicked() {const options={ignoreSearchTab:true,};WI.showResourceRequest(this._resource,options);} _refreshRequestDataSection() {var resource=this._resource;if(!resource) return;var requestData=resource.requestData;if(!requestData){this._requestDataSection.element.remove();return;} this.contentView.element.insertBefore(this._requestDataSection.element,this._requestHeadersSection.element);var requestDataContentType=resource.requestDataContentType||"";if(requestDataContentType&&requestDataContentType.match(/^application\/x-www-form-urlencoded\s*(;.*)?$/i)){var parametersRow=new WI.DetailsSectionDataGridRow(null,WI.UIString("No Parameters"));parametersRow.dataGrid=this._createNameValueDataGrid(parseQueryString(requestData,true));this._requestDataSection.groups=[new WI.DetailsSectionGroup([parametersRow])];return;} var mimeTypeComponents=parseMIMEType(requestDataContentType);var mimeType=mimeTypeComponents.type;var boundary=mimeTypeComponents.boundary;var encoding=mimeTypeComponents.encoding;var rows=[];var mimeTypeRow=new WI.DetailsSectionSimpleRow(WI.UIString("MIME Type"));mimeTypeRow.value=mimeType;rows.push(mimeTypeRow);if(boundary){var boundryRow=new WI.DetailsSectionSimpleRow(WI.UIString("Boundary"));boundryRow.value=boundary;rows.push(boundryRow);} if(encoding){var encodingRow=new WI.DetailsSectionSimpleRow(WI.UIString("Encoding"));encodingRow.value=encoding;rows.push(encodingRow);} var sizeValue=Number.bytesToString(requestData.length);var dataValue=document.createDocumentFragment();dataValue.append(sizeValue);var goToButton=dataValue.appendChild(WI.createGoToArrowButton());goToButton.addEventListener("click",this._goToRequestDataClicked.bind(this));var dataRow=new WI.DetailsSectionSimpleRow(WI.UIString("Data"));dataRow.value=dataValue;rows.push(dataRow);this._requestDataSection.groups=[new WI.DetailsSectionGroup(rows)];} _applyResourceEventListeners() {if(!this._refreshRelatedResourcesSectionThrottler){this._refreshRelatedResourcesSectionThrottler=new Throttler(()=>{this._refreshRelatedResourcesSection();},250);} this._resource.addEventListener(WI.Resource.Event.URLDidChange,this._refreshURL,this);this._resource.addEventListener(WI.Resource.Event.MIMETypeDidChange,this._refreshMIMEType,this);this._resource.addEventListener(WI.Resource.Event.TypeDidChange,this._refreshResourceType,this);this._resource.addEventListener(WI.Resource.Event.LoadingDidFail,this._refreshErrorReason,this);this._resource.addEventListener(WI.Resource.Event.RequestHeadersDidChange,this._refreshRequestHeaders,this);this._resource.addEventListener(WI.Resource.Event.ResponseReceived,this._refreshRequestAndResponse,this);this._resource.addEventListener(WI.Resource.Event.CacheStatusDidChange,this._refreshRequestAndResponse,this);this._resource.addEventListener(WI.Resource.Event.MetricsDidChange,this._refreshRequestAndResponse,this);this._resource.addEventListener(WI.Resource.Event.SizeDidChange,this._refreshDecodedSize,this);this._resource.addEventListener(WI.Resource.Event.TransferSizeDidChange,this._refreshTransferSize,this);this._resource.addEventListener(WI.Resource.Event.InitiatedResourcesDidChange,this._handleResourceInitiatedResourcesDidChange,this);this._needsToRemoveResourceEventListeners=true;} _handleResourceInitiatedResourcesDidChange(event) {this._refreshRelatedResourcesSectionThrottler.fire();}};WI.ResourceHeadersContentView=class ResourceHeadersContentView extends WI.ContentView {constructor(resource,delegate) {super(null);this._resource=resource;this._resource.addEventListener(WI.Resource.Event.MetricsDidChange,this._resourceMetricsDidChange,this);this._resource.addEventListener(WI.Resource.Event.RequestHeadersDidChange,this._resourceRequestHeadersDidChange,this);this._resource.addEventListener(WI.Resource.Event.ResponseReceived,this._resourceResponseReceived,this);this._delegate=delegate;this._searchQuery=null;this._searchResults=null;this._searchDOMChanges=[];this._searchIndex=-1;this._automaticallyRevealFirstSearchResult=false;this._bouncyHighlightElement=null;this._popover=null;this._popoverCallStackIconElement=null;this._redirectDetailsSections=[];this.element.classList.add("resource-details","resource-headers");this.element.tabIndex=0;this._needsSummaryRefresh=false;this._needsRedirectHeadersRefresh=false;this._needsRequestHeadersRefresh=false;this._needsResponseHeadersRefresh=false;} initialLayout() {super.initialLayout();this._summarySection=new WI.ResourceDetailsSection(WI.UIString("Summary"),"summary");this.element.appendChild(this._summarySection.element);this._refreshSummarySection();this._refreshRedirectHeadersSections();this._requestHeadersSection=new WI.ResourceDetailsSection(WI.UIString("Request"),"headers");this.element.appendChild(this._requestHeadersSection.element);this._refreshRequestHeadersSection();this._responseHeadersSection=new WI.ResourceDetailsSection(WI.UIString("Response"),"headers");this.element.appendChild(this._responseHeadersSection.element);this._refreshResponseHeadersSection();if(this._resource.urlComponents.queryString){this._queryStringSection=new WI.ResourceDetailsSection(WI.UIString("Query String Parameters"));this.element.appendChild(this._queryStringSection.element);this._refreshQueryStringSection();} if(this._resource.requestData){this._requestDataSection=new WI.ResourceDetailsSection(WI.UIString("Request Data"));this.element.appendChild(this._requestDataSection.element);this._refreshRequestDataSection();} this._needsSummaryRefresh=false;this._needsRedirectHeadersRefresh=false;this._needsRequestHeadersRefresh=false;this._needsResponseHeadersRefresh=false;} layout() {super.layout();if(this._needsSummaryRefresh){this._refreshSummarySection();this._needsSummaryRefresh=false;} if(this._needsRedirectHeadersRefresh){this._refreshRedirectHeadersSections();this._needsRedirectHeadersRefresh=false;} if(this._needsRequestHeadersRefresh){this._refreshRequestHeadersSection();this._needsRequestHeadersRefresh=false;} if(this._needsResponseHeadersRefresh){this._refreshResponseHeadersSection();this._needsResponseHeadersRefresh=false;}} detached() {if(this._popover) this._popover.dismiss();super.detached();} closed() {this._resource.removeEventListener(WI.Resource.Event.MetricsDidChange,this._resourceMetricsDidChange,this);this._resource.removeEventListener(WI.Resource.Event.RequestHeadersDidChange,this._resourceRequestHeadersDidChange,this);this._resource.removeEventListener(WI.Resource.Event.ResponseReceived,this._resourceResponseReceived,this);super.closed();} get supportsSearch() {return true;} get numberOfSearchResults() {return this._searchResults?this._searchResults.length:null;} get hasPerformedSearch() {return this._searchResults!==null;} set automaticallyRevealFirstSearchResult(reveal) {this._automaticallyRevealFirstSearchResult=reveal;if(this._automaticallyRevealFirstSearchResult&&this.numberOfSearchResults>0){if(this._searchIndex===-1) this.revealNextSearchResult();}} performSearch(query) {if(query===this._searchQuery) return;WI.revertDOMChanges(this._searchDOMChanges);this._searchQuery=query;this._searchResults=[];this._searchDOMChanges=[];this._searchIndex=-1;this._perfomSearchOnKeyValuePairs();this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);if(this._automaticallyRevealFirstSearchResult&&this._searchResults.length>0) this.revealNextSearchResult();} searchCleared() {WI.revertDOMChanges(this._searchDOMChanges);this._searchQuery=null;this._searchResults=null;this._searchDOMChanges=[];this._searchIndex=-1;} revealPreviousSearchResult(changeFocus) {if(!this.numberOfSearchResults) return;if(this._searchIndex>0) --this._searchIndex;else this._searchIndex=this._searchResults.length-1;this._revealSearchResult(this._searchIndex,changeFocus);} revealNextSearchResult(changeFocus) {if(!this.numberOfSearchResults) return;if(this._searchIndex+1a[0].toLowerCase().extendedLocaleCompare(b[0].toLowerCase()));} _refreshSummarySection() {let detailsElement=this._summarySection.detailsElement;detailsElement.removeChildren();this._summarySection.toggleError(this._resource.hadLoadingError());for(let redirect of this._resource.redirects) this._summarySection.appendKeyValuePair(WI.UIString("URL"),redirect.url.insertWordBreakCharacters(),"url");this._summarySection.appendKeyValuePair(WI.UIString("URL"),this._resource.displayURL.insertWordBreakCharacters(),"url");let status=emDash;if(!isNaN(this._resource.statusCode)) status=this._resource.statusCode+(this._resource.statusText?" "+this._resource.statusText:"");this._summarySection.appendKeyValuePair(WI.UIString("Status"),status); let source=this._responseSourceDisplayString(this._resource.responseSource)||emDash;this._summarySection.appendKeyValuePair(WI.UIString("Source"),source);if(this._resource.remoteAddress) this._summarySection.appendKeyValuePair(WI.UIString("Address"),this._resource.displayRemoteAddress);let initiatorLocation=this._resource.initiatorSourceCodeLocation;if(initiatorLocation){let fragment=document.createDocumentFragment();const options={dontFloat:true,ignoreSearchTab:true,ignoreNetworkTab:true,};let link=WI.createSourceCodeLocationLink(initiatorLocation,options);fragment.appendChild(link);if(this._resource.initiatorStackTrace){this._popoverCallStackIconElement=document.createElement("img");this._popoverCallStackIconElement.className="call-stack";fragment.appendChild(this._popoverCallStackIconElement);this._popoverCallStackIconElement.addEventListener("click",(event)=>{if(!this._popover){this._popover=new WI.Popover(this);this._popover.windowResizeHandler=()=>{this._presentPopoverBelowCallStackElement();};} const selectable=false;let callFramesTreeOutline=new WI.TreeOutline(selectable);callFramesTreeOutline.disclosureButtons=false;let callFrameTreeController=new WI.StackTraceTreeController(callFramesTreeOutline);callFrameTreeController.stackTrace=this._resource.initiatorStackTrace;let popoverContent=document.createElement("div");popoverContent.appendChild(callFrameTreeController.treeOutline.element);this._popover.content=popoverContent;this._presentPopoverBelowCallStackElement();});} let pair=this._summarySection.appendKeyValuePair(WI.UIString("Initiator"),fragment);pair.classList.add("initiator");if(this._popover&&this._popover.visible) this._presentPopoverBelowCallStackElement();}} _refreshRedirectHeadersSections() {let referenceElement=this._redirectDetailsSections.length?this._redirectDetailsSections.lastValue.element:this._summarySection.element;for(let i=this._redirectDetailsSections.length;i{this._delegate.headersContentViewGoToRequestData(this);});this._requestDataSection.appendKeyValuePair(WI.UIString("Request Data"),goToButton);} _perfomSearchOnKeyValuePairs() {let searchRegex=WI.SearchUtilities.searchRegExpForString(this._searchQuery,WI.SearchUtilities.defaultSettings);if(!searchRegex){this.searchCleared();this.dispatchEventToListeners(WI.TextEditor.Event.NumberOfSearchResultsDidChange);return;} let elements=this.element.querySelectorAll(".key, .value");for(let element of elements){let matchRanges=[];let text=element.textContent;let match;while(match=searchRegex.exec(text)) matchRanges.push({offset:match.index,length:match[0].length});if(matchRanges.length){let highlightedNodes=WI.highlightRangesWithStyleClass(element,matchRanges,"search-highlight",this._searchDOMChanges);this._searchResults.pushAll(highlightedNodes);}}} _revealSearchResult(index,changeFocus) {let highlightElement=this._searchResults[index];if(!highlightElement) return;highlightElement.scrollIntoViewIfNeeded();if(!this._bouncyHighlightElement){this._bouncyHighlightElement=document.createElement("div");this._bouncyHighlightElement.className="bouncy-highlight";this._bouncyHighlightElement.addEventListener("animationend",(event)=>{this._bouncyHighlightElement.remove();});} this._bouncyHighlightElement.remove();let computedStyles=window.getComputedStyle(highlightElement);let highlightElementRect=highlightElement.getBoundingClientRect();let contentViewRect=this.element.getBoundingClientRect();let contentViewScrollTop=this.element.scrollTop;let contentViewScrollLeft=this.element.scrollLeft;this._bouncyHighlightElement.textContent=highlightElement.textContent;this._bouncyHighlightElement.style.top=(highlightElementRect.top-contentViewRect.top+contentViewScrollTop)+"px";this._bouncyHighlightElement.style.left=(highlightElementRect.left-contentViewRect.left+contentViewScrollLeft)+"px";this._bouncyHighlightElement.style.fontWeight=computedStyles.fontWeight;this.element.appendChild(this._bouncyHighlightElement);} _presentPopoverBelowCallStackElement() {let bounds=WI.Rect.rectFromClientRect(this._popoverCallStackIconElement.getBoundingClientRect());this._popover.present(bounds.pad(2),[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);} _resourceMetricsDidChange(event) {this._needsSummaryRefresh=true;this._needsRequestHeadersRefresh=true;this._needsResponseHeadersRefresh=true;this.needsLayout();} _resourceRequestHeadersDidChange(event) {this._needsSummaryRefresh=true;this._needsRedirectHeadersRefresh=true;this._needsRequestHeadersRefresh=true;this.needsLayout();} _resourceResponseReceived(event) {this._needsSummaryRefresh=true;this._needsResponseHeadersRefresh=true;this.needsLayout();}};WI.ResourceHeadersContentView.ReferencePage=WI.ReferencePage.NetworkTab.HeadersPane;WI.ResourceSecurityContentView=class ResourceSecurityContentView extends WI.ContentView {constructor(resource) {super();this._resource=resource;this._insecureMessageElement=null;this._needsConnectionRefresh=true;this._needsCertificateRefresh=true;this._searchQuery=null;this._searchResults=null;this._searchDOMChanges=[];this._searchIndex=-1;this._automaticallyRevealFirstSearchResult=false;this._bouncyHighlightElement=null;this.element.classList.add("resource-details","resource-security");} initialLayout() {super.initialLayout();this._connectionSection=new WI.ResourceDetailsSection(WI.UIString("Connection"),"connection");this.element.appendChild(this._connectionSection.element);this._certificateSection=new WI.ResourceDetailsSection(WI.UIString("Certificate"),"certificate");this.element.appendChild(this._certificateSection.element);this._resource.addEventListener(WI.Resource.Event.ResponseReceived,this._handleResourceResponseReceived,this);this._resource.addEventListener(WI.Resource.Event.MetricsDidChange,this._handleResourceMetricsDidChange,this);} layout() {super.layout();if(!this._resource.loadedSecurely){if(!this._insecureMessageElement) this._insecureMessageElement=WI.createMessageTextView(WI.UIString("The resource was requested insecurely."),true);this.element.appendChild(this._insecureMessageElement);return;} if(this._needsConnectionRefresh){this._needsConnectionRefresh=false;this._refreshConnectionSection();} if(this._needsCertificateRefresh){this._needsCertificateRefresh=false;this._refreshCetificateSection();}} closed() {if(this.didInitialLayout){this._resource.removeEventListener(WI.Resource.Event.ResponseReceived,this._handleResourceResponseReceived,this);this._resource.removeEventListener(WI.Resource.Event.MetricsDidChange,this._handleResourceMetricsDidChange,this);} super.closed();} get supportsSearch() {return true;} get numberOfSearchResults() {return this._searchResults?this._searchResults.length:null;} get hasPerformedSearch() {return this._searchResults!==null;} set automaticallyRevealFirstSearchResult(reveal) {this._automaticallyRevealFirstSearchResult=reveal;if(this._automaticallyRevealFirstSearchResult&&this.numberOfSearchResults>0){if(this._searchIndex===-1) this.revealNextSearchResult();}} performSearch(query) {if(query===this._searchQuery) return;WI.revertDOMChanges(this._searchDOMChanges);this._searchQuery=query;this._searchResults=[];this._searchDOMChanges=[];this._searchIndex=-1;this._perfomSearchOnKeyValuePairs();this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);if(this._automaticallyRevealFirstSearchResult&&this._searchResults.length>0) this.revealNextSearchResult();} searchCleared() {WI.revertDOMChanges(this._searchDOMChanges);this._searchQuery=null;this._searchResults=null;this._searchDOMChanges=[];this._searchIndex=-1;} revealPreviousSearchResult(changeFocus) {if(!this.numberOfSearchResults) return;if(this._searchIndex>0) --this._searchIndex;else this._searchIndex=this._searchResults.length-1;this._revealSearchResult(this._searchIndex,changeFocus);} revealNextSearchResult(changeFocus) {if(!this.numberOfSearchResults) return;if(this._searchIndex!value)){this._connectionSection.markIncompleteSectionWithMessage(WI.UIString("No connection security information."));return;} this._connectionSection.appendKeyValuePair(WI.UIString("Protocol"),connection.protocol||emDash);this._connectionSection.appendKeyValuePair(WI.UIString("Cipher"),connection.cipher||emDash);} _refreshCetificateSection() {let detailsElement=this._certificateSection.detailsElement;detailsElement.removeChildren();let security=this._resource.security;if(isEmptyObject(security)){this._certificateSection.markIncompleteSectionWithMessage(WI.UIString("No certificate security information."));return;} let certificate=security.certificate;if(isEmptyObject(certificate)||Object.values(certificate).every((value)=>!value)){this._certificateSection.markIncompleteSectionWithMessage(WI.UIString("No certificate security information."));return;} if(WI.NetworkManager.supportsShowCertificate()){let button=document.createElement("button");button.textContent=WI.UIString("Show full certificate");let errorElement=null;button.addEventListener("click",(event)=>{this._resource.showCertificate().then(()=>{if(errorElement){errorElement.remove();errorElement=null;}}).catch((error)=>{if(!errorElement) errorElement=WI.ImageUtilities.useSVGSymbol("Images/Error.svg","error",error);button.insertAdjacentElement("afterend",errorElement);});});let pairElement=this._certificateSection.appendKeyValuePair(button);pairElement.classList.add("show-certificate");} this._certificateSection.appendKeyValuePair(WI.UIString("Subject"),certificate.subject||emDash);let appendFormattedDate=(key,timestamp)=>{if(isNaN(timestamp)) return;let date=new Date(timestamp*1000);let timeElement=document.createElement("time");timeElement.datetime=date.toISOString();timeElement.textContent=date.toLocaleString();this._certificateSection.appendKeyValuePair(key,timeElement);};appendFormattedDate(WI.UIString("Valid From"),certificate.validFrom);appendFormattedDate(WI.UIString("Valid Until"),certificate.validUntil);let appendList=(key,values,className)=>{if(!Array.isArray(values)) return;const initialCount=5;for(let i=0;i{showMorePair.remove();for(let i=initialCount;i{this._bouncyHighlightElement.remove();});} this._bouncyHighlightElement.remove();let computedStyles=window.getComputedStyle(highlightElement);let highlightElementRect=highlightElement.getBoundingClientRect();let contentViewRect=this.element.getBoundingClientRect();let contentViewScrollTop=this.element.scrollTop;let contentViewScrollLeft=this.element.scrollLeft;this._bouncyHighlightElement.textContent=highlightElement.textContent;this._bouncyHighlightElement.style.top=(highlightElementRect.top-contentViewRect.top+contentViewScrollTop)+"px";this._bouncyHighlightElement.style.left=(highlightElementRect.left-contentViewRect.left+contentViewScrollLeft)+"px";this._bouncyHighlightElement.style.fontWeight=computedStyles.fontWeight;this.element.appendChild(this._bouncyHighlightElement);} _handleResourceResponseReceived(event) {this._needsCertificateRefresh=true;this.needsLayout();} _handleResourceMetricsDidChange(event) {this._needsConnectionRefresh=true;this.needsLayout();}};WI.ResourceSecurityContentView.ReferencePage=WI.ReferencePage.NetworkTab.SecurityPane;WI.ResourceSizesContentView=class ResourceSizesContentView extends WI.ContentView {constructor(resource,delegate) {super(null);this._resource=resource;this._resource.addEventListener(WI.Resource.Event.SizeDidChange,this._resourceSizeDidChange,this);this._resource.addEventListener(WI.Resource.Event.TransferSizeDidChange,this._resourceTransferSizeDidChange,this);this._resource.addEventListener(WI.Resource.Event.MetricsDidChange,this._resourceMetricsDidChange,this);this._delegate=delegate;this.element.classList.add("resource-details","resource-sizes");this._needsTransferSizesRefresh=false;this._needsResourceSizeRefresh=false;} initialLayout() {super.initialLayout();let contentElement=this.element.appendChild(document.createElement("div"));contentElement.className="content";let networkSection=contentElement.appendChild(document.createElement("section"));networkSection.className="network split";function createSizeComponents(parentElement,subtitle,imageSource,label1,label2){let subtitleElement=parentElement.appendChild(document.createElement("div"));subtitleElement.className="subtitle";subtitleElement.textContent=subtitle;let container=parentElement.appendChild(document.createElement("div"));container.className="container";let imageElement=container.appendChild(document.createElement("img"));if(imageSource) imageElement.src=imageSource;let bytesElement=container.appendChild(document.createElement("div"));bytesElement.className="bytes";let table=parentElement.appendChild(document.createElement("table"));let headerRow=table.appendChild(document.createElement("tr"));let label1Element=headerRow.appendChild(document.createElement("td"));let value1Element=headerRow.appendChild(document.createElement("td"));let bodyRow=table.appendChild(document.createElement("tr"));let label2Element=bodyRow.appendChild(document.createElement("td"));let value2Element=bodyRow.appendChild(document.createElement("td"));label1Element.textContent=label1;label1Element.className="label";label2Element.textContent=label2;label2Element.className="label";return{container,bytesElement,imageElement,value1Element,value2Element,};} let sendingSection=networkSection.appendChild(document.createElement("div"));sendingSection.className="subsection";let sendingComponents=createSizeComponents(sendingSection,WI.UIString("Bytes Sent"),"Images/Sending.svg",WI.UIString("Headers:"),WI.UIString("Body:"));this._sendingBytesElement=sendingComponents.bytesElement;this._sendingHeaderBytesElement=sendingComponents.value1Element;this._sendingBodyBytesElement=sendingComponents.value2Element;let bytesDivider=networkSection.appendChild(document.createElement("div"));bytesDivider.className="divider";let receivingSection=networkSection.appendChild(document.createElement("div"));receivingSection.className="subsection";let receivingComponents=createSizeComponents(receivingSection,WI.UIString("Bytes Received"),"Images/Receiving.svg",WI.UIString("Headers:"),WI.UIString("Body:"));this._receivingBytesElement=receivingComponents.bytesElement;this._receivingHeaderBytesElement=receivingComponents.value1Element;this._receivingBodyBytesElement=receivingComponents.value2Element;let resourceDivider=networkSection.appendChild(document.createElement("div"));resourceDivider.className="divider";let resourceSection=networkSection.appendChild(document.createElement("div"));resourceSection.className="subsection large";let resourceComponents=createSizeComponents(resourceSection,WI.UIString("Resource Size"),null,WI.UIString("Compression:"),WI.UIString("MIME Type:"));resourceComponents.container.classList.add(WI.ResourceTreeElement.ResourceIconStyleClassName,...WI.Resource.classNamesForResource(this._resource));resourceComponents.imageElement.classList.add("icon");if(this._resource.responseSource===WI.Resource.ResponseSource.InspectorOverride) resourceComponents.imageElement.title=WI.UIString("This resource was loaded from a local override");this._resourceBytesElement=resourceComponents.bytesElement;this._compressionElement=resourceComponents.value1Element;this._contentTypeElement=resourceComponents.value2Element;this._refreshTransferSizeSections();this._refreshResourceSizeSection();this._needsTransferSizesRefresh=false;this._needsResourceSizeRefresh=false;} layout() {super.layout();if(this._needsTransferSizesRefresh){this._refreshTransferSizeSections();this._needsTransferSizesRefresh=false;} if(this._needsResourceSizeRefresh){this._refreshResourceSizeSection();this._needsResourceSizeRefresh=false;}} closed() {this._resource.removeEventListener(WI.Resource.Event.SizeDidChange,this._resourceSizeDidChange,this);this._resource.removeEventListener(WI.Resource.Event.TransferSizeDidChange,this._resourceTransferSizeDidChange,this);this._resource.removeEventListener(WI.Resource.Event.MetricsDidChange,this._resourceMetricsDidChange,this);super.closed();} _formattedSizeComponent(bytes) { const higherResolution=false;const bytesThreshold=100;return Number.bytesToString(bytes,higherResolution,bytesThreshold);} _refreshTransferSizeSections() {let bytesSentHeader=this._resource.requestHeadersTransferSize;let bytesSentBody=this._resource.requestBodyTransferSize;let bytesSent=bytesSentHeader+bytesSentBody;let bytesReceivedHeader=this._resource.responseHeadersTransferSize;let bytesReceivedBody=this._resource.responseBodyTransferSize;let bytesReceived=bytesReceivedHeader+bytesReceivedBody;this._sendingBytesElement.textContent=this._formattedSizeComponent(bytesSent||0);this._sendingHeaderBytesElement.textContent=bytesSentHeader?Number.bytesToString(bytesSentHeader):emDash;this._sendingBodyBytesElement.textContent=bytesSentBody?Number.bytesToString(bytesSentBody):emDash;this._receivingBytesElement.textContent=this._formattedSizeComponent(bytesReceived||0);this._receivingHeaderBytesElement.textContent=bytesReceivedHeader?Number.bytesToString(bytesReceivedHeader):emDash;this._receivingBodyBytesElement.textContent=bytesReceivedBody?Number.bytesToString(bytesReceivedBody):emDash;function appendGoToArrow(parentElement,handler){let goToButton=parentElement.appendChild(WI.createGoToArrowButton());goToButton.addEventListener("click",handler);} if(bytesSentHeader) appendGoToArrow(this._sendingHeaderBytesElement,()=>{this._delegate.sizesContentViewGoToHeaders(this);});if(bytesSentBody) appendGoToArrow(this._sendingBodyBytesElement,()=>{this._delegate.sizesContentViewGoToRequestBody(this);});if(bytesReceivedHeader) appendGoToArrow(this._receivingHeaderBytesElement,()=>{this._delegate.sizesContentViewGoToHeaders(this);});if(bytesReceivedBody) appendGoToArrow(this._receivingBodyBytesElement,()=>{this._delegate.sizesContentViewGoToResponseBody(this);});} _refreshResourceSizeSection() {let encodedSize=!isNaN(this._resource.networkEncodedSize)?this._resource.networkEncodedSize:this._resource.estimatedNetworkEncodedSize;let decodedSize=!isNaN(this._resource.networkDecodedSize)?this._resource.networkDecodedSize:this._resource.size;let compressionRate=decodedSize/encodedSize;let compressionString=compressionRate>0&&isFinite(compressionRate)?WI.UIString("%.2f\u00d7").format(compressionRate):WI.UIString("None");this._resourceBytesElement.textContent=this._formattedSizeComponent(decodedSize||0);let contentEncoding=this._resource.responseHeaders.valueForCaseInsensitiveKey("Content-Encoding");if(contentEncoding) compressionString+=` (${contentEncoding.toLowerCase()})`;this._compressionElement.textContent=compressionString;this._contentTypeElement.textContent=this._resource.mimeType||emDash;const minimumSizeBeforeWarning=1024;if(compressionRate<=1&&encodedSize>=minimumSizeBeforeWarning&&WI.shouldTreatMIMETypeAsText(this._resource.mimeType)) this._compressionElement.appendChild(WI.ImageUtilities.useSVGSymbol("Images/Warning.svg","warning",WI.UIString("This text resource could benefit from compression")));} _resourceSizeDidChange(event) {this._needsTransferSizesRefresh=true;this.needsLayout();} _resourceTransferSizeDidChange(event) {this._needsTransferSizesRefresh=true;this.needsLayout();} _resourceMetricsDidChange(event) {this._needsTransferSizesRefresh=true;this._needsResourceSizeRefresh=true;this.needsLayout();}};WI.ResourceSizesContentView.ReferencePage=WI.ReferencePage.NetworkTab.SizesPane;WI.ResourceTimelineDataGridNode=class ResourceTimelineDataGridNode extends WI.TimelineDataGridNode {constructor(record,options={}) {super([record],options);this._shouldShowPopover=options.shouldShowPopover;this.resource.addEventListener(WI.Resource.Event.LoadingDidFinish,this._needsRefresh,this);this.resource.addEventListener(WI.Resource.Event.LoadingDidFail,this._needsRefresh,this);this.resource.addEventListener(WI.Resource.Event.URLDidChange,this._needsRefresh,this);if(options.includesGraph) this.record.addEventListener(WI.TimelineRecord.Event.Updated,this._timelineRecordUpdated,this);else{this.resource.addEventListener(WI.Resource.Event.TypeDidChange,this._needsRefresh,this);this.resource.addEventListener(WI.Resource.Event.SizeDidChange,this._needsRefresh,this);this.resource.addEventListener(WI.Resource.Event.TransferSizeDidChange,this._needsRefresh,this);}} get resource() {return this.record.resource;} get data() {if(this._cachedData) return this._cachedData;this._cachedData=super.data;this._cachedData.domain=WI.displayNameForHost(this.resource.urlComponents.host);this._cachedData.scheme=this.resource.urlComponents.scheme?this.resource.urlComponents.scheme.toUpperCase():"";this._cachedData.method=this.resource.requestMethod;this._cachedData.type=this.resource.type;this._cachedData.statusCode=this.resource.statusCode;this._cachedData.cached=this.resource.cached;this._cachedData.size=this.resource.size;this._cachedData.transferSize=!isNaN(this.resource.networkTotalTransferSize)?this.resource.networkTotalTransferSize:this.resource.estimatedTotalTransferSize;this._cachedData.requestSent=this.resource.requestSentTimestamp-(this.graphDataSource?this.graphDataSource.zeroTime:0);this._cachedData.duration=this.resource.receiveDuration;this._cachedData.latency=this.resource.latency;this._cachedData.protocol=this.resource.protocol;this._cachedData.priority=this.resource.priority;this._cachedData.remoteAddress=this.resource.displayRemoteAddress;this._cachedData.connectionIdentifier=this.resource.connectionIdentifier;this._cachedData.initiator=this.resource.initiatorSourceCodeLocation;this._cachedData.source=this.resource.initiatorSourceCodeLocation; return this._cachedData;} createCellContent(columnIdentifier,cell) {if(this.resource.hadLoadingError()) cell.classList.add("error");let value=this.data[columnIdentifier];switch(columnIdentifier){case"name":cell.classList.add(...this.iconClassNames());cell.title=this.resource.displayURL;this._updateStatus(cell);return this._createNameCellDocumentFragment();case"type":var text=WI.Resource.displayNameForType(value);cell.title=text;return text;case"statusCode":cell.title=this.resource.statusText||"";return value||emDash;case"cached":var fragment=this._cachedCellContent();cell.title=fragment.textContent;return fragment;case"size":case"transferSize":var text=emDash;if(!isNaN(value)){text=Number.bytesToString(value,true);cell.title=text;} return text;case"requestSent":case"latency":case"duration":var text=emDash;if(!isNaN(value)){text=Number.secondsToString(value,true);cell.title=text;} return text;case"domain":case"method":case"scheme":case"protocol":case"remoteAddress":case"connectionIdentifier":if(value) cell.title=value;return value||emDash;case"priority":var title=WI.Resource.displayNameForPriority(value);if(title) cell.title=title;return title||emDash;case"source": return super.createCellContent("initiator",cell);} return super.createCellContent(columnIdentifier,cell);} generateIconTitle(columnIdentifier) {if(columnIdentifier==="name"){if(this.resource.responseSource===WI.Resource.ResponseSource.InspectorOverride) return WI.UIString("This resource was loaded from a local override");} return super.generateIconTitle(columnIdentifier);} refresh() {if(this._scheduledRefreshIdentifier){cancelAnimationFrame(this._scheduledRefreshIdentifier);this._scheduledRefreshIdentifier=undefined;} this._cachedData=null;super.refresh();} iconClassNames() {return[WI.ResourceTreeElement.ResourceIconStyleClassName,...WI.Resource.classNamesForResource(this.resource)];} appendContextMenuItems(contextMenu) {WI.appendContextMenuItemsForSourceCode(contextMenu,this.resource);} didAddRecordBar(recordBar) {if(!this._shouldShowPopover) return;if(!recordBar.records.length||recordBar.records[0].type!==WI.TimelineRecord.Type.Network) return;this._mouseEnterRecordBarListener=this._mouseoverRecordBar.bind(this);recordBar.element.addEventListener("mouseenter",this._mouseEnterRecordBarListener);} didRemoveRecordBar(recordBar) {if(!this._shouldShowPopover) return;if(!recordBar.records.length||recordBar.records[0].type!==WI.TimelineRecord.Type.Network) return;recordBar.element.removeEventListener("mouseenter",this._mouseEnterRecordBarListener);this._mouseEnterRecordBarListener=null;} filterableDataForColumn(columnIdentifier) {if(columnIdentifier==="name") return this.resource.url;return super.filterableDataForColumn(columnIdentifier);} _createNameCellDocumentFragment() {let fragment=document.createDocumentFragment();let mainTitle=this.displayName();fragment.append(mainTitle);let frame=this.resource.parentFrame;let isMainResource=this.resource.isMainResource();let parentResourceHost;if(frame&&isMainResource){parentResourceHost=frame.parentFrame?frame.parentFrame.mainResource.urlComponents.host:null;}else if(frame){parentResourceHost=frame.mainResource.urlComponents.host;} if(parentResourceHost!==this.resource.urlComponents.host||frame.isMainFrame()&&isMainResource){let subtitle=WI.displayNameForHost(this.resource.urlComponents.host);if(mainTitle!==subtitle){let subtitleElement=document.createElement("span");subtitleElement.classList.add("subtitle");subtitleElement.textContent=subtitle;fragment.append(subtitleElement);}} return fragment;} _cachedCellContent() {if(!this.resource.hasResponse()) return emDash;let responseSource=this.resource.responseSource;if(responseSource===WI.Resource.ResponseSource.MemoryCache||responseSource===WI.Resource.ResponseSource.DiskCache){let span=document.createElement("span");let cacheType=document.createElement("span");cacheType.classList="cache-type";cacheType.textContent=responseSource===WI.Resource.ResponseSource.MemoryCache?WI.UIString("(Memory)"):WI.UIString("(Disk)");span.append(WI.UIString("Yes")," ",cacheType);return span;} let fragment=document.createDocumentFragment();fragment.append(this.resource.cached?WI.UIString("Yes"):WI.UIString("No"));return fragment;} _needsRefresh() {if(this.dataGrid instanceof WI.TimelineDataGrid){this.dataGrid.dataGridNodeNeedsRefresh(this);return;} if(this._scheduledRefreshIdentifier) return;this._scheduledRefreshIdentifier=requestAnimationFrame(this.refresh.bind(this));} _timelineRecordUpdated(event) {if(this.isRecordVisible(this.record)) this.needsGraphRefresh();} _dataGridNodeGoToArrowClicked() {const options={ignoreNetworkTab:true,ignoreSearchTab:true,initiatorHint:WI.TabBrowser.TabNavigationInitiator.LinkClick,};WI.showSourceCode(this.resource,options);} _updateStatus(cell) {if(this.resource.failed) cell.classList.add("error");else{cell.classList.remove("error");if(this.resource.finished) this.createGoToArrowButton(cell,this._dataGridNodeGoToArrowClicked.bind(this));} if(this.resource.isLoading()){if(!this._spinner) this._spinner=new WI.IndeterminateProgressSpinner;let contentElement=cell.firstChild;contentElement.appendChild(this._spinner.element);}else{if(this._spinner) this._spinner.element.remove();}} _mouseoverRecordBar(event) {let recordBar=WI.TimelineRecordBar.fromElement(event.target);if(!recordBar) return;let calculateTargetFrame=()=>{let columnRect=WI.Rect.rectFromClientRect(this.elementWithColumnIdentifier("graph").getBoundingClientRect());let barRect=WI.Rect.rectFromClientRect(event.target.getBoundingClientRect());return columnRect.intersectionWithRect(barRect);};let targetFrame=calculateTargetFrame();if(!targetFrame.size.width&&!targetFrame.size.height) return;let resource=recordBar.records[0].resource;if(!resource.timingData) return;if(!resource.timingData.responseEnd) return;if(this.dataGrid._dismissPopoverTimeout){clearTimeout(this.dataGrid._dismissPopoverTimeout);this.dataGrid._dismissPopoverTimeout=undefined;} let popoverContentElement=document.createElement("div");popoverContentElement.classList.add("resource-timing-popover-content");if(resource.failed||resource.urlComponents.scheme==="data"||(resource.cached&&resource.statusCode!==304)){let descriptionElement=document.createElement("span");descriptionElement.classList.add("description");if(resource.failed) descriptionElement.textContent=WI.UIString("Resource failed to load.");else if(resource.urlComponents.scheme==="data") descriptionElement.textContent=WI.UIString("Resource was loaded with the \u201Cdata\u201D scheme.");else descriptionElement.textContent=WI.UIString("Resource was served from the cache.");popoverContentElement.appendChild(descriptionElement);}else{let columns={description:{width:"80px"},graph:{width:`${WI.ResourceTimelineDataGridNode.PopoverGraphColumnWidthPixels}px`},duration:{width:"70px",aligned:"right"}};let popoverDataGrid=new WI.DataGrid(columns);popoverDataGrid.inline=true;popoverDataGrid.headerVisible=false;popoverContentElement.appendChild(popoverDataGrid.element);let graphDataSource={get secondsPerPixel(){return resource.totalDuration/WI.ResourceTimelineDataGridNode.PopoverGraphColumnWidthPixels;},get zeroTime(){return resource.firstTimestamp;},get startTime(){return this.zeroTime;},get currentTime(){return resource.lastTimestamp+this._extraTimePadding;},get endTime(){return this.currentTime;},get _extraTimePadding(){return this.secondsPerPixel*WI.TimelineRecordBar.MinimumWidthPixels;},};if(resource.timingData.redirectEnd-resource.timingData.redirectStart){ popoverDataGrid.appendChild(new WI.ResourceTimingPopoverDataGridNode(WI.UIString("Redirects"),resource.timingData.redirectStart,resource.timingData.redirectEnd,graphDataSource));} let secondTimestamp=resource.timingData.domainLookupStart||resource.timingData.connectStart||resource.timingData.requestStart;if(secondTimestamp-resource.timingData.fetchStart) popoverDataGrid.appendChild(new WI.ResourceTimingPopoverDataGridNode(WI.UIString("Stalled"),resource.timingData.fetchStart,secondTimestamp,graphDataSource));if(resource.timingData.domainLookupStart) popoverDataGrid.appendChild(new WI.ResourceTimingPopoverDataGridNode(WI.UIString("DNS"),resource.timingData.domainLookupStart,resource.timingData.domainLookupEnd,graphDataSource));if(resource.timingData.connectStart) popoverDataGrid.appendChild(new WI.ResourceTimingPopoverDataGridNode(WI.UIString("Connection"),resource.timingData.connectStart,resource.timingData.connectEnd,graphDataSource));if(resource.timingData.secureConnectionStart) popoverDataGrid.appendChild(new WI.ResourceTimingPopoverDataGridNode(WI.UIString("Secure"),resource.timingData.secureConnectionStart,resource.timingData.connectEnd,graphDataSource));popoverDataGrid.appendChild(new WI.ResourceTimingPopoverDataGridNode(WI.UIString("Request"),resource.timingData.requestStart,resource.timingData.responseStart,graphDataSource));popoverDataGrid.appendChild(new WI.ResourceTimingPopoverDataGridNode(WI.UIString("Response"),resource.timingData.responseStart,resource.timingData.responseEnd,graphDataSource));const higherResolution=true;let totalData={description:WI.UIString("Total time"),duration:Number.secondsToMillisecondsString(resource.timingData.responseEnd-resource.timingData.startTime,higherResolution)};popoverDataGrid.appendChild(new WI.DataGridNode(totalData));popoverDataGrid.updateLayout();} if(!this.dataGrid._popover) this.dataGrid._popover=new WI.Popover;let preferredEdges=[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MIN_X];this.dataGrid._popover.windowResizeHandler=()=>{let bounds=calculateTargetFrame();this.dataGrid._popover.present(bounds.pad(2),preferredEdges);};recordBar.element.addEventListener("mouseleave",()=>{if(!this.dataGrid) return;this.dataGrid._dismissPopoverTimeout=setTimeout(()=>{if(this.dataGrid) this.dataGrid._popover.dismiss();},WI.ResourceTimelineDataGridNode.DelayedPopoverDismissalTimeout);},{once:true});this.dataGrid._popover.presentNewContentWithFrame(popoverContentElement,targetFrame.pad(2),preferredEdges);}};WI.ResourceTimelineDataGridNode.PopoverGraphColumnWidthPixels=110;WI.ResourceTimelineDataGridNode.DelayedPopoverDismissalTimeout=500;WI.ResourceTimingBreakdownView=class ResourceTimingBreakdownView extends WI.View {constructor(resource,fixedWidth) {super(null);this._resource=resource;this.element.classList.add("resource-timing-breakdown");if(fixedWidth) this.element.style.width=fixedWidth+"px";} _appendEmptyRow() {let row=this._tableElement.appendChild(document.createElement("tr"));row.className="empty";return row;} _appendHeaderRow(label,time,additionalClassName) {let row=this._tableElement.appendChild(document.createElement("tr"));row.className="header";if(additionalClassName) row.classList.add(additionalClassName);let labelCell=row.appendChild(document.createElement("td"));labelCell.className="label";labelCell.textContent=label;labelCell.colSpan=2;let timeCell=row.appendChild(document.createElement("td"));timeCell.className="time";if(time) timeCell.textContent=time;else if(time===undefined) timeCell.appendChild(document.createElement("hr"));return row;} _appendRow(label,type,startTime,endTime) {let row=this._tableElement.appendChild(document.createElement("tr"));let labelCell=row.appendChild(document.createElement("td"));labelCell.className="label";labelCell.textContent=label;let duration=endTime-startTime;let graphWidth=(duration/this._graphDuration)*100;let graphOffset=((startTime-this._graphStartTime)/this._graphDuration)*100;let positionProperty=WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL?"right":"left";let graphCell=row.appendChild(document.createElement("td"));graphCell.className="graph";let block=graphCell.appendChild(document.createElement("div"));block.classList.add("block",type);block.style.width=graphWidth+"%";block.style[positionProperty]=graphOffset+"%";let timeCell=row.appendChild(document.createElement("td"));timeCell.className="time";timeCell.textContent=Number.secondsToMillisecondsString(duration);return row;} _appendServerTimingRow(label,duration,maxDuration) {let row=this._tableElement.appendChild(document.createElement("tr"));let labelCell=row.appendChild(document.createElement("td"));labelCell.className="label";labelCell.textContent=label;if(duration!==undefined){let graphWidth=(duration/maxDuration)*100;let graphCell=row.appendChild(document.createElement("td"));graphCell.className="graph";let block=graphCell.appendChild(document.createElement("div"));block.classList.add("block","response");block.style.width=graphWidth+"%";block.style.right=0;let timeCell=row.appendChild(document.createElement("td"));timeCell.className="time";timeCell.textContent=Number.secondsToMillisecondsString(duration/1000);} return row;} _appendDividerRow() {let emptyCell=this._appendEmptyRow().appendChild(document.createElement("td"));emptyCell.colSpan=3;emptyCell.appendChild(document.createElement("hr"));} initialLayout() {super.initialLayout();let{startTime,redirectStart,redirectEnd,fetchStart,domainLookupStart,domainLookupEnd,connectStart,connectEnd,secureConnectionStart,requestStart,responseStart,responseEnd}=this._resource.timingData;let serverTiming=this._resource.serverTiming;this._tableElement=this.element.appendChild(document.createElement("table"));this._tableElement.className="waterfall network";this._graphStartTime=startTime;this._graphEndTime=responseEnd;this._graphDuration=this._graphEndTime-this._graphStartTime;this._appendHeaderRow(WI.UIString("Scheduling:"));if(redirectEnd-redirectStart){ this._appendRow(WI.UIString("Redirects"),"redirect",redirectStart,redirectEnd);} this._appendRow(WI.UIString("Queued"),"queue",fetchStart,domainLookupStart||connectStart||requestStart);if(domainLookupStart||connectStart){this._appendEmptyRow();this._appendHeaderRow(WI.UIString("Connection:"));if(domainLookupStart) this._appendRow(WI.UIString("DNS"),"dns",domainLookupStart,domainLookupEnd||connectStart||requestStart);if(connectStart) this._appendRow(WI.UIString("TCP"),"connect",connectStart,connectEnd||requestStart);if(secureConnectionStart) this._appendRow(WI.UIString("Secure"),"secure",secureConnectionStart,connectEnd||requestStart);} this._appendEmptyRow();this._appendHeaderRow(WI.UIString("Response:"));this._appendRow(WI.UIString("Waiting"),"request",requestStart,responseStart);this._appendRow(WI.UIString("Download"),"response",responseStart,responseEnd);this._appendEmptyRow();this._appendHeaderRow(WI.UIString("Totals:"));this._appendHeaderRow(WI.UIString("Time to First Byte"),Number.secondsToMillisecondsString(responseStart-startTime),"total-row");this._appendHeaderRow(WI.UIString("Start to Finish"),Number.secondsToMillisecondsString(responseEnd-startTime),"total-row");if(serverTiming.length>0){this._appendDividerRow();this._appendHeaderRow(WI.UIString("Server Timing:"));let maxDuration=serverTiming.reduce((max,{duration=0})=>Math.max(max,duration),0);for(let entry of serverTiming){let{name,duration,description}=entry;this._appendServerTimingRow(description||name,duration,maxDuration);}}}};WI.ResourceTimingContentView=class ResourceTimingContentView extends WI.ContentView {constructor(resource) {super(null);this._resource=resource;this._resource.addEventListener(WI.Resource.Event.MetricsDidChange,this._resourceMetricsDidChange,this);this._resource.addEventListener(WI.Resource.Event.TimestampsDidChange,this._resourceTimestampsDidChange,this);this.element.classList.add("resource-details","resource-timing");this._needsTimingRefresh=false;} initialLayout() {super.initialLayout();this._refreshTimingSection();this._needsTimingRefresh=false;} layout() {super.layout();if(this._needsTimingRefresh){this._refreshTimingSection();this._needsTimingRefresh=false;}} closed() {this._resource.removeEventListener(WI.Resource.Event.MetricsDidChange,this._resourceMetricsDidChange,this);this._resource.removeEventListener(WI.Resource.Event.TimestampsDidChange,this._resourceTimestampsDidChange,this);super.closed();} _refreshTimingSection() {this.element.removeChildren();if(!this._resource.hasResponse()){let spinner=new WI.IndeterminateProgressSpinner;this.element.appendChild(spinner.element);return;} if(!this._resource.timingData.startTime||!this._resource.timingData.responseEnd){const isError=false;this.element.appendChild(WI.createMessageTextView(WI.UIString("Resource does not have timing data"),isError));return;} let contentElement=this.element.appendChild(document.createElement("div"));contentElement.className="content";let timingSection=contentElement.appendChild(document.createElement("section"));timingSection.className="timing";let breakdownView=new WI.ResourceTimingBreakdownView(this._resource);timingSection.appendChild(breakdownView.element);breakdownView.updateLayout();} _resourceMetricsDidChange(event) {this._needsTimingRefresh=true;this.needsLayout();} _resourceTimestampsDidChange(event) {this._needsTimingRefresh=true;this.needsLayout();}};WI.ResourceTimingContentView.ReferencePage=WI.ReferencePage.NetworkTab.TimingPane;WI.ResourceTimingPopoverDataGridNode=class ResourceTimingPopoverDataGridNode extends WI.TimelineDataGridNode {constructor(description,startTime,endTime,graphDataSource) {let record=new WI.TimelineRecord(WI.TimelineRecord.Type.Network,startTime,endTime);super([record],{includesGraph:true,graphDataSource,});const higherResolution=true;let duration=Number.secondsToMillisecondsString(endTime-startTime,higherResolution);this._data={description,duration};} get data(){return this._data;} get selectable() {return false;} createCellContent(columnIdentifier,cell) {let value=this.data[columnIdentifier];switch(columnIdentifier){case"description":case"duration":return value||emDash;} return super.createCellContent(columnIdentifier,cell);}};WI.ScopeBar=class ScopeBar extends WI.NavigationItem {constructor(identifier,items,defaultItem,shouldGroupNonExclusiveItems) {super(identifier);this._element.classList.add("scope-bar");this._items=items;this._defaultItem=defaultItem;this._shouldGroupNonExclusiveItems=shouldGroupNonExclusiveItems||false;for(let item of this._items) item.scopeBar=this;this._minimumWidth=0;this._populate();this._element.addEventListener("keydown",this._handleKeyDown.bind(this));} get minimumWidth() {if(!this._minimumWidth){ this.element.style.flexWrap="initial !important";if(this._multipleItem) this._multipleItem.displayWidestItem();this._minimumWidth=this.element.realOffsetWidth;this.element.style.flexWrap=null;if(this._multipleItem) this._multipleItem.displaySelectedItem();} return this._minimumWidth;} get defaultItem() {return this._defaultItem;} get items() {return this._items;} item(id) {return this._itemsById.get(id);} get selectedItems() {return this._items.filter((item)=>item.selected);} hasNonDefaultItemSelected() {return this._items.some((item)=>item.selected&&item!==this._defaultItem);} resetToDefault() {let selectedItems=this.selectedItems;if(selectedItems.length===1&&selectedItems[0]===this._defaultItem) return;for(let item of this._items) item.selected=false;this._defaultItem.selected=true;this.dispatchEventToListeners(WI.ScopeBar.Event.SelectionChanged);} _populate() {this._itemsById=new Map;if(this._shouldGroupNonExclusiveItems){var nonExclusiveItems=[];for(var item of this._items){this._itemsById.set(item.id,item);if(item.exclusive) this._element.appendChild(item.element);else nonExclusiveItems.push(item);item.addEventListener(WI.ScopeBarItem.Event.SelectionChanged,this._itemSelectionDidChange,this);} this._multipleItem=new WI.MultipleScopeBarItem(nonExclusiveItems);this._element.appendChild(this._multipleItem.element);}else{for(var item of this._items){this._itemsById.set(item.id,item);this._element.appendChild(item.element);item.addEventListener(WI.ScopeBarItem.Event.SelectionChanged,this._itemSelectionDidChange,this);}} if(this._defaultItem){if(!this.selectedItems.length) this._defaultItem.selected=true;this._element.classList.toggle("default-item-selected",this._defaultItem.selected);}} _itemSelectionDidChange(event) {var sender=event.target;var item;if(sender.exclusive&&sender.selected){for(var i=0;i{this._popoverCommitted=true;popover.dismiss();},});let completionController=new WI.CodeMirrorCompletionController(WI.CodeMirrorCompletionController.Mode.FullConsoleCommandLineAPI,this._codeMirror);completionController.addExtendedCompletionProvider("javascript",WI.javaScriptRuntimeCompletionProvider);let previousHeight=0;this._codeMirror.on("changes",function(cm,event){let height=cm.getScrollInfo().height;if(previousHeight!==height){previousHeight=height;popover.update(false);}});popover.content=content;popover.windowResizeHandler=presentPopoverOverTargetElement;presentPopoverOverTargetElement();setTimeout(()=>{this._codeMirror.refresh();this._codeMirror.focus();popover.update();},0);} willDismissPopover(popover) {if(this._popoverCommitted){let expression=this._codeMirror.getValue().trim();if(expression) this._addWatchExpression(expression);} this._codeMirror=null;} _refreshAllWatchExpressionsButtonClicked(event) {this.needsLayout();} _clearAllWatchExpressionsButtonClicked(event) {this._clearAllWatchExpressions();} _didEvaluateExpression(event) {if(event.data.objectGroup===WI.ScopeChainDetailsSidebarPanel.WatchExpressionsObjectGroupName) return;this.needsLayout();} _activeExecutionContextChanged() {this.needsLayout();} _activeCallFrameDidChange() {this.needsLayout();} _mainResourceDidChange(event) {if(!event.target.isMainFrame()) return;this.needsLayout();} _objectTreeElementAddContextMenuItems(objectTreeElement,contextMenu) {if(objectTreeElement.parent!==objectTreeElement.treeOutline) return;contextMenu.appendItem(WI.UIString("Delete Watch Expression"),()=>{let expression=objectTreeElement.property.name;this._removeWatchExpression(expression);});} _propertyPathIdentifierForTreeElement(identifier,objectPropertyTreeElement) {if(!objectPropertyTreeElement.property) return null;let propertyPath=objectPropertyTreeElement.thisPropertyPath();if(propertyPath.isFullPathImpossible()) return null;return identifier+"-"+propertyPath.fullPath;} _treeElementAdded(identifier,event) {let treeElement=event.data.element;let propertyPathIdentifier=this._propertyPathIdentifierForTreeElement(identifier,treeElement);if(!propertyPathIdentifier) return;if(WI.ScopeChainDetailsSidebarPanel._autoExpandProperties.has(propertyPathIdentifier)) treeElement.expand();} _treeElementDisclosureDidChange(identifier,event) {let treeElement=event.data.element;let propertyPathIdentifier=this._propertyPathIdentifierForTreeElement(identifier,treeElement);if(!propertyPathIdentifier) return;if(treeElement.expanded) WI.ScopeChainDetailsSidebarPanel._autoExpandProperties.add(propertyPathIdentifier);else WI.ScopeChainDetailsSidebarPanel._autoExpandProperties.delete(propertyPathIdentifier);} _updateWatchExpressionsNavigationBar() {let enabled=this._watchExpressionsSetting.value.length;this._refreshAllWatchExpressionButton.enabled=enabled;this._clearAllWatchExpressionButton.enabled=enabled;}};WI.ScopeChainDetailsSidebarPanel._autoExpandProperties=new Set;WI.ScopeChainDetailsSidebarPanel.WatchExpressionsObjectGroupName="watch-expressions";WI.ScreenshotsTimelineOverviewGraph=class ScreenshotsTimelineOverviewGraph extends WI.TimelineOverviewGraph {constructor(timeline,timelineOverview) {super(timelineOverview);this.element.classList.add("screenshots");this._screenshotsTimeline=timeline;this._lastSelectedRecordInLayout=null;this.reset();} get height() {return 60;} reset() {super.reset();this._imageElementForRecord=new WeakMap;} layout() {super.layout();if(this.hidden) return;this.element.removeChildren();let secondsPerPixel=this.timelineOverview.secondsPerPixel;for(let record of this._visibleRecords()){let recordElement=this.element.appendChild(this._imageElementForRecord.getOrInitialize(record,()=>{let imageElement=document.createElement("img");imageElement.hidden=true;imageElement.addEventListener("load",(event)=>{imageElement.hidden=false;},{once:true});imageElement.src=record.imageData;imageElement.addEventListener("click",(event)=>{event.__timelineRecordClickEventHandled=true;this.selectedRecord=record;});return imageElement;}));recordElement.style.left=(record.startTime-this.startTime)/secondsPerPixel+"px";recordElement.height=this.height;} if(this._lastSelectedRecordInLayout) this._imageElementForRecord.get(this._lastSelectedRecordInLayout)?.classList.remove("selected");this._lastSelectedRecordInLayout=this.selectedRecord;if(this._lastSelectedRecordInLayout) this._imageElementForRecord.get(this._lastSelectedRecordInLayout)?.classList.add("selected");} updateSelectedRecord() {super.updateSelectedRecord();if(this._lastSelectedRecordInLayout!==this.selectedRecord){ this.needsLayout();}} _visibleRecords() {let visibleEndTime=Math.min(this.endTime,this.currentTime);let records=this._screenshotsTimeline.records;let visibleRecords=[];for(let i=0;i=this.startTime||record.startTime<=visibleEndTime)) continue;if(!visibleRecords.length&&i) visibleRecords.push(records[i-1]);visibleRecords.push(record);} return visibleRecords;}};WI.ScreenshotsTimelineView=class ScreenshotsTimelineView extends WI.TimelineView {constructor(timeline,extraArguments) {super(timeline,extraArguments);this._screenshotsTimeline=timeline;this.element.classList.add("screenshots");this._selectedRecord=null;this._imageElementForRecord=new WeakMap;} reset() {super.reset();this.selectRecord(null);this._imageElementForRecord=new WeakMap;} get showsFilterBar(){return false;} initialLayout() {super.initialLayout();this._scrollView=new WI.ContentView;this.addSubview(this._scrollView);} layout() {if(this.layoutReason===WI.View.LayoutReason.Resize) return;super.layout();if(this.hidden) return;this._scrollView.element.removeChildren();let selectedElement=null;for(let record of this._visibleRecords()){this._scrollView.element.appendChild(this._imageElementForRecord.getOrInitialize(record,()=>{let imageElement=document.createElement("img");imageElement.hidden=true;imageElement.addEventListener("load",(event)=>{imageElement.hidden=false;},{once:true});imageElement.src=record.imageData;imageElement.addEventListener("click",(event)=>{this._selectTimelineRecord(record);});if(record===this._selectedRecord) selectedElement=imageElement;return imageElement;}));} if(selectedElement){selectedElement.classList.add("selected");selectedElement.scrollIntoView({inline:"center"});} if(this._scrollView.element.childNodes.length){let spacer=this._scrollView.element.appendChild(document.createElement("div"));spacer.className="spacer";}else this._scrollView.element.appendChild(WI.createMessageTextView(WI.UIString("No screenshots","No screenshots @ Screenshots Timeline","Placeholder text shown when there are no images to display in the Screenshots timeline.")));} selectRecord(record) {if(record===this._selectedRecord) return;if(this._selectedRecord) this._imageElementForRecord.get(this._selectedRecord)?.classList.remove("selected");this._selectedRecord=record;if(this._selectedRecord){let element=this._imageElementForRecord.get(this._selectedRecord);if(element){element.classList.add("selected");element.scrollIntoView({inline:"center"});}}} _selectTimelineRecord(record) {this.dispatchEventToListeners(WI.TimelineView.Event.RecordWasSelected,{record});} _visibleRecords() {let visibleEndTime=Math.min(this.endTime,this.currentTime);let records=this._screenshotsTimeline.records;let visibleRecords=[];for(let i=0;i=this.startTime||record.startTime<=visibleEndTime)) continue;if(!visibleRecords.length&&i) visibleRecords.push(records[i-1]);visibleRecords.push(record);} return visibleRecords;}};WI.ScreenshotsTimelineView.ReferencePage=WI.ReferencePage.TimelinesTab.ScreenshotsTimeline;WI.ScriptClusterTimelineView=class ScriptClusterTimelineView extends WI.ClusterContentView {constructor(timeline,extraArguments) {super(timeline);this._currentContentViewSetting=new WI.Setting("script-cluster-timeline-view-current-view",WI.ScriptClusterTimelineView.EventsIdentifier);function createPathComponent(displayName,className,identifier) {const showSelectorArrows=true;let pathComponent=new WI.HierarchicalPathComponent(displayName,className,identifier,false,showSelectorArrows);pathComponent.addEventListener(WI.HierarchicalPathComponent.Event.SiblingWasSelected,this._pathComponentSelected,this);pathComponent.comparisonData=timeline;return pathComponent;} this._eventsPathComponent=createPathComponent.call(this,WI.UIString("Events"),"events-icon",WI.ScriptClusterTimelineView.EventsIdentifier);this._profilePathComponent=createPathComponent.call(this,WI.UIString("Call Trees"),"call-trees-icon",WI.ScriptClusterTimelineView.ProfileIdentifier);this._eventsPathComponent.nextSibling=this._profilePathComponent;this._profilePathComponent.previousSibling=this._eventsPathComponent;this._eventsContentView=new WI.ScriptDetailsTimelineView(this.representedObject,extraArguments);this._profileContentView=new WI.ScriptProfileTimelineView(this.representedObject,extraArguments);this._showContentViewForIdentifier(this._currentContentViewSetting.value);this.contentViewContainer.addEventListener(WI.ContentViewContainer.Event.CurrentContentViewDidChange,this._scriptClusterViewCurrentContentViewDidChange,this);} get showsLiveRecordingData(){return this._contentViewContainer.currentContentView.showsLiveRecordingData;} get showsFilterBar(){return this._contentViewContainer.currentContentView.showsFilterBar;} get zeroTime(){return this._contentViewContainer.currentContentView.zeroTime;} set zeroTime(x){this._contentViewContainer.currentContentView.zeroTime=x;} get startTime(){return this._contentViewContainer.currentContentView.startTime;} set startTime(x){this._contentViewContainer.currentContentView.startTime=x;} get endTime(){return this._contentViewContainer.currentContentView.endTime;} set endTime(x){this._contentViewContainer.currentContentView.endTime=x;} get currentTime(){return this._contentViewContainer.currentContentView.currentTime;} set currentTime(x){this._contentViewContainer.currentContentView.currentTime=x;} selectRecord(record){this._contentViewContainer.currentContentView.selectRecord(record);} updateFilter(filters){return this._contentViewContainer.currentContentView.updateFilter(filters);} filterDidChange(){return this._contentViewContainer.currentContentView.filterDidChange();} matchDataGridNodeAgainstCustomFilters(node){return this._contentViewContainer.currentContentView.matchDataGridNodeAgainstCustomFilters(node);} reset() {this._eventsContentView.reset();this._profileContentView.reset();} get eventsContentView() {return this._eventsContentView;} get profileContentView() {return this._profileContentView;} get selectionPathComponents() {let currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView) return[];let components=[this._pathComponentForContentView(currentContentView)];let subComponents=currentContentView.selectionPathComponents;if(subComponents) components.pushAll(subComponents);return components;} saveToCookie(cookie) {cookie[WI.ScriptClusterTimelineView.ContentViewIdentifierCookieKey]=this._currentContentViewSetting.value;} restoreFromCookie(cookie) {this._showContentViewForIdentifier(cookie[WI.ScriptClusterTimelineView.ContentViewIdentifierCookieKey]);} showEvents() {return this._showContentViewForIdentifier(WI.ScriptClusterTimelineView.EventsIdentifier);} showProfile() {return this._showContentViewForIdentifier(WI.ScriptClusterTimelineView.ProfileIdentifier);} _pathComponentForContentView(contentView) {if(!contentView) return null;if(contentView===this._eventsContentView) return this._eventsPathComponent;if(contentView===this._profileContentView) return this._profilePathComponent;console.error("Unknown contentView.");return null;} _identifierForContentView(contentView) {if(!contentView) return null;if(contentView===this._eventsContentView) return WI.ScriptClusterTimelineView.EventsIdentifier;if(contentView===this._profileContentView) return WI.ScriptClusterTimelineView.ProfileIdentifier;console.error("Unknown contentView.");return null;} _showContentViewForIdentifier(identifier) {let contentViewToShow=null;switch(identifier){case WI.ScriptClusterTimelineView.EventsIdentifier:contentViewToShow=this.eventsContentView;break;case WI.ScriptClusterTimelineView.ProfileIdentifier:contentViewToShow=this.profileContentView;break;} if(!contentViewToShow) contentViewToShow=this.eventsContentView;this._currentContentViewSetting.value=this._identifierForContentView(contentViewToShow);return this.contentViewContainer.showContentView(contentViewToShow);} _pathComponentSelected(event) {this._showContentViewForIdentifier(event.data.pathComponent.representedObject);} _scriptClusterViewCurrentContentViewDidChange(event) {let currentContentView=this._contentViewContainer.currentContentView;if(!currentContentView) return;let previousContentView=currentContentView===this._eventsContentView?this._profileContentView:this._eventsContentView;currentContentView.zeroTime=previousContentView.zeroTime;currentContentView.startTime=previousContentView.startTime;currentContentView.endTime=previousContentView.endTime;currentContentView.currentTime=previousContentView.currentTime;}};WI.ScriptClusterTimelineView.ContentViewIdentifierCookieKey="script-cluster-timeline-view-identifier";WI.ScriptClusterTimelineView.EventsIdentifier="events";WI.ScriptClusterTimelineView.ProfileIdentifier="profile";WI.ScriptContentView=class ScriptContentView extends WI.ContentView {constructor(script) {super(script);this.element.classList.add("script");var spinner=new WI.IndeterminateProgressSpinner;this.element.appendChild(spinner.element);this._script=script; var toolTip=WI.UIString("Pretty print");var activatedToolTip=WI.UIString("Original formatting");this._prettyPrintButtonNavigationItem=new WI.ActivateButtonNavigationItem("pretty-print",toolTip,activatedToolTip,"Images/NavigationItemCurleyBraces.svg",13,13);this._prettyPrintButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._togglePrettyPrint,this);this._prettyPrintButtonNavigationItem.enabled=false;this._prettyPrintButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;var toolTipTypes=WI.UIString("Show type information");var activatedToolTipTypes=WI.UIString("Hide type information");this._showTypesButtonNavigationItem=new WI.ActivateButtonNavigationItem("show-types",toolTipTypes,activatedToolTipTypes,"Images/NavigationItemTypes.svg",13,14);this._showTypesButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._toggleTypeAnnotations,this);this._showTypesButtonNavigationItem.enabled=false;this._showTypesButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;WI.settings.showJavaScriptTypeInformation.addEventListener(WI.Setting.Event.Changed,this._showJavaScriptTypeInformationSettingChanged,this);let toolTipCodeCoverage=WI.UIString("Fade unexecuted code");let activatedToolTipCodeCoverage=WI.UIString("Do not fade unexecuted code");this._codeCoverageButtonNavigationItem=new WI.ActivateButtonNavigationItem("code-coverage",toolTipCodeCoverage,activatedToolTipCodeCoverage,"Images/NavigationItemCodeCoverage.svg",13,14);this._codeCoverageButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._toggleUnexecutedCodeHighlights,this);this._codeCoverageButtonNavigationItem.enabled=false;this._codeCoverageButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;WI.settings.enableControlFlowProfiler.addEventListener(WI.Setting.Event.Changed,this._enableControlFlowProfilerSettingChanged,this);this._textEditor=new WI.SourceCodeTextEditor(script);this._textEditor.addEventListener(WI.TextEditor.Event.ExecutionLineNumberDidChange,this._executionLineNumberDidChange,this);this._textEditor.addEventListener(WI.TextEditor.Event.NumberOfSearchResultsDidChange,this._numberOfSearchResultsDidChange,this);this._textEditor.addEventListener(WI.TextEditor.Event.FormattingDidChange,this._textEditorFormattingDidChange,this);this._textEditor.addEventListener(WI.TextEditor.Event.MIMETypeChanged,this._handleTextEditorMIMETypeChanged,this);this._textEditor.addEventListener(WI.SourceCodeTextEditor.Event.ContentWillPopulate,this._contentWillPopulate,this);this._textEditor.addEventListener(WI.SourceCodeTextEditor.Event.ContentDidPopulate,this._contentDidPopulate,this);if(this._script instanceof WI.LocalScript&&this._script.editable) this._textEditor.addEventListener(WI.TextEditor.Event.ContentDidChange,this._handleTextEditorContentDidChange,this);} get navigationItems() {return[this._prettyPrintButtonNavigationItem,this._showTypesButtonNavigationItem,this._codeCoverageButtonNavigationItem];} get script() {return this._script;} get textEditor() {return this._textEditor;} get supplementalRepresentedObjects() {if(isNaN(this._textEditor.executionLineNumber)) return[]; return[WI.debuggerManager.activeCallFrame];} revealPosition(position,options={}) {this._textEditor.revealPosition(position,options);} closed() {super.closed();WI.settings.showJavaScriptTypeInformation.removeEventListener(WI.Setting.Event.Changed,this._showJavaScriptTypeInformationSettingChanged,this);WI.settings.enableControlFlowProfiler.removeEventListener(WI.Setting.Event.Changed,this._enableControlFlowProfilerSettingChanged,this);this._textEditor.close();} saveToCookie(cookie) {cookie.type=WI.ContentViewCookieType.Resource;cookie.url=this.representedObject.url;} restoreFromCookie(cookie) {let textRangeToSelect=null;if(!isNaN(cookie.startLine)&&!isNaN(cookie.startColumn)&&!isNaN(cookie.endLine)&&!isNaN(cookie.endColumn)) textRangeToSelect=new WI.TextRange(cookie.startLine,cookie.startColumn,cookie.endLine,cookie.endColumn);let position=null;if(!isNaN(cookie.lineNumber)&&!isNaN(cookie.columnNumber)) position=new WI.SourceCodePosition(cookie.lineNumber,cookie.columnNumber);else if(textRangeToSelect) position=textRangeToSelect.startPosition();let scrollOffset=null;if(!isNaN(cookie.scrollOffsetX)&&!isNaN(cookie.scrollOffsetY)) scrollOffset=new WI.Point(cookie.scrollOffsetX,cookie.scrollOffsetY);if(position) this.revealPosition(position,{...cookie,textRangeToSelect,scrollOffset});} get supportsSave() {return true;} get saveMode() {return WI.FileUtilities.SaveMode.SingleFile;} get saveData() {let saveData={url:this._script.url,content:this._textEditor.string,};if(!this._script.url) saveData.suggestedName=this._script.displayName+".js";return saveData;} get supportsSearch() {return true;} get numberOfSearchResults() {return this._textEditor.numberOfSearchResults;} get hasPerformedSearch() {return this._textEditor.currentSearchQuery!==null;} set automaticallyRevealFirstSearchResult(reveal) {this._textEditor.automaticallyRevealFirstSearchResult=reveal;} performSearch(query) {this._textEditor.performSearch(query);} searchCleared() {this._textEditor.searchCleared();} searchQueryWithSelection() {return this._textEditor.searchQueryWithSelection();} revealPreviousSearchResult(changeFocus) {this._textEditor.revealPreviousSearchResult(changeFocus);} revealNextSearchResult(changeFocus) {this._textEditor.revealNextSearchResult(changeFocus);} _contentWillPopulate(event) {if(this._textEditor.element.parentNode===this.element) return;if(this._script.urlComponents.scheme==="file"||(this._script instanceof WI.LocalScript&&this._script.editable)) this._textEditor.readOnly=false;this.element.removeChildren();this.addSubview(this._textEditor);} _contentDidPopulate(event) {let isLocalScript=this._script instanceof WI.LocalScript;this._prettyPrintButtonNavigationItem.enabled=this._textEditor.canBeFormatted();this._showTypesButtonNavigationItem.enabled=!isLocalScript&&this._textEditor.canShowTypeAnnotations();this._showTypesButtonNavigationItem.activated=WI.settings.showJavaScriptTypeInformation.value;this._codeCoverageButtonNavigationItem.enabled=!isLocalScript&&this._textEditor.canShowCoverageHints();this._codeCoverageButtonNavigationItem.activated=WI.settings.enableControlFlowProfiler.value;} _handleTextEditorContentDidChange(event) {this._updateRevisionContentDebouncer||=new Debouncer(()=>{this._script.editableRevision.updateRevisionContent(this._textEditor.string);});this._updateRevisionContentDebouncer.delayForTime(250);} _togglePrettyPrint(event) {var activated=!this._prettyPrintButtonNavigationItem.activated;this._textEditor.updateFormattedState(activated);} _toggleTypeAnnotations(event) {this._showTypesButtonNavigationItem.enabled=false;this._textEditor.toggleTypeAnnotations().then(()=>{this._showTypesButtonNavigationItem.enabled=true;});} _toggleUnexecutedCodeHighlights(event) {this._codeCoverageButtonNavigationItem.enabled=false;this._textEditor.toggleUnexecutedCodeHighlights().then(()=>{this._codeCoverageButtonNavigationItem.enabled=true;});} _showJavaScriptTypeInformationSettingChanged(event) {this._showTypesButtonNavigationItem.activated=WI.settings.showJavaScriptTypeInformation.value;} _enableControlFlowProfilerSettingChanged(event) {this._codeCoverageButtonNavigationItem.activated=WI.settings.enableControlFlowProfiler.value;} _textEditorFormattingDidChange(event) {this._prettyPrintButtonNavigationItem.activated=this._textEditor.formatted;} _handleTextEditorMIMETypeChanged(event) {this._prettyPrintButtonNavigationItem.enabled=this._textEditor.canBeFormatted();} _executionLineNumberDidChange(event) {this.dispatchEventToListeners(WI.ContentView.Event.SupplementalRepresentedObjectsDidChange);} _numberOfSearchResultsDidChange(event) {this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);}};WI.ScriptDetailsTimelineView=class ScriptDetailsTimelineView extends WI.TimelineView {constructor(timeline,extraArguments) {super(timeline,extraArguments);let columns={name:{},location:{},callCount:{},startTime:{},totalTime:{},selfTime:{},averageTime:{}};columns.name.title=WI.UIString("Name");columns.name.width="30%";columns.name.icon=true;columns.name.disclosure=true;columns.name.locked=true;columns.location.title=WI.UIString("Location");columns.location.icon=true;columns.location.width="15%";columns.callCount.title=WI.UIString("Samples");columns.callCount.width="5%";columns.callCount.aligned="right";columns.startTime.title=WI.UIString("Start Time");columns.startTime.width="10%";columns.startTime.aligned="right";columns.totalTime.title=WI.UIString("Total Time");columns.totalTime.width="10%";columns.totalTime.aligned="right";columns.selfTime.title=WI.UIString("Self Time");columns.selfTime.width="10%";columns.selfTime.aligned="right";columns.averageTime.title=WI.UIString("Average Time");columns.averageTime.width="10%";columns.averageTime.aligned="right";for(var column in columns) columns[column].sortable=true;this._dataGrid=new WI.ScriptTimelineDataGrid(columns);this._dataGrid.sortDelegate=this;this._dataGrid.sortColumnIdentifier="startTime";this._dataGrid.sortOrder=WI.DataGrid.SortOrder.Ascending;this._dataGrid.createSettings("script-timeline-view");this.setupDataGrid(this._dataGrid);this.element.classList.add("script");this.addSubview(this._dataGrid);timeline.addEventListener(WI.Timeline.Event.RecordAdded,this._scriptTimelineRecordAdded,this);timeline.addEventListener(WI.Timeline.Event.Refreshed,this._scriptTimelineRecordRefreshed,this);this._pendingRecords=[];for(let record of timeline.records) this._processRecord(record);} get showsLiveRecordingData(){return false;} closed() {this.representedObject.removeEventListener(WI.Timeline.Event.RecordAdded,this._scriptTimelineRecordAdded,this);this.representedObject.removeEventListener(WI.Timeline.Event.Refreshed,this._scriptTimelineRecordRefreshed,this);this._dataGrid.closed();} get selectionPathComponents() {var dataGridNode=this._dataGrid.selectedNode;if(!dataGridNode) return null;var pathComponents=[];while(dataGridNode&&!dataGridNode.root){if(dataGridNode.hidden) return null;let pathComponent=new WI.TimelineDataGridNodePathComponent(dataGridNode);pathComponent.addEventListener(WI.HierarchicalPathComponent.Event.SiblingWasSelected,this.dataGridNodePathComponentSelected,this);pathComponents.unshift(pathComponent);dataGridNode=dataGridNode.parent;} return pathComponents;} reset() {super.reset();this._dataGrid.reset();this._pendingRecords=[];} dataGridSortComparator(sortColumnIdentifier,sortDirection,node1,node2) {if(sortColumnIdentifier!=="name") return null;let displayName1=node1.displayName();let displayName2=node2.displayName();if(displayName1!==displayName2) return displayName1.extendedLocaleCompare(displayName2)*sortDirection;return node1.subtitle.extendedLocaleCompare(node2.subtitle)*sortDirection;} dataGridNodePathComponentSelected(event) {let dataGridNode=event.data.pathComponent.timelineDataGridNode;dataGridNode.revealAndSelect();} layout() {if(this.startTime!==this._oldStartTime||this.endTime!==this._oldEndTime){let dataGridNode=this._dataGrid.children[0];while(dataGridNode){if(dataGridNode.revealed) dataGridNode.refresh();else dataGridNode.needsRefresh();dataGridNode=dataGridNode.traverseNextNode(false,null,true);} this._oldStartTime=this.startTime;this._oldEndTime=this.endTime;} this._processPendingRecords();} _processPendingRecords() {if(WI.timelineManager.scriptProfilerIsTracking()) return;if(!this._pendingRecords.length) return;for(let scriptTimelineRecord of this._pendingRecords){let rootNodes=[];if(scriptTimelineRecord.profile){rootNodes=scriptTimelineRecord.profile.topDownRootNodes;} let dataGridNode=new WI.ScriptTimelineDataGridNode(scriptTimelineRecord,{graphDataSource:this,});this._dataGrid.addRowInSortOrder(dataGridNode);for(let profileNode of rootNodes){let profileNodeDataGridNode=new WI.ProfileNodeDataGridNode(profileNode,{graphDataSource:this,});this._dataGrid.addRowInSortOrder(profileNodeDataGridNode,dataGridNode);}} this._pendingRecords=[];} _scriptTimelineRecordAdded(event) {let scriptTimelineRecord=event.data.record;this._processRecord(scriptTimelineRecord);this.needsLayout();} _processRecord(scriptTimelineRecord) {this._pendingRecords.push(scriptTimelineRecord);} _scriptTimelineRecordRefreshed(event) {this.needsLayout();}};WI.ScriptDetailsTimelineView.ReferencePage=WI.ReferencePage.TimelinesTab.JavaScriptAndEventsTimeline;WI.ScriptProfileTimelineView=class ScriptProfileTimelineView extends WI.TimelineView {constructor(timeline,extraArguments) {super(timeline,extraArguments);this.element.classList.add("script");this._recording=extraArguments.recording;this._forceNextLayout=false;this._lastLayoutStartTime=undefined;this._lastLayoutEndTime=undefined;this._sharedProfileViewData={selectedNodeHash:null,};if(!WI.ScriptProfileTimelineView.profileOrientationSetting) WI.ScriptProfileTimelineView.profileOrientationSetting=new WI.Setting("script-profile-timeline-view-profile-orientation-setting",WI.ScriptProfileTimelineView.ProfileOrientation.TopDown);if(!WI.ScriptProfileTimelineView.profileTypeSetting) WI.ScriptProfileTimelineView.profileTypeSetting=new WI.Setting("script-profile-timeline-view-profile-type-setting",WI.ScriptProfileTimelineView.ProfileViewType.Hierarchy);this._showProfileViewForOrientation(WI.ScriptProfileTimelineView.profileOrientationSetting.value,WI.ScriptProfileTimelineView.profileTypeSetting.value);let clearTooltip=WI.UIString("Clear focus");this._clearFocusNodesButtonItem=new WI.ButtonNavigationItem("clear-profile-focus",clearTooltip,"Images/Close.svg",16,16);this._clearFocusNodesButtonItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._clearFocusNodes,this);this._updateClearFocusNodesButtonItem();this._profileOrientationButton=new WI.TextToggleButtonNavigationItem("profile-orientation",WI.UIString("Inverted"));this._profileOrientationButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._profileOrientationButtonClicked,this);if(WI.ScriptProfileTimelineView.profileOrientationSetting.value===WI.ScriptProfileTimelineView.ProfileOrientation.TopDown) this._profileOrientationButton.activated=false;else this._profileOrientationButton.activated=true;this._topFunctionsButton=new WI.TextToggleButtonNavigationItem("top-functions",WI.UIString("Top Functions"));this._topFunctionsButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._topFunctionsButtonClicked,this);if(WI.ScriptProfileTimelineView.profileTypeSetting.value===WI.ScriptProfileTimelineView.ProfileViewType.Hierarchy) this._topFunctionsButton.activated=false;else this._topFunctionsButton.activated=true;timeline.addEventListener(WI.Timeline.Event.Refreshed,this._scriptTimelineRecordRefreshed,this);} get scrollableElements(){return this._profileView.scrollableElements;} get showsLiveRecordingData(){return false;} closed() {this.representedObject.removeEventListener(WI.Timeline.Event.Refreshed,this._scriptTimelineRecordRefreshed,this);} get navigationItems() {return[this._clearFocusNodesButtonItem,this._profileOrientationButton,this._topFunctionsButton];} get selectionPathComponents() {return this._profileView.selectionPathComponents;} layout() {if(!this._forceNextLayout&&(this._lastLayoutStartTime===this.startTime&&this._lastLayoutEndTime===this.endTime)) return;this._forceNextLayout=false;this._lastLayoutStartTime=this.startTime;this._lastLayoutEndTime=this.endTime;this._profileView.setStartAndEndTime(this.startTime,this.endTime);} _callingContextTreeForOrientation(profileOrientation,profileViewType) {switch(profileOrientation){case WI.ScriptProfileTimelineView.ProfileOrientation.TopDown:return profileViewType===WI.ScriptProfileTimelineView.ProfileViewType.Hierarchy?this._recording.topDownCallingContextTree:this._recording.topFunctionsTopDownCallingContextTree;case WI.ScriptProfileTimelineView.ProfileOrientation.BottomUp:return profileViewType===WI.ScriptProfileTimelineView.ProfileViewType.Hierarchy?this._recording.bottomUpCallingContextTree:this._recording.topFunctionsBottomUpCallingContextTree;} return this._recording.topDownCallingContextTree;} _profileViewSelectionPathComponentsDidChange(event) {this._updateClearFocusNodesButtonItem();this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);} _scriptTimelineRecordRefreshed(event) {this._forceNextLayout=true;this.needsLayout();} _profileOrientationButtonClicked() {this._profileOrientationButton.activated=!this._profileOrientationButton.activated;let isInverted=this._profileOrientationButton.activated;let newOrientation;if(isInverted) newOrientation=WI.ScriptProfileTimelineView.ProfileOrientation.BottomUp;else newOrientation=WI.ScriptProfileTimelineView.ProfileOrientation.TopDown;WI.ScriptProfileTimelineView.profileOrientationSetting.value=newOrientation;this._showProfileViewForOrientation(newOrientation,WI.ScriptProfileTimelineView.profileTypeSetting.value);this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);this._forceNextLayout=true;this.needsLayout();} _topFunctionsButtonClicked() {this._topFunctionsButton.activated=!this._topFunctionsButton.activated;let isTopFunctionsEnabled=this._topFunctionsButton.activated;let newOrientation;if(isTopFunctionsEnabled) newOrientation=WI.ScriptProfileTimelineView.ProfileViewType.TopFunctions;else newOrientation=WI.ScriptProfileTimelineView.ProfileViewType.Hierarchy;WI.ScriptProfileTimelineView.profileTypeSetting.value=newOrientation;this._showProfileViewForOrientation(WI.ScriptProfileTimelineView.profileOrientationSetting.value,newOrientation);this.dispatchEventToListeners(WI.ContentView.Event.SelectionPathComponentsDidChange);this._forceNextLayout=true;this.needsLayout();} _showProfileViewForOrientation(profileOrientation,profileViewType) {let filterText;if(this._profileView){this._profileView.removeEventListener(WI.ContentView.Event.SelectionPathComponentsDidChange,this._profileViewSelectionPathComponentsDidChange,this);this.removeSubview(this._profileView);filterText=this._profileView.dataGrid.filterText;} let callingContextTree=this._callingContextTreeForOrientation(profileOrientation,profileViewType);this._profileView=new WI.ProfileView(callingContextTree,this._sharedProfileViewData);this._profileView.addEventListener(WI.ContentView.Event.SelectionPathComponentsDidChange,this._profileViewSelectionPathComponentsDidChange,this);this.addSubview(this._profileView);this.setupDataGrid(this._profileView.dataGrid);if(filterText) this._profileView.dataGrid.filterText=filterText;} _updateClearFocusNodesButtonItem() {this._clearFocusNodesButtonItem.enabled=this._profileView.hasFocusNodes();} _clearFocusNodes() {this._profileView.clearFocusNodes();}};WI.ScriptProfileTimelineView.ProfileOrientation={BottomUp:"bottom-up",TopDown:"top-down",};WI.ScriptProfileTimelineView.ProfileViewType={Hierarchy:"hierarchy",TopFunctions:"top-functions",};WI.ScriptProfileTimelineView.ReferencePage=WI.ReferencePage.TimelinesTab.JavaScriptAndEventsTimeline;WI.ScriptTimelineDataGrid=class ScriptTimelineDataGrid extends WI.TimelineDataGrid { callFramePopoverAnchorElement() {return this.selectedNode.elementWithColumnIdentifier("location");} shouldShowCallFramePopover() {return this.isColumnVisible("location");}};WI.ScriptTimelineDataGridNode=class ScriptTimelineDataGridNode extends WI.TimelineDataGridNode {constructor(record,options={}) {super([record],options);} get data() {if(this._cachedData) return this._cachedData;let baseStartTime=0;let rangeStartTime=0;let rangeEndTime=Infinity;if(this.graphDataSource){baseStartTime=this.graphDataSource.zeroTime;rangeStartTime=this.graphDataSource.startTime;rangeEndTime=this.graphDataSource.endTime;} let startTime=this.record.startTime;let duration=this.record.startTime+this.record.duration-startTime;this._cachedData=super.data;this._cachedData.type=this.record.eventType;this._cachedData.name=this.displayName();this._cachedData.startTime=startTime-baseStartTime;this._cachedData.selfTime=duration;this._cachedData.totalTime=duration;this._cachedData.averageTime=duration;this._cachedData.callCount=this.record.callCountOrSamples;this._cachedData.location=this.record.initiatorCallFrame||this.record.sourceCodeLocation;return this._cachedData;} get subtitle() {if(this._subtitle!==undefined) return this._subtitle;this._subtitle="";if(this.record.eventType===WI.ScriptTimelineRecord.EventType.TimerInstalled){let timeoutString=Number.secondsToString(this.record.details.timeout/1000);if(this.record.details.repeating) this._subtitle=WI.UIString("%s interval").format(timeoutString);else this._subtitle=WI.UIString("%s delay").format(timeoutString);}else if(this.record.eventType===WI.ScriptTimelineRecord.EventType.EventDispatched){if(this.record.extraDetails&&this.record.extraDetails.defaultPrevented) this._subtitle=WI.UIString("default prevented");} return this._subtitle;} createCellContent(columnIdentifier,cell) {const higherResolution=true;var value=this.data[columnIdentifier];switch(columnIdentifier){case"name":cell.classList.add(...this.iconClassNames());return this._createNameCellDocumentFragment();case"startTime":case"selfTime":case"totalTime":case"averageTime":return isNaN(value)?emDash:Number.secondsToString(value,higherResolution);case"callCount":return isNaN(value)?emDash:value.toLocaleString();case"width":case"height":case"area":return zeroWidthSpace;case"source": return super.createCellContent("location",cell);} return super.createCellContent(columnIdentifier,cell);} filterableDataForColumn(columnIdentifier) {if(columnIdentifier==="name") return[this.displayName(),this.subtitle];return super.filterableDataForColumn(columnIdentifier);} _createNameCellDocumentFragment(cellElement) {let fragment=document.createDocumentFragment();fragment.append(this.displayName());if(this.subtitle){let subtitleElement=document.createElement("span");subtitleElement.classList.add("subtitle");subtitleElement.textContent=this.subtitle;fragment.append(subtitleElement);} return fragment;}};WI.ScriptTimelineOverviewGraph=class ScriptTimelineOverviewGraph extends WI.TimelineOverviewGraph {constructor(timeline,timelineOverview) {super(timelineOverview);this.element.classList.add("script");this._scriptTimeline=timeline;this._scriptTimeline.addEventListener(WI.Timeline.Event.RecordAdded,this._scriptTimelineRecordAdded,this);this._timelineRecordBars=[];this.reset();} reset() {super.reset();this.element.removeChildren();} layout() {super.layout();if(this.hidden) return;let secondsPerPixel=this.timelineOverview.secondsPerPixel;let recordBarIndex=0;function createBar(records,renderMode) {let timelineRecordBar=this._timelineRecordBars[recordBarIndex];if(!timelineRecordBar) timelineRecordBar=this._timelineRecordBars[recordBarIndex]=new WI.TimelineRecordBar(this,records,renderMode);else{timelineRecordBar.renderMode=renderMode;timelineRecordBar.records=records;} timelineRecordBar.refresh(this);if(!timelineRecordBar.element.parentNode) this.element.appendChild(timelineRecordBar.element);++recordBarIndex;} let[gcRecords,nonGCRecords]=this._scriptTimeline.records.partition((x)=>x.isGarbageCollection());let boundCreateBar=createBar.bind(this);WI.TimelineRecordBar.createCombinedBars(nonGCRecords,secondsPerPixel,this,boundCreateBar);WI.TimelineRecordBar.createCombinedBars(gcRecords,secondsPerPixel,this,boundCreateBar);for(;recordBarIndexcharactersToShowBeforeSearchMatch){modifiedTitle=ellipsis+title.substring(searchTermIndex-charactersToShowBeforeSearchMatch);searchTermIndex=charactersToShowBeforeSearchMatch+1;}else modifiedTitle=title;modifiedTitle=modifiedTitle.truncateEnd(searchTermIndex+searchTermLength+charactersToShowAfterSearchMatch);var highlightedTitle=document.createDocumentFragment();highlightedTitle.append(modifiedTitle.substring(0,searchTermIndex));var highlightSpan=document.createElement("span");highlightSpan.className="highlighted";highlightSpan.append(modifiedTitle.substring(searchTermIndex,searchTermIndex+searchTermLength));highlightedTitle.appendChild(highlightSpan);highlightedTitle.append(modifiedTitle.substring(searchTermIndex+searchTermLength));return highlightedTitle;} get filterableData() {return{text:[this.representedObject.title]};} get synthesizedTextValue() {return this.representedObject.sourceCodeTextRange.synthesizedTextValue+":"+this.representedObject.title;} populateContextMenu(contextMenu,event) {if(this.representedObject instanceof WI.DOMSearchMatchObject){contextMenu.appendItem(WI.UIString("Reveal in Elements Tab"),()=>{WI.showMainFrameDOMTree(this.representedObject.domNode,{ignoreSearchTab:true,initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});}else if(this.representedObject instanceof WI.SourceCodeSearchMatchObject){contextMenu.appendItem(WI.UIString("Reveal in Sources Tab"),()=>{WI.showOriginalOrFormattedSourceCodeTextRange(this.representedObject.sourceCodeTextRange,{ignoreNetworkTab:true,ignoreSearchTab:true,initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});} super.populateContextMenu(contextMenu,event);}};WI.SearchSidebarPanel=class SearchSidebarPanel extends WI.NavigationSidebarPanel {constructor() {super("search",WI.UIString("Search"),true,true);this._searchInputSettings=WI.SearchUtilities.createSettings("search-sidebar");for(let setting of Object.values(this._searchInputSettings)){setting.addEventListener(WI.Setting.Event.Changed,function(event){this.focusSearchField(true);},this);} this._inputContainer=this.element.appendChild(document.createElement("div"));this._inputContainer.classList.add("search-bar");this._inputElement=this._inputContainer.appendChild(document.createElement("input"));this._inputElement.type="search";this._inputElement.spellcheck=false;this._inputElement.addEventListener("change",this._searchFieldChanged.bind(this));this._inputElement.addEventListener("input",this._searchFieldInput.bind(this));this._inputElement.setAttribute("results",5);this._inputElement.setAttribute("autosave","inspector-search-autosave");this._inputElement.setAttribute("placeholder",WI.UIString("Search Resource Content"));this._inputContainer.appendChild(WI.SearchUtilities.createSettingsButton(this._searchInputSettings));this._searchQuerySetting=new WI.Setting("search-sidebar-query","");this._inputElement.value=this._searchQuerySetting.value;WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);const treeItemHeight=20;this.contentTreeOutline.registerScrollVirtualizer(this.contentView.element,treeItemHeight);this.contentTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._treeSelectionDidChange,this);} showDefaultContentView() {let contentView=new WI.ContentView;let contentPlaceholder=WI.createMessageTextView(this._searchQuerySetting.value?WI.UIString("No search results"):WI.UIString("No search string"));contentView.element.appendChild(contentPlaceholder);let searchNavigationItem=new WI.ButtonNavigationItem("search",WI.UIString("Search Resource Content"),"Images/Search.svg",15,15);searchNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleDefaultContentViewSearchNavigationItemClicked,this);let importHelpElement=WI.createNavigationItemHelp(WI.UIString("Press %s to see recent searches."),searchNavigationItem);contentPlaceholder.appendChild(importHelpElement);this.contentBrowser.showContentView(contentView);} closed() {super.closed();WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._mainResourceDidChange,this);} focusSearchField(performSearch) {if(!this.parentSidebar) return;this.parentSidebar.selectedSidebarPanel=this;this.parentSidebar.collapsed=false;this._inputElement.select();if(performSearch) this.performSearch(this._inputElement.value,{omitFocus:true});} performSearch(searchQuery,{omitFocus}={}) {this._inputElement.value=searchQuery;this._searchQuerySetting.value=searchQuery;this.element.classList.remove("changed");if(this._changedBanner) this._changedBanner.remove();if(!searchQuery.length){this._inputContainer.classList.remove("invalid");this.hideEmptyContentPlaceholder();this.showDefaultContentView();return;} let isCaseSensitive=!!this._searchInputSettings.caseSensitive.value;let isRegex=!!this._searchInputSettings.regularExpression.value;let searchRegex=WI.SearchUtilities.searchRegExpForString(searchQuery,{caseSensitive:isCaseSensitive,regularExpression:isRegex,});this._inputContainer.classList.toggle("invalid",!searchRegex);if(!searchRegex) return;this.hideEmptyContentPlaceholder();this.contentTreeOutline.removeChildren();this.contentBrowser.contentViewContainer.closeAllContentViews();let createSearchingPlaceholder=()=>{let searchingPlaceholder=WI.createMessageTextView("");String.format(WI.UIString("Searching %s"),[(new WI.IndeterminateProgressSpinner).element],String.standardFormatters,searchingPlaceholder,(a,b)=>{a.append(b);return a;});this.updateEmptyContentPlaceholder(searchingPlaceholder);};if(!WI.targetsAvailable()&&WI.sharedApp.isWebDebuggable()){createSearchingPlaceholder();WI.whenTargetsAvailable().then(()=>{if(this._searchQuerySetting.value===searchQuery) this.performSearch(searchQuery,{omitFocus});});return;} let target=WI.assumingMainTarget();let promiseCount=0;let countPromise=async(promise,callback)=>{++promiseCount;if(promiseCount===1) createSearchingPlaceholder();let value=await promise;if(callback) callback(value);--promiseCount;if(promiseCount===0){this.updateEmptyContentPlaceholder(WI.UIString("No Search Results"));if(!this.contentTreeOutline.children.length) this.showDefaultContentView();}};function createTreeElementForMatchObject(matchObject,parentTreeElement) {let matchTreeElement=new WI.SearchResultTreeElement(matchObject);matchTreeElement.addEventListener(WI.TreeElement.Event.DoubleClick,this._treeElementDoubleClick,this);parentTreeElement.appendChild(matchTreeElement);if(!this.contentTreeOutline.selectedTreeElement){const selectedByUser=true;matchTreeElement.revealAndSelect(omitFocus??false,selectedByUser);}} function forEachMatch(lineContent,callback) {var lineMatch;while((searchRegex.lastIndex{if(!result||!result.length) return;var frame=WI.networkManager.frameForIdentifier(frameId);if(!frame) return;let resource=frame.url===url?frame.mainResource:frame.resourcesForURL(url).firstValue;if(!resource) return;var resourceTreeElement=this._searchTreeElementForResource(resource);for(var i=0;i{var matchObject=new WI.SourceCodeSearchMatchObject(resource,match.lineContent,searchQuery,new WI.TextRange(match.lineNumber,lineMatch.index,match.lineNumber,lastIndex));createTreeElementForMatchObject.call(this,matchObject,resourceTreeElement);});} if(!resourceTreeElement.children.length) this.contentTreeOutline.removeChild(resourceTreeElement);};let resourcesCallback=({result})=>{let preventDuplicates=new Set;for(let searchResult of result){if(!searchResult.url||!searchResult.frameId) continue; let key=searchResult.frameId+":"+searchResult.url;if(preventDuplicates.has(key)) continue;preventDuplicates.add(key);countPromise(target.PageAgent.searchInResource(searchResult.frameId,searchResult.url,searchQuery,isCaseSensitive,isRegex,searchResult.requestId),resourceCallback.bind(this,searchResult.frameId,searchResult.url));} let promises=[WI.Frame.awaitEvent(WI.Frame.Event.ResourceWasAdded,this),WI.Target.awaitEvent(WI.Target.Event.ResourceAdded,this),];Promise.race(promises).then(this._contentChanged.bind(this));};let scriptCallback=(script,{result})=>{if(!result||!result.length) return;var scriptTreeElement=this._searchTreeElementForScript(script);for(let match of result){forEachMatch(match.lineContent,(lineMatch,lastIndex)=>{var matchObject=new WI.SourceCodeSearchMatchObject(script,match.lineContent,searchQuery,new WI.TextRange(match.lineNumber,lineMatch.index,match.lineNumber,lastIndex));createTreeElementForMatchObject.call(this,matchObject,scriptTreeElement);});} if(!scriptTreeElement.children.length) this.contentTreeOutline.removeChild(scriptTreeElement);};let searchScripts=(scriptsToSearch)=>{if(!scriptsToSearch.length) return;for(let script of scriptsToSearch) countPromise(script.target.DebuggerAgent.searchInContent(script.id,searchQuery,isCaseSensitive,isRegex),scriptCallback.bind(this,script));};let domCallback=({searchId,resultCount})=>{if(!resultCount) return;this._domSearchIdentifier=searchId;let domSearchResults=({nodeIds})=>{if(this._domSearchIdentifier!==searchId) return;for(let nodeId of nodeIds){let domNode=WI.domManager.nodeForId(nodeId);if(!domNode||!domNode.ownerDocument) continue;if(domNode.nodeType()===Node.DOCUMENT_NODE) continue;let resource=WI.networkManager.resourcesForURL(domNode.ownerDocument.documentURL).firstValue;if(!resource) continue;var resourceTreeElement=this._searchTreeElementForResource(resource);var domNodeTitle=WI.DOMSearchMatchObject.titleForDOMNode(domNode);var didFindTextualMatch=false;forEachMatch(domNodeTitle,(lineMatch,lastIndex)=>{var matchObject=new WI.DOMSearchMatchObject(resource,domNode,domNodeTitle,searchQuery,new WI.TextRange(0,lineMatch.index,0,lastIndex));createTreeElementForMatchObject.call(this,matchObject,resourceTreeElement);didFindTextualMatch=true;});if(!didFindTextualMatch){var matchObject=new WI.DOMSearchMatchObject(resource,domNode,domNodeTitle,domNodeTitle,new WI.TextRange(0,0,0,domNodeTitle.length));createTreeElementForMatchObject.call(this,matchObject,resourceTreeElement);} if(!resourceTreeElement.children.length) this.contentTreeOutline.removeChild(resourceTreeElement);}};countPromise(target.DOMAgent.getSearchResults(searchId,0,resultCount),domSearchResults);};WI.domManager.ensureDocument();if(target.hasCommand("Page.searchInResources")) countPromise(target.PageAgent.searchInResources(searchQuery,isCaseSensitive,isRegex),resourcesCallback);setTimeout(searchScripts.bind(this,WI.debuggerManager.searchableScripts),0);if(target.hasDomain("DOM")){if(this._domSearchIdentifier){target.DOMAgent.discardSearchResults(this._domSearchIdentifier);this._domSearchIdentifier=undefined;} let commandArguments={query:searchQuery,caseSensitive:isCaseSensitive,};countPromise(target.DOMAgent.performSearch.invoke(commandArguments),domCallback);} } _searchFieldChanged(event) {this.performSearch(event.target.value);} _searchFieldInput(event) {if(!event.target.value.length) this.performSearch("");} _searchTreeElementForResource(resource) {var resourceTreeElement=this.contentTreeOutline.getCachedTreeElement(resource);if(!resourceTreeElement){resourceTreeElement=new WI.ResourceTreeElement(resource);resourceTreeElement.hasChildren=true;resourceTreeElement.expand();this.contentTreeOutline.appendChild(resourceTreeElement);} return resourceTreeElement;} _searchTreeElementForScript(script) {var scriptTreeElement=this.contentTreeOutline.getCachedTreeElement(script);if(!scriptTreeElement){scriptTreeElement=new WI.ScriptTreeElement(script);scriptTreeElement.hasChildren=true;scriptTreeElement.expand();this.contentTreeOutline.appendChild(scriptTreeElement);} return scriptTreeElement;} _mainResourceDidChange(event) {if(!event.target.isMainFrame()) return;if(this._delayedSearchTimeout){clearTimeout(this._delayedSearchTimeout);this._delayedSearchTimeout=undefined;} this.contentTreeOutline.removeChildren();this.contentBrowser.contentViewContainer.closeAllContentViews();if(this.visible){const performSearch=true;this.focusSearchField(performSearch);}} _treeSelectionDidChange(event) {if(!this.selected) return;let treeElement=this.contentTreeOutline.selectedTreeElement;if(!treeElement||treeElement instanceof WI.FolderTreeElement) return;const options={ignoreNetworkTab:true,};if(treeElement instanceof WI.ResourceTreeElement||treeElement instanceof WI.ScriptTreeElement){const cookie=null;WI.showRepresentedObject(treeElement.representedObject,cookie,options);return;} if(!(treeElement instanceof WI.SearchResultTreeElement)) return;if(treeElement.representedObject instanceof WI.DOMSearchMatchObject) WI.showMainFrameDOMTree(treeElement.representedObject.domNode);else if(treeElement.representedObject instanceof WI.SourceCodeSearchMatchObject) WI.showOriginalOrFormattedSourceCodeTextRange(treeElement.representedObject.sourceCodeTextRange,options);} _treeElementDoubleClick(event) {let treeElement=event.target;if(!treeElement) return;if(treeElement.representedObject instanceof WI.DOMSearchMatchObject){WI.showMainFrameDOMTree(treeElement.representedObject.domNode,{ignoreSearchTab:true,});}else if(treeElement.representedObject instanceof WI.SourceCodeSearchMatchObject){WI.showOriginalOrFormattedSourceCodeTextRange(treeElement.representedObject.sourceCodeTextRange,{ignoreNetworkTab:true,ignoreSearchTab:true,});}} _contentChanged(event) {this.element.classList.add("changed");if(!this._changedBanner){this._changedBanner=document.createElement("div");this._changedBanner.classList.add("banner");this._changedBanner.append(WI.UIString("The page\u2019s content has changed"),document.createElement("br"));let performSearchLink=this._changedBanner.appendChild(document.createElement("a"));performSearchLink.textContent=WI.UIString("Search Again");performSearchLink.addEventListener("click",()=>{const performSearch=true;this.focusSearchField(performSearch);});} this.element.appendChild(this._changedBanner);} _handleDefaultContentViewSearchNavigationItemClicked(event) {this.focusSearchField();}};WI.ShaderProgramContentView=class ShaderProgramContentView extends WI.ContentView {constructor(shaderProgram) {super(shaderProgram);let isWebGPU=this.representedObject.canvas.contextType===WI.Canvas.ContextType.WebGPU;let sharesVertexFragmentShader=isWebGPU&&this.representedObject.sharesVertexFragmentShader;this._refreshButtonNavigationItem=new WI.ButtonNavigationItem("refresh",WI.UIString("Refresh"),"Images/ReloadFull.svg",13,13);this._refreshButtonNavigationItem.visibilityPriority=WI.NavigationItem.VisibilityPriority.Low;this._refreshButtonNavigationItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._refreshContent,this);let contentDidChangeDebouncer=new Debouncer((event)=>{this._contentDidChange(event);});this.element.classList.add("shader-program",this.representedObject.programType);let createEditor=(shaderType)=>{let container=this.element.appendChild(document.createElement("div"));let header=container.appendChild(document.createElement("header"));let shaderTypeContainer=header.appendChild(document.createElement("div"));shaderTypeContainer.classList.add("shader-type");let textEditor=new WI.TextEditor;textEditor.readOnly=false;textEditor.addEventListener(WI.TextEditor.Event.Focused,this._editorFocused,this);textEditor.addEventListener(WI.TextEditor.Event.NumberOfSearchResultsDidChange,this._numberOfSearchResultsDidChange,this);textEditor.addEventListener(WI.TextEditor.Event.ContentDidChange,function(event){contentDidChangeDebouncer.delayForTime(250,event);},textEditor);switch(shaderType){case WI.ShaderProgram.ShaderType.Compute:shaderTypeContainer.textContent=WI.UIString("Compute Shader");textEditor.mimeType=isWebGPU?"x-pipeline/x-compute":"x-shader/x-compute";break;case WI.ShaderProgram.ShaderType.Fragment:shaderTypeContainer.textContent=WI.UIString("Fragment Shader");textEditor.mimeType=isWebGPU?"x-pipeline/x-render":"x-shader/x-fragment";break;case WI.ShaderProgram.ShaderType.Vertex:if(sharesVertexFragmentShader) shaderTypeContainer.textContent=WI.UIString("Vertex/Fragment Shader");else shaderTypeContainer.textContent=WI.UIString("Vertex Shader");textEditor.mimeType=isWebGPU?"x-pipeline/x-render":"x-shader/x-vertex";break;} this.addSubview(textEditor);container.appendChild(textEditor.element);container.classList.add("shader",shaderType);container.classList.toggle("shares-vertex-fragment-shader",sharesVertexFragmentShader);return textEditor;};switch(this.representedObject.programType){case WI.ShaderProgram.ProgramType.Compute:{this._computeEditor=createEditor(WI.ShaderProgram.ShaderType.Compute);this._lastActiveEditor=this._computeEditor;break;} case WI.ShaderProgram.ProgramType.Render:{this._vertexEditor=createEditor(WI.ShaderProgram.ShaderType.Vertex);if(!sharesVertexFragmentShader){this._fragmentEditor=createEditor(WI.ShaderProgram.ShaderType.Fragment);} this._lastActiveEditor=this._vertexEditor;break;}} if(WI.FileUtilities.canSave(WI.FileUtilities.SaveMode.FileVariants)) this._saveMode=WI.FileUtilities.SaveMode.FileVariants;else if(WI.FileUtilities.canSave(WI.FileUtilities.SaveMode.SingleFile)) this._saveMode=WI.FileUtilities.SaveMode.SingleFile;else this._saveMode=null;} get navigationItems() {return[this._refreshButtonNavigationItem];} attached() {super.attached();this._refreshContent();} get supportsSave() {return!!this._saveMode;} get saveMode() {return this._saveMode;} get saveData() {let data=[];let addDataForEditor=(editor)=>{if(!editor||(editor!==this._lastActiveEditor&&this._saveMode===WI.FileUtilities.SaveMode.SingleFile)) return;let filename="";let displayType="";switch(editor){case this._computeEditor:filename=WI.UIString("Compute");displayType=WI.UIString("Compute Shader");break;case this._fragmentEditor:filename=WI.UIString("Fragment");displayType=WI.UIString("Fragment Shader");break;case this._vertexEditor:filename=WI.UIString("Vertex");displayType=WI.UIString("Vertex Shader");break;} let extension="";switch(this.representedObject.canvas.contextType){case WI.Canvas.ContextType.WebGL:case WI.Canvas.ContextType.OffscreenWebGL:case WI.Canvas.ContextType.WebGL2:case WI.Canvas.ContextType.OffscreenWebGL2:extension=WI.unlocalizedString(".glsl");break;case WI.Canvas.ContextType.WebGPU:extension=WI.unlocalizedString(".wsl");break;} data.push({displayType,content:editor.string,suggestedName:filename+extension,forceSaveAs:true,});};addDataForEditor(this._computeEditor);addDataForEditor(this._fragmentEditor);addDataForEditor(this._vertexEditor);return data;} get supportsSearch() {return true;} get numberOfSearchResults() {return this._lastActiveEditor.numberOfSearchResults;} get hasPerformedSearch() {return this._lastActiveEditor.currentSearchQuery!==null;} set automaticallyRevealFirstSearchResult(reveal) {this._lastActiveEditor.automaticallyRevealFirstSearchResult=reveal;} performSearch(query) {this._lastActiveEditor.performSearch(query);} searchCleared() {this._lastActiveEditor.searchCleared();} searchQueryWithSelection() {return this._lastActiveEditor.searchQueryWithSelection();} revealPreviousSearchResult(changeFocus) {this._lastActiveEditor.revealPreviousSearchResult(changeFocus);} revealNextSearchResult(changeFocus) {this._lastActiveEditor.revealNextSearchResult(changeFocus);} revealPosition(position,options={}) {this._lastActiveEditor.revealPosition(position,options);} _refreshContent() {let spinnerContainer=null;if(!this.didInitialLayout){spinnerContainer=this.element.appendChild(document.createElement("div"));spinnerContainer.className="spinner-container";spinnerContainer.appendChild((new WI.IndeterminateProgressSpinner).element);this._contentErrorMessageElement?.remove();} let createCallback=(textEditor)=>{return(source)=>{spinnerContainer?.remove();if(source===null){if(!this._contentErrorMessageElement){const isError=true;this._contentErrorMessageElement=WI.createMessageTextView(WI.UIString("An error occurred trying to load the resource."),isError);} if(!this._contentErrorMessageElement.parentNode) this.element.appendChild(this._contentErrorMessageElement);return;} textEditor.string=source||"";};};switch(this.representedObject.programType){case WI.ShaderProgram.ProgramType.Compute:this.representedObject.requestShaderSource(WI.ShaderProgram.ShaderType.Compute,createCallback(this._computeEditor));return;case WI.ShaderProgram.ProgramType.Render:this.representedObject.requestShaderSource(WI.ShaderProgram.ShaderType.Vertex,createCallback(this._vertexEditor));if(!this.representedObject.sharesVertexFragmentShader) this.representedObject.requestShaderSource(WI.ShaderProgram.ShaderType.Fragment,createCallback(this._fragmentEditor));return;}} _updateShader(shaderType) {switch(shaderType){case WI.ShaderProgram.ShaderType.Compute:this.representedObject.updateShader(shaderType,this._computeEditor.string);return;case WI.ShaderProgram.ShaderType.Fragment:this.representedObject.updateShader(shaderType,this._fragmentEditor.string);return;case WI.ShaderProgram.ShaderType.Vertex:this.representedObject.updateShader(shaderType,this._vertexEditor.string);return;}} _editorFocused(event) {if(this._lastActiveEditor===event.target) return;let currentSearchQuery=null;if(this._lastActiveEditor){currentSearchQuery=this._lastActiveEditor.currentSearchQuery;this._lastActiveEditor.searchCleared();} this._lastActiveEditor=event.target;if(currentSearchQuery) this._lastActiveEditor.performSearch(currentSearchQuery);} _numberOfSearchResultsDidChange(event) {this.dispatchEventToListeners(WI.ContentView.Event.NumberOfSearchResultsDidChange);} _contentDidChange(event) {switch(event.target){case this._computeEditor:this._updateShader(WI.ShaderProgram.ShaderType.Compute);return;case this._fragmentEditor:this._updateShader(WI.ShaderProgram.ShaderType.Fragment);return;case this._vertexEditor:this._updateShader(WI.ShaderProgram.ShaderType.Vertex);return;}}};WI.ShaderProgramTreeElement=class ShaderProgramTreeElement extends WI.GeneralTreeElement {constructor(shaderProgram) {const subtitle=null;super("shader-program",shaderProgram.displayName,subtitle,shaderProgram);if(this.representedObject.canvas.isWebGL||this.representedObject.canvas.isWebGL2){this._disabledImageElement=document.createElement("img");this._disabledImageElement.title=WI.UIString("Disable Program");this._disabledImageElement.addEventListener("click",this._disabledImageElementClicked.bind(this));this.status=this._disabledImageElement;}} onattach() {super.onattach();if(this.representedObject.canvas.isWebGL||this.representedObject.canvas.isWebGL2){this.representedObject.addEventListener(WI.ShaderProgram.Event.DisabledChanged,this._handleShaderProgramDisabledChanged,this);this.element.addEventListener("mouseover",this._handleMouseOver.bind(this));this.element.addEventListener("mouseout",this._handleMouseOut.bind(this));}} ondetach() {if(this.representedObject.canvas.isWebGL||this.representedObject.canvas.isWebGL2) this.representedObject.removeEventListener(WI.ShaderProgram.Event.DisabledChanged,this._handleShaderProgramDisabledChanged,this);super.ondetach();} canSelectOnMouseDown(event) {if(this._disabledImageElement&&this._disabledImageElement.contains(event.target)) return false;return super.canSelectOnMouseDown(event);} populateContextMenu(contextMenu,event) {if(this.representedObject.canvas.isWebGL||this.representedObject.canvas.isWebGL2){let disabled=this.representedObject.disabled;contextMenu.appendItem(disabled?WI.UIString("Enable Program"):WI.UIString("Disable Program"),()=>{this.representedObject.disabled=!disabled;});contextMenu.appendSeparator();} super.populateContextMenu(contextMenu,event);} _disabledImageElementClicked(event) {this.representedObject.disabled=!this.representedObject.disabled;} _handleShaderProgramDisabledChanged(event) {this._listItemNode.classList.toggle("disabled",!!this.representedObject.disabled);this._disabledImageElement.title=this.representedObject.disabled?WI.UIString("Enable Program"):WI.UIString("Disable Program");} _handleMouseOver(event) {this.representedObject.showHighlight();} _handleMouseOut(event) {this.representedObject.hideHighlight();}};WI.SingleSidebar=class SingleSidebar extends WI.Sidebar {constructor(element,side,label,supportsMultiplePanels) {super(element,side,label);this.element.classList.add("single-sidebar");this._allowResizingToCollapse=true;if(supportsMultiplePanels){this.element.classList.add("has-navigation-bar");const navigationBarElement=null;this._navigationBar=new WI.NavigationBar(navigationBarElement,{role:"tablist"});this._navigationBar.addEventListener(WI.NavigationBar.Event.NavigationItemSelected,this._handleNavigationItemSelected,this);this.addSubview(this._navigationBar);} this._widthResizer=new WI.Resizer(WI.Resizer.RuleOrientation.Vertical,this);this.element.insertBefore(this._widthResizer.element,this.element.firstChild);} get allowResizingToCollapse(){return this._allowResizingToCollapse;} set allowResizingToCollapse(allow){this._allowResizingToCollapse=!!allow;} get minimumWidth() {let minimumWidth=super.minimumWidth;if(this._navigationBar) minimumWidth=Math.max(minimumWidth,this._navigationBar.minimumWidth);return minimumWidth;} get width() {return this.element.offsetWidth;} set width(newWidth) {if(newWidth===this.width) return;this._recalculateWidth(newWidth);} shouldInsertSidebarPanel(sidebarPanel,index) {return!sidebarPanel.parentSidebar||sidebarPanel.parentSidebar===this;} didInsertSidebarPanel(sidebarPanel,index) {if(!this._navigationBar) return;this._navigationBar.insertNavigationItem(sidebarPanel.navigationItem,index);if(this.collapsed) return;this._recalculateWidth();} didRemoveSidebarPanel(sidebarPanel) {if(!this._navigationBar) return;this._navigationBar.removeNavigationItem(sidebarPanel.navigationItem);if(this.collapsed) return;this._recalculateWidth();} willSetSelectedSidebarPanel(sidebarPanel) {if(this.selectedSidebarPanel){this.removeSubview(this.selectedSidebarPanel);this.selectedSidebarPanel.selected=false;}} didSetSelectedSidebarPanel(sidebarPanel) {if(this.selectedSidebarPanel){this.selectedSidebarPanel.selected=true;this.addSubview(this.selectedSidebarPanel);} if(this._navigationBar) this._navigationBar.selectedNavigationItem=this.selectedSidebarPanel?.navigationItem??null;} didSetCollapsed() {if(this.selectedSidebarPanel){if(this.collapsed){if(this.selectedSidebarPanel.isAttached) this.removeSubview(this.selectedSidebarPanel);}else{if(!this.selectedSidebarPanel.isAttached) this.addSubview(this.selectedSidebarPanel);}} if(!this.collapsed&&this._navigationBar) this._navigationBar.needsLayout();} resizerDragStarted(resizer) {super.resizerDragStarted(resizer);if(resizer!==this._widthResizer) return;this._widthBeforeResize=this.width;} resizerDragging(resizer,positionDelta) {super.resizerDragging(resizer);if(resizer!==this._widthResizer) return;if(this._side===WI.Sidebar.Sides.Leading) positionDelta*=-1;if(WI.resolvedLayoutDirection()===WI.LayoutDirection.RTL) positionDelta*=-1;let newWidth=positionDelta+this._widthBeforeResize;this.width=newWidth;if(this.collapsable&&this._allowResizingToCollapse) this.collapsed=newWidth<(this.minimumWidth/2);} resizerDragEnded(resizer) {super.resizerDragEnded(resizer);if(resizer!==this._widthResizer||this._widthBeforeResize===this.width) return;if(!this.collapsed&&this._navigationBar) this._navigationBar.sizeDidChange();if(!this.collapsed&&this._selectedSidebarPanel) this._selectedSidebarPanel.sizeDidChange();} _recalculateWidth(newWidth=this.width) {newWidth=Math.ceil(Number.constrain(newWidth,this.minimumWidth+1,this.maximumWidth));this.element.style.width=`${newWidth}px`;this.element.style.minWidth=`${this.minimumWidth}px`;if(this.collapsed) return;if(this._navigationBar) this._navigationBar.needsLayout(WI.View.LayoutReason.Resize);if(this.selectedSidebarPanel) this.selectedSidebarPanel.needsLayout(WI.View.LayoutReason.Resize);this.dispatchEventToListeners(WI.Sidebar.Event.WidthDidChange,{newWidth});} _handleNavigationItemSelected(event) {this.selectedSidebarPanel=event.target.selectedNavigationItem?.identifier??null;}};WI.Slider=class Slider extends WI.Object {constructor() {super();this._element=document.createElement("div");this._element.className="slider";this._element.tabIndex=0;this._knob=this._element.appendChild(document.createElement("img"));this._value=0;this._knobY=0;this._maxY=0;this._element.addEventListener("mousedown",this);this._element.addEventListener("keydown",this._handleKeyDown.bind(this));} get element() {return this._element;} get value() {return this._value;} set value(value) {value=Math.max(Math.min(value,1),0);if(value===this._value){this.recalculateKnobY();return;} this.knobY=value;if(this.delegate&&typeof this.delegate.sliderValueDidChange==="function") this.delegate.sliderValueDidChange(this,value);} set knobY(value) {this._value=value;this._knobY=Math.round((1-value)*this.maxY);this._knob.style.setProperty("--translate-y",`${this._knobY}px`);} get maxY() {if(this._maxY<=0&&document.body.contains(this._element)) this._maxY=Math.max(this._element.offsetHeight-Math.ceil(WI.Slider.KnobWidth/2),0);return this._maxY;} recalculateKnobY() {this._maxY=0;this.knobY=this._value;} handleEvent(event) {switch(event.type){case"mousedown":this._handleMousedown(event);break;case"mousemove":this._handleMousemove(event);break;case"mouseup":this._handleMouseup(event);break;}} _handleMousedown(event) {if(event.button!==0||event.ctrlKey) return;if(event.target!==this._knob) this.value=1-((this._localPointForEvent(event).y-3)/this.maxY);this._startKnobY=this._knobY;this._startMouseY=this._localPointForEvent(event).y;this._element.classList.add("dragging");window.addEventListener("mousemove",this,true);window.addEventListener("mouseup",this,true);this._element.focus();} _handleMousemove(event) {let dy=this._localPointForEvent(event).y-this._startMouseY;let y=Math.max(Math.min(this._startKnobY+dy,this.maxY),0);this.value=1-(y/this.maxY);} _handleMouseup(event) {this._element.classList.remove("dragging");window.removeEventListener("mousemove",this,true);window.removeEventListener("mouseup",this,true);} _handleKeyDown(event) {let y=0;let step=event.shiftKey?0.1:0.01;switch(event.keyIdentifier){case"Down":y-=step;break;case"Up":y+=step;break;} if(y){event.preventDefault();this.value+=y;}} _localPointForEvent(event) { let rect=this._element.getBoundingClientRect();return{x:event.pageX-rect.x,y:event.pageY-rect.y,};}};WI.Slider.KnobWidth=13;WI.SoftContextMenu=class SoftContextMenu {constructor(items,parentMenu) {this._items=items;this._parentMenu=parentMenu;} show(event) {const isSubMenu=!!this._parentMenu;this._contextMenuElement=document.createElement("div");this._contextMenuElement.className="soft-context-menu";this._contextMenuElement.style.left=event.pageX+"px";this._contextMenuElement.style.top=event.pageY+"px";this._contextMenuElement.tabIndex=0;this._contextMenuElement.addEventListener("keydown",this._menuKeyDown.bind(this),false);for(let item of this._items) this._contextMenuElement.appendChild(this._createMenuItem(item));if(!isSubMenu){this._glassPaneElement=document.createElement("div");this._glassPaneElement.className="soft-context-menu-glass-pane";this._glassPaneElement.addEventListener("mousedown",this._glassPaneMouseDown.bind(this),false);this._glassPaneElement.appendChild(this._contextMenuElement);document.body.appendChild(this._glassPaneElement);this._focus();this._consumeEvent(event,true);}else this._parentGlassPaneElement().appendChild(this._contextMenuElement);this._repositionMenuOnScreen(isSubMenu);} _consumeEvent(event,preventDefault) {event.stopImmediatePropagation();if(preventDefault) event.preventDefault();event.handled=true;} _parentGlassPaneElement() {if(!this._parentMenu) return null;if(this._parentMenu._glassPaneElement) return this._parentMenu._glassPaneElement;return this._parentMenu._parentGlassPaneElement();} _createMenuItem(item) {if(item.type==="separator") return this._createSeparator();const checkmark="\u2713";const blackRightPointingTriangle="\u25b6";const menuItemElement=document.createElement("div");menuItemElement.className="item";if(!item.enabled) menuItemElement.classList.add("disabled");const checkMarkElement=document.createElement("span");checkMarkElement.textContent=item.checked?checkmark:"";checkMarkElement.className="checkmark";menuItemElement.appendChild(checkMarkElement);const labelElement=document.createElement("span");labelElement.textContent=item.label;labelElement.className="label";menuItemElement.appendChild(labelElement);if(item.type==="subMenu"){const subMenuArrowElement=document.createElement("span");subMenuArrowElement.textContent=blackRightPointingTriangle;subMenuArrowElement.className="submenu-arrow";menuItemElement.appendChild(subMenuArrowElement);menuItemElement._subItems=item.subItems;}else menuItemElement._actionId=item.id;menuItemElement.addEventListener("contextmenu",this._menuItemContextMenu.bind(this),false);menuItemElement.addEventListener("mousedown",this._menuItemMouseDown.bind(this),false);menuItemElement.addEventListener("mouseup",this._menuItemMouseUp.bind(this),false);menuItemElement.addEventListener("mouseover",this._menuItemMouseOver.bind(this),false);menuItemElement.addEventListener("mouseout",this._menuItemMouseOut.bind(this),false);return menuItemElement;} _createSeparator() {const separatorElement=document.createElement("div");separatorElement.className="separator";separatorElement._isSeparator=true;separatorElement.createChild("div","line");separatorElement.addEventListener("contextmenu",this._menuItemContextMenu.bind(this),false);separatorElement.addEventListener("mousedown",this._menuItemMouseDown.bind(this),false);separatorElement.addEventListener("mouseup",this._menuItemMouseUp.bind(this),false);separatorElement.addEventListener("mouseover",this._menuItemMouseOver.bind(this),false);return separatorElement;} _repositionMenuOnScreen(isSubMenu) {if(this._contextMenuElement.offsetLeft+this._contextMenuElement.offsetWidth>document.body.offsetWidth){if(isSubMenu){const parentContextMenuElement=this._parentMenu._contextMenuElement;const leftOfParent=parentContextMenuElement.offsetLeft-this._contextMenuElement.offsetWidth+2;const fromParentRight=this._contextMenuElement.offsetLeft-this._contextMenuElement.offsetWidth+2;this._contextMenuElement.style.left=(leftOfParent>=0?leftOfParent:fromParentRight)+"px";}else{const leftOfCursor=this._contextMenuElement.offsetLeft-this._contextMenuElement.offsetWidth;const fromRightEdge=document.body.offsetWidth-this._contextMenuElement.offsetWidth;this._contextMenuElement.style.left=(leftOfCursor>=0?leftOfCursor:fromRightEdge)+"px";}} if(this._contextMenuElement.offsetTop+this._contextMenuElement.offsetHeight>document.body.offsetHeight){const aboveCursor=this._contextMenuElement.offsetTop-this._contextMenuElement.offsetHeight;const fromBottomEdge=document.body.offsetHeight-this._contextMenuElement.offsetHeight;this._contextMenuElement.style.top=(!isSubMenu&&aboveCursor>=0?aboveCursor:fromBottomEdge)+"px";}} _showSubMenu(menuItemElement) {if(menuItemElement._subMenuTimer){clearTimeout(menuItemElement._subMenuTimer);menuItemElement._subMenuTimer=0;} if(this._subMenu) return;this._subMenu=new WI.SoftContextMenu(menuItemElement._subItems,this);this._subMenu.show({pageX:this._contextMenuElement.offsetLeft+menuItemElement.offsetWidth,pageY:this._contextMenuElement.offsetTop+menuItemElement.offsetTop-4});} _hideSubMenu() {if(!this._subMenu) return;this._subMenu._discardSubMenus();this._focus();} _menuItemContextMenu(event) {this._consumeEvent(event,true);} _menuItemMouseDown(event) {this._consumeEvent(event,true);} _menuItemMouseUp(event) {this._triggerAction(event.target,event);this._consumeEvent(event);} _menuItemMouseOver(event) {this._highlightMenuItem(event.target._isSeparator?null:event.target);} _menuItemMouseOut(event) {const shouldUnhighlight=!this._subMenu||!event.relatedTarget||this._contextMenuElement.contains(event.relatedTarget)||event.relatedTarget.classList.contains("soft-context-menu-glass-pane");if(shouldUnhighlight) this._highlightMenuItem(null);} _menuKeyDown(event) {switch(event.keyIdentifier){case"Up":this._highlightPrevious();break;case"Down":this._highlightNext();break;case"Left":if(this._parentMenu){this._highlightMenuItem(null);this._parentMenu._hideSubMenu();} break;case"Enter":if(!isEnterKey(event)) break; case"U+0020": if(this._highlightedMenuItemElement&&!this._highlightedMenuItemElement._subItems) this._triggerAction(this._highlightedMenuItemElement,event); case"Right":if(this._highlightedMenuItemElement&&this._highlightedMenuItemElement._subItems){this._showSubMenu(this._highlightedMenuItemElement);this._subMenu._focus();this._subMenu._highlightNext();} break;case"U+001B": this._discardMenu(true,event);break;} this._consumeEvent(event,true);} _glassPaneMouseDown(event) {this._discardMenu(true,event);this._consumeEvent(event);} _focus() {this._contextMenuElement.focus();} _triggerAction(menuItemElement,event) {if(!menuItemElement._subItems){this._discardMenu(true,event);if(typeof menuItemElement._actionId==="number"){WI.ContextMenu.contextMenuItemSelected(menuItemElement._actionId);menuItemElement._actionId=null;} return;} this._showSubMenu(menuItemElement);this._consumeEvent(event);} _highlightMenuItem(menuItemElement,skipSubMenuExpansion) {if(this._highlightedMenuItemElement===menuItemElement) return;this._hideSubMenu();if(this._highlightedMenuItemElement){this._highlightedMenuItemElement.classList.remove("highlighted");if(this._highlightedMenuItemElement._subItems&&this._highlightedMenuItemElement._subMenuTimer){clearTimeout(this._highlightedMenuItemElement._subMenuTimer);this._highlightedMenuItemElement._subMenuTimer=0;}} this._highlightedMenuItemElement=menuItemElement;if(this._highlightedMenuItemElement){this._highlightedMenuItemElement.classList.add("highlighted");this._contextMenuElement.focus();if(!skipSubMenuExpansion&&this._highlightedMenuItemElement._subItems&&!this._highlightedMenuItemElement._subMenuTimer) this._highlightedMenuItemElement._subMenuTimer=setTimeout(this._showSubMenu.bind(this,this._highlightedMenuItemElement),150);}} _highlightPrevious() {let menuItemElement=this._highlightedMenuItemElement?this._highlightedMenuItemElement.previousSibling:this._contextMenuElement.lastChild;while(menuItemElement&&menuItemElement._isSeparator) menuItemElement=menuItemElement.previousSibling;if(menuItemElement) this._highlightMenuItem(menuItemElement,true);} _highlightNext() {let menuItemElement=this._highlightedMenuItemElement?this._highlightedMenuItemElement.nextSibling:this._contextMenuElement.firstChild;while(menuItemElement&&menuItemElement._isSeparator) menuItemElement=menuItemElement.nextSibling;if(menuItemElement) this._highlightMenuItem(menuItemElement,true);} _discardMenu(closeParentMenus,event) {if(this._subMenu&&!closeParentMenus) return;if(this._glassPaneElement){const glassPane=this._glassPaneElement;this._glassPaneElement=null;document.body.removeChild(glassPane);if(this._parentMenu){this._parentMenu._subMenu=null;if(closeParentMenus) this._parentMenu._discardMenu(closeParentMenus,event);} if(event) this._consumeEvent(event,true);}else if(this._parentMenu&&this._contextMenuElement.parentElement){this._discardSubMenus();if(closeParentMenus) this._parentMenu._discardMenu(closeParentMenus,event);if(event) this._consumeEvent(event,true);}} _discardSubMenus() {if(this._subMenu) this._subMenu._discardSubMenus();if(this._contextMenuElement.parentElement) this._contextMenuElement.parentElement.removeChild(this._contextMenuElement);if(this._parentMenu) this._parentMenu._subMenu=null;}};WI.SourceCodeTextEditor=class SourceCodeTextEditor extends WI.TextEditor {constructor(sourceCode) {super();this.delegate=this;this._sourceCode=sourceCode;this._breakpointMap={};this._inlineBreakpointDataForLine=new Multimap;this._issuesLineNumberMap=new Map;this._widgetMap=new Map;this._contentPopulated=false;this._invalidLineNumbers={0:true};this._requestingScriptContent=false;this._activeCallFrameSourceCodeLocation=null;this._threadLineNumberMap=new Map;this._threadWidgetMap=new Map; this._threadTargetMap=new Map; this._typeTokenScrollHandler=null;this._typeTokenAnnotator=null;this._basicBlockAnnotator=null;this._editingController=null;this._autoFormat=false;this._isProbablyMinified=false;this._ignoreContentDidChange=0;this._ignoreLocationUpdateBreakpoint=null;this._ignoreBreakpointAddedBreakpoint=null;this._ignoreBreakpointRemovedBreakpoint=null;this._ignoreAllBreakpointLocationUpdates=false;this._updateTokenTrackingControllerState();this.element.classList.add("source-code");if(this._supportsDebugging){WI.JavaScriptBreakpoint.addEventListener(WI.Breakpoint.Event.DisabledStateDidChange,this._breakpointStatusDidChange,this);WI.JavaScriptBreakpoint.addEventListener(WI.Breakpoint.Event.AutoContinueDidChange,this._breakpointStatusDidChange,this);WI.JavaScriptBreakpoint.addEventListener(WI.JavaScriptBreakpoint.Event.ResolvedStateDidChange,this._breakpointStatusDidChange,this);WI.JavaScriptBreakpoint.addEventListener(WI.JavaScriptBreakpoint.Event.LocationDidChange,this._updateBreakpointLocation,this);WI.targetManager.addEventListener(WI.TargetManager.Event.TargetAdded,this._targetAdded,this);WI.targetManager.addEventListener(WI.TargetManager.Event.TargetRemoved,this._targetRemoved,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BreakpointsEnabledDidChange,this._breakpointsEnabledDidChange,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BreakpointAdded,this._breakpointAdded,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BreakpointRemoved,this._breakpointRemoved,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.CallFramesDidChange,this._callFramesDidChange,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ActiveCallFrameDidChange,this._activeCallFrameDidChange,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.Paused,this._debuggerDidPause,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.Resumed,this._debuggerDidResume,this);if(WI.debuggerManager.activeCallFrame) this._debuggerDidPause();this._activeCallFrameDidChange();} WI.consoleManager.addEventListener(WI.ConsoleManager.Event.IssueAdded,this._issueWasAdded,this);this._sourceCode.addEventListener(WI.SourceCode.Event.FormatterDidChange,this._handleFormatterDidChange,this);if(this._sourceCode instanceof WI.SourceMapResource||this._sourceCode.sourceMaps.length>0) WI.notifications.addEventListener(WI.Notification.GlobalModifierKeysDidChange,this._updateTokenTrackingControllerState,this);else this._sourceCode.addEventListener(WI.SourceCode.Event.SourceMapAdded,this._sourceCodeSourceMapAdded,this);sourceCode.requestContent().then(this._contentAvailable.bind(this));new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Control,"G",this.showGoToLineDialog.bind(this),this.element);WI.consoleManager.addEventListener(WI.ConsoleManager.Event.Cleared,this._logCleared,this);} get sourceCode() {return this._sourceCode;} get target() {if(this._sourceCode instanceof WI.SourceMapResource){if(this._sourceCode.sourceMap.originalSourceCode instanceof WI.Script) return this._sourceCode.sourceMap.originalSourceCode.target;} if(this._sourceCode instanceof WI.Script) return this._sourceCode.target;return WI.mainTarget;} attached() {super.attached();if(WI.settings.showJavaScriptTypeInformation.value){if(this._typeTokenAnnotator) this._typeTokenAnnotator.resume();if(!this._typeTokenScrollHandler&&this._typeTokenAnnotator) this._enableScrollEventsForTypeTokenAnnotator();}else{if(this._typeTokenAnnotator) this._setTypeTokenAnnotatorEnabledState(false);} if(WI.settings.enableControlFlowProfiler.value){if(this._basicBlockAnnotator) this._basicBlockAnnotator.resume();if(!this._controlFlowScrollHandler&&this._basicBlockAnnotator) this._enableScrollEventsForControlFlowAnnotator();}else{this._basicBlockAnnotatorEnabled=false;}} detached() {this.tokenTrackingController.removeHighlightedRange();this._dismissPopover();this._dismissEditingController(true);if(this._typeTokenAnnotator) this._typeTokenAnnotator.pause();if(this._basicBlockAnnotator) this._basicBlockAnnotator.pause();super.detached();} close() {if(this._supportsDebugging){WI.JavaScriptBreakpoint.removeEventListener(WI.Breakpoint.Event.DisabledStateDidChange,this._breakpointStatusDidChange,this);WI.JavaScriptBreakpoint.removeEventListener(WI.Breakpoint.Event.AutoContinueDidChange,this._breakpointStatusDidChange,this);WI.JavaScriptBreakpoint.removeEventListener(WI.JavaScriptBreakpoint.Event.ResolvedStateDidChange,this._breakpointStatusDidChange,this);WI.JavaScriptBreakpoint.removeEventListener(WI.JavaScriptBreakpoint.Event.LocationDidChange,this._updateBreakpointLocation,this);WI.targetManager.removeEventListener(WI.TargetManager.Event.TargetAdded,this._targetAdded,this);WI.targetManager.removeEventListener(WI.TargetManager.Event.TargetRemoved,this._targetRemoved,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.BreakpointsEnabledDidChange,this._breakpointsEnabledDidChange,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.BreakpointAdded,this._breakpointAdded,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.BreakpointRemoved,this._breakpointRemoved,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.CallFramesDidChange,this._callFramesDidChange,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ActiveCallFrameDidChange,this._activeCallFrameDidChange,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.Paused,this._debuggerDidPause,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.Resumed,this._debuggerDidResume,this);if(this._activeCallFrameSourceCodeLocation){this._activeCallFrameSourceCodeLocation.removeEventListener(WI.SourceCodeLocation.Event.LocationChanged,this._activeCallFrameSourceCodeLocationChanged,this);this._activeCallFrameSourceCodeLocation=null;}} WI.consoleManager.removeEventListener(WI.ConsoleManager.Event.IssueAdded,this._issueWasAdded,this);this._sourceCode.removeEventListener(WI.SourceCode.Event.FormatterDidChange,this._handleFormatterDidChange,this);if(this._sourceCode instanceof WI.SourceMapResource||this._sourceCode.sourceMaps.length>0) WI.notifications.removeEventListener(WI.Notification.GlobalModifierKeysDidChange,this._updateTokenTrackingControllerState,this);else this._sourceCode.removeEventListener(WI.SourceCode.Event.SourceMapAdded,this._sourceCodeSourceMapAdded,this);WI.consoleManager.removeEventListener(WI.ConsoleManager.Event.Cleared,this._logCleared,this);} canBeFormatted() { if(this._sourceCode instanceof WI.SourceMapResource) return false;return super.canBeFormatted();} canShowTypeAnnotations() {return!!this._getAssociatedScript()&&!this.hasModified;} canShowCoverageHints() {return!!this._getAssociatedScript()&&!this.hasModified;} customPerformSearch(query) {let queryRegex=WI.SearchUtilities.searchRegExpForString(query,WI.SearchUtilities.defaultSettings);if(!queryRegex){this.searchCleared();this.dispatchEventToListeners(WI.TextEditor.Event.NumberOfSearchResultsDidChange);return true;} function searchResultCallback(error,matches) {if(this.currentSearchQuery!==query) return;if(error||!matches||!matches.length){this.dispatchEventToListeners(WI.TextEditor.Event.NumberOfSearchResultsDidChange);return;} var searchResults=[];for(var i=0;i0&&lineNumber<=this.lineCount;} dialogWasDismissedWithRepresentedObject(goToLineDialog,lineNumber) {this.revealPosition(new WI.SourceCodePosition(lineNumber-1,0),{textRangeToSelect:new WI.TextRange(lineNumber-1,0,lineNumber,0),preventHighlight:true,});} contentDidChange(replacedRanges,newRanges) {super.contentDidChange(replacedRanges,newRanges);if(this._ignoreContentDidChange>0) return;for(var range of newRanges) this._updateEditableMarkers(range);if(this._basicBlockAnnotator){this._basicBlockAnnotatorEnabled=false;this._basicBlockAnnotator=null;} if(this._typeTokenAnnotator){this._setTypeTokenAnnotatorEnabledState(false);this._typeTokenAnnotator=null;}} toggleTypeAnnotations() {if(!this._typeTokenAnnotator) return Promise.reject(new Error("TypeTokenAnnotator is not initialized."));var newActivatedState=!this._typeTokenAnnotator.isActive();if(newActivatedState&&this._isProbablyMinified&&!this.formatted){return this.updateFormattedState(true).then(()=>{this._setTypeTokenAnnotatorEnabledState(newActivatedState);});} this._setTypeTokenAnnotatorEnabledState(newActivatedState);return Promise.resolve();} toggleUnexecutedCodeHighlights() {if(!this._basicBlockAnnotator) return Promise.reject(new Error("BasicBlockAnnotator is not initialized."));let newActivatedState=!this._basicBlockAnnotator.isActive();if(newActivatedState&&this._isProbablyMinified&&!this.formatted){return this.updateFormattedState(true).then(()=>{this._basicBlockAnnotatorEnabled=newActivatedState;});} this._basicBlockAnnotatorEnabled=newActivatedState;return Promise.resolve();} showPopoverForTypes(typeDescription,bounds,title) {var content=document.createElement("div");content.className="object expandable";var titleElement=document.createElement("div");titleElement.className="title";titleElement.textContent=title;content.appendChild(titleElement);var bodyElement=content.appendChild(document.createElement("div"));bodyElement.className="body";var typeTreeView=new WI.TypeTreeView(typeDescription);bodyElement.appendChild(typeTreeView.element);this._showPopover(content,bounds);} prettyPrint(pretty) { var shouldResumeBasicBlockAnnotator=this._basicBlockAnnotator&&this._basicBlockAnnotator.isActive();if(shouldResumeBasicBlockAnnotator) this._basicBlockAnnotatorEnabled=false;let shouldResumeTypeTokenAnnotator=this._typeTokenAnnotator&&this._typeTokenAnnotator.isActive();if(shouldResumeTypeTokenAnnotator) this._setTypeTokenAnnotatorEnabledState(false);return super.prettyPrint(pretty).then(()=>{if(pretty||!this._isProbablyMinified){if(shouldResumeBasicBlockAnnotator) this._basicBlockAnnotatorEnabled=true;if(shouldResumeTypeTokenAnnotator) this._setTypeTokenAnnotatorEnabledState(true);}else{if(this._basicBlockAnnotator) this._basicBlockAnnotatorEnabled=false;this._setTypeTokenAnnotatorEnabledState(false);}});} _unformattedLineInfoForEditorLineInfo(lineInfo) {if(this.formatterSourceMap) return this.formatterSourceMap.formattedToOriginal(lineInfo.lineNumber,lineInfo.columnNumber);return lineInfo;} _sourceCodeLocationForEditorPosition(position) {var lineInfo={lineNumber:position.line,columnNumber:position.ch};var unformattedLineInfo=this._unformattedLineInfoForEditorLineInfo(lineInfo);return this.sourceCode.createSourceCodeLocation(unformattedLineInfo.lineNumber,unformattedLineInfo.columnNumber);} _editorPositionForSourceCodeLocation(sourceCodeLocation) {if(this._sourceCode instanceof WI.SourceMapResource) return sourceCodeLocation.displayPosition();return sourceCodeLocation.formattedPosition();} _editorLineInfoForSourceCodeLocation(sourceCodeLocation) {let position=this._editorPositionForSourceCodeLocation(sourceCodeLocation);return this._editorLineInfoForEditorPosition(position);} _editorLineInfoForEditorPosition(position) {return{lineNumber:position.lineNumber,columnNumber:position.columnNumber,};} _breakpointForEditorLineInfo(lineInfo) {if(!this._breakpointMap[lineInfo.lineNumber]) return null;return this._breakpointMap[lineInfo.lineNumber][lineInfo.columnNumber];} _addBreakpointWithEditorLineInfo(breakpoint,lineInfo) {if(!this._breakpointMap[lineInfo.lineNumber]){this._addBreakpointWidgetsForLine(lineInfo.lineNumber);this._breakpointMap[lineInfo.lineNumber]={};} this._breakpointMap[lineInfo.lineNumber][lineInfo.columnNumber]=breakpoint;} _removeBreakpointWithEditorLineInfo(breakpoint,lineInfo) {delete this._breakpointMap[lineInfo.lineNumber][lineInfo.columnNumber];if(isEmptyObject(this._breakpointMap[lineInfo.lineNumber])){delete this._breakpointMap[lineInfo.lineNumber];this._removeBreakpointWidgetsForLine(lineInfo.lineNumber);}} _populateWithContent(content) {content=content||"";this._prepareEditorForInitialContent(content);if(this._autoFormat){this._autoFormat=false;this.deferReveal=true;this.string=content;this.deferReveal=false;this.updateFormattedState(true).then(()=>{this._proceedPopulateWithContent(this.string);});return;} this._proceedPopulateWithContent(content);} _proceedPopulateWithContent(content) {this.dispatchEventToListeners(WI.SourceCodeTextEditor.Event.ContentWillPopulate);this.string=content;this._createBasicBlockAnnotator();if(WI.settings.enableControlFlowProfiler.value&&this._basicBlockAnnotator) this._basicBlockAnnotatorEnabled=true;this._createTypeTokenAnnotator();if(WI.settings.showJavaScriptTypeInformation.value) this._setTypeTokenAnnotatorEnabledState(true);this._contentDidPopulate();} _contentDidPopulate() {this._contentPopulated=true;this.dispatchEventToListeners(WI.SourceCodeTextEditor.Event.ContentDidPopulate); this._reinsertAllIssues();this._reinsertAllThreadIndicators();this._updateEditableMarkers();} _prepareEditorForInitialContent(content) {if(this._contentPopulated) return;if(this._sourceCode instanceof WI.Resource) this.mimeType=this._sourceCode.syntheticMIMEType;else if(this._sourceCode instanceof WI.Script) this.mimeType="text/javascript";else if(this._sourceCode instanceof WI.CSSStyleSheet) this.mimeType="text/css";if(this.canBeFormatted()&&isTextLikelyMinified(content)){this._autoFormat=true;this._isProbablyMinified=true;} if(this._supportsDebugging){this._removeBreakpointWidgets();this._breakpointMap={};for(let breakpoint of WI.debuggerManager.breakpointsForSourceCode(this._sourceCode)){var lineInfo=this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation);this._addBreakpointWithEditorLineInfo(breakpoint,lineInfo);this.setBreakpointInfoForLineAndColumn(lineInfo.lineNumber,lineInfo.columnNumber,this._breakpointInfoForBreakpoint(breakpoint));}}} _contentAvailable(parameters) {if(parameters.error) return;if(parameters.message){this._showMessage(parameters.message);return;} var sourceCode=parameters.sourceCode;var content=sourceCode.content;var base64Encoded=parameters.base64Encoded;if(this._fullContentPopulated) return;this._fullContentPopulated=true;this._invalidLineNumbers={}; this.repeatReveal=!!this.string;this._populateWithContent(content);this.repeatReveal=false;} _showMessage(message) {this.element.removeChildren();this.element.appendChild(WI.createMessageTextView(message));} _breakpointStatusDidChange(event) {this._updateBreakpointStatus(event.target);} _breakpointsEnabledDidChange() {for(let breakpoint of WI.debuggerManager.breakpointsForSourceCode(this._sourceCode)) this._updateBreakpointStatus(breakpoint);} _updateBreakpointStatus(breakpoint) {if(!this._contentPopulated) return;if(!this._matchesBreakpoint(breakpoint)) return;var lineInfo=this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation);this.setBreakpointInfoForLineAndColumn(lineInfo.lineNumber,lineInfo.columnNumber,this._breakpointInfoForBreakpoint(breakpoint));} _updateBreakpointLocation(event) {if(!this._contentPopulated) return;var breakpoint=event.target;if(!this._matchesBreakpoint(breakpoint)) return;if(this._ignoreAllBreakpointLocationUpdates) return;if(breakpoint===this._ignoreLocationUpdateBreakpoint) return;var sourceCodeLocation=breakpoint.sourceCodeLocation;if(this._sourceCode instanceof WI.SourceMapResource){if(sourceCodeLocation.displaySourceCode!==this._sourceCode) return;var oldLineInfo={lineNumber:event.data.oldDisplayLineNumber,columnNumber:event.data.oldDisplayColumnNumber};var newLineInfo={lineNumber:sourceCodeLocation.displayLineNumber,columnNumber:sourceCodeLocation.displayColumnNumber};}else{if(sourceCodeLocation.sourceCode!==this._sourceCode) return;var oldLineInfo={lineNumber:event.data.oldFormattedLineNumber,columnNumber:event.data.oldFormattedColumnNumber};var newLineInfo={lineNumber:sourceCodeLocation.formattedLineNumber,columnNumber:sourceCodeLocation.formattedColumnNumber};} var existingBreakpoint=this._breakpointForEditorLineInfo(oldLineInfo);if(!existingBreakpoint) return;this.setBreakpointInfoForLineAndColumn(oldLineInfo.lineNumber,oldLineInfo.columnNumber,null);this.setBreakpointInfoForLineAndColumn(newLineInfo.lineNumber,newLineInfo.columnNumber,this._breakpointInfoForBreakpoint(breakpoint));this._removeBreakpointWithEditorLineInfo(breakpoint,oldLineInfo);this._addBreakpointWithEditorLineInfo(breakpoint,newLineInfo);} _breakpointAdded(event) {if(!this._contentPopulated) return;var breakpoint=event.data.breakpoint;if(!this._matchesBreakpoint(breakpoint)) return;if(breakpoint===this._ignoreBreakpointAddedBreakpoint) return;var lineInfo=this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation);this._addBreakpointWithEditorLineInfo(breakpoint,lineInfo);this.setBreakpointInfoForLineAndColumn(lineInfo.lineNumber,lineInfo.columnNumber,this._breakpointInfoForBreakpoint(breakpoint));} _breakpointRemoved(event) {if(!this._contentPopulated) return;var breakpoint=event.data.breakpoint;if(!this._matchesBreakpoint(breakpoint)) return;if(breakpoint===this._ignoreBreakpointRemovedBreakpoint) return;var lineInfo=this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation);this._removeBreakpointWithEditorLineInfo(breakpoint,lineInfo);this.setBreakpointInfoForLineAndColumn(lineInfo.lineNumber,lineInfo.columnNumber,null);} async _addBreakpointWidgetsForLine(lineNumber) {let startPosition=this.currentPositionToOriginalPosition(new WI.SourceCodePosition(lineNumber,0));let script=this._getAssociatedScript(startPosition);if(!script) return;let limitLocations=this._isProbablyMinified&&!this.formatterSourceMap;let endPosition=this.currentPositionToOriginalPosition(new WI.SourceCodePosition(limitLocations?lineNumber:(lineNumber+1),limitLocations?100:0));let locations=await script.breakpointLocations(startPosition,endPosition);for(let location of locations){let position=this.originalPositionToCurrentPosition(location.position()); if(locations.length===1&&position.lineNumber===lineNumber&&!this.line(lineNumber).slice(0,position.columnNumber).trim().length) continue;let inlineBreakpointWidget=new WI.BreakpointInlineWidget(WI.debuggerManager.breakpointsForSourceCodeLocation(location).firstValue||location);let bookmark=this.setInlineWidget(position,inlineBreakpointWidget.element);this._inlineBreakpointDataForLine.add(lineNumber,{bookmark,widget:inlineBreakpointWidget});}} _removeBreakpointWidgetsForLine(lineNumber) {let inlineData=this._inlineBreakpointDataForLine.take(lineNumber);if(!inlineData) return;for(let{bookmark}of inlineData) bookmark.clear();} _removeBreakpointWidgets() {for(let{bookmark}of this._inlineBreakpointDataForLine.values()) bookmark.clear();this._inlineBreakpointDataForLine.clear();} _targetAdded(event) {if(WI.targets.length===2) this._reinsertAllThreadIndicators();} _targetRemoved(event) {if(WI.targets.length===1){this._reinsertAllThreadIndicators();return;} let target=event.data.target;this._removeThreadIndicatorForTarget(target);} _callFramesDidChange(event) {if(WI.targets.length===1) return;let target=event.data.target;this._removeThreadIndicatorForTarget(target);this._addThreadIndicatorForTarget(target);} _addThreadIndicatorForTarget(target) {let targetData=WI.debuggerManager.dataForTarget(target);let topCallFrame=targetData.stackTrace?.callFrames[0];if(!topCallFrame) return;let sourceCodeLocation=topCallFrame.sourceCodeLocation;if(!sourceCodeLocation) return;if(!this._looselyMatchesSourceCodeLocation(sourceCodeLocation)) return;let lineNumberWithIndicator=sourceCodeLocation.formattedLineNumber;this._threadTargetMap.set(target,lineNumberWithIndicator);let threads=this._threadLineNumberMap.get(lineNumberWithIndicator);if(!threads){threads=[];this._threadLineNumberMap.set(lineNumberWithIndicator,threads);} threads.push(target);let widget=this._threadIndicatorWidgetForLine(target,lineNumberWithIndicator);this._updateThreadIndicatorWidget(widget,threads);this.addStyleClassToLine(lineNumberWithIndicator,"thread-indicator");} _removeThreadIndicatorForTarget(target) {let lineNumberWithIndicator=this._threadTargetMap.take(target);if(lineNumberWithIndicator===undefined) return;let threads=this._threadLineNumberMap.get(lineNumberWithIndicator);threads.remove(target);if(threads.length){let widget=this._threadWidgetMap.get(lineNumberWithIndicator);this._updateThreadIndicatorWidget(widget,threads);return;} this._threadLineNumberMap.delete(lineNumberWithIndicator);let widget=this._threadWidgetMap.take(lineNumberWithIndicator);if(widget) widget.clear();this.removeStyleClassFromLine(lineNumberWithIndicator,"thread-indicator");} _threadIndicatorWidgetForLine(target,lineNumber) {let widget=this._threadWidgetMap.get(lineNumber);if(widget) return widget;widget=this.createWidgetForLine(lineNumber);if(!widget) return null;let widgetElement=widget.widgetElement;widgetElement.classList.add("line-indicator-widget","thread-widget","inline");widgetElement.addEventListener("click",this._handleThreadIndicatorWidgetClick.bind(this,widget,lineNumber));this._threadWidgetMap.set(lineNumber,widget);return widget;} _updateThreadIndicatorWidget(widget,threads) {if(!widget) return;let widgetElement=widget.widgetElement;widgetElement.removeChildren();widget[WI.SourceCodeTextEditor.WidgetContainsMultipleThreadsSymbol]=threads.length>1;if(widgetElement.classList.contains("inline")||threads.length===1){let textElement=widgetElement.appendChild(document.createElement("span"));textElement.className="text";textElement.textContent=threads.length===1?threads[0].displayName:WI.UIString("%d Threads").format(threads.length);}else{for(let target of threads){let textElement=widgetElement.appendChild(document.createElement("span"));textElement.className="text";textElement.textContent=target.displayName;widgetElement.appendChild(document.createElement("br"));}} widget.update();} _handleThreadIndicatorWidgetClick(widget,lineNumber,event) {if(!this._isWidgetToggleable(widget)) return;widget.widgetElement.classList.toggle("inline");let threads=this._threadLineNumberMap.get(lineNumber);this._updateThreadIndicatorWidget(widget,threads);} _activeCallFrameDidChange() {if(this._activeCallFrameSourceCodeLocation){this._activeCallFrameSourceCodeLocation.removeEventListener(WI.SourceCodeLocation.Event.LocationChanged,this._activeCallFrameSourceCodeLocationChanged,this);this._activeCallFrameSourceCodeLocation=null;} let activeCallFrame=WI.debuggerManager.activeCallFrame;if(!activeCallFrame||!this._matchesSourceCodeLocation(activeCallFrame.sourceCodeLocation)){this.setExecutionLineAndColumn(NaN,NaN);return;} this._dismissPopover();this._activeCallFrameSourceCodeLocation=activeCallFrame.sourceCodeLocation;this._activeCallFrameSourceCodeLocation.addEventListener(WI.SourceCodeLocation.Event.LocationChanged,this._activeCallFrameSourceCodeLocationChanged,this); let lineInfo=this._editorLineInfoForSourceCodeLocation(activeCallFrame.sourceCodeLocation);this.setExecutionLineAndColumn(lineInfo.lineNumber,lineInfo.columnNumber);if(this._fullContentPopulated||!(this._sourceCode instanceof WI.Resource)||this._requestingScriptContent) return; if(this._sourceCode.type===WI.Resource.Type.Document) this._populateWithInlineScriptContent();else this._populateWithScriptContent();} _activeCallFrameSourceCodeLocationChanged(event) {if(isNaN(this.executionLineNumber)) return;var lineInfo=this._editorLineInfoForSourceCodeLocation(this._activeCallFrameSourceCodeLocation);this.setExecutionLineAndColumn(lineInfo.lineNumber,lineInfo.columnNumber);} _populateWithInlineScriptContent() {var scripts=this._sourceCode.scripts;if(!scripts.length) return;var pendingRequestCount=scripts.length;if(this._inlineScriptContentPopulated===pendingRequestCount) return;this._inlineScriptContentPopulated=pendingRequestCount;function scriptContentAvailable(parameters) {if(--pendingRequestCount) return;this._requestingScriptContent=false;if(this._fullContentPopulated) return;var scriptOpenTag="";var content="";var lineNumber=0;var columnNumber=0;this._invalidLineNumbers={};for(var i=0;i0;--newLinesCount){if(!columnNumber) this._invalidLineNumbers[scripts[i].range.startLine-newLinesCount]=true;columnNumber=0;content+="\n";} for(var spacesCount=scripts[i].range.startColumn-columnNumber-scriptOpenTag.length;spacesCount>0;--spacesCount) content+=" ";content+=scriptOpenTag;content+=scripts[i].content;content+=scriptCloseTag;lineNumber=scripts[i].range.endLine;columnNumber=scripts[i].range.endColumn+scriptCloseTag.length;} this._populateWithContent(content);} this._requestingScriptContent=true;var boundScriptContentAvailable=scriptContentAvailable.bind(this);for(var i=0;i{let data=this.textEditorBreakpointAdded(this,lineNumber,columnNumber);this.setBreakpointInfoForLineAndColumn(data.lineNumber,data.columnNumber,data.breakpointInfo);};let contextMenu=WI.ContextMenu.createFromEvent(event);if(WI.debuggerManager.paused){let editorLineInfo={lineNumber,columnNumber};let unformattedLineInfo=this._unformattedLineInfoForEditorLineInfo(editorLineInfo);let sourceCodeLocation=this._sourceCode.createSourceCodeLocation(unformattedLineInfo.lineNumber,unformattedLineInfo.columnNumber);let script;if(sourceCodeLocation.sourceCode instanceof WI.Script) script=sourceCodeLocation.sourceCode;else if(sourceCodeLocation.sourceCode instanceof WI.Resource) script=sourceCodeLocation.sourceCode.scriptForLocation(sourceCodeLocation);if(script){contextMenu.appendItem(WI.UIString("Continue to Here"),()=>{WI.debuggerManager.continueToLocation(script,sourceCodeLocation.lineNumber,sourceCodeLocation.columnNumber);});contextMenu.appendSeparator();}} let breakpoints=[];for(let lineInfo of editorBreakpoints){let breakpoint=this._breakpointForEditorLineInfo(lineInfo);if(breakpoint) breakpoints.push(breakpoint);} if(!breakpoints.length){contextMenu.appendItem(WI.UIString("Add Breakpoint"),addBreakpoint.bind(this));return;} if(breakpoints.length===1){WI.BreakpointPopover.appendContextMenuItems(contextMenu,breakpoints[0],event.target);if(!WI.isShowingSourcesTab()){contextMenu.appendSeparator();contextMenu.appendItem(WI.UIString("Reveal in Sources Tab"),()=>{WI.showSourcesTab({representedObjectToSelect:breakpoints[0],initiatorHint:WI.TabBrowser.TabNavigationInitiator.ContextMenu,});});} return;} let shouldDisable=breakpoints.some((breakpoint)=>!breakpoint.disabled);contextMenu.appendItem(shouldDisable?WI.UIString("Disable Breakpoints"):WI.UIString("Enable Breakpoints"),()=>{for(let breakpoint of breakpoints) breakpoint.disabled=shouldDisable;});contextMenu.appendItem(WI.UIString("Delete Breakpoints"),()=>{for(let breakpoint of breakpoints) WI.debuggerManager.removeBreakpoint(breakpoint);});} textEditorBreakpointAdded(textEditor,lineNumber,columnNumber) {if(!this._supportsDebugging) return null;var editorLineInfo={lineNumber,columnNumber};var unformattedLineInfo=this._unformattedLineInfoForEditorLineInfo(editorLineInfo);var sourceCodeLocation=this._sourceCode.createSourceCodeLocation(unformattedLineInfo.lineNumber,unformattedLineInfo.columnNumber);var breakpoint=new WI.JavaScriptBreakpoint(sourceCodeLocation);var lineInfo=this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation);this._addBreakpointWithEditorLineInfo(breakpoint,lineInfo);this._ignoreBreakpointAddedBreakpoint=breakpoint;WI.debuggerManager.addBreakpoint(breakpoint);this._ignoreBreakpointAddedBreakpoint=null;return{breakpointInfo:this._breakpointInfoForBreakpoint(breakpoint),lineNumber:lineInfo.lineNumber,columnNumber:lineInfo.columnNumber};} textEditorBreakpointRemoved(textEditor,lineNumber,columnNumber) {if(!this._supportsDebugging) return;let breakpointsToRemove=this._breakpointMap[lineNumber];if(!nullish(columnNumber)) breakpointsToRemove={[columnNumber]:breakpointsToRemove[columnNumber]};for(let column in breakpointsToRemove){let breakpoint=breakpointsToRemove[column];this._removeBreakpointWithEditorLineInfo(breakpoint,{lineNumber,columnNumber:column,});this._ignoreBreakpointRemovedBreakpoint=breakpoint;WI.debuggerManager.removeBreakpoint(breakpoint);this._ignoreBreakpointRemovedBreakpoint=null;}} textEditorBreakpointMoved(textEditor,oldLineNumber,oldColumnNumber,newLineNumber,newColumnNumber) {if(!this._supportsDebugging) return;var oldLineInfo={lineNumber:oldLineNumber,columnNumber:oldColumnNumber};var breakpoint=this._breakpointForEditorLineInfo(oldLineInfo);if(!breakpoint) return;this._removeBreakpointWithEditorLineInfo(breakpoint,oldLineInfo);var newLineInfo={lineNumber:newLineNumber,columnNumber:newColumnNumber};var unformattedNewLineInfo=this._unformattedLineInfoForEditorLineInfo(newLineInfo);this._ignoreLocationUpdateBreakpoint=breakpoint;breakpoint.sourceCodeLocation.update(this._sourceCode,unformattedNewLineInfo.lineNumber,unformattedNewLineInfo.columnNumber);this._ignoreLocationUpdateBreakpoint=null;var accurateNewLineInfo=this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation);this._addBreakpointWithEditorLineInfo(breakpoint,accurateNewLineInfo);if(accurateNewLineInfo.lineNumber!==newLineInfo.lineNumber||accurateNewLineInfo.columnNumber!==newLineInfo.columnNumber) this.updateBreakpointLineAndColumn(newLineInfo.lineNumber,newLineInfo.columnNumber,accurateNewLineInfo.lineNumber,accurateNewLineInfo.columnNumber);} textEditorBreakpointClicked(textEditor,lineNumber,columnNumber) {if(!this._supportsDebugging) return;let breakpointsToToggle=this._breakpointMap[lineNumber];if(!nullish(columnNumber)) breakpointsToToggle={[columnNumber]:breakpointsToToggle[columnNumber]};breakpointsToToggle=Object.values(breakpointsToToggle);let shouldEnable=breakpointsToToggle.some((breakpoint)=>breakpoint.disabled);for(let breakpoint of breakpointsToToggle) breakpoint.disabled=!shouldEnable;} textEditorUpdatedFormatting(textEditor) {this._ignoreAllBreakpointLocationUpdates=true;this._sourceCode.formatterSourceMap=this.formatterSourceMap;this._ignoreAllBreakpointLocationUpdates=false; if(this._sourceCode instanceof WI.Resource&&!(this._sourceCode instanceof WI.SourceMapResource)){var scripts=this._sourceCode.scripts;for(var i=0;i{startPosition=this.originalPositionToCurrentPosition(fromInlineScriptPosition(startPosition));endPosition=this.originalPositionToCurrentPosition(fromInlineScriptPosition(endPosition));callback({startPosition,endPosition});};script.requestScriptSyntaxTree((syntaxTree)=>{if(!syntaxTree){callback(null);return;} position=toInlineScriptPosition(position);let nodes=syntaxTree.containersOfPosition(position);if(!nodes.length){callback(null);return;} for(let node of nodes){if(node.startPosition.equals(position)&&node.type!==WI.ScriptSyntaxTree.NodeType.Program){highlightSourceCodeRange(node.startPosition,node.endPosition);return;} if(node.type===WI.ScriptSyntaxTree.NodeType.ForInStatement||node.type===WI.ScriptSyntaxTree.NodeType.ForOfStatement){if(node.left.startPosition.equals(position)){highlightSourceCodeRange(node.left.startPosition,node.right.endPosition);return;}} if(node.startPosition.isAfter(position)) break;} for(let node of nodes){if(node.endPosition.equals(position)){if(node.type===WI.ScriptSyntaxTree.NodeType.BlockStatement){highlightSourceCodeRange(position.offsetColumn(-1),position);return;}} if(node.startPosition.isAfter(position)) break;} nodes.sort((a,b)=>{let aLength=a.range[1]-a.range[0];let bLength=b.range[1]-b.range[0];return aLength-bLength;});let characterAtPosition=this.getTextInRange(currentPosition,currentPosition.offsetColumn(1));let characterAtPositionIsDotOrBracket=characterAtPosition==="."||characterAtPosition==="[";for(let i=0;i1){for(let target of debuggableTargets) this._addThreadIndicatorForTarget(target);}} _debuggerDidPause(event) {this._updateTokenTrackingControllerState();if(this._typeTokenAnnotator&&this._typeTokenAnnotator.isActive()) this._typeTokenAnnotator.refresh();if(this._basicBlockAnnotator&&this._basicBlockAnnotator.isActive()) this._basicBlockAnnotator.refresh();} _debuggerDidResume(event) {this._updateTokenTrackingControllerState();this._dismissPopover();if(this._typeTokenAnnotator&&this._typeTokenAnnotator.isActive()) this._typeTokenAnnotator.refresh();if(this._basicBlockAnnotator&&this._basicBlockAnnotator.isActive()) this._basicBlockAnnotator.refresh();} _handleFormatterDidChange(event) {if(this._ignoreAllBreakpointLocationUpdates) return; this._removeBreakpointWidgets();var oldBreakpointMap=this._breakpointMap;this._breakpointMap={};for(var lineNumber in oldBreakpointMap){for(var columnNumber in oldBreakpointMap[lineNumber]){var breakpoint=oldBreakpointMap[lineNumber][columnNumber];var newLineInfo=this._editorLineInfoForSourceCodeLocation(breakpoint.sourceCodeLocation);this._addBreakpointWithEditorLineInfo(breakpoint,newLineInfo);this.setBreakpointInfoForLineAndColumn(lineNumber,columnNumber,null);this.setBreakpointInfoForLineAndColumn(newLineInfo.lineNumber,newLineInfo.columnNumber,this._breakpointInfoForBreakpoint(breakpoint));}} this._reinsertAllIssues();this._reinsertAllThreadIndicators();} _sourceCodeSourceMapAdded(event) {WI.notifications.addEventListener(WI.Notification.GlobalModifierKeysDidChange,this._updateTokenTrackingControllerState,this);this._sourceCode.removeEventListener(WI.SourceCode.Event.SourceMapAdded,this._sourceCodeSourceMapAdded,this);this._updateTokenTrackingControllerState();} _updateTokenTrackingControllerState() {var mode=WI.CodeMirrorTokenTrackingController.Mode.None;if(WI.debuggerManager.paused) mode=WI.CodeMirrorTokenTrackingController.Mode.JavaScriptExpression;else if(this._typeTokenAnnotator&&this._typeTokenAnnotator.isActive()) mode=WI.CodeMirrorTokenTrackingController.Mode.JavaScriptTypeInformation;else if(this._hasColorMarkers()) mode=WI.CodeMirrorTokenTrackingController.Mode.MarkedTokens;else if((this._sourceCode instanceof WI.SourceMapResource||this._sourceCode.sourceMaps.length!==0)&&WI.modifierKeys.metaKey&&!WI.modifierKeys.altKey&&!WI.modifierKeys.shiftKey) mode=WI.CodeMirrorTokenTrackingController.Mode.NonSymbolTokens;this.tokenTrackingController.enabled=mode!==WI.CodeMirrorTokenTrackingController.Mode.None;if(mode===this.tokenTrackingController.mode) return;switch(mode){case WI.CodeMirrorTokenTrackingController.Mode.MarkedTokens:this.tokenTrackingController.mouseOverDelayDuration=0;this.tokenTrackingController.mouseOutReleaseDelayDuration=0;break;case WI.CodeMirrorTokenTrackingController.Mode.NonSymbolTokens:this.tokenTrackingController.mouseOverDelayDuration=0;this.tokenTrackingController.mouseOutReleaseDelayDuration=0;this.tokenTrackingController.classNameForHighlightedRange=WI.CodeMirrorTokenTrackingController.JumpToSymbolHighlightStyleClassName;this._dismissPopover();break;case WI.CodeMirrorTokenTrackingController.Mode.JavaScriptExpression:case WI.CodeMirrorTokenTrackingController.Mode.JavaScriptTypeInformation:this.tokenTrackingController.mouseOverDelayDuration=WI.SourceCodeTextEditor.DurationToMouseOverTokenToMakeHoveredToken;this.tokenTrackingController.mouseOutReleaseDelayDuration=WI.SourceCodeTextEditor.DurationToMouseOutOfHoveredTokenToRelease;this.tokenTrackingController.classNameForHighlightedRange=WI.SourceCodeTextEditor.HoveredExpressionHighlightStyleClassName;break;} this.tokenTrackingController.mode=mode;} _hasColorMarkers() {for(var marker of this.markers){if(marker.type===WI.TextMarker.Type.Color) return true;} return false;} tokenTrackingControllerCanReleaseHighlightedRange(tokenTrackingController,element) {if(!this._popover) return true;if(!window.getSelection().isCollapsed&&this._popover.element.contains(window.getSelection().anchorNode)) return false;return true;} tokenTrackingControllerHighlightedRangeReleased(tokenTrackingController,forceHide=false) {if(forceHide||!this._mouseIsOverPopover) this._dismissPopover();} tokenTrackingControllerHighlightedRangeWasClicked(tokenTrackingController) {if(this.tokenTrackingController.mode!==WI.CodeMirrorTokenTrackingController.Mode.NonSymbolTokens) return;if(/\blink\b/.test(this.tokenTrackingController.candidate.hoveredToken.type)) return;const options={ignoreNetworkTab:true,ignoreSearchTab:true,};var sourceCodeLocation=this._sourceCodeLocationForEditorPosition(this.tokenTrackingController.candidate.hoveredTokenRange.start);if(this.sourceCode instanceof WI.SourceMapResource) WI.showOriginalOrFormattedSourceCodeLocation(sourceCodeLocation,options);else WI.showSourceCodeLocation(sourceCodeLocation,options);} tokenTrackingControllerNewHighlightCandidate(tokenTrackingController,candidate) {if(this.tokenTrackingController.mode===WI.CodeMirrorTokenTrackingController.Mode.NonSymbolTokens){this.tokenTrackingController.highlightRange(candidate.hoveredTokenRange);return;} if(this.tokenTrackingController.mode===WI.CodeMirrorTokenTrackingController.Mode.JavaScriptExpression){this._tokenTrackingControllerHighlightedJavaScriptExpression(candidate);return;} if(this.tokenTrackingController.mode===WI.CodeMirrorTokenTrackingController.Mode.JavaScriptTypeInformation){this._tokenTrackingControllerHighlightedJavaScriptTypeInformation(candidate);return;} if(this.tokenTrackingController.mode===WI.CodeMirrorTokenTrackingController.Mode.MarkedTokens){var markers=this.markersAtPosition(candidate.hoveredTokenRange.start);if(markers.length>0) this._tokenTrackingControllerHighlightedMarkedExpression(candidate,markers);else this._dismissEditingController();}} tokenTrackingControllerMouseOutOfHoveredMarker(tokenTrackingController,hoveredMarker) {this._dismissEditingController();} _tokenTrackingControllerHighlightedJavaScriptExpression(candidate) {let target=WI.debuggerManager.activeCallFrame?WI.debuggerManager.activeCallFrame.target:this.target;let expression=appendWebInspectorSourceURL(candidate.expression);function populate(error,result,wasThrown) {if(error||wasThrown) return;if(candidate!==this.tokenTrackingController.candidate) return;let data=WI.RemoteObject.fromPayload(result,target);switch(data.type){case"function":this._showPopoverForFunction(data);break;case"object":if(data.subtype==="null"||data.subtype==="regexp") this._showPopoverWithFormattedValue(data);else this._showPopoverForObject(data);break;case"string":case"number":case"boolean":case"symbol":case"bigint":case"undefined":this._showPopoverWithFormattedValue(data);break;}} if(WI.debuggerManager.activeCallFrame){target.DebuggerAgent.evaluateOnCallFrame.invoke({callFrameId:WI.debuggerManager.activeCallFrame.id,expression,objectGroup:"popover",doNotPauseOnExceptionsAndMuteConsole:true},populate.bind(this));return;} target.RuntimeAgent.evaluate.invoke({expression,objectGroup:"popover",doNotPauseOnExceptionsAndMuteConsole:true},populate.bind(this));} _tokenTrackingControllerHighlightedJavaScriptTypeInformation(candidate) {var sourceCode=this._sourceCode;var sourceID=sourceCode instanceof WI.Script?sourceCode.id:sourceCode.scripts[0].id;var range=candidate.hoveredTokenRange;var offset=this.currentPositionToOriginalOffset(range.start);var allRequests=[{typeInformationDescriptor:WI.ScriptSyntaxTree.TypeProfilerSearchDescriptor.NormalExpression,sourceID,divot:offset}];function handler(error,allTypes){if(error) return;if(candidate!==this.tokenTrackingController.candidate) return;if(!allTypes.length) return;var typeDescription=WI.TypeDescription.fromPayload(allTypes[0]);if(typeDescription.valid){var popoverTitle=WI.TypeTokenView.titleForPopover(WI.TypeTokenView.TitleType.Variable,candidate.expression);this.showPopoverForTypes(typeDescription,null,popoverTitle);}} this.target.RuntimeAgent.getRuntimeTypesForVariablesAtOffsets(allRequests,handler.bind(this));} _showPopover(content,bounds) {var shouldHighlightRange=false;var candidate=this.tokenTrackingController.candidate;if(!bounds){if(!candidate) return;var rects=this.rectsForRange(candidate.hoveredTokenRange);bounds=WI.Rect.unionOfRects(rects);if(this._popover&&this._popover.visible){let intersection=bounds.intersectionWithRect(this._popover.frame);if(intersection.size.width&&intersection.size.height) return;} shouldHighlightRange=true;} content.classList.add(WI.SourceCodeTextEditor.PopoverDebuggerContentStyleClassName);if(!this._popover){this._popover=new WI.Popover(this);this._popover.element.addEventListener("mouseover",this._popoverMouseover.bind(this));this._popover.element.addEventListener("mouseout",this._popoverMouseout.bind(this));} this._popover.presentNewContentWithFrame(content,bounds.pad(5),[WI.RectEdge.MIN_Y,WI.RectEdge.MAX_Y,WI.RectEdge.MAX_X]);if(shouldHighlightRange) this.tokenTrackingController.highlightRange(candidate.expressionRange);} _showPopoverForFunction(data) {let candidate=this.tokenTrackingController.candidate;function didGetDetails(error,response) {if(error){console.error(error);this._dismissPopover();return;} if(candidate!==this.tokenTrackingController.candidate) return;let content=document.createElement("div");content.classList.add("function");let title=document.createElement("div");title.classList.add("title");title.textContent=response.name||response.displayName||WI.UIString("(anonymous function)");content.appendChild(title);let location=response.location;let sourceCode=WI.debuggerManager.scriptForIdentifier(location.scriptId,this.target);let sourceCodeLocation=sourceCode.createSourceCodeLocation(location.lineNumber,location.columnNumber);let functionSourceCodeLink=WI.createSourceCodeLocationLink(sourceCodeLocation);title.appendChild(functionSourceCodeLink);let wrapper=document.createElement("div");wrapper.classList.add("body");content.appendChild(wrapper);let codeMirror=WI.CodeMirrorEditor.create(wrapper,{mode:"text/javascript",readOnly:"nocursor",});const isModule=false;const indentString=WI.indentString();const includeSourceMapData=false;let workerProxy=WI.FormatterWorkerProxy.singleton();workerProxy.formatJavaScript(data.description,isModule,indentString,includeSourceMapData,({formattedText})=>{if(candidate!==this.tokenTrackingController.candidate) return;this._showPopover(content);codeMirror.setValue(formattedText||data.description);this._popover.update();setTimeout(()=>{codeMirror.refresh();});});} data.target.DebuggerAgent.getFunctionDetails(data.objectId,didGetDetails.bind(this));} _showPopoverForObject(data) {var content=document.createElement("div");content.className="object expandable";var titleElement=document.createElement("div");titleElement.className="title";titleElement.textContent=data.description;content.appendChild(titleElement);if(data.subtype==="node"){data.pushNodeToFrontend(function(nodeId){if(!nodeId) return;var domNode=WI.domManager.nodeForId(nodeId);if(!domNode.ownerDocument) return;WI.bindInteractionsForNodeToElement(domNode,titleElement,{ignoreClick:true,});var goToButton=titleElement.appendChild(WI.createGoToArrowButton());goToButton.addEventListener("click",function(){WI.domManager.inspectElement(nodeId,{initiatorHint:WI.TabBrowser.TabNavigationInitiator.LinkClick,});});});} var objectTree=new WI.ObjectTreeView(data);objectTree.showOnlyProperties();objectTree.expand();var bodyElement=content.appendChild(document.createElement("div"));bodyElement.className="body";bodyElement.appendChild(objectTree.element);var candidate=this.tokenTrackingController.candidate;objectTree.singleFireEventListener(WI.ObjectTreeView.Event.Updated,function(event){if(candidate===this.tokenTrackingController.candidate) this._showPopover(content);},this);} _showPopoverWithFormattedValue(remoteObject) {let wrapper=document.createElement("div");wrapper.className="formatted";wrapper.appendChild(WI.FormattedValue.createElementForRemoteObject(remoteObject));this._showPopover(wrapper);} willDismissPopover(popover) {this.tokenTrackingController.removeHighlightedRange();this.target.RuntimeAgent.releaseObjectGroup("popover");} _dismissPopover() {if(!this._popover) return;this._popover.dismiss();} _popoverMouseover(event) {this._mouseIsOverPopover=true;} _popoverMouseout(event) {this._mouseIsOverPopover=this._popover.element.contains(event.relatedTarget);} _hasStyleSheetContents() {let mimeType=this.mimeType;return mimeType==="text/css"||mimeType==="text/x-less"||mimeType==="text/x-sass"||mimeType==="text/x-scss";} _updateEditableMarkers(range) {if(this._hasStyleSheetContents()){this.createColorMarkers(range);this.createGradientMarkers(range);this.createCubicBezierTimingFunctionMarkers(range);this.createLinearTimingFunctionMarkers(range);this.createSpringTimingFunctionMarkers(range);this.createStepsTimingFunctionMarkers(range);} this._updateTokenTrackingControllerState();} _tokenTrackingControllerHighlightedMarkedExpression(candidate,markers) {var editableMarker;for(var marker of markers){if(!marker.range||!Object.values(WI.TextMarker.Type).includes(marker.type)) continue;if(!editableMarker||(marker.range.startLine{if(timeoutIdentifier) clearTimeout(timeoutIdentifier);else{if(this._typeTokenAnnotator) this._typeTokenAnnotator.pause();} timeoutIdentifier=setTimeout(()=>{timeoutIdentifier=null;if(this._typeTokenAnnotator) this._typeTokenAnnotator.resume();},WI.SourceCodeTextEditor.DurationToUpdateTypeTokensAfterScrolling);};return scrollHandler;} _createControlFlowScrollEventHandler() {let timeoutIdentifier=null;let scrollHandler=()=>{if(timeoutIdentifier) clearTimeout(timeoutIdentifier);else if(this._basicBlockAnnotator) this._basicBlockAnnotator.pause();timeoutIdentifier=setTimeout(()=>{timeoutIdentifier=null;if(this._basicBlockAnnotator) this._basicBlockAnnotator.resume();},WI.SourceCodeTextEditor.DurationToUpdateTypeTokensAfterScrolling);};return scrollHandler;} _logCleared(event) {for(let lineNumber of this._issuesLineNumberMap.keys()){this.removeStyleClassFromLine(lineNumber,WI.SourceCodeTextEditor.LineErrorStyleClassName);this.removeStyleClassFromLine(lineNumber,WI.SourceCodeTextEditor.LineWarningStyleClassName);} this._issuesLineNumberMap.clear();this._clearIssueWidgets();}};WI.SourceCodeTextEditor.LineErrorStyleClassName="error";WI.SourceCodeTextEditor.LineWarningStyleClassName="warning";WI.SourceCodeTextEditor.PopoverDebuggerContentStyleClassName="debugger-popover-content";WI.SourceCodeTextEditor.HoveredExpressionHighlightStyleClassName="hovered-expression-highlight";WI.SourceCodeTextEditor.DurationToMouseOverTokenToMakeHoveredToken=500;WI.SourceCodeTextEditor.DurationToMouseOutOfHoveredTokenToRelease=1000;WI.SourceCodeTextEditor.DurationToUpdateTypeTokensAfterScrolling=100;WI.SourceCodeTextEditor.WidgetContainsMultipleIssuesSymbol=Symbol("source-code-widget-contains-multiple-issues");WI.SourceCodeTextEditor.WidgetContainsMultipleThreadsSymbol=Symbol("source-code-widget-contains-multiple-threads");WI.SourceCodeTextEditor.Event={ContentWillPopulate:"source-code-text-editor-content-will-populate",ContentDidPopulate:"source-code-text-editor-content-did-populate"};WI.SourceCodeTimelineTimelineDataGridNode=class SourceCodeTimelineTimelineDataGridNode extends WI.TimelineDataGridNode {constructor(sourceCodeTimeline,options={}) {const records=[];super(records,{includesGraph:true,...options});this._sourceCodeTimeline=sourceCodeTimeline;this._sourceCodeTimeline.addEventListener(WI.Timeline.Event.RecordAdded,this._timelineRecordAdded,this);} get records() {return this._sourceCodeTimeline.records;} get sourceCodeTimeline() {return this._sourceCodeTimeline;} get data() {if(this._cachedData) return this._cachedData;this._cachedData=super.data;this._cachedData.graph=this._sourceCodeTimeline.startTime;return this._cachedData;} createCellContent(columnIdentifier,cell) {if(columnIdentifier==="name"&&this.records.length){cell.classList.add(...this.iconClassNames());return this._createNameCellContent(cell);} return super.createCellContent(columnIdentifier,cell);} filterableDataForColumn(columnIdentifier) {if(columnIdentifier==="name") return this.displayName();return super.filterableDataForColumn(columnIdentifier);} _createNameCellContent(cellElement) {if(!this.records.length) return null;let fragment=document.createDocumentFragment();let mainTitle=this.displayName();fragment.append(mainTitle);let sourceCodeLocation=this._sourceCodeTimeline.sourceCodeLocation;if(sourceCodeLocation){let subtitleElement=document.createElement("span");subtitleElement.classList.add("subtitle");sourceCodeLocation.populateLiveDisplayLocationString(subtitleElement,"textContent",null,WI.SourceCodeLocation.NameStyle.None,WI.UIString("line "));const options={useGoToArrowButton:true,ignoreNetworkTab:true,ignoreSearchTab:true,};let goToArrowButtonLink=WI.createSourceCodeLocationLink(sourceCodeLocation,options);fragment.append(goToArrowButtonLink,subtitleElement);sourceCodeLocation.populateLiveDisplayLocationTooltip(cellElement,mainTitle+"\n");}else cellElement.title=mainTitle;return fragment;} _timelineRecordAdded(event) {if(this.isRecordVisible(event.data.record)) this.needsGraphRefresh();}};WI.SourcesNavigationSidebarPanel=class SourcesNavigationSidebarPanel extends WI.NavigationSidebarPanel {constructor() {const shouldAutoPruneStaleTopLevelResourceTreeElements=true;super("sources",WI.UIString("Sources"),shouldAutoPruneStaleTopLevelResourceTreeElements);this._workerTargetTreeElementMap=new Map;this._mainFrameTreeElement=null;this._extensionScriptsFolderTreeElement=null;this._extensionStyleSheetsFolderTreeElement=null;this._extraScriptsFolderTreeElement=null;this._extraStyleSheetsFolderTreeElement=null;this._anonymousScriptsFolderTreeElement=null;this._anonymousStyleSheetsFolderTreeElement=null;this._originTreeElementMap=new Map;this._boundCompareTreeElements=this._compareTreeElements.bind(this);this._debuggerNavigationBar=new WI.NavigationBar;this.addSubview(this._debuggerNavigationBar);let createActivateNavigationItem=({identifier,defaultToolTip,activatedToolTip,image})=>{let navigationItem=new WI.ActivateButtonNavigationItem(identifier,defaultToolTip,activatedToolTip,image,15,15);this._debuggerNavigationBar.addNavigationItem(navigationItem);return navigationItem;};let createToggleNavigationItem=({identifier,defaultToolTip,alternateToolTip,defaultImage,alternateImage})=>{let navigationItem=new WI.ToggleButtonNavigationItem(identifier,defaultToolTip,alternateToolTip,defaultImage,alternateImage,15,15);this._debuggerNavigationBar.addNavigationItem(navigationItem);return navigationItem;};let createButtonNavigationitem=({identifier,toolTipOrLabel,image})=>{let navigationItem=new WI.ButtonNavigationItem(identifier,toolTipOrLabel,image,15,15);this._debuggerNavigationBar.addNavigationItem(navigationItem);return navigationItem;};this._debuggerBreakpointsButtonItem=createActivateNavigationItem({identifier:"debugger-breakpoints",defaultToolTip:WI.UIString("Enable all breakpoints (%s)").format(WI.toggleBreakpointsKeyboardShortcut.displayName),activatedToolTip:WI.UIString("Disable all breakpoints (%s)").format(WI.toggleBreakpointsKeyboardShortcut.displayName),image:"Images/Breakpoints.svg",});this._debuggerBreakpointsButtonItem.activated=WI.debuggerManager.breakpointsEnabled;this._debuggerBreakpointsButtonItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI.debuggerToggleBreakpoints,this);this._debuggerPauseResumeButtonItem=createToggleNavigationItem({identifier:"debugger-pause-resume",defaultToolTip:WI.UIString("Pause script execution (%s or %s)").format(WI.pauseOrResumeKeyboardShortcut.displayName,WI.pauseOrResumeAlternateKeyboardShortcut.displayName),alternateToolTip:WI.UIString("Continue script execution (%s or %s)").format(WI.pauseOrResumeKeyboardShortcut.displayName,WI.pauseOrResumeAlternateKeyboardShortcut.displayName),defaultImage:"Images/Pause.svg",alternateImage:"Images/Resume.svg",});this._debuggerPauseResumeButtonItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI.debuggerPauseResumeToggle,this);this._debuggerStepOverButtonItem=createButtonNavigationitem({identifier:"debugger-step-over",toolTipOrLabel:WI.UIString("Step over (%s or %s)").format(WI.stepOverKeyboardShortcut.displayName,WI.stepOverAlternateKeyboardShortcut.displayName),image:"Images/StepOver.svg",});this._debuggerStepOverButtonItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI.debuggerStepOver,this);this._debuggerStepOverButtonItem.enabled=false;this._debuggerStepIntoButtonItem=createButtonNavigationitem({identifier:"debugger-step-into",toolTipOrLabel:WI.UIString("Step into (%s or %s)").format(WI.stepIntoKeyboardShortcut.displayName,WI.stepIntoAlternateKeyboardShortcut.displayName),image:"Images/StepInto.svg",});this._debuggerStepIntoButtonItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI.debuggerStepInto,this);this._debuggerStepIntoButtonItem.enabled=false;this._debuggerStepOutButtonItem=createButtonNavigationitem({identifier:"debugger-step-out",toolTipOrLabel:WI.UIString("Step out (%s or %s)").format(WI.stepOutKeyboardShortcut.displayName,WI.stepOutAlternateKeyboardShortcut.displayName),image:"Images/StepOut.svg",});this._debuggerStepOutButtonItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI.debuggerStepOut,this);this._debuggerStepOutButtonItem.enabled=false;if(InspectorBackend.hasCommand("Debugger.stepNext")){this._debuggerStepNextButtonItem=createButtonNavigationitem({identifier:"debugger-step-next",toolTipOrLabel:WI.UIString("Step (%s or %s)").format(WI.stepNextKeyboardShortcut.displayName,WI.stepNextAlternateKeyboardShortcut.displayName),image:"Images/StepNext.svg",});this._debuggerStepNextButtonItem.addEventListener(WI.ButtonNavigationItem.Event.Clicked,WI.debuggerStepNext,this);this._debuggerStepNextButtonItem.enabled=false;} this._timelineRecordingWarningElement=null;this._auditTestWarningElement=null;this._breakpointsDisabledWarningElement=null;this._pauseReasonTreeOutline=null;this._pauseReasonLinkContainerElement=document.createElement("span");this._pauseReasonTextRow=new WI.DetailsSectionTextRow;this._pauseReasonGroup=new WI.DetailsSectionGroup([this._pauseReasonTextRow]);this._pauseReasonSection=new WI.DetailsSection("paused-reason",WI.UIString("Pause Reason"),[this._pauseReasonGroup],this._pauseReasonLinkContainerElement);this._pauseReasonContainer=this.contentView.element.appendChild(document.createElement("div"));this._pauseReasonContainer.classList.add("pause-reason-container");this._pauseReasonContainer.hidden=true;this._pauseReasonContainer.appendChild(this._pauseReasonSection.element);this._callStackTreeOutline=this.createContentTreeOutline({suppressFiltering:true});this._callStackTreeOutline.allowsMultipleSelection=true;this._callStackTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._handleTreeSelectionDidChange,this);this._callStackTreeOutline.populateContextMenu=(contextMenu,event,treeElement)=>{if(this._callStackTreeOutline.selectedTreeElements.length){contextMenu.appendItem(WI.UIString("Copy"),()=>{this.handleCopyEvent(event);});contextMenu.appendSeparator();} WI.TreeOutline.prototype.populateContextMenu(contextMenu,event,treeElement);};let callStackRow=new WI.DetailsSectionRow;callStackRow.element.appendChild(this._callStackTreeOutline.element);let callStackGroup=new WI.DetailsSectionGroup([callStackRow]);this._callStackSection=new WI.DetailsSection("call-stack",WI.UIString("Call Stack"),[callStackGroup]);this._callStackContainer=this.contentView.element.appendChild(document.createElement("div"));this._callStackContainer.classList.add("call-stack-container");this._callStackContainer.hidden=true;this._callStackContainer.appendChild(this._callStackSection.element);this._mainTargetTreeElement=null;this._activeCallFrameTreeElement=null;this._breakpointsTreeOutline=this.createContentTreeOutline({ignoreCookieRestoration:true});this._breakpointsTreeOutline.addEventListener(WI.TreeOutline.Event.ElementRemoved,this._handleBreakpointTreeOutlineElementRemoved,this);this._breakpointsTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._handleTreeSelectionDidChange,this);this._breakpointsTreeOutline.ondelete=(selectedTreeElement)=>{if(selectedTreeElement.representedObject instanceof WI.Breakpoint&&!selectedTreeElement.representedObject.removable){let treeElementToSelect=selectedTreeElement.nextSelectableSibling;if(treeElementToSelect){const omitFocus=true;const selectedByUser=true;treeElementToSelect.select(omitFocus,selectedByUser);}}else if(selectedTreeElement instanceof WI.ResourceTreeElement||selectedTreeElement instanceof WI.ScriptTreeElement){let breakpoints=this._breakpointsBeneathTreeElement(selectedTreeElement);this._removeAllBreakpoints(breakpoints);}else if(selectedTreeElement.representedObject===SourcesNavigationSidebarPanel.__windowEventTargetRepresentedObject){let eventBreakpointsOnWindow=WI.domManager.eventListenerBreakpoints.filter((eventBreakpoint)=>eventBreakpoint.eventListener.onWindow);for(let eventBreakpoint of eventBreakpointsOnWindow) WI.domManager.removeBreakpointForEventListener(eventBreakpoint.eventListener);} return true;};this._breakpointsTreeOutline.populateContextMenu=(contextMenu,event,treeElement)=>{ if(treeElement instanceof WI.ResourceTreeElement||treeElement instanceof WI.ScriptTreeElement){let breakpoints=this._breakpointsBeneathTreeElement(treeElement);let shouldDisable=breakpoints.some((breakpoint)=>!breakpoint.disabled);contextMenu.appendItem(shouldDisable?WI.UIString("Disable Breakpoints"):WI.UIString("Enable Breakpoints"),()=>{this._toggleAllBreakpoints(breakpoints,shouldDisable);});contextMenu.appendItem(WI.UIString("Delete Breakpoints"),()=>{this._removeAllBreakpoints(breakpoints);});} WI.TreeOutline.prototype.populateContextMenu(contextMenu,event,treeElement);};let breakpointsRow=new WI.DetailsSectionRow;breakpointsRow.element.appendChild(this._breakpointsTreeOutline.element);let breakpointNavigationBarWrapper=document.createElement("div");let breakpointNavigationBar=new WI.NavigationBar;breakpointNavigationBarWrapper.appendChild(breakpointNavigationBar.element);this._createBreakpointButton=new WI.ButtonNavigationItem("create-breakpoint",WI.UIString("Create Breakpoint"),"Images/Plus13.svg",13,13);WI.addMouseDownContextMenuHandlers(this._createBreakpointButton.element,this._populateCreateBreakpointContextMenu.bind(this));breakpointNavigationBar.addNavigationItem(this._createBreakpointButton);let breakpointsGroup=new WI.DetailsSectionGroup([breakpointsRow]);this._breakpointsSection=new WI.DetailsSection("breakpoints",WI.UIString("Breakpoints"),[breakpointsGroup],breakpointNavigationBarWrapper);let breakpointsContainer=this.contentView.element.appendChild(document.createElement("div"));breakpointsContainer.classList.add("breakpoints-container");breakpointsContainer.appendChild(this._breakpointsSection.element);this._localOverridesTreeOutline=this.createContentTreeOutline({suppressFiltering:true});this._localOverridesTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._handleTreeSelectionDidChange,this);this._localOverridesRow=new WI.DetailsSectionRow(WI.UIString("No Overrides"));let localOverrideNavigationBarWrapper=document.createElement("div");let localOverrideNavigationBar=new WI.NavigationBar;localOverrideNavigationBarWrapper.appendChild(localOverrideNavigationBar.element);this._createLocalOverrideButton=new WI.ButtonNavigationItem("create-local-override",WI.UIString("Create Local Override"),"Images/Plus13.svg",13,13);WI.addMouseDownContextMenuHandlers(this._createLocalOverrideButton.element,this._populateCreateLocalOverrideContextMenu.bind(this));localOverrideNavigationBar.addNavigationItem(this._createLocalOverrideButton);let localOverridesGroup=new WI.DetailsSectionGroup([this._localOverridesRow]);this._localOverridesSection=new WI.DetailsSection("local-overrides",WI.UIString("Local Overrides"),[localOverridesGroup],localOverrideNavigationBarWrapper);this._localOverridesContainer=this.contentView.element.appendChild(document.createElement("div"));this._localOverridesContainer.classList.add("local-overrides-container");this._localOverridesContainer.hidden=true;this._localOverridesContainer.appendChild(this._localOverridesSection.element);this._consoleSnippetsTreeOutline=this.createContentTreeOutline({suppressFiltering:true});this._consoleSnippetsTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._handleTreeSelectionDidChange,this);this._consoleSnippetsRow=new WI.DetailsSectionRow(WI.UIString("No Console Snippets"));let consoleSnippetNavigationBarWrapper=document.createElement("div");let consoleSnippetNavigationBar=new WI.NavigationBar;consoleSnippetNavigationBarWrapper.appendChild(consoleSnippetNavigationBar.element);this._createConsoleSnippetButton=new WI.ButtonNavigationItem("create-console-snippet",WI.UIString("Create Console Snippet"),"Images/Plus13.svg",13,13);this._createConsoleSnippetButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked,this._handleCreateConsoleSnippetButtonClicked,this);consoleSnippetNavigationBar.addNavigationItem(this._createConsoleSnippetButton);let consoleSnippetsGroup=new WI.DetailsSectionGroup([this._consoleSnippetsRow]);this._consoleSnippetsSection=new WI.DetailsSection("console-snippets",WI.UIString("Console Snippets"),[consoleSnippetsGroup],consoleSnippetNavigationBarWrapper);this._consoleSnippetsContainer=this.contentView.element.appendChild(document.createElement("div"));this._consoleSnippetsContainer.classList.add("console-snippets-container");this._consoleSnippetsContainer.hidden=true;this._consoleSnippetsContainer.appendChild(this._consoleSnippetsSection.element);this._resourcesNavigationBar=new WI.NavigationBar;this.contentView.addSubview(this._resourcesNavigationBar);this._resourceGroupingModeScopeBarItems={};let createResourceGroupingModeScopeBarItem=(mode,label)=>{this._resourceGroupingModeScopeBarItems[mode]=new WI.ScopeBarItem("sources-resource-grouping-mode-"+mode,label,{exclusive:true});this._resourceGroupingModeScopeBarItems[mode][SourcesNavigationSidebarPanel.ResourceGroupingModeSymbol]=mode;};createResourceGroupingModeScopeBarItem(WI.Resource.GroupingMode.Type,WI.UIString("By Type"));createResourceGroupingModeScopeBarItem(WI.Resource.GroupingMode.Path,WI.UIString("By Path"));this._resourceGroupingModeScopeBar=new WI.ScopeBar("sources-resource-grouping-mode-scope-bar",Object.values(this._resourceGroupingModeScopeBarItems),this._resourceGroupingModeScopeBarItems[WI.settings.resourceGroupingMode.value]);this._resourceGroupingModeScopeBar.addEventListener(WI.ScopeBar.Event.SelectionChanged,this._handleResourceGroupingModeScopeBarSelectionChanged,this);this._resourcesNavigationBar.addNavigationItem(this._resourceGroupingModeScopeBar);let resourcesContainer=this.contentView.element.appendChild(document.createElement("div"));resourcesContainer.classList.add("resources-container");this._resourcesTreeOutline=this.contentTreeOutline;this._resourcesTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._handleTreeSelectionDidChange,this);this._resourcesTreeOutline.includeSourceMapResourceChildren=true;resourcesContainer.appendChild(this._resourcesTreeOutline.element);if(WI.NetworkManager.supportsOverridingResponses()||WI.NetworkManager.supportsBootstrapScript()||WI.CSSManager.supportsInspectorStyleSheet()){let createResourceNavigationBar=new WI.NavigationBar;let createResourceButtonNavigationItem=new WI.ButtonNavigationItem("create-resource",WI.UIString("Create Resource"),"Images/Plus15.svg",15,15);WI.addMouseDownContextMenuHandlers(createResourceButtonNavigationItem.element,this._populateCreateResourceContextMenu.bind(this));createResourceNavigationBar.addNavigationItem(createResourceButtonNavigationItem);this.filterBar.element.insertBefore(createResourceNavigationBar.element,this.filterBar.element.firstChild);} const activatedByDefault=false;this.filterBar.addFilterBarButton("sources-only-show-resources-with-issues",this._filterByResourcesWithIssues.bind(this),activatedByDefault,WI.UIString("Only show resources with issues"),WI.UIString("Show all resources"),"Images/Errors.svg",15,15);const resourceTypeScopeItemPrefix="sources-resource-type-";let resourceTypeScopeBarItems=[];resourceTypeScopeBarItems.push(new WI.ScopeBarItem(resourceTypeScopeItemPrefix+"all",WI.UIString("All")));for(let value of Object.values(WI.Resource.Type)){let scopeBarItem=new WI.ScopeBarItem(resourceTypeScopeItemPrefix+value,WI.Resource.displayNameForType(value,true));scopeBarItem[SourcesNavigationSidebarPanel.ResourceTypeSymbol]=value;resourceTypeScopeBarItems.push(scopeBarItem);} const shouldGroupNonExclusiveItems=true;this._resourceTypeScopeBar=new WI.ScopeBar("sources-resource-type-scope-bar",resourceTypeScopeBarItems,resourceTypeScopeBarItems[0],shouldGroupNonExclusiveItems);this._resourceTypeScopeBar.addEventListener(WI.ScopeBar.Event.SelectionChanged,this._handleResourceTypeScopeBarSelectionChanged,this);this.filterBar.addFilterNavigationItem(this._resourceTypeScopeBar);WI.settings.resourceGroupingMode.addEventListener(WI.Setting.Event.Changed,this._handleResourceGroupingModeChanged,this);WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange,this._handleFrameMainResourceDidChange,this);WI.Frame.addEventListener(WI.Frame.Event.ResourceWasAdded,this._handleResourceAdded,this);WI.Target.addEventListener(WI.Target.Event.ResourceAdded,this._handleResourceAdded,this);WI.networkManager.addEventListener(WI.NetworkManager.Event.FrameWasAdded,this._handleFrameWasAdded,this);if(WI.NetworkManager.supportsBootstrapScript()){WI.networkManager.addEventListener(WI.NetworkManager.Event.BootstrapScriptCreated,this._handleBootstrapScriptCreated,this);WI.networkManager.addEventListener(WI.NetworkManager.Event.BootstrapScriptDestroyed,this._handleBootstrapScriptDestroyed,this);} if(WI.NetworkManager.supportsOverridingResponses()){WI.networkManager.addEventListener(WI.NetworkManager.Event.LocalResourceOverrideAdded,this._handleLocalResourceOverrideAdded,this);WI.networkManager.addEventListener(WI.NetworkManager.Event.LocalResourceOverrideRemoved,this._handleLocalResourceOverrideRemoved,this);} WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BreakpointAdded,this._handleDebuggerBreakpointAdded,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.SymbolicBreakpointAdded,this._handleDebuggerBreakpointAdded,this);WI.domDebuggerManager.addEventListener(WI.DOMDebuggerManager.Event.DOMBreakpointAdded,this._handleDebuggerBreakpointAdded,this);WI.domDebuggerManager.addEventListener(WI.DOMDebuggerManager.Event.EventBreakpointAdded,this._handleDebuggerBreakpointAdded,this);WI.domDebuggerManager.addEventListener(WI.DOMDebuggerManager.Event.URLBreakpointAdded,this._handleDebuggerBreakpointAdded,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BreakpointRemoved,this._handleDebuggerBreakpointRemoved,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.SymbolicBreakpointRemoved,this._handleDebuggerBreakpointRemoved,this);WI.domDebuggerManager.addEventListener(WI.DOMDebuggerManager.Event.DOMBreakpointRemoved,this._handleDebuggerBreakpointRemoved,this);WI.domDebuggerManager.addEventListener(WI.DOMDebuggerManager.Event.EventBreakpointRemoved,this._handleDebuggerBreakpointRemoved,this);WI.domDebuggerManager.addEventListener(WI.DOMDebuggerManager.Event.URLBreakpointRemoved,this._handleDebuggerBreakpointRemoved,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.BreakpointsEnabledDidChange,this._handleDebuggerBreakpointsEnabledDidChange,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ScriptAdded,this._handleDebuggerScriptAdded,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ScriptRemoved,this._handleDebuggerScriptRemoved,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ScriptsCleared,this._handleDebuggerScriptsCleared,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.Paused,this._handleDebuggerPaused,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.Resumed,this._handleDebuggerResumed,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.CallFramesDidChange,this._handleDebuggerCallFramesDidChange,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.ActiveCallFrameDidChange,this._handleDebuggerActiveCallFrameDidChange,this);WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.WaitingToPause,this._handleDebuggerWaitingToPause,this);WI.JavaScriptBreakpoint.addEventListener(WI.JavaScriptBreakpoint.Event.DisplayLocationDidChange,this._handleDebuggerObjectDisplayLocationDidChange,this);WI.IssueMessage.addEventListener(WI.IssueMessage.Event.DisplayLocationDidChange,this._handleDebuggerObjectDisplayLocationDidChange,this);WI.DOMBreakpoint.addEventListener(WI.DOMBreakpoint.Event.DOMNodeWillChange,this._handleDOMBreakpointDOMNodeWillChange,this);WI.DOMBreakpoint.addEventListener(WI.DOMBreakpoint.Event.DOMNodeDidChange,this._handleDOMBreakpointDOMNodeDidChange,this);WI.consoleManager.addEventListener(WI.ConsoleManager.Event.IssueAdded,this._handleConsoleIssueAdded,this);WI.consoleManager.addEventListener(WI.ConsoleManager.Event.Cleared,this._handleConsoleCleared,this);WI.consoleManager.addEventListener(WI.ConsoleManager.Event.SnippetAdded,this._handleConsoleSnippetAdded,this);WI.consoleManager.addEventListener(WI.ConsoleManager.Event.SnippetRemoved,this._handleConsoleSnippetRemoved,this);WI.timelineManager.addEventListener(WI.TimelineManager.Event.CapturingStateChanged,this._handleTimelineCapturingStateChanged,this);WI.auditManager.addEventListener(WI.AuditManager.Event.TestScheduled,this._handleAuditManagerTestScheduled,this);WI.auditManager.addEventListener(WI.AuditManager.Event.TestCompleted,this._handleAuditManagerTestCompleted,this);WI.cssManager.addEventListener(WI.CSSManager.Event.StyleSheetAdded,this._handleCSSStyleSheetAdded,this);WI.cssManager.addEventListener(WI.CSSManager.Event.StyleSheetRemoved,this._handleCSSStyleSheetRemoved,this);WI.targetManager.addEventListener(WI.TargetManager.Event.TargetAdded,this._handleTargetAdded,this);WI.targetManager.addEventListener(WI.TargetManager.Event.TargetRemoved,this._handleTargetRemoved,this); WI.notifications.addEventListener(WI.Notification.ExtraDomainsActivated,this._handleExtraDomainsActivated,this);if(WI.SourcesNavigationSidebarPanel.shouldPlaceResourcesAtTopLevel()){this._resourcesTreeOutline.disclosureButtons=false;WI.SourceCode.addEventListener(WI.SourceCode.Event.SourceMapAdded,function(event){this._resourcesTreeOutline.disclosureButtons=true;},this);} if(WI.debuggerManager.debuggerStatementsBreakpoint) this._addBreakpoint(WI.debuggerManager.debuggerStatementsBreakpoint);if(WI.debuggerManager.allExceptionsBreakpoint) this._addBreakpoint(WI.debuggerManager.allExceptionsBreakpoint);if(WI.debuggerManager.uncaughtExceptionsBreakpoint) this._addBreakpoint(WI.debuggerManager.uncaughtExceptionsBreakpoint);if(WI.debuggerManager.assertionFailuresBreakpoint) this._addBreakpoint(WI.debuggerManager.assertionFailuresBreakpoint);if(WI.debuggerManager.allMicrotasksBreakpoint) this._addBreakpoint(WI.debuggerManager.allMicrotasksBreakpoint);for(let target of WI.targets) this._addTarget(target);this._updateCallStackTreeOutline();this._handleResourceGroupingModeChanged();if(WI.NetworkManager.supportsBootstrapScript()){let bootstrapScript=WI.networkManager.bootstrapScript;if(bootstrapScript) this._addLocalOverride(bootstrapScript);} if(WI.NetworkManager.supportsOverridingResponses()){for(let localResourceOverride of WI.networkManager.localResourceOverrides) this._addLocalOverride(localResourceOverride);} if(WI.domDebuggerManager.supported){if(WI.domDebuggerManager.allAnimationFramesBreakpoint) this._addBreakpoint(WI.domDebuggerManager.allAnimationFramesBreakpoint);if(WI.domDebuggerManager.allTimeoutsBreakpoint) this._addBreakpoint(WI.domDebuggerManager.allTimeoutsBreakpoint);if(WI.domDebuggerManager.allIntervalsBreakpoint) this._addBreakpoint(WI.domDebuggerManager.allIntervalsBreakpoint);if(WI.domDebuggerManager.allListenersBreakpoint) this._addBreakpoint(WI.domDebuggerManager.allListenersBreakpoint);for(let eventBreakpoint of WI.domDebuggerManager.listenerBreakpoints) this._addBreakpoint(eventBreakpoint);for(let eventListenerBreakpoint of WI.domManager.eventListenerBreakpoints) this._addBreakpoint(eventListenerBreakpoint);for(let domBreakpoint of WI.domDebuggerManager.domBreakpoints) this._addBreakpoint(domBreakpoint);if(WI.domDebuggerManager.allRequestsBreakpoint) this._addBreakpoint(WI.domDebuggerManager.allRequestsBreakpoint);for(let urlBreakpoints of WI.domDebuggerManager.urlBreakpoints) this._addBreakpoint(urlBreakpoints);} if(WI.debuggerManager.paused) this._handleDebuggerPaused();if(WI.debuggerManager.breakpointsDisabledTemporarily){this._handleTimelineCapturingStateChanged();if(WI.auditManager.runningState===WI.AuditManager.RunningState.Active||WI.auditManager.runningState===WI.AuditManager.RunningState.Stopping) this._handleAuditManagerTestScheduled();} for(let consoleSnippet of WI.consoleManager.snippets) this._addConsoleSnippet(consoleSnippet);this._updateBreakpointsDisabledBanner();} static shouldPlaceResourcesAtTopLevel() {return WI.sharedApp.debuggableType===WI.DebuggableType.ITML||WI.sharedApp.debuggableType===WI.DebuggableType.JavaScript||WI.sharedApp.debuggableType===WI.DebuggableType.ServiceWorker;} get minimumWidth() {return Math.max(this._debuggerNavigationBar.minimumWidth,this._resourcesNavigationBar.minimumWidth);} closed() {WI.settings.resourceGroupingMode.removeEventListener(WI.Setting.Event.Changed,this._handleResourceGroupingModeChanged,this);WI.Frame.removeEventListener(WI.Frame.Event.MainResourceDidChange,this._handleFrameMainResourceDidChange,this);WI.Frame.removeEventListener(WI.Frame.Event.ResourceWasAdded,this._handleResourceAdded,this);WI.Target.removeEventListener(WI.Target.Event.ResourceAdded,this._handleResourceAdded,this);WI.networkManager.removeEventListener(WI.NetworkManager.Event.FrameWasAdded,this._handleFrameWasAdded,this);if(WI.NetworkManager.supportsBootstrapScript()){WI.networkManager.removeEventListener(WI.NetworkManager.Event.BootstrapScriptCreated,this._handleBootstrapScriptCreated,this);WI.networkManager.removeEventListener(WI.NetworkManager.Event.BootstrapScriptDestroyed,this._handleBootstrapScriptDestroyed,this);} if(WI.NetworkManager.supportsOverridingResponses()){WI.networkManager.removeEventListener(WI.NetworkManager.Event.LocalResourceOverrideAdded,this._handleLocalResourceOverrideAdded,this);WI.networkManager.removeEventListener(WI.NetworkManager.Event.LocalResourceOverrideRemoved,this._handleLocalResourceOverrideRemoved,this);} WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.BreakpointAdded,this._handleDebuggerBreakpointAdded,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.SymbolicBreakpointAdded,this._handleDebuggerBreakpointAdded,this);WI.domDebuggerManager.removeEventListener(WI.DOMDebuggerManager.Event.DOMBreakpointAdded,this._handleDebuggerBreakpointAdded,this);WI.domDebuggerManager.removeEventListener(WI.DOMDebuggerManager.Event.EventBreakpointAdded,this._handleDebuggerBreakpointAdded,this);WI.domDebuggerManager.removeEventListener(WI.DOMDebuggerManager.Event.URLBreakpointAdded,this._handleDebuggerBreakpointAdded,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.BreakpointRemoved,this._handleDebuggerBreakpointRemoved,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.SymbolicBreakpointRemoved,this._handleDebuggerBreakpointRemoved,this);WI.domDebuggerManager.removeEventListener(WI.DOMDebuggerManager.Event.DOMBreakpointRemoved,this._handleDebuggerBreakpointRemoved,this);WI.domDebuggerManager.removeEventListener(WI.DOMDebuggerManager.Event.EventBreakpointRemoved,this._handleDebuggerBreakpointRemoved,this);WI.domDebuggerManager.removeEventListener(WI.DOMDebuggerManager.Event.URLBreakpointRemoved,this._handleDebuggerBreakpointRemoved,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.BreakpointsEnabledDidChange,this._handleDebuggerBreakpointsEnabledDidChange,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ScriptAdded,this._handleDebuggerScriptAdded,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ScriptRemoved,this._handleDebuggerScriptRemoved,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ScriptsCleared,this._handleDebuggerScriptsCleared,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.Paused,this._handleDebuggerPaused,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.Resumed,this._handleDebuggerResumed,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.CallFramesDidChange,this._handleDebuggerCallFramesDidChange,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.ActiveCallFrameDidChange,this._handleDebuggerActiveCallFrameDidChange,this);WI.debuggerManager.removeEventListener(WI.DebuggerManager.Event.WaitingToPause,this._handleDebuggerWaitingToPause,this);WI.JavaScriptBreakpoint.removeEventListener(WI.JavaScriptBreakpoint.Event.DisplayLocationDidChange,this._handleDebuggerObjectDisplayLocationDidChange,this);WI.IssueMessage.removeEventListener(WI.IssueMessage.Event.DisplayLocationDidChange,this._handleDebuggerObjectDisplayLocationDidChange,this);WI.DOMBreakpoint.removeEventListener(WI.DOMBreakpoint.Event.DOMNodeWillChange,this._handleDOMBreakpointDOMNodeWillChange,this);WI.DOMBreakpoint.removeEventListener(WI.DOMBreakpoint.Event.DOMNodeDidChange,this._handleDOMBreakpointDOMNodeDidChange,this);WI.consoleManager.removeEventListener(WI.ConsoleManager.Event.IssueAdded,this._handleConsoleIssueAdded,this);WI.consoleManager.removeEventListener(WI.ConsoleManager.Event.Cleared,this._handleConsoleCleared,this);WI.consoleManager.removeEventListener(WI.ConsoleManager.Event.SnippetAdded,this._handleConsoleSnippetAdded,this);WI.consoleManager.removeEventListener(WI.ConsoleManager.Event.SnippetRemoved,this._handleConsoleSnippetRemoved,this);WI.timelineManager.removeEventListener(WI.TimelineManager.Event.CapturingStateChanged,this._handleTimelineCapturingStateChanged,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.TestScheduled,this._handleAuditManagerTestScheduled,this);WI.auditManager.removeEventListener(WI.AuditManager.Event.TestCompleted,this._handleAuditManagerTestCompleted,this);WI.cssManager.removeEventListener(WI.CSSManager.Event.StyleSheetAdded,this._handleCSSStyleSheetAdded,this);WI.cssManager.removeEventListener(WI.CSSManager.Event.StyleSheetRemoved,this._handleCSSStyleSheetRemoved,this);WI.targetManager.removeEventListener(WI.TargetManager.Event.TargetAdded,this._handleTargetAdded,this);WI.targetManager.removeEventListener(WI.TargetManager.Event.TargetRemoved,this._handleTargetRemoved,this); WI.notifications.removeEventListener(WI.Notification.ExtraDomainsActivated,this._handleExtraDomainsActivated,this);super.closed();} showDefaultContentView() {if(WI.networkManager.mainFrame){this.contentBrowser.showContentViewForRepresentedObject(WI.networkManager.mainFrame);return;} let firstTreeElement=this._resourcesTreeOutline.children[0];if(firstTreeElement) this.showDefaultContentViewForTreeElement(firstTreeElement);} treeElementForRepresentedObject(representedObject) {if(representedObject instanceof WI.LocalResourceOverride) return this._localOverridesTreeOutline.findTreeElement(representedObject);if(representedObject instanceof WI.LocalResource){let localResourceOverride=representedObject.localResourceOverride||WI.networkManager.localResourceOverridesForURL(representedObject.url)[0];return this._localOverridesTreeOutline.findTreeElement(localResourceOverride);} if(representedObject instanceof WI.Script&&representedObject===WI.networkManager.bootstrapScript) return this._localOverridesTreeOutline.findTreeElement(representedObject);if(representedObject instanceof WI.ConsoleSnippet) return this._consoleSnippetsTreeOutline.findTreeElement(representedObject);if(!this._mainFrameTreeElement&&(representedObject instanceof WI.Resource||representedObject instanceof WI.Frame||representedObject instanceof WI.Collection)){return null;} switch(WI.settings.resourceGroupingMode.value){case WI.Resource.GroupingMode.Path:if(representedObject instanceof WI.Frame) representedObject=representedObject.mainResource;break;default:WI.reportInternalError("Unknown resource grouping mode",{"Resource Grouping Mode":WI.settings.resourceGroupingMode.value});case WI.Resource.GroupingMode.Type:if(representedObject instanceof WI.Resource&&representedObject.parentFrame&&representedObject.parentFrame.mainResource===representedObject) representedObject=representedObject.parentFrame;break;} function isAncestor(ancestor,resourceOrFrame){if(resourceOrFrame instanceof WI.SourceMapResource){if(resourceOrFrame.sourceMap.originalSourceCode===ancestor) return true;resourceOrFrame=resourceOrFrame.sourceMap.originalSourceCode;} let currentFrame=resourceOrFrame.parentFrame;while(currentFrame){if(currentFrame===ancestor) return true;currentFrame=currentFrame.parentFrame;} return false;} function getParent(resourceOrFrame){if(resourceOrFrame instanceof WI.SourceMapResource) return resourceOrFrame.sourceMap.originalSourceCode;return resourceOrFrame.parentFrame;} function searchTreeOutline(treeOutline,forceSearch){if(!treeOutline||(!treeOutline.selectedTreeElement&&!forceSearch)) return null;return treeOutline.findTreeElement(representedObject,isAncestor,getParent);} let treeElement=searchTreeOutline(this._pauseReasonTreeOutline)||searchTreeOutline(this._callStackTreeOutline)||searchTreeOutline(this._breakpointsTreeOutline)||searchTreeOutline(this._resourcesTreeOutline,true);if(treeElement) return treeElement;if(representedObject instanceof WI.Script){if(representedObject.url){return null;} if(!this._anonymousScriptsFolderTreeElement) this._anonymousScriptsFolderTreeElement=new WI.FolderTreeElement(WI.UIString("Anonymous Scripts"),new WI.ScriptCollection);if(!this._anonymousScriptsFolderTreeElement.parent){let index=insertionIndexForObjectInListSortedByFunction(this._anonymousScriptsFolderTreeElement,this._resourcesTreeOutline.children,this._boundCompareTreeElements);this._resourcesTreeOutline.insertChild(this._anonymousScriptsFolderTreeElement,index);this._resourcesTreeOutline.disclosureButtons=true;} this._anonymousScriptsFolderTreeElement.representedObject.add(representedObject);let scriptTreeElement=new WI.ScriptTreeElement(representedObject);this._anonymousScriptsFolderTreeElement.appendChild(scriptTreeElement);return scriptTreeElement;} if(representedObject instanceof WI.CSSStyleSheet){if(representedObject.url){return null;} if(!this._anonymousStyleSheetsFolderTreeElement) this._anonymousStyleSheetsFolderTreeElement=new WI.FolderTreeElement(WI.UIString("Anonymous Style Sheets"),new WI.CSSStyleSheetCollection);if(!this._anonymousStyleSheetsFolderTreeElement.parent){let index=insertionIndexForObjectInListSortedByFunction(this._anonymousStyleSheetsFolderTreeElement,this._resourcesTreeOutline.children,this._boundCompareTreeElements);this._resourcesTreeOutline.insertChild(this._anonymousStyleSheetsFolderTreeElement,index);this._resourcesTreeOutline.disclosureButtons=true;} let cssStyleSheetTreeElement=new WI.CSSStyleSheetTreeElement(representedObject);this._anonymousStyleSheetsFolderTreeElement.appendChild(cssStyleSheetTreeElement);return cssStyleSheetTreeElement;} return null;} handleCopyEvent(event) {let selectedTreeElements=new Set(this._callStackTreeOutline.selectedTreeElements);if(!selectedTreeElements.size) return;let treeElement=this._callStackTreeOutline.children[0];const ignoreHidden=true;const skipUnrevealed=true;const stayWithin=null;const dontPopulate=true;while(!treeElement.revealed(ignoreHidden)) treeElement=treeElement.traverseNextTreeElement(skipUnrevealed,stayWithin,dontPopulate);let indentString=WI.indentString();let threads=[];let asyncBoundary=null;function addCallFrame(callFrame){if(asyncBoundary){threads.lastValue.frames.push("--- "+asyncBoundary+" ---");asyncBoundary=null;} let line=callFrame.displayName;let sourceCodeLocation=callFrame.sourceCodeLocation;if(sourceCodeLocation) line+=" ("+sourceCodeLocation.displayLocationString()+")";threads.lastValue.frames.push(line);} for(;treeElement;treeElement=treeElement.traverseNextTreeElement(skipUnrevealed,stayWithin,dontPopulate)){if(treeElement instanceof WI.ThreadTreeElement){threads.push({name:treeElement.mainTitle,frames:[],});asyncBoundary=null;continue;} if(treeElement.isAsyncBoundaryCallFrame||treeElement.isTruncatedBoundaryCallFrame) asyncBoundary=treeElement.mainTitle;if(!selectedTreeElements.has(treeElement)) continue;if(treeElement instanceof WI.CallFrameTreeElement){addCallFrame(treeElement.callFrame);continue;} if(treeElement instanceof WI.BlackboxedGroupTreeElement){for(let callFrame of treeElement.callFrames) addCallFrame(callFrame);continue;}} let multipleFramesSelected=threads.filter(({frames})=>frames.length).length>1;let lines=[];for(let{name,frames}of threads){if(multipleFramesSelected) lines.push(name);for(let frame of frames){let prefix="";if(multipleFramesSelected) prefix=indentString;lines.push(prefix+frame);}} if(!lines.length) return;setTimeout(()=>{InspectorFrontendHost.copyText(lines.join("\n"));});event.stop();} createContentTreeOutline(options={}) {let treeOutline=super.createContentTreeOutline(options);treeOutline.addEventListener(WI.TreeOutline.Event.ElementRevealed,function(event){let treeElement=event.data.element;let detailsSections=[this._pauseReasonSection,this._callStackSection,this._breakpointsSection,this._localOverridesSection,this._consoleSnippetsSection,];let detailsSection=detailsSections.find((detailsSection)=>detailsSection.element.contains(treeElement.listItemElement));if(!detailsSection) return; let offset=detailsSection.headerElement.totalOffsetBottom-treeElement.listItemElement.totalOffsetTop;if(offset>0) this.scrollElement.scrollBy(0,-offset);},this);return treeOutline;} resetFilter() {this._resourceTypeScopeBar.resetToDefault();super.resetFilter();} hasCustomFilters() {let selectedScopeBarItem=this._resourceTypeScopeBar.selectedItems[0];return selectedScopeBarItem&&selectedScopeBarItem!==this._resourceTypeScopeBar.defaultItem;} matchTreeElementAgainstCustomFilters(treeElement,flags) {if(treeElement.treeOutline!==this._resourcesTreeOutline) return true;let selectedScopeBarItem=this._resourceTypeScopeBar.selectedItems[0];if(!selectedScopeBarItem||selectedScopeBarItem===this._resourceTypeScopeBar.defaultItem) return true;if(treeElement instanceof WI.FolderTreeElement||treeElement instanceof WI.OriginTreeElement) return false;if(treeElement instanceof WI.IssueTreeElement) treeElement=treeElement.parent;function match() {if(treeElement instanceof WI.FrameTreeElement) return selectedScopeBarItem[WI.SourcesNavigationSidebarPanel.ResourceTypeSymbol]===WI.Resource.Type.Document;if(treeElement instanceof WI.ScriptTreeElement) return selectedScopeBarItem[WI.SourcesNavigationSidebarPanel.ResourceTypeSymbol]===WI.Resource.Type.Script;if(treeElement instanceof WI.CSSStyleSheetTreeElement) return selectedScopeBarItem[WI.SourcesNavigationSidebarPanel.ResourceTypeSymbol]===WI.Resource.Type.StyleSheet;if(!(treeElement instanceof WI.ResourceTreeElement)) return false;return treeElement.resource.type===selectedScopeBarItem[WI.SourcesNavigationSidebarPanel.ResourceTypeSymbol];} let matched=match();if(matched) flags.expandTreeElement=true;return matched;} willDismissPopover(popover) {if(popover instanceof WI.LocalResourceOverridePopover){this._willDismissLocalOverridePopover(popover);return;} if(popover instanceof WI.InputPopover){this._willDismissConsoleSnippetPopover(popover);return;} if(popover instanceof WI.EventBreakpointPopover){this._willDismissEventBreakpointPopover(popover);return;} if(popover instanceof WI.URLBreakpointPopover){this._willDismissURLBreakpointPopover(popover);return;} if(popover instanceof WI.SymbolicBreakpointPopover){this._willDismissSymbolicBreakpointPopover(popover);return;}} _willDismissLocalOverridePopover(popover) {let serializedData=popover.serializedData;if(!serializedData){if(!this._localOverridesTreeOutline.children.length) this._localOverridesContainer.hidden=true;InspectorFrontendHost.beep();return;} if(WI.networkManager.localResourceOverrides.some((existingOverride)=>existingOverride.equals(serializedData))){InspectorFrontendHost.beep();return;} let localResourceOverride=WI.LocalResourceOverride.create(serializedData.url,serializedData.type,serializedData);WI.networkManager.addLocalResourceOverride(localResourceOverride);WI.showLocalResourceOverride(localResourceOverride);} _willDismissConsoleSnippetPopover(popover) {let title=popover.value?.trim();if(!title){if(!this._consoleSnippetsTreeOutline.children.length) this._consoleSnippetsContainer.hidden=true;InspectorFrontendHost.beep();return;} if(WI.consoleManager.snippets.some((consoleSnippet)=>consoleSnippet.title===title)){InspectorFrontendHost.beep();return;} let consoleSnippet=WI.ConsoleSnippet.createDefaultWithTitle(title);WI.consoleManager.addSnippet(consoleSnippet);const cookie=null;WI.showRepresentedObject(consoleSnippet,cookie,{ignoreNetworkTab:true,ignoreSearchTab:true,});} _willDismissEventBreakpointPopover(popover) {let breakpoint=popover.breakpoint;if(!breakpoint){InspectorFrontendHost.beep();return;} if(!WI.domDebuggerManager.addEventBreakpoint(breakpoint)) InspectorFrontendHost.beep();} _willDismissURLBreakpointPopover(popover) {let breakpoint=popover.breakpoint;if(!breakpoint){InspectorFrontendHost.beep();return;} if(!WI.domDebuggerManager.addURLBreakpoint(breakpoint)) InspectorFrontendHost.beep();} _willDismissSymbolicBreakpointPopover(popover) {let breakpoint=popover.breakpoint;if(!breakpoint){InspectorFrontendHost.beep();return;} if(!WI.debuggerManager.addSymbolicBreakpoint(breakpoint)) InspectorFrontendHost.beep();} _filterByResourcesWithIssues(treeElement) {if(treeElement.treeOutline!==this._resourcesTreeOutline) return true;if(treeElement instanceof WI.IssueTreeElement) return true;if(treeElement.hasChildren){for(let child of treeElement.children){if(child instanceof WI.IssueTreeElement) return true;}} return false;} _compareTreeElements(a,b) {const rankFunctions=[(treeElement)=>treeElement instanceof WI.ScriptTreeElement&&treeElement.representedObject===WI.networkManager.bootstrapScript,(treeElement)=>treeElement instanceof WI.LocalResourceOverrideTreeElement,(treeElement)=>treeElement instanceof WI.ScriptTreeElement&&treeElement.representedObject instanceof WI.ConsoleSnippet,(treeElement)=>treeElement instanceof WI.CSSStyleSheetTreeElement&&treeElement.representedObject.isInspectorStyleSheet(),(treeElement)=>treeElement===this._mainFrameTreeElement,(treeElement)=>treeElement instanceof WI.FrameTreeElement,(treeElement)=>treeElement instanceof WI.OriginTreeElement,(treeElement)=>{return treeElement!==this._extensionScriptsFolderTreeElement&&treeElement!==this._extensionStyleSheetsFolderTreeElement&&treeElement!==this._extraScriptsFolderTreeElement&&treeElement!==this._extraStyleSheetsFolderTreeElement&&treeElement!==this._anonymousScriptsFolderTreeElement&&treeElement!==this._anonymousStyleSheetsFolderTreeElement;},(treeElement)=>treeElement===this._extensionScriptsFolderTreeElement,(treeElement)=>treeElement===this._extensionStyleSheetsFolderTreeElement,(treeElement)=>treeElement===this._extraScriptsFolderTreeElement,(treeElement)=>treeElement===this._extraStyleSheetsFolderTreeElement,(treeElement)=>treeElement===this._anonymousScriptsFolderTreeElement,(treeElement)=>treeElement===this._anonymousStyleSheetsFolderTreeElement,];let aRank=rankFunctions.findIndex((rankFunction)=>rankFunction(a));let bRank=rankFunctions.findIndex((rankFunction)=>rankFunction(b));if((aRank>=0&&bRank<0)||aRank=0&&aRank<0)||bRank{if(this._resourcesTreeOutline.selectedTreeElement) return;let currentContentView=this.contentBrowser.currentContentView;let treeElement=currentContentView?this.treeElementForRepresentedObject(currentContentView.representedObject):null;if(!treeElement) treeElement=this.treeElementForRepresentedObject(WI.networkManager.mainFrame);this.showDefaultContentViewForTreeElement(treeElement);});} _addTarget(target) {let treeElement=new WI.ThreadTreeElement(target);this._callStackTreeOutline.appendChild(treeElement);if(target===WI.mainTarget) this._mainTargetTreeElement=treeElement;this._updateCallStackTreeOutline();} _findCallStackTargetTreeElement(target) {for(let child of this._callStackTreeOutline.children){if(child.target===target) return child;} return null;} _updateCallStackTreeOutline() {let singleThreadShowing=WI.targets.length<=1;this._callStackTreeOutline.element.classList.toggle("single-thread",singleThreadShowing);if(this._mainTargetTreeElement) this._mainTargetTreeElement.selectable=!singleThreadShowing;} _addResource(resource) {if(WI.settings.resourceGroupingMode.value===WI.Resource.GroupingMode.Path){if(!this._mainFrameTreeElement||this._resourcesTreeOutline.findTreeElement(resource)) return;let parentTreeElement=null;if(resource instanceof WI.CSSStyleSheet){parentTreeElement=this._resourcesTreeOutline.findTreeElement(resource.parentFrame.mainResource);} if(!parentTreeElement){let origin=resource.urlComponents.origin;if(origin){let originTreeElement=this._originTreeElementMap.get(origin);if(!originTreeElement){let representedObject=resource.type===WI.Resource.Type.Document?resource.parentFrame:null;originTreeElement=new WI.OriginTreeElement(origin,representedObject,{hasChildren:true});this._originTreeElementMap.set(origin,originTreeElement);let index=insertionIndexForObjectInListSortedByFunction(originTreeElement,this._resourcesTreeOutline.children,this._boundCompareTreeElements);this._resourcesTreeOutline.insertChild(originTreeElement,index);} let subpath=resource.urlComponents.path;if(subpath&&subpath[0]==="/") subpath=subpath.substring(1);parentTreeElement=originTreeElement.createFoldersAsNeededForSubpath(subpath,this._boundCompareTreeElements);}else parentTreeElement=this._resourcesTreeOutline;} let resourceTreeElement=null;if(resource instanceof WI.CSSStyleSheet) resourceTreeElement=new WI.CSSStyleSheetTreeElement(resource);else{let constructor=resource.type===WI.Resource.Type.WebSocket?WI.WebSocketResourceTreeElement:WI.ResourceTreeElement;resourceTreeElement=new constructor(resource,resource,{allowDirectoryAsName:true,hideOrigin:true});} let index=insertionIndexForObjectInListSortedByFunction(resourceTreeElement,parentTreeElement.children,this._boundCompareTreeElements);parentTreeElement.insertChild(resourceTreeElement,index);} if(resource.type===WI.Resource.Type.Document||resource.type===WI.Resource.Type.Script){this._addBreakpointsForSourceCode(resource);this._addIssuesForSourceCode(resource);}} _addResourcesRecursivelyForFrame(frame) {this._addResource(frame.mainResource);for(let resource of frame.resourceCollection) this._addResource(resource);for(let childFrame of frame.childFrameCollection) this._addResourcesRecursivelyForFrame(childFrame);if(WI.settings.resourceGroupingMode.value===WI.Resource.GroupingMode.Path){for(let styleSheet of WI.cssManager.inspectorStyleSheetsForFrame(frame)) this._addResource(styleSheet);}} _addStyleSheet(styleSheet) { if(styleSheet.anonymous) return;let parentTreeElement=null;if(WI.browserManager.isExtensionScheme(styleSheet.urlComponents.scheme)){if(!this._extensionStyleSheetsFolderTreeElement) this._extensionStyleSheetsFolderTreeElement=new WI.FolderTreeElement(WI.UIString("Extension Style Sheets"),new WI.CSSStyleSheetCollection);parentTreeElement=this._extensionStyleSheetsFolderTreeElement;}else{if(!this._extraStyleSheetsFolderTreeElement) this._extraStyleSheetsFolderTreeElement=new WI.FolderTreeElement(WI.UIString("Extra Style Sheets"),new WI.CSSStyleSheetCollection);parentTreeElement=this._extraStyleSheetsFolderTreeElement;} if(!parentTreeElement.parent){let index=insertionIndexForObjectInListSortedByFunction(parentTreeElement,this._resourcesTreeOutline.children,this._boundCompareTreeElements);this._resourcesTreeOutline.insertChild(parentTreeElement,index);this._resourcesTreeOutline.disclosureButtons=true;} let treeElement=new WI.CSSStyleSheetTreeElement(styleSheet);let index=insertionIndexForObjectInListSortedByFunction(treeElement,parentTreeElement.children,this._boundCompareTreeElements);parentTreeElement.insertChild(treeElement,index);} _addScript(script) { if(script.anonymous) return;if(WI.sharedApp.debuggableType!==WI.DebuggableType.JavaScript&&WI.sharedApp.debuggableType!==WI.DebuggableType.ITML){if(script.target.type===WI.TargetType.Worker){if(script.isMainResource()){this._addWorkerTargetWithMainResource(script.target);this._addBreakpointsForSourceCode(script);this._addIssuesForSourceCode(script);} this._resourcesTreeOutline.disclosureButtons=true;return;}} if(script.resource||script.dynamicallyAddedScriptElement) return;let scriptTreeElement=new WI.ScriptTreeElement(script);if(!script.injected&&WI.SourcesNavigationSidebarPanel.shouldPlaceResourcesAtTopLevel()){let index=insertionIndexForObjectInListSortedByFunction(scriptTreeElement,this._resourcesTreeOutline.children,this._boundCompareTreeElements);this._resourcesTreeOutline.insertChild(scriptTreeElement,index);}else{let parentFolderTreeElement=null;if(WI.browserManager.isExtensionScheme(script.urlComponents.scheme)){if(!this._extensionScriptsFolderTreeElement){let collection=new WI.ScriptCollection;this._extensionScriptsFolderTreeElement=new WI.FolderTreeElement(WI.UIString("Extension Scripts"),collection);} parentFolderTreeElement=this._extensionScriptsFolderTreeElement;}else{if(!this._extraScriptsFolderTreeElement){let collection=new WI.ScriptCollection;this._extraScriptsFolderTreeElement=new WI.FolderTreeElement(WI.UIString("Extra Scripts"),collection);} parentFolderTreeElement=this._extraScriptsFolderTreeElement;} if(parentFolderTreeElement) parentFolderTreeElement.representedObject.add(script);if(!parentFolderTreeElement.parent){let index=insertionIndexForObjectInListSortedByFunction(parentFolderTreeElement,this._resourcesTreeOutline.children,this._boundCompareTreeElements);this._resourcesTreeOutline.insertChild(parentFolderTreeElement,index);this._resourcesTreeOutline.disclosureButtons=true;} parentFolderTreeElement.appendChild(scriptTreeElement);} this._addBreakpointsForSourceCode(script);this._addIssuesForSourceCode(script);} _addWorkerTargetWithMainResource(target) {if(this._workerTargetTreeElementMap.has(target)) return;let targetTreeElement=new WI.WorkerTreeElement(target);this._workerTargetTreeElementMap.set(target,targetTreeElement);let index=insertionIndexForObjectInListSortedByFunction(targetTreeElement,this._resourcesTreeOutline.children,this._boundCompareTreeElements);this._resourcesTreeOutline.insertChild(targetTreeElement,index);} _addDebuggerTreeElementForSourceCode(sourceCode) {let treeElement=this._breakpointsTreeOutline.findTreeElement(sourceCode);if(!treeElement){if(sourceCode instanceof WI.SourceMapResource) treeElement=new WI.SourceMapResourceTreeElement(sourceCode);else if(sourceCode instanceof WI.Resource) treeElement=new WI.ResourceTreeElement(sourceCode);else if(sourceCode instanceof WI.Script) treeElement=new WI.ScriptTreeElement(sourceCode);} if(!treeElement){console.error("Unknown sourceCode instance",sourceCode);return null;} if(!treeElement.parent){treeElement.hasChildren=false;treeElement.expand();this._insertDebuggerTreeElement(treeElement,this._breakpointsTreeOutline);} return treeElement;} _insertDebuggerTreeElement(treeElement,parentTreeElement) {let comparator=(a,b)=>{const rankFunctions=[(treeElement)=>treeElement.representedObject===WI.debuggerManager.debuggerStatementsBreakpoint,(treeElement)=>treeElement.representedObject===WI.debuggerManager.allExceptionsBreakpoint,(treeElement)=>treeElement.representedObject===WI.debuggerManager.uncaughtExceptionsBreakpoint,(treeElement)=>treeElement.representedObject===WI.debuggerManager.assertionFailuresBreakpoint,(treeElement)=>treeElement instanceof WI.ResourceTreeElement||treeElement instanceof WI.ScriptTreeElement||(treeElement instanceof WI.JavaScriptBreakpointTreeElement&&!treeElement.representedObject.special),(treeElement)=>treeElement instanceof WI.SymbolicBreakpointTreeElement,(treeElement)=>treeElement.representedObject===WI.debuggerManager.allMicrotasksBreakpoint,(treeElement)=>treeElement.representedObject===WI.domDebuggerManager.allAnimationFramesBreakpoint,(treeElement)=>treeElement.representedObject===WI.domDebuggerManager.allTimeoutsBreakpoint,(treeElement)=>treeElement.representedObject===WI.domDebuggerManager.allIntervalsBreakpoint,(treeElement)=>treeElement.representedObject===WI.domDebuggerManager.allListenersBreakpoint,(treeElement)=>treeElement instanceof WI.EventBreakpointTreeElement,(treeElement)=>treeElement instanceof WI.DOMNodeTreeElement,(treeElement)=>treeElement.representedObject===SourcesNavigationSidebarPanel.__windowEventTargetRepresentedObject,(treeElement)=>treeElement instanceof WI.DOMBreakpointTreeElement,(treeElement)=>treeElement.representedObject===WI.domDebuggerManager.allRequestsBreakpoint,(treeElement)=>treeElement instanceof WI.URLBreakpointTreeElement,];let aRank=rankFunctions.findIndex((rankFunction)=>rankFunction(a));let bRank=rankFunctions.findIndex((rankFunction)=>rankFunction(b));if(aRank>=0&&bRank>=0){if(aRank{let domNodeTreeElement=this._breakpointsTreeOutline.findTreeElement(domNode);if(!domNodeTreeElement){domNodeTreeElement=new WI.DOMNodeTreeElement(domNode);this._insertDebuggerTreeElement(domNodeTreeElement,this._breakpointsTreeOutline);} return domNodeTreeElement;};if(breakpoint===WI.debuggerManager.debuggerStatementsBreakpoint) options.classNames=["debugger-statement"];else if(breakpoint===WI.debuggerManager.allExceptionsBreakpoint) options.classNames=["exception"];else if(breakpoint===WI.debuggerManager.uncaughtExceptionsBreakpoint) options.classNames=["exception"];else if(breakpoint===WI.debuggerManager.assertionFailuresBreakpoint) options.classNames=["assertion"];else if(breakpoint===WI.debuggerManager.allMicrotasksBreakpoint) options.classNames=["microtask"];else if(breakpoint instanceof WI.DOMBreakpoint){if(!breakpoint.domNode) return null;constructor=WI.DOMBreakpointTreeElement;parentTreeElement=getDOMNodeTreeElement(breakpoint.domNode);}else if(breakpoint instanceof WI.EventBreakpoint){constructor=WI.EventBreakpointTreeElement;if(breakpoint.eventListener){let eventTargetTreeElement=null;if(breakpoint.eventListener.onWindow){if(!SourcesNavigationSidebarPanel.__windowEventTargetRepresentedObject) SourcesNavigationSidebarPanel.__windowEventTargetRepresentedObject={__window:true};eventTargetTreeElement=this._breakpointsTreeOutline.findTreeElement(SourcesNavigationSidebarPanel.__windowEventTargetRepresentedObject);if(!eventTargetTreeElement){const subtitle=null;eventTargetTreeElement=new WI.GeneralTreeElement(["event-target-window"],WI.unlocalizedString("window"),subtitle,SourcesNavigationSidebarPanel.__windowEventTargetRepresentedObject);this._insertDebuggerTreeElement(eventTargetTreeElement,this._breakpointsTreeOutline);}}else if(breakpoint.eventListener.node) eventTargetTreeElement=getDOMNodeTreeElement(breakpoint.eventListener.node);if(eventTargetTreeElement) parentTreeElement=eventTargetTreeElement;}}else if(breakpoint instanceof WI.URLBreakpoint) constructor=WI.URLBreakpointTreeElement;else if(breakpoint instanceof WI.SymbolicBreakpoint) constructor=WI.SymbolicBreakpointTreeElement;else{let sourceCode=breakpoint.sourceCodeLocation&&breakpoint.sourceCodeLocation.displaySourceCode;if(!sourceCode) return null;parentTreeElement=this._addDebuggerTreeElementForSourceCode(sourceCode); if(breakpoint.disabled) breakpoint.resolved=true;} let breakpointTreeElement=new constructor(breakpoint,options);this._insertDebuggerTreeElement(breakpointTreeElement,parentTreeElement);if(parentTreeElement.children.length===1) parentTreeElement.expand();return breakpointTreeElement;} _removeBreakpoint(breakpoint) {if(this._pauseReasonTreeOutline){let pauseReasonBreakpointTreeElement=this._pauseReasonTreeOutline.findTreeElement(breakpoint);if(pauseReasonBreakpointTreeElement) pauseReasonBreakpointTreeElement.status=null;} let breakpointTreeElement=this._breakpointsTreeOutline.findTreeElement(breakpoint);if(!breakpointTreeElement) return;this._removeDebuggerTreeElement(breakpointTreeElement);} _removeAllBreakpoints(breakpoints) {for(let breakpoint of breakpoints){if(breakpoint.removable) WI.debuggerManager.removeBreakpoint(breakpoint);}} _toggleAllBreakpoints(breakpoints,disabled) {for(let breakpoint of breakpoints) breakpoint.disabled=disabled;} _breakpointsBeneathTreeElement(treeElement) {if(!(treeElement instanceof WI.ResourceTreeElement)&&!(treeElement instanceof WI.ScriptTreeElement)) return[];let breakpoints=[];for(let child of treeElement.children){let breakpoint=child.breakpoint;if(breakpoint) breakpoints.push(breakpoint);} return breakpoints;} _addIssue(issueMessage,sourceCode) {let issueTreeElement=this._resourcesTreeOutline.findTreeElement(issueMessage);if(!issueTreeElement){let parentTreeElement=this._resourcesTreeOutline.findTreeElement(sourceCode||issueMessage.sourceCodeLocation.sourceCode);if(!parentTreeElement) return null;issueTreeElement=new WI.IssueTreeElement(issueMessage);parentTreeElement.insertChild(issueTreeElement,insertionIndexForObjectInListSortedByFunction(issueTreeElement,parentTreeElement.children,this._compareJavaScriptBreakpointTreeElements));if(parentTreeElement.children.length===1) parentTreeElement.expand();} return issueTreeElement;} _removeDebuggerTreeElement(debuggerTreeElement) { if(!debuggerTreeElement.__deletedViaDeleteKeyboardShortcut) debuggerTreeElement.deselect();let parentTreeElement=debuggerTreeElement.parent;parentTreeElement.removeChild(debuggerTreeElement);if(parentTreeElement.children.length||parentTreeElement===this._breakpointsTreeOutline) return;parentTreeElement.treeOutline.removeChild(parentTreeElement);} _addBreakpointsForSourceCode(sourceCode) {for(let breakpoint of WI.debuggerManager.breakpointsForSourceCode(sourceCode)) this._addBreakpoint(breakpoint);} _addIssuesForSourceCode(sourceCode) {for(let issue of WI.consoleManager.issuesForSourceCode(sourceCode)) this._addIssue(issue,sourceCode);} _addLocalOverride(localOverride) {if(this._localOverridesTreeOutline.findTreeElement(localOverride)) return;let parentTreeElement=this._localOverridesTreeOutline;let localOverrideTreeElement=null;if(localOverride===WI.networkManager.bootstrapScript) localOverrideTreeElement=new WI.BootstrapScriptTreeElement(localOverride);else if(localOverride instanceof WI.LocalResourceOverride) localOverrideTreeElement=new WI.LocalResourceOverrideTreeElement(localOverride);let index=insertionIndexForObjectInListSortedByFunction(localOverrideTreeElement,parentTreeElement.children,this._boundCompareTreeElements);parentTreeElement.insertChild(localOverrideTreeElement,index);this._localOverridesRow.hideEmptyMessage();this._localOverridesRow.element.appendChild(this._localOverridesTreeOutline.element);this._localOverridesContainer.hidden=false;} _removeResourceOverride(localOverride) {let resourceTreeElement=this._localOverridesTreeOutline.findTreeElement(localOverride);if(!resourceTreeElement) return;let wasSelected=resourceTreeElement.selected;let parentTreeElement=this._localOverridesTreeOutline;parentTreeElement.removeChild(resourceTreeElement);if(!parentTreeElement.children.length){this._localOverridesContainer.hidden=true;if(wasSelected&&WI.networkManager.mainFrame&&WI.networkManager.mainFrame.mainResource) WI.showRepresentedObject(WI.networkManager.mainFrame.mainResource);}} _addConsoleSnippet(consoleSnippet) {if(this._consoleSnippetsTreeOutline.findTreeElement(consoleSnippet)) return;let parentTreeElement=this._consoleSnippetsTreeOutline;let consoleSnippetTreeElement=new WI.ConsoleSnippetTreeElement(consoleSnippet);let index=insertionIndexForObjectInListSortedByFunction(consoleSnippetTreeElement,parentTreeElement.children,this._boundCompareTreeElements);parentTreeElement.insertChild(consoleSnippetTreeElement,index);this._consoleSnippetsRow.hideEmptyMessage();this._consoleSnippetsRow.element.appendChild(this._consoleSnippetsTreeOutline.element);this._consoleSnippetsContainer.hidden=false;} _removeConsoleSnippet(consoleSnippet) {let consoleSnippetTreeElement=this._consoleSnippetsTreeOutline.findTreeElement(consoleSnippet);if(!consoleSnippetTreeElement) return;let wasSelected=consoleSnippetTreeElement.selected;let parentTreeElement=this._consoleSnippetsTreeOutline;parentTreeElement.removeChild(consoleSnippetTreeElement);if(!parentTreeElement.children.length){this._consoleSnippetsContainer.hidden=true;if(wasSelected&&WI.networkManager.mainFrame&&WI.networkManager.mainFrame.mainResource) WI.showRepresentedObject(WI.networkManager.mainFrame.mainResource);}} _updateTemporarilyDisabledBreakpointsButtons() {let breakpointsDisabledTemporarily=WI.debuggerManager.breakpointsDisabledTemporarily;this._debuggerBreakpointsButtonItem.enabled=!breakpointsDisabledTemporarily;this._debuggerPauseResumeButtonItem.enabled=!breakpointsDisabledTemporarily;} _updateBreakpointsDisabledBanner() {if(!WI.debuggerManager.breakpointsEnabled&&!this._timelineRecordingWarningElement&&!this._auditTestWarningElement){if(!this._breakpointsDisabledWarningElement){let enableBreakpointsButton=document.createElement("button");enableBreakpointsButton.textContent=WI.UIString("Enable Breakpoints");enableBreakpointsButton.addEventListener("click",()=>{WI.debuggerToggleBreakpoints();});this._breakpointsDisabledWarningElement=document.createElement("div");this._breakpointsDisabledWarningElement.classList.add("warning-banner");this._breakpointsDisabledWarningElement.append(WI.UIString("Breakpoints disabled"),document.createElement("br"),enableBreakpointsButton);} this.contentView.element.insertBefore(this._breakpointsDisabledWarningElement,this.contentView.element.firstChild);}else if(this._breakpointsDisabledWarningElement){this._breakpointsDisabledWarningElement.remove();this._breakpointsDisabledWarningElement=null;}} _updatePauseReason() {this._pauseReasonTreeOutline=null;this._updatePauseReasonGotoArrow();let target=WI.debuggerManager.activeCallFrame.target;let targetData=WI.debuggerManager.dataForTarget(target);return this._updatePauseReasonSection(target,targetData.pauseReason,targetData.pauseData);} _updatePauseReasonGotoArrow() {this._pauseReasonLinkContainerElement.removeChildren();let activeCallFrame=WI.debuggerManager.activeCallFrame;if(!activeCallFrame) return;let sourceCodeLocation=activeCallFrame.sourceCodeLocation;if(!sourceCodeLocation) return;const options={useGoToArrowButton:true,};let linkElement=WI.createSourceCodeLocationLink(sourceCodeLocation,options);this._pauseReasonLinkContainerElement.appendChild(linkElement);} _updatePauseReasonSection(target,pauseReason,pauseData) {switch(pauseReason){case WI.DebuggerManager.PauseReason.AnimationFrame:if(!this._updatePauseReasonForBreakpoint(WI.domDebuggerManager.allAnimationFramesBreakpoint,WI.UIString("requestAnimationFrame Fired"))){break;} return true;case WI.DebuggerManager.PauseReason.Assertion:{let title=pauseData?.message?this._createBreakpointPauseReasonTitleWithTooltip(WI.UIString("Assertion Failed: %s"),pauseData.message):WI.UIString("Assertion Failed");if(!this._updatePauseReasonForBreakpoint(WI.debuggerManager.assertionFailuresBreakpoint,title)){break;} return true;} case WI.DebuggerManager.PauseReason.BlackboxedScript:{if(pauseData) this._updatePauseReasonSection(target,WI.DebuggerManager.pauseReasonFromPayload(pauseData.originalReason),pauseData.originalData);let blackboxReasonTextRow=new WI.DetailsSectionTextRow(WI.UIString("Deferred pause from blackboxed script"));blackboxReasonTextRow.__blackboxReason=true;let existingRows=this._pauseReasonGroup.rows.filter((row)=>!row.__blackboxReason);this._pauseReasonGroup.rows=[blackboxReasonTextRow,...existingRows];return true;} case WI.DebuggerManager.PauseReason.Breakpoint:{if(!pauseData||!pauseData.breakpointId) break;let breakpoint=WI.debuggerManager.breakpointForIdentifier(pauseData.breakpointId);if(!breakpoint) break;if(!this._updatePauseReasonForBreakpoint(breakpoint,WI.UIString("Triggered Breakpoint"))){break;} return true;} case WI.DebuggerManager.PauseReason.CSPViolation:{if(!pauseData) break;let breakpoint=WI.debuggerManager.allExceptionsBreakpoint||WI.debuggerManager.uncaughtExceptionsBreakpoint;let titleElement=this._createBreakpointPauseReasonTitleWithTooltip(WI.UIString("Content Security Policy violation of directive: %s"),pauseData.directive);if(!this._updatePauseReasonForBreakpoint(breakpoint,titleElement)){break;} return true;} case WI.DebuggerManager.PauseReason.DebuggerStatement:if(!WI.JavaScriptBreakpoint.supportsDebuggerStatements()){this._pauseReasonTextRow.text=WI.UIString("Debugger Statement");this._pauseReasonGroup.rows=[this._pauseReasonTextRow];return true;} if(!this._updatePauseReasonForBreakpoint(WI.debuggerManager.debuggerStatementsBreakpoint,WI.UIString("Debugger Statement"))){break;} return true;case WI.DebuggerManager.PauseReason.DOM:{if(!pauseData||!pauseData.nodeId) break;let domNode=WI.domManager.nodeForId(pauseData.nodeId);let domBreakpoints=WI.domDebuggerManager.domBreakpointsForNode(domNode);let domBreakpoint;for(let breakpoint of domBreakpoints){if(breakpoint.type===pauseData.type){domBreakpoint=breakpoint;break;}} if(!domBreakpoint) break;if(!this._updatePauseReasonForBreakpoint(domBreakpoint,WI.DOMBreakpoint.displayNameForType(domBreakpoint.type))){break;} let ownerElementRow=new WI.DetailsSectionSimpleRow(WI.UIString("Element"),WI.linkifyNodeReference(domNode));this._pauseReasonGroup.rows=this._pauseReasonGroup.rows.concat(ownerElementRow);let updateTargetDescription=(nodeId)=>{if(!nodeId) return;let node=WI.domManager.nodeForId(nodeId);if(!node) return;let fragment=document.createDocumentFragment();let description=null;switch(domBreakpoint.type){case WI.DOMBreakpoint.Type.SubtreeModified:description=pauseData.insertion?WI.UIString("Child added to "):WI.UIString("Removed descendant ");break;case WI.DOMBreakpoint.Type.NodeRemoved:description=WI.UIString("Removed ancestor ");break;} fragment.append(description,WI.linkifyNodeReference(node));let targetDescriptionRow=new WI.DetailsSectionSimpleRow(WI.UIString("Details"),fragment);targetDescriptionRow.element.classList.add("target-description");this._pauseReasonGroup.rows=this._pauseReasonGroup.rows.concat(targetDescriptionRow);};if(pauseData.targetNodeId){updateTargetDescription(pauseData.targetNodeId);}else if(pauseData.targetNode){let remoteObject=WI.RemoteObject.fromPayload(pauseData.targetNode,target);remoteObject.pushNodeToFrontend(updateTargetDescription);} return true;} case WI.DebuggerManager.PauseReason.Listener:case WI.DebuggerManager.PauseReason.EventListener:{if(!pauseData) break;let eventBreakpoint=null;if(pauseData.eventListenerId) eventBreakpoint=WI.domManager.breakpointForEventListenerId(pauseData.eventListenerId);if(!eventBreakpoint) eventBreakpoint=WI.domDebuggerManager.listenerBreakpointsForEventName(pauseData.eventName)[0];if(!eventBreakpoint) break;let titleElement=this._createBreakpointPauseReasonTitleWithTooltip(WI.UIString("\u201C%s\u201D Event Fired"),pauseData.eventName);if(!this._updatePauseReasonForBreakpoint(eventBreakpoint,titleElement)){break;} let eventListener=eventBreakpoint.eventListener;if(eventListener){let value=null;if(eventListener.onWindow) value=WI.unlocalizedString("window");else if(eventListener.node) value=WI.linkifyNodeReference(eventListener.node);if(value) this._pauseReasonGroup.rows=this._pauseReasonGroup.rows.concat(new WI.DetailsSectionSimpleRow(WI.UIString("Target"),value));} return true;} case WI.DebuggerManager.PauseReason.Exception:{if(!pauseData) break;let data=WI.RemoteObject.fromPayload(pauseData,target);let breakpoint=WI.debuggerManager.allExceptionsBreakpoint||WI.debuggerManager.uncaughtExceptionsBreakpoint;let titleElement=this._createBreakpointPauseReasonTitleWithTooltip(WI.UIString("Exception with thrown value: %s"),data.description);if(!this._updatePauseReasonForBreakpoint(breakpoint,titleElement)){break;} return true;} case WI.DebuggerManager.PauseReason.FunctionCall:{if(!pauseData) break;let symbolicBreakpoint=WI.debuggerManager.symbolicBreakpointsForSymbol(pauseData.name)[0];if(!symbolicBreakpoint) break;const format=WI.UIString("Calling Function \u201C%s\u201D","Calling Function \u201C%s\u201D @ Sources Navigation Sidebar Panel","Label shown when JavaScript execution is paused due to a symbolic breakpoint.");let titleElement=this._createBreakpointPauseReasonTitleWithTooltip(format,pauseData.name);if(!this._updatePauseReasonForBreakpoint(symbolicBreakpoint,titleElement)){break;} return true;} case WI.DebuggerManager.PauseReason.Interval:if(!this._updatePauseReasonForBreakpoint(WI.debuggerManager.allIntervalsBreakpoint,WI.UIString("setInterval Fired"))){break;} return true;case WI.DebuggerManager.PauseReason.Microtask:if(!this._updatePauseReasonForBreakpoint(WI.debuggerManager.allMicrotasksBreakpoint,WI.UIString("Microtask Fired"))){break;} return true;case WI.DebuggerManager.PauseReason.PauseOnNextStatement:this._pauseReasonTextRow.text=WI.UIString("Immediate Pause Requested");this._pauseReasonGroup.rows=[this._pauseReasonTextRow];return true;case WI.DebuggerManager.PauseReason.Timer:{if(!pauseData) break;switch(pauseData.eventName){case"setTimeout":if(!this._updatePauseReasonForBreakpoint(WI.domDebuggerManager.allTimeoutsBreakpoint,WI.UIString("setTimeout Fired"))) break;return true;case"setInterval":if(!this._updatePauseReasonForBreakpoint(WI.domDebuggerManager.allIntervalsBreakpoint,WI.UIString("setInterval Fired"))) break;return true;} break;} case WI.DebuggerManager.PauseReason.Timeout:this._updatePauseReasonForBreakpoint(WI.domDebuggerManager.allTimeoutsBreakpoint,WI.UIString("setTimeout Fired"));return true;case WI.DebuggerManager.PauseReason.URL:{if(!pauseData) break;let urlBreakpoint=null;if(pauseData.breakpointURL) urlBreakpoint=WI.domDebuggerManager.urlBreakpointForURL(pauseData.breakpointURL);else{urlBreakpoint=WI.domDebuggerManager.allRequestsBreakpoint;} if(!urlBreakpoint) break;let titleElement=this._createBreakpointPauseReasonTitleWithTooltip(WI.UIString("Requesting \u201C%s\u201D"),pauseData.url);if(!this._updatePauseReasonForBreakpoint(urlBreakpoint,titleElement)){break;} return true;} case WI.DebuggerManager.PauseReason.Other:console.error("Paused for unknown reason. We should always have a reason.");break;} return false;} _updatePauseReasonForBreakpoint(breakpoint,title) {let Constructor=null;if(breakpoint instanceof WI.JavaScriptBreakpoint) Constructor=WI.JavaScriptBreakpointTreeElement;else if(breakpoint instanceof WI.DOMBreakpoint) Constructor=WI.DOMBreakpointTreeElement;else if(breakpoint instanceof WI.EventBreakpoint) Constructor=WI.EventBreakpointTreeElement;else if(breakpoint instanceof WI.URLBreakpoint) Constructor=WI.URLBreakpointTreeElement;else if(breakpoint instanceof WI.SymbolicBreakpoint) Constructor=WI.SymbolicBreakpointTreeElement;if(!Constructor) return false;this._pauseReasonTreeOutline=this.createContentTreeOutline({suppressFiltering:true});this._pauseReasonTreeOutline.addEventListener(WI.TreeOutline.Event.SelectionDidChange,this._handleTreeSelectionDidChange,this);let breakpointTreeElement=new Constructor(breakpoint,{classNames:["paused"],title,}) this._pauseReasonTreeOutline.appendChild(breakpointTreeElement);let breakpointRow=new WI.DetailsSectionRow;breakpointRow.element.appendChild(this._pauseReasonTreeOutline.element);this._pauseReasonGroup.rows=[breakpointRow];return true;} _createBreakpointPauseReasonTitleWithTooltip(format,title) {let titleElement=document.createElement("span");titleElement.textContent=format.format(title);titleElement.title=title;return titleElement;} _handleResourceGroupingModeScopeBarSelectionChanged(event) {let selectedScopeBarItem=this._resourceGroupingModeScopeBar.selectedItems[0];WI.settings.resourceGroupingMode.value=selectedScopeBarItem[SourcesNavigationSidebarPanel.ResourceGroupingModeSymbol]||WI.Resource.GroupingMode.Type;} _handleResourceTypeScopeBarSelectionChanged(event) {this.updateFilter();} _handleTreeSelectionDidChange(event) {if(!this.selected) return;let treeElement=event.target.selectedTreeElement;if(!treeElement) return;if(treeElement instanceof WI.DOMNodeTreeElement||treeElement instanceof WI.DOMBreakpointTreeElement||treeElement instanceof WI.EventBreakpointTreeElement||treeElement instanceof WI.URLBreakpointTreeElement||treeElement instanceof WI.SymbolicBreakpointTreeElement) return;if(treeElement.representedObject===SourcesNavigationSidebarPanel.__windowEventTargetRepresentedObject) return;if(treeElement instanceof WI.LocalResourceOverrideTreeElement){WI.showRepresentedObject(treeElement.representedObject);return;} let selectTreeElementInResourcesTreeOutline=(sourceCode)=>{let resourceTreeElement=this._resourcesTreeOutline.findTreeElement(sourceCode);if(!resourceTreeElement) return;const omitFocus=true;const selectedByUser=false;const suppressNotification=true;resourceTreeElement.select(omitFocus,selectedByUser,suppressNotification);};if(treeElement instanceof WI.FolderTreeElement||treeElement instanceof WI.OriginTreeElement||treeElement instanceof WI.ResourceTreeElement||treeElement instanceof WI.ScriptTreeElement||treeElement instanceof WI.CSSStyleSheetTreeElement){let representedObject=treeElement.representedObject;if(representedObject instanceof WI.Script&&representedObject.resource) representedObject=representedObject.resource;if(treeElement.treeOutline!==this._resourcesTreeOutline) selectTreeElementInResourcesTreeOutline(representedObject);if(representedObject instanceof WI.Collection||representedObject instanceof WI.SourceCode||representedObject instanceof WI.Frame) WI.showRepresentedObject(representedObject);return;} if(treeElement instanceof WI.CallFrameTreeElement){let callFrame=treeElement.callFrame;if(callFrame.id) WI.debuggerManager.activeCallFrame=callFrame;if(callFrame.sourceCodeLocation) WI.showSourceCodeLocation(callFrame.sourceCodeLocation);return;} if(treeElement instanceof WI.IssueTreeElement){WI.showSourceCodeLocation(treeElement.issueMessage.sourceCodeLocation);return;} if(treeElement instanceof WI.JavaScriptBreakpointTreeElement){let breakpoint=treeElement.breakpoint;if(breakpoint.special) return;let sourceCode=breakpoint.sourceCodeLocation.displaySourceCode;if(sourceCode instanceof WI.Script&&sourceCode.resource) sourceCode=sourceCode.resource;selectTreeElementInResourcesTreeOutline(sourceCode);WI.showSourceCodeLocation(breakpoint.sourceCodeLocation);return;} if(treeElement instanceof WI.BlackboxedGroupTreeElement) return;console.error("Unknown tree element",treeElement);} _handleBreakpointTreeOutlineElementRemoved(event) {let selectedTreeElement=this._breakpointsTreeOutline.selectedTreeElement;if(!selectedTreeElement) return;if(selectedTreeElement.representedObject instanceof WI.Breakpoint&&!selectedTreeElement.representedObject.removable){const skipUnrevealed=true;const stayWithin=null;const dontPopulate=true;let treeElementToSelect=selectedTreeElement.traverseNextTreeElement(skipUnrevealed,stayWithin,dontPopulate);if(treeElementToSelect){const omitFocus=true;const selectedByUser=true;treeElementToSelect.select(omitFocus,selectedByUser);}}} _populateCreateBreakpointContextMenu(contextMenu) {function addToggleForSpecialBreakpoint(label,breakpoint,callback){contextMenu.appendCheckboxItem(label,()=>{if(breakpoint) breakpoint.remove();else callback();},!!breakpoint);} if(WI.SymbolicBreakpoint.supported()){contextMenu.appendItem(WI.UIString("Symbolic Breakpoint\u2026","Symbolic Breakpoint\u2026 @ Sources Navigation Sidebar Panel","Context menu item for creating a new symbolic breakpoint."),()=>{let popover=new WI.SymbolicBreakpointPopover(this);popover.show(this._createBreakpointButton.element,[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);});contextMenu.appendSeparator();} addToggleForSpecialBreakpoint(WI.repeatedUIString.assertionFailures(),WI.debuggerManager.assertionFailuresBreakpoint,()=>{WI.debuggerManager.createAssertionFailuresBreakpoint();});contextMenu.appendSeparator();if(WI.JavaScriptBreakpoint.supportsMicrotasks()){addToggleForSpecialBreakpoint(WI.repeatedUIString.allMicrotasks(),WI.debuggerManager.allMicrotasksBreakpoint,()=>{WI.debuggerManager.createAllMicrotasksBreakpoint();});} if(WI.DOMDebuggerManager.supportsEventBreakpoints()||WI.DOMDebuggerManager.supportsEventListenerBreakpoints()){addToggleForSpecialBreakpoint(WI.repeatedUIString.allAnimationFrames(),WI.domDebuggerManager.allAnimationFramesBreakpoint,()=>{WI.domDebuggerManager.addEventBreakpoint(new WI.EventBreakpoint(WI.EventBreakpoint.Type.AnimationFrame));});addToggleForSpecialBreakpoint(WI.repeatedUIString.allTimeouts(),WI.domDebuggerManager.allTimeoutsBreakpoint,()=>{WI.domDebuggerManager.addEventBreakpoint(new WI.EventBreakpoint(WI.EventBreakpoint.Type.Timeout));});addToggleForSpecialBreakpoint(WI.repeatedUIString.allIntervals(),WI.domDebuggerManager.allIntervalsBreakpoint,()=>{WI.domDebuggerManager.addEventBreakpoint(new WI.EventBreakpoint(WI.EventBreakpoint.Type.Interval));});contextMenu.appendSeparator();if(WI.DOMDebuggerManager.supportsAllListenersBreakpoint()) addToggleForSpecialBreakpoint(WI.repeatedUIString.allEvents(),WI.domDebuggerManager.allListenersBreakpoint,()=>{WI.domDebuggerManager.addEventBreakpoint(new WI.EventBreakpoint(WI.EventBreakpoint.Type.Listener));});contextMenu.appendItem(WI.UIString("Event Breakpoint\u2026"),()=>{let popover=new WI.EventBreakpointPopover(this);popover.show(this._createBreakpointButton.element,[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);});} if(WI.DOMDebuggerManager.supportsURLBreakpoints()||WI.DOMDebuggerManager.supportsXHRBreakpoints()){contextMenu.appendSeparator();addToggleForSpecialBreakpoint(WI.repeatedUIString.allRequests(),WI.domDebuggerManager.allRequestsBreakpoint,()=>{const url="";WI.domDebuggerManager.addURLBreakpoint(new WI.URLBreakpoint(WI.URLBreakpoint.Type.Text,url));});contextMenu.appendItem(WI.DOMDebuggerManager.supportsURLBreakpoints()?WI.UIString("URL Breakpoint\u2026"):WI.UIString("XHR Breakpoint\u2026"),()=>{let popover=new WI.URLBreakpointPopover(this);popover.show(this._createBreakpointButton.element,[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);});}} _populateCreateLocalOverrideContextMenu(contextMenu) {if(WI.NetworkManager.supportsOverridingResponses()){contextMenu.appendItem(WI.UIString("Local Override\u2026"),()=>{let popover=new WI.LocalResourceOverridePopover(this);popover.show(null,this._createLocalOverrideButton.element,[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);});} if(WI.NetworkManager.supportsBootstrapScript()){contextMenu.appendItem(WI.UIString("Inspector Bootstrap Script"),async()=>{await WI.networkManager.createBootstrapScript();WI.networkManager.bootstrapScriptEnabled=true;WI.showRepresentedObject(WI.networkManager.bootstrapScript);});}} _handleCreateConsoleSnippetButtonClicked(event) {let popover=new WI.InputPopover("create-snippet-popover",WI.UIString("Name"),this);popover.show(this._createConsoleSnippetButton.element,[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);} _populateCreateResourceContextMenu(contextMenu) {if(WI.NetworkManager.supportsOverridingResponses()){contextMenu.appendItem(WI.UIString("Local Override\u2026"),()=>{if(!this._localOverridesTreeOutline.children.length) this._localOverridesRow.showEmptyMessage();this._localOverridesContainer.hidden=false;this._createLocalOverrideButton.element.scrollIntoViewIfNeeded(false);requestAnimationFrame(()=>{let popover=new WI.LocalResourceOverridePopover(this);popover.show(null,this._createLocalOverrideButton.element,[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);});});} contextMenu.appendItem(WI.UIString("Console Snippet\u2026"),()=>{if(!this._consoleSnippetsTreeOutline.children.length) this._consoleSnippetsRow.showEmptyMessage();this._consoleSnippetsContainer.hidden=false;this._createConsoleSnippetButton.element.scrollIntoViewIfNeeded(false);requestAnimationFrame(()=>{let popover=new WI.InputPopover("create-snippet-popover",WI.UIString("Name"),this);popover.show(this._createConsoleSnippetButton.element,[WI.RectEdge.MAX_Y,WI.RectEdge.MIN_Y,WI.RectEdge.MAX_X]);});});if(WI.NetworkManager.supportsBootstrapScript()){contextMenu.appendItem(WI.UIString("Inspector Bootstrap Script"),async()=>{await WI.networkManager.createBootstrapScript();WI.networkManager.bootstrapScriptEnabled=true;WI.showRepresentedObject(WI.networkManager.bootstrapScript);});} if(WI.CSSManager.supportsInspectorStyleSheet()){let addInspectorStyleSheetItem=(menu,frame)=>{menu.appendItem(WI.UIString("Inspector Style Sheet"),()=>{if(WI.settings.resourceGroupingMode.value===WI.Resource.GroupingMode.Path){let parentFrameTreeElement=this._resourcesTreeOutline.findTreeElement(frame.mainResource);parentFrameTreeElement.reveal();parentFrameTreeElement.expand();} WI.cssManager.preferredInspectorStyleSheetForFrame(frame,(styleSheet)=>{WI.showRepresentedObject(styleSheet);});});};addInspectorStyleSheetItem(contextMenu,WI.networkManager.mainFrame);let frames=WI.networkManager.frames;if(frames.length>2){let framesSubMenu=contextMenu.appendSubMenuItem(WI.UIString("Frames"));for(let frame of frames){if(frame===WI.networkManager.mainFrame||frame.mainResource.type!==WI.Resource.Type.Document) continue;let frameSubMenuItem=framesSubMenu.appendSubMenuItem(frame.name?WI.UIString("%s (%s)").format(frame.name,frame.mainResource.displayName):frame.mainResource.displayName);addInspectorStyleSheetItem(frameSubMenuItem,frame);}}}} _handleResourceGroupingModeChanged(event) {this._workerTargetTreeElementMap.clear();this._mainFrameTreeElement=null;this._extensionScriptsFolderTreeElement=null;this._extensionStyleSheetsFolderTreeElement=null;this._extraScriptsFolderTreeElement=null;this._extraStyleSheetsFolderTreeElement=null;this._anonymousScriptsFolderTreeElement=null;this._anonymousStyleSheetsFolderTreeElement=null;this._originTreeElementMap.clear();let resourceGroupingModeScopeBarItem=this._resourceGroupingModeScopeBarItems[WI.settings.resourceGroupingMode.value];if(resourceGroupingModeScopeBarItem) resourceGroupingModeScopeBarItem.selected=true;this._resourcesTreeOutline.removeChildren();let mainFrame=WI.networkManager.mainFrame;if(mainFrame){this._updateMainFrameTreeElement(mainFrame);this._addResourcesRecursivelyForFrame(mainFrame);for(let frame of WI.networkManager.frames){if(frame!==mainFrame) this._addResourcesRecursivelyForFrame(frame);}} for(let target of WI.targets){if(target.type===WI.TargetType.Worker&&target.mainResource){this._addWorkerTargetWithMainResource(target);this._addBreakpointsForSourceCode(target.mainResource);this._addIssuesForSourceCode(target.mainResource);}} for(let script of WI.debuggerManager.knownNonResourceScripts){this._addScript(script);if(script.sourceMaps.length&&WI.SourcesNavigationSidebarPanel.shouldPlaceResourcesAtTopLevel()) this._resourcesTreeOutline.disclosureButtons=true;} for(let styleSheet of WI.cssManager.styleSheets){if(styleSheet.origin!==WI.CSSStyleSheet.Type.Author&&!styleSheet.isInspectorStyleSheet()) this._addStyleSheet(styleSheet);}} _handleFrameMainResourceDidChange(event) {let frame=event.target;if(frame.isMainFrame()){this._updateMainFrameTreeElement(frame);this._addResourcesRecursivelyForFrame(frame);for(let domBreakpoint of WI.domDebuggerManager.domBreakpoints) this._removeBreakpoint(domBreakpoint);} if(!event.data.oldMainResource){let resource=event.target.mainResource;this._addBreakpointsForSourceCode(resource);this._addIssuesForSourceCode(resource);}} _handleResourceAdded(event) {this._addResource(event.data.resource);} _handleFrameWasAdded(event) {let{frame}=event.data;if(frame.isMainFrame()) this._updateMainFrameTreeElement(frame);this._addResourcesRecursivelyForFrame(frame);} _handleBootstrapScriptCreated(event) {this._addLocalOverride(event.data.bootstrapScript);} _handleBootstrapScriptDestroyed(event) {this._removeResourceOverride(event.data.bootstrapScript);} _handleLocalResourceOverrideAdded(event) {this._addLocalOverride(event.data.localResourceOverride);} _handleLocalResourceOverrideRemoved(event) {this._removeResourceOverride(event.data.localResourceOverride);} _handleDebuggerBreakpointAdded(event) {this._addBreakpoint(event.data.breakpoint);} _handleDebuggerBreakpointRemoved(event) {this._removeBreakpoint(event.data.breakpoint);} _handleDebuggerBreakpointsEnabledDidChange(event) {this._debuggerBreakpointsButtonItem.activated=WI.debuggerManager.breakpointsEnabled;this._updateBreakpointsDisabledBanner();} _handleDebuggerScriptAdded(event) {this._addScript(event.data.script);} _handleDebuggerScriptRemoved(event) {let script=event.data.script;let scriptTreeElement=this._resourcesTreeOutline.findTreeElement(script);if(!scriptTreeElement) return;let parentTreeElement=scriptTreeElement.parent;parentTreeElement.removeChild(scriptTreeElement);if(parentTreeElement instanceof WI.FolderTreeElement||parentTreeElement instanceof WI.OriginTreeElement){parentTreeElement.representedObject.remove(script);if(!parentTreeElement.children.length) parentTreeElement.parent.removeChild(parentTreeElement);}} _handleDebuggerScriptsCleared(event) {const suppressOnDeselect=true;const suppressSelectSibling=true;for(let i=this._breakpointsTreeOutline.children.length-1;i>=0;--i){let treeElement=this._breakpointsTreeOutline.children[i];if(!(treeElement instanceof WI.ScriptTreeElement)) continue;this._breakpointsTreeOutline.removeChild(treeElement,suppressOnDeselect,suppressSelectSibling);} if(this._extensionScriptsFolderTreeElement){if(this._extensionScriptsFolderTreeElement.parent) this._extensionScriptsFolderTreeElement.parent.removeChild(this._extensionScriptsFolderTreeElement,suppressOnDeselect,suppressSelectSibling);this._extensionScriptsFolderTreeElement.representedObject.clear();this._extensionScriptsFolderTreeElement=null;} if(this._extraScriptsFolderTreeElement){if(this._extraScriptsFolderTreeElement.parent) this._extraScriptsFolderTreeElement.parent.removeChild(this._extraScriptsFolderTreeElement,suppressOnDeselect,suppressSelectSibling);this._extraScriptsFolderTreeElement.representedObject.clear();this._extraScriptsFolderTreeElement=null;} if(this._anonymousScriptsFolderTreeElement){if(this._anonymousScriptsFolderTreeElement.parent) this._anonymousScriptsFolderTreeElement.parent.removeChild(this._anonymousScriptsFolderTreeElement,suppressOnDeselect,suppressSelectSibling);this._anonymousScriptsFolderTreeElement.representedObject.clear();this._anonymousScriptsFolderTreeElement=null;} if(this._workerTargetTreeElementMap.size){for(let treeElement of this._workerTargetTreeElementMap.values()) treeElement.parent.removeChild(treeElement,suppressOnDeselect,suppressSelectSibling);this._workerTargetTreeElementMap.clear();} this._addResourcesRecursivelyForFrame(WI.networkManager.mainFrame);} _handleDebuggerPaused(event) {this._callStackContainer.hidden=false;if(this._updatePauseReason()) this._pauseReasonContainer.hidden=false;this._debuggerPauseResumeButtonItem.enabled=true;this._debuggerPauseResumeButtonItem.toggled=true;this._debuggerStepOverButtonItem.enabled=true;this._debuggerStepIntoButtonItem.enabled=true;this._debuggerStepOutButtonItem.enabled=true;if(this._debuggerStepNextButtonItem) this._debuggerStepNextButtonItem.enabled=true;this.element.classList.add("paused");} _handleDebuggerResumed(event) {this._callStackContainer.hidden=true;this._pauseReasonContainer.hidden=true;this._debuggerPauseResumeButtonItem.enabled=true;this._debuggerPauseResumeButtonItem.toggled=false;this._debuggerStepOverButtonItem.enabled=false;this._debuggerStepIntoButtonItem.enabled=false;this._debuggerStepOutButtonItem.enabled=false;if(this._debuggerStepNextButtonItem) this._debuggerStepNextButtonItem.enabled=false;this.element.classList.remove("paused");} _handleDebuggerCallFramesDidChange(event) {let{target}=event.data;let treeElement=this._findCallStackTargetTreeElement(target);if(treeElement) treeElement.refresh();let activeCallFrameTreeElement=this._callStackTreeOutline.findTreeElement(WI.debuggerManager.activeCallFrame);if(activeCallFrameTreeElement) activeCallFrameTreeElement.reveal();} _handleDebuggerActiveCallFrameDidChange(event) {if(this._activeCallFrameTreeElement){this._activeCallFrameTreeElement.isActiveCallFrame=false;this._activeCallFrameTreeElement=null;} if(!WI.debuggerManager.activeCallFrame) return;this._activeCallFrameTreeElement=this._callStackTreeOutline.findTreeElement(WI.debuggerManager.activeCallFrame);if(this._activeCallFrameTreeElement) this._activeCallFrameTreeElement.isActiveCallFrame=true;} _handleDebuggerWaitingToPause(event) {this._debuggerPauseResumeButtonItem.enabled=false;} _handleDebuggerObjectDisplayLocationDidChange(event) {let debuggerObject=event.target;if(event.data.oldDisplaySourceCode===debuggerObject.sourceCodeLocation.displaySourceCode) return; let wasSelected=false;let oldDebuggerTreeElement=null;let newDebuggerTreeElement=null;if(debuggerObject instanceof WI.JavaScriptBreakpoint){oldDebuggerTreeElement=this._breakpointsTreeOutline.findTreeElement(debuggerObject);if(!oldDebuggerTreeElement) return;wasSelected=oldDebuggerTreeElement.selected;newDebuggerTreeElement=this._addBreakpoint(debuggerObject);}else if(debuggerObject instanceof WI.IssueMessage){oldDebuggerTreeElement=this._resourcesTreeOutline.findTreeElement(debuggerObject);if(!oldDebuggerTreeElement) return;wasSelected=oldDebuggerTreeElement.selected;newDebuggerTreeElement=this._addIssue(debuggerObject);} if(!newDebuggerTreeElement) return;if(oldDebuggerTreeElement) this._removeDebuggerTreeElement(oldDebuggerTreeElement);if(wasSelected) newDebuggerTreeElement.revealAndSelect(true,false,true);} _handleDOMBreakpointDOMNodeWillChange(event) {let breakpoint=event.target;this._removeBreakpoint(breakpoint);} _handleDOMBreakpointDOMNodeDidChange(event) {let breakpoint=event.target;this._addBreakpoint(breakpoint);} _handleConsoleIssueAdded(event) {let{issue}=event.data;if(!issue.sourceCodeLocation||!issue.sourceCodeLocation.sourceCode||(issue.source!=="javascript"&&issue.source!=="console-api")) return;this._addIssue(issue);} _handleConsoleCleared(event) {let issueTreeElements=[];let currentTreeElement=this._resourcesTreeOutline.children[0];while(currentTreeElement&&!currentTreeElement.root){if(currentTreeElement instanceof WI.IssueTreeElement) issueTreeElements.push(currentTreeElement);const skipUnrevealed=false;const stayWithin=null;const dontPopulate=true;currentTreeElement=currentTreeElement.traverseNextTreeElement(skipUnrevealed,stayWithin,dontPopulate);} issueTreeElements.forEach((treeElement)=>treeElement.parent.removeChild(treeElement));} _handleConsoleSnippetAdded(event) {this._addConsoleSnippet(event.data.snippet);} _handleConsoleSnippetRemoved(event) {this._removeConsoleSnippet(event.data.snippet);} _handleTimelineCapturingStateChanged(event) {this._updateTemporarilyDisabledBreakpointsButtons();switch(WI.timelineManager.capturingState){case WI.TimelineManager.CapturingState.Starting:if(!this._timelineRecordingWarningElement){let stopRecordingButton=document.createElement("button");stopRecordingButton.textContent=WI.UIString("Stop recording");stopRecordingButton.addEventListener("click",()=>{WI.timelineManager.stopCapturing();});this._timelineRecordingWarningElement=document.createElement("div");this._timelineRecordingWarningElement.classList.add("warning-banner");this._timelineRecordingWarningElement.append(WI.UIString("Debugger disabled during Timeline recording"),document.createElement("br"),stopRecordingButton);} this.contentView.element.insertBefore(this._timelineRecordingWarningElement,this.contentView.element.firstChild);break;case WI.TimelineManager.CapturingState.Inactive:if(this._timelineRecordingWarningElement){this._timelineRecordingWarningElement.remove();this._timelineRecordingWarningElement=null;} break;} this._updateBreakpointsDisabledBanner();} _handleAuditManagerTestScheduled(event) {this._updateTemporarilyDisabledBreakpointsButtons();if(!this._auditTestWarningElement){let stopAuditButton=document.createElement("button");stopAuditButton.textContent=WI.UIString("Stop Audit");stopAuditButton.addEventListener("click",(event)=>{WI.auditManager.stop();});this._auditTestWarningElement=document.createElement("div");this._auditTestWarningElement.classList.add("warning-banner");this._auditTestWarningElement.append(WI.UIString("Debugger disabled during Audit"),document.createElement("br"),stopAuditButton);} this.contentView.element.insertBefore(this._auditTestWarningElement,this.contentView.element.firstChild);this._updateBreakpointsDisabledBanner();} _handleAuditManagerTestCompleted(event) {this._updateTemporarilyDisabledBreakpointsButtons();if(this._auditTestWarningElement){this._auditTestWarningElement.remove();this._auditTestWarningElement=null;} this._updateBreakpointsDisabledBanner();} _handleCSSStyleSheetAdded(event) {let{styleSheet}=event.data;if(styleSheet.origin===WI.CSSStyleSheet.Type.Author) return;if(styleSheet.isInspectorStyleSheet()){if(WI.settings.resourceGroupingMode.value===WI.Resource.GroupingMode.Type){let frameTreeElement=this.treeElementForRepresentedObject(styleSheet.parentFrame);if(frameTreeElement){frameTreeElement.addRepresentedObjectToNewChildQueue(styleSheet);return;}} this._addResource(styleSheet);}else this._addStyleSheet(styleSheet);} _handleCSSStyleSheetRemoved(event) {let{styleSheet}=event.data;if(styleSheet.origin===WI.CSSStyleSheet.Type.Author) return;let treeElement=this._resourcesTreeOutline.findTreeElement(styleSheet);if(!treeElement) return;let parent=treeElement.parent;treeElement.parent.removeChild(treeElement);if(!parent.children.length) parent.parent.removeChild(parent);switch(parent){case this._extensionStyleSheetsFolderTreeElement:this._extensionStyleSheetsFolderTreeElement=null;break;case this._extraStyleSheetsFolderTreeElement:this._extraStyleSheetsFolderTreeElement=null;break;case this._anonymousStyleSheetsFolderTreeElement:this._anonymousStyleSheetsFolderTreeElement=null;break;}} _handleTargetAdded(event) {this._addTarget(event.data.target);} _handleTargetRemoved(event) {let{target}=event.data;let workerTreeElement=this._workerTargetTreeElementMap.take(target);if(workerTreeElement) workerTreeElement.parent.removeChild(workerTreeElement);let callStackTreeElement=this._findCallStackTargetTreeElement(target);if(callStackTreeElement) this._callStackTreeOutline.removeChild(callStackTreeElement);this._updateCallStackTreeOutline();} _handleExtraDomainsActivated() { if(WI.SourcesNavigationSidebarPanel.shouldPlaceResourcesAtTopLevel()) this._resourcesTreeOutline.disclosureButtons=true;}};WI.SourcesNavigationSidebarPanel.ResourceTypeSymbol=Symbol("resource-type");WI.SourcesNavigationSidebarPanel.ResourceGroupingModeSymbol=Symbol("resource-grouping-mode");WI.SourceMapResourceTreeElement=class SourceMapResourceTreeElement extends WI.ResourceTreeElement {constructor(sourceMapResource) {super(sourceMapResource);this.addClassName("source-map-resource");} _updateTitles() {var oldMainTitle=this.mainTitle;this.mainTitle=this.resource.displayName;var sourceMapHost=this.resource.urlComponents.host;var originalHost=this.resource.sourceMap.originalSourceCode.urlComponents.host;var subtitle=sourceMapHost!==originalHost?WI.displayNameForHost(sourceMapHost):null;this.subtitle=this.mainTitle!==subtitle?subtitle:null;if(oldMainTitle!==this.mainTitle) this.callFirstAncestorFunction("descendantResourceTreeElementMainTitleDidChange",[this,oldMainTitle]);}};WI.SpanningDataGridNode=class SpanningDataGridNode extends WI.DataGridNode {constructor(text) {super({[WI.SpanningDataGridNode.ColumnIdentifier]:text});} createCells() {let cellElement=this.createCell(WI.SpanningDataGridNode.ColumnIdentifier);cellElement.classList.add("spanning");cellElement.setAttribute("colspan",this.dataGrid.columns.size);this.element.appendChild(cellElement);}};WI.SpanningDataGridNode.ColumnIdentifier="spanning-text";WI.SpreadsheetCSSStyleDeclarationEditor=class SpreadsheetCSSStyleDeclarationEditor extends WI.View {constructor(delegate,style) {super();this.element.classList.add(WI.SpreadsheetCSSStyleDeclarationEditor.StyleClassName);this._delegate=delegate;this.style=style;this._propertyViews=[];this._focused=false;this._inlineSwatchActive=false;this._showsImplicitProperties=false;this._alwaysShowPropertyNames=new Set;this._propertyVisibilityMode=WI.SpreadsheetCSSStyleDeclarationEditor.PropertyVisibilityMode.HideUnusedInheritedVariables;this._hiddenUnusedVariables=new Set;this._hideFilterNonMatchingProperties=false;this._sortPropertiesByName=false;this._propertyPendingStartEditing=null;this._pendingAddBlankPropertyIndexOffset=NaN;this._filterText=null;this._anchorIndex=NaN;this._focusIndex=NaN;} initialLayout() {if(!this._style) return;this.element.addEventListener("focus",()=>{this.focused=true;},true);this.element.addEventListener("blur",(event)=>{let focusedElement=event.relatedTarget;if(focusedElement&&this.element.contains(focusedElement)) return;this.focused=false;},true);this.element.addEventListener("keydown",this._handleKeyDown.bind(this));this.element.addEventListener("cut",this._handleCut.bind(this));this.element.addEventListener("copy",this._handleCopy.bind(this));} layout() { if(this.editing&&!this._propertyPendingStartEditing&&isNaN(this._pendingAddBlankPropertyIndexOffset)) return;super.layout();this.element.removeChildren();if(this._style) this._style.updatePropertiesModifiedState();let properties=this.propertiesToRender;this._propertyViews=[];let propertyViewPendingStartEditing=null;for(let index=0;index