@node-projects/web-component-designer-visualization-addons 0.3.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index-min.js CHANGED
@@ -1,12 +1,12 @@
1
- Blockly.Blocks.console={init:function(){this.appendDummyInput().appendField("console").appendField(new Blockly.FieldDropdown([["debug","DEBUG"],["error","ERROR"],["info","INFO"],["log","LOG"],["warn","WARN"]]),"LEVEL"),this.appendValueInput("VALUE").setCheck(null).appendField("value"),this.setInputsInline(!0),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(230)}};Blockly.JavaScript.forBlock.console=function(o,e){var t=o.getFieldValue("LEVEL");let i=Blockly.JavaScript.valueToCode(o,"VALUE",Blockly.JavaScript.ORDER_ATOMIC);return`console['${t.toLowerCase()}'](${i});
2
- `};Blockly.Blocks.debugger={init:function(){this.appendDummyInput().appendField("debugger"),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(230)}};Blockly.JavaScript.forBlock.debugger=function(o){return`debugger;
3
- `};Blockly.Blocks.delay={init:function(){this.appendValueInput("DELAY").setCheck("Number").appendField("delay"),this.setInputsInline(!0),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(230)}};Blockly.JavaScript.forBlock.delay=function(o){return"await delay("+Blockly.JavaScript.valueToCode(o,"DELAY",Blockly.JavaScript.ORDER_ATOMIC)+`);
4
- `};Blockly.Blocks.get_parameter={init:function(){this.appendValueInput("NAME").setCheck("String").appendField("get_parameter"),this.setInputsInline(!0),this.setOutput(!0,null),this.setColour(230)}};Blockly.JavaScript.forBlock.get_parameter=function(o,e){return[`context.parameters[${Blockly.JavaScript.valueToCode(o,"NAME",Blockly.JavaScript.ORDER_ATOMIC)}]`,Blockly.JavaScript.ORDER_NONE]};Blockly.Blocks.get_state={init:function(){this.appendValueInput("OID").setCheck("String").appendField("get_state"),this.setInputsInline(!0),this.setOutput(!0,null),this.setColour(230)}};Blockly.JavaScript.forBlock.get_state=function(o,e){let t=Blockly.JavaScript.valueToCode(o,"OID",Blockly.JavaScript.ORDER_ATOMIC);return[`(await visualizationHandler.getState((${t}[0] === '.' ? relativeSignalsPath : '') + ${t})).val`,Blockly.JavaScript.ORDER_NONE]};Blockly.Blocks.get_sub_property={init:function(){this.appendDummyInput().appendField("getSubProperty"),this.appendValueInput("OBJECT").setCheck("Object").appendField("object"),this.appendValueInput("PROPERTYPATH").setCheck("String").appendField("propertypath"),this.setInputsInline(!0),this.setOutput(!0,null),this.setColour(230)}};Blockly.JavaScript.forBlock.get_sub_property=function(o,e){let t=Blockly.JavaScript.valueToCode(o,"OBJECT",Blockly.JavaScript.ORDER_ATOMIC),i=Blockly.JavaScript.valueToCode(o,"PROPERTYPATH",Blockly.JavaScript.ORDER_ATOMIC);return[`extractPart(${t}, ${i})`,Blockly.JavaScript.ORDER_NONE]};Blockly.Blocks.open_screen={init:function(){this.appendDummyInput().appendField("open screen"),this.appendValueInput("SCREEN").setCheck("String").appendField("screen"),this.appendValueInput("RELATIVESIGNALSPATH").setCheck("String").appendField("relativeSignalsPath"),this.appendValueInput("NOHISTORY").setCheck("Boolean").appendField("noHistory"),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(230)}};Blockly.JavaScript.forBlock.open_screen=function(o){let e=Blockly.JavaScript.valueToCode(o,"SCREEN",Blockly.JavaScript.ORDER_ATOMIC),t=Blockly.JavaScript.valueToCode(o,"RELATIVESIGNALSPATH",Blockly.JavaScript.ORDER_ATOMIC),i=Blockly.JavaScript.valueToCode(o,"NOHISTORY",Blockly.JavaScript.ORDER_ATOMIC);return`RUNTIME.openScreen({screen: ${e}, relativeSignalsPath: ${t}, noHistory: ${i}})`};Blockly.Blocks.query_selector={init:function(){this.appendDummyInput().appendField("querySelector").appendField(new Blockly.FieldDropdown([["currentScreen","CURRENTSCREEN"],["parentScreen","PARENTSCREEN"]]),"SOURCE"),this.appendValueInput("SELECTOR").setCheck("String").appendField("selector"),this.setInputsInline(!0),this.setOutput(!0,"Element"),this.setColour(230)}};Blockly.JavaScript.forBlock.query_selector=function(o,e){var t=o.getFieldValue("SOURCE");let i=Blockly.JavaScript.valueToCode(o,"SELECTOR",Blockly.JavaScript.ORDER_ATOMIC),s;return t==="CURRENTSCREEN"?s=`shadowRoot.querySelector(${i})`:t==="PARENTSCREEN"&&(s=`shadowRoot.host.getRootNode().querySelector(${i})`),[s,Blockly.JavaScript.ORDER_NONE]};Blockly.Blocks.query_selector_all={init:function(){this.appendDummyInput().appendField("querySelectorAll").appendField(new Blockly.FieldDropdown([["currentScreen","CURRENTSCREEN"],["parentScreen","PARENTSCREEN"]]),"SOURCE"),this.appendValueInput("SELECTOR").setCheck("String").appendField("selector"),this.setInputsInline(!0),this.setOutput(!0,"Array"),this.setColour(230)}};Blockly.JavaScript.forBlock.query_selector_all=function(o,e){var t=o.getFieldValue("SOURCE");let i=Blockly.JavaScript.valueToCode(o,"SELECTOR",Blockly.JavaScript.ORDER_ATOMIC),s;return t==="CURRENTSCREEN"?s=`shadowRoot.querySelectorall(${i})`:t==="PARENTSCREEN"&&(s=`shadowRoot.querySelectorall(${i})`),[s,Blockly.JavaScript.ORDER_NONE]};Blockly.Blocks.set_element={init:function(){this.appendDummyInput().appendField("setElement").appendField(new Blockly.FieldDropdown([["property","PROPERTY"],["attribute","ATTRIBUTE"],["style","STYLE"]]),"TARGET"),this.appendValueInput("ELEMENT").setCheck("Element").appendField("element"),this.appendValueInput("NAME").setCheck("String").appendField("name"),this.appendValueInput("VALUE").setCheck(null).appendField("value"),this.setInputsInline(!0),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(230)}};Blockly.JavaScript.forBlock.set_element=function(o){var e=o.getFieldValue("TARGET");let t=Blockly.JavaScript.valueToCode(o,"ELEMENT",Blockly.JavaScript.ORDER_ATOMIC),i=Blockly.JavaScript.valueToCode(o,"NAME",Blockly.JavaScript.ORDER_ATOMIC),s=Blockly.JavaScript.valueToCode(o,"VALUE",Blockly.JavaScript.ORDER_ATOMIC),l="";return e==="PROPERTY"?l+=t+"["+i+"] = "+s+`;
1
+ Blockly.Blocks.console={init:function(){this.appendDummyInput().appendField("console").appendField(new Blockly.FieldDropdown([["debug","DEBUG"],["error","ERROR"],["info","INFO"],["log","LOG"],["warn","WARN"]]),"LEVEL"),this.appendValueInput("VALUE").setCheck(null).appendField("value"),this.setInputsInline(!0),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(230)}};Blockly.JavaScript.forBlock.console=function(r,e){var t=r.getFieldValue("LEVEL");let i=Blockly.JavaScript.valueToCode(r,"VALUE",Blockly.JavaScript.ORDER_ATOMIC);return`console['${t.toLowerCase()}'](${i});
2
+ `};Blockly.Blocks.debugger={init:function(){this.appendDummyInput().appendField("debugger"),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(230)}};Blockly.JavaScript.forBlock.debugger=function(r){return`debugger;
3
+ `};Blockly.Blocks.delay={init:function(){this.appendValueInput("DELAY").setCheck("Number").appendField("delay"),this.setInputsInline(!0),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(230)}};Blockly.JavaScript.forBlock.delay=function(r){return"await delay("+Blockly.JavaScript.valueToCode(r,"DELAY",Blockly.JavaScript.ORDER_ATOMIC)+`);
4
+ `};Blockly.Blocks.get_parameter={init:function(){this.appendValueInput("NAME").setCheck("String").appendField("get_parameter"),this.setInputsInline(!0),this.setOutput(!0,null),this.setColour(230)}};Blockly.JavaScript.forBlock.get_parameter=function(r,e){return[`context.parameters[${Blockly.JavaScript.valueToCode(r,"NAME",Blockly.JavaScript.ORDER_ATOMIC)}]`,Blockly.JavaScript.ORDER_NONE]};Blockly.Blocks.get_state={init:function(){this.appendValueInput("OID").setCheck("String").appendField("get_state"),this.setInputsInline(!0),this.setOutput(!0,null),this.setColour(230)}};Blockly.JavaScript.forBlock.get_state=function(r,e){let t=Blockly.JavaScript.valueToCode(r,"OID",Blockly.JavaScript.ORDER_ATOMIC);return[`(await visualizationHandler.getState((${t}[0] === '.' ? relativeSignalsPath : '') + ${t})).val`,Blockly.JavaScript.ORDER_NONE]};Blockly.Blocks.get_sub_property={init:function(){this.appendDummyInput().appendField("getSubProperty"),this.appendValueInput("OBJECT").setCheck("Object").appendField("object"),this.appendValueInput("PROPERTYPATH").setCheck("String").appendField("propertypath"),this.setInputsInline(!0),this.setOutput(!0,null),this.setColour(230)}};Blockly.JavaScript.forBlock.get_sub_property=function(r,e){let t=Blockly.JavaScript.valueToCode(r,"OBJECT",Blockly.JavaScript.ORDER_ATOMIC),i=Blockly.JavaScript.valueToCode(r,"PROPERTYPATH",Blockly.JavaScript.ORDER_ATOMIC);return[`extractPart(${t}, ${i})`,Blockly.JavaScript.ORDER_NONE]};Blockly.Blocks.open_screen={init:function(){this.appendDummyInput().appendField("open screen"),this.appendValueInput("SCREEN").setCheck("String").appendField("screen"),this.appendValueInput("RELATIVESIGNALSPATH").setCheck("String").appendField("relativeSignalsPath"),this.appendValueInput("NOHISTORY").setCheck("Boolean").appendField("noHistory"),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(230)}};Blockly.JavaScript.forBlock.open_screen=function(r){let e=Blockly.JavaScript.valueToCode(r,"SCREEN",Blockly.JavaScript.ORDER_ATOMIC),t=Blockly.JavaScript.valueToCode(r,"RELATIVESIGNALSPATH",Blockly.JavaScript.ORDER_ATOMIC),i=Blockly.JavaScript.valueToCode(r,"NOHISTORY",Blockly.JavaScript.ORDER_ATOMIC);return`RUNTIME.openScreen({screen: ${e}, relativeSignalsPath: ${t}, noHistory: ${i}})`};Blockly.Blocks.query_selector={init:function(){this.appendDummyInput().appendField("querySelector").appendField(new Blockly.FieldDropdown([["currentScreen","CURRENTSCREEN"],["parentScreen","PARENTSCREEN"]]),"SOURCE"),this.appendValueInput("SELECTOR").setCheck("String").appendField("selector"),this.setInputsInline(!0),this.setOutput(!0,"Element"),this.setColour(230)}};Blockly.JavaScript.forBlock.query_selector=function(r,e){var t=r.getFieldValue("SOURCE");let i=Blockly.JavaScript.valueToCode(r,"SELECTOR",Blockly.JavaScript.ORDER_ATOMIC),s;return t==="CURRENTSCREEN"?s=`shadowRoot.querySelector(${i})`:t==="PARENTSCREEN"&&(s=`shadowRoot.host.getRootNode().querySelector(${i})`),[s,Blockly.JavaScript.ORDER_NONE]};Blockly.Blocks.query_selector_all={init:function(){this.appendDummyInput().appendField("querySelectorAll").appendField(new Blockly.FieldDropdown([["currentScreen","CURRENTSCREEN"],["parentScreen","PARENTSCREEN"]]),"SOURCE"),this.appendValueInput("SELECTOR").setCheck("String").appendField("selector"),this.setInputsInline(!0),this.setOutput(!0,"Array"),this.setColour(230)}};Blockly.JavaScript.forBlock.query_selector_all=function(r,e){var t=r.getFieldValue("SOURCE");let i=Blockly.JavaScript.valueToCode(r,"SELECTOR",Blockly.JavaScript.ORDER_ATOMIC),s;return t==="CURRENTSCREEN"?s=`shadowRoot.querySelectorall(${i})`:t==="PARENTSCREEN"&&(s=`shadowRoot.querySelectorall(${i})`),[s,Blockly.JavaScript.ORDER_NONE]};Blockly.Blocks.set_element={init:function(){this.appendDummyInput().appendField("setElement").appendField(new Blockly.FieldDropdown([["property","PROPERTY"],["attribute","ATTRIBUTE"],["style","STYLE"]]),"TARGET"),this.appendValueInput("ELEMENT").setCheck("Element").appendField("element"),this.appendValueInput("NAME").setCheck("String").appendField("name"),this.appendValueInput("VALUE").setCheck(null).appendField("value"),this.setInputsInline(!0),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(230)}};Blockly.JavaScript.forBlock.set_element=function(r){var e=r.getFieldValue("TARGET");let t=Blockly.JavaScript.valueToCode(r,"ELEMENT",Blockly.JavaScript.ORDER_ATOMIC),i=Blockly.JavaScript.valueToCode(r,"NAME",Blockly.JavaScript.ORDER_ATOMIC),s=Blockly.JavaScript.valueToCode(r,"VALUE",Blockly.JavaScript.ORDER_ATOMIC),l="";return e==="PROPERTY"?l+=t+"["+i+"] = "+s+`;
5
5
  `:e==="ATTRIBUTE"?l+=t+".setAttribute("+i+", "+s+`);
6
6
  `:e==="STYLE"&&(l+=t+".style["+i+"] = "+s+`;
7
- `),l};Blockly.Blocks.set_state={init:function(){this.appendValueInput("OID").setCheck("String").appendField("set_state"),this.appendValueInput("VALUE").setCheck(null).appendField("with"),this.setInputsInline(!0),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(230)}};Blockly.JavaScript.forBlock.set_state=function(o){let e=Blockly.JavaScript.valueToCode(o,"OID",Blockly.JavaScript.ORDER_ATOMIC),t=Blockly.JavaScript.valueToCode(o,"VALUE",Blockly.JavaScript.ORDER_ATOMIC);return`await visualizationHandler.setState((${e}[0] === '.' ? relativeSignalsPath : '') + ${e}, ${t});
8
- `};Blockly.defineBlocksWithJsonArray([{type:"start_event",message0:"Event %1",nextStatement:null,style:"hat_blocks",args0:[{type:"field_variable",name:"EVENTVAR",variable:"event"}]}]);Blockly.JavaScript.forBlock.start_event=function(o){return Blockly.JavaScript.getVariableName(o.getField("EVENTVAR").variable.name)+` = eventData;
9
- `};var tt=`function extractPart(obj, propertyPath) {
7
+ `),l};Blockly.Blocks.set_state={init:function(){this.appendValueInput("OID").setCheck("String").appendField("set_state"),this.appendValueInput("VALUE").setCheck(null).appendField("with"),this.setInputsInline(!0),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(230)}};Blockly.JavaScript.forBlock.set_state=function(r){let e=Blockly.JavaScript.valueToCode(r,"OID",Blockly.JavaScript.ORDER_ATOMIC),t=Blockly.JavaScript.valueToCode(r,"VALUE",Blockly.JavaScript.ORDER_ATOMIC);return`await visualizationHandler.setState((${e}[0] === '.' ? relativeSignalsPath : '') + ${e}, ${t});
8
+ `};Blockly.defineBlocksWithJsonArray([{type:"start_event",message0:"Event %1",nextStatement:null,style:"hat_blocks",args0:[{type:"field_variable",name:"EVENTVAR",variable:"event"}]}]);Blockly.JavaScript.forBlock.start_event=function(r){return Blockly.JavaScript.getVariableName(r.getField("EVENTVAR").variable.name)+` = eventData;
9
+ `};var ot=`function extractPart(obj, propertyPath) {
10
10
  let retVal = obj;
11
11
  for (let p of propertyPath.split('.')) {
12
12
  retVal = retVal?.[p];
@@ -21,16 +21,16 @@ function delay(ms) {
21
21
  }
22
22
 
23
23
  export async function run(eventData, shadowRoot, parameters, relativeSignalsPath, visualizationHandler, context) {
24
- `,it="}";async function ke(o){let e=new Blockly.Workspace;Blockly.serialization.workspaces.load(o,e),Blockly.JavaScript.addReservedWords("eventData"),Blockly.JavaScript.addReservedWords("shadowRoot"),Blockly.JavaScript.addReservedWords("extractPart"),Blockly.JavaScript.addReservedWords("parameters"),Blockly.JavaScript.addReservedWords("relativeSignalsPath"),Blockly.JavaScript.addReservedWords("delay"),Blockly.JavaScript.addReservedWords("visualizationHandler"),Blockly.JavaScript.addReservedWords("context");let t=Blockly.JavaScript.workspaceToCode(e);return(await import(URL.createObjectURL(new Blob([tt+t+it],{type:"application/javascript"})))).run}import{BaseCustomWebComponentConstructorAppend as st,html as nt,css as at}from"@node-projects/base-custom-webcomponent";var Y=class extends st{static template=nt`
24
+ `,rt="}";async function Ee(r){let e=new Blockly.Workspace;Blockly.serialization.workspaces.load(r,e),Blockly.JavaScript.addReservedWords("eventData"),Blockly.JavaScript.addReservedWords("shadowRoot"),Blockly.JavaScript.addReservedWords("extractPart"),Blockly.JavaScript.addReservedWords("parameters"),Blockly.JavaScript.addReservedWords("relativeSignalsPath"),Blockly.JavaScript.addReservedWords("delay"),Blockly.JavaScript.addReservedWords("visualizationHandler"),Blockly.JavaScript.addReservedWords("context");let t=Blockly.JavaScript.workspaceToCode(e);return(await import(URL.createObjectURL(new Blob([ot+t+rt],{type:"application/javascript"})))).run}import{BaseCustomWebComponentConstructorAppend as lt,html as ct,css as pt}from"@node-projects/base-custom-webcomponent";var Y=class extends lt{static template=ct`
25
25
  <div id="blocklyDiv" style="position: absolute; width: 100%; height: 100%;"></div>
26
- `;static style=at`
26
+ `;static style=pt`
27
27
  :host {
28
28
  box-sizing: border-box;
29
29
  position: absolute;
30
30
  height: 100%;
31
31
  width: 100%;
32
32
  display: block;
33
- }`;static is="node-projects-blockly-script-editor";blocklyDiv;workspace;resizeObserver;_toolbox;constructor(e){super(),super._restoreCachedInititalValues(),this._toolbox=e,this.blocklyDiv=this._getDomElement("blocklyDiv"),this._assignEvents(),this.createBlockly()}createBlockly(){let e="zelos",i=Blockly.Theme.defineTheme("webui",{base:Blockly.Themes.Zelos,blockStyles:{hat_blocks:{colourPrimary:"#4a148c"}},categoryStyles:{start_category:{colour:"#4a148c"},system_category:{colour:"#01579b"}}});this.workspace=Blockly.inject(this.blocklyDiv,{theme:i,toolbox:this._toolbox,renderer:e,trashcan:!0,zoom:{controls:!0,wheel:!1,startScale:.7,maxScale:3,minScale:.3,scaleSpeed:1.2,pinch:!1},move:{scrollbars:{horizontal:!0,vertical:!0},drag:!0,wheel:!0},maxInstances:{start_event:1}}),new ZoomToFitControl(this.workspace).init()}ready(){Blockly.svgResize(this.workspace),this.resizeObserver=new ResizeObserver(e=>{Blockly.svgResize(this.workspace)}),this.resizeObserver.observe(this)}save(){return Blockly.serialization.workspaces.save(this.workspace)}load(e){Blockly.serialization.workspaces.load(e,this.workspace)}};customElements.define(Y.is,Y);import{BaseCustomWebComponentConstructorAppend as ct,html as pt,css as dt}from"@node-projects/base-custom-webcomponent";import{BindingMode as ut,BindingTarget as Te,assetsPath as ue}from"@node-projects/web-component-designer";import{BaseCustomWebComponentConstructorAppend as ot,html as rt,css as lt}from"@node-projects/base-custom-webcomponent";var K=class extends ot{static template=rt`
33
+ }`;static is="node-projects-blockly-script-editor";blocklyDiv;workspace;resizeObserver;_toolbox;constructor(e){super(),super._restoreCachedInititalValues(),this._toolbox=e,this.blocklyDiv=this._getDomElement("blocklyDiv"),this._assignEvents(),this.createBlockly()}createBlockly(){let e="zelos",i=Blockly.Theme.defineTheme("webui",{base:Blockly.Themes.Zelos,blockStyles:{hat_blocks:{colourPrimary:"#4a148c"}},categoryStyles:{start_category:{colour:"#4a148c"},system_category:{colour:"#01579b"}}});this.workspace=Blockly.inject(this.blocklyDiv,{theme:i,toolbox:this._toolbox,renderer:e,trashcan:!0,zoom:{controls:!0,wheel:!1,startScale:.7,maxScale:3,minScale:.3,scaleSpeed:1.2,pinch:!1},move:{scrollbars:{horizontal:!0,vertical:!0},drag:!0,wheel:!0},maxInstances:{start_event:1}}),new ZoomToFitControl(this.workspace).init()}ready(){Blockly.svgResize(this.workspace),this.resizeObserver=new ResizeObserver(e=>{Blockly.svgResize(this.workspace)}),this.resizeObserver.observe(this)}save(){return Blockly.serialization.workspaces.save(this.workspace)}load(e){Blockly.serialization.workspaces.load(e,this.workspace)}};customElements.define(Y.is,Y);import{BaseCustomWebComponentConstructorAppend as ht,html as gt,css as ft}from"@node-projects/base-custom-webcomponent";import{BindingMode as yt,BindingTarget as Ne,assetsPath as me}from"@node-projects/web-component-designer";import{BaseCustomWebComponentConstructorAppend as dt,html as ut,css as mt}from"@node-projects/base-custom-webcomponent";var K=class extends dt{static template=ut`
34
34
  <span style="position:absolute;left:30px;top:26px;">from</span>
35
35
  <span style="position:absolute;left:30px;top:77px;">count</span>
36
36
  <span style="position:absolute;left:30px;top:123px;">limit</span>
@@ -97,10 +97,10 @@ export async function run(eventData, shadowRoot, parameters, relativeSignalsPath
97
97
  <input css:visibility="[[this.historic.aggregate == 'quantile' ? 'visible' : 'collapse']]" value="{{this.historic.quantile}}" type="number" id="quantile" style="position:absolute;left:107px;top:325px;width:153px;">
98
98
  <span css:visibility="[[this.historic.aggregate == 'quantile' ? 'visible' : 'collapse']]" id="lblQuantile" style="position:absolute;left:30px;top:325px;">quantile</span>
99
99
  <span style="position:absolute;left:34px;top:417px;">instance</span>
100
- <input type="text" value="{{?this.historic.instance}}" style="position:absolute;left:104px;top:419px;width:155px;">`;static style=lt`
100
+ <input type="text" value="{{?this.historic.instance}}" style="position:absolute;left:104px;top:419px;width:155px;">`;static style=mt`
101
101
  :host {
102
102
  box-sizing: border-box;
103
- }`;static is="node-projects-visualization-bindings-editor-historic";historic;static properties={historic:Object};constructor(e){super(),this._restoreCachedInititalValues(),this.historic=e??{reloadInterval:2e3}}ready(){this._bindingsParse()}#e=!1;refresh(){this.#e||(this.#e=!0,this._bindingsRefresh(null,!0),this.#e=!1)}};customElements.define(K.is,K);var be=`<!DOCTYPE html>
103
+ }`;static is="node-projects-visualization-bindings-editor-historic";historic;static properties={historic:Object};constructor(e){super(),this._restoreCachedInititalValues(),this.historic=e??{reloadInterval:2e3}}ready(){this._bindingsParse()}#e=!1;refresh(){this.#e||(this.#e=!0,this._bindingsRefresh(null,!0),this.#e=!1)}};customElements.define(K.is,K);var we=`<!DOCTYPE html>
104
104
  <html>
105
105
  <head>
106
106
  <meta charset="UTF-8">
@@ -331,7 +331,7 @@ __res <span style="color:#6a737d;font-style:italic">// the res
331
331
 
332
332
  </div>
333
333
  </body>
334
- </html>`;var he=class o extends ct{static template=pt`
334
+ </html>`;var he=class r extends ht{static template=gt`
335
335
  <div id="root">
336
336
  <div class="vertical-grid">
337
337
  <div id="full-width-col">
@@ -386,7 +386,7 @@ __res <span style="color:#6a737d;font-style:italic">// the res
386
386
  <input id="namedConverterInput" value="{{?this.convertersString::change}}">
387
387
  <button id="namedConverterBrowse" class="signal-select-btn" @click="[[this._selectNamedConverter()]]">...</button>
388
388
  </div>
389
- <div class="bordered-section">
389
+ <div id="converterSection" class="bordered-section">
390
390
  <div class="signal-row signal-header">
391
391
  <span class="converter-header-col">condition</span>
392
392
  <span class="converter-header-col">value</span>
@@ -395,7 +395,7 @@ __res <span style="color:#6a737d;font-style:italic">// the res
395
395
  <div id="converterListContainer"></div>
396
396
  <button class="add-signal-btn" @click="[[this._addConverter()]]">+ Add entry</button>
397
397
  </div>
398
- </div>`;static style=dt`
398
+ </div>`;static style=ft`
399
399
  :host {
400
400
  box-sizing: border-box;
401
401
  }
@@ -411,10 +411,15 @@ __res <span style="color:#6a737d;font-style:italic">// the res
411
411
  }
412
412
 
413
413
  #converterListContainer {
414
- max-height: 72px;
415
414
  overflow-y: auto;
416
415
  }
417
416
 
417
+ #converterSection {
418
+ display: grid;
419
+ grid-template-rows: min-content minmax(22px, 1fr) min-content;
420
+ min-height: 0;
421
+ }
422
+
418
423
  .input-headline {
419
424
  height: 30px;
420
425
  }
@@ -432,7 +437,7 @@ __res <span style="color:#6a737d;font-style:italic">// the res
432
437
  #root {
433
438
  padding: 2px 10px;
434
439
  display: grid;
435
- grid-template-rows: min-content min-content;
440
+ grid-template-rows: min-content min-content minmax(0, 1fr);
436
441
  overflow: auto;
437
442
  height: calc(100% - 4px)
438
443
  }
@@ -610,6 +615,7 @@ __res <span style="color:#6a737d;font-style:italic">// the res
610
615
 
611
616
  .add-signal-btn {
612
617
  align-self: flex-start;
618
+ justify-self: start;
613
619
  margin-top: 4px;
614
620
  height: 22px;
615
621
  cursor: pointer;
@@ -633,13 +639,13 @@ __res <span style="color:#6a737d;font-style:italic">// the res
633
639
  .info-btn:hover {
634
640
  background: #eee;
635
641
  border-radius: 3px;
636
- }`;static is="node-projects-visualization-bindings-editor";static properties={twoWayPossible:Boolean,twoWay:Boolean,expression:String,events:String,invert:Boolean,historic:Object};twoWayPossible=!1;twoWay=!1;expression="";writeBackSignal="";expressionTwoWay="";historic;objectNames="";events="";invert=!1;converters=[];static namedConverters=[];static helpSections=[];convertersString;get converter(){if(this.convertersString)return this.convertersString;if(this.converters.length>0)return Object.fromEntries(this.converters.map(e=>[e.key,e.value]))}_property;_binding;_bindingTarget;_serviceContainer;_instanceServiceContainer;_shell;_signals=[];_signalListContainer;_converterListContainer;constructor(e,t,i,s,l,r,n={}){super(),super._restoreCachedInititalValues(),this._property=e,this._binding=t,this._bindingTarget=i,this._serviceContainer=s,this._instanceServiceContainer=l,this._shell=r,n?.namedConverters===!1&&(this._getDomElement("namedConverterRow").style.display="none");let a=this._getDomElement("historicBtn");n?.showHistoric===!1?a.style.display="none":n?.historicLabel&&(a.textContent=n.historicLabel)}ready(){if(this._parseAttributesToProperties(),this._assignEvents(),this._signalListContainer=this._getDomElement("signalListContainer"),this._converterListContainer=this._getDomElement("converterListContainer"),this._getDomElement("helpBtn").onclick=()=>this._showHelp(),o.namedConverters.length===0&&(this._getDomElement("namedConverterBrowse").style.display="none"),this.twoWayPossible=!1,(this._bindingTarget==Te.property||this._bindingTarget==Te.attribute)&&(this.twoWayPossible=!0),this._binding){if(this.twoWay=this._binding.mode==ut.twoWay,this.expression=this._binding.expression,this.writeBackSignal=this._binding.writeBackSignal,this.expressionTwoWay=this._binding.expressionTwoWay,this.historic=this._binding.historic,this.invert=this._binding.invert,this._binding.bindableObjectNames&&(this.objectNames=this._binding.bindableObjectNames.join(";")),this._binding.converter)if(typeof this._binding.converter=="string")this.convertersString=this._binding.converter;else for(let e in this._binding.converter)this.converters.push({key:e,value:this._binding.converter[e]});this._binding.changedEvents&&this._binding.changedEvents.length&&(this.events=this._binding.changedEvents.join(";"))}if(this.expression){let e=this._getDomElement("expression");this.expression.indexOf(`
642
+ }`;static is="node-projects-visualization-bindings-editor";static properties={twoWayPossible:Boolean,twoWay:Boolean,expression:String,events:String,invert:Boolean,historic:Object};twoWayPossible=!1;twoWay=!1;expression="";writeBackSignal="";expressionTwoWay="";historic;objectNames="";events="";invert=!1;converters=[];static namedConverters=[];static helpSections=[];convertersString;get converter(){if(this.convertersString)return this.convertersString;if(this.converters.length>0)return Object.fromEntries(this.converters.map(e=>[e.key,e.value]))}_property;_binding;_bindingTarget;_serviceContainer;_instanceServiceContainer;_shell;_signals=[];_signalListContainer;_converterListContainer;constructor(e,t,i,s,l,a,n={}){super(),super._restoreCachedInititalValues(),this._property=e,this._binding=t,this._bindingTarget=i,this._serviceContainer=s,this._instanceServiceContainer=l,this._shell=a,n?.namedConverters===!1&&(this._getDomElement("namedConverterRow").style.display="none");let o=this._getDomElement("historicBtn");n?.showHistoric===!1?o.style.display="none":n?.historicLabel&&(o.textContent=n.historicLabel)}ready(){if(this._parseAttributesToProperties(),this._assignEvents(),this._signalListContainer=this._getDomElement("signalListContainer"),this._converterListContainer=this._getDomElement("converterListContainer"),this._getDomElement("helpBtn").onclick=()=>this._showHelp(),r.namedConverters.length===0&&(this._getDomElement("namedConverterBrowse").style.display="none"),this.twoWayPossible=!1,(this._bindingTarget==Ne.property||this._bindingTarget==Ne.attribute)&&(this.twoWayPossible=!0),this._binding){if(this.twoWay=this._binding.mode==yt.twoWay,this.expression=this._binding.expression,this.writeBackSignal=this._binding.writeBackSignal,this.expressionTwoWay=this._binding.expressionTwoWay,this.historic=this._binding.historic,this.invert=this._binding.invert,this._binding.bindableObjectNames&&(this.objectNames=this._binding.bindableObjectNames.join(";")),this._binding.converter)if(typeof this._binding.converter=="string")this.convertersString=this._binding.converter;else for(let e in this._binding.converter)this.converters.push({key:e,value:this._binding.converter[e]});this._binding.changedEvents&&this._binding.changedEvents.length&&(this.events=this._binding.changedEvents.join(";"))}if(this.expression){let e=this._getDomElement("expression");this.expression.indexOf(`
637
643
  `)>=0&&(e.style.height="51px")}if(this.expressionTwoWay){let e=this._getDomElement("expression2way");this.expressionTwoWay.indexOf(`
638
- `)>=0&&(e.style.height="51px")}this._signals=this._parseObjectNames(this.objectNames),this._signals.length===0&&this._signals.push({name:"",signal:""}),this._renderSignalList(),this._renderConverterList(),this._bindingsParse()}_parseObjectNames(e){return e?e.split(";").filter(t=>t.length>0).map(t=>{let i=t.indexOf(":");return i>0?{name:t.slice(0,i),signal:t.slice(i+1)}:{name:"",signal:t}}):[]}_signalsToObjectNames(){return this._signals.map(e=>e.name?e.name+":"+e.signal:e.signal).join(";")}_renderSignalList(){let e=this._signalListContainer;e.innerHTML="",this._signals.forEach((t,i)=>{let s=document.createElement("div");s.className="signal-row";let l=document.createElement("input");l.className="signal-name-input",l.placeholder=`__${i}`,l.value=t.name,l.title="variable name used in the formula (defaults to __"+i+" if empty)",l.oninput=()=>{this._signals[i].name=l.value,this._syncSignals()};let r=document.createElement("input");r.className="signal-path-input",r.value=t.signal,r.placeholder="signal path",r.title="signal path (prefix: ? = signal name in screen property, ?? = screen property value, ?$ = signal object in screen property, ?@ = screen attribute, # = signal name in target property, ## = target property value, #$ = signal object in target property, #@ = target attribute)",r.oninput=()=>{this._signals[i].signal=r.value,this._syncSignals()};let n=document.createElement("button");n.className="signal-icon-btn",n.title="Duplicate";let a=document.createElement("img");a.src=ue+"icons/copy.svg",a.style.cssText="width:12px; height:12px;",n.appendChild(a),n.onclick=()=>{this._signals.splice(i+1,0,{...this._signals[i]}),this._syncSignals(),this._renderSignalList()};let c=document.createElement("button");c.className="signal-select-btn",c.textContent="...",c.title="Browse signal",c.onclick=()=>this._selectForRow(i,r);let p=document.createElement("button");p.className="signal-icon-btn",p.title="Remove";let d=document.createElement("img");d.src=ue+"icons/delete.svg",d.style.cssText="width:12px; height:12px;",p.appendChild(d),p.onclick=()=>{this._signals.splice(i,1),this._syncSignals(),this._renderSignalList()},s.appendChild(l),s.appendChild(r),s.appendChild(c),s.appendChild(n),s.appendChild(p),e.appendChild(s)})}_syncSignals(){this.objectNames=this._signalsToObjectNames(),this._bindingsRefresh()}_addSignal(){this._signals.push({name:"",signal:""}),this._renderSignalList()}async _selectForRow(e,t){let i=this._shell.createBindableObjectBrowser();i.initialize(this._serviceContainer,this._instanceServiceContainer,"binding"),i.title="select signal...";let s=new AbortController;if(i.objectDoubleclicked.on(()=>{s.abort();let r="";i.selectedObject.specialType=="signalProperty"?r="?":i.selectedObject.bindabletype==="property"&&(r="??"),this._signals[e].signal=r+i.selectedObject.fullName,t.value=this._signals[e].signal,this._syncSignals()}),await this._shell.openConfirmation(i,{x:100,y:100,width:400,height:300,parent:this,abortSignal:s.signal})){let r="";i.selectedObject.specialType=="signalProperty"?r="?":i.selectedObject.bindabletype==="property"&&(r="??"),this._signals[e].signal=r+i.selectedObject.fullName,t.value=this._signals[e].signal,this._syncSignals()}}_renderConverterList(){let e=this._converterListContainer;e.innerHTML="";let t=this._property?.type==="color"?"color":"text";this.converters.forEach((i,s)=>{let l=document.createElement("div");l.className="signal-row";let r=document.createElement("input");r.style.cssText="flex:1 1 auto; height:22px; box-sizing:border-box;",r.value=i.key,r.placeholder="condition",r.oninput=()=>{this.converters[s].key=r.value};let n=document.createElement("input");n.type=t,n.style.cssText="flex:1 1 auto; height:22px; box-sizing:border-box;",n.value=i.value,n.placeholder="value",n.oninput=()=>{this.converters[s].value=n.value};let a=document.createElement("button");a.className="signal-icon-btn",a.title="Duplicate";let c=document.createElement("img");c.src=ue+"icons/copy.svg",c.style.cssText="width:12px; height:12px;",a.appendChild(c),a.onclick=()=>{this.converters.splice(s+1,0,{...this.converters[s]}),this._renderConverterList()};let p=document.createElement("button");p.className="signal-icon-btn",p.title="Remove";let d=document.createElement("img");d.src=ue+"icons/delete.svg",d.style.cssText="width:12px; height:12px;",p.appendChild(d),p.onclick=()=>{this.converters.splice(s,1),this._renderConverterList()},l.appendChild(r),l.appendChild(n),l.appendChild(a),l.appendChild(p),e.appendChild(l)})}_addConverter(){this.converters.push({key:"",value:""}),this._renderConverterList()}async _selectNamedConverter(){let e=o.namedConverters;if(e.length===0)return;let t="",i=null,s=document.createElement("div");s.style.cssText="display:flex; flex-direction:column; height:100%; box-sizing:border-box; font-size:12px;";let l=document.createElement("div");l.style.cssText="padding:6px 8px 4px; color:#666; font-size:11px; border-bottom:1px solid #e0e0e0; flex-shrink:0;",l.textContent="Select a converter and confirm with OK.",s.appendChild(l);let r=document.createElement("div");r.style.cssText="flex:1; overflow-y:auto; padding:4px;",s.appendChild(r);let n=p=>{p.style.background="",p.style.borderLeftColor="transparent"},a=(p,d)=>{i&&n(i),i=p,p.style.background="#e8f4fd",p.style.borderLeftColor="#0078d7",t=d};for(let p of e){let d=document.createElement("div");d.style.cssText="padding:5px 6px 5px 9px; cursor:pointer; border-radius:3px; border-left:3px solid transparent; margin-bottom:2px;";let g=document.createElement("div");if(g.style.cssText="font-family:monospace; font-weight:bold; color:#111;",g.textContent=p.name,d.appendChild(g),p.description){let u=document.createElement("div");u.style.cssText="color:#555; font-size:11px; margin-top:2px;",u.textContent=p.description,d.appendChild(u)}if(p.converter&&Object.keys(p.converter).length>0){let u=document.createElement("div");u.style.cssText="display:grid; grid-template-columns:max-content max-content 1fr; gap:1px 6px; margin-top:4px; padding:4px 6px; background:#f5f5f5; border-radius:2px; font-family:monospace; font-size:11px; color:#333;";for(let[m,y]of Object.entries(p.converter)){let _=document.createElement("span");_.style.cssText="color:#555; text-align:right;",_.textContent=m;let w=document.createElement("span");w.style.cssText="color:#aaa;",w.textContent="\u2192";let C=document.createElement("span");C.style.cssText="color:#0078d7; font-weight:bold;",C.textContent=String(y),u.appendChild(_),u.appendChild(w),u.appendChild(C)}d.appendChild(u)}d.onmouseenter=()=>{d!==i&&(d.style.background="#f5f5f5")},d.onmouseleave=()=>{d!==i&&(d.style.background="")},d.onclick=()=>a(d,p.name),r.appendChild(d)}await this._shell.openConfirmation(s,{x:100,y:100,width:320,height:300,parent:this})&&t&&(this.convertersString=t,this._getDomElement("namedConverterInput").value=t,this._bindingsRefresh())}_refresh(){requestAnimationFrame(()=>{this._bindingsRefresh()})}async showHistoric(){let e=new K(this.historic),t=new AbortController;e.title="Edit historic binding to: "+this._property.name,await this._shell.openConfirmation(e,{x:100,y:100,width:420,height:510,parent:this,abortSignal:t.signal,disableResize:!0,cancelText:"Remove"})?this.historic=e.historic:this.historic=null,this._bindingsRefresh()}_showHelp(){let e=document.createElement("iframe");e.srcdoc=o.helpSections.length>0?be.replace(`</div>
639
- </body>`,o.helpSections.join("")+`</div>
640
- </body>`):be,e.style.cssText="width:100%; height:100%; border:none; display:block;",this._shell.openModal(e,{title:"Bindings Editor Help",parent:this,x:-660,y:-80,width:630,height:580})}};customElements.define(he.is,he);import{BaseCustomWebComponentConstructorAppend as _t,TypedEvent as St,css as kt,html as Tt}from"@node-projects/base-custom-webcomponent";import{ContextMenu as Ct,assetsPath as ve}from"@node-projects/web-component-designer";import{typeInfoFromJsonSchema as Be}from"@node-projects/propertygrid.webcomponent";import{defaultOptions as Et,defaultStyle as Nt}from"@node-projects/web-component-designer-widgets-wunderbaum";import{Wunderbaum as Ot}from"wunderbaum";import It from"wunderbaum/dist/wunderbaum.css"with{type:"css"};import{PropertyGrid as ht}from"@node-projects/propertygrid.webcomponent";import{CodeViewMonaco as Ce}from"@node-projects/web-component-designer-codeview-monaco";var re=class extends ht{serviceContainer;instanceServiceContainer;visualizationHandler;visualizationShell;bindableObjectsTarget="property";constructor(){super()}bindingDoubleClicked;setNameColumnWidth(e){let t=this._tree?.columns?.[0];t&&(t.width=e+"px",this._tree.update("colStructure"))}async getEditorForType(e,t,i,s,l){if(this.getSpecialEditorForType){let r=await this.getSpecialEditorForType(e,t,i,s,l);if(r)return r}switch(e.format){case"screen":{let r=document.createElement("select");r.style.width="100%";let n=document.createElement("option");n.value=t??"",n.innerText=t??"",r.appendChild(n);for(let a of await this.visualizationHandler.getAllNames("screen")){if(a==t)continue;let c=document.createElement("option");c.value=a,c.innerText=a,r.appendChild(c)}return r.onchange=()=>{this.setPropertyValue(i,r.value)},r.value=t,r}case"signal":{let r=document.createElement("div");r.style.display="flex";let n=document.createElement("input");n.value=t??"",n.style.flexGrow="1",n.style.width="0",n.onchange=c=>this.setPropertyValue(i,n.value),n.onfocus=c=>{n.selectionStart=0,n.selectionEnd=n.value?.length},r.appendChild(n);let a=document.createElement("button");return a.textContent="...",a.onclick=async()=>{let c=this.visualizationShell.createBindableObjectBrowser();c.initialize(this.serviceContainer,this.instanceServiceContainer,this.bindableObjectsTarget),c.title="select signal...";let p=new AbortController;c.objectDoubleclicked.on(()=>{this.bindingDoubleClicked&&this.bindingDoubleClicked(c.selectedObject),p.abort(),n.value=c.selectedObject.fullName,this.setPropertyValue(i,n.value)}),await this.visualizationShell.openConfirmation(c,{x:100,y:100,width:400,height:300,parent:this,abortSignal:p.signal})&&(n.value=c.selectedObject.fullName,this.setPropertyValue(i,n.value))},r.appendChild(a),r}case"html":case"script":{let r=document.createElement("div");r.style.boxSizing="border-box",r.style.width="100%",r.style.display="flex";let n=document.createElement("textarea");n.style.boxSizing="border-box",n.value=t??"",n.style.width="100%",n.onblur=c=>{this.setPropertyValue(i,n.value)},r.appendChild(n);let a=document.createElement("button");return a.innerHTML="...",a.style.boxSizing="border-box",a.onclick=async()=>{let c=new Ce,p=await Ce.getMonacoLib();if(e.format=="html")c.language="html";else{let g={content:`declare global {
644
+ `)>=0&&(e.style.height="51px")}this._signals=this._parseObjectNames(this.objectNames),this._signals.length===0&&this._signals.push({name:"",signal:""}),this._renderSignalList(),this._renderConverterList(),this._bindingsParse()}_parseObjectNames(e){return e?e.split(";").filter(t=>t.length>0).map(t=>{let i=t.indexOf(":");return i>0?{name:t.slice(0,i),signal:t.slice(i+1)}:{name:"",signal:t}}):[]}_signalsToObjectNames(){return this._signals.map(e=>e.name?e.name+":"+e.signal:e.signal).join(";")}_renderSignalList(){let e=this._signalListContainer;e.innerHTML="",this._signals.forEach((t,i)=>{let s=document.createElement("div");s.className="signal-row";let l=document.createElement("input");l.className="signal-name-input",l.placeholder=`__${i}`,l.value=t.name,l.title="variable name used in the formula (defaults to __"+i+" if empty)",l.oninput=()=>{this._signals[i].name=l.value,this._syncSignals()};let a=document.createElement("input");a.className="signal-path-input",a.value=t.signal,a.placeholder="signal path",a.title="signal path (prefix: ? = signal name in screen property, ?? = screen property value, ?$ = signal object in screen property, ?@ = screen attribute, # = signal name in target property, ## = target property value, #$ = signal object in target property, #@ = target attribute)",a.oninput=()=>{this._signals[i].signal=a.value,this._syncSignals()};let n=document.createElement("button");n.className="signal-icon-btn",n.title="Duplicate";let o=document.createElement("img");o.src=me+"icons/copy.svg",o.style.cssText="width:12px; height:12px;",n.appendChild(o),n.onclick=()=>{this._signals.splice(i+1,0,{...this._signals[i]}),this._syncSignals(),this._renderSignalList()};let c=document.createElement("button");c.className="signal-select-btn",c.textContent="...",c.title="Browse signal",c.onclick=()=>this._selectForRow(i,a);let p=document.createElement("button");p.className="signal-icon-btn",p.title="Remove";let d=document.createElement("img");d.src=me+"icons/delete.svg",d.style.cssText="width:12px; height:12px;",p.appendChild(d),p.onclick=()=>{this._signals.splice(i,1),this._syncSignals(),this._renderSignalList()},s.appendChild(l),s.appendChild(a),s.appendChild(c),s.appendChild(n),s.appendChild(p),e.appendChild(s)})}_syncSignals(){this.objectNames=this._signalsToObjectNames(),this._bindingsRefresh()}_addSignal(){this._signals.push({name:"",signal:""}),this._renderSignalList()}async _selectForRow(e,t){let i=this._shell.createBindableObjectBrowser();i.initialize(this._serviceContainer,this._instanceServiceContainer,"binding"),i.title="select signal...";let s=new AbortController;if(i.objectDoubleclicked.on(()=>{s.abort();let a="";i.selectedObject.specialType=="signalProperty"?a="?":i.selectedObject.bindabletype==="property"&&(a="??"),this._signals[e].signal=a+i.selectedObject.fullName,t.value=this._signals[e].signal,this._syncSignals()}),await this._shell.openConfirmation(i,{x:100,y:100,width:400,height:300,parent:this,abortSignal:s.signal})){let a="";i.selectedObject.specialType=="signalProperty"?a="?":i.selectedObject.bindabletype==="property"&&(a="??"),this._signals[e].signal=a+i.selectedObject.fullName,t.value=this._signals[e].signal,this._syncSignals()}}_renderConverterList(){let e=this._converterListContainer;e.innerHTML="";let t=this._property?.type==="color"?"color":"text";this.converters.forEach((i,s)=>{let l=document.createElement("div");l.className="signal-row";let a=document.createElement("input");a.style.cssText="flex:1 1 auto; height:22px; box-sizing:border-box;",a.value=i.key,a.placeholder="condition",a.oninput=()=>{this.converters[s].key=a.value};let n=document.createElement("input");n.type=t,n.style.cssText="flex:1 1 auto; height:22px; box-sizing:border-box;",n.value=i.value,n.placeholder="value",n.oninput=()=>{this.converters[s].value=n.value};let o=document.createElement("button");o.className="signal-icon-btn",o.title="Duplicate";let c=document.createElement("img");c.src=me+"icons/copy.svg",c.style.cssText="width:12px; height:12px;",o.appendChild(c),o.onclick=()=>{this.converters.splice(s+1,0,{...this.converters[s]}),this._renderConverterList()};let p=document.createElement("button");p.className="signal-icon-btn",p.title="Remove";let d=document.createElement("img");d.src=me+"icons/delete.svg",d.style.cssText="width:12px; height:12px;",p.appendChild(d),p.onclick=()=>{this.converters.splice(s,1),this._renderConverterList()},l.appendChild(a),l.appendChild(n),l.appendChild(o),l.appendChild(p),e.appendChild(l)})}_addConverter(){this.converters.push({key:"",value:""}),this._renderConverterList()}async _selectNamedConverter(){let e=r.namedConverters;if(e.length===0)return;let t="",i=null,s=document.createElement("div");s.style.cssText="display:flex; flex-direction:column; height:100%; box-sizing:border-box; font-size:12px;";let l=document.createElement("div");l.style.cssText="padding:6px 8px 4px; color:#666; font-size:11px; border-bottom:1px solid #e0e0e0; flex-shrink:0;",l.textContent="Select a converter and confirm with OK.",s.appendChild(l);let a=document.createElement("div");a.style.cssText="flex:1; overflow-y:auto; padding:4px;",s.appendChild(a);let n=p=>{p.style.background="",p.style.borderLeftColor="transparent"},o=(p,d)=>{i&&n(i),i=p,p.style.background="#e8f4fd",p.style.borderLeftColor="#0078d7",t=d};for(let p of e){let d=document.createElement("div");d.style.cssText="padding:5px 6px 5px 9px; cursor:pointer; border-radius:3px; border-left:3px solid transparent; margin-bottom:2px;";let h=document.createElement("div");if(h.style.cssText="font-family:monospace; font-weight:bold; color:#111;",h.textContent=p.name,d.appendChild(h),p.description){let u=document.createElement("div");u.style.cssText="color:#555; font-size:11px; margin-top:2px;",u.textContent=p.description,d.appendChild(u)}if(p.converter&&Object.keys(p.converter).length>0){let u=document.createElement("div");u.style.cssText="display:grid; grid-template-columns:max-content max-content 1fr; gap:1px 6px; margin-top:4px; padding:4px 6px; background:#f5f5f5; border-radius:2px; font-family:monospace; font-size:11px; color:#333;";for(let[g,f]of Object.entries(p.converter)){let w=document.createElement("span");w.style.cssText="color:#555; text-align:right;",w.textContent=g;let x=document.createElement("span");x.style.cssText="color:#aaa;",x.textContent="\u2192";let T=document.createElement("span");T.style.cssText="color:#0078d7; font-weight:bold;",T.textContent=String(f),u.appendChild(w),u.appendChild(x),u.appendChild(T)}d.appendChild(u)}d.onmouseenter=()=>{d!==i&&(d.style.background="#f5f5f5")},d.onmouseleave=()=>{d!==i&&(d.style.background="")},d.onclick=()=>o(d,p.name),a.appendChild(d)}await this._shell.openConfirmation(s,{x:100,y:100,width:320,height:300,parent:this})&&t&&(this.convertersString=t,this._getDomElement("namedConverterInput").value=t,this._bindingsRefresh())}_refresh(){requestAnimationFrame(()=>{this._bindingsRefresh()})}async showHistoric(){let e=new K(this.historic),t=new AbortController;e.title="Edit historic binding to: "+this._property.name,await this._shell.openConfirmation(e,{x:100,y:100,width:420,height:510,parent:this,abortSignal:t.signal,disableResize:!0,cancelText:"Remove"})?this.historic=e.historic:this.historic=null,this._bindingsRefresh()}_showHelp(){let e=document.createElement("iframe");e.srcdoc=r.helpSections.length>0?we.replace(`</div>
645
+ </body>`,r.helpSections.join("")+`</div>
646
+ </body>`):we,e.style.cssText="width:100%; height:100%; border:none; display:block;",this._shell.openModal(e,{title:"Bindings Editor Help",parent:this,x:-660,y:-80,width:630,height:580})}};customElements.define(he.is,he);import{BaseCustomWebComponentConstructorAppend as Et,TypedEvent as Nt,css as Bt,html as Ot}from"@node-projects/base-custom-webcomponent";import{ContextMenu as It,assetsPath as _e}from"@node-projects/web-component-designer";import{typeInfoFromJsonSchema as Re}from"@node-projects/propertygrid.webcomponent";import{defaultOptions as Vt,defaultStyle as At}from"@node-projects/web-component-designer-widgets-wunderbaum";import{Wunderbaum as Rt}from"wunderbaum";import zt from"wunderbaum/dist/wunderbaum.css"with{type:"css"};import{PropertyGrid as bt}from"@node-projects/propertygrid.webcomponent";import{CodeViewMonaco as Be}from"@node-projects/web-component-designer-codeview-monaco";var re=class extends bt{serviceContainer;instanceServiceContainer;visualizationHandler;visualizationShell;bindableObjectsTarget="property";constructor(){super()}bindingDoubleClicked;setNameColumnWidth(e){let t=this._tree?.columns?.[0];t&&(t.width=e+"px",this._tree.update("colStructure"))}async getEditorForType(e,t,i,s,l){if(this.getSpecialEditorForType){let a=await this.getSpecialEditorForType(e,t,i,s,l);if(a)return a}switch(e.format){case"screen":{let a=document.createElement("select");a.style.width="100%";let n=document.createElement("option");n.value=t??"",n.innerText=t??"",a.appendChild(n);for(let o of await this.visualizationHandler.getAllNames("screen")){if(o==t)continue;let c=document.createElement("option");c.value=o,c.innerText=o,a.appendChild(c)}return a.onchange=()=>{this.setPropertyValue(i,a.value)},a.value=t,a}case"signal":{let a=document.createElement("div");a.style.display="flex";let n=document.createElement("input");n.value=t??"",n.style.flexGrow="1",n.style.width="0",n.onchange=c=>this.setPropertyValue(i,n.value),n.onfocus=c=>{n.selectionStart=0,n.selectionEnd=n.value?.length},a.appendChild(n);let o=document.createElement("button");return o.textContent="...",o.onclick=async()=>{let c=this.visualizationShell.createBindableObjectBrowser();c.initialize(this.serviceContainer,this.instanceServiceContainer,this.bindableObjectsTarget),c.title="select signal...";let p=new AbortController;c.objectDoubleclicked.on(()=>{this.bindingDoubleClicked&&this.bindingDoubleClicked(c.selectedObject),p.abort(),n.value=c.selectedObject.fullName,this.setPropertyValue(i,n.value)}),await this.visualizationShell.openConfirmation(c,{x:100,y:100,width:400,height:300,parent:this,abortSignal:p.signal})&&(n.value=c.selectedObject.fullName,this.setPropertyValue(i,n.value))},a.appendChild(o),a}case"html":case"script":{let a=document.createElement("div");a.style.boxSizing="border-box",a.style.width="100%",a.style.display="flex";let n=document.createElement("textarea");n.style.boxSizing="border-box",n.value=t??"",n.style.width="100%",n.onblur=c=>{this.setPropertyValue(i,n.value)},a.appendChild(n);let o=document.createElement("button");return o.innerHTML="...",o.style.boxSizing="border-box",o.onclick=async()=>{let c=new Be,p=await Be.getMonacoLib();if(e.format=="html")c.language="html";else{let h={content:`declare global {
641
647
  var context: { event: Event, element: Element };
642
- }`,filePath:"global.d.ts"};p.languages.typescript.typescriptDefaults.setExtraLibs([g]),c.language="javascript"}c.code=n.value,c.style.position="relative",await this.visualizationShell.openConfirmation(c,{x:200,y:200,width:600,height:400,parent:this})&&(n.value=c.getText(),this.setPropertyValue(i,n.value))},r.appendChild(a),r}}return super.getEditorForType(e,t,i,s,l)}};customElements.define("node-projects-visualization-property-grid",re);import{CodeViewMonaco as Ve}from"@node-projects/web-component-designer-codeview-monaco";import{BaseCustomWebComponentConstructorAppend as gt,TypedEvent as Ee,css as ft,html as yt}from"@node-projects/base-custom-webcomponent";import{defaultOptions as bt,defaultStyle as vt}from"@node-projects/web-component-designer-widgets-wunderbaum";import{Wunderbaum as xt}from"wunderbaum";import wt from"wunderbaum/dist/wunderbaum.css"with{type:"css"};function mt(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function H(o){return mt(o).replace(/("(?:\\.|[^"\\])*")(\s*:)?|\b(true|false|null)\b|\b(-?\d+(?:\.\d+)?)\b/g,(t,i,s,l,r)=>i?`<span class="${s?"cs-key":"cs-str"}">${i}</span>${s??""}`:l?`<span class="cs-bool">${l}</span>`:r?`<span class="cs-num">${r}</span>`:t)}var Z=class o extends gt{static style=ft`
648
+ }`,filePath:"global.d.ts"};p.languages.typescript.typescriptDefaults.setExtraLibs([h]),c.language="javascript"}c.code=n.value,c.style.position="relative",await this.visualizationShell.openConfirmation(c,{x:200,y:200,width:600,height:400,parent:this})&&(n.value=c.getText(),this.setPropertyValue(i,n.value))},a.appendChild(o),a}}return super.getEditorForType(e,t,i,s,l)}};customElements.define("node-projects-visualization-property-grid",re);import{CodeViewMonaco as ze}from"@node-projects/web-component-designer-codeview-monaco";import{BaseCustomWebComponentConstructorAppend as xt,TypedEvent as Oe,css as wt,html as _t}from"@node-projects/base-custom-webcomponent";import{defaultOptions as St,defaultStyle as kt}from"@node-projects/web-component-designer-widgets-wunderbaum";import{Wunderbaum as Ct}from"wunderbaum";import Tt from"wunderbaum/dist/wunderbaum.css"with{type:"css"};function vt(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function H(r){return vt(r).replace(/("(?:\\.|[^"\\])*")(\s*:)?|\b(true|false|null)\b|\b(-?\d+(?:\.\d+)?)\b/g,(t,i,s,l,a)=>i?`<span class="${s?"cs-key":"cs-str"}">${i}</span>${s??""}`:l?`<span class="cs-bool">${l}</span>`:a?`<span class="cs-num">${a}</span>`:t)}var Z=class r extends xt{static style=wt`
643
649
  :host {
644
650
  display: block;
645
651
  background: white;
@@ -784,7 +790,7 @@ __res <span style="color:#6a737d;font-style:italic">// the res
784
790
  font-style: italic;
785
791
  color: #666;
786
792
  }
787
- `;static template=yt`
793
+ `;static template=_t`
788
794
  <div class="root">
789
795
  <input id="filter" placeholder="Filter..." autocomplete="off">
790
796
  <div class="content">
@@ -798,14 +804,14 @@ __res <span style="color:#6a737d;font-style:italic">// the res
798
804
  <button id="closeBtn" @click="[[this.closeClicked()]]">Close</button>
799
805
  </div>
800
806
  </div>
801
- `;static is="node-projects-visualization-simple-script-command-picker";_title;get title(){return this._title}set title(e){this._title=e}selectedType;commandTypeChosen=new Ee;closeRequested=new Ee;_tree;_filter;_descriptionDiv;_addBtn;_typeInfo;_descriptions;constructor(){super(),this._restoreCachedInititalValues(),this.shadowRoot.adoptedStyleSheets=[wt,vt,o.style],this._descriptionDiv=this._getDomElement("description"),this._addBtn=this._getDomElement("addBtn"),this._filter=this._getDomElement("filter"),this._filter.onkeyup=()=>{let e=this._filter.value;this._tree.filterNodes(t=>new RegExp(e,"i").test(t.title),{})},this._tree=new xt({...bt,element:this._getDomElement("commandList"),icon:!1,filter:{autoExpand:!0,mode:"hide",highlight:!0},activate:e=>{this.selectedType=e.node.title,this._addBtn.disabled=!1,this._renderDescription(e.node.title)},dblclick:e=>(this.selectedType=e.node.title,this.commandTypeChosen.emit(),!1),render:e=>{e.isNew&&(e.nodeElem.oncontextmenu=t=>(t.preventDefault(),!1))},dnd:{guessDropEffect:!1,serializeClipboardData:!0,dragStart:e=>(e.event.dataTransfer.effectAllowed="copy",e.event.dataTransfer.dropEffect="copy",!0)}})}async ready(){this._parseAttributesToProperties(),this._bindingsParse(null,!0),this._assignEvents()}addClicked(){this.selectedType&&this.commandTypeChosen.emit()}closeClicked(){this.closeRequested.emit()}_renderDescription(e){let t=this._descriptions?.[e];if(t){this._descriptionDiv.innerHTML=`
807
+ `;static is="node-projects-visualization-simple-script-command-picker";_title;get title(){return this._title}set title(e){this._title=e}selectedType;commandTypeChosen=new Oe;closeRequested=new Oe;_tree;_filter;_descriptionDiv;_addBtn;_typeInfo;_descriptions;constructor(){super(),this._restoreCachedInititalValues(),this.shadowRoot.adoptedStyleSheets=[Tt,kt,r.style],this._descriptionDiv=this._getDomElement("description"),this._addBtn=this._getDomElement("addBtn"),this._filter=this._getDomElement("filter"),this._filter.onkeyup=()=>{let e=this._filter.value;this._tree.filterNodes(t=>new RegExp(e,"i").test(t.title),{})},this._tree=new Ct({...St,element:this._getDomElement("commandList"),icon:!1,filter:{autoExpand:!0,mode:"hide",highlight:!0},activate:e=>{this.selectedType=e.node.title,this._addBtn.disabled=!1,this._renderDescription(e.node.title)},dblclick:e=>(this.selectedType=e.node.title,this.commandTypeChosen.emit(),!1),render:e=>{e.isNew&&(e.nodeElem.oncontextmenu=t=>(t.preventDefault(),!1))},dnd:{guessDropEffect:!1,serializeClipboardData:!0,dragStart:e=>(e.event.dataTransfer.effectAllowed="copy",e.event.dataTransfer.dropEffect="copy",!0)}})}async ready(){this._parseAttributesToProperties(),this._bindingsParse(null,!0),this._assignEvents()}addClicked(){this.selectedType&&this.commandTypeChosen.emit()}closeClicked(){this.closeRequested.emit()}_renderDescription(e){let t=this._descriptions?.[e];if(t){this._descriptionDiv.innerHTML=`
802
808
  <div class="cmd-title">${e}<span class="hint">${t.description}</span></div>
803
809
  <pre class="snippet">${H(t.example)}</pre>
804
810
  ${t.note?`<div class="note">${t.note}</div>`:""}
805
811
  `;return}let i=this._typeInfo?.definitions?.[e]?.description;this._descriptionDiv.innerHTML=`
806
812
  <div class="cmd-title">${e}</div>
807
813
  ${i?`<div class="note">${i}</div>`:""}
808
- `}loadCommands(e,t){this._typeInfo=e,this._descriptions=t??{};let i=Object.keys(e.definitions).filter(s=>e.definitions[s].type==="object"&&s!=="ScriptCommands");this._tree.root.addChildren(i.map(s=>({title:s})))}};customElements.define(Z.is,Z);function Ne(o,e){return`<span class="cs-attr">${o}</span>='${H(e)}'`}var Oe=`<!DOCTYPE html>
814
+ `}loadCommands(e,t){this._typeInfo=e,this._descriptions=t??{};let i=Object.keys(e.definitions).filter(s=>e.definitions[s].type==="object"&&s!=="ScriptCommands");this._tree.root.addChildren(i.map(s=>({title:s})))}};customElements.define(Z.is,Z);function Ie(r,e){return`<span class="cs-attr">${r}</span>='${H(e)}'`}var Ve=`<!DOCTYPE html>
809
815
  <html>
810
816
  <head>
811
817
  <meta charset="UTF-8">
@@ -926,7 +932,7 @@ html, body {
926
932
 
927
933
  <div class="content-section">
928
934
  <div class="section-title"><span class="section-num">1</span> Basic structure <span class="section-hint">commands array, sequential execution</span></div>
929
- <pre class="snippet">${Ne("@click",`{"commands":[
935
+ <pre class="snippet">${Ie("@click",`{"commands":[
930
936
  { "type": "SetSignalValue", "signal": ".Some.Signal", "value": true },
931
937
  { "type": "SetSignalValue", "signal": ".Some.Other", "value": false }
932
938
  ]}`)}</pre>
@@ -944,14 +950,14 @@ ${H('{ "source": "parameter", "name": "myParam" }')} <span class="cs-comment">/
944
950
 
945
951
  <div class="content-section">
946
952
  <div class="section-title"><span class="section-num">3</span> Cyclic events <span class="section-hint">re-triggering timer event</span></div>
947
- <pre class="snippet">${Ne("@cyclic:100",`{"commands":[
953
+ <pre class="snippet">${Ie("@cyclic:100",`{"commands":[
948
954
  { "type": "SetSignalValue", "signal": ".Local.Tick", "value": true }
949
955
  ]}`)}</pre>
950
956
  <div class="note">A <code>@cyclic:&lt;ms&gt;</code> event retriggers itself automatically every &lt;ms&gt; milliseconds.</div>
951
957
  </div>
952
958
  </div>
953
959
  </body>
954
- </html>`;var Ie={Comment:{description:"has no effect on script execution",example:'{ "type": "Comment", "comment": "explains the next step" }'},OpenScreen:{description:"navigate to a screen (with history)",example:'{ "type": "OpenScreen", "screen": "MyScreen" }'},OpenDialog:{description:"open a screen as a movable/closable dialog",example:`{ "type": "OpenDialog", "screen": "MyScreen", "title": "My Dialog",
960
+ </html>`;var Ae={Comment:{description:"has no effect on script execution",example:'{ "type": "Comment", "comment": "explains the next step" }'},OpenScreen:{description:"navigate to a screen (with history)",example:'{ "type": "OpenScreen", "screen": "MyScreen" }'},OpenDialog:{description:"open a screen as a movable/closable dialog",example:`{ "type": "OpenDialog", "screen": "MyScreen", "title": "My Dialog",
955
961
  "moveable": true, "closeable": true }`},CloseDialog:{description:"close the parent dialog this command runs in",example:'{ "type": "CloseDialog" }'},OpenUrl:{description:"open an URL, optionally as an in-app dialog",example:'{ "type": "OpenUrl", "url": "https://example.com", "target": "_blank", "openInDialog": false }'},ShowMessageBox:{description:"ask the user to confirm before continuing",example:`{ "type": "ShowMessageBox", "title": "Confirm", "message": "Are you sure?",
956
962
  "messageType": "warning", "buttons": "yesNo", "resultSignal": ".Local.Result",
957
963
  "exitScriptOnCancel": true }`,note:"exitScriptOnCancel: true stops the chain when the user picks a negative button."},ShowPrompt:{description:"ask the user for text input",example:`{ "type": "ShowPrompt", "title": "Name?", "message": "Enter a name",
@@ -960,7 +966,7 @@ ${H('{ "source": "parameter", "name": "myParam" }')} <span class="cs-comment">/
960
966
  "targetSelector": ".my-class", "name": "disabled", "value": true }`,note:'target: "property" (default) | "attribute" | "css" | "class". targetSelectorTarget: "container" (screen/customControl, default) | "element" (current element).'},Delay:{description:"pause the script chain",example:'{ "type": "Delay", "value": 500 }'},Console:{description:"write a message to the browser console",example:'{ "type": "Console", "target": "log", "message": "done" }',note:'target: "log" (default) | "info" | "debug" | "warn" | "error".'},SwitchLanguage:{description:"switch the active UI language",example:'{ "type": "SwitchLanguage", "language": "en" }'},Login:{description:"log a user in",example:'{ "type": "Login", "username": "user", "password": "pass" }'},Logout:{description:"log the current user out",example:'{ "type": "Logout" }'},SubscribeSignal:{description:"subscribe to a signal so its updates are pushed to the client",example:'{ "type": "SubscribeSignal", "signal": ".Some.Signal", "oneTime": false }'},UnsubscribeSignal:{description:"unsubscribe from a previously subscribed signal",example:'{ "type": "UnsubscribeSignal", "signal": ".Some.Signal" }'},WriteSignalsInGroup:{description:"write all pending signal values of a named group",example:'{ "type": "WriteSignalsInGroup", "group": "MyGroup" }'},ClearSignalsInGroup:{description:"clear all pending signal values of a named group",example:'{ "type": "ClearSignalsInGroup", "group": "MyGroup" }'},RunScript:{description:"run another named script",example:'{ "type": "RunScript", "name": "MyScript", "scriptType": "SimpleScript" }'},CopySignalValuesFromFolder:{description:"copy signal values from one signal folder to another",example:'{ "type": "CopySignalValuesFromFolder", "sourceFolder": ".Source", "destinationFolder": ".Target" }'},ExportSignalValuesAsJson:{description:"export matching signal values as a downloadable JSON file",example:'{ "type": "ExportSignalValuesAsJson", "regex": "^\\\\.Some\\\\..*", "fileName": "export.json" }'},ImportSignalValuesFromJson:{description:"import signal values from a JSON string",example:'{ "type": "ImportSignalValuesFromJson", "data": "{ \\".Some.Signal\\": true }" }'},Repeat:{description:"jump back to a label a number of times, or indefinitely",example:'{ "type": "Repeat", "label": "lbl_loop", "count": 0, "mode": "eventValid" }',note:'mode: "eventValid" (default, repeats until the event is no longer active) | "always" (repeats until count is 0 or indefinitely when count is 0).'},Condition:{description:"compare two values and jump to a label depending on the result",example:`{ "type": "Condition", "value1": {"source":"signal","name":".Is.On"}, "value2": true,
961
967
  "comparisonType": "==", "trueGotoLabel": "lbl_off", "falseGotoLabel": "lbl_on" }`,note:"comparisonType: ==null | !=null | ==true | ==false | == | != | > | < | >= | <= | && | ||."},If:{description:"evaluate a formula and run nested commands depending on the result",example:`{ "type": "If",
962
968
  "signals": [{"source":"signal","name":".Is.On"}, {"varName":"ready","source":"signal","name":".Is.Ready"}],
963
- "formula": "__0 == true && ready == false", "trueCommands": [], "elseCommands": [] }`,note:"signals is a list of values (like Condition.value1). Each is referenced in the formula either positionally as __0, __1, ... or, if varName is set, by that name. trueCommands/elseCommands are edited as nested commands in the tree, not as JSON here."},Exit:{description:"stop executing the current script chain",example:'{ "type": "Exit" }'},Label:{description:"a named jump target for Condition / Goto / Repeat",example:'{ "type": "Label", "label": "lbl_on" }'},Goto:{description:"jump unconditionally to a label",example:'{ "type": "Goto", "label": "lbl_on" }'}};import"@node-projects/splitview.webcomponent";var Q=class o{static upgradeScriptCommand(e){return e.type==="SetElementProperty"?o.upgradeSetElementProperty(e):(e.type==="If"&&(e.trueCommands=(e.trueCommands??[]).map(t=>o.upgradeScriptCommand(t)),e.elseCommands=(e.elseCommands??[]).map(t=>o.upgradeScriptCommand(t))),e)}static upgradeSetElementProperty(e){return e.targetSelectorTarget==="currentScreen"?e.targetSelectorTarget="container":e.targetSelectorTarget==="parentScreen"?(e.targetSelectorTarget="container",e.parentIndex=1):e.targetSelectorTarget==="currentElement"?e.targetSelectorTarget="element":e.targetSelectorTarget==="parentElement"&&(e.targetSelectorTarget="element",e.parentIndex=1),e}};var ee="application/x-simple-script-move",te=class o extends _t{static style=kt`
969
+ "formula": "__0 == true && ready == false", "trueCommands": [], "elseCommands": [] }`,note:"signals is a list of values (like Condition.value1). Each is referenced in the formula either positionally as __0, __1, ... or, if varName is set, by that name. trueCommands/elseCommands are edited as nested commands in the tree, not as JSON here."},Exit:{description:"stop executing the current script chain",example:'{ "type": "Exit" }'},Label:{description:"a named jump target for Condition / Goto / Repeat",example:'{ "type": "Label", "label": "lbl_on" }'},Goto:{description:"jump unconditionally to a label",example:'{ "type": "Goto", "label": "lbl_on" }'}};import"@node-projects/splitview.webcomponent";var Q=class r{static upgradeScriptCommand(e){return e.type==="SetElementProperty"?r.upgradeSetElementProperty(e):(e.type==="If"&&(e.trueCommands=(e.trueCommands??[]).map(t=>r.upgradeScriptCommand(t)),e.elseCommands=(e.elseCommands??[]).map(t=>r.upgradeScriptCommand(t))),e)}static upgradeSetElementProperty(e){return e.targetSelectorTarget==="currentScreen"?e.targetSelectorTarget="container":e.targetSelectorTarget==="parentScreen"?(e.targetSelectorTarget="container",e.parentIndex=1):e.targetSelectorTarget==="currentElement"?e.targetSelectorTarget="element":e.targetSelectorTarget==="parentElement"&&(e.targetSelectorTarget="element",e.parentIndex=1),e}};var ee="application/x-simple-script-move",te=class r extends Et{static style=Bt`
964
970
  :host {
965
971
  background: white;
966
972
  }
@@ -1158,7 +1164,7 @@ ${H('{ "source": "parameter", "name": "myParam" }')} <span class="cs-comment">/
1158
1164
  height: 12px;
1159
1165
  cursor: pointer;
1160
1166
  }
1161
- `;static template=Tt`
1167
+ `;static template=Ot`
1162
1168
  <div class="root">
1163
1169
  <div class="content">
1164
1170
  <node-projects-split-view
@@ -1208,8 +1214,8 @@ ${H('{ "source": "parameter", "name": "myParam" }')} <span class="cs-comment">/
1208
1214
  </node-projects-split-view>
1209
1215
  </div>
1210
1216
  </div>
1211
- `;static is="node-projects-visualization-simple-script-editor";_title;get title(){return this._title}set title(e){this._title=e}serviceContainer;instanceServiceContainer;visualizationHandler;visualizationShell;scriptCommandsTypeInfo;propertiesTypeInfo;helpRequested=new St;commandDescriptions={...Ie};_script;_commandListDiv;_commandListFancyTree;_propertygrid;_splitView;_codeView;_codeToggleBtn;_addCommandBtn;_showingCode=!1;_dragFromHandle=!1;_draggedNode=null;constructor(){super(),this._restoreCachedInititalValues(),this._commandListDiv=this._getDomElement("commandList"),this._propertygrid=this._getDomElement("propertygrid"),this._splitView=this._getDomElement("splitView"),this._codeView=this._getDomElement("codeView"),this._codeToggleBtn=this._getDomElement("codeToggleBtn"),this._addCommandBtn=this._getDomElement("addCommandBtn");let e=this._getDomElement("listContent");e.addEventListener("mousedown",t=>{this._dragFromHandle=!!t.target?.closest(".drag-handle")}),document.addEventListener("dragend",()=>{this._draggedNode=null},!0),e.addEventListener("dragover",t=>{if(t.preventDefault(),t.dataTransfer){let i=t.dataTransfer.types.includes(ee);t.dataTransfer.dropEffect=i?"move":"copy"}}),e.addEventListener("drop",t=>{if(t.preventDefault(),t.dataTransfer?.types.includes(ee)&&this._draggedNode){let s=this._commandListFancyTree.root.children,l=s?.[s.length-1];l&&this._draggedNode.moveTo(l,"after"),this._draggedNode.setClass("wb-drag-source",!1)}else{let s=t.dataTransfer?.getData("text/plain");if(s){let l={type:s};this._commandListFancyTree.root.addChildren(this.createTreeItem(l))}}}),this.shadowRoot.adoptedStyleSheets=[It,Nt,o.style]}async ready(){this._parseAttributesToProperties(),this._bindingsParse(null,!0),this._assignEvents();let e=async a=>{let c=new re;c.visualizationHandler=this.visualizationHandler,c.visualizationShell=this.visualizationShell,c.serviceContainer=this.serviceContainer,c.instanceServiceContainer=this.instanceServiceContainer,c.bindableObjectsTarget="script",c.getTypeInfo=(d,g)=>Be(this.propertiesTypeInfo,d,g),c.showHead=!1,c.typeName="IScriptMultiplexValue",c.title='Complex for "'+a.propertyPath+'"',typeof a.value=="object"?c.selectedObject=a.value??{}:c.selectedObject={},c.bindingDoubleClicked=d=>{d.bindabletype=="property"?c.setPropertyValue("source","property"):d.bindabletype=="context"?c.setPropertyValue("source","context"):c.setPropertyValue("source","signal"),c.setPropertyValue("name",d.fullName),c.refresh()},await this.visualizationShell.openConfirmation(c,{x:100,y:100,width:400,height:500,parent:this})&&(this._propertygrid.setPropertyValue(a.propertyPath,c.selectedObject),this._propertygrid.refresh())},t=async a=>{let c=new Ve;c.language="javascript",c.style.position="relative",c.code=a.value??"",await this.visualizationShell.openConfirmation(c,{title:"Edit formula",x:100,y:50,width:700,height:450,parent:this})&&(this._propertygrid.setPropertyValue(a.propertyPath,c.code),this._propertygrid.refresh())},i=["signal","property","elementProperty","signalInProperty","event","parameter","context","complexString","complexSignal","expression"],s=/^[A-Za-z_$][A-Za-z0-9_$]*$/,l=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","let","static","enum","await","implements","package","protected","interface","private","public","null","true","false","undefined","arguments","eval"]),r={signal:"read the value from a Signal",property:"read the value from a property of the customControl (not usable in screens)",elementProperty:"a property defined on the element raising the event",signalInProperty:"read the value from a Signal (wich name is in the Property)",event:"read the value of a property of the event object",parameter:"a parameter you hand over",context:"a value of the context",complexString:"a string with signals (contained in {})",complexSignal:"read the value from a signal wich name is build here (it can contain other signals in {})",expression:"js expression, 'ctx' is context object"},n=async a=>{let c=(a.value??[]).map(k=>({...k})),p=k=>{let N=(c[k].varName??"").trim();return N?s.test(N)?l.has(N)?`"${N}" is a reserved word and cannot be used as a variable name.`:c.some((E,O)=>O!==k&&(E.varName??"").trim()===N)?`"${N}" is used by more than one signal.`:null:`"${N}" is not a valid JavaScript variable name.`:null},d="height:22px; box-sizing:border-box; font-size:12px;",g=document.createElement("div");g.style.cssText="display:flex; flex-direction:column; gap:6px; padding:8px; height:100%; box-sizing:border-box; overflow-y:auto; font-size:12px;";let u=document.createElement("div");u.style.cssText="display:flex; align-items:center; gap:4px; font-weight:bold;";let m=document.createElement("span");m.textContent="Name",m.style.cssText="flex:0 0 120px;";let y=document.createElement("span");y.textContent="Typ",y.style.cssText="flex:0 0 130px;";let _=document.createElement("span");_.textContent="Signal",_.style.cssText="flex:1 1 auto;";let w=document.createElement("span");w.style.cssText="flex:0 0 22px;",u.append(m,y,_,w),g.appendChild(u);let C=document.createElement("div");C.style.cssText="display:flex; flex-direction:column; gap:4px;",g.appendChild(C);let z=document.createElement("div");z.style.cssText="flex:0 0 auto; margin-top:4px; padding-top:6px; border-top:1px solid #ccc; font-size:12px;";let P=document.createElement("div");P.style.cssText="font-weight:bold; margin-bottom:2px;";let G=document.createElement("div");G.style.cssText="color:#333; white-space:pre-line;",z.append(P,G);let q=k=>{P.textContent="Typ: "+k,G.textContent=r[k]??""},M=[],X=()=>{c.forEach((k,N)=>{let E=M[N];if(!E)return;let O=p(N);E.title=O??`Variable name used in the formula (defaults to __${N} if empty)`,E.style.borderColor=O?"#c0392b":"",E.style.backgroundColor=O?"#fdecea":""})},B=()=>{C.innerHTML="",M.length=0,c.forEach((k,N)=>{let E=document.createElement("div");E.style.cssText="display:flex; align-items:center; gap:4px;";let O=document.createElement("input");O.value=k.varName??"",O.placeholder="__"+N,O.style.cssText=d+" flex:0 0 120px; min-width: 120px; font-family:monospace;",O.oninput=()=>{k.varName=O.value||void 0,X()},M.push(O),E.appendChild(O);let h=document.createElement("select");h.style.cssText=d+" flex:0 0 130px;";for(let A of i){let S=document.createElement("option");S.value=A,S.textContent=A,k.source===A&&(S.selected=!0),h.appendChild(S)}h.onchange=()=>{k.source=h.value,q(h.value)},h.onfocus=()=>q(h.value),E.appendChild(h);let b=document.createElement("input");b.value=k.name??"",b.placeholder="e.g. srm.rbg{__tagRoot}.error",b.style.cssText=d+" flex:1 1 auto;",b.oninput=()=>{k.name=b.value},E.appendChild(b);let v=document.createElement("button");v.title="Remove signal",v.style.cssText=d+" flex:0 0 22px; width:22px; padding:0; display:flex; align-items:center; justify-content:center;";let V=document.createElement("img");V.src=ve+"icons/delete.svg",V.style.cssText="width:12px; height:12px;",v.appendChild(V),v.onclick=()=>{c.splice(N,1),B()},E.appendChild(v),C.appendChild(E)}),X()};B();let L=document.createElement("button");L.textContent="+ Add signal",L.style.cssText=d+" align-self:flex-start; padding:0 8px;",L.onclick=()=>{c.push({source:"signal",name:""}),B()},g.appendChild(L),q(c[0]?.source??"signal"),g.appendChild(z),await this.visualizationShell.openConfirmation(g,{title:"Edit signals",x:100,y:50,width:500,height:400,parent:this})&&(this._propertygrid.setPropertyValue(a.propertyPath,c),this._propertygrid.refresh())};this._propertygrid.visualizationHandler=this.visualizationHandler,this._propertygrid.visualizationShell=this.visualizationShell,this._propertygrid.serviceContainer=this.serviceContainer,this._propertygrid.instanceServiceContainer=this.instanceServiceContainer,this._propertygrid.bindableObjectsTarget="script",this._propertygrid.setNameColumnWidth(130),this._propertygrid.getTypeInfo=(a,c)=>{let p=Be(this.scriptCommandsTypeInfo,a,c);return p&&(c==="If"||a?.type==="If")&&(p.properties=p.properties.filter(d=>d.name!=="trueCommands"&&d.name!=="elseCommands")),p},this._propertygrid.getSpecialEditorForType=async(a,c,p,d,g)=>{if(!a.specialAllreadyAdded&&(a.specialAllreadyAdded=!0,a.format!=="collection"))if(a.format==="signalList"){let u=document.createElement("button");u.style.height="calc(100% - 6px)",u.style.position="relative",u.style.display="flex",u.style.justifyContent="center",u.style.width="20px",u.style.boxSizing="content-box",u.innerText="del",u.onclick=()=>{this._propertygrid.setPropertyValue(p,void 0),this._propertygrid.refresh()},d.nodeElem.insertAdjacentElement("afterbegin",u);let m=Array.isArray(c)?c:[],y=document.createElement("div");y.style.display="flex";let _=document.createElement("span");_.innerText=m.map((C,z)=>(C?.varName||"__"+z)+": "+(C?.source??"")+":"+(C?.name??"")).join(", "),_.style.overflow="hidden",_.style.whiteSpace="nowrap",_.style.textOverflow="ellipsis",_.style.flexGrow="1",_.title=JSON.stringify(m),y.appendChild(_);let w=document.createElement("button");return w.innerText="...",w.onclick=()=>{n({value:m,propertyPath:p})},y.appendChild(w),d.nodeElem.style.display="flex",y}else if(a.format==="formula"){let u=document.createElement("div");u.style.cssText="display:flex; width:100%; height:100%; align-items:stretch;";let m=new Ve;m.language="javascript",m.singleRow=!0,m.style.cssText="flex:1 1 auto; min-width:0; height:100%; position:relative; overflow:hidden;",m.code=c??"",m.addEventListener("code-changed",()=>{this._propertygrid.setPropertyValue(p,m.code)}),u.appendChild(m);let y=document.createElement("button");return y.innerText="...",y.title="Open in larger editor",y.style.cssText="flex:0 0 28px; width:20px;",y.onclick=()=>t({value:m.code,propertyPath:p}),u.appendChild(y),d.nodeElem.style.display="flex",u}else if(typeof c=="object"&&c!==null||a.format==="complex"){let u=document.createElement("button");u.style.height="calc(100% - 6px)",u.style.position="relative",u.style.display="flex",u.style.justifyContent="center",u.style.width="20px",u.style.boxSizing="content-box",u.innerText="del",u.onclick=()=>{this._propertygrid.setPropertyValue(p,void 0),this._propertygrid.refresh()},d.nodeElem.insertAdjacentElement("afterbegin",u);let m=document.createElement("div");m.style.display="flex";let y=document.createElement("span");c?y.innerText=(c.source??"")+": "+(c.name??""):y.innerText="",y.style.overflow="hidden",y.style.whiteSpace="nowrap",y.style.textOverflow="ellipsis",y.style.flexGrow="1",y.title=JSON.stringify(c),m.appendChild(y);let _=document.createElement("button");return _.innerText="...",_.onclick=()=>{e({value:c,propertyPath:p})},m.appendChild(_),d.nodeElem.style.display="flex",m}else{let u=document.createElement("button");u.style.height="calc(100% - 6px)",u.style.position="relative",u.style.display="flex",u.style.justifyContent="center",u.style.width="20px",u.style.boxSizing="content-box",u.title="complex property value",u.style.opacity="0.2",u.innerText="...",u.onclick=()=>{e({value:c,propertyPath:p})},d.nodeElem.insertAdjacentElement("afterbegin",u),d.nodeElem.style.display="flex"}return null},this._propertygrid.propertyNodeContextMenu.on(a=>{Ct.show([{title:"edit complex value",action:async()=>{e(a)}},{title:"edit string",action:async()=>{let c=prompt("enter value:");c&&(this._propertygrid.setPropertyValue(a.propertyPath,c),this._propertygrid.refresh())}},{title:"remove complex value",action:async()=>{this._propertygrid.setPropertyValue(a.propertyPath,void 0),this._propertygrid.refresh()}}],a.event)})}helpClicked(){let e=document.createElement("iframe");e.srcdoc=Oe,e.style.cssText="width:100%; height:100%; border:none; display:block;",this.visualizationShell.openModal(e,{title:"Simple Script Editor Help",parent:this,x:-650,y:-100,width:620,height:620}),this.helpRequested.emit()}toggleCodeView(){if(!this._showingCode){let t=JSON.stringify({commands:this.getScriptCommands()},null,2);this._codeView.update(t),this._showCodeView(!0);return}let e=this._parseCodeViewScript();e&&(this._showCodeView(!1),this.loadScript(e))}_showCodeView(e){this._codeView.classList.toggle("visible",e),this._commandListDiv.classList.toggle("hidden",e),this._splitView.classList.toggle("code-mode",e),this._addCommandBtn.disabled=e,this._codeToggleBtn.innerText=e?"Visual":"Code",this._showingCode=e,e&&requestAnimationFrame(()=>this._codeView.activated())}_parseCodeViewScript(){let e;try{e=JSON.parse(this._codeView.getText())}catch(t){return alert(`Invalid JSON:
1212
- `+t.message),null}return Array.isArray(e?.commands)?e:(alert('The JSON must have a "commands" array.'),null)}loadScript(e){this._script=e,this._commandListFancyTree&&(this._commandListFancyTree.destroy(),this._commandListDiv=this._getDomElement("commandList"));let t=[];for(let i of this._script.commands)i=Q.upgradeScriptCommand(i),t.push(this.createTreeItem(i));this._commandListFancyTree=new Ot({...Et,element:this._commandListDiv,icon:!1,source:t,activate:i=>{this._propertygrid.selectedObject=i.node.data.data.item??null},render:i=>{let s=!!i.node.data.data?.branch;if(i.isNew){i.nodeElem.oncontextmenu=n=>(n.preventDefault(),!1);let r=document.createElement("span");if(r.style.cssText="display:inline-block; width:24px;",i.nodeElem.prepend(r),s)i.nodeElem._reservedRowWidth=r.offsetWidth;else{let n=document.createElement("div");n.className="drag-handle",n.title="Drag to reorder",n.innerHTML='<svg viewBox="0 0 24 24" width="14" height="14"><path d="M4 6h16M4 12h16M4 18h16" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',i.nodeElem.prepend(n);let a=i.nodeElem.parentElement,c=document.createElement("span");c.style.cssText="display:inline-block; width:32px;",i.nodeElem.appendChild(c);let p=document.createElement("div");p.className="cmd";let d=document.createElement("img");d.src=ve+"icons/copy.svg",d.title="Duplicate",d.onclick=()=>{let u=structuredClone(i.node.data.data.item);i.node.parent.addChildren(this.createTreeItem(u)).moveTo(i.node,"after")};let g=document.createElement("img");g.src=ve+"icons/delete.svg",g.title="Remove",g.onclick=()=>i.node.remove(),p.append(d,g),a.appendChild(p),i.nodeElem._reservedRowWidth=r.offsetWidth+c.offsetWidth}}let l=i.nodeElem._reservedRowWidth??0;if(l){let r=i.nodeElem.querySelector("span.wb-title");if(r){let n=parseFloat(r.style.width);isNaN(n)||(r.style.width=Math.max(0,n-l)+"px")}}},dnd:{guessDropEffect:!0,preventRecursion:!0,preventVoidMoves:!1,serializeClipboardData:!1,dragStart:i=>this._dragFromHandle?(this._draggedNode=i.node,i.event.dataTransfer.effectAllowed="move",i.event.dataTransfer.dropEffect="move",i.event.dataTransfer.setData(ee,"1"),!0):!1,dragEnd:()=>{this._draggedNode=null},dragEnter:i=>{let s=i.event.dataTransfer?.types.includes(ee);return i.event.dataTransfer.dropEffect=s?"move":"copy",!!i.node.data.data?.branch?new Set(["over"]):new Set(["before","after"])},dragOver:i=>{let s=i.event.dataTransfer?.types.includes(ee);i.event.dataTransfer.dropEffect=s?"move":"copy"},drop:async i=>{let s=i.event.dataTransfer?.types.includes(ee);if(i.region==="over"){if(s&&this._draggedNode)this._draggedNode.moveTo(i.node,"appendChild"),this._draggedNode.setClass("wb-drag-source",!1);else{let r=i.event.dataTransfer?.getData("text/plain");r&&i.node.addChildren(this.createTreeItem({type:r}))}return}let l=i.region=="before"?"before":"after";if(s&&this._draggedNode)this._draggedNode.moveTo(i.node,l),this._draggedNode.setClass("wb-drag-source",!1);else{let r=i.event.dataTransfer?.getData("text/plain");if(r){let n={type:r},a=this.createTreeItem(n);i.node.parent.addChildren(a).moveTo(i.node,l)}}}}}),this._commandListFancyTree.root.children?.[0]?.setActive()}createTreeItem(e){if(e.type==="If"){let t=e;return t.trueCommands??=[],t.elseCommands??=[],{title:"If",expanded:!0,data:{item:e},children:[{title:"true",expanded:!0,data:{branch:"true"},children:t.trueCommands.map(i=>this.createTreeItem(i))},{title:"else",expanded:!0,data:{branch:"else"},children:t.elseCommands.map(i=>this.createTreeItem(i))}]}}return{title:e.type,data:{item:e}}}nodeToCommand(e){let t=e.data.data.item;if(t.type==="If"){let i=e.children?.find(l=>l.data.data?.branch==="true"),s=e.children?.find(l=>l.data.data?.branch==="else");t.trueCommands=(i?.children??[]).map(l=>this.nodeToCommand(l)),t.elseCommands=(s?.children??[]).map(l=>this.nodeToCommand(l))}return t}_getBranchContainerNode(e){let t=e;for(;t;){if(t.data?.data?.branch)return t;t=t.parent}return null}async addCommand(){let e=new Z;e.loadCommands(this.scriptCommandsTypeInfo,this.commandDescriptions),e.title="Add Script Command",e.commandTypeChosen.on(()=>{if(e.selectedType){let i={type:e.selectedType},s=this.createTreeItem(i),l=this._getBranchContainerNode(this._commandListFancyTree.activeNode);l?l.addChildren(s):this._commandListFancyTree.addChildren(s)}});let t=new AbortController;e.closeRequested.on(()=>t.abort()),await this.visualizationShell.openModal(e,{title:"Add Script Command",x:300,y:50,width:620,height:400,parent:this,abortSignal:t.signal})}getScriptCommands(){if(this._showingCode){let t=this._parseCodeViewScript();t&&this.loadScript(t)}return this._commandListFancyTree.root.children.map(t=>this.nodeToCommand(t))}};customElements.define(te.is,te);import{BaseCustomWebComponentConstructorAppend as Bt,css as Vt,html as Rt}from"@node-projects/base-custom-webcomponent";var ie=class extends Bt{static style=Vt`
1217
+ `;static is="node-projects-visualization-simple-script-editor";_title;get title(){return this._title}set title(e){this._title=e}serviceContainer;instanceServiceContainer;visualizationHandler;visualizationShell;scriptCommandsTypeInfo;propertiesTypeInfo;helpRequested=new Nt;commandDescriptions={...Ae};_script;_commandListDiv;_commandListFancyTree;_propertygrid;_splitView;_codeView;_codeToggleBtn;_addCommandBtn;_showingCode=!1;_dragFromHandle=!1;_draggedNode=null;constructor(){super(),this._restoreCachedInititalValues(),this._commandListDiv=this._getDomElement("commandList"),this._propertygrid=this._getDomElement("propertygrid"),this._splitView=this._getDomElement("splitView"),this._codeView=this._getDomElement("codeView"),this._codeToggleBtn=this._getDomElement("codeToggleBtn"),this._addCommandBtn=this._getDomElement("addCommandBtn");let e=this._getDomElement("listContent");e.addEventListener("mousedown",t=>{this._dragFromHandle=!!t.target?.closest(".drag-handle")}),document.addEventListener("dragend",()=>{this._draggedNode=null},!0),e.addEventListener("dragover",t=>{if(t.preventDefault(),t.dataTransfer){let i=t.dataTransfer.types.includes(ee);t.dataTransfer.dropEffect=i?"move":"copy"}}),e.addEventListener("drop",t=>{if(t.preventDefault(),t.dataTransfer?.types.includes(ee)&&this._draggedNode){let s=this._commandListFancyTree.root.children,l=s?.[s.length-1];l&&this._draggedNode.moveTo(l,"after"),this._draggedNode.setClass("wb-drag-source",!1)}else{let s=t.dataTransfer?.getData("text/plain");if(s){let l={type:s};this._commandListFancyTree.root.addChildren(this.createTreeItem(l))}}}),this.shadowRoot.adoptedStyleSheets=[zt,At,r.style]}async ready(){this._parseAttributesToProperties(),this._bindingsParse(null,!0),this._assignEvents();let e=async o=>{let c=new re;c.visualizationHandler=this.visualizationHandler,c.visualizationShell=this.visualizationShell,c.serviceContainer=this.serviceContainer,c.instanceServiceContainer=this.instanceServiceContainer,c.bindableObjectsTarget="script",c.getTypeInfo=(d,h)=>Re(this.propertiesTypeInfo,d,h),c.showHead=!1,c.typeName="IScriptMultiplexValue",c.title='Complex for "'+o.propertyPath+'"',typeof o.value=="object"?c.selectedObject=o.value??{}:c.selectedObject={},c.bindingDoubleClicked=d=>{d.bindabletype=="property"?c.setPropertyValue("source","property"):d.bindabletype=="context"?c.setPropertyValue("source","context"):c.setPropertyValue("source","signal"),c.setPropertyValue("name",d.fullName),c.refresh()},await this.visualizationShell.openConfirmation(c,{x:100,y:100,width:400,height:500,parent:this})&&(this._propertygrid.setPropertyValue(o.propertyPath,c.selectedObject),this._propertygrid.refresh())},t=async o=>{let c=new ze;c.language="javascript",c.style.position="relative",c.code=o.value??"",await this.visualizationShell.openConfirmation(c,{title:"Edit formula",x:100,y:50,width:700,height:450,parent:this})&&(this._propertygrid.setPropertyValue(o.propertyPath,c.code),this._propertygrid.refresh())},i=["signal","property","elementProperty","signalInProperty","event","parameter","context","complexString","complexSignal","expression"],s=/^[A-Za-z_$][A-Za-z0-9_$]*$/,l=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","let","static","enum","await","implements","package","protected","interface","private","public","null","true","false","undefined","arguments","eval"]),a={signal:"read the value from a Signal",property:"read the value from a property of the customControl (not usable in screens)",elementProperty:"a property defined on the element raising the event",signalInProperty:"read the value from a Signal (wich name is in the Property)",event:"read the value of a property of the event object",parameter:"a parameter you hand over",context:"a value of the context",complexString:"a string with signals (contained in {})",complexSignal:"read the value from a signal wich name is build here (it can contain other signals in {})",expression:"js expression, 'ctx' is context object"},n=async o=>{let c=(o.value??[]).map(k=>({...k})),p=k=>{let N=(c[k].varName??"").trim();return N?s.test(N)?l.has(N)?`"${N}" is a reserved word and cannot be used as a variable name.`:c.some((E,B)=>B!==k&&(E.varName??"").trim()===N)?`"${N}" is used by more than one signal.`:null:`"${N}" is not a valid JavaScript variable name.`:null},d="height:22px; box-sizing:border-box; font-size:12px;",h=document.createElement("div");h.style.cssText="display:flex; flex-direction:column; gap:6px; padding:8px; height:100%; box-sizing:border-box; overflow-y:auto; font-size:12px;";let u=document.createElement("div");u.style.cssText="display:flex; align-items:center; gap:4px; font-weight:bold;";let g=document.createElement("span");g.textContent="Name",g.style.cssText="flex:0 0 120px;";let f=document.createElement("span");f.textContent="Typ",f.style.cssText="flex:0 0 130px;";let w=document.createElement("span");w.textContent="Signal",w.style.cssText="flex:1 1 auto;";let x=document.createElement("span");x.style.cssText="flex:0 0 22px;",u.append(g,f,w,x),h.appendChild(u);let T=document.createElement("div");T.style.cssText="display:flex; flex-direction:column; gap:4px;",h.appendChild(T);let z=document.createElement("div");z.style.cssText="flex:0 0 auto; margin-top:4px; padding-top:6px; border-top:1px solid #ccc; font-size:12px;";let P=document.createElement("div");P.style.cssText="font-weight:bold; margin-bottom:2px;";let G=document.createElement("div");G.style.cssText="color:#333; white-space:pre-line;",z.append(P,G);let q=k=>{P.textContent="Typ: "+k,G.textContent=a[k]??""},M=[],X=()=>{c.forEach((k,N)=>{let E=M[N];if(!E)return;let B=p(N);E.title=B??`Variable name used in the formula (defaults to __${N} if empty)`,E.style.borderColor=B?"#c0392b":"",E.style.backgroundColor=B?"#fdecea":""})},I=()=>{T.innerHTML="",M.length=0,c.forEach((k,N)=>{let E=document.createElement("div");E.style.cssText="display:flex; align-items:center; gap:4px;";let B=document.createElement("input");B.value=k.varName??"",B.placeholder="__"+N,B.style.cssText=d+" flex:0 0 120px; min-width: 120px; font-family:monospace;",B.oninput=()=>{k.varName=B.value||void 0,X()},M.push(B),E.appendChild(B);let m=document.createElement("select");m.style.cssText=d+" flex:0 0 130px;";for(let R of i){let S=document.createElement("option");S.value=R,S.textContent=R,k.source===R&&(S.selected=!0),m.appendChild(S)}m.onchange=()=>{k.source=m.value,q(m.value)},m.onfocus=()=>q(m.value),E.appendChild(m);let b=document.createElement("input");b.value=k.name??"",b.placeholder="e.g. srm.rbg{__tagRoot}.error",b.style.cssText=d+" flex:1 1 auto;",b.oninput=()=>{k.name=b.value},E.appendChild(b);let v=document.createElement("button");v.title="Remove signal",v.style.cssText=d+" flex:0 0 22px; width:22px; padding:0; display:flex; align-items:center; justify-content:center;";let V=document.createElement("img");V.src=_e+"icons/delete.svg",V.style.cssText="width:12px; height:12px;",v.appendChild(V),v.onclick=()=>{c.splice(N,1),I()},E.appendChild(v),T.appendChild(E)}),X()};I();let L=document.createElement("button");L.textContent="+ Add signal",L.style.cssText=d+" align-self:flex-start; padding:0 8px;",L.onclick=()=>{c.push({source:"signal",name:""}),I()},h.appendChild(L),q(c[0]?.source??"signal"),h.appendChild(z),await this.visualizationShell.openConfirmation(h,{title:"Edit signals",x:100,y:50,width:500,height:400,parent:this})&&(this._propertygrid.setPropertyValue(o.propertyPath,c),this._propertygrid.refresh())};this._propertygrid.visualizationHandler=this.visualizationHandler,this._propertygrid.visualizationShell=this.visualizationShell,this._propertygrid.serviceContainer=this.serviceContainer,this._propertygrid.instanceServiceContainer=this.instanceServiceContainer,this._propertygrid.bindableObjectsTarget="script",this._propertygrid.setNameColumnWidth(130),this._propertygrid.getTypeInfo=(o,c)=>{let p=Re(this.scriptCommandsTypeInfo,o,c);return p&&(c==="If"||o?.type==="If")&&(p.properties=p.properties.filter(d=>d.name!=="trueCommands"&&d.name!=="elseCommands")),p},this._propertygrid.getSpecialEditorForType=async(o,c,p,d,h)=>{if(!o.specialAllreadyAdded&&(o.specialAllreadyAdded=!0,o.format!=="collection"))if(o.format==="signalList"){let u=document.createElement("button");u.style.height="calc(100% - 6px)",u.style.position="relative",u.style.display="flex",u.style.justifyContent="center",u.style.width="20px",u.style.boxSizing="content-box",u.innerText="del",u.onclick=()=>{this._propertygrid.setPropertyValue(p,void 0),this._propertygrid.refresh()},d.nodeElem.insertAdjacentElement("afterbegin",u);let g=Array.isArray(c)?c:[],f=document.createElement("div");f.style.display="flex";let w=document.createElement("span");w.innerText=g.map((T,z)=>(T?.varName||"__"+z)+": "+(T?.source??"")+":"+(T?.name??"")).join(", "),w.style.overflow="hidden",w.style.whiteSpace="nowrap",w.style.textOverflow="ellipsis",w.style.flexGrow="1",w.title=JSON.stringify(g),f.appendChild(w);let x=document.createElement("button");return x.innerText="...",x.onclick=()=>{n({value:g,propertyPath:p})},f.appendChild(x),d.nodeElem.style.display="flex",f}else if(o.format==="formula"){let u=document.createElement("div");u.style.cssText="display:flex; width:100%; height:100%; align-items:stretch;";let g=new ze;g.language="javascript",g.singleRow=!0,g.style.cssText="flex:1 1 auto; min-width:0; height:100%; position:relative; overflow:hidden;",g.code=c??"",g.addEventListener("code-changed",()=>{this._propertygrid.setPropertyValue(p,g.code)}),u.appendChild(g);let f=document.createElement("button");return f.innerText="...",f.title="Open in larger editor",f.style.cssText="flex:0 0 28px; width:20px;",f.onclick=()=>t({value:g.code,propertyPath:p}),u.appendChild(f),d.nodeElem.style.display="flex",u}else if(typeof c=="object"&&c!==null||o.format==="complex"){let u=document.createElement("button");u.style.height="calc(100% - 6px)",u.style.position="relative",u.style.display="flex",u.style.justifyContent="center",u.style.width="20px",u.style.boxSizing="content-box",u.innerText="del",u.onclick=()=>{this._propertygrid.setPropertyValue(p,void 0),this._propertygrid.refresh()},d.nodeElem.insertAdjacentElement("afterbegin",u);let g=document.createElement("div");g.style.display="flex";let f=document.createElement("span");c?f.innerText=(c.source??"")+": "+(c.name??""):f.innerText="",f.style.overflow="hidden",f.style.whiteSpace="nowrap",f.style.textOverflow="ellipsis",f.style.flexGrow="1",f.title=JSON.stringify(c),g.appendChild(f);let w=document.createElement("button");return w.innerText="...",w.onclick=()=>{e({value:c,propertyPath:p})},g.appendChild(w),d.nodeElem.style.display="flex",g}else{let u=document.createElement("button");u.style.height="calc(100% - 6px)",u.style.position="relative",u.style.display="flex",u.style.justifyContent="center",u.style.width="20px",u.style.boxSizing="content-box",u.title="complex property value",u.style.opacity="0.2",u.innerText="...",u.onclick=()=>{e({value:c,propertyPath:p})},d.nodeElem.insertAdjacentElement("afterbegin",u),d.nodeElem.style.display="flex"}return null},this._propertygrid.propertyNodeContextMenu.on(o=>{It.show([{title:"edit complex value",action:async()=>{e(o)}},{title:"edit string",action:async()=>{let c=prompt("enter value:");c&&(this._propertygrid.setPropertyValue(o.propertyPath,c),this._propertygrid.refresh())}},{title:"remove complex value",action:async()=>{this._propertygrid.setPropertyValue(o.propertyPath,void 0),this._propertygrid.refresh()}}],o.event)})}helpClicked(){let e=document.createElement("iframe");e.srcdoc=Ve,e.style.cssText="width:100%; height:100%; border:none; display:block;",this.visualizationShell.openModal(e,{title:"Simple Script Editor Help",parent:this,x:-650,y:-100,width:620,height:620}),this.helpRequested.emit()}toggleCodeView(){if(!this._showingCode){let t=JSON.stringify({commands:this.getScriptCommands()},null,2);this._codeView.update(t),this._showCodeView(!0);return}let e=this._parseCodeViewScript();e&&(this._showCodeView(!1),this.loadScript(e))}_showCodeView(e){this._codeView.classList.toggle("visible",e),this._commandListDiv.classList.toggle("hidden",e),this._splitView.classList.toggle("code-mode",e),this._addCommandBtn.disabled=e,this._codeToggleBtn.innerText=e?"Visual":"Code",this._showingCode=e,e&&requestAnimationFrame(()=>this._codeView.activated())}_parseCodeViewScript(){let e;try{e=JSON.parse(this._codeView.getText())}catch(t){return alert(`Invalid JSON:
1218
+ `+t.message),null}return Array.isArray(e?.commands)?e:(alert('The JSON must have a "commands" array.'),null)}loadScript(e){this._script=e,this._commandListFancyTree&&(this._commandListFancyTree.destroy(),this._commandListDiv=this._getDomElement("commandList"));let t=[];for(let i of this._script.commands)i=Q.upgradeScriptCommand(i),t.push(this.createTreeItem(i));this._commandListFancyTree=new Rt({...Vt,element:this._commandListDiv,icon:!1,source:t,activate:i=>{this._propertygrid.selectedObject=i.node.data.data.item??null},render:i=>{let s=!!i.node.data.data?.branch;if(i.isNew){i.nodeElem.oncontextmenu=n=>(n.preventDefault(),!1);let a=document.createElement("span");if(a.style.cssText="display:inline-block; width:24px;",i.nodeElem.prepend(a),s)i.nodeElem._reservedRowWidth=a.offsetWidth;else{let n=document.createElement("div");n.className="drag-handle",n.title="Drag to reorder",n.innerHTML='<svg viewBox="0 0 24 24" width="14" height="14"><path d="M4 6h16M4 12h16M4 18h16" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',i.nodeElem.prepend(n);let o=i.nodeElem.parentElement,c=document.createElement("span");c.style.cssText="display:inline-block; width:32px;",i.nodeElem.appendChild(c);let p=document.createElement("div");p.className="cmd";let d=document.createElement("img");d.src=_e+"icons/copy.svg",d.title="Duplicate",d.onclick=()=>{let u=structuredClone(i.node.data.data.item);i.node.parent.addChildren(this.createTreeItem(u)).moveTo(i.node,"after")};let h=document.createElement("img");h.src=_e+"icons/delete.svg",h.title="Remove",h.onclick=()=>i.node.remove(),p.append(d,h),o.appendChild(p),i.nodeElem._reservedRowWidth=a.offsetWidth+c.offsetWidth}}let l=i.nodeElem._reservedRowWidth??0;if(l){let a=i.nodeElem.querySelector("span.wb-title");if(a){let n=parseFloat(a.style.width);isNaN(n)||(a.style.width=Math.max(0,n-l)+"px")}}},dnd:{guessDropEffect:!0,preventRecursion:!0,preventVoidMoves:!1,serializeClipboardData:!1,dragStart:i=>this._dragFromHandle?(this._draggedNode=i.node,i.event.dataTransfer.effectAllowed="move",i.event.dataTransfer.dropEffect="move",i.event.dataTransfer.setData(ee,"1"),!0):!1,dragEnd:()=>{this._draggedNode=null},dragEnter:i=>{let s=i.event.dataTransfer?.types.includes(ee);return i.event.dataTransfer.dropEffect=s?"move":"copy",!!i.node.data.data?.branch?new Set(["over"]):new Set(["before","after"])},dragOver:i=>{let s=i.event.dataTransfer?.types.includes(ee);i.event.dataTransfer.dropEffect=s?"move":"copy"},drop:async i=>{let s=i.event.dataTransfer?.types.includes(ee);if(i.region==="over"){if(s&&this._draggedNode)this._draggedNode.moveTo(i.node,"appendChild"),this._draggedNode.setClass("wb-drag-source",!1);else{let a=i.event.dataTransfer?.getData("text/plain");a&&i.node.addChildren(this.createTreeItem({type:a}))}return}let l=i.region=="before"?"before":"after";if(s&&this._draggedNode)this._draggedNode.moveTo(i.node,l),this._draggedNode.setClass("wb-drag-source",!1);else{let a=i.event.dataTransfer?.getData("text/plain");if(a){let n={type:a},o=this.createTreeItem(n);i.node.parent.addChildren(o).moveTo(i.node,l)}}}}}),this._commandListFancyTree.root.children?.[0]?.setActive()}createTreeItem(e){if(e.type==="If"){let t=e;return t.trueCommands??=[],t.elseCommands??=[],{title:"If",expanded:!0,data:{item:e},children:[{title:"true",expanded:!0,data:{branch:"true"},children:t.trueCommands.map(i=>this.createTreeItem(i))},{title:"else",expanded:!0,data:{branch:"else"},children:t.elseCommands.map(i=>this.createTreeItem(i))}]}}return{title:e.type,data:{item:e}}}nodeToCommand(e){let t=e.data.data.item;if(t.type==="If"){let i=e.children?.find(l=>l.data.data?.branch==="true"),s=e.children?.find(l=>l.data.data?.branch==="else");t.trueCommands=(i?.children??[]).map(l=>this.nodeToCommand(l)),t.elseCommands=(s?.children??[]).map(l=>this.nodeToCommand(l))}return t}_getBranchContainerNode(e){let t=e;for(;t;){if(t.data?.data?.branch)return t;t=t.parent}return null}async addCommand(){let e=new Z;e.loadCommands(this.scriptCommandsTypeInfo,this.commandDescriptions),e.title="Add Script Command",e.commandTypeChosen.on(()=>{if(e.selectedType){let i={type:e.selectedType},s=this.createTreeItem(i),l=this._getBranchContainerNode(this._commandListFancyTree.activeNode);l?l.addChildren(s):this._commandListFancyTree.addChildren(s)}});let t=new AbortController;e.closeRequested.on(()=>t.abort()),await this.visualizationShell.openModal(e,{title:"Add Script Command",x:300,y:50,width:620,height:400,parent:this,abortSignal:t.signal})}getScriptCommands(){if(this._showingCode){let t=this._parseCodeViewScript();t&&this.loadScript(t)}return this._commandListFancyTree.root.children.map(t=>this.nodeToCommand(t))}};customElements.define(te.is,te);import{BaseCustomWebComponentConstructorAppend as Dt,css as Lt,html as jt}from"@node-projects/base-custom-webcomponent";var ie=class extends Dt{static style=Lt`
1213
1219
  :host {
1214
1220
  display: grid;
1215
1221
  grid-template-columns: 80px 80px 80px auto;
@@ -1223,7 +1229,7 @@ ${H('{ "source": "parameter", "name": "myParam" }')} <span class="cs-comment">/
1223
1229
 
1224
1230
  span {
1225
1231
  font-size: 10px;
1226
- }`;static template=Rt`
1232
+ }`;static template=jt`
1227
1233
  <span></span>
1228
1234
  <span>name</span>
1229
1235
  <span>type</span>
@@ -1242,7 +1248,7 @@ ${H('{ "source": "parameter", "name": "myParam" }')} <span class="cs-comment">/
1242
1248
  <input hidden="[[item.type !== 'boolean']]" type="checkbox" checked="{{item.value}}">
1243
1249
  <div hidden="[[item.type !== 'null']]">-null-</div>
1244
1250
  </template>
1245
- <button @click="[[this._add()]]" style="width: 40px; height: 20px; align-self: center;">add</button>`;static is="node-projects-visualization-parameter-editor";constructor(){super(),this._restoreCachedInititalValues()}ready(){this._bindingsParse()}_parameterArray;setParametersObject(e){e!=null?this._parameterArray=Object.keys(e).map(t=>({key:t,type:typeof e[t]=="object"?"null":typeof e[t],value:e[t]})):this._parameterArray=[],this._bindingsRefresh()}getParametersObject(){let e=!1,t={};for(let i of this._parameterArray)if(i.key)switch(e=!0,t[i.key]=null,i.type){case"string":t[i.key]=i.value.toString();break;case"number":let s=parseFloat(i.value);t[i.key]=isNaN(s)?0:s;break;case"boolean":t[i.key]=!!i.value;break}return e?t:null}_remove(e){this._parameterArray.splice(e,1),this._bindingsRefresh()}_add(){this._parameterArray.push({type:"null"}),this._bindingsRefresh()}};customElements.define(ie.is,ie);import{BaseCustomWebComponentConstructorAppend as At,css as zt,html as Re}from"@node-projects/base-custom-webcomponent";import{ContextMenu as Ae,copyTextToClipboard as ze,getTextFromClipboard as De,PropertiesHelper as Dt}from"@node-projects/web-component-designer";var me=class o extends At{static style=zt`
1251
+ <button @click="[[this._add()]]" style="width: 40px; height: 20px; align-self: center;">add</button>`;static is="node-projects-visualization-parameter-editor";constructor(){super(),this._restoreCachedInititalValues()}ready(){this._bindingsParse()}_parameterArray;setParametersObject(e){e!=null?this._parameterArray=Object.keys(e).map(t=>({key:t,type:typeof e[t]=="object"?"null":typeof e[t],value:e[t]})):this._parameterArray=[],this._bindingsRefresh()}getParametersObject(){let e=!1,t={};for(let i of this._parameterArray)if(i.key)switch(e=!0,t[i.key]=null,i.type){case"string":t[i.key]=i.value.toString();break;case"number":let s=parseFloat(i.value);t[i.key]=isNaN(s)?0:s;break;case"boolean":t[i.key]=!!i.value;break}return e?t:null}_remove(e){this._parameterArray.splice(e,1),this._bindingsRefresh()}_add(){this._parameterArray.push({type:"null"}),this._bindingsRefresh()}};customElements.define(ie.is,ie);import{BaseCustomWebComponentConstructorAppend as Pt,css as Mt,html as De}from"@node-projects/base-custom-webcomponent";import{ContextMenu as Le,copyTextToClipboard as je,getTextFromClipboard as Pe,PropertiesHelper as Wt}from"@node-projects/web-component-designer";var ge=class r extends Pt{static style=Mt`
1246
1252
  :host {
1247
1253
  display: grid;
1248
1254
  grid-template-columns: 20px 1fr auto;
@@ -1276,18 +1282,81 @@ ${H('{ "source": "parameter", "name": "myParam" }')} <span class="cs-comment">/
1276
1282
  }
1277
1283
  button {
1278
1284
  cursor: pointer;
1279
- }`;static template=Re`
1285
+ }`;static template=De`
1280
1286
  <template repeat:item="[[this.events]]">
1281
1287
  <div @click="[[this._ctxMenu(event, item)]]" @contextmenu="[[this._ctxMenu(event, item)]]" class="rect" title="[[this._getScriptType(item)]]" css:background-color="[[this._getScriptTypeColor(item)]]"></div>
1282
1288
  <a @click="[[this._showContextMenuAssignScript(event, item, false)]]" @contextmenu="[[this._ctxMenu(event, item)]]" title="[[item.name]]">[[item.name]]</a>
1283
1289
  <div>[[this._createControlsForScript(item)]]</div>
1284
1290
  </template>
1285
1291
  <span style="grid-column: 1 / span 3; margin-top: 8px; margin-left: 3px;">add event:</span>
1286
- <input id="addEventInput" style="grid-column: 1 / span 3; margin: 5px;" @keypress="[[this._addEvent(event)]]" type="text">`;static editRowTemplate=Re`
1292
+ <input id="addEventInput" style="grid-column: 1 / span 3; margin: 5px;" @keypress="[[this._addEvent(event)]]" type="text">`;static editRowTemplate=De`
1287
1293
  <div style="display: flex; justify-content: flex-end;">
1288
1294
  <input value="[[this._getScriptName(item)]]" @keypress="[[this._changeScriptName(event, item)]]" hidden="[[this._getScriptType(item) !== 'js']]" placeholder="name" title="name" style="min-width: 50px; flex-basis: 30px; flex-grow: 2;" class="mth" type="text">
1289
1295
  <input value="[[this._getRelativeSignalsPath(item)]]" @keypress="[[this._changeRelativeSignalsPath(event, item)]]" placeholder="relative signals path" title="relative signals path" style="min-width: 50px; flex-basis: 20px; flex-grow: 1;" class="mth" type="text">
1290
1296
  <button css:background="[[this._hasParameters(item) ? 'lime' : '']]" style="display: flex; padding: 0; flex-grow: 0;" title="parameter" @click="[[this._editParameter(event, item)]]">p</button>
1291
- </div>`;static scriptTypeColors={js:"purple",blockly:"yellow",script:"lightgreen",empty:"pink"};static is="node-projects-visualization-event-assignment";constructor(){super(),this._restoreCachedInititalValues()}ready(){this._bindingsParse()}_blocklyToolbox;_instanceServiceContainer;_selectionChangedHandler;_selectedItems;_visualizationHandler;_visualizationShell;_scriptCommandsTypeInfo;_propertiesTypeInfo;_commandDescriptions;events;initialize(e,t,i,s,l,r){this._visualizationHandler=e,this._visualizationShell=t,this._scriptCommandsTypeInfo=i,this._propertiesTypeInfo=s,this._blocklyToolbox=l,this._commandDescriptions=r}set instanceServiceContainer(e){this._instanceServiceContainer=e,this._selectionChangedHandler?.dispose(),this._selectionChangedHandler=this._instanceServiceContainer?.selectionService.onSelectionChanged.on(t=>{this.selectedItems=t.selectedElements}),this.selectedItems=this._instanceServiceContainer?.selectionService.selectedElements??[]}dispose(){this.instanceServiceContainer=null}_createControlsForScript(e){switch(this._getScriptType(e)){case"none":return""}return this.constructor.editRowTemplate.content.cloneNode(!0)}_getScriptName(e){if(this.selectedItems[0].hasAttribute("@"+e.name)){let t=this.selectedItems[0].getAttribute("@"+e.name);if(t[0]==="{"){if(t.includes("name"))return JSON.parse(t).name}else return t}return null}async _changeScriptName(e,t){if(e.key=="Enter"&&this.selectedItems&&this.selectedItems.length&&this.selectedItems[0].hasAttribute("@"+t.name)){let i=e.target.value,s=this.selectedItems[0].getAttribute("@"+t.name);if(s.startsWith("{")){let l=JSON.parse(s);l.name=i,this._selectedItems[0].setAttribute("@"+t.name,JSON.stringify(l))}else this._selectedItems[0].setAttribute("@"+t.name,i)}}_getRelativeSignalsPath(e){if(this.selectedItems[0].hasAttribute("@"+e.name)){let t=this.selectedItems[0].getAttribute("@"+e.name);if(t[0]==="{"&&t.includes("relativeSignalsPath"))return JSON.parse(t).relativeSignalsPath}return null}async _changeRelativeSignalsPath(e,t){if(e.key=="Enter"&&this.selectedItems&&this.selectedItems.length&&this.selectedItems[0].hasAttribute("@"+t.name)){let i=e.target.value,s=this.selectedItems[0].getAttribute("@"+t.name);if(s.startsWith("{")){let l=JSON.parse(s);l.relativeSignalsPath=i,this._selectedItems[0].setAttribute("@"+t.name,JSON.stringify(l))}else{let l={name:s,relativeSignalsPath:i};this._selectedItems[0].setAttribute("@"+t.name,JSON.stringify(l))}}}_hasParameters(e){return this.selectedItems[0].hasAttribute("@"+e.name)?this.selectedItems[0].getAttribute("@"+e.name).includes("parameters"):!1}_getScriptTypeColor(e){let t=this._getScriptType(e);return o.scriptTypeColors[t]??"white"}_getScriptType(e){if(e.designItem.hasAttribute("@"+e.name)){let t=e.designItem.getAttribute("@"+e.name);if(t.startsWith("{")){let i=JSON.parse(t);return"blocks"in i?"blockly":"commands"in i?"script":"js"}else return t==""?"empty":"js"}return"none"}_getEventMethodname(e){return this.selectedItems.length?this.selectedItems[0].getAttribute("@"+e.name):""}_inputMthName(e,t){let i=e.target;this.selectedItems[0].setAttribute("@"+t.name,i.value)}_ctxMenu(e,t){e.preventDefault();let i=this._getScriptType(t);if(i=="empty")this._showContextMenuAssignScript(e,t,!0);else if(i!="none"){let s=[{title:"remove",action:()=>{this.selectedItems[0].removeAttribute("@"+t.name),this._bindingsRefresh()}},{title:"-"},{title:"copy",action:()=>{ze(this.selectedItems[0].getAttribute("@"+t.name))}},{title:"paste",action:async()=>{this.selectedItems[0].setAttribute("@"+t.name,await De()),this._bindingsRefresh()}}];Ae.show(s,e)}else this._showContextMenuAssignScript(e,t,!0)}async _addEvent(e){if(e.key=="Enter"){let t=this._getDomElement("addEventInput");this._selectedItems[0].setAttribute("@"+Dt.camelToDashCase(t.value.replaceAll(" ","-")),""),t.value="",this.scrollTop=0,this.refresh()}}_createAssignScriptContextMenu(e,t){let i=[{title:"Simple Script",action:()=>{this._editEvent("script",e,t)}},{title:"Javascript",action:()=>{let l=prompt("name of function ?");l&&(this._selectedItems[0].setAttribute("@"+t.name,l),this.refresh(),this._editEvent("js",null,t))}},{title:"Blockly",action:()=>{this._editBlockly(null,t)}}],s=this._getScriptType(t);return s!="none"&&(i.push({title:"-"}),i.push({title:"remove",action:()=>{this.selectedItems[0].removeAttribute("@"+t.name),this._bindingsRefresh()}})),s!="empty"&&i.push({title:"-"},{title:"copy",action:()=>{ze(this.selectedItems[0].getAttribute("@"+t.name))}},{title:"paste",action:async()=>{this.selectedItems[0].setAttribute("@"+t.name,await De()),this._bindingsRefresh()}}),i}async _showContextMenuAssignScript(e,t,i){e.preventDefault();let s=this._getScriptType(t);if(s!="none"&&s!="empty"&&!i)this._editEvent(s,e,t);else{let l=this._createAssignScriptContextMenu(e,t);Ae.show(l,e)}}async _editParameter(e,t){let i=new ie,s={};i.title="ParameterEditor for '"+t.name+"' of '"+t.designItem.name+"'";let l=t.designItem.getAttribute("@"+t.name);if(l&&l[0]=="{")try{s=JSON.parse(l).parameters}catch{}if(i.setParametersObject(s),await this._visualizationShell.openConfirmation(i,{x:100,y:100,width:700,height:500})){let n=i.getParametersObject(),a={name:l,parameters:n};l&&l[0]=="{"&&(a=JSON.parse(l),a.parameters=n),n==null&&delete a.parameters;let c=JSON.stringify(a);t.designItem.setAttribute("@"+t.name,c),this._bindingsRefresh()}}async _editBlockly(e,t){let i=new Y(this._blocklyToolbox);i.title="Blockly Script for '"+t.name+"' of '"+t.designItem.name+"'";let s=t.designItem.getAttribute("@"+t.name),l=null,r=null;if(s){let a=JSON.parse(s);l=a.parameters,r=a.relativeSignalsPath,i.load(a)}if(await this._visualizationShell.openConfirmation(i,{x:100,y:100,width:700,height:500})){let a=i.save();l&&(a.parameters=l),r&&(a.relativeSignalsPath=r),t.designItem.setAttribute("@"+t.name,JSON.stringify(a)),this._bindingsRefresh()}}async _editJavascript(e,t){}async _editSimpleScript(e,t){let i=t.designItem.getAttribute("@"+t.name);if(!i||i.startsWith("{")){let s={commands:[]},l=null,r=null;i&&(s=JSON.parse(i),l=s.parameters,r=s.relativeSignalsPath);let n=new te;if(n.serviceContainer=t.designItem.serviceContainer,n.instanceServiceContainer=t.designItem.instanceServiceContainer,n.scriptCommandsTypeInfo=this._scriptCommandsTypeInfo,n.propertiesTypeInfo=this._propertiesTypeInfo,n.visualizationShell=this._visualizationShell,n.visualizationHandler=this._visualizationHandler,this._commandDescriptions&&(n.commandDescriptions={...n.commandDescriptions,...this._commandDescriptions}),n.loadScript(s),n.title="Script '"+t.name+"' on "+t.designItem.name,await this._visualizationShell.openConfirmation(n,{title:n.title,width:600,height:500})){let c=n.getScriptCommands();if(c&&c.length){let p={commands:c};l&&(p.parameters=l),r&&(p.relativeSignalsPath=r);let d=JSON.stringify(p);t.designItem.setAttribute("@"+t.name,d),this._bindingsRefresh()}}}}async _editEvent(e,t,i){e=="js"?this._editJavascript(t,i):e=="blockly"?this._editBlockly(t,i):this._editSimpleScript(t,i)}refresh(){this._selectedItems!=null&&this._selectedItems.length?this.events=this._selectedItems[0].serviceContainer.getLastServiceWhere("eventsService",e=>e.isHandledElementFromEventsService(this._selectedItems[0])).getPossibleEvents(this._selectedItems[0]).map(e=>({...e,designItem:this._selectedItems[0]})):this.events=[],this._bindingsRefresh()}get selectedItems(){return this._selectedItems}set selectedItems(e){this._selectedItems!=e&&(this._selectedItems=e,this.refresh())}};customElements.define(me.is,me);import{TypedEvent as Lt,cssFromString as Le}from"@node-projects/base-custom-webcomponent";import{BindingTarget as f}from"@node-projects/web-component-designer/dist/elements/item/BindingTarget.js";import{PropertiesHelper as I}from"@node-projects/web-component-designer/dist/elements/services/propertiesService/services/PropertiesHelper.js";var se="bind-prop:",le="bind-attr:",ce="bind-class:",pe="bind-css:",ne="bind-cssvar:",J="bind-content:",xe="bind-visible:",je="bind(",jt="--tmpBinding_",as=/{{(.*)}}/;function de(o){return o.constructor?.elementProperties!=null}function _e(o){let e=[],t=[],i=0;for(let s=0;s<o.length;s++)o[s]=="{"?(e.push(o.substring(i,s)),i=s+1):o[s]=="}"&&(t.push(o.substring(i,s)),i=s+1);return e.push(o.substring(i)),{parts:e,signals:t}}function Me(o,e,t,i){let s=!0,l=0,r=()=>{let a=++l,c=o.valueProvider(e,t);c instanceof Promise?c.then(p=>s&&a===l&&i(p)):s&&i(c)};r(),o.valueChangedCallbacks||(o.valueChangedCallbacks=new Map);let n=o.valueChangedCallbacks.get(e);return n||(n=[],o.valueChangedCallbacks.set(e,n)),n.push(r),()=>{s=!1;let a=n.indexOf(r);a>=0&&n.splice(a,1),n.length===0&&o.valueChangedCallbacks.get(e)===n&&o.valueChangedCallbacks.delete(e)}}function Pt(o,e){let t=e.split("."),i=o;for(let s of t){if(i==null||typeof i!="object")return;i=i[s]}return i}function ge(o,e,t,i,s=!1){let l=s&&t.includes("."),r=l?()=>Pt(e,t):()=>e[t];if(i(r()),l)return()=>{};let n=()=>i(r()),a=o.getChangedEventName(e,t);return e.addEventListener(a,n),()=>e.removeEventListener(a,n)}function We(o,e,t){t(o.getAttribute(e));let i=new MutationObserver(()=>t(o.getAttribute(e)));return i.observe(o,{attributes:!0,attributeFilter:[e]}),()=>i.disconnect()}var we=class{bindingsHelper;parts;signals;values;unsubscribeTargetValue;cleanupCalls=[];combinedName;disposed=!1;valueChangedCb;visualizationHandler;element;relativeSignalPath;constructor(e,t,i,s,l,r,n,a){this.bindingsHelper=e,this.visualizationHandler=t,this.valueChangedCb=s,this.element=l,this.relativeSignalPath=r,this.parseIndirectBinding(i),this.values=new Array(this.signals.length);let c=(p,d,g)=>{let u,m=()=>{},y=_=>{let w=_;if(typeof w=="string"&&w[0]==="."&&(w=t.getNormalizedSignalName(w,r,l)),w!==u)if(m(),u=w,typeof w=="string"){let C=(z,P)=>this.handleValueChanged(P.val,g);m=e.subscribeToState(w,C)}else m=()=>{}};this.cleanupCalls.push(ge(e,p,d,y,!0)),this.cleanupCalls.push(()=>m())};try{for(let p=0;p<this.signals.length;p++){let d=this.signals[p];if(d.startsWith("?@")||d.startsWith("#@")){let g=d[0]==="?"?n:l;this.cleanupCalls.push(We(g,d.substring(2),u=>this.handleValueChanged(u,p)))}else if(d.startsWith("??")||d.startsWith("##")||d.startsWith("?$")||d.startsWith("#$")){let g=d[0]==="?"?n:l;this.cleanupCalls.push(ge(e,g,d.substring(2),u=>this.handleValueChanged(u,p),!0))}else if(d[0]==="\xA7"){let g=d.substring(1);if(!a)throw new Error(`No special value handler registered for "${d}"`);this.cleanupCalls.push(Me(a,g,{element:l,relativeSignalPath:r,root:n},u=>this.handleValueChanged(u,p)))}else if(d[0]==="?"||d[0]==="#")c(d[0]==="?"?n:l,d.substring(1),p);else{let g=(u,m)=>this.handleValueChanged(m.val,p);this.cleanupCalls.push(e.subscribeToState(d,g))}}}catch(p){throw this.dispose(),p}}parseIndirectBinding(e){let{parts:t,signals:i}=_e(e);this.parts=t,this.signals=i;for(let s=0;s<i.length;s++)i[s][0]=="."&&(i[s]=this.visualizationHandler.getNormalizedSignalName(i[s],this.relativeSignalPath,this.element))}handleValueChanged(e,t){if(this.disposed)return;this.values[t]=e;let i=this.parts[0];for(let s=0;s<this.parts.length-1;s++){let l=this.values[s];if(l==null)return;i+=l+this.parts[s+1]}if(i[0]=="."&&(i=this.visualizationHandler.getNormalizedSignalName(i,this.relativeSignalPath,this.element)),this.combinedName!=i&&(this.unsubscribeTargetValue&&this.unsubscribeTargetValue(),!this.disposed)){this.combinedName=i;let s=(l,r)=>this.valueChangedCb(r);this.unsubscribeTargetValue=this.bindingsHelper.subscribeToState(i,s)}}dispose(){this.disposed=!0,this.unsubscribeTargetValue&&(this.unsubscribeTargetValue(),this.unsubscribeTargetValue=null);for(let e of this.cleanupCalls)e();this.cleanupCalls.length=0}setState(e){!this.disposed&&this.combinedName&&this.visualizationHandler.setState(this.combinedName,e)}},Pe=class o{_visualizationHandler;namedConverterCallback;_stateSubscriptions=new Map;_scheduledUpdates=new Set;_updateFlushScheduled=!1;_compiledConverters=new WeakMap;constructor(e){this._visualizationHandler=e}scheduleUpdate(e){this._scheduledUpdates.add(e),!this._updateFlushScheduled&&(this._updateFlushScheduled=!0,queueMicrotask(()=>{this._updateFlushScheduled=!1;let t=[...this._scheduledUpdates];this._scheduledUpdates.clear();for(let i of t)i()}))}getChangedEventName(e,t){let i=t.indexOf("::");if(i>=0)return t.substring(i+2);if(e instanceof HTMLInputElement||e instanceof HTMLSelectElement)return"change";let s=I.camelToDashCase(t);return de(e)?s:s+"-changed"}getParsedTargetName(e,t){return t===f.cssvar||t===f.class?o.dotToCamelCase(e):t===f.attribute?e:I.dashToCamelCase(e)}parseBinding(e,t,i,s,l){let r=t.substring(l.length);if(s===f.cssvar&&(r="--"+r),!i.startsWith("{")){let a={signal:i,target:s};if(i[0]==="="){if(i=i.substring(1),a.signal=i,i.includes("::")){let c=i.split("::");i=c[0],a.signal=i,a.events=c[1].split(",")}a.twoWay=!0,a.events||(a.events=[this.getChangedEventName(e,r)],!(e instanceof HTMLInputElement)&&!(e instanceof HTMLSelectElement)&&!de(e)&&(a.maybeLitElement=!0,a.litEventNames=a.events))}if(i[0]==="!"&&(a.signal=i.substring(1),a.inverted=!0),a.signal.includes(";")){let c=a.signal.split(";");a.expression=c.pop(),a.signal=c.join(";")}return[this.getParsedTargetName(r,s),a]}let n=JSON.parse(i);return n.target=s,n.twoWay&&(n.events==null||n.events.length==0)&&(n.events=[this.getChangedEventName(e,r)]),[this.getParsedTargetName(r,s),n]}serializeBinding(e,t,i){let s={...i};delete s.type,i.twoWay?i.events!=null&&i.events.length==1&&((e instanceof HTMLInputElement||e instanceof HTMLSelectElement)&&i.events?.[0]=="change"||de(e)&&i.events?.[0]==t||!de(e)&&i.events?.[0]==t+"-changed")&&delete s.events:(delete s.events,delete s.expressionTwoWay);let l=s.twoWay&&s.events?.length>0?"::"+s.events.join(","):"",r=l!==""&&!!i.expression?.includes("::")||!!i.expressionTwoWay?.includes("::")||i.signal.trim()[0]=="{",n=i.target==f.property||i.target==f.attribute||i.target==f.class||i.target==f.css||i.target==f.cssvar,a=!r&&n&&!i.expressionTwoWay&&i.converter==null&&!i.historic&&!i.writeBackSignal;if(a&&!i.expression){let c=this.getShortBindingAttributeName(t,i.target,!1),d=((i.target==f.property||i.target==f.attribute)&&i.twoWay?"=":"")+(i.inverted?"!":"")+i.signal+(!i.twoWay&&i.signal.includes(";")?";":"")+l;return[c,d]}if(a&&i.expression&&!i.expression.includes(`
1292
- `)&&!i.expression.includes(";")){let c=this.getShortBindingAttributeName(t,i.target,!0),d=((i.target==f.attribute||i.target==f.property&&t!="textContent"&&t!="innerHTML")&&i.twoWay?"=":"")+(i.inverted?"!":"")+i.signal+";"+i.expression+l;return[c,d]}return(i.inverted===null||i.inverted===!1)&&delete s.inverted,(i.expression===null||i.expression==="")&&delete s.expression,(i.expressionTwoWay===null||i.expressionTwoWay==="")&&delete s.expressionTwoWay,(i.twoWay===null||i.twoWay===!1)&&delete s.twoWay,delete s.target,i.historic||delete s.historic,[this.getJsonBindingAttributeName(t,i.target),JSON.stringify(s)]}getShortBindingAttributeName(e,t,i){return t==f.property&&e=="textContent"?J+"text":t==f.property&&e=="innerHTML"?J+"html":t==f.attribute?le+I.camelToDashCase(e):t==f.class?ce+I.camelToDashCase(e):t==f.css?pe+I.camelToDashCase(e):t==f.cssvar?i?ne+I.camelToDashCase(e):ne+o.camelToDotCase(e.substring(2)):se+I.camelToDashCase(e)}getJsonBindingAttributeName(e,t){return t==f.content||t==f.property&&e=="innerHTML"?J+"html":t==f.property&&e=="textContent"?J+"text":t==f.attribute?le+I.camelToDashCase(e):t==f.class?ce+o.camelToDotCase(e):t==f.css?pe+I.camelToDashCase(e):t==f.cssvar?ne+o.camelToDotCase(e.substring(2)):se+I.camelToDashCase(e)}getBindingAttributeName(e,t,i){return i==f.attribute?le+I.camelToDashCase(t):i==f.class?ce+o.camelToDotCase(t):i==f.css?pe+I.camelToDashCase(t):i==f.visible?xe:i==f.cssvar?ne+o.camelToDotCase(t):i==f.property&&t=="innerHTML"?J+"html":i==f.property&&t=="textContent"?J+"text":se+I.camelToDashCase(t)}*getBindings(e){if(e.attributes)for(let t of e.attributes)t.name.startsWith(se)?yield this.parseBinding(e,t.name,t.value,f.property,se):t.name.startsWith(J)?yield this.parseBinding(e,t.name==="bind-content:html"?"bind-prop:inner-h-t-m-l":"bind-prop:text-content",t.value,f.property,se):t.name.startsWith(le)?yield this.parseBinding(e,t.name,t.value,f.attribute,le):t.name.startsWith(ce)?yield this.parseBinding(e,t.name,t.value,f.class,ce):t.name.startsWith(pe)?yield this.parseBinding(e,t.name,t.value,f.css,pe):t.name.startsWith(ne)?yield this.parseBinding(e,t.name,t.value,f.cssvar,ne):t.name.startsWith(xe)&&(yield this.parseBinding(e,t.name,t.value,f.visible,xe))}applyAllBindings(e,t,i,s,l){let r=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT),a=n.nextNode();for(;a;){let c=this.getBindings(a);for(let p of c)try{let d=this.applyBinding(a,p,t,i,s),g=!1,u=()=>{g||(g=!0,d())};if(r.push(u),p[1].maybeLitElement&&a.localName.includes("-")&&!customElements.get(a.localName)){let m=a,y=p;customElements.whenDefined(a.localName).then(()=>{!g&&de(m)&&(g=!0,d(),y[1].events=y[1].litEventNames,r.push(this.applyBinding(m,y,t,i,s)))})}}catch(d){console.warn("error applying binding",a,p,d)}if(l&&l(a)){let p=n.nextSibling();for(;!p&&a;)a=n.parentNode(),p=n.nextSibling();a=p}else a=n.nextNode()}return r}static#e=0;async parseCssBindings(e,t,i,s){if(!e.includes(je))return[Le(e),[]];let l=await import("@node-projects/css-parser"),r=l.parse(e),n=[];for(let c of r.stylesheet.rules)if(c.type===l.CssTypes.rule){for(let p of c.declarations)if(p.type===l.CssTypes.declaration&&p.value.includes(je)){let d=this.parseCssBinding(p.value,t,i,s);p.value=d[0],n.push(...d[1])}}let a=l.stringify(r,{indent:"",compress:!0});return[Le(a),n]}parseCssBinding(e,t,i,s,l){e=e.trim();let r="",n="",a=!1,c="",p=!1,d=null,g=[];for(let u=0;u<e.length;u++){let m=e[u];if(a)if(p)c+=m,p=!1;else if(d&&m==="\\")p=!0;else if(m===d)d=null;else if(d===null&&m===")"){let y=o.#e++,_=jt+y,w=[_,{signal:c,target:f.cssvar}];c.startsWith("{")&&(w=JSON.parse(c)),g.push(this.applyBinding(t,w,i,s,l)),r+="var("+_+")",a=!1,c=""}else c+=m;else m==="("?(n!=="bind"?(r+=n,r+=m):(a=!0,e[u+1]==="'"||e[u+1]==='"'?(u++,d=e[u]):d=null),n=""):m===" "||m===","||m==="("||m==="+"||m==="-"||m==="*"||m==="/"?(r+=n+m,n=""):n+=m}return[r+n,g]}subscribeToState(e,t){let i=this._stateSubscriptions.get(e);if(i){if(i.callbacks.add(t),i.hasValue){let l=i.value;queueMicrotask(()=>i.callbacks.has(t)&&t(e,l))}}else{i={callbacks:new Set([t]),callback:null,subscriptionResult:null,revision:0,hasValue:!1},i.callback=(l,r)=>{i.revision++,i.hasValue=!0,i.value=r;for(let n of i.callbacks)n(l,r)},this._stateSubscriptions.set(e,i);try{i.subscriptionResult=this._visualizationHandler.subscribeState(e,i.callback);let l=i.revision;this._visualizationHandler.getState(e).then(r=>{this._stateSubscriptions.get(e)===i&&i.revision===l&&i.callback(e,r)})}catch(l){throw this._stateSubscriptions.delete(e),i.subscriptionResult!=null&&this._visualizationHandler.unsubscribeState(e,i.callback,i.subscriptionResult),l}}let s=!0;return()=>{s&&(s=!1,i.callbacks.delete(t),i.callbacks.size===0&&this._stateSubscriptions.get(e)===i&&(this._stateSubscriptions.delete(e),this._visualizationHandler.unsubscribeState(e,i.callback,i.subscriptionResult)))}}applyBinding(e,t,i,s,l){let r=[],n=!0,a=()=>{if(n){n=!1,this._scheduledUpdates.delete(X);for(let h=r.length-1;h>=0;h--)r[h]();r.length=0}},c=h=>r.push(h),p=t[1].signal.split(";"),d=new Array(p.length);for(let h=0;h<p.length;h++){let b=p[h];d[h]="__"+h;let v=b.indexOf(":");v>=0&&(d[h]=b.substring(0,v),b=b.substring(v+1),p[h]=b)}let g=new Array(p.length),u=[...d,"__res","__ctx"];t[1].expression&&!t[1].compiledExpression&&(t[1].compiledExpression=t[1].expression.includes("return ")?new Function(u,t[1].expression):new Function(u,"return "+t[1].expression));let m=this.getCompiledConverter(t[1],u),y={element:e,root:s,boundNames:t[1].signal,boundTargetName:t[0],boundTargetType:t[1].target},_=this.createTargetWriter(e,t),w=t[1].writeBackSignal;w?.[0]==="."&&(w=i+w);let C,z,P,G=!1,q=!1,M=!1,X=()=>{if(M=!1,!n)return;let h=C;t[1].compiledExpression&&(h=t[1].compiledExpression(...g,z,y),z=h),t[1].converter&&(typeof t[1].converter=="string"?h=this.namedConverterCallback(t[1].converter,h,e,t):h=this.applyCompiledConverter(h,m,g,z,y,t[1].converterDefault)),t[1].inverted&&(h=!h),q=!0,!(G&&(h===null||typeof h!="object")&&Object.is(P,h))&&(G=!0,P=h,w&&this._visualizationHandler.setState(w,h,!0),_(h))},B=(h,b,v)=>{n&&(!v&&b===0&&(h=o.parseValueWithType(h,t)),g[b]=h,C=h,!q&&p.length===1?X():M||(M=!0,this.scheduleUpdate(X)))},L=new Array(p.length),oe=(h,b)=>(L[h]=b,()=>{L[h]===b&&(L[h]=null)}),k=(h,b,v)=>{let V=oe(v,S=>h[b]=S),A=ge(this,h,b,S=>B(S,v,!1));return()=>{A(),V()}},N=(h,b,v)=>{let V=oe(v,S=>S==null?h.removeAttribute(b):h.setAttribute(b,S)),A=We(h,b,S=>B(S,v,!1));return()=>{A(),V()}},E=(h,b)=>{if(h.startsWith("?@")||h.startsWith("#@")){let x=h[0]==="?"?s:e;return x?N(x,h.substring(2),b):()=>{}}if(h.startsWith("?$")||h.startsWith("#$")){let x=h[0]==="?"?s:e;return x?k(x,h.substring(2),b):()=>{}}if(h[0]==="?"||h[0]==="#"){let x=h[0]==="?"?s:e;return x?k(x,h.substring(1),b):()=>{}}if(h[0]==="$"){let x=h.substring(1);x[0]==="."&&(x=this._visualizationHandler.getNormalizedSignalName(x,i,e));let D=!0;return this._visualizationHandler.getObject(x).then(R=>{D&&B(R,b,!0)}),()=>D=!1}if(h[0]==="\xA7"){if(!l)throw new Error(`No special value handler registered for "${h}"`);return Me(l,h.substring(1),{element:e,binding:t,relativeSignalPath:i,root:s},x=>B(x,b,!0))}if(h.includes("{")){let x=new we(this,this._visualizationHandler,h,R=>B(R.val,b,!1),e,i,s,l),D=oe(b,R=>x.setState(R));return()=>{x.dispose(),D()}}let v=h;if(v[0]==="."&&(v=this._visualizationHandler.getNormalizedSignalName(v,i,e)),t[1].historic){let x=t[1].historic;if(x.reloadInterval){let R=!0,W=null,F=async()=>{let et=await this._visualizationHandler.getHistoricData(v,x);!n||!R||(B(et?.values,b,!0),W=setTimeout(F,x.reloadInterval))};return F(),()=>{R=!1,W!==null&&clearTimeout(W),W=null}}let D=!0;return this._visualizationHandler.getHistoricData(v,x).then(R=>{D&&B(R?.values,b,!0)}),()=>D=!1}let V=(x,D)=>B(D?.val,b,!1),A=this.subscribeToState(v,V),S=oe(b,x=>this._visualizationHandler.setState(v,x));return()=>{A(),S()}},O=(h,b)=>{if(h.startsWith("?@")||h.startsWith("#@")||h.startsWith("?$")||h.startsWith("#$"))return E(h,b);let v=h[0];if(v!=="?"&&v!=="#"||h[1]===v)return E(h[1]===v?h.substring(1):h,b);let V=v==="?"?s:e;if(!V)return()=>{};let A=h.substring(1),S=()=>{},x,R=ge(this,V,A,W=>{let F=typeof W=="string"?W:null;F!==x&&(S(),x=F,S=F?E(F,b):()=>{})});return()=>{R(),S()}};try{t[1].twoWay&&c(this.addTwoWayBinding(t,e,h=>L[0]?.(h)));for(let h=0;h<p.length;h++)typeof p[h]=="string"&&c(O(p[h],h))}catch(h){throw a(),h}return a}addTwoWayBinding(e,t,i){e[1].expressionTwoWay&&!e[1].compiledExpressionTwoWay&&(e[1].compiledExpressionTwoWay=e[1].expressionTwoWay.includes("return ")?new Function(["value"],e[1].expressionTwoWay):new Function(["value"],"return "+e[1].expressionTwoWay));let s=[],l=()=>{let r=e[1].target==f.attribute?t.getAttribute(e[0]):t[e[0]];r=o.parseValueWithType(r,e),e[1].compiledExpressionTwoWay&&(r=e[1].compiledExpressionTwoWay(r)),i(r)};for(let r of e[1].events??[]){let n=t[r];if(n instanceof Lt){let a=n.on(l);s.push(()=>a.dispose())}else t.addEventListener(r,l),s.push(()=>t.removeEventListener(r,l))}return()=>{for(let r of s)r();s.length=0}}static parseValueWithType(e,t){if(t[1].type)switch(t[1].type){case"number":return parseFloat(e);case"boolean":return e===!0||e==="true"||!!parseInt(e);case"string":return e?.toString();case"integer":return parseInt(e)}return e}compileConverter(e,t){let i=new Map,s=[],l=r=>{if(typeof r!="string")return{value:r};let n=new Function(t,"return `"+r+"`");return{value:r,evaluate:(a,c,p)=>n(...a,c,p)}};for(let r in e){let n=l(e[r]);if(i.set(r,n),r.startsWith(">=")){let a=parseFloat(r.substring(2));s.push({matches:c=>c>=a,value:n})}else if(r.startsWith("<=")){let a=parseFloat(r.substring(2));s.push({matches:c=>c<=a,value:n})}else if(r[0]===">"){let a=parseFloat(r.substring(1));s.push({matches:c=>c>a,value:n})}else if(r[0]==="<"){let a=parseFloat(r.substring(1));s.push({matches:c=>c<a,value:n})}else{let a=r.split("-");if(a.length>1){let c=a[0]===""?null:parseFloat(a[0]),p=a[1]===""?null:parseFloat(a[1]);s.push({matches:d=>(c===null||d>=c)&&(p===null||p>=d),value:n})}}}return{exactValues:i,conditions:s}}getCompiledConverter(e,t){if(!e.converter||typeof e.converter!="object")return null;let i=t.join("\0"),s=this._compiledConverters.get(e);if(s?.converter===e.converter&&s.argumentsKey===i)return s.compiled;let l=this.compileConverter(e.converter,t);return this._compiledConverters.set(e,{converter:e.converter,argumentsKey:i,compiled:l}),l}applyCompiledConverter(e,t,i,s,l,r){let n=String(e),a=t.exactValues.get(n),c=t.exactValues.has(n);if(!c){let p=parseFloat(e);for(let d of t.conditions)if(d.matches(p)){a=d.value,c=!0;break}}return c?a.evaluate?a.evaluate(i,s,l):a.value:r!==void 0?r:e}createTargetWriter(e,t){let i=t[0];switch(t[1].target){case f.property:return s=>e[i]=s;case f.attribute:return s=>{typeof s=="boolean"?s?e.setAttribute(i,""):e.removeAttribute(i):e.setAttribute(i,s)};case f.css:return s=>e.style[i]=s;case f.cssvar:return s=>e.style.setProperty(i,s);case f.class:return s=>e.classList.toggle(i,!!s);case f.visible:return s=>e.style.visibility=s?"":"collapse";default:return()=>{}}}static camelToDotCase(e){return e.replace(/([A-Z])/g,t=>`.${t[0].toLowerCase()}`)}static dotToCamelCase(e){return e.replace(/\.([a-z])/g,t=>t[1].toUpperCase())}};var Fe=class{name;relativeSignalsPath;commands;parameters};import{deepValue as U,setDeepValue as He,sleep as Mt}from"@node-projects/web-component-designer/dist/elements/helper/Helper.js";import ae from"long";var fe="cyclic",Wt={pointerdown:"pointerup",pointerenter:"pointerleave",mouseenter:"mouseleave",mouseover:"mouseout",focus:"blur",focusin:"focusout",keydown:"keyup"},Je=class{_visualizationHandler;_subscriptionCallback=()=>{};constructor(o){this._visualizationHandler=o}async execute(o,e){let t=-1,i=!1,s=!1,l=e.event?.type,r=l?Wt[l]:null;if(r){let n=e.element;l=="pointerdown"&&(n=window),n.addEventListener(r,()=>{i=!0},{once:!0})}for(let n=0;n<o.length;n++){let a=o[n];if(a.type=="Exit"){s=!0;break}else if(a.type=="If"){let p=(await this.evaluateIfFormula(a,e)?a.trueCommands:a.elseCommands)??[];if(!await this.execute(p,e)){s=!0;break}}else if(a.type=="Goto"){let c=await this.getValue(a.label,e);if(n=o.findIndex(p=>p.type=="Label"&&p.label==c),n<0)break}else if(a.type=="Condition"){let c=await this.getValue(a.value1,e),p=await this.getValue(a.value2,e),d=await this.getValue(a.comparisonType,e),g=!1;switch(d){case"==null":g=c==null;break;case"!=null":g=c!=null;break;case"==true":g=c==!0;break;case"==false":g=c==!1;break;case"==":g=c==p;break;case"!=":g=c!=p;break;case">":g=c>p;break;case"<":g=c<p;break;case">=":g=c>=p;break;case"<=":g=c<=p;break;case"&&":g=c&&p;break;case"||":g=c||p;break}if(g){await this.runExternalScript(await this.getValue(a.trueScriptName,e),await this.getValue(a.trueScriptType,e));let u=await this.getValue(a.trueGotoLabel,e);if(u&&(n=o.findIndex(m=>m.type=="Label"&&m.label==u),n<0))break}else{await this.runExternalScript(await this.getValue(a.falseScriptName,e),await this.getValue(a.falseScriptType,e));let u=await this.getValue(a.falseGotoLabel,e);if(u&&(n=o.findIndex(m=>m.type=="Label"&&m.label==u),n<0))break}}else if(a.type=="Repeat"){let c=await this.getValue(a.label,e),p=await this.getValue(a.count,e);if(await this.getValue(a.mode,e)=="eventValid"&&i){i=!1;continue}if(p!=0&&t==-1&&(t=p-1),t==0||(t>0&&t--,n=-1,c&&(n=o.findIndex(g=>g.type=="Label"&&g.label==c),n<0)))continue}else if(!await this.runScriptCommand(a,e)){s=!0;break}}return!s}async getValueFromTarget(o,e,t){return o==="property"?U(t.root,e):o==="elementProperty"?U(t.element,e):(await this._visualizationHandler.getState(this.getSignalName(e,t)))?.val}async setValueOnTarget(o,e,t,i){o==="property"?He(t.root,e,i):o==="elementProperty"?He(t.element,e,i):await this._visualizationHandler.setState(this.getSignalName(e,t),i)}async runExternalScript(o,e){}async runScriptCommand(command,context){switch(command.type){case"Comment":case"Label":case"Condition":case"If":case"Goto":case"Exit":case"Repeat":break;case"OpenUrl":{window.open(await this.getValue(command.url,context),command.target);break}case"Delay":{let o=await this.getValue(command.value??500,context);await Mt(o);break}case"Console":{let o=await this.getValue(command.target??"log",context),e=await this.getValue(command.message,context);console[o](e);break}case"ToggleSignalValue":{let o=await this.getValue(command.signal,context),e=await this.getValue(command.target,context),t=await this.getValueFromTarget(e,o,context);await this._visualizationHandler.setState(this.getSignalName(o,context),!t);break}case"ToggleSignalValueThroughList":{let o=await this.getValue(command.valueList,context),e=await this.getValue(command.signal,context),t=await this.getValue(command.target,context),i=await this.getValueFromTarget(t,e,context),s=o.indexOf(i)+1;s>=o.length&&(s=0);let l=o[s];await this._visualizationHandler.setState(this.getSignalName(e,context),l);break}case"SetSignalValue":{let o=await this.getValue(command.signal,context),e=await this.getValue(command.target,context);await this.setValueOnTarget(e,o,context,await this.getValue(command.value,context));break}case"IncrementSignalValue":{let o=await this.getValue(command.signal,context),e=await this.getValue(command.target,context),i=await this.getValueFromTarget(e,o,context)+await this.getValue(command.value,context);await this.setValueOnTarget(e,o,context,i);break}case"DecrementSignalValue":{let o=await this.getValue(command.signal,context),e=await this.getValue(command.target,context),i=await this.getValueFromTarget(e,o,context)-await this.getValue(command.value,context);await this.setValueOnTarget(e,o,context,i);break}case"CalculateSignalValue":{let formula=await this.getValue(command.formula,context),target=await this.getValue(command.target,context),targetSignal=await this.getValue(command.targetSignal,context),nm=await this.parseStringWithValues(formula,context),result=eval(nm);await this.setValueOnTarget(target,targetSignal,context,result);break}case"SetBitInSignal":{let o=await this.getValue(command.signal,context),e=await this.getValue(command.bitNumber??0,context),t=await this.getValue(command.target,context),i=await this.getValueFromTarget(t,o,context),s=ae.fromNumber(1).shiftLeft(e),l=ae.fromNumber(i).or(s).toNumber();await this.setValueOnTarget(t,o,context,l);break}case"ClearBitInSignal":{let o=await this.getValue(command.signal,context),e=await this.getValue(command.bitNumber??0,context),t=await this.getValue(command.target,context),i=await this.getValueFromTarget(t,o,context),s=ae.fromNumber(1).shiftLeft(e);s.negate();let l=ae.fromNumber(i).and(s).toNumber();await this.setValueOnTarget(t,o,context,l);break}case"ToggleBitInSignal":{let o=await this.getValue(command.signal,context),e=await this.getValue(command.bitNumber??0,context),t=await this.getValue(command.target,context),i=await this.getValueFromTarget(t,o,context),s=ae.fromNumber(1).shiftLeft(e),l=ae.fromNumber(i).xor(s).toNumber();await this.setValueOnTarget(t,o,context,l);break}case"Javascript":{let o=await this.getValue(command.script,context),e=context;e.shadowRoot=context.element.getRootNode(),e.instance=context.shadowRoot.host,command.compiledScript||(command.compiledScript=new Function("context",o)),command.compiledScript(e);break}case"SetElementProperty":{command=Q.upgradeSetElementProperty(command);let o=await this.getValue(command.name,context);o===""&&(o=null);let e=await this.getValue(command.value,context),t=await this.getValue(command.parentIndex??0,context),i=await this.getValue(command.target??"property",context),s=await this.getValue(command.targetSelectorTarget??"container",context),l=await this.getValue(command.targetSelector,context),r=await this.getValue(command.mode??"toggle",context),n=this.getTargetFromTargetSelector(context,s,t,l);for(let a of n)i=="attribute"?a.setAttribute(o,e):i=="property"?a[o]=e:i=="css"?a.style[o]=e:i=="class"&&(r==="toggle"?a.classList.toggle(o??e):r==="remove"?a.classList.remove(o??e):a.classList.add(o??e));break}case"SubscribeSignal":{let o=await this.getValue(command.signal,context);if(await this.getValue(command.oneTime,context)){let t=()=>{this._visualizationHandler.unsubscribeState(o,t,null)};this._visualizationHandler.subscribeState(o,t)}else this._visualizationHandler.subscribeState(o,this._subscriptionCallback);break}case"UnsubscribeSignal":{let o=await this.getValue(command.signal,context);this._visualizationHandler.unsubscribeState(o,this._subscriptionCallback,null);break}case"WriteSignalsInGroup":{let o=await this.getValue(command.group,context);this._visualizationHandler.writeSignalsInGroup(o);break}case"ClearSignalsInGroup":{let o=await this.getValue(command.group,context);this._visualizationHandler.clearSignalsInGroup(o);break}case"RunScript":{let o=await this.getValue(command.name,context),e=await this.getValue(command.scriptType,context);this.runExternalScript(o,e);break}case"ShowMessageBox":{let o=null,e=await this.getValue(command.exitScriptOnCancel,context);if(await this.getValue(command.buttons,context)=="yesNo"){let s=await this.getValue(command.message,context);confirm(s)?o=1:o=2}else{let s=await this.getValue(command.message,context);alert(s),o=1}let i=await this.getValue(command.resultSignal,context);if(i&&this._visualizationHandler.setState(i,o),e&&o!=1)return!1;break}case"ShowPrompt":{let o=await this.getValue(command.message,context),e=await this.getValue(command.default,context),t=prompt(o,e),i=await this.getValue(command.resultSignal,context);i&&t&&this._visualizationHandler.setState(i,t);break}case"Login":case"Logout":case"CloseDialog":case"OpenDialog":case"OpenScreen":case"SwitchLanguage":case"CopySignalValuesFromFolder":case"ExportSignalValuesAsJson":case"ImportSignalValuesFromJson":{alert('command: "'+command.type+'" is not yet implemented');break}}return!0}getTarget(o,e,t){if(e==="container"){let i=o.element.getRootNode().host;for(let s=0;s<(t??0);s++)i=i.getRootNode().host;return i}else if(e==="element"){let i=o.element;for(let s=0;s<(t??0);s++)i=i.parentElement;return i}return null}getTargetFromTargetSelector(o,e,t,i){let s=this.getTarget(o,e,t),l=[s];return i&&(e==="container"?l=s.shadowRoot.querySelectorAll(i):l=s.querySelectorAll(i)),l}async getValue(value,outerContext){if(value==null)return null;if(typeof value=="object")switch(value.source){case"property":return U(outerContext.root,value.name);case"elementProperty":return U(outerContext.element,value.name);case"signal":return(await this._visualizationHandler.getState(this.getSignalName(value.name,outerContext)))?.val;case"signalInProperty":{let o=U(outerContext.root,value.name);return(await this._visualizationHandler.getState(this.getSignalName(o,outerContext)))?.val}case"event":{let o=outerContext.event;return value.name&&(o=U(o,value.name)),o}case"parameter":return outerContext.parameters[value.name];case"context":return U(outerContext,value.name);case"complexString":{let o=value.name;return o!=null?await this.parseStringWithValues(o,outerContext):null}case"complexSignal":{let o=value.name;if(o!=null){let e=await this.parseStringWithValues(o,outerContext);return(await this._visualizationHandler.getState(this.getSignalName(e,outerContext)))?.val}return null}case"expression":{var ctx=outerContext;return eval(value.name)}}return value}async getStateOrFieldOrParameter(name,context){if(name[0]==="\xA7"){var ctx=context;return eval("ctx."+name.substring(1))}else{if(name[0]==="?"&&name[1]==="?")return context.root[name.substring(2)];if(name[0]==="?")return await this._visualizationHandler.getState(this.getSignalName(context.root[name.substring(1)],context))}return await this._visualizationHandler.getState(this.getSignalName(name,context))}async parseStringWithValues(o,e){let t=_e(o),i=await Promise.all(t.signals.map(l=>this.getStateOrFieldOrParameter(this.getSignalName(l,e),e))),s=t.parts[0];for(let l=0;l<t.parts.length-1;l++){let r=i[l];typeof r=="object"&&(r=r.val),r==null&&(r=""),s+=r+t.parts[l+1]}return s}async evaluateIfFormula(o,e){let t=o.signals??[],i=t.map((r,n)=>r.varName?.trim()||"__"+n),s=await Promise.all(t.map(r=>this.getValue(r,e))),l=await this.getValue(o.formula,e);return(!o.compiledFormula||o._compiledFormulaSrc!==l)&&(o.compiledFormula=new Function(...i,"return ("+l+");"),o._compiledFormulaSrc=l),!!o.compiledFormula(...s)}getSignalName(o,e){return o[0]==="."?e.relativeSignalsPath+o:o}createScriptContext(o,e,t,i,s){return{root:o,event:e,element:t,parameters:i,relativeSignalsPath:s}}async assignAllScripts(o,e,t,i,s,l,r,n){l??=this.createScriptContext;let a=await this.loadAndInitJsObject(o,e,t,i,n);for(let c of t.querySelectorAll("*"))for(let p of c.attributes)if(p.name[0]==="@")try{let d=p.name.substring(1),g=p.value.trim(),u=d.startsWith(fe),m=u?parseInt(d.substring(d.indexOf(":")+1)):null,y=await this.resolveHandler(g,a,c,t,i,s,l,r,d);y&&this.bindHandler(c,d,u,m,y)}catch{console.warn("error assigning script",c,p)}return a}async loadAndInitJsObject(o,e,t,i,s){if(!e)return null;try{let r=await import(URL.createObjectURL(new Blob([e],{type:"application/javascript"})));return s?s(r):r.init?.(i,t),r}catch(l){return console.error("error parsing javascript - "+o,l),null}}async resolveHandler(o,e,t,i,s,l,r,n,a){if(o[0]!=="{")return p=>{e?.[o]?e[o](p,t,i,s):console.warn(`javascript function named: "${o}" not found, maybe missing a "export" ?`)};let c=JSON.parse(o);if("commands"in c)return p=>this.execute(c.commands,r(s,p,t,c.parameters,c.relativeSignalsPath));if("blocks"in c){let p=null;return async d=>{p??=await ke(c),p(d,i,c.parameters,c.relativeSignalsPath??"",l,r(s,d,t,c.parameters,c.relativeSignalsPath))}}if("name"in c){if(n)return n(t,a,c),null;let p=c.name;return d=>{e?.[p]?e[p](d,t,i,s,c.parameters):console.warn(`javascript function named: "${p}" not found, maybe missing a "export" ?`)}}return null}bindHandler(o,e,t,i,s){if(!t){o.addEventListener(e,s);return}let l=setInterval(()=>{o.isConnected?s(null):clearInterval(l)},i)}};import{OverlayLayer as Ft,DesignItem as $,InsertAction as Ht,BindingTarget as j,PropertyType as ye}from"@node-projects/web-component-designer";var Ue=class{constructor(e,t){this._bindingsHelper=e,this._visualizationHandler=t}_bindingsHelper;_visualizationHandler;rectMap=new Map;rect;dragEnter(e,t,i){let s=$.GetDesignItem(i);if(s&&!s.isRootItem){let l=e.getNormalizedElementCoordinates(i);this.rect=e.overlayLayer.drawRect("IobrokerWebuiBindableObjectDragDropService",l.x,l.y,l.width,l.height,"",null,Ft.Background),this.rect.style.fill="#ff0000",this.rect.style.opacity="0.3",this.rectMap.set(i,this.rect)}}dragLeave(e,t,i){let s=$.GetDesignItem(i);if(s&&!s.isRootItem){let l=this.rectMap.get(i);e.overlayLayer.removeOverlay(l),this.rectMap.delete(i)}}dragOver(e,t,i){return"copy"}async drop(e,t,i,s){for(let a of this.rectMap.values())e.overlayLayer.removeOverlay(a);this.rectMap.clear();let l=$.GetDesignItem(s),r=await this._visualizationHandler.getObject(i.fullName),n=this._visualizationHandler.getSignalInformation(r);if(l&&!l.isRootItem)if(s instanceof HTMLInputElement){let a={signal:i.fullName,target:j.property},c=this._bindingsHelper.serializeBinding(s,s.type=="checkbox"?"checked":"value",a);l.setAttribute(c[0],c[1])}else{let a={signal:i.fullName,target:j.content},c=this._bindingsHelper.serializeBinding(s,null,a);l.setAttribute(c[0],c[1])}else{let a=e.getNormalizedEventCoordinates(t),c,p,d=await this._visualizationHandler.getState(i.fullName);if(n.role==="url"&&typeof d?.val=="string")if(d.val.endsWith("jpg")||d.val.endsWith("jpeg")||d.val.endsWith("png")||d.val.endsWith("gif")||d.val.endsWith("svg")){let g=document.createElement("img");c=$.createDesignItemFromInstance(g,e.serviceContainer,e.instanceServiceContainer),p=c.openGroup("Insert");let u={signal:i.fullName,target:j.property},m=this._bindingsHelper.serializeBinding(g,"src",u);c.setAttribute(m[0],m[1]),c.element.src=d.val}else if(d.val.endsWith("mp4")){let g=document.createElement("video");c=$.createDesignItemFromInstance(g,e.serviceContainer,e.instanceServiceContainer),p=c.openGroup("Insert");let u={signal:i.fullName,target:j.property},m=this._bindingsHelper.serializeBinding(g,"src",u);c.setAttribute(m[0],m[1]),c.element.src=d.val}else{let g=document.createElement("iframe");c=$.createDesignItemFromInstance(g,e.serviceContainer,e.instanceServiceContainer),p=c.openGroup("Insert");let u={signal:i.fullName,target:j.property},m=this._bindingsHelper.serializeBinding(g,"src",u);c.setAttribute(m[0],m[1]),c.element.src=d.val}if(!c){let g=document.createElement("input");c=$.createDesignItemFromInstance(g,e.serviceContainer,e.instanceServiceContainer),p=c.openGroup("Insert");let u=n.writeable!==!1,m={signal:i.fullName,target:j.property,twoWay:u},y=this._bindingsHelper.serializeBinding(g,"value",m);n.type==="boolean"?(y=this._bindingsHelper.serializeBinding(g,"checked",m),c.setAttribute("type","checkbox")):n.role=="date"?(m.twoWay=u,y=this._bindingsHelper.serializeBinding(g,"value-as-number",m),c.setAttribute("type","date"),c.setAttribute("readonly","")):n.role=="datetime"&&(m.twoWay=u,y=this._bindingsHelper.serializeBinding(g,"value-as-number",m),c.setAttribute("type","datetime-local"),c.setAttribute("readonly","")),c.setAttribute(y[0],y[1])}c.setStyle("position","absolute"),c.setStyle("left",a.x+"px"),c.setStyle("top",a.y+"px"),e.instanceServiceContainer.undoService.execute(new Ht(e.rootDesignItem,e.rootDesignItem.childCount,c)),p.commit(),requestAnimationFrame(()=>e.instanceServiceContainer.selectionService.setSelectedElements([c]))}}dragOverOnProperty(e,t,i){return"copy"}dropOnProperty(e,t,i,s){if(t.type=="signal"){t.service.setValue(s,t,i.fullName);return}let l={signal:i.fullName,target:j.property};t.propertyType==ye.attribute&&(l.target=j.attribute),t.propertyType==ye.cssValue&&(l.target=j.css),l.signal=i.fullName,l.twoWay=t.propertyType==ye.property||t.propertyType==ye.propertyAndAttribute;let r=s[0].openGroup("drop binding");for(let n of s){let a=this._bindingsHelper.serializeBinding(n.element,t.name,l);n.setAttribute(a[0],a[1])}r.commit()}};import{BindingMode as Se,BindingTarget as $e,PropertiesHelper as Jt}from"@node-projects/web-component-designer";var Ge=class o{constructor(e){this._bindingsHelper=e}_bindingsHelper;static type="visualization-binding";getBindings(e){return Array.from(this._bindingsHelper.getBindings(e.element)).map(i=>({targetName:i[1].target===$e.css||i[1].target===$e.attribute?Jt.camelToDashCase(i[0]):i[0],target:i[1].target,mode:i[1].twoWay?Se.twoWay:Se.oneWay,invert:i[1].inverted,bindableObjectNames:i[1].signal.split(";"),expression:i[1].expression,expressionTwoWay:i[1].expressionTwoWay,converter:i[1].converter,type:o.type,service:this,changedEvents:i[1].events,historic:i[1].historic,writeBackSignal:i[1].writeBackSignal}))}setBinding(e,t){let i={signal:t.bindableObjectNames.join(";"),target:t.target};i.inverted=t.invert,i.twoWay=t.mode==Se.twoWay,i.expression=t.expression,i.expressionTwoWay=t.expressionTwoWay,i.historic=t.historic,i.type=t.type,typeof t.converters=="string"?i.converter=t.converters:Array.isArray(t.converters)&&t.converters.length>0?i.converter=Object.fromEntries(t.converters.map(r=>[r.key,r.value])):t.converters!=null&&(i.converter=t.converters),i.target=t.target,i.events=t.changedEvents;let s=this._bindingsHelper.serializeBinding(e.element,t.targetName,i),l=e.openGroup("edit_binding");return e.setAttribute(s[0],s[1]),l.commit(),!0}clearBinding(e,t,i){let s=this._bindingsHelper.getBindingAttributeName(e.element,t,i);return e.removeAttribute(s),!0}};var Ut=[{prefix:"?@",itemType:"attribute"},{prefix:"#@",itemType:"attribute"},{prefix:"?$",itemType:"signalObject"},{prefix:"#$",itemType:"signalObject"},{prefix:"??",itemType:"property"},{prefix:"##",itemType:"property"},{prefix:"?",itemType:"property"},{prefix:"#",itemType:"property"}];function qe(o){let e=Ut.find(t=>o.startsWith(t.prefix));return e?{name:o.substring(e.prefix.length),...e}:{name:o,prefix:"",itemType:"signal"}}var Xe=class{getRefactorings(e){let t=[];for(let i of e){let s=i.serviceContainer.bindingService.getBindings(i);if(s)for(let l of s)for(let r of l.bindableObjectNames)if(r.includes(":")){let n=r.split(":")[0],a=qe(r.substring(n.length+1));t.push({service:this,name:a.name,itemType:a.itemType,designItem:i,type:"binding",sourceObject:l,display:l.target+"/"+l.targetName+" - "+n+":",shortName:n,prefix:a.prefix})}else{let n=qe(r);t.push({service:this,name:n.name,itemType:n.itemType,designItem:i,type:"binding",sourceObject:l,display:l.target+"/"+l.targetName,prefix:n.prefix})}}return t}refactor(e,t,i){let s=e.sourceObject;e.shortName?s.bindableObjectNames=s.bindableObjectNames.map(l=>l==e.shortName+":"+e.prefix+t?e.shortName+":"+e.prefix+i:l):s.bindableObjectNames=s.bindableObjectNames.map(l=>l==e.prefix+t?e.prefix+i:l),e.designItem.serviceContainer.bindingService.setBinding(e.designItem,s)}};var Ye=class{dragOverOnProperty(e,t,i){return"copy"}dropOnProperty(e,t,i,s){t.service.setValue(s,t,i.text)}};import{BindingTarget as T}from"@node-projects/web-component-designer";var Ke=class{getRefactorings(e){let t=[];for(let i of e)for(let s of i.attributes())if(s[0][0]=="@"){let l=s[1];if(l[0]=="{"){let r=JSON.parse(l);if("commands"in r)for(let n of r.commands){for(let a in n){let c=n[a];if(c!=null&&typeof c=="object"){let p=c;if(p.source==="signal")t.push({name:p.name,itemType:"signal",target:T.event,targetName:s[0],service:this,designItem:i,type:"script",sourceObject:r,display:n.type+"/"+s[0].substring(1)+"/"+a+"[signal]",refactor:d=>p.name=d});else if(p.source==="property")t.push({name:p.name,itemType:"property",target:T.event,targetName:s[0],service:this,designItem:i,type:"script",sourceObject:r,display:n.type+"/"+s[0].substring(1)+"/"+a+"[property]",refactor:d=>p.name=d});else if(p.source==="complexString")for(let d of p.name.matchAll(/\{(.*?)\}/g)){let g=d[0],u=d[1];if(u[0]==="?"){let m="?";u=u.substring(1),u[0]==="?"&&(m="??",u=u.substring(1)),t.push({name:u,itemType:"property",target:T.event,targetName:s[0],service:this,designItem:i,type:"script",sourceObject:r,display:n.type+"/"+s[0].substring(1)+"/"+a+"[complexString]->property",refactor:y=>p.name=p.name.replace(g,"{"+m+y+"}")})}else t.push({name:u,itemType:"signal",target:T.event,targetName:s[0],service:this,designItem:i,type:"script",sourceObject:r,display:n.type+"/"+s[0].substring(1)+"/"+a+"[complexString]->signal",refactor:m=>p.name=p.name.replace(g,"{"+m+"}")})}}}switch(n.type){case"SetSignalValue":n.signal&&typeof n.signal=="string"&&t.push({name:n.signal,itemType:"signal",target:T.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/signal",service:this,designItem:i,type:"script",sourceObject:r,refactor:a=>n.signal=a});break;case"ToggleSignalValue":n.signal&&typeof n.signal=="string"&&t.push({name:n.signal,itemType:"signal",target:T.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/signal",service:this,designItem:i,type:"script",sourceObject:r,refactor:a=>n.signal=a});break;case"IncrementSignalValue":n.signal&&typeof n.signal=="string"&&t.push({name:n.signal,itemType:"signal",target:T.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/signal",service:this,designItem:i,type:"script",sourceObject:r,refactor:a=>n.signal=a});break;case"DecrementSignalValue":n.signal&&typeof n.signal=="string"&&t.push({name:n.signal,itemType:"signal",target:T.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/signal",service:this,designItem:i,type:"script",sourceObject:r,refactor:a=>n.signal=a});break;case"SetBitInSignal":n.signal&&typeof n.signal=="string"&&t.push({name:n.signal,itemType:"signal",target:T.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/signal",service:this,designItem:i,type:"script",sourceObject:r,refactor:a=>n.signal=a});break;case"ClearBitInSignal":n.signal&&typeof n.signal=="string"&&t.push({name:n.signal,itemType:"signal",target:T.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/signal",service:this,designItem:i,type:"script",sourceObject:r,refactor:a=>n.signal=a});break;case"ToggleBitInSignal":n.signal&&typeof n.signal=="string"&&t.push({name:n.signal,itemType:"signal",target:T.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/signal",service:this,designItem:i,type:"script",sourceObject:r,refactor:a=>n.signal=a});break;case"OpenScreen":n.screen&&typeof n.screen=="string"&&t.push({name:n.screen,itemType:"screen",target:T.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/screen",service:this,designItem:i,type:"script",sourceObject:r,refactor:a=>n.screen=a});break;case"OpenDialog":n.screen&&typeof n.screen=="string"&&t.push({name:n.screen,itemType:"screen",target:T.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/screen",service:this,designItem:i,type:"script",sourceObject:r,refactor:a=>n.screen=a});break;case"CalculateSignalValue":n.targetSignal&&typeof n.targetSignal=="string"&&t.push({name:n.targetSignal,itemType:"signal",target:T.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/targetSignal",service:this,designItem:i,type:"script",sourceObject:r,refactor:a=>n.targetSignal=a});break;case"SubscribeSignal":n.signal&&typeof n.signal=="string"&&t.push({name:n.signal,itemType:"signal",target:T.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/signal",service:this,designItem:i,type:"script",sourceObject:r,refactor:a=>n.signal=a});break;case"UnsubscribeSignal":n.signal&&typeof n.signal=="string"&&t.push({name:n.signal,itemType:"signal",target:T.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/signal",service:this,designItem:i,type:"script",sourceObject:r,refactor:a=>n.signal=a});break;case"ShowMessageBox":n.resultSignal&&typeof n.resultSignal=="string"&&t.push({name:n.resultSignal,itemType:"signal",target:T.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/resultSignal",service:this,designItem:i,type:"script",sourceObject:r,refactor:a=>n.resultSignal=a});break}}else"blocks"in r;if("parameters"in r)for(let n in r.parameters)typeof r.parameters[n]=="string"&&t.push({name:r.parameters[n],itemType:"parameter",target:T.event,targetName:s[0],service:this,designItem:i,type:"script",sourceObject:r,display:s[0].substring(1)+"/parameters/"+n,refactor:a=>r.parameters[n]=a})}}return t}refactor(e,t,i){e.refactor(i);let s=JSON.stringify(e.sourceObject);e.designItem.setAttribute(e.targetName,s)}};import{BasePropertyEditor as $t}from"@node-projects/web-component-designer";var Ze=class extends $t{_ip;_container;constructor(e,t){super(e),this._container=document.createElement("div"),this._container.style.display="flex",this._ip=document.createElement("input"),this._ip.onchange=s=>this._valueChanged(this._ip.value),this._ip.onfocus=s=>{this._ip.selectionStart=0,this._ip.selectionEnd=this._ip.value?.length},this._container.appendChild(this._ip);let i=document.createElement("button");i.textContent="...",i.onclick=async()=>{let s=t.createBindableObjectBrowser();s.initialize(this.designItems[0].serviceContainer,this.designItems[0].instanceServiceContainer,"property"),s.title="select signal...";let l=new AbortController;s.objectDoubleclicked.on(()=>{l.abort(),this._ip.value=s.selectedObject.fullName,this._valueChanged(this._ip.value)}),await t.openConfirmation(s,{x:100,y:100,width:400,height:300,abortSignal:l.signal})&&(this._ip.value=s.selectedObject.fullName,this._valueChanged(this._ip.value))},this._container.appendChild(i),this.element=this._container}refreshValue(e,t){t==null?this._ip.value="":this._ip.value=t}};import{EventsService as Gt}from"@node-projects/web-component-designer";var Qe=class o extends Gt{static _cyclicEvent=[{name:`${fe}:100`,propertyName:void 0,eventObjectName:"Event",description:"this event will retrigger itself every 100 ms"}];getPossibleEvents(e){let t=super.getPossibleEvents(e);return t.push(...o._cyclicEvent),t}getEvent(e,t){return t.includes(fe)?o._cyclicEvent.find(s=>s.name==t)??{name:t,propertyName:"on"+t,eventObjectName:"Event"}:super.getEvent(e,t)}};export{Ue as BindableObjectDragDropService,he as BindingsEditor,K as BindingsEditorHistoric,Pe as BindingsHelper,Y as BlocklyScriptEditor,me as EventAssignment,ie as ParameterEditor,Ye as PropertyGridDragDropService,Fe as Script,Ke as ScriptRefactorService,Je as ScriptSystem,Ze as SignalPropertyEditor,Z as SimpleScriptCommandPicker,te as SimpleScriptEditor,Xe as VisualizationBindingsRefactorService,Ge as VisualizationBindingsService,Qe as VisualizationEventsService,re as VisualizationPropertyGrid,le as bindingPrefixAttribute,ce as bindingPrefixClass,J as bindingPrefixContent,pe as bindingPrefixCss,ne as bindingPrefixCssVar,je as bindingPrefixInsideCss,jt as bindingPrefixInsideCssVarName,se as bindingPrefixProperty,xe as bindingPrefixVisible,as as bindingsInCssRegex,fe as cyclicAttributeName,ke as generateEventCodeFromBlockly,Pt as getNestedProperty,de as isLit,Ie as nativeScriptCommandDescriptions,_e as parseBindingString,Oe as simpleScriptEditorHelpHtml};
1297
+ </div>`;static scriptTypeColors={js:"purple",blockly:"yellow",script:"lightgreen",empty:"pink"};static is="node-projects-visualization-event-assignment";constructor(){super(),this._restoreCachedInititalValues()}ready(){this._bindingsParse()}_blocklyToolbox;_instanceServiceContainer;_selectionChangedHandler;_selectedItems;_visualizationHandler;_visualizationShell;_scriptCommandsTypeInfo;_propertiesTypeInfo;_commandDescriptions;events;initialize(e,t,i,s,l,a){this._visualizationHandler=e,this._visualizationShell=t,this._scriptCommandsTypeInfo=i,this._propertiesTypeInfo=s,this._blocklyToolbox=l,this._commandDescriptions=a}set instanceServiceContainer(e){this._instanceServiceContainer=e,this._selectionChangedHandler?.dispose(),this._selectionChangedHandler=this._instanceServiceContainer?.selectionService.onSelectionChanged.on(t=>{this.selectedItems=t.selectedElements}),this.selectedItems=this._instanceServiceContainer?.selectionService.selectedElements??[]}dispose(){this.instanceServiceContainer=null}_createControlsForScript(e){switch(this._getScriptType(e)){case"none":return""}return this.constructor.editRowTemplate.content.cloneNode(!0)}_getScriptName(e){if(this.selectedItems[0].hasAttribute("@"+e.name)){let t=this.selectedItems[0].getAttribute("@"+e.name);if(t[0]==="{"){if(t.includes("name"))return JSON.parse(t).name}else return t}return null}async _changeScriptName(e,t){if(e.key=="Enter"&&this.selectedItems&&this.selectedItems.length&&this.selectedItems[0].hasAttribute("@"+t.name)){let i=e.target.value,s=this.selectedItems[0].getAttribute("@"+t.name);if(s.startsWith("{")){let l=JSON.parse(s);l.name=i,this._selectedItems[0].setAttribute("@"+t.name,JSON.stringify(l))}else this._selectedItems[0].setAttribute("@"+t.name,i)}}_getRelativeSignalsPath(e){if(this.selectedItems[0].hasAttribute("@"+e.name)){let t=this.selectedItems[0].getAttribute("@"+e.name);if(t[0]==="{"&&t.includes("relativeSignalsPath"))return JSON.parse(t).relativeSignalsPath}return null}async _changeRelativeSignalsPath(e,t){if(e.key=="Enter"&&this.selectedItems&&this.selectedItems.length&&this.selectedItems[0].hasAttribute("@"+t.name)){let i=e.target.value,s=this.selectedItems[0].getAttribute("@"+t.name);if(s.startsWith("{")){let l=JSON.parse(s);l.relativeSignalsPath=i,this._selectedItems[0].setAttribute("@"+t.name,JSON.stringify(l))}else{let l={name:s,relativeSignalsPath:i};this._selectedItems[0].setAttribute("@"+t.name,JSON.stringify(l))}}}_hasParameters(e){return this.selectedItems[0].hasAttribute("@"+e.name)?this.selectedItems[0].getAttribute("@"+e.name).includes("parameters"):!1}_getScriptTypeColor(e){let t=this._getScriptType(e);return r.scriptTypeColors[t]??"white"}_getScriptType(e){if(e.designItem.hasAttribute("@"+e.name)){let t=e.designItem.getAttribute("@"+e.name);if(t.startsWith("{")){let i=JSON.parse(t);return"blocks"in i?"blockly":"commands"in i?"script":"js"}else return t==""?"empty":"js"}return"none"}_getEventMethodname(e){return this.selectedItems.length?this.selectedItems[0].getAttribute("@"+e.name):""}_inputMthName(e,t){let i=e.target;this.selectedItems[0].setAttribute("@"+t.name,i.value)}_ctxMenu(e,t){e.preventDefault();let i=this._getScriptType(t);if(i=="empty")this._showContextMenuAssignScript(e,t,!0);else if(i!="none"){let s=[{title:"remove",action:()=>{this.selectedItems[0].removeAttribute("@"+t.name),this._bindingsRefresh()}},{title:"-"},{title:"copy",action:()=>{je(this.selectedItems[0].getAttribute("@"+t.name))}},{title:"paste",action:async()=>{this.selectedItems[0].setAttribute("@"+t.name,await Pe()),this._bindingsRefresh()}}];Le.show(s,e)}else this._showContextMenuAssignScript(e,t,!0)}async _addEvent(e){if(e.key=="Enter"){let t=this._getDomElement("addEventInput");this._selectedItems[0].setAttribute("@"+Wt.camelToDashCase(t.value.replaceAll(" ","-")),""),t.value="",this.scrollTop=0,this.refresh()}}_createAssignScriptContextMenu(e,t){let i=[{title:"Simple Script",action:()=>{this._editEvent("script",e,t)}},{title:"Javascript",action:()=>{let l=prompt("name of function ?");l&&(this._selectedItems[0].setAttribute("@"+t.name,l),this.refresh(),this._editEvent("js",null,t))}},{title:"Blockly",action:()=>{this._editBlockly(null,t)}}],s=this._getScriptType(t);return s!="none"&&(i.push({title:"-"}),i.push({title:"remove",action:()=>{this.selectedItems[0].removeAttribute("@"+t.name),this._bindingsRefresh()}})),s!="empty"&&i.push({title:"-"},{title:"copy",action:()=>{je(this.selectedItems[0].getAttribute("@"+t.name))}},{title:"paste",action:async()=>{this.selectedItems[0].setAttribute("@"+t.name,await Pe()),this._bindingsRefresh()}}),i}async _showContextMenuAssignScript(e,t,i){e.preventDefault();let s=this._getScriptType(t);if(s!="none"&&s!="empty"&&!i)this._editEvent(s,e,t);else{let l=this._createAssignScriptContextMenu(e,t);Le.show(l,e)}}async _editParameter(e,t){let i=new ie,s={};i.title="ParameterEditor for '"+t.name+"' of '"+t.designItem.name+"'";let l=t.designItem.getAttribute("@"+t.name);if(l&&l[0]=="{")try{s=JSON.parse(l).parameters}catch{}if(i.setParametersObject(s),await this._visualizationShell.openConfirmation(i,{x:100,y:100,width:700,height:500})){let n=i.getParametersObject(),o={name:l,parameters:n};l&&l[0]=="{"&&(o=JSON.parse(l),o.parameters=n),n==null&&delete o.parameters;let c=JSON.stringify(o);t.designItem.setAttribute("@"+t.name,c),this._bindingsRefresh()}}async _editBlockly(e,t){let i=new Y(this._blocklyToolbox);i.title="Blockly Script for '"+t.name+"' of '"+t.designItem.name+"'";let s=t.designItem.getAttribute("@"+t.name),l=null,a=null;if(s){let o=JSON.parse(s);l=o.parameters,a=o.relativeSignalsPath,i.load(o)}if(await this._visualizationShell.openConfirmation(i,{x:100,y:100,width:700,height:500})){let o=i.save();l&&(o.parameters=l),a&&(o.relativeSignalsPath=a),t.designItem.setAttribute("@"+t.name,JSON.stringify(o)),this._bindingsRefresh()}}async _editJavascript(e,t){}async _editSimpleScript(e,t){let i=t.designItem.getAttribute("@"+t.name);if(!i||i.startsWith("{")){let s={commands:[]},l=null,a=null;i&&(s=JSON.parse(i),l=s.parameters,a=s.relativeSignalsPath);let n=new te;if(n.serviceContainer=t.designItem.serviceContainer,n.instanceServiceContainer=t.designItem.instanceServiceContainer,n.scriptCommandsTypeInfo=this._scriptCommandsTypeInfo,n.propertiesTypeInfo=this._propertiesTypeInfo,n.visualizationShell=this._visualizationShell,n.visualizationHandler=this._visualizationHandler,this._commandDescriptions&&(n.commandDescriptions={...n.commandDescriptions,...this._commandDescriptions}),n.loadScript(s),n.title="Script '"+t.name+"' on "+t.designItem.name,await this._visualizationShell.openConfirmation(n,{title:n.title,width:600,height:500})){let c=n.getScriptCommands();if(c&&c.length){let p={commands:c};l&&(p.parameters=l),a&&(p.relativeSignalsPath=a);let d=JSON.stringify(p);t.designItem.setAttribute("@"+t.name,d),this._bindingsRefresh()}}}}async _editEvent(e,t,i){e=="js"?this._editJavascript(t,i):e=="blockly"?this._editBlockly(t,i):this._editSimpleScript(t,i)}refresh(){this._selectedItems!=null&&this._selectedItems.length?this.events=this._selectedItems[0].serviceContainer.getLastServiceWhere("eventsService",e=>e.isHandledElementFromEventsService(this._selectedItems[0])).getPossibleEvents(this._selectedItems[0]).map(e=>({...e,designItem:this._selectedItems[0]})):this.events=[],this._bindingsRefresh()}get selectedItems(){return this._selectedItems}set selectedItems(e){this._selectedItems!=e&&(this._selectedItems=e,this.refresh())}};customElements.define(ge.is,ge);import{TypedEvent as Ft,cssFromString as Me}from"@node-projects/base-custom-webcomponent";import{BindingTarget as y}from"@node-projects/web-component-designer/dist/elements/item/BindingTarget.js";import{PropertiesHelper as O}from"@node-projects/web-component-designer/dist/elements/services/propertiesService/services/PropertiesHelper.js";var se="bind-prop:",le="bind-attr:",ce="bind-class:",pe="bind-css:",ne="bind-cssvar:",J="bind-content:",Se="bind-visible:",We="bind(",Ht="--tmpBinding_",bs=/{{(.*)}}/;function de(r){return r.constructor?.elementProperties!=null}function Ce(r){let e=[],t=[],i=0;for(let s=0;s<r.length;s++)r[s]=="{"?(e.push(r.substring(i,s)),i=s+1):r[s]=="}"&&(t.push(r.substring(i,s)),i=s+1);return e.push(r.substring(i)),{parts:e,signals:t}}function He(r,e,t,i){let s=!0,l=0,a=()=>{let o=++l,c=r.valueProvider(e,t);c instanceof Promise?c.then(p=>s&&o===l&&i(p)):s&&i(c)};a(),r.valueChangedCallbacks||(r.valueChangedCallbacks=new Map);let n=r.valueChangedCallbacks.get(e);return n||(n=[],r.valueChangedCallbacks.set(e,n)),n.push(a),()=>{s=!1;let o=n.indexOf(a);o>=0&&n.splice(o,1),n.length===0&&r.valueChangedCallbacks.get(e)===n&&r.valueChangedCallbacks.delete(e)}}function Jt(r,e){let t=e.split("."),i=r;for(let s of t){if(i==null||typeof i!="object")return;i=i[s]}return i}function fe(r,e,t,i,s=!1){let l=s&&t.includes("."),a=l?()=>Jt(e,t):()=>e[t];if(i(a()),l)return()=>{};let n=()=>i(a()),o=r.getChangedEventName(e,t);return e.addEventListener(o,n),()=>e.removeEventListener(o,n)}function Je(r,e,t){t(r.getAttribute(e));let i=new MutationObserver(()=>t(r.getAttribute(e)));return i.observe(r,{attributes:!0,attributeFilter:[e]}),()=>i.disconnect()}var ke=class{bindingsHelper;parts;signals;values;unsubscribeTargetValue;cleanupCalls=[];combinedName;disposed=!1;valueChangedCb;visualizationHandler;element;relativeSignalPath;constructor(e,t,i,s,l,a,n,o){this.bindingsHelper=e,this.visualizationHandler=t,this.valueChangedCb=s,this.element=l,this.relativeSignalPath=a,this.parseIndirectBinding(i),this.values=new Array(this.signals.length);let c=(p,d,h)=>{let u,g=()=>{},f=w=>{let x=w;if(typeof x=="string"&&x[0]==="."&&(x=t.getNormalizedSignalName(x,a,l)),x!==u)if(g(),u=x,typeof x=="string"){let T=(z,P)=>this.handleValueChanged(P.val,h);g=e.subscribeToState(x,T)}else g=()=>{}};this.cleanupCalls.push(fe(e,p,d,f,!0)),this.cleanupCalls.push(()=>g())};try{for(let p=0;p<this.signals.length;p++){let d=this.signals[p];if(d.startsWith("?@")||d.startsWith("#@")){let h=d[0]==="?"?n:l;this.cleanupCalls.push(Je(h,d.substring(2),u=>this.handleValueChanged(u,p)))}else if(d.startsWith("??")||d.startsWith("##")||d.startsWith("?$")||d.startsWith("#$")){let h=d[0]==="?"?n:l;this.cleanupCalls.push(fe(e,h,d.substring(2),u=>this.handleValueChanged(u,p),!0))}else if(d[0]==="\xA7"){let h=d.substring(1);if(!o)throw new Error(`No special value handler registered for "${d}"`);this.cleanupCalls.push(He(o,h,{element:l,relativeSignalPath:a,root:n},u=>this.handleValueChanged(u,p)))}else if(d[0]==="?"||d[0]==="#")c(d[0]==="?"?n:l,d.substring(1),p);else{let h=(u,g)=>this.handleValueChanged(g.val,p);this.cleanupCalls.push(e.subscribeToState(d,h))}}}catch(p){throw this.dispose(),p}}parseIndirectBinding(e){let{parts:t,signals:i}=Ce(e);this.parts=t,this.signals=i;for(let s=0;s<i.length;s++)i[s][0]=="."&&(i[s]=this.visualizationHandler.getNormalizedSignalName(i[s],this.relativeSignalPath,this.element))}handleValueChanged(e,t){if(this.disposed)return;this.values[t]=e;let i=this.parts[0];for(let s=0;s<this.parts.length-1;s++){let l=this.values[s];if(l==null)return;i+=l+this.parts[s+1]}if(i[0]=="."&&(i=this.visualizationHandler.getNormalizedSignalName(i,this.relativeSignalPath,this.element)),this.combinedName!=i&&(this.unsubscribeTargetValue&&this.unsubscribeTargetValue(),!this.disposed)){this.combinedName=i;let s=(l,a)=>this.valueChangedCb(a);this.unsubscribeTargetValue=this.bindingsHelper.subscribeToState(i,s)}}dispose(){this.disposed=!0,this.unsubscribeTargetValue&&(this.unsubscribeTargetValue(),this.unsubscribeTargetValue=null);for(let e of this.cleanupCalls)e();this.cleanupCalls.length=0}setState(e){!this.disposed&&this.combinedName&&this.visualizationHandler.setState(this.combinedName,e)}},Fe=class r{_visualizationHandler;namedConverterCallback;_stateSubscriptions=new Map;_scheduledUpdates=new Set;_updateFlushScheduled=!1;_compiledConverters=new WeakMap;constructor(e){this._visualizationHandler=e}scheduleUpdate(e){this._scheduledUpdates.add(e),!this._updateFlushScheduled&&(this._updateFlushScheduled=!0,queueMicrotask(()=>{this._updateFlushScheduled=!1;let t=[...this._scheduledUpdates];this._scheduledUpdates.clear();for(let i of t)i()}))}getChangedEventName(e,t){let i=t.indexOf("::");if(i>=0)return t.substring(i+2);if(e instanceof HTMLInputElement||e instanceof HTMLSelectElement)return"change";let s=O.camelToDashCase(t);return de(e)?s:s+"-changed"}getParsedTargetName(e,t){return t===y.cssvar||t===y.class?r.dotToCamelCase(e):t===y.attribute?e:O.dashToCamelCase(e)}parseBinding(e,t,i,s,l){let a=t.substring(l.length);if(s===y.cssvar&&(a="--"+a),!i.startsWith("{")){let o={signal:i,target:s};if(i[0]==="="){if(i=i.substring(1),o.signal=i,i.includes("::")){let c=i.split("::");i=c[0],o.signal=i,o.events=c[1].split(",")}o.twoWay=!0,o.events||(o.events=[this.getChangedEventName(e,a)],!(e instanceof HTMLInputElement)&&!(e instanceof HTMLSelectElement)&&!de(e)&&(o.maybeLitElement=!0,o.litEventNames=o.events))}if(i[0]==="!"&&(o.signal=i.substring(1),o.inverted=!0),o.signal.includes(";")){let c=o.signal.split(";");o.expression=c.pop(),o.signal=c.join(";")}return[this.getParsedTargetName(a,s),o]}let n=JSON.parse(i);return n.target=s,n.twoWay&&(n.events==null||n.events.length==0)&&(n.events=[this.getChangedEventName(e,a)]),[this.getParsedTargetName(a,s),n]}serializeBinding(e,t,i){let s={...i};delete s.type,i.twoWay?i.events!=null&&i.events.length==1&&((e instanceof HTMLInputElement||e instanceof HTMLSelectElement)&&i.events?.[0]=="change"||de(e)&&i.events?.[0]==t||!de(e)&&i.events?.[0]==t+"-changed")&&delete s.events:(delete s.events,delete s.expressionTwoWay);let l=s.twoWay&&s.events?.length>0?"::"+s.events.join(","):"",a=l!==""&&!!i.expression?.includes("::")||!!i.expressionTwoWay?.includes("::")||i.signal.trim()[0]=="{",n=i.target==y.property||i.target==y.attribute||i.target==y.class||i.target==y.css||i.target==y.cssvar,o=!a&&n&&!i.expressionTwoWay&&i.converter==null&&!i.historic&&!i.writeBackSignal;if(o&&!i.expression){let c=this.getShortBindingAttributeName(t,i.target,!1),d=((i.target==y.property||i.target==y.attribute)&&i.twoWay?"=":"")+(i.inverted?"!":"")+i.signal+(!i.twoWay&&i.signal.includes(";")?";":"")+l;return[c,d]}if(o&&i.expression&&!i.expression.includes(`
1298
+ `)&&!i.expression.includes(";")){let c=this.getShortBindingAttributeName(t,i.target,!0),d=((i.target==y.attribute||i.target==y.property&&t!="textContent"&&t!="innerHTML")&&i.twoWay?"=":"")+(i.inverted?"!":"")+i.signal+";"+i.expression+l;return[c,d]}return(i.inverted===null||i.inverted===!1)&&delete s.inverted,(i.expression===null||i.expression==="")&&delete s.expression,(i.expressionTwoWay===null||i.expressionTwoWay==="")&&delete s.expressionTwoWay,i.writeBackSignal||delete s.writeBackSignal,(i.twoWay===null||i.twoWay===!1)&&delete s.twoWay,delete s.target,i.historic||delete s.historic,[this.getJsonBindingAttributeName(t,i.target),JSON.stringify(s)]}getShortBindingAttributeName(e,t,i){return t==y.property&&e=="textContent"?J+"text":t==y.property&&e=="innerHTML"?J+"html":t==y.attribute?le+O.camelToDashCase(e):t==y.class?ce+O.camelToDashCase(e):t==y.css?pe+O.camelToDashCase(e):t==y.cssvar?i?ne+O.camelToDashCase(e):ne+r.camelToDotCase(e.substring(2)):se+O.camelToDashCase(e)}getJsonBindingAttributeName(e,t){return t==y.content||t==y.property&&e=="innerHTML"?J+"html":t==y.property&&e=="textContent"?J+"text":t==y.attribute?le+O.camelToDashCase(e):t==y.class?ce+r.camelToDotCase(e):t==y.css?pe+O.camelToDashCase(e):t==y.cssvar?ne+r.camelToDotCase(e.substring(2)):se+O.camelToDashCase(e)}getBindingAttributeName(e,t,i){return i==y.attribute?le+O.camelToDashCase(t):i==y.class?ce+r.camelToDotCase(t):i==y.css?pe+O.camelToDashCase(t):i==y.visible?Se:i==y.cssvar?ne+r.camelToDotCase(t):i==y.property&&t=="innerHTML"?J+"html":i==y.property&&t=="textContent"?J+"text":se+O.camelToDashCase(t)}*getBindings(e){if(e.attributes)for(let t of e.attributes)t.name.startsWith(se)?yield this.parseBinding(e,t.name,t.value,y.property,se):t.name.startsWith(J)?yield this.parseBinding(e,t.name==="bind-content:html"?"bind-prop:inner-h-t-m-l":"bind-prop:text-content",t.value,y.property,se):t.name.startsWith(le)?yield this.parseBinding(e,t.name,t.value,y.attribute,le):t.name.startsWith(ce)?yield this.parseBinding(e,t.name,t.value,y.class,ce):t.name.startsWith(pe)?yield this.parseBinding(e,t.name,t.value,y.css,pe):t.name.startsWith(ne)?yield this.parseBinding(e,t.name,t.value,y.cssvar,ne):t.name.startsWith(Se)&&(yield this.parseBinding(e,t.name,t.value,y.visible,Se))}applyAllBindings(e,t,i,s,l){let a=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT),o=n.nextNode();for(;o;){let c=this.getBindings(o);for(let p of c)try{let d=this.applyBinding(o,p,t,i,s),h=!1,u=()=>{h||(h=!0,d())};if(a.push(u),p[1].maybeLitElement&&o.localName.includes("-")&&!customElements.get(o.localName)){let g=o,f=p;customElements.whenDefined(o.localName).then(()=>{!h&&de(g)&&(h=!0,d(),f[1].events=f[1].litEventNames,a.push(this.applyBinding(g,f,t,i,s)))})}}catch(d){console.warn("error applying binding",o,p,d)}if(l&&l(o)){let p=n.nextSibling();for(;!p&&o;)o=n.parentNode(),p=n.nextSibling();o=p}else o=n.nextNode()}return a}static#e=0;async parseCssBindings(e,t,i,s){if(!e.includes(We))return[Me(e),[]];let l=await import("@node-projects/css-parser"),a=l.parse(e),n=[];for(let c of a.stylesheet.rules)if(c.type===l.CssTypes.rule){for(let p of c.declarations)if(p.type===l.CssTypes.declaration&&p.value.includes(We)){let d=this.parseCssBinding(p.value,t,i,s);p.value=d[0],n.push(...d[1])}}let o=l.stringify(a,{indent:"",compress:!0});return[Me(o),n]}parseCssBinding(e,t,i,s,l){e=e.trim();let a="",n="",o=!1,c="",p=!1,d=null,h=[];for(let u=0;u<e.length;u++){let g=e[u];if(o)if(p)c+=g,p=!1;else if(d&&g==="\\")p=!0;else if(g===d)d=null;else if(d===null&&g===")"){let f=r.#e++,w=Ht+f,x=[w,{signal:c,target:y.cssvar}];c.startsWith("{")&&(x=JSON.parse(c)),h.push(this.applyBinding(t,x,i,s,l)),a+="var("+w+")",o=!1,c=""}else c+=g;else g==="("?(n!=="bind"?(a+=n,a+=g):(o=!0,e[u+1]==="'"||e[u+1]==='"'?(u++,d=e[u]):d=null),n=""):g===" "||g===","||g==="("||g==="+"||g==="-"||g==="*"||g==="/"?(a+=n+g,n=""):n+=g}return[a+n,h]}subscribeToState(e,t){let i=this._stateSubscriptions.get(e);if(i){if(i.callbacks.add(t),i.hasValue){let l=i.value;queueMicrotask(()=>i.callbacks.has(t)&&t(e,l))}}else{i={callbacks:new Set([t]),callback:null,subscriptionResult:null,revision:0,hasValue:!1},i.callback=(l,a)=>{i.revision++,i.hasValue=!0,i.value=a;for(let n of i.callbacks)n(l,a)},this._stateSubscriptions.set(e,i);try{i.subscriptionResult=this._visualizationHandler.subscribeState(e,i.callback);let l=i.revision;this._visualizationHandler.getState(e).then(a=>{this._stateSubscriptions.get(e)===i&&i.revision===l&&i.callback(e,a)})}catch(l){throw this._stateSubscriptions.delete(e),i.subscriptionResult!=null&&this._visualizationHandler.unsubscribeState(e,i.callback,i.subscriptionResult),l}}let s=!0;return()=>{s&&(s=!1,i.callbacks.delete(t),i.callbacks.size===0&&this._stateSubscriptions.get(e)===i&&(this._stateSubscriptions.delete(e),this._visualizationHandler.unsubscribeState(e,i.callback,i.subscriptionResult)))}}applyBinding(e,t,i,s,l){let a=[],n=!0,o=()=>{if(n){n=!1,this._scheduledUpdates.delete(X);for(let m=a.length-1;m>=0;m--)a[m]();a.length=0}},c=m=>a.push(m),p=t[1].signal.split(";"),d=new Array(p.length);for(let m=0;m<p.length;m++){let b=p[m];d[m]="__"+m;let v=b.indexOf(":");v>=0&&(d[m]=b.substring(0,v),b=b.substring(v+1),p[m]=b)}let h=new Array(p.length),u=[...d,"__res","__ctx"];t[1].expression&&!t[1].compiledExpression&&(t[1].compiledExpression=t[1].expression.includes("return ")?new Function(u,t[1].expression):new Function(u,"return "+t[1].expression));let g=this.getCompiledConverter(t[1],u),f={element:e,root:s,boundNames:t[1].signal,boundTargetName:t[0],boundTargetType:t[1].target},w=this.createTargetWriter(e,t),x=t[1].writeBackSignal;x?.[0]==="."&&(x=i+x);let T,z,P,G=!1,q=!1,M=!1,X=()=>{if(M=!1,!n)return;let m=T;t[1].compiledExpression&&(m=t[1].compiledExpression(...h,z,f),z=m),t[1].converter&&(typeof t[1].converter=="string"?m=this.namedConverterCallback(t[1].converter,m,e,t):m=this.applyCompiledConverter(m,g,h,z,f,t[1].converterDefault)),t[1].inverted&&(m=!m),q=!0,!(G&&(m===null||typeof m!="object")&&Object.is(P,m))&&(G=!0,P=m,x&&this._visualizationHandler.setState(x,m,!0),w(m))},I=(m,b,v)=>{n&&(!v&&b===0&&(m=r.parseValueWithType(m,t)),h[b]=m,T=m,!q&&p.length===1?X():M||(M=!0,this.scheduleUpdate(X)))},L=new Array(p.length),oe=(m,b)=>(L[m]=b,()=>{L[m]===b&&(L[m]=null)}),k=(m,b,v)=>{let V=oe(v,S=>m[b]=S),R=fe(this,m,b,S=>I(S,v,!1));return()=>{R(),V()}},N=(m,b,v)=>{let V=oe(v,S=>S==null?m.removeAttribute(b):m.setAttribute(b,S)),R=Je(m,b,S=>I(S,v,!1));return()=>{R(),V()}},E=(m,b)=>{if(m.startsWith("?@")||m.startsWith("#@")){let _=m[0]==="?"?s:e;return _?N(_,m.substring(2),b):()=>{}}if(m.startsWith("?$")||m.startsWith("#$")){let _=m[0]==="?"?s:e;return _?k(_,m.substring(2),b):()=>{}}if(m[0]==="?"||m[0]==="#"){let _=m[0]==="?"?s:e;return _?k(_,m.substring(1),b):()=>{}}if(m[0]==="$"){let _=m.substring(1);_[0]==="."&&(_=this._visualizationHandler.getNormalizedSignalName(_,i,e));let D=!0;return this._visualizationHandler.getObject(_).then(A=>{D&&I(A,b,!0)}),()=>D=!1}if(m[0]==="\xA7"){if(!l)throw new Error(`No special value handler registered for "${m}"`);return He(l,m.substring(1),{element:e,binding:t,relativeSignalPath:i,root:s},_=>I(_,b,!0))}if(m.includes("{")){let _=new ke(this,this._visualizationHandler,m,A=>I(A.val,b,!1),e,i,s,l),D=oe(b,A=>_.setState(A));return()=>{_.dispose(),D()}}let v=m;if(v[0]==="."&&(v=this._visualizationHandler.getNormalizedSignalName(v,i,e)),t[1].historic){let _=t[1].historic;if(_.reloadInterval){let A=!0,W=null,F=async()=>{let at=await this._visualizationHandler.getHistoricData(v,_);!n||!A||(I(at?.values,b,!0),W=setTimeout(F,_.reloadInterval))};return F(),()=>{A=!1,W!==null&&clearTimeout(W),W=null}}let D=!0;return this._visualizationHandler.getHistoricData(v,_).then(A=>{D&&I(A?.values,b,!0)}),()=>D=!1}let V=(_,D)=>I(D?.val,b,!1),R=this.subscribeToState(v,V),S=oe(b,_=>this._visualizationHandler.setState(v,_));return()=>{R(),S()}},B=(m,b)=>{if(m.startsWith("?@")||m.startsWith("#@")||m.startsWith("?$")||m.startsWith("#$"))return E(m,b);let v=m[0];if(v!=="?"&&v!=="#"||m[1]===v)return E(m[1]===v?m.substring(1):m,b);let V=v==="?"?s:e;if(!V)return()=>{};let R=m.substring(1),S=()=>{},_,A=fe(this,V,R,W=>{let F=typeof W=="string"?W:null;F!==_&&(S(),_=F,S=F?E(F,b):()=>{})});return()=>{A(),S()}};try{t[1].twoWay&&c(this.addTwoWayBinding(t,e,m=>L[0]?.(m)));for(let m=0;m<p.length;m++)typeof p[m]=="string"&&c(B(p[m],m))}catch(m){throw o(),m}return o}addTwoWayBinding(e,t,i){e[1].expressionTwoWay&&!e[1].compiledExpressionTwoWay&&(e[1].compiledExpressionTwoWay=e[1].expressionTwoWay.includes("return ")?new Function(["value"],e[1].expressionTwoWay):new Function(["value"],"return "+e[1].expressionTwoWay));let s=[],l=()=>{let a=e[1].target==y.attribute?t.getAttribute(e[0]):t[e[0]];a=r.parseValueWithType(a,e),e[1].compiledExpressionTwoWay&&(a=e[1].compiledExpressionTwoWay(a)),i(a)};for(let a of e[1].events??[]){let n=t[a];if(n instanceof Ft){let o=n.on(l);s.push(()=>o.dispose())}else t.addEventListener(a,l),s.push(()=>t.removeEventListener(a,l))}return()=>{for(let a of s)a();s.length=0}}static parseValueWithType(e,t){if(t[1].type)switch(t[1].type){case"number":return parseFloat(e);case"boolean":return e===!0||e==="true"||!!parseInt(e);case"string":return e?.toString();case"integer":return parseInt(e)}return e}compileConverter(e,t){let i=new Map,s=[],l=a=>{if(typeof a!="string")return{value:a};let n=new Function(t,"return `"+a+"`");return{value:a,evaluate:(o,c,p)=>n(...o,c,p)}};for(let a in e){let n=l(e[a]);if(i.set(a,n),a.startsWith(">=")){let o=parseFloat(a.substring(2));s.push({matches:c=>c>=o,value:n})}else if(a.startsWith("<=")){let o=parseFloat(a.substring(2));s.push({matches:c=>c<=o,value:n})}else if(a[0]===">"){let o=parseFloat(a.substring(1));s.push({matches:c=>c>o,value:n})}else if(a[0]==="<"){let o=parseFloat(a.substring(1));s.push({matches:c=>c<o,value:n})}else{let o=a.split("-");if(o.length>1){let c=o[0]===""?null:parseFloat(o[0]),p=o[1]===""?null:parseFloat(o[1]);s.push({matches:d=>(c===null||d>=c)&&(p===null||p>=d),value:n})}}}return{exactValues:i,conditions:s}}getCompiledConverter(e,t){if(!e.converter||typeof e.converter!="object")return null;let i=t.join("\0"),s=this._compiledConverters.get(e);if(s?.converter===e.converter&&s.argumentsKey===i)return s.compiled;let l=this.compileConverter(e.converter,t);return this._compiledConverters.set(e,{converter:e.converter,argumentsKey:i,compiled:l}),l}applyCompiledConverter(e,t,i,s,l,a){let n=String(e),o=t.exactValues.get(n),c=t.exactValues.has(n);if(!c){let p=parseFloat(e);for(let d of t.conditions)if(d.matches(p)){o=d.value,c=!0;break}}return c?o.evaluate?o.evaluate(i,s,l):o.value:a!==void 0?a:e}createTargetWriter(e,t){let i=t[0];switch(t[1].target){case y.property:return s=>e[i]=s;case y.attribute:return s=>{typeof s=="boolean"?s?e.setAttribute(i,""):e.removeAttribute(i):e.setAttribute(i,s)};case y.css:return s=>e.style[i]=s;case y.cssvar:return s=>e.style.setProperty(i,s);case y.class:return s=>e.classList.toggle(i,!!s);case y.visible:return s=>e.style.visibility=s?"":"collapse";default:return()=>{}}}static camelToDotCase(e){return e.replace(/([A-Z])/g,t=>`.${t[0].toLowerCase()}`)}static dotToCamelCase(e){return e.replace(/\.([a-z])/g,t=>t[1].toUpperCase())}};var Ue=class{name;relativeSignalsPath;commands;parameters};import{deepValue as U,setDeepValue as $e,sleep as Ut}from"@node-projects/web-component-designer/dist/elements/helper/Helper.js";import ae from"long";var ye="cyclic",$t={pointerdown:"pointerup",pointerenter:"pointerleave",mouseenter:"mouseleave",mouseover:"mouseout",focus:"blur",focusin:"focusout",keydown:"keyup"},Ge=class{_visualizationHandler;_subscriptionCallback=()=>{};constructor(r){this._visualizationHandler=r}async execute(r,e){let t=-1,i=!1,s=!1,l=e.event?.type,a=l?$t[l]:null;if(a){let n=e.element;l=="pointerdown"&&(n=window),n.addEventListener(a,()=>{i=!0},{once:!0})}for(let n=0;n<r.length;n++){let o=r[n];if(o.type=="Exit"){s=!0;break}else if(o.type=="If"){let p=(await this.evaluateIfFormula(o,e)?o.trueCommands:o.elseCommands)??[];if(!await this.execute(p,e)){s=!0;break}}else if(o.type=="Goto"){let c=await this.getValue(o.label,e);if(n=r.findIndex(p=>p.type=="Label"&&p.label==c),n<0)break}else if(o.type=="Condition"){let c=await this.getValue(o.value1,e),p=await this.getValue(o.value2,e),d=await this.getValue(o.comparisonType,e),h=!1;switch(d){case"==null":h=c==null;break;case"!=null":h=c!=null;break;case"==true":h=c==!0;break;case"==false":h=c==!1;break;case"==":h=c==p;break;case"!=":h=c!=p;break;case">":h=c>p;break;case"<":h=c<p;break;case">=":h=c>=p;break;case"<=":h=c<=p;break;case"&&":h=c&&p;break;case"||":h=c||p;break}if(h){await this.runExternalScript(await this.getValue(o.trueScriptName,e),await this.getValue(o.trueScriptType,e));let u=await this.getValue(o.trueGotoLabel,e);if(u&&(n=r.findIndex(g=>g.type=="Label"&&g.label==u),n<0))break}else{await this.runExternalScript(await this.getValue(o.falseScriptName,e),await this.getValue(o.falseScriptType,e));let u=await this.getValue(o.falseGotoLabel,e);if(u&&(n=r.findIndex(g=>g.type=="Label"&&g.label==u),n<0))break}}else if(o.type=="Repeat"){let c=await this.getValue(o.label,e),p=await this.getValue(o.count,e);if(await this.getValue(o.mode,e)=="eventValid"&&i){i=!1;continue}if(p!=0&&t==-1&&(t=p-1),t==0||(t>0&&t--,n=-1,c&&(n=r.findIndex(h=>h.type=="Label"&&h.label==c),n<0)))continue}else if(!await this.runScriptCommand(o,e)){s=!0;break}}return!s}async getValueFromTarget(r,e,t){return r==="property"?U(t.root,e):r==="elementProperty"?U(t.element,e):(await this._visualizationHandler.getState(this.getSignalName(e,t)))?.val}async setValueOnTarget(r,e,t,i){r==="property"?$e(t.root,e,i):r==="elementProperty"?$e(t.element,e,i):await this._visualizationHandler.setState(this.getSignalName(e,t),i)}async runExternalScript(r,e){}async runScriptCommand(command,context){switch(command.type){case"Comment":case"Label":case"Condition":case"If":case"Goto":case"Exit":case"Repeat":break;case"OpenUrl":{window.open(await this.getValue(command.url,context),command.target);break}case"Delay":{let r=await this.getValue(command.value??500,context);await Ut(r);break}case"Console":{let r=await this.getValue(command.target??"log",context),e=await this.getValue(command.message,context);console[r](e);break}case"ToggleSignalValue":{let r=await this.getValue(command.signal,context),e=await this.getValue(command.target,context),t=await this.getValueFromTarget(e,r,context);await this._visualizationHandler.setState(this.getSignalName(r,context),!t);break}case"ToggleSignalValueThroughList":{let r=await this.getValue(command.valueList,context),e=await this.getValue(command.signal,context),t=await this.getValue(command.target,context),i=await this.getValueFromTarget(t,e,context),s=r.indexOf(i)+1;s>=r.length&&(s=0);let l=r[s];await this._visualizationHandler.setState(this.getSignalName(e,context),l);break}case"SetSignalValue":{let r=await this.getValue(command.signal,context),e=await this.getValue(command.target,context);await this.setValueOnTarget(e,r,context,await this.getValue(command.value,context));break}case"IncrementSignalValue":{let r=await this.getValue(command.signal,context),e=await this.getValue(command.target,context),i=await this.getValueFromTarget(e,r,context)+await this.getValue(command.value,context);await this.setValueOnTarget(e,r,context,i);break}case"DecrementSignalValue":{let r=await this.getValue(command.signal,context),e=await this.getValue(command.target,context),i=await this.getValueFromTarget(e,r,context)-await this.getValue(command.value,context);await this.setValueOnTarget(e,r,context,i);break}case"CalculateSignalValue":{let formula=await this.getValue(command.formula,context),target=await this.getValue(command.target,context),targetSignal=await this.getValue(command.targetSignal,context),nm=await this.parseStringWithValues(formula,context),result=eval(nm);await this.setValueOnTarget(target,targetSignal,context,result);break}case"SetBitInSignal":{let r=await this.getValue(command.signal,context),e=await this.getValue(command.bitNumber??0,context),t=await this.getValue(command.target,context),i=await this.getValueFromTarget(t,r,context),s=ae.fromNumber(1).shiftLeft(e),l=ae.fromNumber(i).or(s).toNumber();await this.setValueOnTarget(t,r,context,l);break}case"ClearBitInSignal":{let r=await this.getValue(command.signal,context),e=await this.getValue(command.bitNumber??0,context),t=await this.getValue(command.target,context),i=await this.getValueFromTarget(t,r,context),s=ae.fromNumber(1).shiftLeft(e);s.negate();let l=ae.fromNumber(i).and(s).toNumber();await this.setValueOnTarget(t,r,context,l);break}case"ToggleBitInSignal":{let r=await this.getValue(command.signal,context),e=await this.getValue(command.bitNumber??0,context),t=await this.getValue(command.target,context),i=await this.getValueFromTarget(t,r,context),s=ae.fromNumber(1).shiftLeft(e),l=ae.fromNumber(i).xor(s).toNumber();await this.setValueOnTarget(t,r,context,l);break}case"Javascript":{let r=await this.getValue(command.script,context),e=context;e.shadowRoot=context.element.getRootNode(),e.instance=context.shadowRoot.host,command.compiledScript||(command.compiledScript=new Function("context",r)),command.compiledScript(e);break}case"SetElementProperty":{command=Q.upgradeSetElementProperty(command);let r=await this.getValue(command.name,context);r===""&&(r=null);let e=await this.getValue(command.value,context),t=await this.getValue(command.parentIndex??0,context),i=await this.getValue(command.target??"property",context),s=await this.getValue(command.targetSelectorTarget??"container",context),l=await this.getValue(command.targetSelector,context),a=await this.getValue(command.mode??"toggle",context),n=this.getTargetFromTargetSelector(context,s,t,l);for(let o of n)i=="attribute"?o.setAttribute(r,e):i=="property"?o[r]=e:i=="css"?o.style[r]=e:i=="class"&&(a==="toggle"?o.classList.toggle(r??e):a==="remove"?o.classList.remove(r??e):o.classList.add(r??e));break}case"SubscribeSignal":{let r=await this.getValue(command.signal,context);if(await this.getValue(command.oneTime,context)){let t=()=>{this._visualizationHandler.unsubscribeState(r,t,null)};this._visualizationHandler.subscribeState(r,t)}else this._visualizationHandler.subscribeState(r,this._subscriptionCallback);break}case"UnsubscribeSignal":{let r=await this.getValue(command.signal,context);this._visualizationHandler.unsubscribeState(r,this._subscriptionCallback,null);break}case"WriteSignalsInGroup":{let r=await this.getValue(command.group,context);this._visualizationHandler.writeSignalsInGroup(r);break}case"ClearSignalsInGroup":{let r=await this.getValue(command.group,context);this._visualizationHandler.clearSignalsInGroup(r);break}case"RunScript":{let r=await this.getValue(command.name,context),e=await this.getValue(command.scriptType,context);this.runExternalScript(r,e);break}case"ShowMessageBox":{let r=null,e=await this.getValue(command.exitScriptOnCancel,context);if(await this.getValue(command.buttons,context)=="yesNo"){let s=await this.getValue(command.message,context);confirm(s)?r=1:r=2}else{let s=await this.getValue(command.message,context);alert(s),r=1}let i=await this.getValue(command.resultSignal,context);if(i&&this._visualizationHandler.setState(i,r),e&&r!=1)return!1;break}case"ShowPrompt":{let r=await this.getValue(command.message,context),e=await this.getValue(command.default,context),t=prompt(r,e),i=await this.getValue(command.resultSignal,context);i&&t&&this._visualizationHandler.setState(i,t);break}case"Login":case"Logout":case"CloseDialog":case"OpenDialog":case"OpenScreen":case"SwitchLanguage":case"CopySignalValuesFromFolder":case"ExportSignalValuesAsJson":case"ImportSignalValuesFromJson":{alert('command: "'+command.type+'" is not yet implemented');break}}return!0}getTarget(r,e,t){if(e==="container"){let i=r.element.getRootNode().host;for(let s=0;s<(t??0);s++)i=i.getRootNode().host;return i}else if(e==="element"){let i=r.element;for(let s=0;s<(t??0);s++)i=i.parentElement;return i}return null}getTargetFromTargetSelector(r,e,t,i){let s=this.getTarget(r,e,t),l=[s];return i&&(e==="container"?l=s.shadowRoot.querySelectorAll(i):l=s.querySelectorAll(i)),l}async getValue(value,outerContext){if(value==null)return null;if(typeof value=="object")switch(value.source){case"property":return U(outerContext.root,value.name);case"elementProperty":return U(outerContext.element,value.name);case"signal":return(await this._visualizationHandler.getState(this.getSignalName(value.name,outerContext)))?.val;case"signalInProperty":{let r=U(outerContext.root,value.name);return(await this._visualizationHandler.getState(this.getSignalName(r,outerContext)))?.val}case"event":{let r=outerContext.event;return value.name&&(r=U(r,value.name)),r}case"parameter":return outerContext.parameters[value.name];case"context":return U(outerContext,value.name);case"complexString":{let r=value.name;return r!=null?await this.parseStringWithValues(r,outerContext):null}case"complexSignal":{let r=value.name;if(r!=null){let e=await this.parseStringWithValues(r,outerContext);return(await this._visualizationHandler.getState(this.getSignalName(e,outerContext)))?.val}return null}case"expression":{var ctx=outerContext;return eval(value.name)}}return value}async getStateOrFieldOrParameter(name,context){if(name[0]==="\xA7"){var ctx=context;return eval("ctx."+name.substring(1))}else{if(name[0]==="?"&&name[1]==="?")return context.root[name.substring(2)];if(name[0]==="?")return await this._visualizationHandler.getState(this.getSignalName(context.root[name.substring(1)],context))}return await this._visualizationHandler.getState(this.getSignalName(name,context))}async parseStringWithValues(r,e){let t=Ce(r),i=await Promise.all(t.signals.map(l=>this.getStateOrFieldOrParameter(this.getSignalName(l,e),e))),s=t.parts[0];for(let l=0;l<t.parts.length-1;l++){let a=i[l];typeof a=="object"&&(a=a.val),a==null&&(a=""),s+=a+t.parts[l+1]}return s}async evaluateIfFormula(r,e){let t=r.signals??[],i=t.map((a,n)=>a.varName?.trim()||"__"+n),s=await Promise.all(t.map(a=>this.getValue(a,e))),l=await this.getValue(r.formula,e);return(!r.compiledFormula||r._compiledFormulaSrc!==l)&&(r.compiledFormula=new Function(...i,"return ("+l+");"),r._compiledFormulaSrc=l),!!r.compiledFormula(...s)}getSignalName(r,e){return r[0]==="."?e.relativeSignalsPath+r:r}createScriptContext(r,e,t,i,s){return{root:r,event:e,element:t,parameters:i,relativeSignalsPath:s}}async assignAllScripts(r,e,t,i,s,l,a,n){l??=this.createScriptContext;let o=await this.loadAndInitJsObject(r,e,t,i,n);for(let c of t.querySelectorAll("*"))for(let p of c.attributes)if(p.name[0]==="@")try{let d=p.name.substring(1),h=p.value.trim(),u=d.startsWith(ye),g=u?parseInt(d.substring(d.indexOf(":")+1)):null,f=await this.resolveHandler(h,o,c,t,i,s,l,a,d);f&&this.bindHandler(c,d,u,g,f)}catch{console.warn("error assigning script",c,p)}return o}async loadAndInitJsObject(r,e,t,i,s){if(!e)return null;try{let a=await import(URL.createObjectURL(new Blob([e],{type:"application/javascript"})));return s?s(a):a.init?.(i,t),a}catch(l){return console.error("error parsing javascript - "+r,l),null}}async resolveHandler(r,e,t,i,s,l,a,n,o){if(r[0]!=="{")return p=>{e?.[r]?e[r](p,t,i,s):console.warn(`javascript function named: "${r}" not found, maybe missing a "export" ?`)};let c=JSON.parse(r);if("commands"in c)return p=>this.execute(c.commands,a(s,p,t,c.parameters,c.relativeSignalsPath));if("blocks"in c){let p=null;return async d=>{p??=await Ee(c),p(d,i,c.parameters,c.relativeSignalsPath??"",l,a(s,d,t,c.parameters,c.relativeSignalsPath))}}if("name"in c){if(n)return n(t,o,c),null;let p=c.name;return d=>{e?.[p]?e[p](d,t,i,s,c.parameters):console.warn(`javascript function named: "${p}" not found, maybe missing a "export" ?`)}}return null}bindHandler(r,e,t,i,s){if(!t){r.addEventListener(e,s);return}let l=setInterval(()=>{r.isConnected?s(null):clearInterval(l)},i)}};import{OverlayLayer as Gt,DesignItem as $,InsertAction as qt,BindingTarget as j,PropertyType as be}from"@node-projects/web-component-designer";var qe=class{constructor(e,t){this._bindingsHelper=e,this._visualizationHandler=t}_bindingsHelper;_visualizationHandler;rectMap=new Map;rect;dragEnter(e,t,i){let s=$.GetDesignItem(i);if(s&&!s.isRootItem){let l=e.getNormalizedElementCoordinates(i);this.rect=e.overlayLayer.drawRect("IobrokerWebuiBindableObjectDragDropService",l.x,l.y,l.width,l.height,"",null,Gt.Background),this.rect.style.fill="#ff0000",this.rect.style.opacity="0.3",this.rectMap.set(i,this.rect)}}dragLeave(e,t,i){let s=$.GetDesignItem(i);if(s&&!s.isRootItem){let l=this.rectMap.get(i);e.overlayLayer.removeOverlay(l),this.rectMap.delete(i)}}dragOver(e,t,i){return"copy"}async drop(e,t,i,s){for(let o of this.rectMap.values())e.overlayLayer.removeOverlay(o);this.rectMap.clear();let l=$.GetDesignItem(s),a=await this._visualizationHandler.getObject(i.fullName),n=this._visualizationHandler.getSignalInformation(a);if(l&&!l.isRootItem)if(s instanceof HTMLInputElement){let o={signal:i.fullName,target:j.property},c=this._bindingsHelper.serializeBinding(s,s.type=="checkbox"?"checked":"value",o);l.setAttribute(c[0],c[1])}else{let o={signal:i.fullName,target:j.content},c=this._bindingsHelper.serializeBinding(s,null,o);l.setAttribute(c[0],c[1])}else{let o=e.getNormalizedEventCoordinates(t),c,p,d=await this._visualizationHandler.getState(i.fullName);if(n.role==="url"&&typeof d?.val=="string")if(d.val.endsWith("jpg")||d.val.endsWith("jpeg")||d.val.endsWith("png")||d.val.endsWith("gif")||d.val.endsWith("svg")){let h=document.createElement("img");c=$.createDesignItemFromInstance(h,e.serviceContainer,e.instanceServiceContainer),p=c.openGroup("Insert");let u={signal:i.fullName,target:j.property},g=this._bindingsHelper.serializeBinding(h,"src",u);c.setAttribute(g[0],g[1]),c.element.src=d.val}else if(d.val.endsWith("mp4")){let h=document.createElement("video");c=$.createDesignItemFromInstance(h,e.serviceContainer,e.instanceServiceContainer),p=c.openGroup("Insert");let u={signal:i.fullName,target:j.property},g=this._bindingsHelper.serializeBinding(h,"src",u);c.setAttribute(g[0],g[1]),c.element.src=d.val}else{let h=document.createElement("iframe");c=$.createDesignItemFromInstance(h,e.serviceContainer,e.instanceServiceContainer),p=c.openGroup("Insert");let u={signal:i.fullName,target:j.property},g=this._bindingsHelper.serializeBinding(h,"src",u);c.setAttribute(g[0],g[1]),c.element.src=d.val}if(!c){let h=document.createElement("input");c=$.createDesignItemFromInstance(h,e.serviceContainer,e.instanceServiceContainer),p=c.openGroup("Insert");let u=n.writeable!==!1,g={signal:i.fullName,target:j.property,twoWay:u},f=this._bindingsHelper.serializeBinding(h,"value",g);n.type==="boolean"?(f=this._bindingsHelper.serializeBinding(h,"checked",g),c.setAttribute("type","checkbox")):n.role=="date"?(g.twoWay=u,f=this._bindingsHelper.serializeBinding(h,"value-as-number",g),c.setAttribute("type","date"),c.setAttribute("readonly","")):n.role=="datetime"&&(g.twoWay=u,f=this._bindingsHelper.serializeBinding(h,"value-as-number",g),c.setAttribute("type","datetime-local"),c.setAttribute("readonly","")),c.setAttribute(f[0],f[1])}c.setStyle("position","absolute"),c.setStyle("left",o.x+"px"),c.setStyle("top",o.y+"px"),e.instanceServiceContainer.undoService.execute(new qt(e.rootDesignItem,e.rootDesignItem.childCount,c)),p.commit(),requestAnimationFrame(()=>e.instanceServiceContainer.selectionService.setSelectedElements([c]))}}dragOverOnProperty(e,t,i){return"copy"}dropOnProperty(e,t,i,s){if(t.type=="signal"){t.service.setValue(s,t,i.fullName);return}let l={signal:i.fullName,target:j.property};t.propertyType==be.attribute&&(l.target=j.attribute),t.propertyType==be.cssValue&&(l.target=j.css),l.signal=i.fullName,l.twoWay=t.propertyType==be.property||t.propertyType==be.propertyAndAttribute;let a=s[0].openGroup("drop binding");for(let n of s){let o=this._bindingsHelper.serializeBinding(n.element,t.name,l);n.setAttribute(o[0],o[1])}a.commit()}};import{BindingMode as Te,BindingTarget as Xe,PropertiesHelper as Xt}from"@node-projects/web-component-designer";var Ye=class r{constructor(e){this._bindingsHelper=e}_bindingsHelper;static type="visualization-binding";getBindings(e){return Array.from(this._bindingsHelper.getBindings(e.element)).map(i=>({targetName:i[1].target===Xe.css||i[1].target===Xe.attribute?Xt.camelToDashCase(i[0]):i[0],target:i[1].target,mode:i[1].twoWay?Te.twoWay:Te.oneWay,invert:i[1].inverted,bindableObjectNames:i[1].signal.split(";"),expression:i[1].expression,expressionTwoWay:i[1].expressionTwoWay,converter:i[1].converter,converters:i[1].converter,type:r.type,service:this,changedEvents:i[1].events,historic:i[1].historic,writeBackSignal:i[1].writeBackSignal}))}setBinding(e,t){let i={signal:t.bindableObjectNames.join(";"),target:t.target};i.inverted=t.invert,i.twoWay=t.mode==Te.twoWay,i.expression=t.expression,i.expressionTwoWay=t.expressionTwoWay,i.historic=t.historic,i.type=t.type,typeof t.converters=="string"?i.converter=t.converters:Array.isArray(t.converters)&&t.converters.length>0?i.converter=Object.fromEntries(t.converters.map(a=>[a.key,a.value])):t.converters!=null&&(i.converter=t.converters),i.target=t.target,i.events=t.changedEvents,i.writeBackSignal=t.writeBackSignal;let s=this._bindingsHelper.serializeBinding(e.element,t.targetName,i),l=e.openGroup("edit_binding");return e.setAttribute(s[0],s[1]),l.commit(),!0}clearBinding(e,t,i){let s=this._bindingsHelper.getBindingAttributeName(e.element,t,i);return e.removeAttribute(s),!0}};var Yt=[{prefix:"?@",itemType:"attribute"},{prefix:"#@",itemType:"attribute"},{prefix:"?$",itemType:"signalObject"},{prefix:"#$",itemType:"signalObject"},{prefix:"??",itemType:"property"},{prefix:"##",itemType:"property"},{prefix:"?",itemType:"property"},{prefix:"#",itemType:"property"}];function Ke(r){let e=Yt.find(t=>r.startsWith(t.prefix));return e?{name:r.substring(e.prefix.length),...e}:{name:r,prefix:"",itemType:"signal"}}var Ze=class{getRefactorings(e){let t=[];for(let i of e){let s=i.serviceContainer.bindingService.getBindings(i);if(s)for(let l of s)for(let a of l.bindableObjectNames)if(a.includes(":")){let n=a.split(":")[0],o=Ke(a.substring(n.length+1));t.push({service:this,name:o.name,itemType:o.itemType,designItem:i,type:"binding",sourceObject:l,display:l.target+"/"+l.targetName+" - "+n+":",shortName:n,prefix:o.prefix})}else{let n=Ke(a);t.push({service:this,name:n.name,itemType:n.itemType,designItem:i,type:"binding",sourceObject:l,display:l.target+"/"+l.targetName,prefix:n.prefix})}}return t}refactor(e,t,i){let s=e.sourceObject;e.shortName?s.bindableObjectNames=s.bindableObjectNames.map(l=>l==e.shortName+":"+e.prefix+t?e.shortName+":"+e.prefix+i:l):s.bindableObjectNames=s.bindableObjectNames.map(l=>l==e.prefix+t?e.prefix+i:l),e.designItem.serviceContainer.bindingService.setBinding(e.designItem,s)}};var Qe=class{dragOverOnProperty(e,t,i){return"copy"}dropOnProperty(e,t,i,s){t.service.setValue(s,t,i.text)}};import{BindingTarget as C}from"@node-projects/web-component-designer";var et=class{getRefactorings(e){let t=[];for(let i of e)for(let s of i.attributes())if(s[0][0]=="@"){let l=s[1];if(l[0]=="{"){let a=JSON.parse(l);if("commands"in a)for(let n of a.commands){for(let o in n){let c=n[o];if(c!=null&&typeof c=="object"){let p=c;if(p.source==="signal")t.push({name:p.name,itemType:"signal",target:C.event,targetName:s[0],service:this,designItem:i,type:"script",sourceObject:a,display:n.type+"/"+s[0].substring(1)+"/"+o+"[signal]",refactor:d=>p.name=d});else if(p.source==="property")t.push({name:p.name,itemType:"property",target:C.event,targetName:s[0],service:this,designItem:i,type:"script",sourceObject:a,display:n.type+"/"+s[0].substring(1)+"/"+o+"[property]",refactor:d=>p.name=d});else if(p.source==="complexString")for(let d of p.name.matchAll(/\{(.*?)\}/g)){let h=d[0],u=d[1];if(u[0]==="?"){let g="?";u=u.substring(1),u[0]==="?"&&(g="??",u=u.substring(1)),t.push({name:u,itemType:"property",target:C.event,targetName:s[0],service:this,designItem:i,type:"script",sourceObject:a,display:n.type+"/"+s[0].substring(1)+"/"+o+"[complexString]->property",refactor:f=>p.name=p.name.replace(h,"{"+g+f+"}")})}else t.push({name:u,itemType:"signal",target:C.event,targetName:s[0],service:this,designItem:i,type:"script",sourceObject:a,display:n.type+"/"+s[0].substring(1)+"/"+o+"[complexString]->signal",refactor:g=>p.name=p.name.replace(h,"{"+g+"}")})}}}switch(n.type){case"SetSignalValue":n.signal&&typeof n.signal=="string"&&t.push({name:n.signal,itemType:"signal",target:C.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/signal",service:this,designItem:i,type:"script",sourceObject:a,refactor:o=>n.signal=o});break;case"ToggleSignalValue":n.signal&&typeof n.signal=="string"&&t.push({name:n.signal,itemType:"signal",target:C.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/signal",service:this,designItem:i,type:"script",sourceObject:a,refactor:o=>n.signal=o});break;case"IncrementSignalValue":n.signal&&typeof n.signal=="string"&&t.push({name:n.signal,itemType:"signal",target:C.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/signal",service:this,designItem:i,type:"script",sourceObject:a,refactor:o=>n.signal=o});break;case"DecrementSignalValue":n.signal&&typeof n.signal=="string"&&t.push({name:n.signal,itemType:"signal",target:C.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/signal",service:this,designItem:i,type:"script",sourceObject:a,refactor:o=>n.signal=o});break;case"SetBitInSignal":n.signal&&typeof n.signal=="string"&&t.push({name:n.signal,itemType:"signal",target:C.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/signal",service:this,designItem:i,type:"script",sourceObject:a,refactor:o=>n.signal=o});break;case"ClearBitInSignal":n.signal&&typeof n.signal=="string"&&t.push({name:n.signal,itemType:"signal",target:C.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/signal",service:this,designItem:i,type:"script",sourceObject:a,refactor:o=>n.signal=o});break;case"ToggleBitInSignal":n.signal&&typeof n.signal=="string"&&t.push({name:n.signal,itemType:"signal",target:C.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/signal",service:this,designItem:i,type:"script",sourceObject:a,refactor:o=>n.signal=o});break;case"OpenScreen":n.screen&&typeof n.screen=="string"&&t.push({name:n.screen,itemType:"screen",target:C.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/screen",service:this,designItem:i,type:"script",sourceObject:a,refactor:o=>n.screen=o});break;case"OpenDialog":n.screen&&typeof n.screen=="string"&&t.push({name:n.screen,itemType:"screen",target:C.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/screen",service:this,designItem:i,type:"script",sourceObject:a,refactor:o=>n.screen=o});break;case"CalculateSignalValue":n.targetSignal&&typeof n.targetSignal=="string"&&t.push({name:n.targetSignal,itemType:"signal",target:C.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/targetSignal",service:this,designItem:i,type:"script",sourceObject:a,refactor:o=>n.targetSignal=o});break;case"SubscribeSignal":n.signal&&typeof n.signal=="string"&&t.push({name:n.signal,itemType:"signal",target:C.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/signal",service:this,designItem:i,type:"script",sourceObject:a,refactor:o=>n.signal=o});break;case"UnsubscribeSignal":n.signal&&typeof n.signal=="string"&&t.push({name:n.signal,itemType:"signal",target:C.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/signal",service:this,designItem:i,type:"script",sourceObject:a,refactor:o=>n.signal=o});break;case"ShowMessageBox":n.resultSignal&&typeof n.resultSignal=="string"&&t.push({name:n.resultSignal,itemType:"signal",target:C.event,targetName:s[0],display:n.type+"/"+s[0].substring(1)+"/resultSignal",service:this,designItem:i,type:"script",sourceObject:a,refactor:o=>n.resultSignal=o});break}}else"blocks"in a;if("parameters"in a)for(let n in a.parameters)typeof a.parameters[n]=="string"&&t.push({name:a.parameters[n],itemType:"parameter",target:C.event,targetName:s[0],service:this,designItem:i,type:"script",sourceObject:a,display:s[0].substring(1)+"/parameters/"+n,refactor:o=>a.parameters[n]=o})}}return t}refactor(e,t,i){e.refactor(i);let s=JSON.stringify(e.sourceObject);e.designItem.setAttribute(e.targetName,s)}};import{BasePropertyEditor as Kt}from"@node-projects/web-component-designer";var tt=class extends Kt{_ip;_container;constructor(e,t){super(e),this._container=document.createElement("div"),this._container.style.display="flex",this._ip=document.createElement("input"),this._ip.onchange=s=>this._valueChanged(this._ip.value),this._ip.onfocus=s=>{this._ip.selectionStart=0,this._ip.selectionEnd=this._ip.value?.length},this._container.appendChild(this._ip);let i=document.createElement("button");i.textContent="...",i.onclick=async()=>{let s=t.createBindableObjectBrowser();s.initialize(this.designItems[0].serviceContainer,this.designItems[0].instanceServiceContainer,"property"),s.title="select signal...";let l=new AbortController;s.objectDoubleclicked.on(()=>{l.abort(),this._ip.value=s.selectedObject.fullName,this._valueChanged(this._ip.value)}),await t.openConfirmation(s,{x:100,y:100,width:400,height:300,abortSignal:l.signal})&&(this._ip.value=s.selectedObject.fullName,this._valueChanged(this._ip.value))},this._container.appendChild(i),this.element=this._container}refreshValue(e,t){t==null?this._ip.value="":this._ip.value=t}};import{EventsService as Zt}from"@node-projects/web-component-designer";var it=class r extends Zt{static _cyclicEvent=[{name:`${ye}:100`,propertyName:void 0,eventObjectName:"Event",description:"this event will retrigger itself every 100 ms"}];getPossibleEvents(e){let t=super.getPossibleEvents(e);return t.push(...r._cyclicEvent),t}getEvent(e,t){return t.includes(ye)?r._cyclicEvent.find(s=>s.name==t)??{name:t,propertyName:"on"+t,eventObjectName:"Event"}:super.getEvent(e,t)}};import{PropertyType as oi}from"@node-projects/web-component-designer/dist/elements/services/propertiesService/PropertyType.js";import{BaseCustomWebComponentLazyAppend as ii,css as si}from"@node-projects/base-custom-webcomponent";import{BindingTarget as ni}from"@node-projects/web-component-designer/dist/elements/item/BindingTarget.js";import{ContextMenu as ai}from"@node-projects/web-component-designer/dist/elements/helper/contextMenu/ContextMenu.js";import{BindingTarget as ve}from"@node-projects/web-component-designer/dist/elements/item/BindingTarget.js";import{RefreshMode as Qt}from"@node-projects/web-component-designer/dist/elements/services/propertiesService/IPropertiesService.js";import{PropertyType as ei}from"@node-projects/web-component-designer/dist/elements/services/propertiesService/PropertyType.js";import{ValueType as st}from"@node-projects/web-component-designer/dist/elements/services/propertiesService/ValueType.js";import{AbstractPropertiesService as ti}from"@node-projects/web-component-designer/dist/elements/services/propertiesService/services/AbstractPropertiesService.js";var xe=class extends ti{getRefreshMode(){return Qt.fullOnValueChange}isHandledElement(e){return!e.isRootItem}getBindings(e){return e.serviceContainer.getServices("bindingService").flatMap(t=>(t.getBindings(e)??[]).filter(i=>i.target===ve.class).map(i=>({...i,service:t})))}async getProperties(e){return this.getBindings(e).map(t=>this.createProperty(t.targetName))}async getProperty(e,t){return this.createProperty(t)}createProperty(e){return{name:e,type:"boolean",propertyType:ei.property,service:this}}getPropertyTarget(){return ve.class}getBinding(e,t){return this.getBindings(e[0]).find(i=>i.targetName===t.name)}isSet(e,t){return this.getBinding(e,t)?st.bound:st.none}getValue(e,t){return this.getBinding(e,t)?.expression}validateName(e,t,i){return!t||/[\s"'<>/=]/.test(t)||t!==t.toLowerCase()?"Use a lowercase class name without spaces or HTML attribute delimiters, e.g. is-active.":t!==i&&this.getBindings(e).some(s=>s.targetName===t)?"This class already has a binding.":null}rename(e,t,i){let s=this.validateName(e,i,t.targetName);if(s)throw new Error(s);if(i===t.targetName)return;let l=e.openGroup(`rename class binding: ${t.targetName} to ${i}`);try{if(!t.service.setBinding(e,{...t,targetName:i}))throw new Error("The binding service could not rename this binding.");if(!t.service.clearBinding(e,t.targetName,ve.class))throw new Error("The binding service could not remove the previous binding.");l.commit()}catch(a){throw l.abort(),a}}remove(e,t){let i=e.openGroup(`remove class binding: ${t.targetName}`);try{if(!t.service.clearBinding(e,t.targetName,ve.class))throw new Error("The binding service could not remove this binding.");i.commit()}catch(s){throw i.abort(),s}}};var ue=class extends ii{_items=[];_service=new xe;_rows;_add;_toggle;_signature;_editing=!1;static style=si`
1299
+ :host { display: block; grid-column: 1 / -1; min-width: 0; color: var(--wcd-color-text, white); }
1300
+ :host([hidden]) { display: none !important; }
1301
+ .header, .row { display: flex; align-items: center; gap: 8px; min-height: 28px; }
1302
+ .row { padding-left: 16px; }
1303
+ button { font: inherit; color: inherit; background: transparent; border: none; cursor: pointer; padding: 4px; }
1304
+ button:focus-visible { outline: 2px solid var(--wcd-color-accent, #e91e63); outline-offset: -2px; }
1305
+ button:disabled { opacity: .5; cursor: default; }
1306
+ .toggle, .name { text-align: left; }
1307
+ .toggle { flex: 1; }
1308
+ .name { flex: 0 1 45%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1309
+ .summary { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--wcd-color-text-muted, #bdbdbd); }
1310
+ .message { padding: 4px 16px; font-size: 12px; color: var(--wcd-color-text-muted, #bdbdbd); }
1311
+ dialog { box-sizing: border-box; width: min(420px, calc(100vw - 32px)); color: inherit; background: var(--wcd-property-grid-background, var(--wcd-color-surface-raised, #2f3545)); border: 1px solid var(--wcd-color-border, #596c7a); padding: 16px; }
1312
+ dialog::backdrop { background: #0006; }
1313
+ form, label { display: grid; gap: 8px; }
1314
+ form { gap: 16px; }
1315
+ h3 { font: inherit; font-weight: 600; margin: 0; }
1316
+ input { box-sizing: border-box; width: 100%; padding: 6px; font: inherit; color: inherit; background: transparent; border: 1px solid var(--wcd-color-border, #596c7a); }
1317
+ .help { font-size: 12px; color: var(--wcd-color-text-muted, #bdbdbd); }
1318
+ .error { color: var(--wcd-color-error, #ff8a80); font-size: 12px; }
1319
+ .actions { display: flex; justify-content: flex-end; gap: 8px; }
1320
+ .actions button { border: 1px solid var(--wcd-color-border, #596c7a); padding: 6px 12px; }
1321
+ [hidden] { display: none !important; }
1322
+ :host([appearance="modern"]) { color: var(--_wcd-pg-text); font-size: 13px; }
1323
+ :host([appearance="modern"]) .header {
1324
+ padding: 5px 12px;
1325
+ min-height: 38px;
1326
+ background: var(--_wcd-pg-raised);
1327
+ border-bottom: 1px solid var(--_wcd-pg-border);
1328
+ }
1329
+ :host([appearance="modern"]) .toggle { font-weight: 600; }
1330
+ :host([appearance="modern"]) .row {
1331
+ display: grid;
1332
+ grid-template-columns: minmax(0, .85fr) minmax(0, 1fr) 28px;
1333
+ padding: 5px 12px 5px 24px;
1334
+ min-height: 38px;
1335
+ border-bottom: 1px solid var(--_wcd-pg-border);
1336
+ }
1337
+ :host([appearance="modern"]) .row:hover,
1338
+ :host([appearance="modern"]) .row:focus-within { background: var(--_wcd-pg-hover); }
1339
+ :host([appearance="modern"]) .summary { color: var(--_wcd-pg-muted); }
1340
+ :host([appearance="modern"]) button { border-radius: 4px; }
1341
+ :host([appearance="modern"]) button:hover { background: var(--_wcd-pg-hover); }
1342
+ :host([appearance="modern"]) button:focus-visible { outline-color: var(--wcd-color-focus, var(--_wcd-pg-accent)); }
1343
+ :host([appearance="modern"]) dialog {
1344
+ padding: 24px;
1345
+ border-radius: 10px;
1346
+ color: var(--_wcd-pg-text);
1347
+ background: var(--_wcd-pg-surface);
1348
+ border-color: var(--_wcd-pg-border);
1349
+ box-shadow: 0 16px 64px #0003;
1350
+ }
1351
+ :host([appearance="modern"]) h3 { font-size: 16px; }
1352
+ :host([appearance="modern"]) input { border-radius: 5px; border-color: var(--_wcd-pg-border); padding: 8px; }
1353
+ :host([appearance="modern"]) input:focus-visible { outline: 2px solid var(--wcd-color-focus, var(--_wcd-pg-accent)); outline-offset: 1px; }
1354
+ :host([appearance="modern"]) .help { color: var(--_wcd-pg-muted); }
1355
+ :host([appearance="modern"]) .actions button { border-color: var(--_wcd-pg-border); }
1356
+ :host([appearance="modern"]) .actions button[type="submit"] {
1357
+ background: var(--_wcd-pg-accent);
1358
+ color: var(--wcd-color-accent-text, light-dark(white, #162b48));
1359
+ border-color: transparent;
1360
+ }
1361
+ `;constructor(){super();let e=document.createElement("div");e.className="header",this._toggle=document.createElement("button"),this._toggle.type="button",this._toggle.className="toggle",this._toggle.textContent="\u25BE Class bindings",this._toggle.setAttribute("aria-expanded","true"),this._toggle.onclick=()=>{this._rows.hidden=!this._rows.hidden,this._toggle.textContent=(this._rows.hidden?"\u25B8":"\u25BE")+" Class bindings",this._toggle.setAttribute("aria-expanded",String(!this._rows.hidden))},this._add=document.createElement("button"),this._add.type="button",this._add.textContent="+",this._add.title="Add class binding\u2026",this._add.setAttribute("aria-label","Add class binding"),this._add.onclick=()=>this.addBinding(),e.append(this._toggle,this._add),this._rows=document.createElement("div"),this.shadowRoot.append(e,this._rows)}refresh(e){let t=this._items[0]!==e?.[0]||this._items.length!==e?.length;t&&this.shadowRoot.querySelector("dialog")?.close(),this._items=e??[];let i=this._items.length===1?this._items[0]:null,s=i?this._service.getBindings(i):[];this._add.disabled=!i||!i.serviceContainer.config.openBindingsEditor;let l=JSON.stringify(s.map(({service:a,...n})=>n));if(!(!t&&l===this._signature)){if(this._signature=l,this._rows.replaceChildren(),!i){let a=document.createElement("div");a.className="message",a.textContent="Select one element to edit class bindings.",this._rows.appendChild(a);return}for(let a of s){let n=document.createElement("div");n.className="row";let o=document.createElement("button");o.type="button",o.className="name",o.textContent=a.targetName,o.title=`Edit class binding: ${a.targetName}`,o.onclick=()=>this.editBinding(i,a);let c=document.createElement("span");c.className="summary",c.textContent="\u2190 "+(a.expression||a.bindableObjectNames?.join(";")||a.rawValue||"binding"),c.title=c.textContent,c.ondblclick=()=>this.editBinding(i,a);let p=document.createElement("button");p.type="button",p.textContent="\u22EF",p.setAttribute("aria-label",`Actions for class binding ${a.targetName}`);let d=h=>{h.preventDefault(),ai.show([{title:"Edit binding\u2026",action:()=>this.editBinding(i,a)},{title:"Rename class\u2026",action:()=>this.showNameDialog(i,a)},{title:"Remove binding",action:()=>{this._service.remove(i,a),this.refresh(this._items)}}],h)};p.onclick=d,n.oncontextmenu=d,n.append(o,c,p),this._rows.appendChild(n)}}}addBinding(){this._add.disabled||this.showNameDialog(this._items[0])}async editBinding(e,t,i=t?.targetName){if(this._editing)return;let s=e.serviceContainer.config.openBindingsEditor;if(s){this._editing=!0;try{await s(this._service.createProperty(i),[e],t,ni.class),this.refresh(this._items)}finally{this._editing=!1}}}showNameDialog(e,t,i=t?.targetName??""){if(this.shadowRoot.querySelector("dialog"))return;let s=document.createElement("dialog"),l=document.createElement("form"),a=document.createElement("h3");a.textContent=t?"Rename class":"Add class binding";let n=document.createElement("label");n.textContent="Class name";let o=document.createElement("input");o.value=i,o.required=!0;let c=document.createElement("span");c.className="help",c.textContent="Use lowercase names, e.g. is-active.",n.append(o,c);let p=document.createElement("div");p.className="error",p.setAttribute("role","alert"),p.hidden=!0;let d=document.createElement("div");d.className="actions";let h=document.createElement("button");h.type="button",h.textContent="Cancel",h.onclick=()=>s.close();let u=document.createElement("button");u.type="submit",u.textContent=t?"Save":"Next\u2026",d.append(h,u),l.append(a,n),l.append(p,d),s.appendChild(l),this.shadowRoot.appendChild(s),s.onclose=()=>s.remove(),l.onsubmit=async g=>{g.preventDefault();let f=o.value.trim(),w=this._service.validateName(e,f,t?.targetName);try{if(w)throw new Error(w);t&&this._service.rename(e,t,f),s.close(),t||await this.editBinding(e,void 0,f),this.refresh(this._items)}catch(x){p.textContent=x.message,p.hidden=!1}},s.showModal(),o.focus()}};customElements.define("node-projects-property-grid-class-bindings",ue);var nt=class{createExtension(e){if(e.name!=="class"&&e.name!=="className"||e.propertyType===oi.cssValue)return;let t=new ue;return{element:t,refresh:i=>t.refresh(i),getContextMenuItems:i=>[{title:"Add class binding\u2026",disabled:i?.length!==1||!i[0].serviceContainer.config.openBindingsEditor,action:()=>t.addBinding()}]}}};export{qe as BindableObjectDragDropService,he as BindingsEditor,K as BindingsEditorHistoric,Fe as BindingsHelper,Y as BlocklyScriptEditor,nt as ClassBindingsPropertyGridExtensionProvider,ge as EventAssignment,ie as ParameterEditor,Qe as PropertyGridDragDropService,Ue as Script,et as ScriptRefactorService,Ge as ScriptSystem,tt as SignalPropertyEditor,Z as SimpleScriptCommandPicker,te as SimpleScriptEditor,Ze as VisualizationBindingsRefactorService,Ye as VisualizationBindingsService,it as VisualizationEventsService,re as VisualizationPropertyGrid,le as bindingPrefixAttribute,ce as bindingPrefixClass,J as bindingPrefixContent,pe as bindingPrefixCss,ne as bindingPrefixCssVar,We as bindingPrefixInsideCss,Ht as bindingPrefixInsideCssVarName,se as bindingPrefixProperty,Se as bindingPrefixVisible,bs as bindingsInCssRegex,ye as cyclicAttributeName,Ee as generateEventCodeFromBlockly,Jt as getNestedProperty,de as isLit,Ae as nativeScriptCommandDescriptions,Ce as parseBindingString,Ve as simpleScriptEditorHelpHtml};
1293
1362
  //!varname => inverted