import{ObjectWrapper}from'../common/common.js';import{UIUtils,ListModel,SoftDropDown,Toolbar,Utils,Fragment,ThrottledWidget,Widget}from'../ui/ui.js';import{SDKModel,ResourceTreeModel}from'../sdk/sdk.js';const PortPadding=4;const InputPortRadius=10;const AudioParamRadius=5;const LeftMarginOfText=12;const RightMarginOfText=30;const LeftSideTopPadding=5;const BottomPaddingWithoutParam=6;const BottomPaddingWithParam=8;const ArrowHeadSize=12;const GraphPadding=20;const GraphMargin=20;const TotalInputPortHeight=InputPortRadius*2+PortPadding;const TotalOutputPortHeight=TotalInputPortHeight;const TotalParamPortHeight=AudioParamRadius*2+PortPadding;const NodeLabelFontStyle='14px Segoe UI, Arial';const ParamLabelFontStyle='12px Segoe UI, Arial';const PortTypes={In:Symbol('In'),Out:Symbol('Out'),Param:Symbol('Param'),};let Size;let Point;let NodeLayout;let Port;let NodeCreationData;let ParamCreationData;let NodesConnectionData;let NodesDisconnectionData;let NodesDisconnectionDataWithDestination;let NodeParamConnectionData;let NodeParamDisconnectionData;var GraphStyle=Object.freeze({__proto__:null,PortPadding:PortPadding,InputPortRadius:InputPortRadius,AudioParamRadius:AudioParamRadius,LeftMarginOfText:LeftMarginOfText,RightMarginOfText:RightMarginOfText,LeftSideTopPadding:LeftSideTopPadding,BottomPaddingWithoutParam:BottomPaddingWithoutParam,BottomPaddingWithParam:BottomPaddingWithParam,ArrowHeadSize:ArrowHeadSize,GraphPadding:GraphPadding,GraphMargin:GraphMargin,TotalInputPortHeight:TotalInputPortHeight,TotalOutputPortHeight:TotalOutputPortHeight,TotalParamPortHeight:TotalParamPortHeight,NodeLabelFontStyle:NodeLabelFontStyle,ParamLabelFontStyle:ParamLabelFontStyle,PortTypes:PortTypes,Size:Size,Point:Point,NodeLayout:NodeLayout,Port:Port,NodeCreationData:NodeCreationData,ParamCreationData:ParamCreationData,NodesConnectionData:NodesConnectionData,NodesDisconnectionData:NodesDisconnectionData,NodesDisconnectionDataWithDestination:NodesDisconnectionDataWithDestination,NodeParamConnectionData:NodeParamConnectionData,NodeParamDisconnectionData:NodeParamDisconnectionData});const calculateInputPortXY=portIndex=>{const y=InputPortRadius+LeftSideTopPadding+portIndex*TotalInputPortHeight;return{x:0,y:y};};const calculateOutputPortXY=(portIndex,nodeSize,numberOfOutputs)=>{const{width,height}=nodeSize;const outputPortY=(height/2)+(2*portIndex-numberOfOutputs+1)*TotalOutputPortHeight/2;return{x:width,y:outputPortY};};const calculateParamPortXY=(portIndex,offsetY)=>{const paramPortY=offsetY+TotalParamPortHeight*(portIndex+1)-AudioParamRadius;return{x:0,y:paramPortY};};var NodeRendererUtility=Object.freeze({__proto__:null,calculateInputPortXY:calculateInputPortXY,calculateOutputPortXY:calculateOutputPortXY,calculateParamPortXY:calculateParamPortXY});class NodeView{constructor(data,label){this.id=data.nodeId;this.type=data.nodeType;this.numberOfInputs=data.numberOfInputs;this.numberOfOutputs=data.numberOfOutputs;this.label=label;this.size={width:0,height:0};this.position=null;this._layout={inputPortSectionHeight:0,outputPortSectionHeight:0,maxTextLength:0,totalHeight:0,};this.ports=new Map();this._initialize(data);}
_initialize(data){this._updateNodeLayoutAfterAddingNode(data);this._setupInputPorts();this._setupOutputPorts();}
addParamPort(paramId,paramType){const paramPorts=this.getPortsByType(PortTypes.Param);const numberOfParams=paramPorts.length;const{x,y}=calculateParamPortXY(numberOfParams,this._layout.inputPortSectionHeight);this._addPort({id:generateParamPortId(this.id,paramId),type:PortTypes.Param,label:paramType,x,y,});this._updateNodeLayoutAfterAddingParam(numberOfParams+1,paramType);this._setupOutputPorts();}
getPortsByType(type){const result=[];this.ports.forEach(port=>{if(port.type===type){result.push(port);}});return result;}
_updateNodeLayoutAfterAddingNode(data){const inputPortSectionHeight=TotalInputPortHeight*Math.max(1,data.numberOfInputs)+LeftSideTopPadding;this._layout.inputPortSectionHeight=inputPortSectionHeight;this._layout.outputPortSectionHeight=TotalOutputPortHeight*data.numberOfOutputs;this._layout.totalHeight=Math.max(inputPortSectionHeight+BottomPaddingWithoutParam,this._layout.outputPortSectionHeight);const nodeLabelLength=measureTextWidth(this.label,NodeLabelFontStyle);this._layout.maxTextLength=Math.max(this._layout.maxTextLength,nodeLabelLength);this._updateNodeSize();}
_updateNodeLayoutAfterAddingParam(numberOfParams,paramType){const leftSideMaxHeight=this._layout.inputPortSectionHeight+numberOfParams*TotalParamPortHeight+BottomPaddingWithParam;this._layout.totalHeight=Math.max(leftSideMaxHeight,this._layout.outputPortSectionHeight);const paramLabelLength=measureTextWidth(paramType,ParamLabelFontStyle);this._layout.maxTextLength=Math.max(this._layout.maxTextLength,paramLabelLength);this._updateNodeSize();}
_updateNodeSize(){this.size={width:Math.ceil(LeftMarginOfText+this._layout.maxTextLength+RightMarginOfText),height:this._layout.totalHeight,};}
_setupInputPorts(){for(let i=0;i<this.numberOfInputs;i++){const{x,y}=calculateInputPortXY(i);this._addPort({id:generateInputPortId(this.id,i),type:PortTypes.In,x,y,});}}
_setupOutputPorts(){for(let i=0;i<this.numberOfOutputs;i++){const portId=generateOutputPortId(this.id,i);const{x,y}=calculateOutputPortXY(i,this.size,this.numberOfOutputs);if(this.ports.has(portId)){const port=this.ports.get(portId);port.x=x;port.y=y;}else{this._addPort({id:portId,type:PortTypes.Out,x,y,});}}}
_addPort(port){this.ports.set(port.id,port);}}
const generateInputPortId=(nodeId,inputIndex)=>{return`${nodeId}-input-${inputIndex || 0}`;};const generateOutputPortId=(nodeId,outputIndex)=>{return`${nodeId}-output-${outputIndex || 0}`;};const generateParamPortId=(nodeId,paramId)=>{return`${nodeId}-param-${paramId}`;};class NodeLabelGenerator{constructor(){this._totalNumberOfNodes=0;}
generateLabel(nodeType){if(nodeType.endsWith('Node')){nodeType=nodeType.slice(0,nodeType.length-4);}
this._totalNumberOfNodes+=1;const label=`${nodeType} ${this._totalNumberOfNodes}`;return label;}}
let _contextForFontTextMeasuring;const measureTextWidth=(text,fontStyle)=>{if(!_contextForFontTextMeasuring){_contextForFontTextMeasuring=createElement('canvas').getContext('2d');}
const context=_contextForFontTextMeasuring;context.save();context.font=fontStyle;const width=UIUtils.measureTextWidth(context,text);context.restore();return width;};var NodeView$1=Object.freeze({__proto__:null,NodeView:NodeView,generateInputPortId:generateInputPortId,generateOutputPortId:generateOutputPortId,generateParamPortId:generateParamPortId,NodeLabelGenerator:NodeLabelGenerator,measureTextWidth:measureTextWidth});class EdgeView{constructor(data,type){const{edgeId,sourcePortId,destinationPortId}=generateEdgePortIdsByData(data,type);this.id=edgeId;this.type=type;this.sourceId=data.sourceId;this.destinationId=data.destinationId;this.sourcePortId=sourcePortId;this.destinationPortId=destinationPortId;}}
const generateEdgePortIdsByData=(data,type)=>{if(!data.sourceId||!data.destinationId){console.error(`Undefined node message: ${JSON.stringify(data)}`);return null;}
const sourcePortId=generateOutputPortId(data.sourceId,data.sourceOutputIndex);const destinationPortId=getDestinationPortId(data,type);return{edgeId:`${sourcePortId}->${destinationPortId}`,sourcePortId:sourcePortId,destinationPortId:destinationPortId,};function getDestinationPortId(data,type){if(type===EdgeTypes.NodeToNode){return generateInputPortId(data.destinationId,data.destinationInputIndex);}
if(type===EdgeTypes.NodeToParam){return generateParamPortId(data.destinationId,data.destinationParamId);}
console.error(`Unknown edge type: ${type}`);return'';}};const EdgeTypes={NodeToNode:Symbol('NodeToNode'),NodeToParam:Symbol('NodeToParam'),};var EdgeView$1=Object.freeze({__proto__:null,EdgeView:EdgeView,generateEdgePortIdsByData:generateEdgePortIdsByData,EdgeTypes:EdgeTypes});class GraphView extends Common.Object{constructor(contextId){super();this.contextId=contextId;this._nodes=new Map();this._edges=new Map();this._outboundEdgeMap=new Platform.Multimap();this._inboundEdgeMap=new Platform.Multimap();this._nodeLabelGenerator=new NodeLabelGenerator();this._paramIdToNodeIdMap=new Map();}
addNode(data){const label=this._nodeLabelGenerator.generateLabel(data.nodeType);const node=new NodeView(data,label);this._nodes.set(data.nodeId,node);this._notifyShouldRedraw();}
removeNode(nodeId){this._outboundEdgeMap.get(nodeId).forEach(edgeId=>this._removeEdge(edgeId));this._inboundEdgeMap.get(nodeId).forEach(edgeId=>this._removeEdge(edgeId));this._nodes.delete(nodeId);this._notifyShouldRedraw();}
addParam(data){const node=this.getNodeById(data.nodeId);if(!node){console.error('AudioNode should be added before AudioParam');return;}
node.addParamPort(data.paramId,data.paramType);this._paramIdToNodeIdMap.set(data.paramId,data.nodeId);this._notifyShouldRedraw();}
removeParam(paramId){this._paramIdToNodeIdMap.delete(paramId);}
addNodeToNodeConnection(edgeData){const edge=new EdgeView(edgeData,EdgeTypes.NodeToNode);this._addEdge(edge);}
removeNodeToNodeConnection(edgeData){if(edgeData.destinationId){const{edgeId}=generateEdgePortIdsByData((edgeData),EdgeTypes.NodeToNode);this._removeEdge(edgeId);}else{this._outboundEdgeMap.get(edgeData.sourceId).forEach(edgeId=>this._removeEdge(edgeId));}}
addNodeToParamConnection(edgeData){const edge=new EdgeView(edgeData,EdgeTypes.NodeToParam);this._addEdge(edge);}
removeNodeToParamConnection(edgeData){const{edgeId}=generateEdgePortIdsByData(edgeData,EdgeTypes.NodeToParam);this._removeEdge(edgeId);}
getNodeById(nodeId){return this._nodes.get(nodeId);}
getNodes(){return this._nodes;}
getEdges(){return this._edges;}
getNodeIdByParamId(paramId){return this._paramIdToNodeIdMap.get(paramId);}
_addEdge(edge){const sourceId=edge.sourceId;if(this._outboundEdgeMap.hasValue(sourceId,edge.id)){return;}
this._edges.set(edge.id,edge);this._outboundEdgeMap.set(sourceId,edge.id);this._inboundEdgeMap.set(edge.destinationId,edge.id);this._notifyShouldRedraw();}
_removeEdge(edgeId){const edge=this._edges.get(edgeId);if(!edge){return;}
this._outboundEdgeMap.delete(edge.sourceId,edgeId);this._inboundEdgeMap.delete(edge.destinationId,edgeId);this._edges.delete(edgeId);this._notifyShouldRedraw();}
_notifyShouldRedraw(){this.dispatchEventToListeners(Events.ShouldRedraw,this);}}
const Events={ShouldRedraw:Symbol('ShouldRedraw')};var GraphView$1=Object.freeze({__proto__:null,GraphView:GraphView,Events:Events});class GraphManager extends ObjectWrapper.ObjectWrapper{constructor(){super();this._graphMapByContextId=new Map();}
createContext(contextId){const graph=new GraphView(contextId);graph.addEventListener(Events.ShouldRedraw,this._notifyShouldRedraw,this);this._graphMapByContextId.set(contextId,graph);}
destroyContext(contextId){if(!this._graphMapByContextId.has(contextId)){return;}
const graph=this._graphMapByContextId.get(contextId);graph.removeEventListener(Events.ShouldRedraw,this._notifyShouldRedraw,this);this._graphMapByContextId.delete(contextId);}
hasContext(contextId){return this._graphMapByContextId.has(contextId);}
clearGraphs(){this._graphMapByContextId.clear();}
getGraph(contextId){return this._graphMapByContextId.get(contextId);}
_notifyShouldRedraw(event){const graph=(event.data);this.dispatchEventToListeners(Events.ShouldRedraw,graph);}}
var GraphManager$1=Object.freeze({__proto__:null,GraphManager:GraphManager});class WebAudioModel extends SDKModel.SDKModel{constructor(target){super(target);this._enabled=false;this._agent=target.webAudioAgent();target.registerWebAudioDispatcher(this);SDKModel.TargetManager.instance().addModelListener(ResourceTreeModel.ResourceTreeModel,ResourceTreeModel.Events.FrameNavigated,this._flushContexts,this);}
_flushContexts(){this.dispatchEventToListeners(Events$1.ModelReset);}
suspendModel(){this.dispatchEventToListeners(Events$1.ModelSuspend);return this._agent.disable();}
resumeModel(){if(!this._enabled){return Promise.resolve();}
return this._agent.enable();}
ensureEnabled(){if(this._enabled){return;}
this._agent.enable();this._enabled=true;}
contextCreated(context){this.dispatchEventToListeners(Events$1.ContextCreated,context);}
contextWillBeDestroyed(contextId){this.dispatchEventToListeners(Events$1.ContextDestroyed,contextId);}
contextChanged(context){this.dispatchEventToListeners(Events$1.ContextChanged,context);}
audioListenerCreated(listener){this.dispatchEventToListeners(Events$1.AudioListenerCreated,listener);}
audioListenerWillBeDestroyed(contextId,listenerId){this.dispatchEventToListeners(Events$1.AudioListenerWillBeDestroyed,{contextId,listenerId});}
audioNodeCreated(node){this.dispatchEventToListeners(Events$1.AudioNodeCreated,node);}
audioNodeWillBeDestroyed(contextId,nodeId){this.dispatchEventToListeners(Events$1.AudioNodeWillBeDestroyed,{contextId,nodeId});}
audioParamCreated(param){this.dispatchEventToListeners(Events$1.AudioParamCreated,param);}
audioParamWillBeDestroyed(contextId,nodeId,paramId){this.dispatchEventToListeners(Events$1.AudioParamWillBeDestroyed,{contextId,paramId});}
nodesConnected(contextId,sourceId,destinationId,sourceOutputIndex,destinationInputIndex){this.dispatchEventToListeners(Events$1.NodesConnected,{contextId,sourceId,destinationId,sourceOutputIndex,destinationInputIndex});}
nodesDisconnected(contextId,sourceId,destinationId,sourceOutputIndex,destinationInputIndex){this.dispatchEventToListeners(Events$1.NodesDisconnected,{contextId,sourceId,destinationId,sourceOutputIndex,destinationInputIndex});}
nodeParamConnected(contextId,sourceId,destinationId,sourceOutputIndex){this.dispatchEventToListeners(Events$1.NodeParamConnected,{contextId,sourceId,destinationId,sourceOutputIndex,});}
nodeParamDisconnected(contextId,sourceId,destinationId,sourceOutputIndex){this.dispatchEventToListeners(Events$1.NodeParamDisconnected,{contextId,sourceId,destinationId,sourceOutputIndex,});}
async requestRealtimeData(contextId){return await this._agent.getRealtimeData(contextId);}}
SDKModel.SDKModel.register(WebAudioModel,SDKModel.Capability.DOM,false);const Events$1={ContextCreated:Symbol('ContextCreated'),ContextDestroyed:Symbol('ContextDestroyed'),ContextChanged:Symbol('ContextChanged'),ModelReset:Symbol('ModelReset'),ModelSuspend:Symbol('ModelSuspend'),AudioListenerCreated:Symbol('AudioListenerCreated'),AudioListenerWillBeDestroyed:Symbol('AudioListenerWillBeDestroyed'),AudioNodeCreated:Symbol('AudioNodeCreated'),AudioNodeWillBeDestroyed:Symbol('AudioNodeWillBeDestroyed'),AudioParamCreated:Symbol('AudioParamCreated'),AudioParamWillBeDestroyed:Symbol('AudioParamWillBeDestroyed'),NodesConnected:Symbol('NodesConnected'),NodesDisconnected:Symbol('NodesDisconnected'),NodeParamConnected:Symbol('NodeParamConnected'),NodeParamDisconnected:Symbol('NodeParamDisconnected'),};var WebAudioModel$1=Object.freeze({__proto__:null,WebAudioModel:WebAudioModel,Events:Events$1});class AudioContextSelector extends ObjectWrapper.ObjectWrapper{constructor(){super();this._placeholderText=ls`(no recordings)`;this._items=new ListModel.ListModel();this._dropDown=new SoftDropDown.SoftDropDown(this._items,this);this._dropDown.setPlaceholderText(this._placeholderText);this._toolbarItem=new Toolbar.ToolbarItem(this._dropDown.element);this._toolbarItem.setEnabled(false);this._toolbarItem.setTitle(ls`Audio context: ${this._placeholderText}`);this._items.addEventListener(ListModel.Events.ItemsReplaced,this._onListItemReplaced,this);this._toolbarItem.element.classList.add('toolbar-has-dropdown');this._selectedContext=null;}
_onListItemReplaced(){const hasItems=!!this._items.length;this._toolbarItem.setEnabled(hasItems);if(!hasItems){this._toolbarItem.setTitle(ls`Audio context: ${this._placeholderText}`);}}
contextCreated(event){const context=(event.data);this._items.insert(this._items.length,context);if(this._items.length===1){this._dropDown.selectItem(context);}}
contextDestroyed(event){const contextId=(event.data);const contextIndex=this._items.findIndex(context=>context.contextId===contextId);if(contextIndex>-1){this._items.remove(contextIndex);}}
contextChanged(event){const changedContext=(event.data);const contextIndex=this._items.findIndex(context=>context.contextId===changedContext.contextId);if(contextIndex>-1){this._items.replace(contextIndex,changedContext);if(this._selectedContext&&this._selectedContext.contextId===changedContext.contextId){this._dropDown.selectItem(changedContext);}}}
createElementForItem(item){const element=createElementWithClass('div');const shadowRoot=Utils.createShadowRootWithCoreStyles(element,'web_audio/audioContextSelector.css');const title=shadowRoot.createChild('div','title');title.createTextChild(this.titleFor(item).trimEndWithMaxLength(100));return element;}
selectedContext(){if(!this._selectedContext){return null;}
return this._selectedContext;}
highlightedItemChanged(from,to,fromElement,toElement){if(fromElement){fromElement.classList.remove('highlighted');}
if(toElement){toElement.classList.add('highlighted');}}
isItemSelectable(item){return true;}
itemSelected(item){if(!item){return;}
if(!this._selectedContext||this._selectedContext.contextId!==item.contextId){this._selectedContext=item;this._toolbarItem.setTitle(ls`Audio context: ${this.titleFor(item)}`);}
this.dispatchEventToListeners(WebAudio.AudioContextSelector.Events.ContextSelected,item);}
reset(){this._items.replaceAll([]);}
titleFor(context){return`${context.contextType} (${context.contextId.substr(-6)})`;}
toolbarItem(){return this._toolbarItem;}}
const Events$2={ContextSelected:Symbol('ContextSelected')};var AudioContextSelector$1=Object.freeze({__proto__:null,AudioContextSelector:AudioContextSelector,Events:Events$2});class ContextDetailBuilder{constructor(context){this._fragment=createDocumentFragment();this._container=createElementWithClass('div','context-detail-container');this._fragment.appendChild(this._container);this._build(context);}
_build(context){const title=context.contextType==='realtime'?ls`AudioContext`:ls`OfflineAudioContext`;this._addTitle(title,context.contextId);this._addEntry(ls`State`,context.contextState);this._addEntry(ls`Sample Rate`,context.sampleRate,'Hz');if(context.contextType==='realtime'){this._addEntry(ls`Callback Buffer Size`,context.callbackBufferSize,'frames');}
this._addEntry(ls`Max Output Channels`,context.maxOutputChannelCount,'ch');}
_addTitle(title,subtitle){this._container.appendChild(Fragment.html`
      <div class="context-detail-header">
        <div class="context-detail-title">${title}</div>
        <div class="context-detail-subtitle">${subtitle}</div>
      </div>
    `);}
_addEntry(entry,value,unit){const valueWithUnit=value+(unit?` ${unit}`:'');this._container.appendChild(Fragment.html`
      <div class="context-detail-row">
        <div class="context-detail-row-entry">${entry}</div>
        <div class="context-detail-row-value">${valueWithUnit}</div>
      </div>
    `);}
getFragment(){return this._fragment;}}
class ContextSummaryBuilder{constructor(contextId,contextRealtimeData){const time=contextRealtimeData.currentTime.toFixed(3);const mean=(contextRealtimeData.callbackIntervalMean*1000).toFixed(3);const stddev=(Math.sqrt(contextRealtimeData.callbackIntervalVariance)*1000).toFixed(3);const capacity=(contextRealtimeData.renderCapacity*100).toFixed(3);this._fragment=createDocumentFragment();this._fragment.appendChild(Fragment.html`
      <div class="context-summary-container">
        <span>${ls`Current Time`}: ${time} s</span>
        <span>\u2758</span>
        <span>${ls`Callback Interval`}: μ = ${mean} ms, σ = ${stddev} ms</span>
        <span>\u2758</span>
        <span>${ls`Render Capacity`}: ${capacity} %</span>
      </div>
    `);}
getFragment(){return this._fragment;}}
var AudioContextContentBuilder=Object.freeze({__proto__:null,ContextDetailBuilder:ContextDetailBuilder,ContextSummaryBuilder:ContextSummaryBuilder});class WebAudioView extends ThrottledWidget.ThrottledWidget{constructor(){super(true,1000);this.element.classList.add('web-audio-drawer');this.registerRequiredCSS('web_audio/webAudio.css');const toolbarContainer=this.contentElement.createChild('div','web-audio-toolbar-container vbox');this._contextSelector=new AudioContextSelector();const toolbar=new Toolbar.Toolbar('web-audio-toolbar',toolbarContainer);toolbar.appendToolbarItem(Toolbar.Toolbar.createActionButtonForId('components.collect-garbage'));toolbar.appendSeparator();toolbar.appendToolbarItem(this._contextSelector.toolbarItem());this._contentContainer=this.contentElement.createChild('div','web-audio-content-container vbox flex-auto');this._detailViewContainer=this._contentContainer.createChild('div','web-audio-details-container vbox flex-auto');this._graphManager=new GraphManager();this._landingPage=new Widget.VBox();this._landingPage.contentElement.classList.add('web-audio-landing-page','fill');this._landingPage.contentElement.appendChild(Fragment.html`
      <div>
        <p>${ls`Open a page that uses Web Audio API to start monitoring.`}</p>
      </div>
    `);this._landingPage.show(this._detailViewContainer);this._summaryBarContainer=this._contentContainer.createChild('div','web-audio-summary-container');this._contextSelector.addEventListener(Events$2.ContextSelected,event=>{const context=(event.data);this._updateDetailView(context);this.doUpdate();});SDKModel.TargetManager.instance().observeModels(WebAudioModel,this);}
wasShown(){super.wasShown();for(const model of SDKModel.TargetManager.instance().models(WebAudioModel)){this._addEventListeners(model);}}
willHide(){for(const model of SDKModel.TargetManager.instance().models(WebAudioModel)){this._removeEventListeners(model);}}
modelAdded(webAudioModel){if(this.isShowing()){this._addEventListeners(webAudioModel);}}
modelRemoved(webAudioModel){this._removeEventListeners(webAudioModel);}
async doUpdate(){await this._pollRealtimeData();this.update();}
_addEventListeners(webAudioModel){webAudioModel.ensureEnabled();webAudioModel.addEventListener(Events$1.ContextCreated,this._contextCreated,this);webAudioModel.addEventListener(Events$1.ContextDestroyed,this._contextDestroyed,this);webAudioModel.addEventListener(Events$1.ContextChanged,this._contextChanged,this);webAudioModel.addEventListener(Events$1.ModelReset,this._reset,this);webAudioModel.addEventListener(Events$1.ModelSuspend,this._suspendModel,this);webAudioModel.addEventListener(Events$1.AudioListenerCreated,this._audioListenerCreated,this);webAudioModel.addEventListener(Events$1.AudioListenerWillBeDestroyed,this._audioListenerWillBeDestroyed,this);webAudioModel.addEventListener(Events$1.AudioNodeCreated,this._audioNodeCreated,this);webAudioModel.addEventListener(Events$1.AudioNodeWillBeDestroyed,this._audioNodeWillBeDestroyed,this);webAudioModel.addEventListener(Events$1.AudioParamCreated,this._audioParamCreated,this);webAudioModel.addEventListener(Events$1.AudioParamWillBeDestroyed,this._audioParamWillBeDestroyed,this);webAudioModel.addEventListener(Events$1.NodesConnected,this._nodesConnected,this);webAudioModel.addEventListener(Events$1.NodesDisconnected,this._nodesDisconnected,this);webAudioModel.addEventListener(Events$1.NodeParamConnected,this._nodeParamConnected,this);webAudioModel.addEventListener(Events$1.NodeParamDisconnected,this._nodeParamDisconnected,this);}
_removeEventListeners(webAudioModel){webAudioModel.removeEventListener(Events$1.ContextCreated,this._contextCreated,this);webAudioModel.removeEventListener(Events$1.ContextDestroyed,this._contextDestroyed,this);webAudioModel.removeEventListener(Events$1.ContextChanged,this._contextChanged,this);webAudioModel.removeEventListener(Events$1.ModelReset,this._reset,this);webAudioModel.removeEventListener(Events$1.ModelSuspend,this._suspendModel,this);webAudioModel.removeEventListener(Events$1.AudioListenerCreated,this._audioListenerCreated,this);webAudioModel.removeEventListener(Events$1.AudioListenerWillBeDestroyed,this._audioListenerWillBeDestroyed,this);webAudioModel.removeEventListener(Events$1.AudioNodeCreated,this._audioNodeCreated,this);webAudioModel.removeEventListener(Events$1.AudioNodeWillBeDestroyed,this._audioNodeWillBeDestroyed,this);webAudioModel.removeEventListener(Events$1.AudioParamCreated,this._audioParamCreated,this);webAudioModel.removeEventListener(Events$1.AudioParamWillBeDestroyed,this._audioParamWillBeDestroyed,this);webAudioModel.removeEventListener(Events$1.NodesConnected,this._nodesConnected,this);webAudioModel.removeEventListener(Events$1.NodesDisconnected,this._nodesDisconnected,this);webAudioModel.removeEventListener(Events$1.NodeParamConnected,this._nodeParamConnected,this);webAudioModel.removeEventListener(Events$1.NodeParamDisconnected,this._nodeParamDisconnected,this);}
_contextCreated(event){const context=(event.data);this._graphManager.createContext(context.contextId);this._contextSelector.contextCreated(event);}
_contextDestroyed(event){const contextId=(event.data);this._graphManager.destroyContext(contextId);this._contextSelector.contextDestroyed(event);}
_contextChanged(event){const context=(event.data);if(!this._graphManager.hasContext(context.contextId)){return;}
this._contextSelector.contextChanged(event);}
_reset(){if(this._landingPage.isShowing()){this._landingPage.detach();}
this._contextSelector.reset();this._detailViewContainer.removeChildren();this._landingPage.show(this._detailViewContainer);this._graphManager.clearGraphs();}
_suspendModel(){this._graphManager.clearGraphs();}
_audioListenerCreated(event){const listener=(event.data);const graph=this._graphManager.getGraph(listener.contextId);if(!graph){return;}
graph.addNode({nodeId:listener.listenerId,nodeType:'Listener',numberOfInputs:0,numberOfOutputs:0,});}
_audioListenerWillBeDestroyed(event){const{contextId,listenerId}=event.data;const graph=this._graphManager.getGraph(contextId);if(!graph){return;}
graph.removeNode(listenerId);}
_audioNodeCreated(event){const node=(event.data);const graph=this._graphManager.getGraph(node.contextId);if(!graph){return;}
graph.addNode({nodeId:node.nodeId,nodeType:node.nodeType,numberOfInputs:node.numberOfInputs,numberOfOutputs:node.numberOfOutputs,});}
_audioNodeWillBeDestroyed(event){const{contextId,nodeId}=event.data;const graph=this._graphManager.getGraph(contextId);if(!graph){return;}
graph.removeNode(nodeId);}
_audioParamCreated(event){const param=(event.data);const graph=this._graphManager.getGraph(param.contextId);if(!graph){return;}
graph.addParam({paramId:param.paramId,paramType:param.paramType,nodeId:param.nodeId,});}
_audioParamWillBeDestroyed(event){const{contextId,paramId}=event.data;const graph=this._graphManager.getGraph(contextId);if(!graph){return;}
graph.removeParam(paramId);}
_nodesConnected(event){const{contextId,sourceId,destinationId,sourceOutputIndex,destinationInputIndex}=event.data;const graph=this._graphManager.getGraph(contextId);if(!graph){return;}
graph.addNodeToNodeConnection({sourceId,destinationId,sourceOutputIndex,destinationInputIndex,});}
_nodesDisconnected(event){const{contextId,sourceId,destinationId,sourceOutputIndex,destinationInputIndex}=event.data;const graph=this._graphManager.getGraph(contextId);if(!graph){return;}
graph.removeNodeToNodeConnection({sourceId,destinationId,sourceOutputIndex,destinationInputIndex,});}
_nodeParamConnected(event){const{contextId,sourceId,destinationId,sourceOutputIndex}=event.data;const graph=this._graphManager.getGraph(contextId);if(!graph){return;}
const nodeId=graph.getNodeIdByParamId(destinationId);if(!nodeId){return;}
graph.addNodeToParamConnection({sourceId,destinationId:nodeId,sourceOutputIndex,destinationParamId:destinationId,});}
_nodeParamDisconnected(event){const{contextId,sourceId,destinationId,sourceOutputIndex}=event.data;const graph=this._graphManager.getGraph(contextId);if(!graph){return;}
const nodeId=graph.getNodeIdByParamId(destinationId);if(!nodeId){return;}
graph.removeNodeToParamConnection({sourceId,destinationId:nodeId,sourceOutputIndex,destinationParamId:destinationId,});}
_updateDetailView(context){if(this._landingPage.isShowing()){this._landingPage.detach();}
const detailBuilder=new ContextDetailBuilder(context);this._detailViewContainer.removeChildren();this._detailViewContainer.appendChild(detailBuilder.getFragment());}
_updateSummaryBar(contextId,contextRealtimeData){const summaryBuilder=new ContextSummaryBuilder(contextId,contextRealtimeData);this._summaryBarContainer.removeChildren();this._summaryBarContainer.appendChild(summaryBuilder.getFragment());}
_clearSummaryBar(){this._summaryBarContainer.removeChildren();}
async _pollRealtimeData(){const context=this._contextSelector.selectedContext();if(!context){this._clearSummaryBar();return;}
for(const model of SDKModel.TargetManager.instance().models(WebAudio.WebAudioModel)){if(context.contextType==='realtime'){if(!this._graphManager.hasContext(context.contextId)){continue;}
const realtimeData=await model.requestRealtimeData(context.contextId);if(realtimeData){this._updateSummaryBar(context.contextId,realtimeData);}}else{this._clearSummaryBar();}}}}
var WebAudioView$1=Object.freeze({__proto__:null,WebAudioView:WebAudioView});export{AudioContextContentBuilder,AudioContextSelector$1 as AudioContextSelector,EdgeView$1 as EdgeView,GraphManager$1 as GraphManager,GraphStyle,GraphView$1 as GraphView,NodeRendererUtility,NodeView$1 as NodeView,WebAudioModel$1 as WebAudioModel,WebAudioView$1 as WebAudioView};