morphic-blocks 0.2.1 → 0.4.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.
@@ -1,30 +1,39 @@
1
- (function(A,R){typeof exports=="object"&&typeof module<"u"?R(exports,require("blockly/blocks"),require("blockly"),require("blockly/javascript")):typeof define=="function"&&define.amd?define(["exports","blockly/blocks","blockly","blockly/javascript"],R):(A=typeof globalThis<"u"?globalThis:A||self,R(A.MorphicBlocks={},A.Blockly,A.Blockly,A.javascript))})(this,(function(A,R,X,K){"use strict";var qo=Object.defineProperty;var Zo=(A,R,X)=>R in A?qo(A,R,{enumerable:!0,configurable:!0,writable:!0,value:X}):A[R]=X;var g=(A,R,X)=>Zo(A,typeof R!="symbol"?R+"":R,X);function at(n){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const e in n)if(e!=="default"){const o=Object.getOwnPropertyDescriptor(n,e);Object.defineProperty(t,e,o.get?o:{enumerable:!0,get:()=>n[e]})}}return t.default=n,Object.freeze(t)}const L=at(X);function te(n){if(!(!n||typeof n=="function"))return n}function lt(n){if(n)return typeof n=="function"?n:n.generate}const oe="morphic-mode-",ne="morphic-context-",Be="morphic-category-",dt="morphic-block-",ht=-1,ut=0,pt=1;function U(n){if(n!==void 0)return typeof n=="string"?n:n.type}const Y=16;function ft(n){if(!n||typeof n=="string")return{width:Y,height:Y};const t=n.size;if(t===void 0)return{width:Y,height:Y};if(typeof t=="number")return{width:t,height:t};const e=/^(\d+)(?:x(\d+))?$/i.exec(t.trim());if(!e)return{width:Y,height:Y};const o=Number.parseInt(e[1],10),i=e[2]?Number.parseInt(e[2],10):o;return{width:o,height:i}}function mt(n,t){if(n!=null&&n.default)return n.default;if(!t||typeof t=="string")return;const e=t.empty;if(!e)return;const o=n!=null&&n.check?Array.isArray(n.check)?n.check[0]:n.check:void 0;return(o?e[o]:void 0)??e.default}const ie=18;function q(n){const t=[];let e=0;for(;e<n.length;){const o=n[e];if(o==="<"&&/^<img\b/i.test(n.slice(e))){const s=n.indexOf(">",e);if(s===-1){Ie(t,n.slice(e));break}const r=n.slice(e,s+1),c=yt(r);c&&t.push(c),e=s+1;continue}if(o==="%"&&/\d/.test(n[e+1]??"")){let s=e+1;for(;s<n.length&&/\d/.test(n[s]??"");)s+=1;const r=Number.parseInt(n.slice(e+1,s),10);Number.isNaN(r)||t.push({kind:"placeholder",index:r}),e=s;continue}if(o==="%"&&/[A-Z_]/.test(n[e+1]??"")){let s=e+1;for(;s<n.length&&/[A-Z0-9_]/.test(n[s]??"");)s+=1;const r=n.slice(e+1,s);t.push({kind:"field",name:r}),e=s;continue}let i=e+1;for(;i<n.length;){const s=n[i],r=s==="%"&&/\d/.test(n[i+1]??""),c=s==="%"&&/[A-Z_]/.test(n[i+1]??"");if(s==="<"&&/^<img\b/i.test(n.slice(i))||r||c)break;i+=1}Ie(t,n.slice(e,i)),e=i}return bt(t)}function gt(n){return n.replace(/\s+/g," ").trim()}function H(n){return n.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}function Me(n){return n.map(t=>t.kind==="text"?kt(t.value):t.kind==="image"?`<img src="${se(t.src)}" alt="${se(t.alt)}" width="${t.width}" height="${t.height}">`:t.kind==="field"?`<span class="morphic-field-placeholder" data-field-name="${se(t.name)}"></span>`:`<span class="morphic-toolbox-slot" data-slot-index="${t.index}"></span>`).join("")}function kt(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function se(n){return n.replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const vt=/\.(svg|png|jpe?g|gif|webp)(?:[#?].*)?$/i;function wt(n,t){if(!n)return n;const e=n.trim();return/^<img\b/i.test(e)?n:vt.test(e)?`<img src="${se(e)}" width="${t.width}" height="${t.height}">`:n}function yt(n){if(!/^<img\b/i.test(n))return null;const t=re(n,"src");if(!t)return null;const e=re(n,"alt")??"",o=Number.parseInt(re(n,"width")??`${ie}`,10),i=Number.parseInt(re(n,"height")??`${ie}`,10);return{kind:"image",src:t,alt:e,width:Number.isNaN(o)?ie:o,height:Number.isNaN(i)?ie:i}}function re(n,t){const e=new RegExp(`${t}\\s*=\\s*(['"])(.*?)\\1`,"i").exec(n);if(e!=null&&e[2])return e[2];const o=new RegExp(`${t}\\s*=\\s*([^\\s>]+)`,"i").exec(n);return(o==null?void 0:o[1])??null}function Ie(n,t){t&&n.push({kind:"text",value:t})}function bt(n){const t=[];for(const e of n){const o=t[t.length-1];if(e.kind==="text"&&(o==null?void 0:o.kind)==="text"){o.value+=e.value;continue}t.push(e)}return t}function De(n){const{block:t,definition:e,view:o,mode:i,context:s,elementTypes:r,resolveBlocklyType:c}=n,a=Ot(t);Ft(t),Lt(t,e,o),Rt(t,e),typeof e.inputsInline=="boolean"&&t.setInputsInline(e.inputsInline),e.color!==void 0&&t.setColour(e.color),e.tooltip&&t.setTooltip(e.tooltip),e.helpUrl&&t.setHelpUrl(e.helpUrl),$t(t,a),r&&Nt(t,e,o,r,c),Tt(t,i,s);const l=t;l.__morphicMode=i,l.__morphicContext=s,t.rendered&&t.render()}function ke(n,t,e,o){Z(n.classList,oe),Z(n.classList,ne),n.classList.add(o),n.classList.add(`${oe}${H(t)}`),n.classList.add(`${ne}${e}`)}function Ct(n){return n.__morphicMode}function Et(n,t){const e=n.getSvgRoot();e&&(Z(e.classList,Be),t&&e.classList.add(`${Be}${t}`))}function St(n,t){const e=n.getSvgRoot();if(!e)return;const o=`${dt}${H(t)}`;e.classList.contains(o)||e.classList.add(o)}function xt(n){const t=n.getSvgRoot();if(!t)return;const e=getComputedStyle(t).getPropertyValue("--morphic-block-color").trim();e&&(n.setColour(e),n.rendered&&n.render())}function Tt(n,t,e){const o=n.getSvgRoot();o&&(Z(o.classList,oe),Z(o.classList,ne),o.classList.add(`${oe}${H(t)}`),o.classList.add(`${ne}${e}`))}function Lt(n,t,e){var r;const o=q(e.template),i=[],s=new Set;for(const c of o){if(c.kind==="text"){const d=gt(c.value);d&&i.push(d);continue}if(c.kind==="image"){i.push(new L.FieldImage(c.src,c.width,c.height,c.alt));continue}if(c.kind==="field"){const d=(r=t.fields)==null?void 0:r[c.name];d&&i.push({field:Dt(d,e.elementName),name:c.name});continue}if(s.has(c.index)){const d=n.appendDummyInput(`DUPLICATE_${c.index}_${n.inputList.length}`);ce(d,i),d.appendField(`%${c.index}`);continue}s.add(c.index);const a=Bt(t,e,c.index);if((a==null?void 0:a.kind)==="statement"&&i.length>0){const d=n.appendDummyInput(`PRE_STMT_${n.inputList.length}`);ce(d,i)}const l=Mt(n,a,c.index);ce(l,i),a!=null&&a.label&&l.appendField(a.label)}if(i.length>0){const c=n.appendDummyInput(`TRAILING_${n.inputList.length}`);ce(c,i)}n.inputList.length===0&&n.appendDummyInput("LABEL").appendField(t.identifier)}function Bt(n,t,e){var i,s;const o=`${e}`;return((i=t.inputSlots)==null?void 0:i[o])??((s=n.inputSlots)==null?void 0:s[o])}function Mt(n,t,e){const o=(t==null?void 0:t.name)??`ARG${e}`,i=(t==null?void 0:t.kind)??"value";let s;return i==="statement"?(s=n.appendStatementInput(o),t!=null&&t.check&&s.setCheck(t.check)):(s=n.appendValueInput(o),t!=null&&t.check&&s.setCheck(t.check)),t!=null&&t.align&&s.setAlign(It(t.align)),s}function It(n){return n==="right"?pt:n==="centre"?ut:ht}function ce(n,t){for(const e of t)typeof e=="object"&&"field"in e?n.appendField(e.field,e.name):n.appendField(e);t.length=0}function Dt(n,t){switch(n.type){case"dropdown":{const e=n.options.map(i=>At(i,t)),o=new L.FieldDropdown(e);return n.default!==void 0&&o.setValue(n.default),o}case"number":return new L.FieldNumber(n.default??0,n.min,n.max,n.precision);case"checkbox":return new L.FieldCheckbox(n.default?"TRUE":"FALSE");case"text":default:return new L.FieldTextInput(n.default??"")}}function At(n,t){var o;if(typeof n=="string")return[n,n];if(Array.isArray(n)){const[i,s]=n;return[s??i,i]}return[(t?(o=n.display)==null?void 0:o[t]:void 0)??n.label??n.value,n.value]}function Ot(n){var e;const t=new Map;for(const o of n.inputList){const i=(e=o.connection)==null?void 0:e.targetBlock();i&&!i.isShadow()&&t.set(o.name,i)}return t}function Nt(n,t,e,o,i=s=>s){var a,l;const s=e.elementName?o[e.elementName]:void 0,r=new Map;for(const d of Object.values(t.inputSlots??{}))d!=null&&d.name&&(d.kind??"value")==="value"&&r.set(d.name,d);if(r.size===0)return;const c=n.workspace;for(const d of n.inputList){const u=d.connection;if(!u||u.type!==L.INPUT_VALUE)continue;const w=r.get(d.name);if(!w)continue;const v=mt(w,s);if(v){if(v.shadow&&!(((a=u.getShadowState)==null?void 0:a.call(u,!0))??((l=u.getShadowDom)==null?void 0:l.call(u))))try{u.setShadowState({type:i(v.shadow),fields:v.fieldValues??{}})}catch{}if(v.placeholder){const C=n,E=C.__morphicPlaceholderSlots??(C.__morphicPlaceholderSlots=new Set),k=u.targetBlock(),m=!k||k.isShadow(),p=E.has(d.name);if(E.add(d.name),m&&!p)try{const y=c.newBlock(i(v.placeholder));if(v.fieldValues)for(const[S,h]of Object.entries(v.fieldValues)){const f=y.getField(S);f&&f.setValue(h)}n.rendered&&(y.initSvg(),y.render()),y.outputConnection&&u.connect(y.outputConnection)}catch{}}}}}function $t(n,t){for(const[e,o]of t){const i=n.getInput(e);if(!(i!=null&&i.connection)||i.connection.isConnected())continue;const s=[o.outputConnection,o.previousConnection];for(const r of s)if(r)try{i.connection.connect(r);break}catch{continue}}}function Pt(n){const t=new Map;for(const e of n.inputList)for(const o of e.fieldRow)o.name&&t.set(o.name,o.getValue());return t}function Ht(n,t){for(const[e,o]of t){const i=n.getField(e);if(i&&o!==void 0&&o!==null)try{i.setValue(o)}catch{}}}function Ft(n){for(;n.inputList.length>0;){const t=n.inputList[0];if(!t)break;n.removeInput(t.name,!0)}}function Rt(n,t){t.output!==void 0&&_t(n,t.output),t.previousStatement!==void 0&&Vt(n,t.previousStatement),t.nextStatement!==void 0&&zt(n,t.nextStatement)}function _t(n,t){if(t===!1){n.setOutput(!1);return}if(t===!0){n.setOutput(!0);return}n.setOutput(!0,t)}function Vt(n,t){if(t===!1){n.setPreviousStatement(!1);return}if(t===!0){n.setPreviousStatement(!0);return}n.setPreviousStatement(!0,t)}function zt(n,t){if(t===!1){n.setNextStatement(!1);return}if(t===!0){n.setNextStatement(!0);return}n.setNextStatement(!0,t)}function Z(n,t){const e=Array.from(n).filter(o=>o.startsWith(t));for(const o of e)n.remove(o)}function Ae(n,t,e){if(!e)return[];const o=new Set(e.keywords??[]),i=e.strings??[],s=e.comment,r=e.numbers!==!1,c=n.Decoration.mark({class:"morphic-tok-keyword"}),a=n.Decoration.mark({class:"morphic-tok-string"}),l=n.Decoration.mark({class:"morphic-tok-number"}),d=n.Decoration.mark({class:"morphic-tok-comment"}),u=(p,y,S)=>{const h=p.length;let f=0;for(;f<h;){if(s&&p.startsWith(s,f)){S.add(y+f,y+h,d);return}let x=!1;for(const b of i)if(p.startsWith(b,f)){const I=f;for(f+=b.length;f<h;){if(p[f]==="\\"&&f+1<h){f+=2;continue}if(p.startsWith(b,f)){f+=b.length;break}f+=1}S.add(y+I,y+f,a),x=!0;break}if(x)continue;if(r){const b=/^\d+(?:\.\d+)?/.exec(p.slice(f));if(b){S.add(y+f,y+f+b[0].length,l),f+=b[0].length;continue}}const B=/^[A-Za-z_]\w*/.exec(p.slice(f));if(B){o.has(B[0])&&S.add(y+f,y+f+B[0].length,c),f+=B[0].length;continue}f+=1}},w=p=>{const y=new t.RangeSetBuilder,S=p.state.doc;for(const{from:h,to:f}of p.visibleRanges){let x=h;for(;x<=f;){const B=S.lineAt(x);if(u(B.text,B.from,y),B.to>=f)break;x=B.to+1}}return y.finish()},v=n.ViewPlugin.fromClass(class{constructor(p){g(this,"decorations");this.decorations=w(p)}update(p){(p.docChanged||p.viewportChanged)&&(this.decorations=w(p.view))}},{decorations:p=>p.decorations}),C=n.EditorView.baseTheme({".morphic-tok-keyword":{color:"#cc7832"},".morphic-tok-string":{color:"#6a8759"},".morphic-tok-number":{color:"#6897bb"},".morphic-tok-comment":{color:"#808080",fontStyle:"italic"}}),E=e.colors??{},k={};E.keyword&&(k[".morphic-tok-keyword"]={color:E.keyword}),E.string&&(k[".morphic-tok-string"]={color:E.string}),E.number&&(k[".morphic-tok-number"]={color:E.number}),E.comment&&(k[".morphic-tok-comment"]={color:E.comment,fontStyle:"italic"});const m=[v,C];return Object.keys(k).length>0&&m.push(n.EditorView.theme(k)),m}const ve="morphic/block-id";let ae;function Oe(){return ae}function Ne(n){ae=n}const $e={fontSize:"14px",fontFamily:"monospace",lineHeight:1.5,background:"#1e1e1e",foreground:"#d4d4d4",gutterBackground:"#1e1e1e",gutterForeground:"#858585",selectionBackground:"#264f78"},le=(n,t)=>`color-mix(in srgb, ${n} ${t}%, transparent)`;let Pe=!1;async function Wt(){if(Pe)return;Pe=!0;const t=(await Promise.resolve().then(()=>Yo)).default,e=document.createElement("style");e.dataset.morphicSource="code-editor",e.textContent=t,document.head.appendChild(e)}const jt=150,Ut=new Set(["create","delete","move","change"]);function Gt(n){return Ut.has(n.type)}async function Xt(){try{const[n,t,e]=await Promise.all([import("@codemirror/view"),import("@codemirror/state"),import("@codemirror/lang-javascript")]);return{view:n,state:t,langJs:e}}catch{throw new Error(`CodeMirror is required for the code editor. Install it:
2
- bun add codemirror @codemirror/view @codemirror/state @codemirror/lang-javascript
3
- # or: npm install codemirror @codemirror/view @codemirror/state @codemirror/lang-javascript`)}}function we(n,t){const e={...$e,...t};return n.EditorView.theme({"&":{fontSize:e.fontSize,fontFamily:e.fontFamily,backgroundColor:e.background,color:e.foreground},".cm-content":{lineHeight:String(e.lineHeight)},".cm-gutters":{backgroundColor:e.gutterBackground,color:e.gutterForeground,border:"none"},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground":{backgroundColor:`${e.selectionBackground} !important`},".morphic-delete-marker":{color:le(e.foreground,70),backgroundColor:le(e.foreground,12)},".morphic-delete-marker:hover":{color:e.foreground,backgroundColor:le(e.foreground,22)},".morphic-grip-marker":{color:le(e.foreground,75)},".morphic-grip-marker:hover":{color:e.foreground}})}class ye{constructor(t,e,o,i={}){g(this,"editorView");g(this,"container");g(this,"options");g(this,"workspace");g(this,"generateWithMetadata");g(this,"visible",!0);g(this,"syncTimer");g(this,"changeListener");g(this,"lastCode","");g(this,"metadata",new Map);g(this,"placeholders",[]);g(this,"placeholderEditorEl");g(this,"placeholderEditorScrollHandler");g(this,"placeholderEditorOutsideHandler");g(this,"onCursorLine");g(this,"onEmptyClick");g(this,"cm");g(this,"themeCompartment");g(this,"syntaxHighlightCompartment");g(this,"highlightEffect");g(this,"highlightColor","rgba(255, 255, 255, 0.07)");g(this,"metadataEffect");g(this,"placeholderEffect");g(this,"dropIndicatorEffect");g(this,"valueSlotHighlightEffect");g(this,"hoverHighlightEffect");g(this,"editableHoverHighlightEffect");g(this,"emptyClickListener");g(this,"disposed",!1);g(this,"zoomFactor",1);this.container=t,this.workspace=e,this.generateWithMetadata=o,this.options=i}getPlaceholders(){return this.placeholders}findPlaceholderAtPos(t){if(this.options.showPlaceholderMarkers===!1)return null;let e=null,o=1/0;for(const i of this.placeholders){if(i.start>t)break;if(t>=i.start&&t<=i.end){const s=i.end-i.start;s<o&&(o=s,e=i)}}return e}closePlaceholderEditor(){const t=this.placeholderEditorEl;t&&(this.placeholderEditorEl=void 0,this.placeholderEditorScrollHandler&&this.editorView&&(this.editorView.scrollDOM.removeEventListener("scroll",this.placeholderEditorScrollHandler),this.placeholderEditorScrollHandler=void 0),this.placeholderEditorOutsideHandler&&(document.removeEventListener("mousedown",this.placeholderEditorOutsideHandler),this.placeholderEditorOutsideHandler=void 0),t.parentNode&&t.parentNode.removeChild(t))}openPlaceholderEditor(t){if(!this.editorView||!t.edit)return;const e=this.options.onPlaceholderApply;if(!e)return;this.closePlaceholderEditor();const o=this.editorView,i=o.coordsAtPos(t.start),s=o.coordsAtPos(t.end);if(!i||!s)return;const r=o.scrollDOM.getBoundingClientRect(),c=o.state.doc.sliceString(t.start,t.end),a=t.edit;let l;if(a.fieldType==="dropdown"){const C=document.createElement("select");for(const[E,k]of a.options??[]){const m=document.createElement("option");m.value=k,m.textContent=E,C.appendChild(m)}l=C}else{const C=document.createElement("input");C.type=a.fieldType==="number"?"number":"text",C.value=c,l=C}const d=getComputedStyle(o.contentDOM),u=(()=>{let C=o.dom;for(;C;){const E=getComputedStyle(C).backgroundColor;if(E&&E!=="rgba(0, 0, 0, 0)"&&E!=="transparent")return E;C=C.parentElement}return"#fff"})();Object.assign(l.style,{position:"absolute",left:`${i.left-r.left+o.scrollDOM.scrollLeft}px`,top:`${i.top-r.top+o.scrollDOM.scrollTop}px`,minWidth:`${Math.max(40,s.right-i.left+8)}px`,height:`${i.bottom-i.top}px`,font:d.font,lineHeight:d.lineHeight,padding:"0 2px",margin:"0",border:`1px solid ${d.color}`,borderRadius:"2px",background:u,color:d.color,boxSizing:"border-box",zIndex:"20"}),o.scrollDOM.appendChild(l),this.placeholderEditorEl=l;const w=()=>{const C=l.value;this.closePlaceholderEditor(),e(a,C)},v=()=>{this.closePlaceholderEditor()};if(l.addEventListener("keydown",C=>{const E=C.key;E==="Enter"?(C.preventDefault(),w()):E==="Escape"&&(C.preventDefault(),v())}),l.addEventListener("mousedown",C=>C.stopPropagation()),l.addEventListener("click",C=>C.stopPropagation()),a.fieldType==="dropdown"){l.addEventListener("change",()=>w());const C=this.workspace.getBlockById(a.blockId),E=C==null?void 0:C.getField(a.fieldName),k=E==null?void 0:E.getValue();k!=null&&(l.value=String(k)),requestAnimationFrame(()=>{this.placeholderEditorOutsideHandler=m=>{m.target instanceof Node&&!l.contains(m.target)&&v()},document.addEventListener("mousedown",this.placeholderEditorOutsideHandler)})}else l.addEventListener("blur",()=>w());this.placeholderEditorScrollHandler=()=>this.closePlaceholderEditor(),o.scrollDOM.addEventListener("scroll",this.placeholderEditorScrollHandler),requestAnimationFrame(()=>{l.focus(),l instanceof HTMLInputElement&&l.select()})}async mount(){if(Wt(),this.cm=await Xt(),this.disposed)return;const{view:t,state:e,langJs:o}=this.cm;this.themeCompartment=new e.Compartment,this.syntaxHighlightCompartment=new e.Compartment;const i=we(t,this.options.theme??{}),s=Ae(t,e,this.options.highlightRules),r=e.StateEffect.define();this.metadataEffect=r;const c=e.StateEffect.define();this.placeholderEffect=c;const a=e.StateField.define({create(){return t.Decoration.none},update(k,m){for(const p of m.effects)if(p.is(c)){const y=p.value;if(!y||y.length===0)return t.Decoration.none;const S=m.state.doc.length,h=[...y].filter(b=>b.start<b.end&&b.end<=S).sort((b,I)=>b.start-I.start||b.end-I.end),f=new e.RangeSetBuilder,x=t.Decoration.mark({class:"morphic-placeholder-default"}),B=t.Decoration.mark({class:"morphic-placeholder-set"});for(const b of h)f.add(b.start,b.end,b.kind==="default"?x:B);return f.finish()}return m.changes.empty?k:t.Decoration.none},provide(k){return t.EditorView.decorations.from(k)}}),l=e.StateEffect.define();this.highlightEffect=l;const d=this,u=e.StateField.define({create(){return t.Decoration.none},update(k,m){for(const p of m.effects)if(p.is(l)){const y=p.value;if(!y)return t.Decoration.none;const S=Array.isArray(y)?y:[y];if(S.length===0)return t.Decoration.none;const h=m.state.doc,f=t.Decoration.mark({class:"morphic-highlight",attributes:{style:`background: ${d.highlightColor}`}}),x=S.map(B=>{const b=h.line(Math.min(B.fromLine,h.lines)).from,I=h.line(Math.min(B.toLine,h.lines)).to;return f.range(b,I)}).sort((B,b)=>B.from-b.from);return t.Decoration.set(x)}return m.changes.empty?k:t.Decoration.none},provide(k){return t.EditorView.decorations.from(k)}}),w=t.EditorView.updateListener.of(k=>{var S;if(k.docChanged||k.transactions.some(h=>h.isUserEvent("select.pointer")))return;const m=k.state.selection.main.head,p=k.startState.selection.main.head;if(m===p)return;if(d.findPlaceholderAtPos(m)){(S=d.onEmptyClick)==null||S.call(d);return}if(!d.onCursorLine)return;const y=k.state.doc.lineAt(m).number;d.onCursorLine(y)}),v=this.options.showPlaceholderMarkers!==!1,C=[t.lineNumbers(),t.highlightSpecialChars(),e.EditorState.readOnly.of(!0),o.javascript(),u,...v?[a]:[],w,this.themeCompartment.of(i),this.syntaxHighlightCompartment.of(s),...this.buildDeleteExtensions(t,e,r),...this.buildGripExtensions(t,e,r),...this.buildDropIndicatorExtensions(t,e),...this.buildValueSlotHighlightExtensions(t,e),...this.buildHoverHighlightExtensions(t,e),...this.buildEditableHoverHighlightExtensions(t,e),...this.options.extensions??[]],E=this.generateWithMetadata();this.lastCode=E.code,this.metadata=E.metadata,this.placeholders=[...E.placeholders].sort((k,m)=>k.start-m.start),this.editorView=new t.EditorView({parent:this.container,state:e.EditorState.create({doc:this.lastCode,extensions:C})}),this.metadataEffect&&this.metadata.size>0&&this.editorView.dispatch({effects:this.metadataEffect.of(this.metadata)}),this.placeholderEffect&&E.placeholders.length>0&&this.editorView.dispatch({effects:this.placeholderEffect.of(E.placeholders)}),this.emptyClickListener=k=>{var p,y,S;if(this.isBelowLastLine(k.clientY)){(p=this.onEmptyClick)==null||p.call(this);return}const m=(y=this.editorView)==null?void 0:y.posAtCoords({x:k.clientX,y:k.clientY});if(typeof m=="number"){const h=this.findPlaceholderAtPos(m);if(h){(S=this.onEmptyClick)==null||S.call(this),h.edit&&this.options.onPlaceholderApply&&requestAnimationFrame(()=>this.openPlaceholderEditor(h));return}}if(this.onCursorLine){const h=this.getLineAtCoords(k.clientX,k.clientY);h!==null&&this.onCursorLine(h)}},this.editorView.scrollDOM.addEventListener("click",this.emptyClickListener),this.attachSyncListener()}buildDeleteExtensions(t,e,o){const i=this.options.onDelete;if(!i)return[];class s extends t.GutterMarker{toDOM(){const u=document.createElement("span");return u.textContent="✕",u.className="morphic-delete-marker",u.style.cssText=["display: inline-flex","align-items: center","justify-content: center","width: 16px","height: 16px","margin: 0 4px","border-radius: 50%","font-size: 10px","line-height: 1","cursor: pointer","transition: background 0.15s, color 0.15s"].join(";"),u}}const r=new s,c=e.StateField.define({create(){return e.RangeSet.empty},update(d,u){for(const w of u.effects)if(w.is(o)){const v=w.value,C=u.state.doc,E=new Set;for(const{startLine:m}of v.values())m>=1&&m<=C.lines&&E.add(m);const k=Array.from(E).sort((m,p)=>m-p).map(m=>r.range(C.line(m).from));return e.RangeSet.of(k,!0)}return d.map(u.changes)}}),a=t.gutter({class:"morphic-delete-gutter",markers(d){return d.state.field(c)},initialSpacer:()=>r,domEventHandlers:{click(d,u){const w=d.state.doc.lineAt(u.from).number;return i(w),!0}}}),l=t.keymap.of([{key:"Delete",run:d=>{if(!d.state.selection.main.empty)return!1;const u=d.state.doc.lineAt(d.state.selection.main.head).number;return i(u),!0}},{key:"Backspace",run:d=>{if(!d.state.selection.main.empty)return!1;const u=d.state.doc.lineAt(d.state.selection.main.head).number;return i(u),!0}}]);return[c,a,e.Prec.highest(l)]}buildGripExtensions(t,e,o){const i=this.options.canDragBlock;if(!i)return[];class s extends t.GutterMarker{constructor(l){super(),this.blockId=l}eq(l){return l instanceof s&&l.blockId===this.blockId}toDOM(){const l=document.createElement("span");l.textContent="⠿",l.draggable=!0,l.className="morphic-grip-marker",l.style.cssText=["display: inline-flex","align-items: center","justify-content: center","width: 16px","height: 16px","margin: 0 2px","font-size: 14px","line-height: 1","cursor: grab","user-select: none","transition: color 0.15s"].join(";");const d=this.blockId;return l.addEventListener("dragstart",u=>{u.dataTransfer&&(u.dataTransfer.setData(ve,d),u.dataTransfer.effectAllowed="move",l.style.cursor="grabbing",ae=d)}),l.addEventListener("dragend",()=>{l.style.cursor="grab",ae=void 0}),l}}const r=e.StateField.define({create(){return e.RangeSet.empty},update(a,l){for(const d of l.effects)if(d.is(o)){const u=d.value,w=l.state.doc,v=new Map;for(const[E,{startLine:k,startChar:m,endChar:p}]of u){if(k<1||k>w.lines||!i(E))continue;const y=(p??0)-(m??0),S=v.get(k);(!S||y>S.width)&&v.set(k,{id:E,width:y})}const C=Array.from(v.entries()).sort((E,k)=>E[0]-k[0]).map(([E,{id:k}])=>new s(k).range(w.line(E).from));return e.RangeSet.of(C,!0)}return a.map(l.changes)}}),c=t.gutter({class:"morphic-grip-gutter",markers(a){return a.state.field(r)},initialSpacer:()=>new s("")});return[r,c]}buildDropIndicatorExtensions(t,e){const o=e.StateEffect.define();this.dropIndicatorEffect=o;const i=e.StateField.define({create(){return t.Decoration.none},update(r,c){for(const a of c.effects)if(a.is(o)){const l=a.value;if(!l)return t.Decoration.none;const d=c.state.doc,u=Math.max(1,Math.min(l.line,d.lines)),w=d.line(u),v=l.position==="above"?"morphic-drop-indicator-above":"morphic-drop-indicator-below",C=t.Decoration.line({class:v});return t.Decoration.set([C.range(w.from)])}return c.changes.empty?r:t.Decoration.none},provide(r){return t.EditorView.decorations.from(r)}}),s=t.EditorView.baseTheme({".morphic-drop-indicator-above":{boxShadow:"inset 0 2px 0 0 #5a86bc"},".morphic-drop-indicator-below":{boxShadow:"inset 0 -2px 0 0 #5a86bc"}});return[i,s]}buildValueSlotHighlightExtensions(t,e){const o=e.StateEffect.define();this.valueSlotHighlightEffect=o;const i=t.Decoration.mark({class:"morphic-value-slot-target"}),s=e.StateField.define({create(){return t.Decoration.none},update(c,a){for(const l of a.effects)if(l.is(o)){const d=l.value;if(!d)return t.Decoration.none;const u=a.state.doc.length,w=Math.max(0,Math.min(d.from,u)),v=Math.max(w,Math.min(d.to,u));return w===v?t.Decoration.none:t.Decoration.set([i.range(w,v)])}return a.changes.empty?c:t.Decoration.none},provide(c){return t.EditorView.decorations.from(c)}}),r=t.EditorView.baseTheme({".morphic-value-slot-target":{outline:"1px solid #5a86bc",outlineOffset:"1px",borderRadius:"2px"}});return[s,r]}buildHoverHighlightExtensions(t,e){const o=e.StateEffect.define();this.hoverHighlightEffect=o;const i=t.Decoration.mark({class:"morphic-hover-target"}),s=e.StateField.define({create(){return t.Decoration.none},update(c,a){for(const l of a.effects)if(l.is(o)){const d=l.value;if(!d)return t.Decoration.none;const u=a.state.doc.length,w=Math.max(0,Math.min(d.from,u)),v=Math.max(w,Math.min(d.to,u));return w===v?t.Decoration.none:t.Decoration.set([i.range(w,v)])}return a.changes.empty?c:t.Decoration.none},provide(c){return t.EditorView.decorations.from(c)}}),r=t.EditorView.baseTheme({".morphic-hover-target":{backgroundColor:"rgba(127, 127, 127, 0.10)",borderRadius:"2px"}});return[s,r]}setHoverHighlight(t){!this.editorView||!this.hoverHighlightEffect||this.editorView.dispatch({effects:this.hoverHighlightEffect.of(t)})}buildEditableHoverHighlightExtensions(t,e){const o=e.StateEffect.define();this.editableHoverHighlightEffect=o;const i=t.Decoration.mark({class:"morphic-editable-hover"}),s=e.StateField.define({create(){return t.Decoration.none},update(c,a){for(const l of a.effects)if(l.is(o)){const d=l.value;if(!d)return t.Decoration.none;const u=a.state.doc.length,w=Math.max(0,Math.min(d.from,u)),v=Math.max(w,Math.min(d.to,u));return w===v?t.Decoration.none:t.Decoration.set([i.range(w,v)])}return a.changes.empty?c:t.Decoration.none},provide(c){return t.EditorView.decorations.from(c)}}),r=t.EditorView.baseTheme({".morphic-editable-hover":{outline:"1px solid #5a86bc",outlineOffset:"1px",borderRadius:"2px"}});return[s,r]}setEditableHoverHighlight(t){!this.editorView||!this.editableHoverHighlightEffect||this.editorView.dispatch({effects:this.editableHoverHighlightEffect.of(t)})}show(){this.visible||(this.visible=!0,this.container.style.display="",this.syncNow(),this.attachSyncListener())}hide(){this.visible&&(this.visible=!1,this.container.style.display="none",this.detachSyncListener())}isVisible(){return this.visible}highlightLines(t){!this.editorView||!this.highlightEffect||this.editorView.dispatch({effects:this.highlightEffect.of(t)})}clearHighlight(){!this.editorView||!this.highlightEffect||this.editorView.dispatch({effects:this.highlightEffect.of(null)})}setHighlightColor(t){this.highlightColor=t}showDropIndicator(t,e="above"){!this.editorView||!this.dropIndicatorEffect||this.editorView.dispatch({effects:this.dropIndicatorEffect.of({line:t,position:e})})}hideDropIndicator(){!this.editorView||!this.dropIndicatorEffect||this.editorView.dispatch({effects:this.dropIndicatorEffect.of(null)})}showValueSlotHighlight(t,e){!this.editorView||!this.valueSlotHighlightEffect||this.editorView.dispatch({effects:this.valueSlotHighlightEffect.of({from:t,to:e})})}hideValueSlotHighlight(){!this.editorView||!this.valueSlotHighlightEffect||this.editorView.dispatch({effects:this.valueSlotHighlightEffect.of(null)})}getLineAtCoords(t,e){if(!this.editorView)return null;const o=this.editorView.posAtCoords({x:t,y:e});return o===null?null:this.editorView.state.doc.lineAt(o).number}charAtCoords(t,e){return this.editorView?this.editorView.posAtCoords({x:t,y:e})??null:null}getLineCount(){var t;return((t=this.editorView)==null?void 0:t.state.doc.lines)??0}isBelowLastLine(t){if(!this.editorView)return!1;const e=this.editorView.state.doc,o=e.line(e.lines).to,i=this.editorView.coordsAtPos(o);return i?t>i.bottom:!1}isInLowerHalfOfLine(t,e){if(!this.editorView)return!1;const o=this.editorView.state.doc;if(t<1||t>o.lines)return!1;const i=o.line(t),s=this.editorView.coordsAtPos(i.from),r=this.editorView.coordsAtPos(i.to);return!s||!r?!1:e>(s.top+r.bottom)/2}setTheme(t){if(!this.editorView||!this.cm||!this.themeCompartment)return;const e=we(this.cm.view,t);this.editorView.dispatch({effects:this.themeCompartment.reconfigure(e)})}setHighlightRules(t){if(!this.editorView||!this.cm||!this.syntaxHighlightCompartment)return;const e=Ae(this.cm.view,this.cm.state,t);this.editorView.dispatch({effects:this.syntaxHighlightCompartment.reconfigure(e)})}dispose(){var t;this.disposed=!0,this.detachSyncListener(),this.syncTimer!==void 0&&(clearTimeout(this.syncTimer),this.syncTimer=void 0),this.emptyClickListener&&this.editorView&&(this.editorView.scrollDOM.removeEventListener("click",this.emptyClickListener),this.emptyClickListener=void 0),(t=this.editorView)==null||t.destroy(),this.editorView=void 0,this.metadata=new Map,this.placeholders=[],this.lastCode=""}refresh(){this.syncNow()}getValue(){var t;return((t=this.editorView)==null?void 0:t.state.doc.toString())??this.lastCode??""}getCursorLine(){if(!this.editorView)return 1;const t=this.editorView.state.selection.main.head;return this.editorView.state.doc.lineAt(t).number}adjustZoom(t){if(!this.editorView||!this.cm||!this.themeCompartment)return;const e=this.options.theme??{},o=parseFloat(e.fontSize??$e.fontSize);t==="fit"?this.zoomFactor=1:t==="in"?this.zoomFactor=Math.min(4,this.zoomFactor*1.2):this.zoomFactor=Math.max(.25,this.zoomFactor/1.2);const i={...e,fontSize:`${(o*this.zoomFactor).toFixed(2)}px`},s=we(this.cm.view,i);this.editorView.dispatch({effects:this.themeCompartment.reconfigure(s)})}syncNow(){if(!this.editorView||!this.cm)return;const t=this.generateWithMetadata();if(t.code===this.lastCode)return;this.closePlaceholderEditor(),this.lastCode=t.code,this.metadata=t.metadata,this.placeholders=[...t.placeholders].sort((o,i)=>o.start-i.start);const e=[];this.metadataEffect&&e.push(this.metadataEffect.of(t.metadata)),this.placeholderEffect&&e.push(this.placeholderEffect.of(t.placeholders)),this.editorView.dispatch({changes:{from:0,to:this.editorView.state.doc.length,insert:t.code},effects:e.length>0?e:void 0})}scheduleDebouncedSync(){this.syncTimer!==void 0&&clearTimeout(this.syncTimer),this.syncTimer=setTimeout(()=>{this.syncTimer=void 0,this.syncNow()},jt)}attachSyncListener(){this.changeListener||(this.changeListener=t=>{Gt(t)&&this.scheduleDebouncedSync()},this.workspace.addChangeListener(this.changeListener))}detachSyncListener(){this.changeListener&&(this.workspace.removeChangeListener(this.changeListener),this.changeListener=void 0,this.syncTimer!==void 0&&(clearTimeout(this.syncTimer),this.syncTimer=void 0))}}const be="morphic:";function Ce(n){return be+n}function W(n){return n.startsWith(be)?n.slice(be.length):n}function G(n,t){return t.has(n)?Ce(n):n}function Kt(n,t,e,o){const i={behaviors:e,definitions:t};return Fe(K.javascriptGenerator,i,o,!1),K.javascriptGenerator.workspaceToCode(n)}function Yt(n,t,e,o){const i={behaviors:e,definitions:t};Fe(K.javascriptGenerator,i,o,!0);const s=K.javascriptGenerator.workspaceToCode(n);return ao(s)}const Jt="// __MORPHIC_BLOCK_START:",qt="// __MORPHIC_BLOCK_END:",He="__";function Fe(n,t,e,o=!1){n.STATEMENT_PREFIX=(e==null?void 0:e.statementPrefix)??null,n.STATEMENT_SUFFIX=(e==null?void 0:e.statementSuffix)??null,n.INFINITE_LOOP_TRAP=(e==null?void 0:e.infiniteLoopTrap)??null,e!=null&&e.reservedWords&&n.addReservedWords(e.reservedWords);for(const[i,s]of t.definitions){const r=lt(t.behaviors[i]);n.forBlock[Ce(i)]=(c,a)=>{const l=Zt(c,a),d=r?r(l):so(i,s);if(oo(c,s))return[io(d),K.Order.NONE];const u=no(d);return o?`${Jt}${c.id}${He}
4
- ${u}${qt}${c.id}${He}
5
- `:u}}}function Zt(n,t){var c;const e={},o={},i={},s=n.workspace.isFlyout?"toolbox":"workspace",r=Re(n)>=2;for(const a of n.inputList){const l=(c=a.connection)==null?void 0:c.targetBlock();if(l)if(l.outputConnection){const d=t.valueToCode(n,a.name,K.Order.NONE)||"undefined";e[a.name]=r?Qt(d,l):d}else e[a.name]=t.statementToCode(n,a.name).trimEnd();for(const d of a.fieldRow){if(!d.name)continue;const u=String(d.getValue()??"");o[d.name]=u,i[d.name]=JSON.stringify(u)}}return{blockId:n.id,blockType:W(n.type),mode:Ct(n)??"default",context:s,inputs:e,fields:o,quoted:i}}function Qt(n,t){return!eo(t)||to(n)?n:`(${n})`}function eo(n){return Re(n)>0}function Re(n){return n.inputList.filter(t=>{var e;return((e=t.connection)==null?void 0:e.type)===L.INPUT_VALUE}).length}function to(n){if(!n.startsWith("(")||!n.endsWith(")"))return!1;let t=0;for(let e=0;e<n.length;e++){const o=n[e];if(o==="(")t++;else if(o===")"&&(t--,t===0))return e===n.length-1}return!1}function oo(n,t){return n.outputConnection?!0:t.output===!1?!1:t.output!==void 0}function no(n){const t=n.trim();return t?t.endsWith(";")||t.endsWith("}")||t.endsWith(`
6
- `)?`${t}
7
- `:`${t};
8
- `:""}function io(n){const t=n.trim();return t?t.endsWith(";")?t.slice(0,-1):t:"undefined"}function so(n,t){return t.output!==void 0&&t.output!==!1?"undefined":`// No generator behavior defined for "${n}"`}const ro=/^\s*\/\/ __MORPHIC_BLOCK_START:(.+)__$/,co=/^\s*\/\/ __MORPHIC_BLOCK_END:(.+)__$/;function ao(n){const t=n.split(`
9
- `),e=[],o=new Map,i=new Map;let s=0;for(const r of t){const c=r.match(ro);if(c){i.set(c[1],s+1);continue}const a=r.match(co);if(a){const l=a[1],d=i.get(l);d!==void 0&&(o.set(l,{startLine:d,endLine:s}),i.delete(l));continue}e.push(r),s++}return{code:e.join(`
10
- `),metadata:o,placeholders:[]}}function de(n,t={}){for(const e of n.elements)if(U(t[e])==="code")return e}function Ee(n,t,e={},o=[]){const i=n.elements,s=o.find(c=>c.name===t);if(s){for(const c of s.elements)if(U(e[c])==="code"&&i[c]!==void 0)return{mode:t,template:i[c],elementName:c,inputSlots:n.inputSlots}}for(const[c,a]of Object.entries(i))if(U(e[c])==="code")return{mode:t,template:a,elementName:c,inputSlots:n.inputSlots};if(i.block!==void 0)return{mode:t,template:i.block,elementName:"block",inputSlots:n.inputSlots};const r=Object.entries(i)[0];if(r===void 0)throw new Error(`Block "${n.identifier}" does not have any elements.`);return{mode:t,template:r[1],elementName:r[0],inputSlots:n.inputSlots}}function _(n,t){if(t.length===0)return;if(n.indent===""||!t.includes(`
11
- `)){n.output+=t;return}const e=t.split(`
12
- `);n.output+=e[0];for(let o=1;o<e.length;o++)n.output+=`
13
- `+n.indent+e[o]}function Se(n,t,e,o,i,s){const r={output:"",metadata:new Map,placeholders:[],indent:""},c={mode:t,definitions:e,elementTypes:o,modeDefs:i,elementOverride:s};let a=!0;for(const l of n.getTopBlocks(!0)){const d=r.output.length;a||(r.output+=`
14
- `),_e(l,c,r),r.output.length===d+(a?0:1)?r.output=r.output.slice(0,d):a=!1}return{code:r.output,metadata:r.metadata,placeholders:r.placeholders}}function _e(n,t,e){const o=1+e.indent.length;let i=n,s=!0;for(;i;){const r=e.output.length;s||_(e,`
15
- `),Ve(i,t,e),e.output.length===r+(s?0:o)?e.output=e.output.slice(0,r):s=!1,i=i.getNextBlock()}}function lo(n){return n.inputList.some(t=>{var e;return((e=t.connection)==null?void 0:e.type)===L.INPUT_VALUE})}function ho(n,t){var o;let e=0;for(const i of n){if(i.kind!=="placeholder")continue;const s=(o=t.inputSlots)==null?void 0:o[String(i.index)];((s==null?void 0:s.kind)??"value")==="value"&&e++}return e}function Ve(n,t,e,o=!1){var p,y,S;const i=t.definitions.get(W(n.type));if(!i){const h=e.output.length,f=J(e.output);if(uo(n,e),e.output.length===h)return;const x=J(e.output),B=e.output.endsWith(`
16
- `)?Math.max(f,x-1):x;let b=e.output.length;for(;b>h&&e.output[b-1]===`
17
- `;)b--;const I=he(n);e.metadata.set(n.id,{startLine:f,endLine:B,startChar:h,endChar:b,atomic:!!I}),Q(e,h,"set",I??void 0);return}let s,r;if(t.elementOverride){const h=i.elements[t.elementOverride];if(h===void 0)return;s=h,r=t.elementOverride}else try{const h=Ee(i,t.mode,t.elementTypes,t.modeDefs);s=h.template,r=h.elementName}catch{return}const c=r?t.elementTypes[r]:void 0,a=e.output.length;o&&_(e,"(");const l=e.output.length,d=J(e.output),u={},w=q(s),v=ho(w,i)>=2;for(const h of w){if(h.kind==="text"){_(e,h.value);continue}if(h.kind==="field"){const $=n.getField(h.name);if(!$)continue;const V=e.output.length;_(e,We(i,r,h.name,$));const T=ze(n,$,h.name);T&&Q(e,V,"set",T);continue}if(h.kind==="image")continue;const f=(p=i.inputSlots)==null?void 0:p[String(h.index)],x=f==null?void 0:f.name;if(!x)continue;const B=n.getInput(x),b=((y=B==null?void 0:B.connection)==null?void 0:y.targetBlock())??null,I=b!=null&&b.isShadow()?null:b;if((f==null?void 0:f.kind)==="statement"){const $=J(e.output),V=e.indent,T=e.output.lastIndexOf(`
18
- `)+1;e.indent=((S=/^[ \t]*/.exec(e.output.slice(T)))==null?void 0:S[0])??"",I&&_e(I,t,e),e.indent=V;const M=J(e.output),N=e.output.endsWith(`
19
- `)?Math.max($,M-1):M;u[x]={startLine:$,endLine:N};continue}let D=!1;if(!I){const $=b!=null&&b.isShadow()?b.inputList.flatMap(P=>P.fieldRow).filter(P=>!!P.name):[],V=!(b!=null&&b.isShadow())&&B?B.fieldRow.filter(P=>{var z;return!!P.name&&!((z=i.fields)!=null&&z[P.name])}):[],T=$.length>0||V.length>0,M=T?fo(f,c):void 0;M&&_(e,M);const N=e.output.length;if($.length>0){const P=b?t.definitions.get(W(b.type)):void 0;for(const z of $)_(e,P&&z.name?We(P,r,z.name,z):ue(z))}else if(V.length>0)for(const P of V){const z=e.output.length;_(e,ue(P));const ct=ze(n,P,P.name);ct&&(Q(e,z,"set",ct),D=!0)}let F;if(T||(_(e,po(f==null?void 0:f.check)),F={parentBlockId:n.id,inputName:x}),!D){const P=b!=null&&b.isShadow()?he(b)??void 0:void 0;Q(e,N,"default",P,F)}M&&_(e,M);continue}const j=e.output.length;Ve(I,t,e,v&&lo(I)),Q(e,j,"set",he(I)??void 0)}if(e.output.length===l){e.output=e.output.slice(0,a);return}o&&_(e,")");const C=J(e.output),E=e.output.endsWith(`
20
- `)?Math.max(d,C-1):C;let k=e.output.length;for(;k>a&&e.output[k-1]===`
21
- `;)k--;const m={startLine:d,endLine:E,startChar:a,endChar:k};Object.keys(u).length>0&&(m.statementSlots=u),he(n)&&(m.atomic=!0),e.metadata.set(n.id,m)}function uo(n,t){for(const e of n.inputList)for(const o of e.fieldRow)o.name&&_(t,ue(o))}function Q(n,t,e,o,i){const s=n.output.length;if(s>t){const r={start:t,end:s,kind:e};o&&(r.edit=o),i&&(r.emptySlot=i),n.placeholders.push(r)}}function po(n){const t=Array.isArray(n)?n[0]:n;return t?`[${{Number:"NUMBER",String:"TEXT",Boolean:"BOOL"}[t]??t.toUpperCase()}]`:"[VALUE]"}function fo(n,t){if(!(!(n!=null&&n.check)||(Array.isArray(n.check)?n.check[0]:n.check)!=="String")&&!(!t||typeof t=="string"))return t.stringQuote}function ze(n,t,e){let o,i;if(t instanceof L.FieldNumber)o="number";else if(t instanceof L.FieldDropdown){o="dropdown";const s=t.getOptions();Array.isArray(s)&&(i=s.filter(r=>Array.isArray(r)&&r.length>=2).map(([r,c])=>[String(r),String(c)]))}else if(t instanceof L.FieldTextInput)o="text";else return null;return{blockId:n.id,fieldName:e,fieldType:o,options:i}}function he(n){let t=null,e=null,o=0;for(const c of n.inputList){if(c.connection&&c.connection.type===L.INPUT_VALUE)return null;for(const a of c.fieldRow)a.name&&(o++,t=a.name,e=a)}if(o!==1||!t||!e)return null;const i=e.constructor.name;let s="text",r;if(i.includes("Number"))s="number";else if(i.includes("Dropdown")){s="dropdown";const c=e.getOptions;if(typeof c=="function"){const a=c.call(e);Array.isArray(a)&&(r=a.filter(l=>Array.isArray(l)&&l.length>=2).map(([l,d])=>[String(l),String(d)]))}}return{blockId:n.id,fieldName:t,fieldType:s,options:r}}function We(n,t,e,o){var s,r;const i=(s=n.fields)==null?void 0:s[e];if((i==null?void 0:i.type)==="dropdown"&&t){const c=String(o.getValue());for(const a of i.options)if(!(typeof a!="object"||Array.isArray(a))&&a.value===c)return((r=a.display)==null?void 0:r[t])??c}return ue(o)}function ue(n){if(!n)return"";if(n instanceof L.FieldDropdown)return String(n.getValue());const t=n.getText;return typeof t=="function"?t.call(n):String(n.getValue())}function J(n){let t=1;for(let e=0;e<n.length;e++)n[e]===`
22
- `&&t++;return t}const mo="rgba(255, 255, 255, 0.07)";class go{constructor(t,e,o={}){g(this,"workspace");g(this,"editors");g(this,"blockToCode");g(this,"codeToBlock");g(this,"blockListener");g(this,"cursorCallbacks",new Map);g(this,"emptyClickCallbacks",new Map);g(this,"guard",!1);this.workspace=t,this.editors=Array.isArray(e)?[...e]:[e],this.blockToCode=o.blockToCode!==!1,this.codeToBlock=o.codeToBlock!==!1;const i=o.highlightColor??mo;for(const s of this.editors)s.setHighlightColor(i)}enable(){this.blockToCode&&this.attachBlockListener(),this.codeToBlock&&this.attachCursorListeners()}disable(){this.detachBlockListener(),this.detachCursorListeners();for(const t of this.editors)t.clearHighlight()}attachBlockListener(){this.blockListener||(this.blockListener=t=>{if(t.type!=="selected"||this.guard)return;const e=t.newElementId??void 0;this.guard=!0,this.broadcastHighlight(e),this.guard=!1},this.workspace.addChangeListener(this.blockListener))}detachBlockListener(){this.blockListener&&(this.workspace.removeChangeListener(this.blockListener),this.blockListener=void 0)}broadcastHighlight(t){for(const e of this.editors){if(!t){e.clearHighlight();continue}const o=this.computeOwnSpans(t,e.metadata);o?e.highlightLines(o):e.clearHighlight()}}attachCursorListeners(){for(const t of this.editors){if(!this.cursorCallbacks.has(t)){const e=o=>{if(this.guard)return;const i=this.findBlockAtLine(o,t.metadata);if(!i){this.clearAll();return}const s=this.workspace.getBlockById(i);s&&L.common.getSelected()!==s&&(this.guard=!0,L.common.setSelected(s),this.broadcastHighlight(i),this.guard=!1)};this.cursorCallbacks.set(t,e),t.onCursorLine=e}if(!this.emptyClickCallbacks.has(t)){const e=()=>{this.guard||this.clearAll()};this.emptyClickCallbacks.set(t,e),t.onEmptyClick=e}}}detachCursorListeners(){for(const[t,e]of this.cursorCallbacks)t.onCursorLine===e&&(t.onCursorLine=void 0);this.cursorCallbacks.clear();for(const[t,e]of this.emptyClickCallbacks)t.onEmptyClick===e&&(t.onEmptyClick=void 0);this.emptyClickCallbacks.clear()}clearAll(){this.guard=!0,L.common.setSelected(null);for(const t of this.editors)t.clearHighlight();this.guard=!1}computeOwnSpans(t,e){const o=e.get(t);if(!o)return;const i=[];for(const[c,a]of e)c!==t&&a.startLine>=o.startLine&&a.endLine<=o.endLine&&i.push(a);if(i.length===0)return[{fromLine:o.startLine,toLine:o.endLine}];i.sort((c,a)=>c.startLine-a.startLine);const s=[];let r=o.startLine;for(const c of i)r<c.startLine&&s.push({fromLine:r,toLine:c.startLine-1}),r=Math.max(r,c.endLine+1);return r<=o.endLine&&s.push({fromLine:r,toLine:o.endLine}),s.length>0?s:void 0}findBlockAtLine(t,e){let o;for(const[i,s]of e)if(t>=s.startLine&&t<=s.endLine){const r=s.endLine-s.startLine;(!o||r<o.size)&&(o={id:i,size:r})}return o==null?void 0:o.id}}const je={statement:{above:!0,below:!0},start:{above:!1,below:!0},end:{above:!0,below:!1},standalone:{above:!1,below:!1}},Ue=Object.keys(je);function ko(n){return n.map(t=>{const e=t.shape?je[t.shape]:void 0;if(!e)return t;const o={...t};return e.above&&o.previousStatement===void 0&&(o.previousStatement=!0),e.below&&o.nextStatement===void 0&&(o.nextStatement=!0),o})}const pe="default";function vo(n,t){const e=Object.keys(t).filter(o=>U(t[o])==="code");return n.map(o=>{var a;const i=(a=o.elements)==null?void 0:a[pe];if(i===void 0||e.length===0)return o;const{[pe]:s,...r}=o.elements,c={...r};for(const l of e)c[l]===void 0&&(c[l]=i);return{...o,elements:c}})}function wo(n){const t=new Map,e=Array.isArray(n)?n:[n];for(const o of e)yo(o,t),t.set(o.identifier,o);return t}function yo(n,t){if(!n.identifier.trim())throw new Error("Each block definition must include a non-empty identifier.");if(Object.keys(n.elements).length===0)throw new Error(`Block "${n.identifier}" must define at least one element.`);if(t.has(n.identifier))throw new Error(`Duplicate block identifier "${n.identifier}".`)}const bo=4/3,Co={normal:"400",bold:"700"},Ge=n=>Co[n]??n;function Eo(n){const t=parseFloat(n);if(!Number.isFinite(t)||t<=0)return;const e=n.trim().endsWith("pt")?t:t/bo;return Math.round(e*100)/100}function Xe(n){const t=n.getRenderer().getConstants();return{family:t.FIELD_TEXT_FONTFAMILY,size:t.FIELD_TEXT_FONTSIZE,weight:Ge(t.FIELD_TEXT_FONTWEIGHT)}}function Ke(n,t,e){const o=document.createElement("div");o.setAttribute("aria-hidden","true"),o.style.cssText="position:absolute;visibility:hidden;width:0;height:0;overflow:hidden;";let i=o;for(const l of t){const d=document.createElement("div");d.className=l.join(" "),i.appendChild(d),i=d}const s=document.createElementNS("http://www.w3.org/2000/svg","svg"),r=document.createElementNS("http://www.w3.org/2000/svg","text");r.setAttribute("class","blocklyText"),s.appendChild(r),i.appendChild(s),n.appendChild(o);const c=getComputedStyle(r),a={family:c.fontFamily||e.family,size:Eo(c.fontSize)??e.size,weight:c.fontWeight?Ge(c.fontWeight):e.weight};return o.remove(),a}const So=(n,t)=>n.family===t.family&&n.size===t.size&&n.weight===t.weight,xe=new Map;function xo(n,t){const e=`${n.name}
23
- ${t.family}
24
- ${t.size}
25
- ${t.weight}`;let o=xe.get(e);if(!o){const i=`${n.name}-morphic-font-${xe.size+1}`;o=L.Theme.defineTheme(i,{name:i,base:n,fontStyle:{family:t.family,size:t.size,weight:t.weight},...n.startHats!==void 0&&{startHats:n.startHats}}),xe.set(e,o)}return o}function Ye(n,t,e,o){const i=So(o,e)?t:xo(t,o);return n.getTheme()===i?!1:(n.setTheme(i),!0)}function Je(n){for(const t of n.getAllBlocks(!1)){t.markDirty();for(const e of t.inputList)for(const o of e.fieldRow)o.getConstants()}n.render()}function qe(n){var m,p,y,S;const{definitions:t,elementTypes:e,behaviors:o,modes:i,presets:s,highlighting:r,categories:c}=n,a=[],l=[],d=new Set(Object.keys(e)),u=new Set(Object.keys(e).filter(h=>U(e[h])==="code")),w=new Set((c??[]).map(h=>h.name));d.has(pe)&&a.push(`elementTypes declares "${pe}", which is reserved for a block's fallback template. Rename the element.`);const v=h=>t.has(h)||L.Blocks[h]!==void 0;for(const h of t.values()){const f=h.identifier;if(h.shape!==void 0)if(!Ue.includes(h.shape))a.push(`Block "${f}": unknown shape "${h.shape}". Use one of: ${Ue.join(", ")}.`);else{const T=N=>N!==void 0&&N!==!1,M=[];T(h.output)&&M.push("it also has an output, which makes it a value block"),(h.shape==="start"||h.shape==="standalone")&&T(h.previousStatement)&&M.push("it also connects above (previousStatement)"),(h.shape==="end"||h.shape==="standalone")&&T(h.nextStatement)&&M.push("it also connects below (nextStatement)"),h.shape==="statement"&&(h.previousStatement===!1||h.nextStatement===!1)&&M.push("a connection flag is set to false");for(const N of M)l.push(`Block "${f}": shape "${h.shape}" contradicts its flags: ${N}. The flags win.`)}const x=te(o[f]),B=!!(x!=null&&x.onViewApplied);for(const T of Object.keys(h.elements))d.has(T)||l.push(`Block "${f}": element "${T}" is not declared in elementTypes — it renders with no known type.`);const b=new Map,I=new Set,D=new Set;for(const[T,M]of Object.entries(h.elements)){if(!u.has(T))continue;const N=new Set;for(const F of q(M))F.kind==="placeholder"?(N.add(F.index),I.add(F.index)):F.kind==="field"&&D.add(F.name);b.set(T,N)}const j=[...b.entries()];if(j.length>1){const[T,M]=j[0];for(const[N,F]of j.slice(1))To(M,F)||a.push(`Block "${f}": code elements "${T}" and "${N}" use different placeholders (${tt(M)} vs ${tt(F)}). All code elements must share the same %N set, or an input disappears when switching to the differing mode.`)}const $=new Set(Object.keys(h.inputSlots??{}).map(T=>Number(T)).filter(T=>Number.isInteger(T)));for(const T of I)(m=h.inputSlots)!=null&&m[String(T)]||l.push(`Block "${f}": placeholder %${T} has no inputSlots["${T}"] entry — the input is auto-named ARG${T} and can't be read by name in behaviors.`);for(const T of $)I.has(T)||l.push(`Block "${f}": inputSlots["${T}"] has no matching %${T} placeholder in any code element — the config is ignored.`);const V=new Set(Object.keys(h.fields??{}));for(const T of D)!((p=h.fields)!=null&&p[T])&&!B&&a.push(`Block "${f}": field token %${T} has no fields["${T}"] entry and the block has no onViewApplied behavior to create it — the field will never appear.`);for(const T of V)D.has(T)||l.push(`Block "${f}": fields["${T}"] has no matching %${T} token in any code element — the config is ignored.`);for(const[T,M]of Object.entries(h.fields??{}))if((M==null?void 0:M.type)==="dropdown"){for(const N of M.options)if(!(typeof N!="object"||Array.isArray(N)||!N.display))for(const F of Object.keys(N.display))u.has(F)||l.push(`Block "${f}": fields["${T}"] option "${N.value}" has display for "${F}", which is not a code element — that entry never applies.`)}h.category!==void 0&&w.size>0&&!w.has(h.category)&&l.push(`Block "${f}": category "${h.category}" is not declared in categories — the block loses its colour and grouping.`);for(const[T,M]of Object.entries(h.inputSlots??{}))(M==null?void 0:M.kind)!==void 0&&!Qe.includes(M.kind)&&a.push(`Block "${f}": inputSlots["${T}"] has unknown kind "${M.kind}". Use one of: ${Qe.join(", ")}.`);for(const[T,M]of Object.entries(h.fields??{}))et.includes(M==null?void 0:M.type)||a.push(`Block "${f}": fields["${T}"] has unknown type "${M==null?void 0:M.type}". Use one of: ${et.join(", ")}.`);for(const[T,M]of Object.entries(h.inputSlots??{}))k((y=M==null?void 0:M.default)==null?void 0:y.shadow,`Block "${f}": inputSlots["${T}"].default.shadow`),k((S=M==null?void 0:M.default)==null?void 0:S.placeholder,`Block "${f}": inputSlots["${T}"].default.placeholder`)}for(const[h,f]of Object.entries(e)){const x=U(f);Ze.includes(x)||a.push(`elementTypes."${h}": unknown type "${x}". Use one of: ${Ze.join(", ")}.`)}for(const[h,f]of Object.entries(e)){if(typeof f=="string")continue;const x=f.empty;if(x)for(const[B,b]of Object.entries(x))k(b.shadow,`elementTypes.${h}.empty.${B}.shadow`),k(b.placeholder,`elementTypes.${h}.empty.${B}.placeholder`)}for(const[h,f]of Object.entries(e)){if(typeof f=="string")continue;const x=f.type;f.size!==void 0&&x!=="image"&&l.push(`elementTypes."${h}": "size" applies only to image elements — ignored for a ${x} element.`),f.stringQuote!==void 0&&x!=="code"&&l.push(`elementTypes."${h}": "stringQuote" applies only to code elements — ignored for a ${x} element.`),f.empty!==void 0&&x!=="code"&&l.push(`elementTypes."${h}": "empty" applies only to code elements — ignored for a ${x} element.`)}for(const h of i??[])for(const f of h.elements)d.has(f)||l.push(`Mode "${h.name}": element "${f}" is not declared in elementTypes — it renders nothing.`);for(const h of Object.keys(r??{}))u.has(h)||l.push(`highlighting["${h}"] is not a code element — its rules will never apply.`);const C=new Map,E=(h,f)=>{const x=C.get(h)??new Set;x.add(f),C.set(h,x)};for(const h of d)E(h,"element");for(const h of i??[])E(h.name,"mode");for(const h of s??[])E(h.name,"preset");for(const[h,f]of C)f.size>1&&l.push(`Name "${h}" is used as ${[...f].sort().join(" and ")} — reusing a name across element / mode / preset is allowed but confusing; consider distinct names.`);return{errors:a,warnings:l};function k(h,f){!h||v(h)||a.push(`${f}: "${h}" is neither a defined block nor a registered Blockly block type.`)}}const Ze=["text","code","image"],Qe=["value","statement"],et=["dropdown","text","number","checkbox"];function To(n,t){if(n.size!==t.size)return!1;for(const e of n)if(!t.has(e))return!1;return!0}function tt(n){const t=[...n].sort((e,o)=>e-o);return t.length?t.map(e=>`%${e}`).join(" "):"(none)"}class Lo{ensureModeVisibilityStyles(t){const e=['[class^="morphic-element-"] { display: none; }'];for(const o of t){const i=H(o.name);for(const s of o.elements){const r=H(s);e.push(`.morphic-mode-${i} > .morphic-element-${r} { display: block; }`)}}fe("mode-visibility",e.join(`
26
- `))}ensureStyles(t,e){this.ensureStyleBundle(t,"base");for(const o of e)this.ensureStyleBundle(o,`mode:${o.mode}`)}async ensureToolbarStyles(){const t=await Promise.resolve().then(()=>Jo);fe("toolbar",t.default)}ensureCategoryStyles(t){for(const e of t){if(!e.color)continue;const o=H(e.name);fe(`category:${o}`,`.morphic-category-${o} { --morphic-category-color: ${e.color}; }`)}}validateModeCoverage(t,e){const o=new Set(t.map(s=>s.mode)),i=e.filter(s=>!o.has(s));i.length>0&&console.warn(`[MorphicBlocks] Modes without explicit CSS definition: ${i.join(", ")}.`)}ensureStyleBundle(t,e){t&&(t.href&&Bo(e,t.href),t.cssText&&fe(e,t.cssText))}}function fe(n,t){for(const o of Array.from(document.head.querySelectorAll("style[data-morphic-source]")))if(o.dataset.morphicSource===n&&o.textContent===t)return;const e=document.createElement("style");e.dataset.morphicSource=n,e.textContent=t,document.head.appendChild(e)}function Bo(n,t){for(const o of Array.from(document.head.querySelectorAll("link[data-morphic-source]")))if(o.getAttribute("href")===t)return;const e=document.createElement("link");e.rel="stylesheet",e.href=t,e.dataset.morphicSource=n,document.head.appendChild(e)}const ee="morphic/block-type";class ot{constructor(t){g(this,"container");g(this,"workspaceContainer");g(this,"workspace");g(this,"definitions");g(this,"blockColors");g(this,"behaviors");g(this,"elementTypes");g(this,"options");g(this,"modes");g(this,"currentMode");g(this,"renderOverride");g(this,"previewWorkspace");g(this,"onPreviewWorkspace");g(this,"previewContainer");g(this,"previewBase");g(this,"onDragOver");g(this,"onDrop");this.container=t.container,this.workspaceContainer=t.workspaceContainer,this.workspace=t.workspace,this.onPreviewWorkspace=t.onPreviewWorkspace,this.definitions=t.definitions,this.blockColors=t.blockColors,this.behaviors=t.behaviors,this.elementTypes=t.elementTypes??{},this.currentMode=t.mode,this.renderOverride=t.render,this.modes=t.modes??[],this.options=t.options??{},this.onDragOver=e=>{var o;(o=e.dataTransfer)!=null&&o.types.includes(ee)&&e.preventDefault()},this.onDrop=e=>{var i;const o=(i=e.dataTransfer)==null?void 0:i.getData(ee);o&&(e.preventDefault(),this.createBlockAtPosition(o,e.clientX,e.clientY))},this.workspaceContainer.addEventListener("dragover",this.onDragOver),this.workspaceContainer.addEventListener("drop",this.onDrop),this.render()}rerender(t,e){this.currentMode=t,this.renderOverride=e,this.render()}dispose(){var t;this.workspaceContainer.removeEventListener("dragover",this.onDragOver),this.workspaceContainer.removeEventListener("drop",this.onDrop),this.container.innerHTML="",this.previewWorkspace&&(this.previewWorkspace.dispose(),this.previewWorkspace=void 0,this.previewBase=void 0),(t=this.previewContainer)!=null&&t.parentNode&&(this.previewContainer.parentNode.removeChild(this.previewContainer),this.previewContainer=void 0)}render(){if(this.container.innerHTML="",this.options.modeLabel!==!1){const i=document.createElement("div");i.className="morphic-toolbox-header";const s=document.createElement("span");s.className="morphic-toolbar-label",s.textContent=`Mode: ${this.currentMode}`,i.appendChild(s),this.container.appendChild(i)}const t=this.resolveBlockIds(),e=this.options.categories??[];if(e.length===0){for(const i of t){const s=this.definitions.get(i);s&&this.container.appendChild(this.createTile(s))}return}const o=new Set;for(const i of e){const s=this.resolveCategoryBlockIds(i,t);if(s.length===0)continue;const r=document.createElement("div");r.setAttribute("data-category",H(i.name)),i.color&&r.style.setProperty("--morphic-category-color",i.color);for(const c of s){const a=this.definitions.get(c);a&&(r.appendChild(this.createTile(a)),o.add(c))}this.container.appendChild(r)}for(const i of t)if(!o.has(i)){const s=this.definitions.get(i);s&&this.container.appendChild(this.createTile(s))}}createTile(t){var d;const e=H(this.currentMode),o=H(t.identifier),i=this.blockColors.get(t.identifier),s=document.createElement("div");s.setAttribute("draggable","true"),s.setAttribute("data-block-type",t.identifier),s.className=`morphic-block morphic-mode-${e} morphic-block-${o}`,i&&s.style.setProperty("--morphic-block-color",i);const r=this.modes.find(u=>u.name===this.currentMode),c=(r==null?void 0:r.elements)??[],a=Object.entries(t.elements),l=[...c.map(u=>a.find(([w])=>w===u)).filter(u=>u!==void 0),...a.filter(([u])=>!c.includes(u))];for(const[u,w]of l){const v=document.createElement("div");v.className=`morphic-element-${H(u)}`;const C=this.elementTypes[u],E=U(C),k=E==="code",m=E==="image",p=((d=this.renderOverride)==null?void 0:d[u])??(k?"block":"text"),y=m?wt(w,ft(C)):w;if(k&&p==="block"){this.syncPreviewFont(u);const S=this.createBlockPreviewSvg(t,this.currentMode);S?v.appendChild(S):v.innerHTML=Me(q(y))}else v.innerHTML=Me(q(y));s.appendChild(v)}return s.addEventListener("dragstart",u=>{var w;(w=u.dataTransfer)==null||w.setData(ee,t.identifier)}),s}ensurePreviewWorkspace(){var e;if(this.previewWorkspace)return this.previewWorkspace;this.previewContainer=document.createElement("div"),this.previewContainer.style.cssText="position:absolute;left:-9999px;top:-9999px;width:800px;height:600px;overflow:hidden;",document.body.appendChild(this.previewContainer);const t=this.workspace.options;return this.previewWorkspace=L.inject(this.previewContainer,{scrollbars:!1,media:t.pathToMedia,sounds:!1,renderer:t.renderer,rendererOverrides:t.rendererOverrides??void 0,theme:t.theme,rtl:t.RTL}),(e=this.onPreviewWorkspace)==null||e.call(this,this.previewWorkspace),this.previewWorkspace}syncPreviewFont(t){const e=this.ensurePreviewWorkspace();this.previewBase??(this.previewBase={theme:e.getTheme(),font:Xe(e)});const o=Ke(this.container,[["morphic-block",`morphic-mode-${H(this.currentMode)}`],[`morphic-element-${H(t)}`]],this.previewBase.font);Ye(e,this.previewBase.theme,this.previewBase.font,o)}createBlockPreviewSvg(t,e){var o;try{const i=this.ensurePreviewWorkspace(),s=i.newBlock(G(t.identifier,this.definitions)),r=this.blockColors.get(t.identifier);r&&s.setColour(r);const c=Ee(t,e,this.elementTypes,this.modes);De({block:s,definition:t,view:c,mode:"block",context:"toolbox"});const a=te(this.behaviors[t.identifier]);(o=a==null?void 0:a.onViewApplied)==null||o.call(a,s,{Blockly:L,workspace:i,mode:e,context:"toolbox",definition:t}),s.initSvg(),s.render();const l=s.getSvgRoot();if(!l)return s.dispose(!1),null;const d=l.getBBox(),u=l.cloneNode(!0),w=4,v=document.createElementNS("http://www.w3.org/2000/svg","svg");return v.setAttribute("width",String(Math.ceil(d.width+w*2))),v.setAttribute("height",String(Math.ceil(d.height+w*2))),v.setAttribute("viewBox",`${d.x-w} ${d.y-w} ${d.width+w*2} ${d.height+w*2}`),v.appendChild(u),s.dispose(!1),v}catch{return null}}createBlockAtPosition(t,e,o){const i=this.workspace,s=i.getInjectionDiv().getBoundingClientRect(),r=(e-s.left-i.scrollX)/i.scale,c=(o-s.top-i.scrollY)/i.scale,a=i.newBlock(G(t,this.definitions));a.initSvg(),a.render(),a.moveTo(new L.utils.Coordinate(r,c))}resolveBlockIds(){return this.options.blocks??[...this.definitions.keys()]}resolveCategoryBlockIds(t,e){return t.blocks&&t.blocks.length>0?t.blocks.filter(o=>e.includes(o)):e.filter(o=>{var i,s;return((s=(i=this.definitions.get(o))==null?void 0:i.category)==null?void 0:s.toLowerCase())===t.name.toLowerCase()})}}function Te(n,t){var o;if(n.blocks&&n.blocks.length>0)return n.blocks;const e=[];for(const i of t.values())((o=i.category)==null?void 0:o.toLowerCase())===n.name.toLowerCase()&&e.push(i.identifier);return e}function nt(n,t){var i,s,r;if((n.kind??((i=n.categories)!=null&&i.length?"categoryToolbox":"flyoutToolbox"))==="categoryToolbox")return{kind:"categoryToolbox",contents:(n.categories??[]).map(a=>({kind:"category",name:a.name,colour:a.color,contents:Te(a,t).map(l=>({kind:"block",type:G(l,t)}))}))};if((s=n.categories)!=null&&s.length){const c=n.categories,a=[];return c.forEach((d,u)=>{const w=H(d.name);a.push({kind:"label",id:`morphic-category-${w}`,text:d.name,"web-class":`morphic-flyout-category-label morphic-category-${w}`});for(const v of it(Te(d,t)))a.push({kind:"block",type:G(v,t)});u<c.length-1&&a.push({kind:"sep",gap:14})}),{kind:"flyoutToolbox",contents:a}}return{kind:"flyoutToolbox",contents:(n.blocks??it(((r=n.categories)==null?void 0:r.flatMap(c=>Te(c,t)))??[...t.keys()])).map(c=>({kind:"block",type:G(c,t)}))}}function it(n){return n.filter((t,e,o)=>o.indexOf(t)===e)}const Mo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="4" y="4" width="9" height="10" rx="1.5"/><path d="M3 11V3a1 1 0 0 1 1-1h7"/></svg>',Io='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 3h6v2H5z"/><path d="M4 3H3a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V4a1 1 0 0 0-1-1h-1"/></svg>',Do='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8h7a3 3 0 0 1 0 6H6"/><polyline points="5 5 2 8 5 11"/></svg>',Ao='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M13 8H6a3 3 0 0 0 0 6h4"/><polyline points="11 5 14 8 11 11"/></svg>',Oo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 4 13 4"/><path d="M5 4V3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v1"/><path d="M4 4l1 9a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1l1-9"/></svg>',No='<svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor"><polygon points="4,3 13,8 4,13"/></svg>',$o='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="7" r="4"/><line x1="10" y1="10" x2="14" y2="14"/><line x1="5" y1="7" x2="9" y2="7"/><line x1="7" y1="5" x2="7" y2="9"/></svg>',Po='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="7" r="4"/><line x1="10" y1="10" x2="14" y2="14"/><line x1="5" y1="7" x2="9" y2="7"/></svg>',Ho='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 3 3 6 3"/><polyline points="13 6 13 3 10 3"/><polyline points="3 10 3 13 6 13"/><polyline points="13 10 13 13 10 13"/></svg>',Fo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 2h8l2 2v10H3z"/><rect x="5" y="2" width="6" height="4"/><rect x="5" y="9" width="6" height="4"/></svg>',Ro='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8v5a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V8"/><polyline points="5 5 8 2 11 5"/><line x1="8" y1="2" x2="8" y2="10"/></svg>',_o='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8a5 5 0 1 0 1.5-3.5"/><polyline points="3 2 3 5 6 5"/></svg>',Vo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2 8s2-4 6-4 6 4 6 4-2 4-6 4-6-4-6-4z"/><circle cx="8" cy="8" r="1.5"/></svg>',O={modeLabel(){return{id:"mode-label",render:n=>{const t=document.createElement("span");return t.className="morphic-toolbar-label",t.textContent=zo(n),t}}},copy(){return{id:"copy",label:"Copy",title:"Copy block",icon:Mo,onClick:n=>{n.engine.copyActiveBlock(n.pane)}}},paste(){return{id:"paste",label:"Paste",title:"Paste block",icon:Io,disabled:n=>!n.engine.hasClipboardContents(),onClick:n=>{n.engine.pasteActiveBlock(n.pane)}}},undo(){return{id:"undo",label:"Undo",title:"Undo (block model)",icon:Do,onClick:n=>{var t;(t=n.engine.getWorkspace())==null||t.undo(!1)},disabled:n=>{var t;return!((t=n.engine.getWorkspace())!=null&&t.getUndoStack().length)}}},redo(){return{id:"redo",label:"Redo",title:"Redo (block model)",icon:Ao,onClick:n=>{var t;(t=n.engine.getWorkspace())==null||t.undo(!0)},disabled:n=>{var t;return!((t=n.engine.getWorkspace())!=null&&t.getRedoStack().length)}}},zoomIn(){return{id:"zoom-in",label:"Zoom in",title:"Zoom in",icon:$o,onClick:n=>n.engine.zoomPane(n.pane,"in")}},zoomOut(){return{id:"zoom-out",label:"Zoom out",title:"Zoom out",icon:Po,onClick:n=>n.engine.zoomPane(n.pane,"out")}},zoomFit(){return{id:"zoom-fit",label:"Fit",title:"Reset zoom",icon:Ho,onClick:n=>n.engine.zoomPane(n.pane,"fit")}},clear(){return{id:"clear",label:"Clear",title:"Clear workspace",icon:Oo,onClick:n=>{var t;window.confirm("Clear workspace? This cannot be undone.")&&((t=n.engine.getWorkspace())==null||t.clear())}}},runCode(){return{id:"run",label:"Run",title:"Run generated code",icon:No,onClick:n=>{n.engine.runJavaScript()}}},save(){return{id:"save",label:"Save",title:"Save workspace as JSON",icon:Fo,onClick:n=>{if(!n.engine.getWorkspace())return;const e=n.engine.serializeWorkspace(),o=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),i=URL.createObjectURL(o),s=document.createElement("a");s.href=i,s.download="workspace.json",s.click(),URL.revokeObjectURL(i)}}},load(){return{id:"load",label:"Load",title:"Load workspace JSON",icon:Ro,onClick:n=>{const t=document.createElement("input");t.type="file",t.accept="application/json",t.addEventListener("change",async()=>{var o;const e=(o=t.files)==null?void 0:o[0];if(e)try{const i=await e.text(),s=JSON.parse(i);n.engine.loadWorkspace(s)}catch(i){window.alert(`Load failed: ${i instanceof Error?i.message:String(i)}`)}}),t.click()}}},reset(){return{id:"reset",label:"Reset",title:"Reset workspace",icon:_o,onClick:n=>{var t;window.confirm("Reset workspace to empty? This cannot be undone.")&&((t=n.engine.getWorkspace())==null||t.clear())}}},togglePreview(){return{id:"toggle-preview",label:"Preview",title:"Toggle preview pane",icon:Vo,onClick:()=>{const n=document.querySelector("[data-morphic-preview-host]");n&&(n.hidden=!n.hidden)}}},readOnlyBadge(){return{id:"read-only",align:"right",render:()=>{const n=document.createElement("span");return n.className="morphic-toolbar-badge",n.textContent="read-only",n}}},spacer(){return{id:"spacer",render:()=>{const n=document.createElement("span");return n.className="morphic-toolbar-spacer",n}}},defaultsFor(n){switch(n){case"workspace":case"codespace":return[O.modeLabel(),O.spacer(),O.undo(),O.redo(),O.copy(),O.paste(),O.zoomIn(),O.zoomOut(),O.zoomFit(),O.clear()];case"preview":return[O.modeLabel(),O.spacer(),O.copy(),O.zoomIn(),O.zoomOut(),O.zoomFit(),O.readOnlyBadge()]}}};function zo(n){const t=n.engine,e=n.pane==="workspace"?t.getWorkspaceMode():n.pane==="codespace"?t.getCodespaceMode():t.getPreviewMode();return e?`Mode: ${e}`:""}function st(n,t,e){const o=t.items??O.defaultsFor(t.pane),i=t.display??"icon";n.classList.add("morphic-toolbar"),n.setAttribute("data-morphic-pane",t.pane);const s=document.createElement("div");s.className="morphic-toolbar-left";const r=document.createElement("div");r.className="morphic-toolbar-right";const c=()=>{s.replaceChildren(),r.replaceChildren();let a=!1;for(const l of o){if(l.visible&&!l.visible(e))continue;if(l.id==="spacer"){a=!0;continue}(l.align==="right"||a&&l.align!=="left"?r:s).appendChild(Wo(l,i,e))}};return n.replaceChildren(s,r),c(),{refresh:c,pane:t.pane,dispose:()=>n.replaceChildren()}}function Wo(n,t,e){if(n.render){const i=n.render(e);if(typeof i=="string"){const s=document.createElement("span");return s.className="morphic-toolbar-item",s.dataset.toolbarId=n.id,s.textContent=i,s}return i.classList.add("morphic-toolbar-item"),i.dataset.toolbarId=n.id,i}const o=document.createElement("button");return o.className="morphic-toolbar-item",o.dataset.toolbarId=n.id,o.type="button",n.title&&(o.title=n.title),jo(o,n,t),n.disabled&&n.disabled(e)&&(o.disabled=!0),n.onClick&&o.addEventListener("click",()=>n.onClick(e)),o}function jo(n,t,e){const o=e!=="label"&&!!t.icon,i=e!=="icon"&&!!t.label,s=o||e==="icon"&&!t.label,r=i||e==="label"&&!t.icon;if(s&&t.icon){const c=document.createElement("span");c.className="morphic-toolbar-icon",c.innerHTML=t.icon,n.appendChild(c)}if(r&&t.label){const c=document.createElement("span");c.className="morphic-toolbar-text",c.textContent=t.label,n.appendChild(c)}!n.title&&t.label&&(n.title=t.label),!n.childNodes.length&&t.label&&(n.textContent=t.label)}function rt(n,t){return t.includes("{")?{mode:n,cssText:t}:{mode:n,href:t}}function Uo(n){const t=[];for(const[e,o]of Object.entries(n)){const s=(e.split("/").pop()??e).replace(/\.css$/i,""),r=typeof o=="string"?o:typeof o=="object"&&o!==null&&"default"in o?String(o.default):void 0;r&&t.push(rt(s,r))}return t}function Le(n){return typeof n=="string"?{mode:n}:{mode:n.mode,render:n.render}}const me=new WeakMap,ge=new Map;class Go extends EventTarget{constructor(e,o={}){super();g(this,"definitions");g(this,"behaviors");g(this,"elementTypes");g(this,"styles",new Lo);g(this,"registeredBlockTypes",new Set);g(this,"toolbars",new Set);g(this,"toolbarsBlocklyListener");g(this,"lastCopyData");g(this,"mountConfig");g(this,"workspace");g(this,"flyoutWorkspace");g(this,"toolboxCanvas");g(this,"codeEditor");g(this,"codespace");g(this,"previewEditor");g(this,"selectionSync");g(this,"toolboxDefinition");g(this,"blockCategoryIndex",new Map);g(this,"appliedWorkspaceClasses",[]);g(this,"appliedToolboxFlyoutClasses",[]);g(this,"appliedToolboxShellClasses",[]);g(this,"headlessWorkspaceHost");g(this,"codespaceDropTeardown");g(this,"workspaceResizeObserver");g(this,"activePreset");g(this,"baseTheme");g(this,"baseFont");g(this,"mountGeneration",0);g(this,"selectionSyncOptions");g(this,"formatModes");g(this,"formatPresets");g(this,"formatHighlighting");g(this,"formatCategories");g(this,"onWorkspaceChange",e=>{if(!this.workspace||!this.mountConfig||e.workspaceId!==this.workspace.id||e.type!==L.Events.BLOCK_CREATE)return;const o=e;for(const i of o.ids??[]){const s=this.workspace.getBlockById(i);if(!s)continue;const r=this.definitions.get(W(s.type));r&&(this.applyView(s,r,this.mountConfig.workspaceMode,"workspace"),s.getSvgRoot()||this.deferApplyView(i,this.mountConfig.workspaceMode,"workspace"))}});g(this,"onFlyoutChange",e=>{if(!this.flyoutWorkspace||!this.mountConfig||e.workspaceId!==this.flyoutWorkspace.id||e.type!==L.Events.BLOCK_CREATE)return;const o=e;for(const i of o.ids??[]){const s=this.flyoutWorkspace.getBlockById(i);if(!s)continue;const r=this.definitions.get(W(s.type));r&&(this.applyView(s,r,this.mountConfig.toolboxMode,"toolbox"),s.getSvgRoot()||this.deferApplyView(i,this.mountConfig.toolboxMode,"toolbox"))}});g(this,"onStylesLoaded",()=>{var e;!this.workspace||!this.mountConfig||(this.syncWorkspaceFont(),Je(this.workspace),(e=this.toolboxCanvas)==null||e.rerender(this.mountConfig.toolboxMode,this.mountConfig.toolboxRender))});const i=e;this.definitions=wo(ko(vo(i.blocks,i.elementTypes??{}))),this.behaviors=o,this.elementTypes=i.elementTypes??{},this.formatModes=i.modes,this.formatPresets=i.presets,this.formatHighlighting=i.highlighting,this.formatCategories=i.categories}mount(e){var p,y,S,h,f,x,B;this.dispose();const o={...e,modes:e.modes??this.formatModes,presets:e.presets??this.formatPresets,highlighting:e.highlighting??this.formatHighlighting,toolbox:e.toolbox||this.formatCategories?{...e.toolbox,categories:((p=e.toolbox)==null?void 0:p.categories)??this.formatCategories}:void 0},i=o.modesFolder?Uo(o.modesFolder):[],s=[...i,...Object.entries(o.modeStyles??{}).filter(([b])=>!i.some(I=>I.mode===b)).map(([b,I])=>rt(b,I))];this.validateDefinitions(o),this.validatePresets(o);const r=(y=o.presets)!=null&&y.length?o.presets.find(b=>b.name===o.preset)??o.presets[0]:void 0;if(o.preset&&!r)throw new Error(`MorphicBlocks.mount: unknown preset "${o.preset}".`);const c=(o.modes??[]).map(b=>b.name),a=c[0]??((S=s[0])==null?void 0:S.mode)??"default",l=r?Le(r.toolbox):void 0,d=r?r.workspace??r.codespace??a:a,u=l?l.mode:a,w=l==null?void 0:l.render,v=r==null?void 0:r.codespace,C=r==null?void 0:r.preview;this.validateContainers(o);const E=o.workspaceContainer??this.createHeadlessHost(),k={...o,modeStyles:s,workspaceMode:d,toolboxMode:u,toolboxRender:w,codespaceMode:v,previewMode:C,workspaceHost:E,canvasToolbox:o.canvasToolbox??!!o.toolboxContainer};this.mountConfig=k,this.styles.validateModeCoverage(s,c),(h=k.modes)!=null&&h.length&&this.styles.ensureModeVisibilityStyles(k.modes),this.styles.ensureStyles(k.baseStyle,s);for(const b of Array.from(document.head.querySelectorAll('link[data-morphic-source^="mode:"]')))b.sheet||b.addEventListener("load",this.onStylesLoaded,{once:!0});(f=document.fonts)==null||f.addEventListener("loadingdone",this.onStylesLoaded),this.blockCategoryIndex=this.createCategoryIndex(k.toolbox,k),this.styles.ensureCategoryStyles(((x=k.toolbox)==null?void 0:x.categories)??[]),this.registerBlocks(),this.toolboxDefinition=this.resolveToolboxDefinition(k);const m=k.blockly??{};if(this.workspace=L.inject(k.workspaceHost,{...m,...k.canvasToolbox?{}:{toolbox:this.toolboxDefinition}}),this.workspace.addChangeListener(this.onWorkspaceChange),me.set(this.workspace,this),this.baseTheme=this.workspace.getTheme(),this.baseFont=Xe(this.workspace),o.workspaceContainer&&typeof ResizeObserver<"u"){const b=this.workspace;this.workspaceResizeObserver=new ResizeObserver(()=>L.svgResize(b)),this.workspaceResizeObserver.observe(o.workspaceContainer)}return this.applyWorkspaceContainerClass(),this.syncWorkspaceFont(),this.refreshToolbox(),this.bindFlyoutWorkspace(),this.renderWorkspaceBlocks(),this.renderFlyoutBlocks(),o.toolboxContainer&&this.mountToolbox(o.toolboxContainer),this.activePreset=r,r&&((B=k.onPresetApplied)==null||B.call(k,r)),this.mountViews(o,++this.mountGeneration)}async mountViews(e,o){const i=e.editorTheme?{theme:e.editorTheme}:void 0,s=e.previewTheme??e.editorTheme,r=[];if(e.codespaceContainer&&r.push(this.mountCodespace(i)),e.previewContainer&&r.push(this.mountPreview(e.previewContainer,s?{theme:s}:void 0)),e.codeEditorContainer&&r.push(this.mountCodeEditor(e.codeEditorContainer,i).then(()=>{o===this.mountGeneration&&this.hideCodeEditor()})),await Promise.all(r),o!==this.mountGeneration||!this.workspace)return;for(const[l,d]of Object.entries(e.toolbarContainers??{}))d&&this.mountToolbar(d,{pane:l});const c=(e.workspaceContainer?1:0)+r.length,a=e.selectionSync??c>1;a&&r.length>0&&this.enableSelectionSync(typeof a=="object"?a:void 0)}getPresets(){var e;return[...((e=this.mountConfig)==null?void 0:e.presets)??[]]}getActivePreset(){return this.activePreset}applyPreset(e){var r,c;if(!this.mountConfig||!this.workspace)throw new Error("MorphicBlocks must be mounted before applyPreset can be used.");const o=this.mountConfig.presets??[],i=typeof e=="number"?o[e]:o.find(a=>a.name===e);if(!i)throw new Error(`applyPreset: unknown preset "${e}".`);const s=Le(i.toolbox);return this.setModes({toolboxMode:s.mode,toolboxRender:s.render??null,workspaceMode:i.workspace??i.codespace,codespaceMode:i.codespace??null,previewMode:i.preview??null}),this.activePreset=i,(c=(r=this.mountConfig).onPresetApplied)==null||c.call(r,i),i}validateDefinitions(e){var s;const{errors:o,warnings:i}=qe({definitions:this.definitions,elementTypes:this.elementTypes,behaviors:this.behaviors,modes:e.modes,presets:e.presets,highlighting:e.highlighting,categories:(s=e.toolbox)==null?void 0:s.categories});if(i.length>0&&console.warn(`[MorphicBlocks] Definition warnings:
27
- - ${i.join(`
28
- - `)}`),o.length>0)throw new Error(`[MorphicBlocks] Invalid definitions:
29
- - ${o.join(`
30
- - `)}`)}validatePresets(e){const o=e.presets??[];if(o.length===0)return;const i=e.modes??[],s=new Map(i.map(c=>[c.name,c])),r=new Set;for(const c of o){if(r.has(c.name))throw new Error(`Preset "${c.name}" is defined more than once.`);if(r.add(c.name),!c.workspace&&!c.codespace)throw new Error(`Preset "${c.name}": at least one of workspace or codespace must be set.`);if(c.codespace&&!e.codespaceContainer)throw new Error(`Preset "${c.name}" uses a codespace but no codespaceContainer was provided.`);const a=Le(c.toolbox),l=[["toolbox",a.mode],["workspace",c.workspace],["codespace",c.codespace],["preview",c.preview]];for(const[d,u]of l){if(u===void 0)continue;const w=s.get(u);if(!w)throw new Error(`Preset "${c.name}": unknown mode "${u}" for ${d}.`);if((d==="codespace"||d==="preview")&&de(w,this.elementTypes)===void 0)throw new Error(`Preset "${c.name}": mode "${u}" has no code element to render in the ${d}.`)}for(const d of Object.values(a.render??{}))if(d!=="block"&&d!=="text")throw new Error(`Preset "${c.name}": toolbox render values must be "block" or "text".`)}}dispose(){var e,o,i,s,r,c,a,l;for(const[d,u]of ge)u===this&&ge.delete(d);(e=this.workspaceResizeObserver)==null||e.disconnect(),this.workspaceResizeObserver=void 0,(o=document.fonts)==null||o.removeEventListener("loadingdone",this.onStylesLoaded),this.activePreset=void 0,(i=this.selectionSync)==null||i.disable(),this.selectionSync=void 0,(s=this.codeEditor)==null||s.dispose(),this.codeEditor=void 0,(r=this.codespaceDropTeardown)==null||r.call(this),this.codespaceDropTeardown=void 0,(c=this.codespace)==null||c.dispose(),this.codespace=void 0,(a=this.previewEditor)==null||a.dispose(),this.previewEditor=void 0,(l=this.toolboxCanvas)==null||l.dispose(),this.toolboxCanvas=void 0;for(const d of[...this.toolbars])d.dispose();this.flyoutWorkspace&&(this.flyoutWorkspace.removeChangeListener(this.onFlyoutChange),this.flyoutWorkspace=void 0),this.workspace&&(this.workspace.removeChangeListener(this.onWorkspaceChange),this.workspace.dispose(),this.workspace=void 0),this.headlessWorkspaceHost&&(this.headlessWorkspaceHost.remove(),this.headlessWorkspaceHost=void 0),this.mountConfig=void 0,this.baseTheme=void 0,this.baseFont=void 0,this.toolboxDefinition=void 0,this.blockCategoryIndex.clear(),this.appliedWorkspaceClasses=[],this.appliedToolboxFlyoutClasses=[],this.appliedToolboxShellClasses=[]}mountToolbox(e,o){var s,r;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before mountToolbox can be used.");(s=this.toolboxCanvas)==null||s.dispose(),this.styles.ensureToolbarStyles(),this.mountConfig.canvasToolbox||this.workspace.updateToolbox({kind:"flyoutToolbox",contents:[]});const i={...o,categories:(o==null?void 0:o.categories)??((r=this.mountConfig.toolbox)==null?void 0:r.categories)};this.toolboxCanvas=new ot({container:e,workspaceContainer:this.mountConfig.workspaceHost,workspace:this.workspace,definitions:this.definitions,blockColors:this.buildBlockColorMap(),behaviors:this.behaviors,elementTypes:this.elementTypes,mode:this.mountConfig.toolboxMode,render:this.mountConfig.toolboxRender,modes:this.mountConfig.modes,options:i,onPreviewWorkspace:c=>me.set(c,this)})}getWorkspace(){return this.workspace}getAvailableModes(){var e;return(((e=this.mountConfig)==null?void 0:e.modes)??[]).map(o=>o.name)}getWorkspaceMode(){var e;return(e=this.mountConfig)==null?void 0:e.workspaceMode}getCodespaceMode(){var e,o;return((e=this.mountConfig)==null?void 0:e.codespaceMode)??((o=this.mountConfig)==null?void 0:o.workspaceMode)}getPreviewMode(){var e;return(e=this.mountConfig)==null?void 0:e.previewMode}modeDef(e){var o;if(e)return(((o=this.mountConfig)==null?void 0:o.modes)??[]).find(i=>i.name===e)}getActivePrimarySourceElement(){const e=this.modeDef(this.getCodespaceMode());if(e)return de(e,this.elementTypes)}getActivePreviewElement(){var o;const e=this.modeDef((o=this.mountConfig)==null?void 0:o.previewMode);if(e)return de(e,this.elementTypes)}mountToolbar(e,o){if(!this.workspace)throw new Error("MorphicBlocks must be mounted before mountToolbar can be used.");this.styles.ensureToolbarStyles();const i=st(e,o,{engine:this,pane:o.pane,getText:()=>this.toolbarTextFor(o.pane),refresh:()=>this.toolbarRefreshFor(o.pane)});this.toolbars.add(i),this.ensureToolbarBlocklyListener();const s=i.dispose;return i.dispose=()=>{this.toolbars.delete(i),this.toolbars.size===0&&this.teardownToolbarBlocklyListener(),s()},i}toolbarTextFor(e){var o,i;if(e==="codespace")return((o=this.codespace)==null?void 0:o.getValue())??this.generateCodespaceText().code;if(e==="preview")return((i=this.previewEditor)==null?void 0:i.getValue())??"";if(this.codespace)return this.codespace.getValue();try{return this.generateJavaScript()}catch{return""}}toolbarRefreshFor(e){var o,i;e==="codespace"?(o=this.codespace)==null||o.refresh():e==="preview"&&((i=this.previewEditor)==null||i.refresh())}runJavaScript(e){let o="",i,s=null;const r=[],c=(e==null?void 0:e.console)??(e!=null&&e.logToConsole?console:void 0),a=u=>(...w)=>{r.push({level:u,text:w.map(String).join(" ")}),c&&(c[u]??c.log).apply(c,w)},l={log:a("log"),warn:a("warn"),error:a("error")};try{o=this.generateJavaScript(),i=new Function("console",o)(l)}catch(u){s=u instanceof Error?u:new Error(String(u))}const d={code:o,result:i,error:s,output:r};return this.dispatchEvent(new CustomEvent("morphic-run",{detail:d})),d}hasClipboardContents(){return!!this.lastCopyData}copyActiveBlock(e){var s;const o=this.resolveActiveBlock(e);if(!o)return!1;const i=o.toCopyData();if(!i)return!1;this.lastCopyData=i;try{const r=this.toolbarTextFor(e==="workspace"?"codespace":e);r&&((s=navigator.clipboard)==null||s.writeText(r))}catch{}for(const r of this.toolbars)r.refresh();return!0}pasteActiveBlock(e){return!this.lastCopyData||!this.workspace?!1:L.clipboard.paste(this.lastCopyData,this.workspace)!==null}resolveActiveBlock(e){var i,s;const o=L.common.getSelected();if(o&&"id"in o&&((i=this.workspace)!=null&&i.getBlockById(o.id)))return o;if(e==="codespace"||e==="preview"){const r=e==="codespace"?this.codespace:this.previewEditor;if(r){const c=r.metadata,a=r.getCursorLine();let l=null;for(const[d,u]of c)if(u.startLine<=a&&u.endLine>=a){const w=u.endLine-u.startLine;(!l||w<l.size)&&(l={id:d,size:w})}if(l){const d=(s=this.workspace)==null?void 0:s.getBlockById(l.id);if(d)return d}}}return null}serializeWorkspace(){return this.workspace?L.serialization.workspaces.save(this.workspace):null}loadWorkspace(e){this.workspace&&(this.workspace.clear(),L.serialization.workspaces.load(e,this.workspace))}zoomPane(e,o){if(e==="workspace"){if(!this.workspace)return;o==="in"?this.workspace.zoomCenter(1):o==="out"?this.workspace.zoomCenter(-1):this.workspace.zoomToFit();return}const i=e==="codespace"?this.codespace:this.previewEditor;i==null||i.adjustZoom(o)}ensureToolbarBlocklyListener(){if(this.toolbarsBlocklyListener||!this.workspace)return;const e=o=>{for(const i of this.toolbars)i.refresh()};this.toolbarsBlocklyListener=e,this.workspace.addChangeListener(e)}teardownToolbarBlocklyListener(){!this.toolbarsBlocklyListener||!this.workspace||(this.workspace.removeChangeListener(this.toolbarsBlocklyListener),this.toolbarsBlocklyListener=void 0)}setModes(e){var o,i,s,r,c,a;if(!this.mountConfig||!this.workspace)throw new Error("MorphicBlocks must be mounted before setModes can be used.");for(const[l,d]of[["workspaceMode",e.workspaceMode],["toolboxMode",e.toolboxMode],["codespaceMode",e.codespaceMode],["previewMode",e.previewMode]])if(typeof d=="string"&&!this.modeDef(d))throw new Error(`setModes: unknown mode "${d}" for ${l}.`);if(typeof e.codespaceMode=="string"&&!this.mountConfig.codespaceContainer)throw new Error("setModes: codespaceMode requires a codespaceContainer at mount.");e.workspaceMode&&(this.mountConfig.workspaceMode=e.workspaceMode),e.codespaceMode!==void 0&&(this.mountConfig.codespaceMode=e.codespaceMode??void 0),e.previewMode!==void 0&&(this.mountConfig.previewMode=e.previewMode??void 0),e.toolboxRender!==void 0&&(this.mountConfig.toolboxRender=e.toolboxRender??void 0),(e.toolboxMode||e.toolboxRender!==void 0)&&(e.toolboxMode&&(this.mountConfig.toolboxMode=e.toolboxMode),(o=this.toolboxCanvas)==null||o.rerender(this.mountConfig.toolboxMode,this.mountConfig.toolboxRender)),this.applyWorkspaceContainerClass(),this.syncWorkspaceFont(),this.refreshToolbox(),this.bindFlyoutWorkspace(),this.renderWorkspaceBlocks(),this.renderFlyoutBlocks(),(i=this.codespace)==null||i.setHighlightRules(this.resolveHighlightRules("codespace")),(s=this.previewEditor)==null||s.setHighlightRules(this.resolveHighlightRules("preview")),(r=this.codespace)==null||r.refresh(),(c=this.previewEditor)==null||c.refresh();for(const l of this.toolbars)l.refresh();(a=this.selectionSync)==null||a.clearAll()}resolveHighlightRules(e){var i;if(!this.mountConfig)return;const o=e==="codespace"?this.getActivePrimarySourceElement():this.getActivePreviewElement();if(o)return(i=this.mountConfig.highlighting)==null?void 0:i[o]}generateJavaScript(){if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before generateJavaScript can be used.");return Kt(this.workspace,this.definitions,this.behaviors,this.mountConfig.javascript)}generateJavaScriptWithMetadata(){if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before generateJavaScriptWithMetadata can be used.");return Yt(this.workspace,this.definitions,this.behaviors,this.mountConfig.javascript)}async mountCodeEditor(e,o){var s;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before mountCodeEditor can be used.");(s=this.codeEditor)==null||s.dispose(),this.codeEditor=new ye(e,this.workspace,()=>this.generateJavaScriptWithMetadata(),o);const i=this.codeEditor;await i.mount(),this.codeEditor===i&&this.refreshSelectionSync()}async mountCodespace(e){var s,r;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before mountCodespace can be used.");if(!this.mountConfig.codespaceContainer)throw new Error("mountCodespace requires a codespaceContainer to be passed to mount().");(s=this.codespace)==null||s.dispose(),(r=this.codespaceDropTeardown)==null||r.call(this);const o={...e,onDelete:(e==null?void 0:e.onDelete)??(c=>this.deleteBlockAtCodespaceLine(c)),canDragBlock:(e==null?void 0:e.canDragBlock)??(c=>{var l;const a=(l=this.workspace)==null?void 0:l.getBlockById(c);return!!(a!=null&&a.previousConnection||a!=null&&a.outputConnection)}),highlightRules:(e==null?void 0:e.highlightRules)??this.resolveHighlightRules("codespace"),onPlaceholderApply:(e==null?void 0:e.onPlaceholderApply)??((c,a)=>this.applyPlaceholderEdit(c,a))};this.codespace=new ye(this.mountConfig.codespaceContainer,this.workspace,()=>this.generateCodespaceText(),o);const i=this.codespace;await i.mount(),this.codespace===i&&(this.codespaceDropTeardown=this.attachCodespaceDropTarget(this.mountConfig.codespaceContainer,this.workspace),this.refreshSelectionSync())}attachCodespaceDropTarget(e,o){const i=m=>{var y;const p=(y=m.dataTransfer)==null?void 0:y.types;return p?p.includes(ee)||p.includes(ve):!1},s=m=>{var y,S,h,f,x,B;if(!i(m))return;m.preventDefault();const p=this.computeCodespaceDrop(m.clientX,m.clientY);if(!p){(y=this.codespace)==null||y.hideDropIndicator(),(S=this.codespace)==null||S.hideValueSlotHighlight();return}p.indicator.kind==="line"?((h=this.codespace)==null||h.showDropIndicator(p.indicator.line,p.indicator.position),(f=this.codespace)==null||f.hideValueSlotHighlight()):((x=this.codespace)==null||x.showValueSlotHighlight(p.indicator.from,p.indicator.to),(B=this.codespace)==null||B.hideDropIndicator())},r=m=>{var y,S;const p=m.relatedTarget;p&&e.contains(p)||((y=this.codespace)==null||y.hideDropIndicator(),(S=this.codespace)==null||S.hideValueSlotHighlight())},c=m=>{var x,B,b,I;if(!i(m))return;m.preventDefault(),(x=this.codespace)==null||x.hideDropIndicator(),(B=this.codespace)==null||B.hideValueSlotHighlight();const p=this.computeCodespaceDrop(m.clientX,m.clientY);if(!p)return;const y=(b=m.dataTransfer)==null?void 0:b.getData(ee),S=(I=m.dataTransfer)==null?void 0:I.getData(ve);let h=null;if(y)h=o.newBlock(G(y,this.definitions)),h.initSvg(),h.render();else if(S){if(h=o.getBlockById(S),!h)return}else return;let f=!1;L.Events.setGroup(!0);try{if(S&&h.getParent()&&h.unplug(!0),p.target.kind==="top")this.placeAtTopIndex(o,h,p.target.index),f=!0;else if(p.target.kind==="statement"){if(h.previousConnection){const D=o.getBlockById(p.target.targetBlockId);D&&D!==h&&(this.connectStatement(h,D,p.target.position),f=!0)}}else if(p.target.kind==="into-slot"){if(h.previousConnection){const D=o.getBlockById(p.target.parentBlockId);D&&D!==h&&(this.connectIntoSlot(h,D,p.target.inputName),f=!0)}}else if(p.target.kind==="value-slot"){if(h.outputConnection){const D=o.getBlockById(p.target.parentBlockId);D&&D!==h&&!this.isDescendantOf(D,h)&&(f=this.connectIntoValueSlot(h,D,p.target.inputName))}!f&&y&&h.dispose(!1)}}finally{L.Events.setGroup(!1)}!f&&h.workspace&&!h.getParent()&&this.placeOrphanBelowTops(h),L.svgResize(o)};let a=null;const l=3,d=m=>m.button===2||m.button===0&&m.ctrlKey,u=m=>{var y,S,h,f,x,B;if(!a)return;if(!a.dragging){const b=Math.abs(m.clientX-a.startX),I=Math.abs(m.clientY-a.startY);if(b+I<l)return;a.dragging=!0}const p=this.computeCodespaceDrop(m.clientX,m.clientY);if(!p){(y=this.codespace)==null||y.hideDropIndicator(),(S=this.codespace)==null||S.hideValueSlotHighlight();return}p.indicator.kind==="line"?((h=this.codespace)==null||h.showDropIndicator(p.indicator.line,p.indicator.position),(f=this.codespace)==null||f.hideValueSlotHighlight()):((x=this.codespace)==null||x.showValueSlotHighlight(p.indicator.from,p.indicator.to),(B=this.codespace)==null||B.hideDropIndicator())},w=m=>{var h,f;window.removeEventListener("mousemove",u),window.removeEventListener("mouseup",w),(h=this.codespace)==null||h.hideDropIndicator(),(f=this.codespace)==null||f.hideValueSlotHighlight();const p=a;if(a=null,Ne(void 0),!(p!=null&&p.dragging))return;const y=this.computeCodespaceDrop(m.clientX,m.clientY);if(!y)return;const S=o.getBlockById(p.sourceId);S&&this.applyRightDragMove(o,S,y)},v=m=>{var S;if(!d(m))return;const p=(S=this.codespace)==null?void 0:S.charAtCoords(m.clientX,m.clientY);if(p==null)return;const y=this.findInnermostBlockAtChar(p);y&&(m.preventDefault(),m.stopPropagation(),a={sourceId:y.id,startX:m.clientX,startY:m.clientY,dragging:!1},Ne(y.id),window.addEventListener("mousemove",u),window.addEventListener("mouseup",w))},C=m=>{m.preventDefault()},E=m=>{var f,x,B,b,I,D,j,$;if(a)return;const p=(f=this.codespace)==null?void 0:f.charAtCoords(m.clientX,m.clientY);if(p==null){(x=this.codespace)==null||x.setHoverHighlight(null),(B=this.codespace)==null||B.setEditableHoverHighlight(null);return}const y=this.findInnermostEditablePlaceholderAtChar(p);(b=this.codespace)==null||b.setEditableHoverHighlight(y?{from:y.start,to:y.end}:null);const S=this.findHoverBlockAtChar(p);if(!S){(I=this.codespace)==null||I.setHoverHighlight(null);return}const h=(D=this.codespace)==null?void 0:D.metadata.get(S.id);if(!h||h.startChar===void 0||h.endChar===void 0){(j=this.codespace)==null||j.setHoverHighlight(null);return}($=this.codespace)==null||$.setHoverHighlight({from:h.startChar,to:h.endChar})},k=()=>{var m,p;(m=this.codespace)==null||m.setHoverHighlight(null),(p=this.codespace)==null||p.setEditableHoverHighlight(null)};return e.addEventListener("dragover",s),e.addEventListener("dragleave",r),e.addEventListener("drop",c),e.addEventListener("mousedown",v,!0),e.addEventListener("contextmenu",C),e.addEventListener("mousemove",E),e.addEventListener("mouseleave",k),()=>{e.removeEventListener("dragover",s),e.removeEventListener("dragleave",r),e.removeEventListener("drop",c),e.removeEventListener("mousedown",v,!0),e.removeEventListener("contextmenu",C),e.removeEventListener("mousemove",E),e.removeEventListener("mouseleave",k),window.removeEventListener("mousemove",u),window.removeEventListener("mouseup",w)}}findInnermostBlockAtChar(e){if(!this.workspace||!this.codespace)return null;let o=null;for(const[i,s]of this.codespace.metadata){if(s.startChar===void 0||s.endChar===void 0||e<s.startChar||e>=s.endChar)continue;const r=s.endChar-s.startChar;(o===null||r<o.size)&&(o={id:i,size:r})}return o?this.workspace.getBlockById(o.id):null}findHoverBlockAtChar(e){if(!this.workspace||!this.codespace)return null;let o=null,i=null;for(const[r,c]of this.codespace.metadata){if(c.startChar===void 0||c.endChar===void 0||e<c.startChar||e>=c.endChar)continue;const a=c.endChar-c.startChar;(i===null||a<i.size)&&(i={id:r,size:a}),!c.atomic&&(o===null||a<o.size)&&(o={id:r,size:a})}const s=o??i;return s?this.workspace.getBlockById(s.id):null}findInnermostEditablePlaceholderAtChar(e){if(!this.codespace)return null;let o=null;for(const i of this.codespace.getPlaceholders()){if(!i.edit||e<i.start||e>=i.end)continue;const s=i.end-i.start;(o===null||s<o.size)&&(o={ph:i,size:s})}return o?{start:o.ph.start,end:o.ph.end}:null}applyRightDragMove(e,o,i){if(!i)return;let s=!1;L.Events.setGroup(!0);try{if(o.getParent()&&o.unplug(!0),i.target.kind==="top")this.placeAtTopIndex(e,o,i.target.index),s=!0;else if(i.target.kind==="statement"){if(o.previousConnection){const r=e.getBlockById(i.target.targetBlockId);r&&r!==o&&(this.connectStatement(o,r,i.target.position),s=!0)}}else if(i.target.kind==="into-slot"){if(o.previousConnection){const r=e.getBlockById(i.target.parentBlockId);r&&r!==o&&(this.connectIntoSlot(o,r,i.target.inputName),s=!0)}}else if(i.target.kind==="value-slot"&&o.outputConnection){const r=e.getBlockById(i.target.parentBlockId);r&&r!==o&&!this.isDescendantOf(r,o)&&(s=this.connectIntoValueSlot(o,r,i.target.inputName))}}finally{L.Events.setGroup(!1)}!s&&o.workspace&&!o.getParent()&&this.placeOrphanBelowTops(o),L.svgResize(e)}computeCodespaceDrop(e,o){var u,w;if(!this.workspace||!this.codespace)return null;const i=this.workspace.getTopBlocks(!0),s=this.codespace.metadata,r=this.codespace.getLineCount();if(i.length===0)return{indicator:{kind:"line",line:1,position:"above"},target:{kind:"top",index:0}};if(this.codespace.isBelowLastLine(o)){const v=s.get(i[i.length-1].id);return{indicator:{kind:"line",line:(v==null?void 0:v.endLine)??r,position:"below"},target:{kind:"top",index:i.length}}}const c=this.codespace.getLineAtCoords(e,o);if(c===null){const v=s.get(i[0].id);return{indicator:{kind:"line",line:(v==null?void 0:v.startLine)??1,position:"above"},target:{kind:"top",index:0}}}const a=this.codespace.charAtCoords(e,o);if(a!==null){const v=this.findValueSlotDropAtChar(a);if(v)return{indicator:{kind:"value-slot",from:v.highlight.from,to:v.highlight.to},target:{kind:"value-slot",parentBlockId:v.parentBlockId,inputName:v.inputName}}}const l=this.findInnermostStatementSlotAtLine(c,s);if(l){const v=this.workspace.getBlockById(l.blockId);if(v){const C=Oe(),E=[];let k=(w=(u=v.getInput(l.inputName))==null?void 0:u.connection)==null?void 0:w.targetBlock();for(;k;)k.id!==C&&E.push(k),k=k.getNextBlock();for(const m of E){const p=s.get(m.id);if(!p||c<p.startLine||c>p.endLine)continue;const y=c===p.endLine,S=this.codespace.isInLowerHalfOfLine(c,o);return y&&S?{indicator:{kind:"line",line:p.endLine,position:"below"},target:{kind:"statement",targetBlockId:m.id,position:"after"}}:{indicator:{kind:"line",line:p.startLine,position:"above"},target:{kind:"statement",targetBlockId:m.id,position:"before"}}}if(E.length>0){const m=E[E.length-1],p=s.get(m.id);return{indicator:{kind:"line",line:(p==null?void 0:p.endLine)??l.range.endLine,position:"below"},target:{kind:"into-slot",parentBlockId:l.blockId,inputName:l.inputName}}}return{indicator:{kind:"line",line:l.range.startLine,position:"above"},target:{kind:"into-slot",parentBlockId:l.blockId,inputName:l.inputName}}}}for(let v=0;v<i.length;v++){const C=s.get(i[v].id);if(!C||c<C.startLine||c>C.endLine)continue;const E=c===C.endLine,k=this.codespace.isInLowerHalfOfLine(c,o);return E&&k?{indicator:{kind:"line",line:C.endLine,position:"below"},target:{kind:"top",index:v+1}}:{indicator:{kind:"line",line:C.startLine,position:"above"},target:{kind:"top",index:v}}}const d=s.get(i[i.length-1].id);return{indicator:{kind:"line",line:(d==null?void 0:d.endLine)??r,position:"below"},target:{kind:"top",index:i.length}}}findInnermostStatementSlotAtLine(e,o){let i=null;for(const[s,r]of o)if(r.statementSlots)for(const[c,a]of Object.entries(r.statementSlots)){if(e<a.startLine||e>a.endLine)continue;const l=a.endLine-a.startLine,d=this.computeBlockDepth(s);(i===null||l<i.size||l===i.size&&d>i.depth)&&(i={blockId:s,inputName:c,range:a,size:l,depth:d})}return i?{blockId:i.blockId,inputName:i.inputName,range:i.range}:null}connectIntoSlot(e,o,i){if(!e.previousConnection)return;const s=o.getInput(i),r=s==null?void 0:s.connection;if(!r)return;const c=r.targetBlock();if(!c){r.connect(e.previousConnection);return}let a=c,l=a.getNextBlock();for(;l;)a=l,l=a.getNextBlock();a.nextConnection&&a.nextConnection.connect(e.previousConnection)}findValueSlotDropAtChar(e){var s,r;if(!this.workspace||!this.codespace)return null;const o=Oe();for(const c of this.codespace.getPlaceholders()){if(e<c.start||e>=c.end)continue;if(c.emptySlot){const{parentBlockId:u,inputName:w}=c.emptySlot;if(u===o)continue;const v=this.workspace.getBlockById(u);if(!((s=v==null?void 0:v.getInput(w))!=null&&s.connection))continue;return{parentBlockId:u,inputName:w,highlight:{from:c.start,to:c.end}}}const a=(r=c.edit)==null?void 0:r.blockId;if(!a||a===o)continue;const l=this.workspace.getBlockById(a);if(!l)continue;const d=this.resolveValueParent(l);if(d)return{parentBlockId:d.parentBlockId,inputName:d.inputName,highlight:{from:c.start,to:c.end}}}let i=null;for(const[c,a]of this.codespace.metadata){if(a.startChar===void 0||a.endChar===void 0||e<a.startChar||e>=a.endChar||c===o)continue;const l=this.workspace.getBlockById(c);if(!(l!=null&&l.outputConnection))continue;const d=a.endChar-a.startChar;(i===null||d<i.size)&&(i={id:c,size:d,from:a.startChar,to:a.endChar})}if(i){const c=this.workspace.getBlockById(i.id);if(c){const a=this.resolveValueParent(c);if(a)return{parentBlockId:a.parentBlockId,inputName:a.inputName,highlight:{from:i.from,to:i.to}}}}return null}resolveValueParent(e){var s;const o=(s=e.outputConnection)==null?void 0:s.targetConnection;if(!o)return null;const i=o.getSourceBlock();if(!i)return null;for(const r of i.inputList)if(r.connection===o)return{parentBlockId:i.id,inputName:r.name};return null}placeOrphanBelowTops(e){var s,r;if(!this.workspace)return;const o=this.workspace.getTopBlocks(!0).filter(c=>c.id!==e.id);if(o.length===0){e.moveTo(new L.utils.Coordinate(20,20));return}let i=0;for(const c of o){const a=c.getRelativeToSurfaceXY(),l=((r=(s=c.getHeightWidth)==null?void 0:s.call(c))==null?void 0:r.height)??50;i=Math.max(i,a.y+l)}e.moveTo(new L.utils.Coordinate(20,i+20))}isDescendantOf(e,o){let i=e;for(;i;){if(i===o)return!0;i=i.getParent()}return!1}connectIntoValueSlot(e,o,i){if(!e.outputConnection)return!1;const s=o.getInput(i),r=s==null?void 0:s.connection;if(!r)return!1;const c=r.targetBlock(),a=!!c&&!c.isShadow();a&&(c.unplug(!1),this.placeOrphanBelowTops(c));const d=r.check_;r.setCheck(null);try{return r.connect(e.outputConnection),!0}catch{if(a&&(c!=null&&c.outputConnection))try{r.connect(c.outputConnection)}catch{}return!1}finally{r.setCheck(d)}}computeBlockDepth(e){var s,r;let o=0,i=((r=(s=this.workspace)==null?void 0:s.getBlockById(e))==null?void 0:r.getParent())??null;for(;i;)o++,i=i.getParent();return o}placeAtTopIndex(e,o,i){const s=e.getTopBlocks(!0).map(c=>c.id).filter(c=>c!==o.id),r=Math.max(0,Math.min(i,s.length));s.splice(r,0,o.id),this.applyTopBlockOrder(e,s)}connectStatement(e,o,i){var s,r,c;if(e.previousConnection)if(i==="before"){const a=((s=o.previousConnection)==null?void 0:s.targetConnection)??null;(r=o.previousConnection)==null||r.disconnect(),a&&a.connect(e.previousConnection),e.nextConnection&&o.previousConnection&&e.nextConnection.connect(o.previousConnection)}else{const a=o.getNextBlock();(c=a==null?void 0:a.previousConnection)==null||c.disconnect(),o.nextConnection&&o.nextConnection.connect(e.previousConnection),a!=null&&a.previousConnection&&e.nextConnection&&e.nextConnection.connect(a.previousConnection)}}applyTopBlockOrder(e,o){var s,r,c;const i=L.Events.disable!==void 0;i&&L.Events.disable();try{for(let a=0;a<o.length;a++){const l=e.getBlockById(o[a]);l&&l.moveTo(new L.utils.Coordinate(20,20+a*100))}}finally{i&&L.Events.enable()}L.svgResize(e),(s=this.codespace)==null||s.refresh(),(r=this.previewEditor)==null||r.refresh(),(c=this.codeEditor)==null||c.refresh()}async mountPreview(e,o){var r;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before mountPreview can be used.");(r=this.previewEditor)==null||r.dispose();const i={...o,highlightRules:(o==null?void 0:o.highlightRules)??this.resolveHighlightRules("preview"),showPlaceholderMarkers:(o==null?void 0:o.showPlaceholderMarkers)??!1};this.previewEditor=new ye(e,this.workspace,()=>this.generatePreviewText(),i);const s=this.previewEditor;await s.mount(),this.previewEditor===s&&this.refreshSelectionSync()}generatePreviewText(){if(!this.workspace||!this.mountConfig)return{code:"",metadata:new Map,placeholders:[]};const e=this.mountConfig.previewMode,o=this.getActivePreviewElement();return!e||!o?{code:"",metadata:new Map,placeholders:[]}:Se(this.workspace,e,this.definitions,this.elementTypes,this.mountConfig.modes??[],o)}applyPlaceholderEdit(e,o){var a;if(!this.workspace)return;let i=this.workspace.getBlockById(e.blockId);if(!i)return;if(i.isShadow()){const l=(a=i.outputConnection)==null?void 0:a.targetConnection;if(l){const d=this.workspace.newBlock(i.type);for(const u of i.inputList)for(const w of u.fieldRow){if(!w.name)continue;const v=d.getField(w.name);v&&v.setValue(w.getValue())}i.rendered&&(d.initSvg(),d.render()),l.connect(d.outputConnection),i=d}}const s=i.getField(e.fieldName);if(!s)return;s.setValue(o);const r=i;r.rendered&&typeof r.render=="function"&&r.render();const c=i.getParent();if(c){const l=c;l.rendered&&typeof l.render=="function"&&l.render()}}deleteBlockAtCodespaceLine(e){var r,c;const o=(r=this.codespace)==null?void 0:r.metadata;if(!this.workspace||!o||o.size===0)return;let i=null,s=1/0;for(const[a,{startLine:l,endLine:d}]of o){if(e<l||e>d)continue;const u=d-l;u<s&&(s=u,i=a)}i&&((c=this.workspace.getBlockById(i))==null||c.dispose(!0))}generateCodespaceText(){if(!this.workspace||!this.mountConfig)return{code:"",metadata:new Map,placeholders:[]};const e=this.mountConfig.codespaceMode;if(e){const o=this.modeDef(e),i=o?de(o,this.elementTypes):void 0;return Se(this.workspace,e,this.definitions,this.elementTypes,this.mountConfig.modes??[],i)}return Se(this.workspace,this.mountConfig.workspaceMode,this.definitions,this.elementTypes,this.mountConfig.modes??[])}showCodeEditor(){var e;(e=this.codeEditor)==null||e.show()}hideCodeEditor(){var e;(e=this.codeEditor)==null||e.hide()}isCodeEditorVisible(){var e;return((e=this.codeEditor)==null?void 0:e.isVisible())??!1}setCodeEditorTheme(e){var o;(o=this.codeEditor)==null||o.setTheme(e)}setCodespaceTheme(e){var o;(o=this.codespace)==null||o.setTheme(e)}setPreviewTheme(e){var o;(o=this.previewEditor)==null||o.setTheme(e)}enableSelectionSync(e){var i;if(!this.workspace)throw new Error("MorphicBlocks must be mounted before enableSelectionSync can be used.");const o=[this.codeEditor,this.codespace,this.previewEditor].filter(s=>s!==void 0);if(o.length===0)throw new Error("enableSelectionSync requires at least one of mountCodeEditor, mountCodespace, or mountPreview to have been called first.");(i=this.selectionSync)==null||i.disable(),this.selectionSyncOptions=e,this.selectionSync=new go(this.workspace,o,e),this.selectionSync.enable()}refreshSelectionSync(){this.selectionSync&&this.enableSelectionSync(this.selectionSyncOptions)}disableSelectionSync(){var e;(e=this.selectionSync)==null||e.disable(),this.selectionSync=void 0,this.selectionSyncOptions=void 0}registerBlocks(){for(const e of this.definitions.values()){const o=Ce(e.identifier);if(ge.set(o,this),this.registeredBlockTypes.has(o))continue;const i=e.identifier;L.Blocks[o]={init(){const s=me.get(this.workspace)??ge.get(o);s==null||s.initManagedBlock(this,i)}},this.registeredBlockTypes.add(o)}}initManagedBlock(e,o){var a;const i=this.definitions.get(o);if(!i)return;const s=e.workspace.isFlyout?"toolbox":"workspace",r=this.resolveMode(s);this.applyView(e,i,r,s);const c=te(this.behaviors[i.identifier]);(a=c==null?void 0:c.init)==null||a.call(c,e,this.createBehaviorContext(e,i,r,s))}validateContainers(e){if(!e.workspaceContainer&&!e.codespaceContainer)throw new Error("MorphicBlocks.mount requires at least one of workspaceContainer or codespaceContainer.")}createHeadlessHost(){const e=document.createElement("div");return e.style.cssText="position:absolute;left:-9999px;top:-9999px;width:800px;height:600px;overflow:hidden;",document.body.appendChild(e),this.headlessWorkspaceHost=e,e}resolveMode(e){return this.mountConfig?e==="toolbox"?this.mountConfig.toolboxMode:this.mountConfig.workspaceMode:"default"}applyView(e,o,i,s){var u,w;if(e.isDeadOrDying())return;const r=this.blockCategoryIndex.get(o.identifier);o.color===void 0&&(r==null?void 0:r.color)!==void 0&&e.setColour(r.color);const c=Pt(e),a=Ee(o,i,this.elementTypes,((u=this.mountConfig)==null?void 0:u.modes)??[]),l=e.workspace===this.workspace;De({block:e,definition:o,view:a,mode:i,context:s,elementTypes:l?this.elementTypes:void 0,resolveBlocklyType:v=>G(v,this.definitions)}),Et(e,r==null?void 0:r.token),St(e,o.identifier),xt(e),o.color!==void 0&&(e.setColour(o.color),e.rendered&&e.render());const d=te(this.behaviors[o.identifier]);(w=d==null?void 0:d.onViewApplied)==null||w.call(d,e,this.createBehaviorContext(e,o,i,s)),Ht(e,c)}applyWorkspaceContainerClass(){var i;if(!this.mountConfig)return;const e=this.mountConfig.workspaceHost;ke(e,this.mountConfig.workspaceMode,"workspace","morphic-workspace-root");const o=this.resolveClassNames((i=this.mountConfig.ui)==null?void 0:i.workspaceClassName);this.replaceUserClasses(e,this.appliedWorkspaceClasses,o),this.appliedWorkspaceClasses=o}syncWorkspaceFont(){var s;const e=this.workspace,o=(s=this.mountConfig)==null?void 0:s.workspaceHost;if(!e||!o||!this.baseTheme||!this.baseFont)return;const i=Ke(o,[[e.getRenderer().getClassName(),this.baseTheme.getClassName()]],this.baseFont);Ye(e,this.baseTheme,this.baseFont,i)&&Je(e)}applyFlyoutClass(){var c,a,l;if(!this.workspace||!this.mountConfig)return;const e=this.resolveClassNames((c=this.mountConfig.ui)==null?void 0:c.toolboxClassName),o=this.workspace.getToolbox(),i=((a=o==null?void 0:o.getDiv)==null?void 0:a.call(o))??null;i&&(ke(i,this.mountConfig.toolboxMode,"toolbox","morphic-toolbox-shell"),this.replaceUserClasses(i,this.appliedToolboxShellClasses,e),this.appliedToolboxShellClasses=e);const s=(l=this.workspace.getFlyout())==null?void 0:l.getWorkspace(),r=s==null?void 0:s.getParentSvg();r&&(ke(r,this.mountConfig.toolboxMode,"toolbox","morphic-toolbox-root"),this.replaceUserClasses(r,this.appliedToolboxFlyoutClasses,e),this.appliedToolboxFlyoutClasses=e)}renderWorkspaceBlocks(){if(!(!this.workspace||!this.mountConfig))for(const e of this.workspace.getAllBlocks(!1)){const o=e,i=this.definitions.get(W(o.type));i&&this.applyView(o,i,this.mountConfig.workspaceMode,"workspace")}}renderFlyoutBlocks(){if(!(!this.flyoutWorkspace||!this.mountConfig)){for(const e of this.flyoutWorkspace.getAllBlocks(!1)){const o=e,i=this.definitions.get(W(o.type));i&&this.applyView(o,i,this.mountConfig.toolboxMode,"toolbox")}this.applyFlyoutClass()}}refreshToolbox(){var e;!this.workspace||!this.toolboxDefinition||(e=this.mountConfig)!=null&&e.canvasToolbox||this.workspace.updateToolbox(this.toolboxDefinition)}bindFlyoutWorkspace(){var o;if(this.flyoutWorkspace&&(this.flyoutWorkspace.removeChangeListener(this.onFlyoutChange),this.flyoutWorkspace=void 0),!this.workspace)return;const e=(o=this.workspace.getFlyout())==null?void 0:o.getWorkspace();e&&(this.flyoutWorkspace=e,me.set(e,this),this.flyoutWorkspace.addChangeListener(this.onFlyoutChange),this.applyFlyoutClass())}resolveToolboxDefinition(e){if(e.toolbox){const s=this.resolveToolboxKind(e.toolboxLayout),r=s?{...e.toolbox,kind:s}:e.toolbox;return nt(r,this.definitions)}const o=e.blockly;if(o!=null&&o.toolbox)return o.toolbox;const i=this.resolveToolboxKind(e.toolboxLayout);return nt({...i!==void 0?{kind:i}:{},blocks:[...this.definitions.keys()]},this.definitions)}createBehaviorContext(e,o,i,s){return{Blockly:L,workspace:e.workspace,mode:i,context:s,definition:o}}resolveClassNames(e){return e?(Array.isArray(e)?e.join(" "):e).split(/\s+/).map(i=>i.trim()).filter((i,s,r)=>!!i&&r.indexOf(i)===s):[]}replaceUserClasses(e,o,i){for(const s of o)e.classList.remove(s);for(const s of i)e.classList.add(s)}buildBlockColorMap(){var o;const e=new Map;for(const[i,s]of this.definitions){const r=s.color??((o=this.blockCategoryIndex.get(i))==null?void 0:o.color);r!==void 0&&e.set(i,String(r))}return e}resolveToolboxKind(e){if(e)return e==="category"?"categoryToolbox":"flyoutToolbox"}createCategoryIndex(e,o){const i=new Map,s=(e==null?void 0:e.categories)??[],r=new Map;for(const a of s){const l=H(a.name);if(r.set(a.name.toLowerCase(),{token:l,color:a.color}),a.blocks)for(const d of a.blocks)i.has(d)||i.set(d,{token:l,color:a.color})}const c=o?this.definitions:new Map;for(const a of c.values()){if(!a.category||i.has(a.identifier))continue;const l=r.get(a.category.toLowerCase());l&&i.set(a.identifier,l)}return i}deferApplyView(e,o,i){const s=i==="toolbox"?this.flyoutWorkspace:this.workspace;s&&requestAnimationFrame(()=>{const r=s.getBlockById(e);if(!r)return;const c=this.definitions.get(W(r.type));c&&this.applyView(r,c,o,i)})}}function Xo(n,t,e){return Math.min(Math.max(n,t),e)}function Ko(n,t){const{target:e,axis:o,invert:i=!1,onResize:s}=t,r=t.min??0,c=t.max??Number.POSITIVE_INFINITY,a=l=>{if(l.button!==0)return;l.preventDefault();const d=e.getBoundingClientRect(),u=o==="x"?d.width:d.height,w=o==="x"?l.clientX:l.clientY,v=document.body.style.userSelect,C=document.body.style.cursor;document.body.style.userSelect="none",document.body.style.cursor=o==="x"?"col-resize":"row-resize",n.setPointerCapture(l.pointerId);const E=m=>{const y=(o==="x"?m.clientX:m.clientY)-w,S=Xo(u+(i?-y:y),r,c);e.style.flexBasis=`${S}px`,s==null||s(S)},k=()=>{n.removeEventListener("pointermove",E),n.removeEventListener("pointerup",k),n.removeEventListener("lostpointercapture",k),document.body.style.userSelect=v,document.body.style.cursor=C};n.addEventListener("pointermove",E),n.addEventListener("pointerup",k),n.addEventListener("lostpointercapture",k)};return n.addEventListener("pointerdown",a),{dispose:()=>n.removeEventListener("pointerdown",a)}}const Yo=Object.freeze(Object.defineProperty({__proto__:null,default:".morphic-placeholder-default,.morphic-placeholder-set{border-radius:2px;padding:0 .2em}.morphic-placeholder-default{font-style:italic;opacity:.55}"},Symbol.toStringTag,{value:"Module"})),Jo=Object.freeze(Object.defineProperty({__proto__:null,default:".morphic-toolbar{display:flex;align-items:center;gap:var(--morphic-toolbar-gap, .5em);padding:var(--morphic-toolbar-padding, 4px 8px);background:var(--morphic-toolbar-bg, inherit);color:var(--morphic-toolbar-fg, inherit);font:var(--morphic-toolbar-font, inherit);border-bottom:var(--morphic-toolbar-border, 1px solid rgba(127, 127, 127, .2));box-sizing:border-box}.morphic-toolbar-left,.morphic-toolbar-right{display:flex;align-items:center;gap:var(--morphic-toolbar-gap, .5em)}.morphic-toolbar-right{margin-left:auto}.morphic-toolbar-item{display:inline-flex;align-items:center;gap:4px;background:var(--morphic-toolbar-item-bg, transparent);color:inherit;border:var(--morphic-toolbar-item-border, none);padding:var(--morphic-toolbar-item-padding, 2px 6px);border-radius:var(--morphic-toolbar-item-radius, 3px);cursor:pointer;font:inherit;line-height:1}.morphic-toolbar-item:hover:not(:disabled){background:var(--morphic-toolbar-item-hover-bg, rgba(127, 127, 127, .15))}.morphic-toolbar-item:disabled{opacity:.4;cursor:default}.morphic-toolbar-icon{display:inline-flex}.morphic-toolbar-label{opacity:.7;font-size:.9em}.morphic-toolbox-header{display:flex;align-items:center;padding:4px 6px 8px}.morphic-toolbar-badge{font-size:.85em;opacity:.6;padding:1px 6px;border:1px solid currentColor;border-radius:3px}.morphic-toolbar-spacer{flex:1}"},Symbol.toStringTag,{value:"Module"}));A.MorphicBlocks=Go,A.MorphicToolboxCanvas=ot,A.makeResizable=Ko,A.renderToolbar=st,A.toolbarItems=O,A.validateDefinitions=qe,Object.defineProperty(A,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(P,U){typeof exports=="object"&&typeof module<"u"?U(exports,require("blockly/blocks"),require("blockly"),require("blockly/javascript")):typeof define=="function"&&define.amd?define(["exports","blockly/blocks","blockly","blockly/javascript"],U):(P=typeof globalThis<"u"?globalThis:P||self,U(P.MorphicBlocks={},P.Blockly,P.Blockly,P.javascript))})(this,(function(P,U,Q,ee){"use strict";var Pn=Object.defineProperty;var Fn=(P,U,Q)=>U in P?Pn(P,U,{enumerable:!0,configurable:!0,writable:!0,value:Q}):P[U]=Q;var v=(P,U,Q)=>Fn(P,typeof U!="symbol"?U+"":U,Q);function Dt(i){const o=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const e in i)if(e!=="default"){const t=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(o,e,t.get?t:{enumerable:!0,get:()=>i[e]})}}return o.default=i,Object.freeze(o)}const T=Dt(Q);function he(i){if(!(!i||typeof i=="function"))return i}function Nt(i){if(i)return typeof i=="function"?i:i.generate}const se="morphic-mode-",ue="morphic-context-",fe="morphic-shows-",Vt="morphic-view-",_e="morphic-preset-",We="morphic-category-",Pt="morphic-block-",Ft=-1,Ht=0,Rt=1;function W(i){if(i!==void 0)return typeof i=="string"?i:i.type}function je(i,o){const e={...i};for(const[t,n]of Object.entries(o??{})){const s=i[t];if(W(s)!=="code")continue;const{empty:r,stringQuote:c,emptyStatement:a,types:l}=n;if(r===void 0&&c===void 0&&a===void 0&&l===void 0)continue;const h={...typeof s=="string"?{type:s}:s,empty:r,stringQuote:c,emptyStatement:a,types:l};e[t]=h}return e}const te=16;function ze(i){if(!i||typeof i=="string")return{width:te,height:te};const o=i.size;if(o===void 0)return{width:te,height:te};if(typeof o=="number")return{width:o,height:o};const e=/^(\d+)(?:x(\d+))?$/i.exec(o.trim());if(!e)return{width:te,height:te};const t=Number.parseInt(e[1],10),n=e[2]?Number.parseInt(e[2],10):t;return{width:t,height:n}}function _t(i,o){if(i!=null&&i.default)return i.default;if(!o||typeof o=="string")return;const e=o.empty;if(!e)return;const t=i!=null&&i.check?Array.isArray(i.check)?i.check[0]:i.check:void 0;return(t?e[t]:void 0)??e.default}const Te="MORPHIC_TYPE_",pe=i=>{var o;return!!((o=i.name)!=null&&o.startsWith(Te))};function Ue(i,o,e){var c,a,l;const t=typeof e=="object"?e.types:void 0;if(!t)return"";const n=o!=null&&o.name?(a=(c=i.getInput(o.name))==null?void 0:c.connection)==null?void 0:a.targetBlock():null,s=typeof(o==null?void 0:o.check)=="string"?[o.check]:(o==null?void 0:o.check)??[],r=n?((l=n.outputConnection)==null?void 0:l.getCheck())??[]:s.length===1?s:[];for(const d of r){const h=t[d];if(h!==void 0)return h}return t.default??""}const me=18,Ge=":type";function oe(i){const o=[];let e=0;for(;e<i.length;){const t=i[e];if(t==="<"&&/^<img\b/i.test(i.slice(e))){const s=i.indexOf(">",e);if(s===-1){Ye(o,i.slice(e));break}const r=i.slice(e,s+1),c=Ut(r);c&&o.push(c),e=s+1;continue}if(t==="%"&&/\d/.test(i[e+1]??"")){let s=e+1;for(;s<i.length&&/\d/.test(i[s]??"");)s+=1;const r=Number.parseInt(i.slice(e+1,s),10);if(i.startsWith(Ge,s)){o.push({kind:"valueType",index:r}),e=s+Ge.length;continue}Number.isNaN(r)||o.push({kind:"placeholder",index:r}),e=s;continue}if(t==="%"&&/[A-Z_]/.test(i[e+1]??"")){let s=e+1;for(;s<i.length&&/[A-Z0-9_]/.test(i[s]??"");)s+=1;const r=i.slice(e+1,s);o.push({kind:"field",name:r}),e=s;continue}let n=e+1;for(;n<i.length;){const s=i[n],r=s==="%"&&/\d/.test(i[n+1]??""),c=s==="%"&&/[A-Z_]/.test(i[n+1]??"");if(s==="<"&&/^<img\b/i.test(i.slice(n))||r||c)break;n+=1}Ye(o,i.slice(e,n)),e=n}return Gt(o)}function Wt(i){return i.replace(/\s+/g," ").trim()}function H(i){return i.trim().replace(/[^A-Za-z0-9_-]+/g,"-")}function Le(i){return i.map(o=>o.kind==="text"?jt(o.value):o.kind==="image"?`<img src="${ge(o.src)}" alt="${ge(o.alt)}" width="${o.width}" height="${o.height}">`:o.kind==="field"?`<span class="morphic-field-placeholder" data-field-name="${ge(o.name)}"></span>`:o.kind==="valueType"?`<span class="morphic-value-type" data-slot-index="${o.index}"></span>`:`<span class="morphic-toolbox-slot" data-slot-index="${o.index}"></span>`).join("")}function jt(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function ge(i){return i.replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const zt=/\.(svg|png|jpe?g|gif|webp)(?:[#?].*)?$/i;function Xe(i,o){if(!i)return i;const e=i.trim();return/^<img\b/i.test(e)?i:zt.test(e)?`<img src="${ge(e)}" width="${o.width}" height="${o.height}">`:i}function Ut(i){if(!/^<img\b/i.test(i))return null;const o=we(i,"src");if(!o)return null;const e=we(i,"alt")??"",t=Number.parseInt(we(i,"width")??`${me}`,10),n=Number.parseInt(we(i,"height")??`${me}`,10);return{kind:"image",src:o,alt:e,width:Number.isNaN(t)?me:t,height:Number.isNaN(n)?me:n}}function we(i,o){const e=new RegExp(`${o}\\s*=\\s*(['"])(.*?)\\1`,"i").exec(i);if(e!=null&&e[2])return e[2];const t=new RegExp(`${o}\\s*=\\s*([^\\s>]+)`,"i").exec(i);return(t==null?void 0:t[1])??null}function Ye(i,o){o&&i.push({kind:"text",value:o})}function Gt(i){const o=[];for(const e of i){const t=o[o.length-1];if(e.kind==="text"&&(t==null?void 0:t.kind)==="text"){t.value+=e.value;continue}o.push(e)}return o}function Ke(i){const{block:o,definition:e,view:t,mode:n,context:s,elementTypes:r,resolveBlocklyType:c}=i,a=so(o),l=ro(o);fo(o),Jt(o,e,t),po(o,e),typeof e.inputsInline=="boolean"&&o.setInputsInline(e.inputsInline),e.color!==void 0&&o.setColour(e.color),e.tooltip&&o.setTooltip(e.tooltip),e.helpUrl&&o.setHelpUrl(e.helpUrl),lo(o,a),co(o,l),r&&ao(o,e,t,r,c),Zt(o,e,t,i.codeSettings??r),Je(o,n,s);const d=o;d.__morphicMode=n,d.__morphicContext=s,Be(o)&&o.render()}function Be(i){var o;return i.rendered&&!!((o=i.getSvgRoot())!=null&&o.parentNode)}function qe(i,o,e,t){K(i.classList,se),K(i.classList,ue),i.classList.add(t),i.classList.add(`${se}${H(o)}`),i.classList.add(`${ue}${e}`)}function Xt(i){return i.__morphicMode}function Yt(i,o){const e=i.getSvgRoot();e&&(K(e.classList,We),o&&e.classList.add(`${We}${o}`))}function Kt(i,o){const e=i.getSvgRoot();if(!e)return;const t=`${Pt}${H(o)}`;e.classList.contains(t)||e.classList.add(t)}function qt(i){const o=i.getSvgRoot();if(!o)return;const e=getComputedStyle(o).getPropertyValue("--morphic-block-color").trim();e&&(i.setColour(e),Be(i)&&i.render())}function ke(i,o){K(i.classList,se),K(i.classList,fe),i.classList.add("morphic-view",...o.classNames),o.name&&i.classList.add(`${Vt}${H(o.name)}`),o.element&&i.classList.add(`${fe}${H(o.element)}`)}function ve(i,o){K(i.classList,_e),o&&i.classList.add(`${_e}${H(o)}`)}function Je(i,o,e){const t=i.getSvgRoot();if(!t)return;K(t.classList,se),K(t.classList,fe),K(t.classList,ue);const n=e==="workspace"?fe:se;t.classList.add(`${n}${H(o)}`),t.classList.add(`${ue}${e}`)}function Jt(i,o,e){var r;const t=oe(e.template),n=[],s=new Set;for(const c of t){if(c.kind==="text"){const d=Wt(c.value);d&&n.push(d);continue}if(c.kind==="image"){n.push(new T.FieldImage(c.src,c.width,c.height,c.alt));continue}if(c.kind==="valueType"){n.push({field:new T.FieldLabel(""),name:`${Te}${c.index}`});continue}if(c.kind==="field"){const d=(r=o.fields)==null?void 0:r[c.name];d&&n.push({field:to(d,e.elementName),name:c.name});continue}if(s.has(c.index)){const d=i.appendDummyInput(`DUPLICATE_${c.index}_${i.inputList.length}`);ye(d,n),d.appendField(`%${c.index}`);continue}s.add(c.index);const a=Ze(o,e,c.index);if((a==null?void 0:a.kind)==="statement"&&n.length>0){const d=i.appendDummyInput(`PRE_STMT_${i.inputList.length}`);ye(d,n)}const l=Qt(i,a,c.index);ye(l,n),a!=null&&a.label&&l.appendField(a.label)}if(n.length>0){const c=i.appendDummyInput(`TRAILING_${i.inputList.length}`);ye(c,n)}i.inputList.length===0&&i.appendDummyInput("LABEL").appendField(o.identifier)}function Zt(i,o,e,t){const n=i.inputList.flatMap(c=>c.fieldRow.filter(pe));if(n.length===0){i.onchange&&i.setOnChange(()=>{});return}const s=e.elementName?t==null?void 0:t[e.elementName]:void 0,r=()=>{for(const c of n){const a=c.name.slice(Te.length),l=Ue(i,Ze(o,e,Number(a)),s);c.getValue()!==l&&c.setValue(l)}};r(),i.setOnChange(c=>{(c.type===T.Events.BLOCK_MOVE||c.type===T.Events.BLOCK_CREATE)&&r()})}function Ze(i,o,e){var n,s;const t=`${e}`;return((n=o.inputSlots)==null?void 0:n[t])??((s=i.inputSlots)==null?void 0:s[t])}function Qt(i,o,e){const t=(o==null?void 0:o.name)??`ARG${e}`,n=(o==null?void 0:o.kind)??"value";let s;return n==="statement"?(s=i.appendStatementInput(t),o!=null&&o.check&&s.setCheck(o.check)):(s=i.appendValueInput(t),o!=null&&o.check&&s.setCheck(o.check)),o!=null&&o.align&&s.setAlign(eo(o.align)),s}function eo(i){return i==="right"?Rt:i==="centre"?Ht:Ft}function ye(i,o){for(const e of o)typeof e=="object"&&"field"in e?i.appendField(e.field,e.name):i.appendField(e);o.length=0}function to(i,o){switch(i.type){case"dropdown":{const e=i.options.map(n=>oo(n,o)),t=new no(e);return i.default!==void 0&&t.setValue(i.default),t}case"number":return new T.FieldNumber(i.default??0,i.min,i.max,i.precision);case"checkbox":return new T.FieldCheckbox(i.default?"TRUE":"FALSE");case"text":default:return new T.FieldTextInput(i.default??"")}}function oo(i,o){var n;if(typeof i=="string")return[i,i];if(Array.isArray(i)){const[s,r]=i;return[r??s,s]}const e=o?(n=i.display)==null?void 0:n[o]:void 0;if(e!==void 0)return[e,i.value];const t=i.label;if(t&&typeof t=="object"){const s=t.width??16,r=t.height??16;return[{src:t.color!==void 0?io(t.color,s,r):t.src,alt:t.alt??i.value,width:s,height:r},i.value]}return[t??i.value,i.value]}class no extends T.FieldDropdown{showEditor_(o){var t;super.showEditor_(o);const e=(t=this.menu_)==null?void 0:t.getElement();e==null||e.classList.add("morphic-menu"),this.name&&(e==null||e.classList.add(`morphic-menu-${this.name}`))}}function io(i,o,e){const t=`<svg xmlns="http://www.w3.org/2000/svg" width="${o}" height="${e}"><rect width="${o}" height="${e}" rx="3" fill="${i.replace(/["<>&]/g,"")}"/></svg>`;return`data:image/svg+xml,${encodeURIComponent(t)}`}function so(i){var e;const o=new Map;for(const t of i.inputList){const n=(e=t.connection)==null?void 0:e.targetBlock();n&&!n.isShadow()&&o.set(t.name,n)}return o}function ro(i){var e;const o=new Map;for(const t of i.inputList){const n=(e=t.connection)==null?void 0:e.getShadowState(!0);n&&o.set(t.name,n)}return o}function co(i,o){var e;for(const[t,n]of o){const s=(e=i.getInput(t))==null?void 0:e.connection;if(!(!s||s.getShadowState()))try{s.setShadowState(n)}catch{}}}function ao(i,o,e,t,n=s=>s){var a,l;const s=e.elementName?t[e.elementName]:void 0,r=new Map;for(const d of Object.values(o.inputSlots??{}))d!=null&&d.name&&(d.kind??"value")==="value"&&r.set(d.name,d);if(r.size===0)return;const c=i.workspace;for(const d of i.inputList){const h=d.connection;if(!h||h.type!==T.INPUT_VALUE)continue;const u=r.get(d.name);if(!u)continue;const p=_t(u,s);if(p){if(p.shadow&&!(((a=h.getShadowState)==null?void 0:a.call(h,!0))??((l=h.getShadowDom)==null?void 0:l.call(h))))try{h.setShadowState({type:n(p.shadow),fields:p.fieldValues??{}})}catch{}if(p.placeholder){const m=i,w=m.__morphicPlaceholderSlots??(m.__morphicPlaceholderSlots=new Set),b=h.targetBlock(),k=!b||b.isShadow(),B=w.has(d.name);if(w.add(d.name),k&&!B)try{const L=c.newBlock(n(p.placeholder));if(p.fieldValues)for(const[E,x]of Object.entries(p.fieldValues)){const g=L.getField(E);g&&g.setValue(x)}L.outputConnection&&h.connect(L.outputConnection),i.rendered&&(L.initSvg(),L.queueRender())}catch{}}}}}function lo(i,o){for(const[e,t]of o){const n=i.getInput(e);if(!(n!=null&&n.connection)||n.connection.isConnected())continue;const s=[t.outputConnection,t.previousConnection];for(const r of s)if(r)try{n.connection.connect(r);break}catch{continue}}}function ho(i){const o=new Map;for(const e of i.inputList)for(const t of e.fieldRow)t.name&&!pe(t)&&o.set(t.name,t.getValue());return o}function uo(i,o){for(const[e,t]of o){const n=i.getField(e);if(n&&t!==void 0&&t!==null)try{n.setValue(t)}catch{}}}function fo(i){for(;i.inputList.length>0;){const o=i.inputList[0];if(!o)break;i.removeInput(o.name,!0)}}function po(i,o){o.output!==void 0&&mo(i,o.output),o.previousStatement!==void 0&&go(i,o.previousStatement),o.nextStatement!==void 0&&wo(i,o.nextStatement)}function mo(i,o){if(o===!1){i.setOutput(!1);return}if(o===!0){i.setOutput(!0);return}i.setOutput(!0,o)}function go(i,o){if(o===!1){i.setPreviousStatement(!1);return}if(o===!0){i.setPreviousStatement(!0);return}i.setPreviousStatement(!0,o)}function wo(i,o){if(o===!1){i.setNextStatement(!1);return}if(o===!0){i.setNextStatement(!0);return}i.setNextStatement(!0,o)}function K(i,o){const e=Array.from(i).filter(t=>t.startsWith(o));for(const t of e)i.remove(t)}function Qe(i,o,e){if(!e)return[];const t={keyword:i.Decoration.mark({class:"morphic-tok-keyword"}),string:i.Decoration.mark({class:"morphic-tok-string"}),number:i.Decoration.mark({class:"morphic-tok-number"}),comment:i.Decoration.mark({class:"morphic-tok-comment"})},n=et(e),s=(u,p,m)=>{for(const w of n(u))m.add(p+w.from,p+w.to,t[w.kind])},r=u=>{const p=new o.RangeSetBuilder,m=u.state.doc;for(const{from:w,to:b}of u.visibleRanges){let k=w;for(;k<=b;){const B=m.lineAt(k);if(s(B.text,B.from,p),B.to>=b)break;k=B.to+1}}return p.finish()},c=i.ViewPlugin.fromClass(class{constructor(u){v(this,"decorations");this.decorations=r(u)}update(u){(u.docChanged||u.viewportChanged)&&(this.decorations=r(u.view))}},{decorations:u=>u.decorations}),a=i.EditorView.baseTheme({".morphic-tok-keyword":{color:"#cc7832"},".morphic-tok-string":{color:"#6a8759"},".morphic-tok-number":{color:"#6897bb"},".morphic-tok-comment":{color:"#808080",fontStyle:"italic"}}),l=e.colors??{},d={};l.keyword&&(d[".cm-content .morphic-tok-keyword"]={color:l.keyword}),l.string&&(d[".cm-content .morphic-tok-string"]={color:l.string}),l.number&&(d[".cm-content .morphic-tok-number"]={color:l.number}),l.comment&&(d[".cm-content .morphic-tok-comment"]={color:l.comment,fontStyle:"italic"});const h=[c,a];return Object.keys(d).length>0&&h.push(i.EditorView.theme(d)),h}function et(i){const o=new Set(i.keywords??[]),e=(i.strings??[]).map(s=>typeof s=="string"?{open:s,close:s}:{open:s[0],close:s[1]}),t=i.comment,n=i.numbers!==!1;return s=>{const r=[],c=s.length;let a=0;for(;a<c;){if(t&&s.startsWith(t,a))return r.push({from:a,to:c,kind:"comment"}),r;let l=!1;for(const h of e)if(s.startsWith(h.open,a)){const u=a;for(a+=h.open.length;a<c;){if(s[a]==="\\"&&a+1<c){a+=2;continue}if(s.startsWith(h.close,a)){a+=h.close.length;break}a+=1}r.push({from:u,to:a,kind:"string"}),l=!0;break}if(l)continue;if(n){const h=/^\d+(?:\.\d+)?/.exec(s.slice(a));if(h){r.push({from:a,to:a+h[0].length,kind:"number"}),a+=h[0].length;continue}}const d=/^[\p{L}\p{M}_][\p{L}\p{M}\p{N}_]*/u.exec(s.slice(a));if(d){o.has(d[0])&&r.push({from:a,to:a+d[0].length,kind:"keyword"}),a+=d[0].length;continue}a+=1}return r}}const Ie="morphic/block-id";let be;function Me(i){const{from:o,to:e,empty:t}=i.selection.main;if(t)return null;const n=i.doc.lineAt(o).number,s=i.doc.lineAt(e),r=s.from===e&&s.number>n?s.number-1:s.number;return{first:n,last:r}}function $e(){return be}function tt(i){be=i}const re={fontSize:"14px",fontFamily:"monospace",lineHeight:1.5,background:"#1e1e1e",foreground:"#d4d4d4",gutterBackground:"#1e1e1e",gutterForeground:"#858585",selectionBackground:"#264f78"};function ko(i){return typeof ResizeObserver>"u"?[]:[i.ViewPlugin.fromClass(class{constructor(o){v(this,"observer");v(this,"watched",new Set);v(this,"destroyed",!1);this.view=o,this.observer=new ResizeObserver(()=>{const e=this.view.viewState;e&&(e.mustMeasureContent=!0),this.view.requestMeasure()}),queueMicrotask(()=>this.watch())}update(){queueMicrotask(()=>this.watch())}destroy(){this.destroyed=!0,this.observer.disconnect()}watch(){if(this.destroyed)return;const o=new Set(Array.from(this.view.contentDOM.children));for(const e of this.watched)o.has(e)||(this.observer.unobserve(e),this.watched.delete(e));for(const e of o)this.watched.has(e)||(this.observer.observe(e,{box:"border-box"}),this.watched.add(e))}})]}const ce=(i,o)=>`color-mix(in srgb, ${i} ${o}%, transparent)`;let ot=!1;async function vo(){if(ot)return;ot=!0;const o=(await Promise.resolve().then(()=>Nn)).default,e=document.createElement("style");e.dataset.morphicSource="code-editor",e.textContent=o,document.head.appendChild(e)}const yo=150,bo=new Set(["create","delete","move","change"]);function Co(i){return bo.has(i.type)}async function Eo(i){let o,e;try{[o,e]=await Promise.all([import("@codemirror/view"),import("@codemirror/state")])}catch{throw new Error(`CodeMirror is required for the codespace, preview and code editor. Install it:
2
+ npm install @codemirror/view @codemirror/state`)}if(!i)return{view:o,state:e,langJs:void 0};try{return{view:o,state:e,langJs:await import("@codemirror/lang-javascript")}}catch{throw new Error(`The code editor also needs JavaScript language support. Install it:
3
+ npm install @codemirror/lang-javascript`)}}function Ae(i,o){const e={...re,...o};return i.EditorView.theme({"&":{fontSize:e.fontSize,fontFamily:e.fontFamily,backgroundColor:e.background,color:e.foreground},".cm-scroller":{fontFamily:e.fontFamily},".cm-content":{lineHeight:String(e.lineHeight)},".cm-gutters":{backgroundColor:e.gutterBackground,color:e.gutterForeground,border:"none"},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground":{backgroundColor:`${e.selectionBackground} !important`},".morphic-delete-marker":{color:ce(e.foreground,70),backgroundColor:ce(e.foreground,12)},".morphic-delete-marker:hover":{color:e.foreground,backgroundColor:ce(e.foreground,22)},".morphic-grip-marker":{color:ce(e.foreground,75)},".morphic-grip-marker:hover":{color:e.foreground}})}class nt{constructor(o,e,t,n={},s=!1){v(this,"editorView");v(this,"container");v(this,"options");v(this,"workspace");v(this,"generateWithMetadata");v(this,"visible",!0);v(this,"syncTimer");v(this,"changeListener");v(this,"lastCode","");v(this,"metadata",new Map);v(this,"placeholders",[]);v(this,"placeholderEditorEl");v(this,"placeholderEditorScrollHandler");v(this,"placeholderEditorOutsideHandler");v(this,"onCursorLine");v(this,"onEmptyClick");v(this,"cm");v(this,"themeCompartment");v(this,"syntaxHighlightCompartment");v(this,"highlightEffect");v(this,"themeSelection",re.selectionBackground);v(this,"activeHighlight");v(this,"metadataEffect");v(this,"placeholderEffect");v(this,"dropIndicatorEffect");v(this,"valueSlotHighlightEffect");v(this,"hoverHighlightEffect");v(this,"groupsEffect");v(this,"editableHoverHighlightEffect");v(this,"emptyClickListener");v(this,"disposed",!1);v(this,"zoomFactor",1);this.javascript=s,this.container=o,this.workspace=e,this.generateWithMetadata=t,this.options=n}getPlaceholders(){return this.placeholders}findPlaceholderAtPos(o){if(this.options.showPlaceholderMarkers===!1)return null;let e=null,t=1/0;for(const n of this.placeholders){if(n.start>o)break;if(o>=n.start&&o<=n.end){const s=n.end-n.start;s<t&&(t=s,e=n)}}return e}closePlaceholderEditor(){const o=this.placeholderEditorEl;o&&(this.placeholderEditorEl=void 0,this.placeholderEditorScrollHandler&&this.editorView&&(this.editorView.scrollDOM.removeEventListener("scroll",this.placeholderEditorScrollHandler),this.placeholderEditorScrollHandler=void 0),this.placeholderEditorOutsideHandler&&(document.removeEventListener("mousedown",this.placeholderEditorOutsideHandler),this.placeholderEditorOutsideHandler=void 0),o.parentNode&&o.parentNode.removeChild(o))}openPlaceholderEditor(o){if(!this.editorView||!o.edit)return;const e=this.options.onPlaceholderApply;if(!e)return;this.closePlaceholderEditor();const t=this.editorView,n=t.coordsAtPos(o.start),s=t.coordsAtPos(o.end);if(!n||!s)return;const r=t.scrollDOM.getBoundingClientRect(),c=t.state.doc.sliceString(o.start,o.end),a=o.edit;let l;if(a.fieldType==="dropdown"){const m=document.createElement("select");for(const[w,b]of a.options??[]){const k=document.createElement("option");k.value=b,k.textContent=w,m.appendChild(k)}l=m}else{const m=document.createElement("input");m.type=a.fieldType==="number"?"number":"text",m.value=c,l=m}const d=getComputedStyle(t.contentDOM),h=(()=>{let m=t.dom;for(;m;){const w=getComputedStyle(m).backgroundColor;if(w&&w!=="rgba(0, 0, 0, 0)"&&w!=="transparent")return w;m=m.parentElement}return"#fff"})();Object.assign(l.style,{position:"absolute",left:`${n.left-r.left+t.scrollDOM.scrollLeft}px`,top:`${n.top-r.top+t.scrollDOM.scrollTop}px`,minWidth:`${Math.max(40,s.right-n.left+8)}px`,height:`${n.bottom-n.top}px`,font:d.font,lineHeight:d.lineHeight,padding:"0 2px",margin:"0",border:`1px solid ${d.color}`,borderRadius:"2px",background:h,color:d.color,boxSizing:"border-box",zIndex:"20"}),t.scrollDOM.appendChild(l),this.placeholderEditorEl=l;const u=()=>{const m=l.value;this.closePlaceholderEditor(),e(a,m)},p=()=>{this.closePlaceholderEditor()};if(l.addEventListener("keydown",m=>{const w=m.key;w==="Enter"?(m.preventDefault(),u()):w==="Escape"&&(m.preventDefault(),p())}),l.addEventListener("mousedown",m=>m.stopPropagation()),l.addEventListener("click",m=>m.stopPropagation()),a.fieldType==="dropdown"){l.addEventListener("change",()=>u());const m=this.workspace.getBlockById(a.blockId),w=m==null?void 0:m.getField(a.fieldName),b=w==null?void 0:w.getValue();b!=null&&(l.value=String(b)),requestAnimationFrame(()=>{this.placeholderEditorOutsideHandler=k=>{k.target instanceof Node&&!l.contains(k.target)&&p()},document.addEventListener("mousedown",this.placeholderEditorOutsideHandler)})}else l.addEventListener("blur",()=>u());this.placeholderEditorScrollHandler=()=>this.closePlaceholderEditor(),t.scrollDOM.addEventListener("scroll",this.placeholderEditorScrollHandler),requestAnimationFrame(()=>{l.focus({preventScroll:!0}),l instanceof HTMLInputElement&&l.select()})}async mount(){var B,L;if(vo(),this.cm=await Eo(this.javascript),this.disposed)return;const{view:o,state:e,langJs:t}=this.cm;this.themeCompartment=new e.Compartment,this.syntaxHighlightCompartment=new e.Compartment;const n=Ae(o,this.options.theme??{});this.themeSelection=((B=this.options.theme)==null?void 0:B.selectionBackground)??re.selectionBackground;const s=Qe(o,e,this.options.highlightRules),r=e.StateEffect.define();this.metadataEffect=r;const c=e.StateEffect.define();this.placeholderEffect=c;const a=e.StateField.define({create(){return o.Decoration.none},update(E,x){for(const g of x.effects)if(g.is(c)){const C=g.value;if(!C||C.length===0)return o.Decoration.none;const f=x.state.doc.length,y=[...C].filter(V=>V.start<V.end&&V.end<=f).sort((V,I)=>V.start-I.start||V.end-I.end),S=new e.RangeSetBuilder,M=o.Decoration.mark({class:"morphic-placeholder-default"}),O=o.Decoration.mark({class:"morphic-placeholder-set"});for(const V of y)S.add(V.start,V.end,V.kind==="default"?M:O);return S.finish()}return x.changes.empty?E:o.Decoration.none},provide(E){return o.EditorView.decorations.from(E)}}),l=e.StateEffect.define();this.highlightEffect=l;const d=this,h=e.StateField.define({create(){return o.Decoration.none},update(E,x){for(const g of x.effects)if(g.is(l)){const C=g.value;if(!C)return o.Decoration.none;const f=Array.isArray(C)?C:[C];if(f.length===0)return o.Decoration.none;const y=x.state.doc,S=o.Decoration.mark({class:"morphic-highlight",attributes:{style:`background: var(--morphic-highlight-color, ${ce(d.themeSelection,60)})`}}),M=f.map(O=>{const V=y.line(Math.min(O.fromLine,y.lines)).from,I=y.line(Math.min(O.toLine,y.lines)).to;return S.range(V,I)}).sort((O,V)=>O.from-V.from);return o.Decoration.set(M)}return x.changes.empty?E:o.Decoration.none},provide(E){return o.EditorView.decorations.from(E)}}),u=o.EditorView.updateListener.of(E=>{var f;if(E.docChanged||E.transactions.some(y=>y.isUserEvent("select.pointer")))return;const x=E.state.selection.main.head,g=E.startState.selection.main.head;if(x===g)return;if(d.findPlaceholderAtPos(x)){(f=d.onEmptyClick)==null||f.call(d);return}if(!d.onCursorLine)return;const C=E.state.doc.lineAt(x).number;d.onCursorLine(C)});let p="";const m=o.EditorView.updateListener.of(E=>{var C,f;if(!E.selectionSet&&!E.docChanged)return;const x=Me(E.state),g=x?`${x.first}-${x.last}`:"";g!==p&&(p=g,(f=(C=d.options).onLineSelection)==null||f.call(C))}),w=this.options.showPlaceholderMarkers!==!1,b=[o.lineNumbers(),o.highlightSpecialChars(),e.EditorState.readOnly.of(!0),...t?[t.javascript()]:[],h,...w?[a]:[],u,m,this.themeCompartment.of(n),this.syntaxHighlightCompartment.of(s),...this.buildDeleteExtensions(o,e,r),...this.buildGripExtensions(o,e,r),...this.buildDropIndicatorExtensions(o,e),...this.buildValueSlotHighlightExtensions(o,e),...this.buildHoverHighlightExtensions(o,e),...this.buildGroupExtensions(o,e),...ko(o),...this.buildEditableHoverHighlightExtensions(o,e),...this.options.extensions??[]],k=this.generateWithMetadata();this.lastCode=k.code,this.metadata=k.metadata,this.placeholders=[...k.placeholders].sort((E,x)=>E.start-x.start),this.editorView=new o.EditorView({parent:this.container,state:e.EditorState.create({doc:this.lastCode,extensions:b})}),this.groupsEffect&&((L=k.groups)!=null&&L.length)&&this.editorView.dispatch({effects:this.groupsEffect.of(k.groups)}),this.metadataEffect&&this.metadata.size>0&&this.editorView.dispatch({effects:this.metadataEffect.of(this.metadata)}),this.placeholderEffect&&k.placeholders.length>0&&this.editorView.dispatch({effects:this.placeholderEffect.of(k.placeholders)}),this.emptyClickListener=E=>{var g,C,f;if(this.isBelowLastLine(E.clientY)){(g=this.onEmptyClick)==null||g.call(this);return}const x=(C=this.editorView)==null?void 0:C.posAtCoords({x:E.clientX,y:E.clientY});if(typeof x=="number"){const y=this.findPlaceholderAtPos(x);if(y){(f=this.onEmptyClick)==null||f.call(this),y.edit&&this.options.onPlaceholderApply&&requestAnimationFrame(()=>this.openPlaceholderEditor(y));return}}if(this.onCursorLine){const y=this.getLineAtCoords(E.clientX,E.clientY);y!==null&&this.onCursorLine(y)}},this.editorView.scrollDOM.addEventListener("click",this.emptyClickListener),this.attachSyncListener()}buildDeleteExtensions(o,e,t){const n=this.options.onDelete;if(!n)return[];class s extends o.GutterMarker{toDOM(){const u=document.createElement("span");return u.textContent="✕",u.className="morphic-delete-marker",u.style.cssText=["display: inline-flex","align-items: center","justify-content: center","width: 16px","height: 16px","margin: 0 4px","border-radius: 50%","font-size: 10px","line-height: 1","cursor: pointer","transition: background 0.15s, color 0.15s"].join(";"),u}}const r=new s,c=e.StateField.define({create(){return e.RangeSet.empty},update(h,u){for(const p of u.effects)if(p.is(t)){const m=p.value,w=u.state.doc,b=new Set;for(const{startLine:B}of m.values())B>=1&&B<=w.lines&&b.add(B);const k=Array.from(b).sort((B,L)=>B-L).map(B=>r.range(w.line(B).from));return e.RangeSet.of(k,!0)}return h.map(u.changes)}}),a=o.gutter({class:"morphic-delete-gutter",markers(h){return h.state.field(c)},initialSpacer:()=>r,domEventHandlers:{click(h,u){const p=h.state.doc.lineAt(u.from).number;return n(p),!0}}}),l=h=>{const u=Me(h.state);return u?n(u.first,u.last):n(h.state.doc.lineAt(h.state.selection.main.head).number),!0},d=o.keymap.of([{key:"Delete",run:l},{key:"Backspace",run:l}]);return[...this.options.deleteButtons!==!1?[c,a]:[],...this.options.deleteKeys!==!1?[e.Prec.highest(d)]:[]]}buildGripExtensions(o,e,t){const n=this.options.canDragBlock;if(!n)return[];class s extends o.GutterMarker{constructor(l){super(),this.blockId=l}eq(l){return l instanceof s&&l.blockId===this.blockId}toDOM(){const l=document.createElement("span");l.textContent="⠿",l.draggable=!0,l.className="morphic-grip-marker",l.style.cssText=["display: inline-flex","align-items: center","justify-content: center","width: 16px","height: 16px","margin: 0 2px","font-size: 14px","line-height: 1","cursor: grab","user-select: none","transition: color 0.15s"].join(";");const d=this.blockId;return l.addEventListener("dragstart",h=>{h.dataTransfer&&(h.dataTransfer.setData(Ie,d),h.dataTransfer.effectAllowed="move",l.style.cursor="grabbing",be=d)}),l.addEventListener("dragend",()=>{l.style.cursor="grab",be=void 0}),l}}const r=e.StateField.define({create(){return e.RangeSet.empty},update(a,l){for(const d of l.effects)if(d.is(t)){const h=d.value,u=l.state.doc,p=new Map;for(const[w,{startLine:b,startChar:k,endChar:B}]of h){if(b<1||b>u.lines||!n(w))continue;const L=(B??0)-(k??0),E=p.get(b);(!E||L>E.width)&&p.set(b,{id:w,width:L})}const m=Array.from(p.entries()).sort((w,b)=>w[0]-b[0]).map(([w,{id:b}])=>new s(b).range(u.line(w).from));return e.RangeSet.of(m,!0)}return a.map(l.changes)}}),c=o.gutter({class:"morphic-grip-gutter",markers(a){return a.state.field(r)},initialSpacer:()=>new s("")});return[r,c]}buildDropIndicatorExtensions(o,e){const t=e.StateEffect.define();this.dropIndicatorEffect=t;const n=e.StateField.define({create(){return o.Decoration.none},update(r,c){for(const a of c.effects)if(a.is(t)){const l=a.value;if(!l)return o.Decoration.none;const d=c.state.doc,h=Math.max(1,Math.min(l.line,d.lines)),u=d.line(h),p=l.position==="above"?"morphic-drop-indicator-above":"morphic-drop-indicator-below",m=o.Decoration.line({class:p});return o.Decoration.set([m.range(u.from)])}return c.changes.empty?r:o.Decoration.none},provide(r){return o.EditorView.decorations.from(r)}}),s=o.EditorView.baseTheme({".morphic-drop-indicator-above":{boxShadow:"inset 0 2px 0 0 #5a86bc"},".morphic-drop-indicator-below":{boxShadow:"inset 0 -2px 0 0 #5a86bc"}});return[n,s]}buildValueSlotHighlightExtensions(o,e){const t=e.StateEffect.define();this.valueSlotHighlightEffect=t;const n=o.Decoration.mark({class:"morphic-value-slot-target"}),s=e.StateField.define({create(){return o.Decoration.none},update(c,a){for(const l of a.effects)if(l.is(t)){const d=l.value;if(!d)return o.Decoration.none;const h=a.state.doc.length,u=Math.max(0,Math.min(d.from,h)),p=Math.max(u,Math.min(d.to,h));return u===p?o.Decoration.none:o.Decoration.set([n.range(u,p)])}return a.changes.empty?c:o.Decoration.none},provide(c){return o.EditorView.decorations.from(c)}}),r=o.EditorView.baseTheme({".morphic-value-slot-target":{outline:"1px solid #5a86bc",outlineOffset:"1px",borderRadius:"2px"}});return[s,r]}buildGroupExtensions(o,e){const t=e.StateEffect.define(),n=e.StateEffect.define();this.groupsEffect=t;class s extends o.GutterMarker{constructor(p){super(),this.elementClass=p}eq(p){return p.elementClass===this.elementClass}}const r=e.StateField.define({create:()=>({groups:[],hover:null}),update(u,p){let m=u;for(const w of p.effects)w.is(t)&&(m={groups:w.value,hover:null}),w.is(n)&&(m={...m,hover:w.value});return m}}),c=u=>{const{groups:p,hover:m}=u.field(r),w=new Map;return p.forEach(({startLine:b,endLine:k},B)=>{for(let L=b;L<=Math.min(k,u.doc.lines);L++){const E=[B%2===0?"morphic-group-odd":"morphic-group-even"];L===b&&E.push("morphic-group-start"),L===k&&E.push("morphic-group-end"),k>b&&E.push("morphic-group-line"),B===m&&E.push("morphic-group-hover"),w.set(L,E.join(" "))}}),w},a=o.EditorView.decorations.compute([r,"doc"],u=>{const p=[...c(u)].map(([m,w])=>o.Decoration.line({class:w}).range(u.doc.line(m).from));return o.Decoration.set(p)}),l=o.gutterLineClass.compute([r,"doc"],u=>e.RangeSet.of([...c(u)].map(([p,m])=>new s(m).range(u.doc.line(p).from)))),d=(u,p)=>{const m=u.posAtCoords({x:p.clientX,y:p.clientY},!1),w=u.state.doc.lineAt(m).number,b=u.state.field(r).groups.findIndex(k=>w>=k.startLine&&w<=k.endLine);return b===-1?null:b},h=o.EditorView.domEventHandlers({mousemove(u,p){const m=d(p,u);m!==p.state.field(r).hover&&p.dispatch({effects:n.of(m)})},mouseleave(u,p){p.state.field(r).hover!==null&&p.dispatch({effects:n.of(null)})}});return[r,a,l,h]}buildHoverHighlightExtensions(o,e){const t=e.StateEffect.define();this.hoverHighlightEffect=t;const n=o.Decoration.mark({class:"morphic-hover-target"}),s=e.StateField.define({create(){return o.Decoration.none},update(c,a){for(const l of a.effects)if(l.is(t)){const d=l.value;if(!d)return o.Decoration.none;const h=a.state.doc.length,u=Math.max(0,Math.min(d.from,h)),p=Math.max(u,Math.min(d.to,h));return u===p?o.Decoration.none:o.Decoration.set([n.range(u,p)])}return a.changes.empty?c:o.Decoration.none},provide(c){return o.EditorView.decorations.from(c)}}),r=o.EditorView.baseTheme({".morphic-hover-target":{backgroundColor:"rgba(127, 127, 127, 0.10)",borderRadius:"2px"}});return[s,r]}setHoverHighlight(o){!this.editorView||!this.hoverHighlightEffect||this.editorView.dispatch({effects:this.hoverHighlightEffect.of(o)})}buildEditableHoverHighlightExtensions(o,e){const t=e.StateEffect.define();this.editableHoverHighlightEffect=t;const n=o.Decoration.mark({class:"morphic-editable-hover"}),s=e.StateField.define({create(){return o.Decoration.none},update(c,a){for(const l of a.effects)if(l.is(t)){const d=l.value;if(!d)return o.Decoration.none;const h=a.state.doc.length,u=Math.max(0,Math.min(d.from,h)),p=Math.max(u,Math.min(d.to,h));return u===p?o.Decoration.none:o.Decoration.set([n.range(u,p)])}return a.changes.empty?c:o.Decoration.none},provide(c){return o.EditorView.decorations.from(c)}}),r=o.EditorView.baseTheme({".morphic-editable-hover":{outline:"1px solid #5a86bc",outlineOffset:"1px",borderRadius:"2px"}});return[s,r]}setEditableHoverHighlight(o){!this.editorView||!this.editableHoverHighlightEffect||this.editorView.dispatch({effects:this.editableHoverHighlightEffect.of(o)})}show(){this.visible||(this.visible=!0,this.container.style.display="",this.syncNow(),this.attachSyncListener())}hide(){this.visible&&(this.visible=!1,this.container.style.display="none",this.detachSyncListener())}isVisible(){return this.visible}highlightLines(o){!this.editorView||!this.highlightEffect||(this.activeHighlight=o,this.editorView.dispatch({effects:this.highlightEffect.of(o)}))}clearHighlight(){!this.editorView||!this.highlightEffect||(this.activeHighlight=void 0,this.editorView.dispatch({effects:this.highlightEffect.of(null)}))}showDropIndicator(o,e="above"){!this.editorView||!this.dropIndicatorEffect||this.editorView.dispatch({effects:this.dropIndicatorEffect.of({line:o,position:e})})}hideDropIndicator(){!this.editorView||!this.dropIndicatorEffect||this.editorView.dispatch({effects:this.dropIndicatorEffect.of(null)})}showValueSlotHighlight(o,e){!this.editorView||!this.valueSlotHighlightEffect||this.editorView.dispatch({effects:this.valueSlotHighlightEffect.of({from:o,to:e})})}hideValueSlotHighlight(){!this.editorView||!this.valueSlotHighlightEffect||this.editorView.dispatch({effects:this.valueSlotHighlightEffect.of(null)})}getLineAtCoords(o,e){if(!this.editorView)return null;const t=this.editorView.posAtCoords({x:o,y:e});return t===null?null:this.editorView.state.doc.lineAt(t).number}charAtCoords(o,e){return this.editorView?this.editorView.posAtCoords({x:o,y:e})??null:null}getLineCount(){var o;return((o=this.editorView)==null?void 0:o.state.doc.lines)??0}isBelowLastLine(o){if(!this.editorView)return!1;const e=this.editorView.state.doc,t=e.line(e.lines).to,n=this.editorView.coordsAtPos(t);return n?o>n.bottom:!1}isInLowerHalfOfLine(o,e){if(!this.editorView)return!1;const t=this.editorView.state.doc;if(o<1||o>t.lines)return!1;const n=t.line(o),s=this.editorView.coordsAtPos(n.from),r=this.editorView.coordsAtPos(n.to);return!s||!r?!1:e>(s.top+r.bottom)/2}setTheme(o){if(!this.editorView||!this.cm||!this.themeCompartment)return;this.themeSelection=o.selectionBackground??re.selectionBackground,this.activeHighlight&&this.highlightLines(this.activeHighlight);const e=Ae(this.cm.view,o);this.editorView.dispatch({effects:this.themeCompartment.reconfigure(e)})}setHighlightRules(o){if(!this.editorView||!this.cm||!this.syntaxHighlightCompartment)return;const e=Qe(this.cm.view,this.cm.state,o);this.editorView.dispatch({effects:this.syntaxHighlightCompartment.reconfigure(e)})}dispose(){var o;this.disposed=!0,this.detachSyncListener(),this.syncTimer!==void 0&&(clearTimeout(this.syncTimer),this.syncTimer=void 0),this.emptyClickListener&&this.editorView&&(this.editorView.scrollDOM.removeEventListener("click",this.emptyClickListener),this.emptyClickListener=void 0),(o=this.editorView)==null||o.destroy(),this.editorView=void 0,this.metadata=new Map,this.placeholders=[],this.lastCode=""}refresh(){this.syncNow()}getValue(){var o;return((o=this.editorView)==null?void 0:o.state.doc.toString())??this.lastCode??""}getSelectedLines(){return this.editorView?Me(this.editorView.state):null}clearSelection(){const o=this.editorView;if(!o)return;o.dispatch({selection:{anchor:o.state.selection.main.from}});const e=document.getSelection();e!=null&&e.anchorNode&&o.contentDOM.contains(e.anchorNode)&&e.removeAllRanges()}getCursorLine(){if(!this.editorView)return 1;const o=this.editorView.state.selection.main.head;return this.editorView.state.doc.lineAt(o).number}adjustZoom(o){if(!this.editorView||!this.cm||!this.themeCompartment)return;const e=this.options.theme??{},t=parseFloat(e.fontSize??re.fontSize);o==="fit"?this.zoomFactor=1:o==="in"?this.zoomFactor=Math.min(4,this.zoomFactor*1.2):this.zoomFactor=Math.max(.25,this.zoomFactor/1.2);const n={...e,fontSize:`${(t*this.zoomFactor).toFixed(2)}px`},s=Ae(this.cm.view,n);this.editorView.dispatch({effects:this.themeCompartment.reconfigure(s)})}syncNow(){if(!this.editorView||!this.cm)return;const o=this.generateWithMetadata();if(o.code===this.lastCode)return;this.closePlaceholderEditor(),this.lastCode=o.code,this.metadata=o.metadata,this.placeholders=[...o.placeholders].sort((t,n)=>t.start-n.start);const e=[];this.metadataEffect&&e.push(this.metadataEffect.of(o.metadata)),this.placeholderEffect&&e.push(this.placeholderEffect.of(o.placeholders)),this.groupsEffect&&e.push(this.groupsEffect.of(o.groups??[])),this.editorView.dispatch({changes:{from:0,to:this.editorView.state.doc.length,insert:o.code},effects:e.length>0?e:void 0})}scheduleDebouncedSync(){this.syncTimer!==void 0&&clearTimeout(this.syncTimer),this.syncTimer=setTimeout(()=>{this.syncTimer=void 0,this.syncNow()},yo)}attachSyncListener(){this.changeListener||(this.changeListener=o=>{Co(o)&&this.scheduleDebouncedSync()},this.workspace.addChangeListener(this.changeListener))}detachSyncListener(){this.changeListener&&(this.workspace.removeChangeListener(this.changeListener),this.changeListener=void 0,this.syncTimer!==void 0&&(clearTimeout(this.syncTimer),this.syncTimer=void 0))}}const Oe="morphic:";function De(i){return Oe+i}function G(i){return i.startsWith(Oe)?i.slice(Oe.length):i}function X(i,o){return o.has(i)?De(i):i}function So(i,o,e,t){const n={behaviors:e,definitions:o};return st(ee.javascriptGenerator,n,t,!1),ee.javascriptGenerator.workspaceToCode(i)}function xo(i,o,e,t){const n={behaviors:e,definitions:o};st(ee.javascriptGenerator,n,t,!0);const s=ee.javascriptGenerator.workspaceToCode(i);return Fo(s)}const To="// __MORPHIC_BLOCK_START:",Lo="// __MORPHIC_BLOCK_END:",it="__";function st(i,o,e,t=!1){i.STATEMENT_PREFIX=(e==null?void 0:e.statementPrefix)??null,i.STATEMENT_SUFFIX=(e==null?void 0:e.statementSuffix)??null,i.INFINITE_LOOP_TRAP=(e==null?void 0:e.infiniteLoopTrap)??null,e!=null&&e.reservedWords&&i.addReservedWords(e.reservedWords);for(const[n,s]of o.definitions){const r=Nt(o.behaviors[n]);i.forBlock[De(n)]=(c,a)=>{const l=Bo(c,a),d=r?r(l):No(n,s);if(Ao(c,s))return[Do(d),ee.Order.NONE];const h=Oo(d);return t?`${To}${c.id}${it}
4
+ ${h}${Lo}${c.id}${it}
5
+ `:h}}}function Bo(i,o){var c;const e={},t={},n={},s=i.workspace.isFlyout?"toolbox":"workspace",r=rt(i)>=2;for(const a of i.inputList){const l=(c=a.connection)==null?void 0:c.targetBlock();if(l)if(l.outputConnection){const d=o.valueToCode(i,a.name,ee.Order.NONE)||"undefined";e[a.name]=r?Io(d,l):d}else e[a.name]=o.statementToCode(i,a.name).trimEnd();for(const d of a.fieldRow){if(!d.name||pe(d))continue;const h=String(d.getValue()??"");t[d.name]=h,n[d.name]=JSON.stringify(h)}}return{blockId:i.id,blockType:G(i.type),element:Xt(i)??"default",context:s,inputs:e,fields:t,quoted:n}}function Io(i,o){return!Mo(o)||$o(i)?i:`(${i})`}function Mo(i){return rt(i)>0}function rt(i){return i.inputList.filter(o=>{var e;return((e=o.connection)==null?void 0:e.type)===T.INPUT_VALUE}).length}function $o(i){if(!i.startsWith("(")||!i.endsWith(")"))return!1;let o=0;for(let e=0;e<i.length;e++){const t=i[e];if(t==="(")o++;else if(t===")"&&(o--,o===0))return e===i.length-1}return!1}function Ao(i,o){return i.outputConnection?!0:o.output===!1?!1:o.output!==void 0}function Oo(i){const o=i.trim();return o?o.endsWith(";")||o.endsWith("}")||o.endsWith(`
6
+ `)?`${o}
7
+ `:`${o};
8
+ `:""}function Do(i){const o=i.trim();return o?o.endsWith(";")?o.slice(0,-1):o:"undefined"}function No(i,o){return o.output!==void 0&&o.output!==!1?"undefined":`// No generator behavior defined for "${i}"`}const Vo=/^\s*\/\/ __MORPHIC_BLOCK_START:(.+)__$/,Po=/^\s*\/\/ __MORPHIC_BLOCK_END:(.+)__$/;function Fo(i){const o=i.split(`
9
+ `),e=[],t=new Map,n=new Map;let s=0;for(const r of o){const c=r.match(Vo);if(c){n.set(c[1],s+1);continue}const a=r.match(Po);if(a){const l=a[1],d=n.get(l);d!==void 0&&(t.set(l,{startLine:d,endLine:s}),n.delete(l));continue}e.push(r),s++}return{code:e.join(`
10
+ `),metadata:t,placeholders:[]}}function Ho(i,o={}){for(const e of i.elements)if(W(o[e])==="code")return e}function ae(i,o,e={},t=[]){const n=i.elements,s=t.find(c=>c.name===o);if(s){for(const c of s.elements)if(W(e[c])==="code"&&n[c]!==void 0)return{mode:o,template:n[c],elementName:c,inputSlots:i.inputSlots}}for(const[c,a]of Object.entries(n))if(W(e[c])==="code")return{mode:o,template:a,elementName:c,inputSlots:i.inputSlots};if(n.block!==void 0)return{mode:o,template:n.block,elementName:"block",inputSlots:i.inputSlots};const r=Object.entries(n)[0];if(r===void 0)throw new Error(`Block "${i.identifier}" does not have any elements.`);return{mode:o,template:r[1],elementName:r[0],inputSlots:i.inputSlots}}function ct(i,o,e={}){const t=i.elements[o];return t!==void 0&&W(e[o])==="code"?{mode:o,template:t,elementName:o,inputSlots:i.inputSlots}:ae(i,o,e,[])}function j(i,o){if(o.length===0)return;if(i.indent===""||!o.includes(`
11
+ `)){i.output+=o;return}const e=o.split(`
12
+ `);i.output+=e[0];for(let t=1;t<e.length;t++)i.output+=`
13
+ `+i.indent+e[t]}function at(i,o,e,t,n,s,r={}){const c={output:"",metadata:new Map,placeholders:[],indent:""},a={mode:o,definitions:e,elementTypes:t,modeDefs:n,elementOverride:s,emptyStatements:r.emptyStatements!==!1},l=[],d=()=>c.output.split(`
14
+ `).length;let h=!0;for(const u of i.getTopBlocks(!0)){const p=c.output.length;h||(c.output+=`
15
+ `);const m=d();lt(u,a,c),c.output.length===p+(h?0:1)?c.output=c.output.slice(0,p):(h=!1,l.push({startLine:m,endLine:d()}))}return{code:c.output,metadata:c.metadata,placeholders:c.placeholders,groups:l}}function lt(i,o,e){const t=1+e.indent.length;let n=i,s=!0;for(;n;){const r=e.output.length;s||j(e,`
16
+ `),Ne(n,o,e),e.output.length===r+(s?0:t)?e.output=e.output.slice(0,r):s=!1,n=n.getNextBlock()}}function dt(i){return i.inputList.some(o=>{var e;return((e=o.connection)==null?void 0:e.type)===T.INPUT_VALUE})}function Ro(i,o){var t;let e=0;for(const n of i){if(n.kind!=="placeholder")continue;const s=(t=o.inputSlots)==null?void 0:t[String(n.index)];((s==null?void 0:s.kind)??"value")==="value"&&e++}return e}function Ne(i,o,e,t=!1){var B,L,E,x;const n=o.definitions.get(G(i.type));if(!n){const g=e.output.length,C=ne(e.output);if(_o(i,e),e.output.length===g)return;const f=ne(e.output),y=e.output.endsWith(`
17
+ `)?Math.max(C,f-1):f;let S=e.output.length;for(;S>g&&e.output[S-1]===`
18
+ `;)S--;const M=Ce(i);e.metadata.set(i.id,{startLine:C,endLine:y,startChar:g,endChar:S,atomic:!!M}),J(e,g,"set",M??void 0);return}let s,r;if(o.elementOverride){const g=n.elements[o.elementOverride];if(g===void 0)return;s=g,r=o.elementOverride}else try{const g=ae(n,o.mode,o.elementTypes,o.modeDefs);s=g.template,r=g.elementName}catch{return}const c=r?o.elementTypes[r]:void 0,a=e.output.length;t&&j(e,"(");const l=e.output.length,d=ne(e.output),h={},u=oe(s),p=Ro(u,n)>=2;for(const g of u){if(g.kind==="text"){j(e,g.value);continue}if(g.kind==="field"){const I=i.getField(g.name);if(!I)continue;const F=e.output.length;j(e,ut(n,r,g.name,I));const R=Ve(ht(i,I,g.name),i,o);R&&J(e,F,"set",R);continue}if(g.kind==="image")continue;if(g.kind==="valueType"){j(e,Ue(i,(B=n.inputSlots)==null?void 0:B[String(g.index)],c));continue}const C=(L=n.inputSlots)==null?void 0:L[String(g.index)],f=C==null?void 0:C.name;if(!f)continue;const y=i.getInput(f),S=((E=y==null?void 0:y.connection)==null?void 0:E.targetBlock())??null,M=S!=null&&S.isShadow()?null:S;if((C==null?void 0:C.kind)==="statement"){const I=ne(e.output),F=e.indent,R=e.output.lastIndexOf(`
19
+ `)+1;if(e.indent=((x=/^[ \t]*/.exec(e.output.slice(R)))==null?void 0:x[0])??"",M)lt(M,o,e);else{const A=o.emptyStatements&&typeof c=="object"?c.emptyStatement:void 0;if(A){const $=e.output.length;j(e,A),J(e,$,"default")}}e.indent=F;const z=ne(e.output),de=e.output.endsWith(`
20
+ `)?Math.max(I,z-1):z;h[f]={startLine:I,endLine:de};continue}let O=!1;if(!M&&S&&o.definitions.has(G(S.type))){const I=e.output.length,F=e.placeholders.length;Ne(S,o,e,p&&dt(S));for(const R of S.getDescendants(!1))e.metadata.delete(R.id);if(e.output.length>I){const R=e.placeholders.splice(F);for(const z of R)e.placeholders.push({...z,kind:"default"});R.length===0&&J(e,I,"default");continue}}if(!M){const I=S!=null&&S.isShadow()?S.inputList.flatMap($=>$.fieldRow).filter($=>!!$.name):[],F=!(S!=null&&S.isShadow())&&y?y.fieldRow.filter($=>{var D;return!!$.name&&!((D=n.fields)!=null&&D[$.name])&&!pe($)}):[],R=I.length>0||F.length>0,z=R?jo(C,c):void 0;z&&j(e,z);const de=e.output.length;if(I.length>0){const $=S?o.definitions.get(G(S.type)):void 0;for(const D of I)j(e,$&&D.name?ut($,r,D.name,D):Ee(D))}else if(F.length>0)for(const $ of F){const D=e.output.length;j(e,Ee($));const _=ht(i,$,$.name);_&&(J(e,D,"set",_),O=!0)}let A;if(R||(j(e,Wo(C==null?void 0:C.check)),A={parentBlockId:i.id,inputName:f}),!O){const $=S!=null&&S.isShadow()?Ve(Ce(S),S,o)??void 0:void 0;J(e,de,"default",$,A)}z&&j(e,z);continue}const V=e.output.length;Ne(M,o,e,p&&dt(M)),J(e,V,"set",Ve(Ce(M),M,o)??void 0)}if(e.output.length===l){e.output=e.output.slice(0,a);return}t&&j(e,")");const m=ne(e.output),w=e.output.endsWith(`
21
+ `)?Math.max(d,m-1):m;let b=e.output.length;for(;b>a&&e.output[b-1]===`
22
+ `;)b--;const k={startLine:d,endLine:w,startChar:a,endChar:b};Object.keys(h).length>0&&(k.statementSlots=h),Ce(i)&&(k.atomic=!0),e.metadata.set(i.id,k)}function _o(i,o){for(const e of i.inputList)for(const t of e.fieldRow)t.name&&j(o,Ee(t))}function J(i,o,e,t,n){const s=i.output.length;if(s>o){const r={start:o,end:s,kind:e};t&&(r.edit=t),n&&(r.emptySlot=n),i.placeholders.push(r)}}function Wo(i){const o=Array.isArray(i)?i[0]:i;return o?`[${{Number:"NUMBER",String:"TEXT",Boolean:"BOOL"}[o]??o.toUpperCase()}]`:"[VALUE]"}function jo(i,o){if(!(!(i!=null&&i.check)||(Array.isArray(i.check)?i.check[0]:i.check)!=="String")&&!(!o||typeof o=="string"))return o.stringQuote}function ht(i,o,e){let t,n;if(o instanceof T.FieldNumber)t="number";else if(o instanceof T.FieldDropdown){t="dropdown";const s=o.getOptions();Array.isArray(s)&&(n=s.filter(r=>Array.isArray(r)&&r.length>=2).map(([r,c])=>[typeof r=="string"?r:String(c),String(c)]))}else if(o instanceof T.FieldTextInput)t="text";else return null;return{blockId:i.id,fieldName:e,fieldType:t,options:n}}function Ve(i,o,e){var c;if(!(i!=null&&i.options))return i;const t=e.definitions.get(G(o.type)),n=(c=t==null?void 0:t.fields)==null?void 0:c[i.fieldName];if(!t||(n==null?void 0:n.type)!=="dropdown")return i;let s=e.elementOverride;if(!s)try{s=ae(t,e.mode,e.elementTypes,e.modeDefs).elementName}catch{return i}const r=a=>{var l;for(const d of n.options)if(typeof d=="object"&&!Array.isArray(d)&&d.value===a)return(s&&((l=d.display)==null?void 0:l[s]))??a;return a};return{...i,options:i.options.map(([,a])=>[r(a),a])}}function Ce(i){let o=null,e=null,t=0;for(const c of i.inputList){if(c.connection&&c.connection.type===T.INPUT_VALUE)return null;for(const a of c.fieldRow)a.name&&(t++,o=a.name,e=a)}if(t!==1||!o||!e)return null;const n=e.constructor.name;let s="text",r;if(n.includes("Number"))s="number";else if(n.includes("Dropdown")){s="dropdown";const c=e.getOptions;if(typeof c=="function"){const a=c.call(e);Array.isArray(a)&&(r=a.filter(l=>Array.isArray(l)&&l.length>=2).map(([l,d])=>[typeof l=="string"?l:String(d),String(d)]))}}return{blockId:i.id,fieldName:o,fieldType:s,options:r}}function ut(i,o,e,t){var s,r;const n=(s=i.fields)==null?void 0:s[e];if((n==null?void 0:n.type)==="dropdown"&&o){const c=String(t.getValue());for(const a of n.options)if(!(typeof a!="object"||Array.isArray(a))&&a.value===c)return((r=a.display)==null?void 0:r[o])??c}return Ee(t)}function Ee(i){if(!i)return"";if(i instanceof T.FieldDropdown)return String(i.getValue());const o=i.getText;return typeof o=="function"?o.call(i):String(i.getValue())}function ne(i){let o=1;for(let e=0;e<i.length;e++)i[e]===`
23
+ `&&o++;return o}class zo{constructor(o,e,t={}){v(this,"workspace");v(this,"editors");v(this,"blockToCode");v(this,"codeToBlock");v(this,"blockListener");v(this,"cursorCallbacks",new Map);v(this,"emptyClickCallbacks",new Map);v(this,"guard",!1);this.workspace=o,this.editors=Array.isArray(e)?[...e]:[e],this.blockToCode=t.blockToCode!==!1,this.codeToBlock=t.codeToBlock!==!1}enable(){this.blockToCode&&this.attachBlockListener(),this.codeToBlock&&this.attachCursorListeners()}disable(){this.detachBlockListener(),this.detachCursorListeners();for(const o of this.editors)o.clearHighlight()}attachBlockListener(){this.blockListener||(this.blockListener=o=>{if(o.type!=="selected"||this.guard)return;const e=o.newElementId??void 0;this.guard=!0,this.broadcastHighlight(e),this.guard=!1},this.workspace.addChangeListener(this.blockListener))}detachBlockListener(){this.blockListener&&(this.workspace.removeChangeListener(this.blockListener),this.blockListener=void 0)}broadcastHighlight(o){for(const e of this.editors){if(!o){e.clearHighlight();continue}const t=this.computeOwnSpans(o,e.metadata);t?e.highlightLines(t):e.clearHighlight()}}attachCursorListeners(){for(const o of this.editors){if(!this.cursorCallbacks.has(o)){const e=t=>{if(this.guard)return;const n=this.findBlockAtLine(t,o.metadata);if(!n){this.clearAll();return}const s=this.workspace.getBlockById(n);s&&T.common.getSelected()!==s&&(this.guard=!0,T.common.setSelected(s),this.broadcastHighlight(n),this.guard=!1)};this.cursorCallbacks.set(o,e),o.onCursorLine=e}if(!this.emptyClickCallbacks.has(o)){const e=()=>{this.guard||this.clearAll()};this.emptyClickCallbacks.set(o,e),o.onEmptyClick=e}}}detachCursorListeners(){for(const[o,e]of this.cursorCallbacks)o.onCursorLine===e&&(o.onCursorLine=void 0);this.cursorCallbacks.clear();for(const[o,e]of this.emptyClickCallbacks)o.onEmptyClick===e&&(o.onEmptyClick=void 0);this.emptyClickCallbacks.clear()}clearAll(){this.guard=!0,T.common.setSelected(null);for(const o of this.editors)o.clearHighlight();this.guard=!1}computeOwnSpans(o,e){const t=e.get(o);if(!t)return;const n=[];for(const[c,a]of e)c!==o&&a.startLine>=t.startLine&&a.endLine<=t.endLine&&n.push(a);if(n.length===0)return[{fromLine:t.startLine,toLine:t.endLine}];n.sort((c,a)=>c.startLine-a.startLine);const s=[];let r=t.startLine;for(const c of n)r<c.startLine&&s.push({fromLine:r,toLine:c.startLine-1}),r=Math.max(r,c.endLine+1);return r<=t.endLine&&s.push({fromLine:r,toLine:t.endLine}),s.length>0?s:void 0}findBlockAtLine(o,e){let t;for(const[n,s]of e)if(o>=s.startLine&&o<=s.endLine){const r=s.endLine-s.startLine;(!t||r<t.size)&&(t={id:n,size:r})}return t==null?void 0:t.id}}const ft={statement:{above:!0,below:!0},start:{above:!1,below:!0},end:{above:!0,below:!1},standalone:{above:!1,below:!1}},pt=Object.keys(ft);function Uo(i){return i.map(o=>{const e=o.shape?ft[o.shape]:void 0;if(!e)return o;const t={...o};return e.above&&t.previousStatement===void 0&&(t.previousStatement=!0),e.below&&t.nextStatement===void 0&&(t.nextStatement=!0),t})}const Se="default";function Go(i,o){const e=Object.keys(o).filter(t=>W(o[t])==="code");return i.map(t=>{var a;const n=(a=t.elements)==null?void 0:a[Se];if(n===void 0||e.length===0)return t;const{[Se]:s,...r}=t.elements,c={...r};for(const l of e)c[l]===void 0&&(c[l]=n);return{...t,elements:c}})}function Xo(i){const o=new Map,e=Array.isArray(i)?i:[i];for(const t of e)Yo(t,o),o.set(t.identifier,t);return o}function Yo(i,o){if(!i.identifier.trim())throw new Error("Each block definition must include a non-empty identifier.");if(Object.keys(i.elements).length===0)throw new Error(`Block "${i.identifier}" must define at least one element.`);if(o.has(i.identifier))throw new Error(`Duplicate block identifier "${i.identifier}".`)}const Ko=4/3,qo={normal:"400",bold:"700"},mt=i=>qo[i]??i;function Jo(i){const o=parseFloat(i);if(!Number.isFinite(o)||o<=0)return;const e=i.trim().endsWith("pt")?o:o/Ko;return Math.round(e*100)/100}function gt(i){const o=i.getRenderer().getConstants();return{family:o.FIELD_TEXT_FONTFAMILY,size:o.FIELD_TEXT_FONTSIZE,weight:mt(o.FIELD_TEXT_FONTWEIGHT)}}function wt(i,o,e){const t=document.createElement("div");t.setAttribute("aria-hidden","true"),t.style.cssText="position:absolute;visibility:hidden;width:0;height:0;overflow:hidden;";let n=t;for(const l of o){const d=document.createElement("div");d.className=l.join(" "),n.appendChild(d),n=d}const s=document.createElementNS("http://www.w3.org/2000/svg","svg"),r=document.createElementNS("http://www.w3.org/2000/svg","text");r.setAttribute("class","blocklyText"),s.appendChild(r),n.appendChild(s),i.appendChild(t);const c=getComputedStyle(r),a={family:c.fontFamily||e.family,size:Jo(c.fontSize)??e.size,weight:c.fontWeight?mt(c.fontWeight):e.weight};return t.remove(),a}const Zo=(i,o)=>i.family===o.family&&i.size===o.size&&i.weight===o.weight,Pe=new Map;function Qo(i,o){const e=`${i.name}
24
+ ${o.family}
25
+ ${o.size}
26
+ ${o.weight}`;let t=Pe.get(e);if(!t){const n=`${i.name}-morphic-font-${Pe.size+1}`;t=T.Theme.defineTheme(n,{name:n,base:i,fontStyle:{family:o.family,size:o.size,weight:o.weight},...i.startHats!==void 0&&{startHats:i.startHats}}),Pe.set(e,t)}return t}function kt(i,o,e,t){const n=Zo(t,e)?o:Qo(o,t);return i.getTheme()===n?!1:(i.setTheme(n),!0)}function Fe(i){for(const o of i.getAllBlocks(!1)){o.markDirty();for(const e of o.inputList)for(const t of e.fieldRow)t.getConstants()}i.render()}function vt(i){var B,L,E,x,g,C;const{definitions:o,elementTypes:e,behaviors:t,modes:n,presets:s,code:r,categories:c,views:a}=i,l=[],d=[],h=new Set(Object.keys(e)),u=new Set(Object.keys(e).filter(f=>W(e[f])==="code")),p=new Set((c??[]).map(f=>f.name));h.has(Se)&&l.push(`elementTypes declares "${Se}", which is reserved for a block's fallback template. Rename the element.`);const m=f=>o.has(f)||T.Blocks[f]!==void 0;for(const f of o.values()){const y=f.identifier;if(f.shape!==void 0)if(!pt.includes(f.shape))l.push(`Block "${y}": unknown shape "${f.shape}". Use one of: ${pt.join(", ")}.`);else{const A=D=>D!==void 0&&D!==!1,$=[];A(f.output)&&$.push("it also has an output, which makes it a value block"),(f.shape==="start"||f.shape==="standalone")&&A(f.previousStatement)&&$.push("it also connects above (previousStatement)"),(f.shape==="end"||f.shape==="standalone")&&A(f.nextStatement)&&$.push("it also connects below (nextStatement)"),f.shape==="statement"&&(f.previousStatement===!1||f.nextStatement===!1)&&$.push("a connection flag is set to false");for(const D of $)d.push(`Block "${y}": shape "${f.shape}" contradicts its flags: ${D}. The flags win.`)}const S=he(t[y]),M=!!(S!=null&&S.onViewApplied);for(const A of Object.keys(f.elements))h.has(A)||d.push(`Block "${y}": element "${A}" is not declared in elementTypes — it renders with no known type.`);const O=new Map,V=new Set,I=new Set,F=new Map;for(const[A,$]of Object.entries(f.elements)){if(!u.has(A))continue;const D=new Set,_=new Set;for(const Y of oe($))Y.kind==="placeholder"?(D.add(Y.index),V.add(Y.index)):Y.kind==="field"?I.add(Y.name):Y.kind==="valueType"&&_.add(Y.index);O.set(A,D),F.set(A,_)}for(const[A,$]of F)for(const D of $){const _=(B=f.inputSlots)==null?void 0:B[String(D)];(!((L=O.get(A))!=null&&L.has(D))||(_==null?void 0:_.kind)==="statement")&&l.push(`Block "${y}": element "${A}" uses %${D}:type, but %${D} is not a value slot in it — the type comes from the value in that slot.`)}const R=[...O.entries()];if(R.length>1){const[A,$]=R[0];for(const[D,_]of R.slice(1))tn($,_)||l.push(`Block "${y}": code elements "${A}" and "${D}" use different placeholders (${Ct($)} vs ${Ct(_)}). All code elements must share the same %N set, or an input disappears when switching to the differing mode.`)}const z=new Set(Object.keys(f.inputSlots??{}).map(A=>Number(A)).filter(A=>Number.isInteger(A)));for(const A of V)(E=f.inputSlots)!=null&&E[String(A)]||d.push(`Block "${y}": placeholder %${A} has no inputSlots["${A}"] entry — the input is auto-named ARG${A} and can't be read by name in behaviors.`);for(const A of z)V.has(A)||d.push(`Block "${y}": inputSlots["${A}"] has no matching %${A} placeholder in any code element — the config is ignored.`);const de=new Set(Object.keys(f.fields??{}));for(const A of I)!((x=f.fields)!=null&&x[A])&&!M&&l.push(`Block "${y}": field token %${A} has no fields["${A}"] entry and the block has no onViewApplied behavior to create it — the field will never appear.`);for(const A of de)I.has(A)||d.push(`Block "${y}": fields["${A}"] has no matching %${A} token in any code element — the config is ignored.`);for(const[A,$]of Object.entries(f.fields??{}))if(($==null?void 0:$.type)==="dropdown")for(const D of $.options){if(typeof D!="object"||Array.isArray(D))continue;const _=D.label;if(_&&typeof _=="object"&&typeof _.src!="string"&&typeof _.color!="string"&&l.push(`Block "${y}": fields["${A}"] option "${D.value}" has an image label without "src" or "color".`),!!D.display)for(const Y of Object.keys(D.display))u.has(Y)||d.push(`Block "${y}": fields["${A}"] option "${D.value}" has display for "${Y}", which is not a code element — that entry never applies.`)}f.category!==void 0&&p.size>0&&!p.has(f.category)&&d.push(`Block "${y}": category "${f.category}" is not declared in categories — the block loses its colour and grouping.`);for(const[A,$]of Object.entries(f.inputSlots??{}))($==null?void 0:$.kind)!==void 0&&!yt.includes($.kind)&&l.push(`Block "${y}": inputSlots["${A}"] has unknown kind "${$.kind}". Use one of: ${yt.join(", ")}.`);for(const[A,$]of Object.entries(f.fields??{}))bt.includes($==null?void 0:$.type)||l.push(`Block "${y}": fields["${A}"] has unknown type "${$==null?void 0:$.type}". Use one of: ${bt.join(", ")}.`);for(const[A,$]of Object.entries(f.inputSlots??{}))k((g=$==null?void 0:$.default)==null?void 0:g.shadow,`Block "${y}": inputSlots["${A}"].default.shadow`),k((C=$==null?void 0:$.default)==null?void 0:C.placeholder,`Block "${y}": inputSlots["${A}"].default.placeholder`)}for(const[f,y]of Object.entries(e)){const S=W(y);He.includes(S)||l.push(`elementTypes."${f}": unknown type "${S}". Use one of: ${He.join(", ")}.`)}for(const[f,y]of Object.entries(r??{}))for(const[S,M]of Object.entries(y.empty??{}))k(M.shadow,`code.${f}.empty.${S}.shadow`),k(M.placeholder,`code.${f}.empty.${S}.placeholder`);for(const[f,y]of Object.entries(e)){if(typeof y=="string")continue;const S=y.type;y.size!==void 0&&S!=="image"&&d.push(`elementTypes."${f}": "size" applies only to image elements — ignored for a ${S} element.`);for(const M of["empty","stringQuote"])M in y&&l.push(`elementTypes."${f}": "${M}" moved into the "code" section: "code": { "${f}": { "${M}": … } }.`)}for(const f of n??[])for(const y of f.elements)h.has(y)||d.push(`Mode "${f.name}": element "${y}" is not declared in elementTypes — it renders nothing.`);for(const f of n??[])for(const[y,S]of Object.entries(f.render??{}))S==="block"||S==="text"?l.push(`Mode "${f.name}": render "${S}" is now "${S}-based" (render.${y}).`):S!=="block-based"&&S!=="text-based"?l.push(`Mode "${f.name}": render.${y} must be "block-based" or "text-based".`):u.has(y)||d.push(`Mode "${f.name}": render.${y} names no code element — it changes nothing.`);for(const f of s??[]){const y=f.toolbox;if(typeof y=="object"&&y!==null){const{mode:S,render:M}=y,O=Object.keys(M??{})[0]??"python";l.push(`Preset "${f.name}": the toolbox entry is a mode name since 0.4.0, and its "render" moved into the mode: "toolbox": "${S??"<mode>"}", and on that mode "render": { "${O}": "text-based" }.`)}}for(const f of Object.keys(r??{}))u.has(f)||d.push(`code["${f}"] is not a code element — its settings will never apply.`);const w=new Map,b=(f,y)=>{const S=w.get(f)??new Set;S.add(y),w.set(f,S)};for(const f of h)b(f,"element");for(const f of n??[])b(f.name,"mode");for(const f of s??[])b(f.name,"preset");for(const f of a??[])b(f,"view");for(const f of c??[])b(f.name,"category");for(const[f,y]of w){y.size>1&&d.push(`Name "${f}" is used as ${[...y].sort().join(" and ")} — reusing a name across element / mode / preset / view / category is allowed but confusing; consider distinct names.`);const S=[...y].filter(O=>O!=="category");S.length>0&&/[^A-Za-z0-9_-]/.test(f)&&d.push(`Name "${f}" (${S.sort().join(", ")}) has characters a CSS class cannot hold; its classes use "${H(f)}".`);const M=f.toLowerCase();en.includes(M)&&d.push(`Name "${f}" (${[...y].sort().join(", ")}) is a Morphic Blocks word — name it after what it is in your app (e.g. "python", "icon-tiles", "editor-pane").`)}return{errors:l,warnings:d};function k(f,y){!f||m(f)||l.push(`${y}: "${f}" is neither a defined block nor a registered Blockly block type.`)}}const He=["text","code","image","custom"],en=["workspace","codespace","preview","toolbox","mode","preset","view","element","block","blocks","tile","tiles","category",...He],yt=["value","statement"],bt=["dropdown","text","number","checkbox"];function tn(i,o){if(i.size!==o.size)return!1;for(const e of i)if(!o.has(e))return!1;return!0}function Ct(i){const o=[...i].sort((e,t)=>e-t);return o.length?o.map(e=>`%${e}`).join(" "):"(none)"}function Et(i,o,e=!1){var t;if(!o)return String(i);if(typeof i=="string"){const n=e?(t=o.list)==null?void 0:t.quote:void 0;return n?`${n}${i}${n}`:i}if(typeof i=="boolean")return(i?o.true:o.false)??String(i);if(i===null)return o.null??"null";if(i===void 0)return o.undefined??"undefined";if(typeof i=="number")return Number.isNaN(i)?o.NaN??"NaN":i===1/0?o.Infinity??"Infinity":i===-1/0?o["-Infinity"]??"-Infinity":String(i);if(Array.isArray(i)&&o.list){const{open:n="[",close:s="]",separator:r=", "}=o.list;return`${n}${i.map(c=>Et(c,o,!0)).join(r)}${s}`}return String(i)}class on{ensureModeVisibilityStyles(o,e){const t=St(o);if(e){const n=St(e);for(const s of Array.from(document.head.querySelectorAll("style[data-morphic-source]")))if(s.dataset.morphicSource==="mode-visibility"&&s.textContent===n){s.textContent=t;return}}q("mode-visibility",t)}ensureStyles(o,e){this.ensureStyleBundle(o,"base");for(const t of e)this.ensureStyleBundle(t,`mode:${t.mode}`)}async ensureToolbarStyles(){const o=await Promise.resolve().then(()=>Vn);q("toolbar",o.default)}ensureWorkspaceStyles(){q("workspace",[".morphic-workspace-root .blocklyMainBackground {"," stroke: var(--morphic-workspace-border-color, transparent);"," stroke-width: var(--morphic-workspace-border-width, 1px);","}"].join(`
27
+ `))}ensureCategoryStyles(o){for(const e of o){if(!e.color)continue;const t=H(e.name);q(`category:${t}`,`.morphic-category-${t} { --morphic-category-color: ${e.color}; }`)}}validateModeCoverage(o,e,t=console.warn){const n=new Set(o.map(r=>r.mode)),s=e.filter(r=>!n.has(r));s.length>0&&t(`[MorphicBlocks] Modes without explicit CSS definition: ${s.join(", ")}.`)}ensureStyleBundle(o,e){o&&(o.href&&cn(e,o.href),o.cssText&&q(e,o.cssText))}}function nn(i,o={}){const e=`.morphic-block .morphic-element-${H(i)}`;q(`tile-highlight:${i}`,[`${e} .morphic-tok-keyword { color: ${o.keyword??"#cc7832"}; }`,`${e} .morphic-tok-string { color: ${o.string??"#6a8759"}; }`,`${e} .morphic-tok-number { color: ${o.number??"#6897bb"}; }`,`${e} .morphic-tok-comment { color: ${o.comment??"#808080"}; font-style: italic; }`].join(`
28
+ `))}function sn(){q("tile-touch",".morphic-block[data-block-type] { touch-action: pan-y; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; }")}function rn(){const i=":where(.morphic-toolbox-hide-scrollbar",o=e=>`mask-image: ${e}; -webkit-mask-image: ${e};`;q("toolbox-scroll",[`${i}) { scrollbar-width: none; }`,`${i})::-webkit-scrollbar { display: none; }`,`${i}.morphic-toolbox-more-below) { ${o("linear-gradient(to bottom, #000 calc(100% - 2rem), transparent)")} }`,`${i}.morphic-toolbox-more-above) { ${o("linear-gradient(to top, #000 calc(100% - 2rem), transparent)")} }`,`${i}.morphic-toolbox-more-above.morphic-toolbox-more-below) { ${o("linear-gradient(transparent, #000 2rem, #000 calc(100% - 2rem), transparent)")} }`].join(`
29
+ `))}function St(i){const o=['[class^="morphic-element-"] { display: none; }'];for(const e of i){const t=H(e.name);for(const n of e.elements){const s=H(n);o.push(`.morphic-mode-${t} > .morphic-element-${s} { display: block; }`)}}return o.join(`
30
+ `)}function q(i,o){for(const t of Array.from(document.head.querySelectorAll("style[data-morphic-source]")))if(t.dataset.morphicSource===i&&t.textContent===o)return;const e=document.createElement("style");e.dataset.morphicSource=i,e.textContent=o,document.head.appendChild(e)}function cn(i,o){for(const t of Array.from(document.head.querySelectorAll("link[data-morphic-source]")))if(t.getAttribute("href")===o)return;const e=document.createElement("link");e.rel="stylesheet",e.href=o,e.dataset.morphicSource=i,document.head.appendChild(e)}const Z="morphic/block-type";let an=0;const ln=8,dn=350;function hn(i,o){const e=et(o),t=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return i.split(`
31
+ `).map(n=>{let s="",r=0;for(const c of e(n))s+=t(n.slice(r,c.from)),s+=`<span class="morphic-tok-${c.kind}">${t(n.slice(c.from,c.to))}</span>`,r=c.to;return s+t(n.slice(r))}).join(`
32
+ `)}class xt{constructor(o){v(this,"container");v(this,"workspaceContainer");v(this,"workspace");v(this,"definitions");v(this,"blockColors");v(this,"behaviors");v(this,"elementTypes");v(this,"options");v(this,"modes");v(this,"currentMode");v(this,"code");v(this,"previewWorkspace");v(this,"onPreviewWorkspace");v(this,"previewContainer");v(this,"previewBase");v(this,"onDragOver");v(this,"onDrop");v(this,"dropTargets");v(this,"collapsedCategories",new Set);v(this,"categoryParts",[]);v(this,"activeCategory");v(this,"onScroll",()=>this.showScrollHints());v(this,"resizeObserver",typeof ResizeObserver<"u"?new ResizeObserver(()=>this.showScrollHints()):void 0);v(this,"onChoose");v(this,"widestBlock",0);var n;this.container=o.container,this.workspaceContainer=o.workspaceContainer,this.workspace=o.workspace,this.onPreviewWorkspace=o.onPreviewWorkspace,this.definitions=o.definitions,this.blockColors=o.blockColors,this.behaviors=o.behaviors,this.elementTypes=o.elementTypes??{},this.code=o.code??{},this.currentMode=o.mode,this.modes=o.modes??[],this.options=o.options??{},this.dropTargets=o.dropTargets??(()=>[]);const e=this.options.collapsed,t=e===!0?(this.options.categories??[]).map(s=>s.name):e||[];for(const s of t)this.collapsedCategories.add(s);this.onChoose=o.onChoose,this.onDragOver=s=>{var r;(r=s.dataTransfer)!=null&&r.types.includes(Z)&&s.preventDefault()},this.onDrop=s=>{var c;const r=(c=s.dataTransfer)==null?void 0:c.getData(Z);r&&(s.preventDefault(),this.createBlockAtPosition(r,s.clientX,s.clientY))},this.workspaceContainer.addEventListener("dragover",this.onDragOver),this.workspaceContainer.addEventListener("drop",this.onDrop),this.container.classList.add("morphic-toolbox"),this.options.scrollbar!==!0&&(rn(),this.container.classList.add("morphic-toolbox-hide-scrollbar")),this.container.addEventListener("scroll",this.onScroll,{passive:!0}),(n=this.resizeObserver)==null||n.observe(this.container),this.render()}rerender(o){this.currentMode=o,this.render()}dispose(){var o,e;this.workspaceContainer.removeEventListener("dragover",this.onDragOver),this.workspaceContainer.removeEventListener("drop",this.onDrop),this.container.removeEventListener("scroll",this.onScroll),(o=this.resizeObserver)==null||o.disconnect(),this.container.classList.remove("morphic-toolbox","morphic-toolbox-hide-scrollbar","morphic-toolbox-more-above","morphic-toolbox-more-below","morphic-toolbox-stacked","morphic-toolbox-tabs"),this.container.innerHTML="",this.previewWorkspace&&(this.previewWorkspace.dispose(),this.previewWorkspace=void 0,this.previewBase=void 0),(e=this.previewContainer)!=null&&e.parentNode&&(this.previewContainer.parentNode.removeChild(this.previewContainer),this.previewContainer=void 0)}render(){this.widestBlock=0,this.renderTiles();for(const o of Array.from(this.container.querySelectorAll("[data-morphic-text-code]")))this.widestBlock=Math.max(this.widestBlock,o.scrollWidth);this.container.style.setProperty("--morphic-toolbox-block-width",`${Math.ceil(this.widestBlock)}px`),this.showCategories()}renderTiles(){this.container.innerHTML="";const o=this.options.modeLabel??!0,e=typeof o=="function"?o(this.currentMode):typeof o=="string"?o:o?`Mode: ${this.currentMode}`:"";if(e){const a=document.createElement("div");a.className="morphic-toolbox-header";const l=document.createElement("span");l.className="morphic-toolbar-label",l.textContent=e,a.appendChild(l),this.container.appendChild(a)}const t=this.resolveBlockIds(),n=this.options.categories??[];this.categoryParts=[];const s=this.options.layout==="tabs";this.container.classList.toggle("morphic-toolbox-tabs",s),this.container.classList.toggle("morphic-toolbox-stacked",!s);const r=s&&n.length>0?document.createElement("div"):void 0;if(r&&(r.className="morphic-category-tabs",r.setAttribute("role","tablist"),this.container.appendChild(r)),n.length===0){for(const a of t){const l=this.definitions.get(a);l&&this.container.appendChild(this.createTile(l))}return}const c=new Set;for(const a of n){const l=this.resolveCategoryBlockIds(a,t);if(l.length===0)continue;const d=document.createElement("div");d.setAttribute("data-category",H(a.name)),a.color&&d.style.setProperty("--morphic-category-color",a.color);const h=document.createElement("div");h.className="morphic-category-tiles",h.id=`morphic-category-${++an}`;let u,p;if(r)p=document.createElement("button"),p.className="morphic-category-tab",p.type="button",p.setAttribute("role","tab"),p.setAttribute("aria-controls",h.id),p.textContent=a.name,a.color&&p.style.setProperty("--morphic-category-color",a.color),p.addEventListener("click",()=>{this.activeCategory=a.name,this.showCategories()}),r.appendChild(p),h.setAttribute("role","tabpanel");else if(this.options.categoryHeadings!==!1){const m=this.options.collapsible!==!1;u=document.createElement(m?"button":"div"),u.className="morphic-category-heading",u.textContent=a.name,m?(u.type="button",u.setAttribute("aria-controls",h.id),u.addEventListener("click",()=>this.toggleCategory(a.name))):(u.setAttribute("role","heading"),u.setAttribute("aria-level","3")),d.appendChild(u)}this.categoryParts.push({name:a.name,group:d,heading:u,tiles:h,tab:p});for(const m of l){const w=this.definitions.get(m);w&&(h.appendChild(this.createTile(w)),c.add(m))}d.appendChild(h),this.container.appendChild(d)}for(const a of t)if(!c.has(a)){const l=this.definitions.get(a);l&&this.container.appendChild(this.createTile(l))}}toggleCategory(o){var t,n;const e=!this.collapsedCategories.delete(o);e&&this.collapsedCategories.add(o),this.showCategories(),(n=(t=this.options).onCategoryToggle)==null||n.call(t,o,e)}showScrollHints(){const{scrollTop:o,clientHeight:e,scrollHeight:t}=this.container;this.container.classList.toggle("morphic-toolbox-more-above",o>1),this.container.classList.toggle("morphic-toolbox-more-below",o+e<t-1)}showCategories(){this.showCategoryState(),this.showScrollHints()}showCategoryState(){var e;if(this.options.layout==="tabs"){const t=this.categoryParts.find(n=>n.name===this.activeCategory)??this.categoryParts[0];for(const n of this.categoryParts)n.group.hidden=n!==t,(e=n.tab)==null||e.setAttribute("aria-selected",String(n===t));return}const o=this.options.collapsible!==!1;for(const{name:t,group:n,heading:s,tiles:r}of this.categoryParts){const c=o&&this.collapsedCategories.has(t);r.hidden=c,n.toggleAttribute("data-collapsed",c),(s==null?void 0:s.tagName)==="BUTTON"&&s.setAttribute("aria-expanded",String(!c))}}createTile(o){var h,u,p;const e=H(this.currentMode),t=H(o.identifier),n=this.blockColors.get(o.identifier),s=document.createElement("div");s.setAttribute("draggable","true"),s.setAttribute("data-block-type",o.identifier),s.className=`morphic-block morphic-mode-${e} morphic-block-${t}`,n&&s.style.setProperty("--morphic-block-color",n);const r=this.modes.find(m=>m.name===this.currentMode),c=(r==null?void 0:r.elements)??[],a=Object.entries(o.elements),l=[...c.map(m=>a.find(([w])=>w===m)).filter(m=>m!==void 0),...a.filter(([m])=>!c.includes(m))];for(const[m,w]of l){const b=document.createElement("div");b.className=`morphic-element-${H(m)}`;const k=this.elementTypes[m],B=W(k),L=B==="code",E=B==="image",x=(h=this.modes.find(f=>f.name===this.currentMode))==null?void 0:h.render,g=L&&(x==null?void 0:x[m])!=="text-based",C=E?Xe(w,ze(k)):w;if(B==="custom"){b.dataset.morphicCustom="";const f=(u=this.options.custom)==null?void 0:u[m],y=(f==null?void 0:f(w,{block:o.identifier,element:m,mode:this.currentMode}))??w;typeof y=="string"?b.textContent=y:b.appendChild(y)}else if(g){this.syncPreviewFont(m);const f=this.createBlockPreviewSvg(o,this.currentMode,m);f?b.appendChild(f):b.innerHTML=Le(oe(C))}else if(L){b.dataset.morphicTextCode="";const f=this.createCodeText(o,this.currentMode,m),y=this.options.highlight===!1||(p=this.code[m])==null?void 0:p.highlighting;f!==null&&y?(nn(m,y.colors),b.innerHTML=hn(f,y)):f!==null?b.textContent=f:b.innerHTML=Le(oe(C))}else b.innerHTML=Le(oe(C));s.appendChild(b)}let d=!1;return s.addEventListener("pointerdown",m=>{d=Tt(m.target)},!0),s.addEventListener("dragstart",m=>{var w;if(d){m.preventDefault();return}(w=m.dataTransfer)==null||w.setData(Z,o.identifier)}),this.options.touch!==!1&&(sn(),this.attachTouchDrag(s,o.identifier)),this.options.keyboard!==!1&&(s.tabIndex=0,s.setAttribute("role","button"),s.setAttribute("aria-label",this.tileName(o,c)),s.addEventListener("keydown",m=>{var w;m.key!=="Enter"&&m.key!==" "||m.target===s&&(m.preventDefault(),(w=this.onChoose)==null||w.call(this,o.identifier))})),s}tileName(o,e){var c,a;const{label:t}=this.options,n=typeof t=="function"?t(this.currentMode):t,s=n===void 0?void 0:o.elements[n];if(s!==void 0){const l=document.createElement("div");l.innerHTML=s;const d=(c=l.textContent)==null?void 0:c.trim();if(d)return d}const r=[];for(const l of e){const d=o.elements[l];if(d===void 0)continue;const h=W(this.elementTypes[l]);if(h==="custom")continue;if(h==="code"){const m=this.createCodeText(o,this.currentMode,l);m!=null&&m.trim()&&r.push(m.trim());continue}const u=document.createElement("div");u.innerHTML=h==="image"?Xe(d,ze(this.elementTypes[l])):d;const p=h==="image"?Array.from(u.querySelectorAll("img"),m=>m.alt).join(" ").trim():(a=u.textContent)==null?void 0:a.trim();p&&r.push(p)}return r.join(", ")||o.identifier}dropTargetAt(o,e){const t=document.elementFromPoint(o,e);if(!t)return;const n={element:this.workspaceContainer,drop:(s,r,c)=>this.createBlockAtPosition(s,r,c)};return[...this.dropTargets(),n].find(s=>s.element.contains(t))}attachTouchDrag(o,e){o.addEventListener("pointerdown",t=>{var B;if(t.pointerType==="mouse"||!t.isPrimary||Tt(t.target))return;const n=o.getBoundingClientRect();let s,r,c={x:t.clientX,y:t.clientY};o.draggable=!1;let a={x:0,y:0},l=1,d=0;const h=()=>{if(s)return;s=o.cloneNode(!0),s.classList.add("morphic-drag-ghost"),s.removeAttribute("tabindex"),Object.assign(s.style,{position:"fixed",left:"0",top:"0",margin:"0",pointerEvents:"none",zIndex:"2147483647",transition:"none",animation:"none"}),this.container.appendChild(s);const L=s.getBoundingClientRect();s.style.left="100px",l=(s.getBoundingClientRect().left-L.left)/100||1,a={x:L.left,y:L.top},Object.assign(s.style,{left:`${(n.left-a.x)/l}px`,top:`${(n.top-a.y)/l}px`,width:`${n.width/l}px`}),p()},u=window.setTimeout(h,dn),p=()=>{!s||d||(d=requestAnimationFrame(()=>{var E,x;if(d=0,!s)return;s.style.transform=`translate(${(c.x-t.clientX)/l}px, ${(c.y-t.clientY)/l}px)`;const L=this.dropTargetAt(c.x,c.y);L!==r&&((E=r==null?void 0:r.leave)==null||E.call(r)),r=L,(x=r==null?void 0:r.over)==null||x.call(r,c.x,c.y)}))},m=L=>{if(L.pointerId!==t.pointerId)return;c={x:L.clientX,y:L.clientY};const E=Math.abs(L.clientX-t.clientX),x=Math.abs(L.clientY-t.clientY);!s&&(E<ln||x>E)||(window.clearTimeout(u),h(),p())},w=L=>{s&&L.preventDefault()},b=L=>L.preventDefault(),k=L=>{var E,x;L.pointerId===t.pointerId&&(window.clearTimeout(u),o.removeEventListener("pointermove",m),o.removeEventListener("pointerup",k),o.removeEventListener("pointercancel",k),o.removeEventListener("touchmove",w),o.removeEventListener("contextmenu",b),o.draggable=!0,cancelAnimationFrame(d),(E=r==null?void 0:r.leave)==null||E.call(r),s&&(s.remove(),L.type==="pointerup"&&((x=this.dropTargetAt(L.clientX,L.clientY))==null||x.drop(e,L.clientX,L.clientY))))};(B=o.setPointerCapture)==null||B.call(o,t.pointerId),o.addEventListener("pointermove",m),o.addEventListener("pointerup",k),o.addEventListener("pointercancel",k),o.addEventListener("touchmove",w,{passive:!1}),o.addEventListener("contextmenu",b)})}ensurePreviewWorkspace(){var e;if(this.previewWorkspace)return this.previewWorkspace;this.previewContainer=document.createElement("div"),this.previewContainer.style.cssText="position:absolute;left:-9999px;top:-9999px;width:800px;height:600px;overflow:hidden;",document.body.appendChild(this.previewContainer);const o=this.workspace.options;return this.previewWorkspace=T.inject(this.previewContainer,{scrollbars:!1,media:o.pathToMedia,sounds:!1,renderer:o.renderer,rendererOverrides:o.rendererOverrides??void 0,theme:o.theme,rtl:o.RTL}),(e=this.onPreviewWorkspace)==null||e.call(this,this.previewWorkspace),this.previewWorkspace}syncPreviewFont(o){const e=this.ensurePreviewWorkspace();this.previewBase??(this.previewBase={theme:e.getTheme(),font:gt(e)});const t=wt(this.container,[["morphic-block",`morphic-mode-${H(this.currentMode)}`],[`morphic-element-${H(o)}`],[e.getRenderer().getClassName(),e.getTheme().getClassName()]],this.previewBase.font);kt(e,this.previewBase.theme,this.previewBase.font,t)}createPreviewBlock(o,e,t){var l;const n=this.ensurePreviewWorkspace(),s=n.newBlock(X(o.identifier,this.definitions)),r=this.blockColors.get(o.identifier);r&&s.setColour(r);const c={mode:e,template:o.elements[t]??"",elementName:t,inputSlots:o.inputSlots};Ke({block:s,definition:o,view:c,mode:"block",context:"toolbox",elementTypes:this.elementTypes,resolveBlocklyType:d=>X(d,this.definitions)});const a=he(this.behaviors[o.identifier]);return(l=a==null?void 0:a.onViewApplied)==null||l.call(a,s,{Blockly:T,workspace:n,element:t,mode:e,context:"toolbox",definition:o}),s}createCodeText(o,e,t){try{const n=this.createPreviewBlock(o,e,t),{code:s}=at(n.workspace,e,this.definitions,this.elementTypes,this.modes,t,{emptyStatements:!1});return n.dispose(!1),s}catch{return null}}createBlockPreviewSvg(o,e,t){try{const n=this.ensurePreviewWorkspace(),s=this.createPreviewBlock(o,e,t);for(const u of s.getDescendants(!1))u.initSvg(),u.queueRender();s.render();const r=s.getSvgRoot();if(!r)return s.dispose(!1),null;const c=r.getBBox(),a=r.cloneNode(!0),l=4,d=document.createElementNS("http://www.w3.org/2000/svg","svg"),h=Math.ceil(c.width+l*2);return this.widestBlock=Math.max(this.widestBlock,h),d.setAttribute("width",String(h)),d.setAttribute("height",String(Math.ceil(c.height+l*2))),d.setAttribute("viewBox",`${c.x-l} ${c.y-l} ${c.width+l*2} ${c.height+l*2}`),d.setAttribute("class",`${n.getRenderer().getClassName()} ${n.getTheme().getClassName()}`),d.style.direction="ltr",d.appendChild(a),s.dispose(!1),d}catch{return null}}createBlockAtPosition(o,e,t){const n=this.workspace,s=n.getInjectionDiv().getBoundingClientRect(),r=(e-s.left-n.scrollX)/n.scale,c=(t-s.top-n.scrollY)/n.scale,a=n.newBlock(X(o,this.definitions));a.moveTo(new T.utils.Coordinate(r,c)),a.initSvg(),a.render()}resolveBlockIds(){return this.options.blocks??[...this.definitions.keys()]}resolveCategoryBlockIds(o,e){return o.blocks&&o.blocks.length>0?o.blocks.filter(t=>e.includes(t)):e.filter(t=>{var n,s;return((s=(n=this.definitions.get(t))==null?void 0:n.category)==null?void 0:s.toLowerCase())===o.name.toLowerCase()})}}function Tt(i){if(!(i instanceof Element))return!1;const o=i.closest("button, a[href], input, select, textarea, [contenteditable]");return o!==null&&o.closest("[data-morphic-custom]")!==null}function Re(i,o){var t;if(i.blocks&&i.blocks.length>0)return i.blocks;const e=[];for(const n of o.values())((t=n.category)==null?void 0:t.toLowerCase())===i.name.toLowerCase()&&e.push(n.identifier);return e}function Lt(i,o){var n,s,r;if((i.kind??((n=i.categories)!=null&&n.length?"categoryToolbox":"flyoutToolbox"))==="categoryToolbox")return{kind:"categoryToolbox",contents:(i.categories??[]).map(a=>({kind:"category",name:a.name,colour:a.color,contents:Re(a,o).map(l=>({kind:"block",type:X(l,o)}))}))};if((s=i.categories)!=null&&s.length){const c=i.categories,a=[];return c.forEach((d,h)=>{const u=H(d.name);a.push({kind:"label",id:`morphic-category-${u}`,text:d.name,"web-class":`morphic-flyout-category-label morphic-category-${u}`});for(const p of Bt(Re(d,o)))a.push({kind:"block",type:X(p,o)});h<c.length-1&&a.push({kind:"sep",gap:14})}),{kind:"flyoutToolbox",contents:a}}return{kind:"flyoutToolbox",contents:(i.blocks??Bt(((r=i.categories)==null?void 0:r.flatMap(c=>Re(c,o)))??[...o.keys()])).map(c=>({kind:"block",type:X(c,o)}))}}function Bt(i){return i.filter((o,e,t)=>t.indexOf(o)===e)}const un='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="4" y="4" width="9" height="10" rx="1.5"/><path d="M3 11V3a1 1 0 0 1 1-1h7"/></svg>',fn='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 3h6v2H5z"/><path d="M4 3H3a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V4a1 1 0 0 0-1-1h-1"/></svg>',pn='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8h7a3 3 0 0 1 0 6H6"/><polyline points="5 5 2 8 5 11"/></svg>',mn='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M13 8H6a3 3 0 0 0 0 6h4"/><polyline points="11 5 14 8 11 11"/></svg>',gn='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 4 13 4"/><path d="M5 4V3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v1"/><path d="M4 4l1 9a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1l1-9"/></svg>',wn='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="4" y1="4" x2="12" y2="12"/><line x1="12" y1="4" x2="4" y2="12"/></svg>',kn='<svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor"><polygon points="4,3 13,8 4,13"/></svg>',vn='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="7" r="4"/><line x1="10" y1="10" x2="14" y2="14"/><line x1="5" y1="7" x2="9" y2="7"/><line x1="7" y1="5" x2="7" y2="9"/></svg>',yn='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="7" r="4"/><line x1="10" y1="10" x2="14" y2="14"/><line x1="5" y1="7" x2="9" y2="7"/></svg>',bn='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 3 3 6 3"/><polyline points="13 6 13 3 10 3"/><polyline points="3 10 3 13 6 13"/><polyline points="13 10 13 13 10 13"/></svg>',Cn='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 2h8l2 2v10H3z"/><rect x="5" y="2" width="6" height="4"/><rect x="5" y="9" width="6" height="4"/></svg>',En='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8v5a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V8"/><polyline points="5 5 8 2 11 5"/><line x1="8" y1="2" x2="8" y2="10"/></svg>',Sn='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8a5 5 0 1 0 1.5-3.5"/><polyline points="3 2 3 5 6 5"/></svg>',N={viewLabel(){return{id:"view-label",render:i=>{const o=document.createElement("span");return o.className="morphic-toolbar-label",o.textContent=i.engine.getViewElement(i.view)??"",o}}},copy(){return{id:"copy",label:"Copy",title:"Copy block",icon:un,onClick:i=>{i.engine.copyActiveBlock(i.view)}}},paste(){return{id:"paste",label:"Paste",title:"Paste block",icon:fn,disabled:i=>!i.engine.hasClipboardContents(),onClick:i=>{i.engine.pasteActiveBlock(i.view)}}},undo(){return{id:"undo",label:"Undo",title:"Undo (block model)",icon:pn,onClick:i=>{var o;(o=i.engine.getWorkspace())==null||o.undo(!1)},disabled:i=>{var o;return!((o=i.engine.getWorkspace())!=null&&o.getUndoStack().length)}}},redo(){return{id:"redo",label:"Redo",title:"Redo (block model)",icon:mn,onClick:i=>{var o;(o=i.engine.getWorkspace())==null||o.undo(!0)},disabled:i=>{var o;return!((o=i.engine.getWorkspace())!=null&&o.getRedoStack().length)}}},zoomIn(){return{id:"zoom-in",label:"Zoom in",title:"Zoom in",icon:vn,onClick:i=>i.engine.zoomPane(i.view,"in")}},zoomOut(){return{id:"zoom-out",label:"Zoom out",title:"Zoom out",icon:yn,onClick:i=>i.engine.zoomPane(i.view,"out")}},zoomFit(){return{id:"zoom-fit",label:"Fit",title:"Reset zoom",icon:bn,onClick:i=>i.engine.zoomPane(i.view,"fit")}},deleteSelection(){return{id:"delete",label:"Delete",title:"Delete selected lines",icon:wn,visible:i=>i.engine.getDeleteOptions(i.view).toolbarButton,disabled:i=>!i.engine.hasSelectedLines(i.view),onClick:i=>{i.engine.deleteSelectedLines(i.view)}}},clear(){return{id:"clear",label:"Clear",title:"Clear workspace",icon:gn,onClick:i=>{var o;window.confirm("Clear workspace? This cannot be undone.")&&((o=i.engine.getWorkspace())==null||o.clear())}}},runCode(){return{id:"run",label:"Run",title:"Run generated code",icon:kn,onClick:i=>{i.engine.runJavaScript()}}},save(){return{id:"save",label:"Save",title:"Save workspace as JSON",icon:Cn,onClick:i=>{if(!i.engine.getWorkspace())return;const e=i.engine.serializeWorkspace(),t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),n=URL.createObjectURL(t),s=document.createElement("a");s.href=n,s.download="workspace.json",s.click(),URL.revokeObjectURL(n)}}},load(){return{id:"load",label:"Load",title:"Load workspace JSON",icon:En,onClick:i=>{const o=document.createElement("input");o.type="file",o.accept="application/json",o.addEventListener("change",async()=>{var t;const e=(t=o.files)==null?void 0:t[0];if(e)try{const n=await e.text(),s=JSON.parse(n);i.engine.loadWorkspace(s)}catch(n){window.alert(`Load failed: ${n instanceof Error?n.message:String(n)}`)}}),o.click()}}},reset(){return{id:"reset",label:"Reset",title:"Reset workspace",icon:Sn,onClick:i=>{var o;window.confirm("Reset workspace to empty? This cannot be undone.")&&((o=i.engine.getWorkspace())==null||o.clear())}}},readOnlyBadge(){return{id:"read-only",align:"right",render:()=>{const i=document.createElement("span");return i.className="morphic-toolbar-badge",i.textContent="read-only",i}}},spacer(){return{id:"spacer",render:()=>{const i=document.createElement("span");return i.className="morphic-toolbar-spacer",i}}},readOnlyDefaults(){return[N.viewLabel(),N.spacer(),N.copy(),N.zoomIn(),N.zoomOut(),N.zoomFit(),N.readOnlyBadge()]},defaultsFor(i,o=!1){if(o)return N.readOnlyDefaults();switch(i){case"workspace":return[N.viewLabel(),N.spacer(),N.undo(),N.redo(),N.copy(),N.paste(),N.zoomIn(),N.zoomOut(),N.zoomFit(),N.clear()];case"codespace":return[N.viewLabel(),N.spacer(),N.undo(),N.redo(),N.copy(),N.paste(),N.deleteSelection(),N.zoomIn(),N.zoomOut(),N.zoomFit(),N.clear()]}}};function It(i,o,e){const t=o.items??N.defaultsFor(e.kind,e.readOnly),n=o.display??"icon";i.classList.add("morphic-toolbar"),i.setAttribute("data-morphic-kind",e.kind),i.setAttribute("data-morphic-view",e.view);const s=document.createElement("div");s.className="morphic-toolbar-left";const r=document.createElement("div");r.className="morphic-toolbar-right";const c=()=>{s.replaceChildren(),r.replaceChildren();let a=!1;for(const l of t){if(l.visible&&!l.visible(e))continue;if(l.id==="spacer"){a=!0;continue}(l.align==="right"||a&&l.align!=="left"?r:s).appendChild(xn(l,n,e))}};return i.replaceChildren(s,r),c(),{refresh:c,kind:e.kind,view:e.view,dispose:()=>i.replaceChildren()}}function xn(i,o,e){if(i.render){const n=i.render(e);if(typeof n=="string"){const s=document.createElement("span");return s.className="morphic-toolbar-item",s.dataset.toolbarId=i.id,s.textContent=n,s}return n.classList.add("morphic-toolbar-item"),n.dataset.toolbarId=i.id,n}const t=document.createElement("button");return t.className="morphic-toolbar-item",t.dataset.toolbarId=i.id,t.type="button",i.title&&(t.title=i.title),Tn(t,i,o),i.disabled&&i.disabled(e)&&(t.disabled=!0),i.onClick&&t.addEventListener("click",()=>i.onClick(e)),t}function Tn(i,o,e){const t=e!=="label"&&!!o.icon,n=e!=="icon"&&!!o.label,s=t||e==="icon"&&!o.label,r=n||e==="label"&&!o.icon;if(s&&o.icon){const c=document.createElement("span");c.className="morphic-toolbar-icon",c.innerHTML=o.icon,i.appendChild(c)}if(r&&o.label){const c=document.createElement("span");c.className="morphic-toolbar-text",c.textContent=o.label,i.appendChild(c)}!i.title&&o.label&&(i.title=o.label),!i.childNodes.length&&o.label&&(i.textContent=o.label)}function Mt(i,o){return o.includes("{")?{mode:i,cssText:o}:{mode:i,href:o}}function Ln(i){const o=[];for(const[e,t]of Object.entries(i)){const s=(e.split("/").pop()??e).replace(/\.css$/i,""),r=typeof t=="string"?t:typeof t=="object"&&t!==null&&"default"in t?String(t.default):void 0;r&&o.push(Mt(s,r))}return o}const Bn={workspace:"workspace",codespace:"codespace"};function $t(i){return Object.fromEntries(Object.entries(i??Bn).map(([o,e])=>[o,typeof e=="string"?{kind:e}:e]))}const In="blockly-media/",At=new Set;function Mn(i,o){if(At.has(i)||typeof Image>"u")return;At.add(i);const e=new Image;e.onerror=()=>{o(`[MorphicBlocks] Blockly's media is missing at "${i}", so icons are not shown and sounds stay silent. Copy it there with the bundler plugin (morphic-blocks/vite and others) or "morphic-blocks copy-media <folder>", or point blockly.media to where it is.`)},e.src=`${i}sprites.png`}const ie=i=>i.onWarning??(o=>console.warn(o)),le=new WeakMap,xe=new Map;function Ot(i,o){const e=Object.keys(i);return e.find(t=>i[t].kind==="workspace")??e.find(t=>o[t])}function $n(i){const o=i.setInsertionMarker;i.setInsertionMarker=function(e){var t;if(o.call(this,e),!!e)for(const n of this.inputList)(t=n.connection)==null||t.setShadowState(null)}}class An extends EventTarget{constructor(e,t={}){super();v(this,"definitions");v(this,"behaviors");v(this,"elementTypes");v(this,"formatElementTypes");v(this,"styles",new on);v(this,"registeredBlockTypes",new Set);v(this,"toolbars",new Set);v(this,"toolbarsBlocklyListener");v(this,"lastCopyData");v(this,"mountConfig");v(this,"workspace");v(this,"flyoutWorkspace");v(this,"toolboxCanvas");v(this,"tileDropTargets",new Set);v(this,"codeEditor");v(this,"views",new Set);v(this,"viewWorkspaceElements",new WeakMap);v(this,"viewCount",0);v(this,"selectionSync");v(this,"toolboxDefinition");v(this,"blockCategoryIndex",new Map);v(this,"appliedWorkspaceClasses",[]);v(this,"appliedToolboxFlyoutClasses",[]);v(this,"appliedToolboxShellClasses",[]);v(this,"headlessWorkspaceHost");v(this,"workspaceResizeObserver");v(this,"activePreset");v(this,"baseTheme");v(this,"baseFont");v(this,"mountGeneration",0);v(this,"selectionSyncOptions");v(this,"formatModes");v(this,"formatPresets");v(this,"formatViews");v(this,"formatCode");v(this,"formatHasHighlighting");v(this,"formatCategories");v(this,"onWorkspaceChange",e=>{if(!this.workspace||!this.mountConfig||e.workspaceId!==this.workspace.id||e.type!==T.Events.BLOCK_CREATE)return;const t=e;for(const n of t.ids??[]){const s=this.workspace.getBlockById(n);if(!s)continue;const r=this.definitions.get(G(s.type));if(!r)continue;const c=this.mountConfig.workspaceElement,a=s;if(a.__morphicMode===c&&a.__morphicContext==="workspace"&&s.getSvgRoot()){Je(s,c,"workspace"),this.styleBlock(s,r);continue}this.applyView(s,r,c,"workspace"),s.getSvgRoot()||this.deferApplyView(n,c,"workspace")}});v(this,"onFlyoutChange",e=>{if(!this.flyoutWorkspace||!this.mountConfig||e.workspaceId!==this.flyoutWorkspace.id||e.type!==T.Events.BLOCK_CREATE)return;const t=e;for(const n of t.ids??[]){const s=this.flyoutWorkspace.getBlockById(n);if(!s)continue;const r=this.definitions.get(G(s.type));r&&(this.applyView(s,r,this.mountConfig.toolboxMode,"toolbox"),s.getSvgRoot()||this.deferApplyView(n,this.mountConfig.toolboxMode,"toolbox"))}});v(this,"onStylesLoaded",()=>this.refresh());const n=e;this.definitions=Xo(Uo(Go(n.blocks,n.elementTypes??{}))),this.behaviors=t,this.formatElementTypes=n.elementTypes??{},this.elementTypes=je(this.formatElementTypes,n.code),this.formatModes=n.modes,this.formatPresets=n.presets,this.formatViews=n.views,this.formatCode=n.code,this.formatHasHighlighting="highlighting"in n,this.formatCategories=n.categories}mount(e){var x,g,C,f,y,S,M,O,V;this.dispose();const t={...e,modes:(x=e.modes??this.formatModes)==null?void 0:x.slice(),presets:e.presets??this.formatPresets,code:e.code??this.formatCode,toolbox:e.toolbox||this.formatCategories?{...e.toolbox,categories:((g=e.toolbox)==null?void 0:g.categories)??this.formatCategories}:void 0},n=t.modesFolder?Ln(t.modesFolder):[],s=[...n,...Object.entries(t.modeStyles??{}).filter(([I])=>!n.some(F=>F.mode===I)).map(([I,F])=>Mt(I,F))];this.elementTypes=je(this.formatElementTypes,t.code),this.validateDefinitions(t),this.validatePresets(t);const r=(C=t.presets)!=null&&C.length?t.presets.find(I=>I.name===t.preset)??t.presets[0]:void 0;if(t.preset&&!r)throw new Error(`MorphicBlocks.mount: unknown preset "${t.preset}".`);const c=(t.modes??[]).map(I=>I.name),a=c[0]??((f=s[0])==null?void 0:f.mode)??"default",l=r?r.toolbox:a,d=$t(t.views??this.formatViews),h={...t.containers};t.workspaceContainer&&(h.workspace??(h.workspace=t.workspaceContainer)),t.codespaceContainer&&(h.codespace??(h.codespace=t.codespaceContainer)),this.validateViews(d,h);const u=Object.keys(d).find(I=>d[I].kind==="workspace"&&h[I]),p=this.defaultElement(t.modes??[]),m=I=>(I?r==null?void 0:r.views[I]:void 0)??p,w=m(u??Ot(d,h)),b=u&&h[u]||this.createHeadlessHost(),k={...t,modeStyles:s,workspaceElement:w,toolboxMode:l,viewDeclarations:d,viewContainers:h,programView:u,workspaceHost:b,canvasToolbox:t.canvasToolbox??!!t.toolboxContainer};this.mountConfig=k,this.styles.validateModeCoverage(s,c,ie(t)),(y=k.modes)!=null&&y.length&&this.styles.ensureModeVisibilityStyles(k.modes),this.styles.ensureStyles(k.baseStyle,s);for(const I of Array.from(document.head.querySelectorAll('link[data-morphic-source^="mode:"]')))I.sheet||I.addEventListener("load",this.onStylesLoaded,{once:!0});(S=document.fonts)==null||S.addEventListener("loadingdone",this.onStylesLoaded),this.blockCategoryIndex=this.createCategoryIndex(k.toolbox,k),this.styles.ensureCategoryStyles(((M=k.toolbox)==null?void 0:M.categories)??[]),this.styles.ensureWorkspaceStyles(),this.registerBlocks(),this.toolboxDefinition=this.resolveToolboxDefinition(k);const B=k.blockly??{},L=u?d[u].editable!==!1:!0;if(this.workspace=T.inject(k.workspaceHost,{...B,...L?{}:{readOnly:!0},...u&&d[u].rtl!==void 0?{rtl:d[u].rtl}:{},media:B.media??In,...k.canvasToolbox?{}:{toolbox:this.toolboxDefinition}}),this.workspace.addChangeListener(this.onWorkspaceChange),le.set(this.workspace,this),this.baseTheme=this.workspace.getTheme(),this.baseFont=gt(this.workspace),u&&Mn(this.workspace.options.pathToMedia,ie(t)),u&&typeof ResizeObserver<"u"){const I=this.workspace;this.workspaceResizeObserver=new ResizeObserver(()=>T.svgResize(I)),this.workspaceResizeObserver.observe(b)}this.applyWorkspaceContainerClass(),this.syncWorkspaceFont(),this.refreshToolbox(),this.bindFlyoutWorkspace(),this.renderWorkspaceBlocks(),this.renderFlyoutBlocks(),t.toolboxContainer&&this.mountToolbox(t.toolboxContainer);const E=[];for(const[I,F]of Object.entries(d)){const R=h[I];if(!R||I===u)continue;const z=this.addView({kind:F.kind,name:I,container:R,element:m(I),editable:F.editable,rtl:F.rtl,delete:F.delete,theme:((O=t.themes)==null?void 0:O[I])??t.editorTheme});E.push(z.ready)}return this.activePreset=r,this.applyPresetClasses(),r&&((V=k.onPresetApplied)==null||V.call(k,r)),this.mountViews(t,E,++this.mountGeneration)}async mountViews(e,t,n){var a;const s=[...t];if(e.codeEditorContainer){const l=e.editorTheme?{theme:e.editorTheme}:void 0;s.push(this.mountCodeEditor(e.codeEditorContainer,l).then(()=>{n===this.mountGeneration&&this.hideCodeEditor()}))}if(await Promise.all(s),n!==this.mountGeneration||!this.workspace)return;for(const[l,d]of Object.entries(e.toolbars??{}))d&&this.resolveView(l)&&this.mountToolbar(d,{view:l});const r=Object.keys(((a=this.mountConfig)==null?void 0:a.viewContainers)??{}).filter(l=>this.resolveView(l)).length+(e.codeEditorContainer?1:0),c=e.selectionSync??r>1;c&&this.hasTextEditor()&&this.enableSelectionSync(typeof c=="object"?c:void 0)}applyPresetClasses(){var t,n;const e=(t=this.activePreset)==null?void 0:t.name;(n=this.mountConfig)!=null&&n.programView&&ve(this.mountConfig.workspaceHost,e);for(const s of this.views)ve(s.container,e)}hasTextEditor(){return!!this.codeEditor||[...this.views].some(e=>e.editor)}get codespace(){for(const e of this.views)if(e.kind==="codespace"&&e.editable!==!1)return e.editor}getPresets(){var e;return[...((e=this.mountConfig)==null?void 0:e.presets)??[]]}getActivePreset(){return this.activePreset}applyPreset(e){var r,c;if(!this.mountConfig||!this.workspace)throw new Error("MorphicBlocks must be mounted before applyPreset can be used.");const t=this.mountConfig.presets??[],n=typeof e=="number"?t[e]:t.find(a=>a.name===e);if(!n)throw new Error(`applyPreset: unknown preset "${e}".`);const s=Object.fromEntries(Object.entries(n.views).filter(([a])=>{var l;return((l=this.mountConfig)==null?void 0:l.viewDeclarations[a])||this.resolveView(a)}));return this.show({toolbox:n.toolbox,views:s}),this.activePreset=n,this.applyPresetClasses(),(c=(r=this.mountConfig).onPresetApplied)==null||c.call(r,n),n}validateDefinitions(e){var r;const{errors:t,warnings:n}=vt({definitions:this.definitions,elementTypes:this.formatElementTypes,behaviors:this.behaviors,modes:e.modes,presets:e.presets,code:e.code,categories:(r=e.toolbox)==null?void 0:r.categories,views:Object.keys(e.views??this.formatViews??{})}),s={previewContainer:'the preview is a codespace that cannot be edited: declare it in "views" ({ "preview": { "kind": "codespace", "editable": false } }) and pass containers: { preview: element }',previewTheme:"themes: { <view>: theme } sets a single text view's colours",toolbarContainers:"toolbars: { <view>: element }, by view name",codespace:'the codespace options sit on its view in "views": { "codespace": { "kind": "codespace", "delete": { … } } }'};for(const[c,a]of Object.entries(s))c in e&&t.push(`mount option "${c}" moved in 0.4.0: ${a}.`);for(const c of e.presets??[]){const a=["workspace","codespace","preview"].filter(l=>l in c);a.length>0&&t.push(`Preset "${c.name}": ${a.map(l=>`"${l}"`).join(", ")} moved into "views" in 0.4.0, by view name: "views": { ${a.map(l=>`"${l}": "${c[l]}"`).join(", ")} }.`)}if((this.formatHasHighlighting||"highlighting"in e)&&t.push('The top level "highlighting" map moved into the "code" section: "code": { "<element>": { "highlighting": { … } } }.'),n.length>0&&ie(e)(`[MorphicBlocks] Definition warnings:
33
+ - ${n.join(`
34
+ - `)}`),t.length>0)throw new Error(`[MorphicBlocks] Invalid definitions:
35
+ - ${t.join(`
36
+ - `)}`)}validatePresets(e){const t=e.presets??[];if(t.length===0)return;const n=e.modes??[],s=new Map(n.map(a=>[a.name,a])),r=$t(e.views??this.formatViews),c=new Set;for(const a of t){if(c.has(a.name))throw new Error(`Preset "${a.name}" is defined more than once.`);if(c.add(a.name),!s.has(a.toolbox))throw new Error(`Preset "${a.name}": unknown mode "${a.toolbox}" for the toolbox.`);const l=Object.entries(a.views??{});if(l.length===0)throw new Error(`Preset "${a.name}": "views" must name at least one view.`);for(const[d,h]of l)if(r[d]||ie(e)(`[MorphicBlocks] Preset "${a.name}" names "${d}", which is no declared view (${Object.keys(r).join(", ")}).`),W(this.elementTypes[h])!=="code")throw new Error(`Preset "${a.name}": view "${d}" shows "${h}", which is no code element.`+(s.has(h)?` Views show elements since 0.4.0, and "${h}" is a mode.`:""))}}dispose(){var e,t,n,s,r;for(const[c,a]of xe)a===this&&xe.delete(c);(e=this.workspaceResizeObserver)==null||e.disconnect(),this.workspaceResizeObserver=void 0,(t=document.fonts)==null||t.removeEventListener("loadingdone",this.onStylesLoaded),this.activePreset=void 0,(n=this.selectionSync)==null||n.disable(),this.selectionSync=void 0,(s=this.codeEditor)==null||s.dispose(),this.codeEditor=void 0;for(const c of this.views)this.disposeView(c);this.views.clear(),(r=this.toolboxCanvas)==null||r.dispose(),this.toolboxCanvas=void 0;for(const c of[...this.toolbars])c.dispose();this.flyoutWorkspace&&(this.flyoutWorkspace.removeChangeListener(this.onFlyoutChange),this.flyoutWorkspace=void 0),this.workspace&&(this.workspace.removeChangeListener(this.onWorkspaceChange),this.workspace.dispose(),this.workspace=void 0),this.headlessWorkspaceHost&&(this.headlessWorkspaceHost.remove(),this.headlessWorkspaceHost=void 0),this.mountConfig=void 0,this.baseTheme=void 0,this.baseFont=void 0,this.toolboxDefinition=void 0,this.blockCategoryIndex.clear(),this.appliedWorkspaceClasses=[],this.appliedToolboxFlyoutClasses=[],this.appliedToolboxShellClasses=[]}mountToolbox(e,t){var r,c,a;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before mountToolbox can be used.");(r=this.toolboxCanvas)==null||r.dispose(),this.styles.ensureToolbarStyles(),this.mountConfig.canvasToolbox||this.workspace.updateToolbox({kind:"flyoutToolbox",contents:[]});const n=this.mountConfig.toolbox,s={...t,blocks:(t==null?void 0:t.blocks)??(n==null?void 0:n.blocks),categories:(t==null?void 0:t.categories)??(n==null?void 0:n.categories),modeLabel:(t==null?void 0:t.modeLabel)??(n==null?void 0:n.modeLabel),highlight:(t==null?void 0:t.highlight)??(n==null?void 0:n.highlight),touch:(t==null?void 0:t.touch)??(n==null?void 0:n.touch),keyboard:(t==null?void 0:t.keyboard)??(n==null?void 0:n.keyboard),categoryHeadings:(t==null?void 0:t.categoryHeadings)??(n==null?void 0:n.categoryHeadings),collapsible:(t==null?void 0:t.collapsible)??(n==null?void 0:n.collapsible),collapsed:(t==null?void 0:t.collapsed)??(n==null?void 0:n.collapsed),onCategoryToggle:(t==null?void 0:t.onCategoryToggle)??(n==null?void 0:n.onCategoryToggle),layout:(t==null?void 0:t.layout)??(n==null?void 0:n.layout),scrollbar:(t==null?void 0:t.scrollbar)??(n==null?void 0:n.scrollbar),custom:(t==null?void 0:t.custom)??(n==null?void 0:n.custom),label:(t==null?void 0:t.label)??(n==null?void 0:n.label)};for(const[l,d]of Object.entries(this.elementTypes))W(d)==="custom"&&!((c=s.custom)!=null&&c[l])&&ie(this.mountConfig)(`[MorphicBlocks] The custom element "${l}" has no function in toolbox.custom; tiles show its content as text.`);s.layout==="tabs"&&!((a=s.categories)!=null&&a.length)&&ie(this.mountConfig)('[MorphicBlocks] The toolbox layout "tabs" needs categories; the tiles show as a flat list.'),this.toolboxCanvas=new xt({container:e,workspaceContainer:this.mountConfig.workspaceHost,workspace:this.workspace,definitions:this.definitions,blockColors:this.buildBlockColorMap(),behaviors:this.behaviors,elementTypes:this.elementTypes,mode:this.mountConfig.toolboxMode,modes:this.mountConfig.modes,code:this.mountConfig.code,options:s,onPreviewWorkspace:l=>le.set(l,this),dropTargets:()=>[...this.tileDropTargets],onChoose:l=>this.addBlockFromTile(l)})}refresh(){var e;if(!(!this.workspace||!this.mountConfig)){this.syncWorkspaceFont(),Fe(this.workspace);for(const t of this.views)t.workspace&&(this.syncFontOf(t.workspace,t.container),Fe(t.workspace));(e=this.toolboxCanvas)==null||e.rerender(this.mountConfig.toolboxMode)}}getWorkspace(){return this.workspace}getAvailableModes(){var e;return(((e=this.mountConfig)==null?void 0:e.modes)??[]).map(t=>t.name)}getToolboxMode(){var e;return(e=this.mountConfig)==null?void 0:e.toolboxMode}getViewNames(){var e;return[...(e=this.mountConfig)!=null&&e.programView?[this.mountConfig.programView]:[],...[...this.views].map(t=>t.name)]}setModeElements(e,t){var d;if(!this.mountConfig||!this.workspace)throw new Error("MorphicBlocks must be mounted before setModeElements can be used.");const n=this.mountConfig.modes??[],s=n.findIndex(h=>h.name===e);if(s===-1)throw new Error(`setModeElements: unknown mode "${e}".`);const r=t.filter(h=>!(h in this.elementTypes));if(r.length>0)throw new Error(`setModeElements: unknown elements ${r.map(h=>`"${h}"`).join(", ")}.`);const c={...n[s],elements:[...t]},a=n.map((h,u)=>u===s?c:h);this.validatePresets({...this.mountConfig,modes:a});const l=n.slice();n[s]=c,this.styles.ensureModeVisibilityStyles(n,l),e===this.mountConfig.toolboxMode&&((d=this.toolboxCanvas)==null||d.rerender(this.mountConfig.toolboxMode),this.renderFlyoutBlocks())}modeDef(e){var t;if(e)return(((t=this.mountConfig)==null?void 0:t.modes)??[]).find(n=>n.name===e)}codespaceElement(){var e,t;return((e=[...this.views].find(n=>n.kind==="codespace"))==null?void 0:e.element)??((t=this.mountConfig)==null?void 0:t.workspaceElement)}mountToolbar(e,t){if(!this.workspace)throw new Error("MorphicBlocks must be mounted before mountToolbar can be used.");const n=t.view,s=this.resolveView(n);if(!s)throw new Error(`mountToolbar: no view named "${n}".`);this.styles.ensureToolbarStyles();const r=It(e,t,{engine:this,kind:s.kind,readOnly:s.readOnly,view:n,getText:()=>this.toolbarTextFor(n),refresh:()=>this.toolbarRefreshFor(n)});this.toolbars.add(r),this.ensureToolbarBlocklyListener();const c=r.dispose;return r.dispose=()=>{this.toolbars.delete(r),this.toolbars.size===0&&this.teardownToolbarBlocklyListener(),c()},r}toolbarTextFor(e){var n;const t=this.resolveView(e);if((t==null?void 0:t.kind)==="codespace")return((n=t.editor)==null?void 0:n.getValue())??this.generateElementText(t.element).code;if((t==null?void 0:t.kind)==="workspace"&&t.workspace!==this.workspace)return this.generateElementText(t.element).code;if(this.codespace)return this.codespace.getValue();try{return this.generateJavaScript()}catch{return""}}toolbarRefreshFor(e){var t,n;(n=(t=this.resolveView(e))==null?void 0:t.editor)==null||n.refresh()}runJavaScript(e){var p,m,w;let t="",n,s=null;const r=[],c=(e==null?void 0:e.console)??(e!=null&&e.logToConsole?console:void 0),a=this.codespaceElement(),l=a?(w=(m=(p=this.mountConfig)==null?void 0:p.code)==null?void 0:m[a])==null?void 0:w.values:void 0,d=b=>(...k)=>{r.push({level:b,text:k.map(B=>Et(B,l)).join(" ")}),c&&(c[b]??c.log).apply(c,k)},h={log:d("log"),warn:d("warn"),error:d("error")};try{t=this.generateJavaScript(),n=new Function("console",t)(h)}catch(b){s=b instanceof Error?b:new Error(String(b))}const u={code:t,result:n,error:s,output:r};return this.dispatchEvent(new CustomEvent("morphic-run",{detail:u})),u}hasClipboardContents(){return!!this.lastCopyData}getDeleteOptions(e){var n;const t=(n=[...this.views].find(s=>s.name===e))==null?void 0:n.delete;return{lineButtons:(t==null?void 0:t.lineButtons)!==!1,keys:(t==null?void 0:t.keys)!==!1,toolbarButton:(t==null?void 0:t.toolbarButton)!==!1}}hasSelectedLines(e){var n;const t=this.resolveView(e);return(t==null?void 0:t.kind)==="codespace"&&!!((n=t.editor)!=null&&n.getSelectedLines())}deleteSelectedLines(e){var s;const t=this.resolveView(e),n=(t==null?void 0:t.kind)==="codespace"?(s=t.editor)==null?void 0:s.getSelectedLines():null;return!(t!=null&&t.editor)||!n?!1:(t.editor.clearSelection(),this.deleteBlockAtCodespaceLine(t.editor,n.first,n.last),!0)}copyActiveBlock(e){var s;const t=this.resolveActiveBlock(e);if(!t)return!1;const n=t.toCopyData();if(!n)return!1;this.lastCopyData=n;try{const r=this.blockTextIn(e,t);r&&((s=navigator.clipboard)==null||s.writeText(r))}catch{}for(const r of this.toolbars)r.refresh();return!0}blockTextIn(e,t){var d,h;const n=this.resolveView(e),{code:s,metadata:r}=n!=null&&n.editor?{code:n.editor.getValue(),metadata:n.editor.metadata}:this.generateElementText((n==null?void 0:n.element)??((d=this.mountConfig)==null?void 0:d.workspaceElement)),c=r.get(t.id);if((c==null?void 0:c.startChar)===void 0||c.endChar===void 0)return"";const a=s.lastIndexOf(`
37
+ `,c.startChar-1)+1,l=((h=/^[ \t]*/.exec(s.slice(a)))==null?void 0:h[0])??"";return s.slice(c.startChar,c.endChar).split(`
38
+ `).map((u,p)=>p>0&&u.startsWith(l)?u.slice(l.length):u).join(`
39
+ `)}pasteActiveBlock(e){return!this.lastCopyData||!this.workspace?!1:T.clipboard.paste(this.lastCopyData,this.workspace)!==null}resolveActiveBlock(e){var a,l,d;const t=T.common.getSelected();if(t&&"id"in t&&((a=this.workspace)!=null&&a.getBlockById(t.id)))return t;const n=(l=this.resolveView(e))==null?void 0:l.editor;if(!n)return null;const s=n.getCursorLine();let r=null;for(const[h,u]of n.metadata)if(u.startLine<=s&&u.endLine>=s){const p=u.endLine-u.startLine;(!r||p<r.size)&&(r={id:h,size:p})}return(r?(d=this.workspace)==null?void 0:d.getBlockById(r.id):null)??null}serializeWorkspace(){return this.workspace?T.serialization.workspaces.save(this.workspace):null}loadWorkspace(e){this.workspace&&(this.workspace.clear(),T.serialization.workspaces.load(e,this.workspace))}zoomPane(e,t){var r;const n=this.resolveView(e),s=n==null?void 0:n.workspace;if(s){t==="in"?s.zoomCenter(1):t==="out"?s.zoomCenter(-1):s.zoomToFit();return}(r=n==null?void 0:n.editor)==null||r.adjustZoom(t)}refreshToolbars(e){for(const t of this.toolbars)t.view===e&&t.refresh()}ensureToolbarBlocklyListener(){if(this.toolbarsBlocklyListener||!this.workspace)return;const e=t=>{for(const n of this.toolbars)n.refresh()};this.toolbarsBlocklyListener=e,this.workspace.addChangeListener(e)}teardownToolbarBlocklyListener(){!this.toolbarsBlocklyListener||!this.workspace||(this.workspace.removeChangeListener(this.toolbarsBlocklyListener),this.toolbarsBlocklyListener=void 0)}show(e){var t,n,s;if(!this.mountConfig||!this.workspace)throw new Error("MorphicBlocks must be mounted before show can be used.");if(e.toolbox!==void 0&&!this.modeDef(e.toolbox))throw new Error(`show: unknown mode "${e.toolbox}" for the toolbox.`);for(const[r,c]of Object.entries(e.views??{})){if(!this.mountConfig.viewDeclarations[r]&&!this.resolveView(r))throw new Error(`show: no view named "${r}".`);this.checkViewElement("show",c)}e.toolbox&&(this.mountConfig.toolboxMode=e.toolbox,(t=this.toolboxCanvas)==null||t.rerender(this.mountConfig.toolboxMode),this.refreshToolbox(),this.bindFlyoutWorkspace(),this.renderFlyoutBlocks());for(const[r,c]of Object.entries(e.views??{})){(this.mountConfig.programView?r===this.mountConfig.programView:r===Ot(this.mountConfig.viewDeclarations,this.mountConfig.viewContainers??{}))&&c!==this.mountConfig.workspaceElement&&(this.mountConfig.workspaceElement=c,this.applyWorkspaceContainerClass(),this.syncWorkspaceFont(),this.renderWorkspaceBlocks());const l=[...this.views].find(d=>d.name===r);l&&l.element!==c&&((n=l.show)==null||n.call(l,c))}this.refreshTextViews();for(const r of this.toolbars)r.refresh();(s=this.selectionSync)==null||s.clearAll()}setModes(e){throw new Error('setModes was replaced by show() in 0.4.0: show({ toolbox: "<mode>", views: { "<view>": "<element>" } }).')}generateJavaScript(){if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before generateJavaScript can be used.");return So(this.workspace,this.definitions,this.behaviors,this.mountConfig.javascript)}generateJavaScriptWithMetadata(){if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before generateJavaScriptWithMetadata can be used.");return xo(this.workspace,this.definitions,this.behaviors,this.mountConfig.javascript)}async mountCodeEditor(e,t){var s;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before mountCodeEditor can be used.");(s=this.codeEditor)==null||s.dispose(),this.codeEditor=new nt(e,this.workspace,()=>this.generateJavaScriptWithMetadata(),t,!0);const n=this.codeEditor;await n.mount(),this.codeEditor===n&&this.refreshSelectionSync()}attachCodespaceDropTarget(e,t,n){const s=g=>{var f;const C=(f=g.dataTransfer)==null?void 0:f.types;return C?C.includes(Z)||C.includes(Ie):!1},r=()=>{e.hideDropIndicator(),e.hideValueSlotHighlight()},c=(g,C)=>{const f=this.computeCodespaceDrop(e,g,C);if(!f){r();return}f.indicator.kind==="line"?(e.showDropIndicator(f.indicator.line,f.indicator.position),e.hideValueSlotHighlight()):(e.showValueSlotHighlight(f.indicator.from,f.indicator.to),e.hideDropIndicator())},a=g=>{s(g)&&(g.preventDefault(),c(g.clientX,g.clientY))},l=g=>{const C=g.relatedTarget;C&&t.contains(C)||r()},d=g=>{var C,f;s(g)&&(g.preventDefault(),h(g.clientX,g.clientY,(C=g.dataTransfer)==null?void 0:C.getData(Z),(f=g.dataTransfer)==null?void 0:f.getData(Ie)))},h=(g,C,f,y)=>{r();const S=this.computeCodespaceDrop(e,g,C);if(!S)return;let M=null;if(f)M=n.newBlock(X(f,this.definitions)),this.placeOrphanBelowTops(M),M.initSvg(),M.render();else if(y){if(M=n.getBlockById(y),!M)return}else return;const O=this.fitOrLoose(n,M,S);if(!O){f&&M.dispose(!1);return}let V=!1;T.Events.setGroup(!0);try{if(y&&M.getParent()&&M.unplug(!0),O.target.kind==="top")this.placeAtTopIndex(n,M,O.target.index),V=!0;else if(O.target.kind==="statement"){if(M.previousConnection){const I=n.getBlockById(O.target.targetBlockId);I&&I!==M&&(this.connectStatement(M,I,O.target.position),V=!0)}}else if(O.target.kind==="into-slot"){if(M.previousConnection){const I=n.getBlockById(O.target.parentBlockId);I&&I!==M&&(this.connectIntoSlot(M,I,O.target.inputName),V=!0)}}else if(O.target.kind==="value-slot"){if(M.outputConnection){const I=n.getBlockById(O.target.parentBlockId);I&&I!==M&&!this.isDescendantOf(I,M)&&(V=this.connectIntoValueSlot(M,I,O.target.inputName))}!V&&f&&M.dispose(!1)}}finally{T.Events.setGroup(!1)}!V&&M.workspace&&!M.getParent()&&this.placeOrphanBelowTops(M),T.svgResize(n)};let u=null;const p=3,m=g=>g.button===2||g.button===0&&g.ctrlKey,w=g=>{if(!u)return;if(!u.dragging){const f=Math.abs(g.clientX-u.startX),y=Math.abs(g.clientY-u.startY);if(f+y<p)return;u.dragging=!0}const C=this.computeCodespaceDrop(e,g.clientX,g.clientY);if(!C){e.hideDropIndicator(),e.hideValueSlotHighlight();return}C.indicator.kind==="line"?(e.showDropIndicator(C.indicator.line,C.indicator.position),e.hideValueSlotHighlight()):(e.showValueSlotHighlight(C.indicator.from,C.indicator.to),e.hideDropIndicator())},b=g=>{window.removeEventListener("mousemove",w),window.removeEventListener("mouseup",b),e.hideDropIndicator(),e.hideValueSlotHighlight();const C=u;if(u=null,tt(void 0),!(C!=null&&C.dragging))return;const f=this.computeCodespaceDrop(e,g.clientX,g.clientY);if(!f)return;const y=n.getBlockById(C.sourceId);y&&this.applyRightDragMove(n,y,f)},k=g=>{if(!m(g))return;const C=e.charAtCoords(g.clientX,g.clientY);if(C==null)return;const f=this.findInnermostBlockAtChar(e,C);f&&(g.preventDefault(),g.stopPropagation(),u={sourceId:f.id,startX:g.clientX,startY:g.clientY,dragging:!1},tt(f.id),window.addEventListener("mousemove",w),window.addEventListener("mouseup",b))},B=g=>{g.preventDefault()},L=g=>{if(u)return;const C=e.charAtCoords(g.clientX,g.clientY);if(C==null){e.setHoverHighlight(null),e.setEditableHoverHighlight(null);return}const f=this.findInnermostEditablePlaceholderAtChar(e,C);e.setEditableHoverHighlight(f?{from:f.start,to:f.end}:null);const y=this.findHoverBlockAtChar(e,C);if(!y){e.setHoverHighlight(null);return}const S=e.metadata.get(y.id);if(!S||S.startChar===void 0||S.endChar===void 0){e.setHoverHighlight(null);return}e.setHoverHighlight({from:S.startChar,to:S.endChar})},E=()=>{e.setHoverHighlight(null),e.setEditableHoverHighlight(null)},x={element:t,over:c,leave:r,drop:(g,C,f)=>h(C,f,g)};return this.tileDropTargets.add(x),t.addEventListener("dragover",a),t.addEventListener("dragleave",l),t.addEventListener("drop",d),t.addEventListener("mousedown",k,!0),t.addEventListener("contextmenu",B),t.addEventListener("mousemove",L),t.addEventListener("mouseleave",E),()=>{this.tileDropTargets.delete(x),t.removeEventListener("dragover",a),t.removeEventListener("dragleave",l),t.removeEventListener("drop",d),t.removeEventListener("mousedown",k,!0),t.removeEventListener("contextmenu",B),t.removeEventListener("mousemove",L),t.removeEventListener("mouseleave",E),window.removeEventListener("mousemove",w),window.removeEventListener("mouseup",b)}}findInnermostBlockAtChar(e,t){if(!this.workspace)return null;let n=null;for(const[s,r]of e.metadata){if(r.startChar===void 0||r.endChar===void 0||t<r.startChar||t>=r.endChar)continue;const c=r.endChar-r.startChar;(n===null||c<n.size)&&(n={id:s,size:c})}return n?this.workspace.getBlockById(n.id):null}findHoverBlockAtChar(e,t){if(!this.workspace)return null;let n=null,s=null;for(const[c,a]of e.metadata){if(a.startChar===void 0||a.endChar===void 0||t<a.startChar||t>=a.endChar)continue;const l=a.endChar-a.startChar;(s===null||l<s.size)&&(s={id:c,size:l}),!a.atomic&&(n===null||l<n.size)&&(n={id:c,size:l})}const r=n??s;return r?this.workspace.getBlockById(r.id):null}findInnermostEditablePlaceholderAtChar(e,t){let n=null;for(const s of e.getPlaceholders()){if(!s.edit||t<s.start||t>=s.end)continue;const r=s.end-s.start;(n===null||r<n.size)&&(n={ph:s,size:r})}return n?{start:n.ph.start,end:n.ph.end}:null}applyRightDragMove(e,t,n){if(!n||(n=this.fitOrLoose(e,t,n),!n))return;let s=!1;T.Events.setGroup(!0);try{if(t.getParent()&&t.unplug(!0),n.target.kind==="top")this.placeAtTopIndex(e,t,n.target.index),s=!0;else if(n.target.kind==="statement"){if(t.previousConnection){const r=e.getBlockById(n.target.targetBlockId);r&&r!==t&&(this.connectStatement(t,r,n.target.position),s=!0)}}else if(n.target.kind==="into-slot"){if(t.previousConnection){const r=e.getBlockById(n.target.parentBlockId);r&&r!==t&&(this.connectIntoSlot(t,r,n.target.inputName),s=!0)}}else if(n.target.kind==="value-slot"&&t.outputConnection){const r=e.getBlockById(n.target.parentBlockId);r&&r!==t&&!this.isDescendantOf(r,t)&&(s=this.connectIntoValueSlot(t,r,n.target.inputName))}}finally{T.Events.setGroup(!1)}!s&&t.workspace&&!t.getParent()&&this.placeOrphanBelowTops(t),T.svgResize(e)}computeCodespaceDrop(e,t,n){var p,m;if(!this.workspace)return null;const s=this.workspace.getTopBlocks(!0),r=e.metadata,c=e.getLineCount();if(s.length===0)return{indicator:{kind:"line",line:1,position:"above"},target:{kind:"top",index:0}};if(e.isBelowLastLine(n)){const w=r.get(s[s.length-1].id);return{indicator:{kind:"line",line:(w==null?void 0:w.endLine)??c,position:"below"},target:{kind:"top",index:s.length}}}const a=e.getLineAtCoords(t,n);if(a===null){const w=r.get(s[0].id);return{indicator:{kind:"line",line:(w==null?void 0:w.startLine)??1,position:"above"},target:{kind:"top",index:0}}}const l=e.charAtCoords(t,n);if(l!==null){const w=this.findValueSlotDropAtChar(e,l);if(w)return{indicator:{kind:"value-slot",from:w.highlight.from,to:w.highlight.to},target:{kind:"value-slot",parentBlockId:w.parentBlockId,inputName:w.inputName}}}const d=this.findInnermostStatementSlotAtLine(a,r);if(d){const w=this.workspace.getBlockById(d.blockId);if(w){const b=$e(),k=[];let B=(m=(p=w.getInput(d.inputName))==null?void 0:p.connection)==null?void 0:m.targetBlock();for(;B;)B.id!==b&&k.push(B),B=B.getNextBlock();for(const L of k){const E=r.get(L.id);if(!E||a<E.startLine||a>E.endLine)continue;const x=a===E.endLine,g=e.isInLowerHalfOfLine(a,n);return x&&g?{indicator:{kind:"line",line:E.endLine,position:"below"},target:{kind:"statement",targetBlockId:L.id,position:"after"}}:{indicator:{kind:"line",line:E.startLine,position:"above"},target:{kind:"statement",targetBlockId:L.id,position:"before"}}}if(k.length>0){const L=k[k.length-1],E=r.get(L.id);return{indicator:{kind:"line",line:(E==null?void 0:E.endLine)??d.range.endLine,position:"below"},target:{kind:"into-slot",parentBlockId:d.blockId,inputName:d.inputName}}}return{indicator:{kind:"line",line:d.range.startLine,position:"above"},target:{kind:"into-slot",parentBlockId:d.blockId,inputName:d.inputName}}}}const h=$e();for(let w=0;w<s.length;w++)for(let b=s[w];b;b=b.getNextBlock()){if(b.id===h)continue;const k=r.get(b.id);if(!k||a<k.startLine||a>k.endLine)continue;const B=a===k.endLine,L=e.isInLowerHalfOfLine(a,n),E=B&&L,x=E&&!b.getNextBlock();return{indicator:E?{kind:"line",line:k.endLine,position:"below"}:{kind:"line",line:k.startLine,position:"above"},target:{kind:"statement",targetBlockId:b.id,position:E?"after":"before",topIndex:x?w+1:w}}}const u=r.get(s[s.length-1].id);return{indicator:{kind:"line",line:(u==null?void 0:u.endLine)??c,position:"below"},target:{kind:"top",index:s.length}}}findInnermostStatementSlotAtLine(e,t){let n=null;for(const[s,r]of t)if(r.statementSlots)for(const[c,a]of Object.entries(r.statementSlots)){if(e<a.startLine||e>a.endLine)continue;const l=a.endLine-a.startLine,d=this.computeBlockDepth(s);(n===null||l<n.size||l===n.size&&d>n.depth)&&(n={blockId:s,inputName:c,range:a,size:l,depth:d})}return n?{blockId:n.blockId,inputName:n.inputName,range:n.range}:null}fitOrLoose(e,t,n){return this.codespaceDropAllowed(e,t,n.target)?n:n.target.kind==="statement"&&n.target.topIndex!==void 0?{...n,target:{kind:"top",index:n.target.topIndex}}:null}codespaceDropAllowed(e,t,n){var a,l,d;const s=(h,u)=>!!h&&!!u&&e.connectionChecker.canConnect(h,u,!1);if(n.kind==="top")return!0;if(n.kind==="value-slot"){const h=e.getBlockById(n.parentBlockId);return s((a=h==null?void 0:h.getInput(n.inputName))==null?void 0:a.connection,t.outputConnection)}if(n.kind==="into-slot"){const h=e.getBlockById(n.parentBlockId),u=(l=h==null?void 0:h.getInput(n.inputName))==null?void 0:l.connection;let p=u==null?void 0:u.targetBlock();for(;p!=null&&p.getNextBlock()&&p.getNextBlock()!==t;)p=p.getNextBlock();return s(p&&p!==t?p.nextConnection:u,t.previousConnection)}const r=e.getBlockById(n.targetBlockId);if(!r||r===t)return!1;if(n.position==="before"){const h=(d=r.previousConnection)==null?void 0:d.targetConnection;return h&&h.getSourceBlock()!==t&&!s(h,t.previousConnection)?!1:s(t.nextConnection,r.previousConnection)}const c=r.getNextBlock();return s(r.nextConnection,t.previousConnection)?!c||c===t||s(t.nextConnection,c.previousConnection):!1}connectIntoSlot(e,t,n){if(!e.previousConnection)return;const s=t.getInput(n),r=s==null?void 0:s.connection;if(!r)return;const c=r.targetBlock();if(!c){r.connect(e.previousConnection);return}let a=c,l=a.getNextBlock();for(;l;)a=l,l=a.getNextBlock();a.nextConnection&&a.nextConnection.connect(e.previousConnection)}findValueSlotDropAtChar(e,t){var r,c;if(!this.workspace)return null;const n=$e();for(const a of e.getPlaceholders()){if(t<a.start||t>=a.end)continue;if(a.emptySlot){const{parentBlockId:u,inputName:p}=a.emptySlot;if(u===n)continue;const m=this.workspace.getBlockById(u);if(!((r=m==null?void 0:m.getInput(p))!=null&&r.connection))continue;return{parentBlockId:u,inputName:p,highlight:{from:a.start,to:a.end}}}const l=(c=a.edit)==null?void 0:c.blockId;if(!l||l===n)continue;const d=this.workspace.getBlockById(l);if(!d)continue;const h=this.resolveValueParent(d);if(h)return{parentBlockId:h.parentBlockId,inputName:h.inputName,highlight:{from:a.start,to:a.end}}}let s=null;for(const[a,l]of e.metadata){if(l.startChar===void 0||l.endChar===void 0||t<l.startChar||t>=l.endChar||a===n)continue;const d=this.workspace.getBlockById(a);if(!(d!=null&&d.outputConnection))continue;const h=l.endChar-l.startChar;(s===null||h<s.size)&&(s={id:a,size:h,from:l.startChar,to:l.endChar})}if(s){const a=this.workspace.getBlockById(s.id);if(a){const l=this.resolveValueParent(a);if(l)return{parentBlockId:l.parentBlockId,inputName:l.inputName,highlight:{from:s.from,to:s.to}}}}return null}resolveValueParent(e){var s;const t=(s=e.outputConnection)==null?void 0:s.targetConnection;if(!t)return null;const n=t.getSourceBlock();if(!n)return null;for(const r of n.inputList)if(r.connection===t)return{parentBlockId:n.id,inputName:r.name};return null}addBlockFromTile(e){const t=this.workspace;if(!t)return;const n=T.common.getSelected(),s=n instanceof T.BlockSvg&&n.workspace===t?n:null;T.Events.setGroup(!0);try{const r=t.newBlock(X(e,this.definitions)),c=s&&!s.isShadow()?{kind:"statement",targetBlockId:s.id,position:"after"}:null,a=c!==null&&this.codespaceDropAllowed(t,r,c);a||this.placeOrphanBelowTops(r),r.initSvg(),r.render(),a&&s&&this.connectStatement(r,s,"after"),T.common.setSelected(r);const l=t.getMetricsManager().getViewMetrics(!0),d=r.getBoundingRectangle();d.left>=l.left&&d.top>=l.top&&d.right<=l.left+l.width&&d.bottom<=l.top+l.height||t.centerOnBlock(r.id)}finally{T.Events.setGroup(!1)}}placeOrphanBelowTops(e){var s,r;if(!this.workspace)return;const t=this.workspace.getTopBlocks(!0).filter(c=>c.id!==e.id);if(t.length===0){e.moveTo(new T.utils.Coordinate(20,20));return}let n=0;for(const c of t){const a=c.getRelativeToSurfaceXY(),l=((r=(s=c.getHeightWidth)==null?void 0:s.call(c))==null?void 0:r.height)??50;n=Math.max(n,a.y+l)}e.moveTo(new T.utils.Coordinate(20,n+20))}isDescendantOf(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.getParent()}return!1}connectIntoValueSlot(e,t,n){if(!e.outputConnection)return!1;const s=t.getInput(n),r=s==null?void 0:s.connection;if(!r)return!1;const c=r.targetBlock(),a=!!c&&!c.isShadow();a&&c.unplug(!1);try{r.connect(e.outputConnection)}catch{if(a&&(c!=null&&c.outputConnection))try{r.connect(c.outputConnection)}catch{}return!1}if(a&&c.outputConnection){const l=T.Connection.getConnectionForOrphanedConnection(e,c.outputConnection);l?l.connect(c.outputConnection):this.placeOrphanBelowTops(c)}return!0}computeBlockDepth(e){var s,r;let t=0,n=((r=(s=this.workspace)==null?void 0:s.getBlockById(e))==null?void 0:r.getParent())??null;for(;n;)t++,n=n.getParent();return t}placeAtTopIndex(e,t,n){const s=e.getTopBlocks(!0).map(c=>c.id).filter(c=>c!==t.id),r=Math.max(0,Math.min(n,s.length));s.splice(r,0,t.id),this.applyTopBlockOrder(e,s)}connectStatement(e,t,n){var s,r,c;if(e.previousConnection)if(n==="before"){const a=((s=t.previousConnection)==null?void 0:s.targetConnection)??null;(r=t.previousConnection)==null||r.disconnect(),a?a.connect(e.previousConnection):e.moveTo(t.getRelativeToSurfaceXY()),e.nextConnection&&t.previousConnection&&e.nextConnection.connect(t.previousConnection)}else{const a=t.getNextBlock();(c=a==null?void 0:a.previousConnection)==null||c.disconnect(),t.nextConnection&&t.nextConnection.connect(e.previousConnection),a!=null&&a.previousConnection&&e.nextConnection&&e.nextConnection.connect(a.previousConnection)}}applyTopBlockOrder(e,t){const n=T.Events.disable!==void 0;n&&T.Events.disable();try{let s=20;for(const r of t){const c=e.getBlockById(r);c&&(c.moveTo(new T.utils.Coordinate(20,s)),s+=c.getHeightWidth().height+20)}}finally{n&&T.Events.enable()}T.svgResize(e),this.refreshTextViews()}refreshTextViews(){var e,t;(e=this.codeEditor)==null||e.refresh();for(const n of this.views)(t=n.editor)==null||t.refresh()}generateElementText(e){return!this.workspace||!this.mountConfig||!e?{code:"",metadata:new Map,placeholders:[]}:at(this.workspace,e,this.definitions,this.elementTypes,this.mountConfig.modes??[],e)}highlightRulesFor(e){var t,n,s;return(s=(n=(t=this.mountConfig)==null?void 0:t.code)==null?void 0:n[e])==null?void 0:s.highlighting}defaultElement(e){return(e[0]?Ho(e[0],this.elementTypes):void 0)??Object.keys(this.elementTypes).find(n=>W(this.elementTypes[n])==="code")??"default"}addView(e){var d,h,u;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before addView can be used.");if(e.kind==="preview")throw new Error('addView: the preview is a codespace that cannot be edited since 0.4.0: { kind: "codespace", editable: false }.');if(e.kind!=="codespace"&&e.kind!=="workspace")throw new Error(`addView: unknown view kind "${String(e.kind)}".`);if(e.name!==void 0&&this.resolveView(e.name))throw new Error(`addView: a view named "${e.name}" already exists.`);if(e.kind==="workspace")return this.addWorkspaceView(e);this.checkViewElement("addView",e.element);const t=e.editable!==!1,n=new nt(e.container,this.workspace,()=>this.generateElementText(c.element),{theme:e.theme,highlightRules:this.highlightRulesFor(e.element),...t?{onDelete:(p,m)=>this.deleteBlockAtCodespaceLine(n,p,m),onLineSelection:()=>this.refreshToolbars(c.name),deleteButtons:(d=e.delete)==null?void 0:d.lineButtons,deleteKeys:(h=e.delete)==null?void 0:h.keys,canDragBlock:p=>this.canMoveInCodespace(p),onPlaceholderApply:(p,m)=>this.applyPlaceholderEdit(p,m)}:{showPlaceholderMarkers:!1}}),s=t?["morphic-codespace-root"]:["morphic-codespace-root","morphic-read-only"];let r=e.name;for(;r===void 0||this.resolveView(r);)r=`view-${++this.viewCount}`;const c={kind:e.kind,name:r,container:e.container,element:e.element,editor:n,editable:t,delete:e.delete};this.views.add(c),e.rtl!==void 0&&(e.container.dir=e.rtl?"rtl":"ltr"),ke(c.container,{name:r,element:c.element,classNames:s}),ve(c.container,(u=this.activePreset)==null?void 0:u.name);const a=e.toolbar?this.mountToolbar(e.toolbar.container,{view:r,items:e.toolbar.items,display:e.toolbar.display}):void 0,l={kind:c.kind,name:c.name,ready:n.mount().then(()=>{this.views.has(c)&&(t&&this.workspace&&(c.teardown=this.attachCodespaceDropTarget(n,c.container,this.workspace)),this.linkAddedView())}),getElement:()=>c.element,show:p=>{if(this.views.has(c)){this.checkViewElement("show",p),c.element=p,ke(c.container,{name:r,element:p,classNames:s}),n.setHighlightRules(this.highlightRulesFor(p)),n.refresh();for(const m of this.toolbars)m.refresh()}},setTheme:p=>n.setTheme(p),dispose:()=>{var p;this.views.delete(c)&&(a==null||a.dispose(),(p=c.teardown)==null||p.call(c),n.dispose(),this.refreshSelectionSync())}};return c.show=l.show,l}addWorkspaceView(e){var E;const t=this.workspace;this.checkViewElement("addView",e.element);let n=e.name;for(;n===void 0||this.resolveView(n);)n=`view-${++this.viewCount}`;const s=t.options,r=e.editable!==!1,c=T.inject(e.container,{readOnly:!r,media:s.pathToMedia,sounds:!1,renderer:s.renderer,rendererOverrides:s.rendererOverrides??void 0,theme:this.baseTheme??s.theme,rtl:e.rtl??s.RTL,move:{scrollbars:!0,drag:!0,wheel:!0}});le.set(c,this),this.viewWorkspaceElements.set(c,e.element);const a={kind:"workspace",name:n,container:e.container,element:e.element,workspace:c,editable:r};this.views.add(a),this.styleWorkspaceView(a),ve(a.container,(E=this.activePreset)==null?void 0:E.name);const l=()=>{const{scrollX:x,scrollY:g,scale:C}=c;T.Events.disable();try{T.serialization.workspaces.load(T.serialization.workspaces.save(t),c)}finally{T.Events.enable()}this.renderWorkspaceView(a),c.scale!==C&&c.setScale(C),c.scroll(x,g)};l();let d=null,h=!1;const u=()=>{var x;for(const g of c.getAllBlocks(!1))g.unselect();(x=c.getBlockById(d??""))==null||x.select()},p=x=>{if(x.workspaceId!==t.id)return;if(x.type===T.Events.SELECTED){d=x.newElementId??null,u();return}if(x.isUiEvent||h)return;h=!0;const g=()=>{if(this.views.has(a)){if(r&&(c.isDragging()||T.WidgetDiv.isVisible()||T.DropDownDiv.isVisible())){setTimeout(g,100);return}h=!1,l(),u()}};setTimeout(g,0)};t.addChangeListener(p);const m=x=>{if(x.isUiEvent||x.workspaceId!==c.id)return;const g=T.Events.getGroup();T.Events.setGroup(x.group||g||!0);try{T.Events.fromJson(x.toJson(),t).run(!0)}catch{}finally{T.Events.setGroup(g)}},w=r?this.attachWorkspaceTileDrop(c,e.container):void 0;r&&(c.addChangeListener(m),c.undo=x=>t.undo(x));const b=x=>{var y;const g=x.target,C=(y=g==null?void 0:g.closest)==null?void 0:y.call(g,"[data-id]");let f=C?t.getBlockById(C.getAttribute("data-id")??""):null;for(;f!=null&&f.isShadow();)f=f.getParent();f?T.common.setSelected(f):g!=null&&g.classList.contains("blocklyMainBackground")&&T.common.setSelected(null)};e.container.addEventListener("click",b);const k=typeof ResizeObserver<"u"?new ResizeObserver(()=>T.svgResize(c)):void 0;k==null||k.observe(e.container);const B=e.toolbar?this.mountToolbar(e.toolbar.container,{view:n,items:e.toolbar.items,display:e.toolbar.display}):void 0;a.teardown=()=>{t.removeChangeListener(p),c.removeChangeListener(m),w==null||w(),e.container.removeEventListener("click",b),k==null||k.disconnect(),B==null||B.dispose()};const L={kind:"workspace",name:n,ready:Promise.resolve(),getElement:()=>a.element,show:x=>{if(this.views.has(a)){this.checkViewElement("show",x),a.element=x,this.viewWorkspaceElements.set(c,x),this.styleWorkspaceView(a),this.renderWorkspaceView(a);for(const g of this.toolbars)g.refresh()}},setTheme:()=>{},dispose:()=>{this.views.delete(a)&&this.disposeView(a)}};return a.show=L.show,L}styleWorkspaceView(e){e.workspace&&(ke(e.container,{name:e.name,element:e.element,classNames:["morphic-workspace-root","morphic-context-workspace",...e.editable===!1?["morphic-read-only"]:[]]}),this.syncFontOf(e.workspace,e.container))}renderWorkspaceView(e){var t;T.Events.disable();try{for(const n of((t=e.workspace)==null?void 0:t.getAllBlocks(!1))??[]){const s=this.definitions.get(G(n.type));s&&this.applyView(n,s,e.element,"workspace")}}finally{T.Events.enable()}}attachWorkspaceTileDrop(e,t){const n=(a,l,d)=>{const h=this.workspace;if(!h)return;const u=e.getInjectionDiv().getBoundingClientRect(),p=h.newBlock(X(a,this.definitions));p.moveTo(new T.utils.Coordinate((l-u.left-e.scrollX)/e.scale,(d-u.top-e.scrollY)/e.scale)),p.initSvg(),p.render()},s=a=>{var l;(l=a.dataTransfer)!=null&&l.types.includes(Z)&&a.preventDefault()},r=a=>{var d;const l=(d=a.dataTransfer)==null?void 0:d.getData(Z);l&&(a.preventDefault(),n(l,a.clientX,a.clientY))},c={element:t,drop:n};return this.tileDropTargets.add(c),t.addEventListener("dragover",s),t.addEventListener("drop",r),()=>{this.tileDropTargets.delete(c),t.removeEventListener("dragover",s),t.removeEventListener("drop",r)}}disposeView(e){var t,n,s;(t=e.teardown)==null||t.call(e),(n=e.editor)==null||n.dispose(),(s=e.workspace)==null||s.dispose()}linkAddedView(){var t,n;if(this.selectionSync){this.refreshSelectionSync();return}const e=(t=this.mountConfig)==null?void 0:t.selectionSync;e===!1||!((n=this.mountConfig)!=null&&n.programView)||this.enableSelectionSync(typeof e=="object"?e:void 0)}resolveView(e){var t,n;if(this.workspace&&e===((t=this.mountConfig)==null?void 0:t.programView))return{name:e,kind:"workspace",element:this.mountConfig.workspaceElement,workspace:this.workspace,readOnly:((n=this.mountConfig.viewDeclarations[e])==null?void 0:n.editable)===!1};for(const s of this.views)if(s.name===e)return{name:e,kind:s.kind,element:s.element,editor:s.editor,workspace:s.workspace,readOnly:s.editable===!1}}getViewElement(e){var t;return(t=this.resolveView(e))==null?void 0:t.element}checkViewElement(e,t){if(W(this.elementTypes[t])==="code")return;const n=!!this.modeDef(t);throw new Error(`${e}: "${t}" is no code element.`+(n?` Views show elements since 0.4.0, and "${t}" is a mode.`:""))}applyPlaceholderEdit(e,t){var a;if(!this.workspace)return;let n=this.workspace.getBlockById(e.blockId);if(!n)return;if(n.isShadow()){const l=(a=n.outputConnection)==null?void 0:a.targetConnection;if(l){const d=this.workspace.newBlock(n.type);for(const h of n.inputList)for(const u of h.fieldRow){if(!u.name)continue;const p=d.getField(u.name);p&&p.setValue(u.getValue())}n.rendered&&(d.initSvg(),d.render()),l.connect(d.outputConnection),n=d}}const s=n.getField(e.fieldName);if(!s)return;s.setValue(t);const r=n;r.rendered&&typeof r.render=="function"&&r.render();const c=n.getParent();if(c){const l=c;l.rendered&&typeof l.render=="function"&&l.render()}}canMoveInCodespace(e){var n;const t=(n=this.workspace)==null?void 0:n.getBlockById(e);return!!(t!=null&&t.previousConnection||t!=null&&t.outputConnection)}deleteBlockAtCodespaceLine(e,t,n=t){const s=new Set;for(let a=t;a<=n;a++){const l=this.blockOwningLine(e,a);l&&s.add(l)}const r=a=>{for(let l=a.getSurroundParent();l;l=l.getSurroundParent())if(s.has(l))return!0;return!1},c=[...s].filter(a=>!r(a));if(c.length!==0){T.Events.setGroup(!0);try{for(const a of c)a.dispose(!0)}finally{T.Events.setGroup(!1)}}}blockOwningLine(e,t){const n=e.metadata;if(!this.workspace||!n||n.size===0)return null;const s=a=>{let l=0;for(let d=a.getParent();d;d=d.getParent())l++;return l},r=[];for(const[a,{startLine:l,endLine:d}]of n){if(t<l||t>d)continue;const h=this.workspace.getBlockById(a);!h||h.isShadow()||!(h.previousConnection||h.nextConnection)&&h.getParent()||r.push({block:h,startLine:l,size:d-l,depth:s(h)})}const c=a=>{var l;return((l=a.sort((d,h)=>d.size-h.size||h.depth-d.depth)[0])==null?void 0:l.block)??null};return c(r.filter(a=>a.startLine===t))??c(r)}showCodeEditor(){var e;(e=this.codeEditor)==null||e.show()}hideCodeEditor(){var e;(e=this.codeEditor)==null||e.hide()}isCodeEditorVisible(){var e;return((e=this.codeEditor)==null?void 0:e.isVisible())??!1}setCodeEditorTheme(e){var t;(t=this.codeEditor)==null||t.setTheme(e)}setViewTheme(e,t){var n,s;(s=(n=this.resolveView(e))==null?void 0:n.editor)==null||s.setTheme(t)}enableSelectionSync(e){var n;if(!this.workspace)throw new Error("MorphicBlocks must be mounted before enableSelectionSync can be used.");const t=[this.codeEditor,...[...this.views].map(s=>s.editor)].filter(s=>s!==void 0);if(t.length===0)throw new Error("enableSelectionSync needs a text view or the code editor to be set up first.");(n=this.selectionSync)==null||n.disable(),this.selectionSyncOptions=e,this.selectionSync=new zo(this.workspace,t,e),this.selectionSync.enable()}refreshSelectionSync(){this.selectionSync&&(this.hasTextEditor()?this.enableSelectionSync(this.selectionSyncOptions):this.disableSelectionSync())}disableSelectionSync(){var e;(e=this.selectionSync)==null||e.disable(),this.selectionSync=void 0,this.selectionSyncOptions=void 0}registerBlocks(){for(const e of this.definitions.values()){const t=De(e.identifier);if(xe.set(t,this),this.registeredBlockTypes.has(t))continue;const n=e.identifier;T.Blocks[t]={init(){const s=le.get(this.workspace)??xe.get(t);s==null||s.initManagedBlock(this,n)}},this.registeredBlockTypes.add(t)}}initManagedBlock(e,t){var l,d;const n=this.definitions.get(t);if(!n)return;const s=e.workspace.isFlyout?"toolbox":"workspace",r=this.viewWorkspaceElements.get(e.workspace)??this.resolveMode(s);this.applyView(e,n,r,s),$n(e);const c=he(this.behaviors[n.identifier]),a=s==="workspace"?ct(n,r,this.elementTypes).elementName:ae(n,r,this.elementTypes,((l=this.mountConfig)==null?void 0:l.modes)??[]).elementName;(d=c==null?void 0:c.init)==null||d.call(c,e,this.createBehaviorContext(e,n,a??r,s,r))}validateViews(e,t){for(const[n,s]of Object.entries(e)){if(s.kind==="preview")throw new Error(`View "${n}": the preview is a codespace that cannot be edited since 0.4.0: { "kind": "codespace", "editable": false }.`);if(s.kind!=="workspace"&&s.kind!=="codespace")throw new Error(`View "${n}": unknown kind "${String(s.kind)}". Use "workspace" or "codespace".`)}for(const n of Object.keys(t))if(!e[n])throw new Error(`mount: a container for "${n}", but no view of that name. Declared views: ${Object.keys(e).join(", ")}.`);if(!Object.keys(e).some(n=>t[n]))throw new Error("MorphicBlocks.mount needs a container for at least one view.")}createHeadlessHost(){const e=document.createElement("div");return e.style.cssText="position:absolute;left:-9999px;top:-9999px;width:800px;height:600px;overflow:hidden;",document.body.appendChild(e),this.headlessWorkspaceHost=e,e}resolveMode(e){return this.mountConfig?e==="toolbox"?this.mountConfig.toolboxMode:this.mountConfig.workspaceElement:"default"}applyView(e,t,n,s){var h,u;if(e.isDeadOrDying())return;const r=this.blockCategoryIndex.get(t.identifier);t.color===void 0&&(r==null?void 0:r.color)!==void 0&&e.setColour(r.color);const c=e.__morphicFieldMemory??(e.__morphicFieldMemory=new Map);for(const[p,m]of ho(e))c.set(p,m);const a=s==="workspace"?ct(t,n,this.elementTypes):ae(t,n,this.elementTypes,((h=this.mountConfig)==null?void 0:h.modes)??[]),l=e.workspace===this.workspace;Ke({block:e,definition:t,view:a,mode:n,context:s,elementTypes:l?this.elementTypes:void 0,codeSettings:this.elementTypes,resolveBlocklyType:p=>X(p,this.definitions)}),this.styleBlock(e,t);const d=he(this.behaviors[t.identifier]);(u=d==null?void 0:d.onViewApplied)==null||u.call(d,e,this.createBehaviorContext(e,t,a.elementName??n,s,n)),uo(e,c)}styleBlock(e,t){const n=this.blockCategoryIndex.get(t.identifier);Yt(e,n==null?void 0:n.token),Kt(e,t.identifier),qt(e),t.color!==void 0&&(e.setColour(t.color),Be(e)&&e.render())}applyWorkspaceContainerClass(){var s,r;if(!this.mountConfig)return;const e=this.mountConfig.workspaceHost,t=this.mountConfig.programView;ke(e,{name:t,element:this.mountConfig.workspaceElement,classNames:["morphic-workspace-root","morphic-context-workspace",...t&&((s=this.mountConfig.viewDeclarations[t])==null?void 0:s.editable)===!1?["morphic-read-only"]:[]]});const n=this.resolveClassNames((r=this.mountConfig.ui)==null?void 0:r.workspaceClassName);this.replaceUserClasses(e,this.appliedWorkspaceClasses,n),this.appliedWorkspaceClasses=n}syncWorkspaceFont(){var e;this.workspace&&((e=this.mountConfig)!=null&&e.workspaceHost)&&this.syncFontOf(this.workspace,this.mountConfig.workspaceHost)}syncFontOf(e,t){if(!this.baseTheme||!this.baseFont)return;const n=wt(t,[[e.getRenderer().getClassName(),this.baseTheme.getClassName()]],this.baseFont);kt(e,this.baseTheme,this.baseFont,n)&&Fe(e)}applyFlyoutClass(){var c,a,l;if(!this.workspace||!this.mountConfig)return;const e=this.resolveClassNames((c=this.mountConfig.ui)==null?void 0:c.toolboxClassName),t=this.workspace.getToolbox(),n=((a=t==null?void 0:t.getDiv)==null?void 0:a.call(t))??null;n&&(qe(n,this.mountConfig.toolboxMode,"toolbox","morphic-toolbox-shell"),this.replaceUserClasses(n,this.appliedToolboxShellClasses,e),this.appliedToolboxShellClasses=e);const s=(l=this.workspace.getFlyout())==null?void 0:l.getWorkspace(),r=s==null?void 0:s.getParentSvg();r&&(qe(r,this.mountConfig.toolboxMode,"toolbox","morphic-toolbox-root"),this.replaceUserClasses(r,this.appliedToolboxFlyoutClasses,e),this.appliedToolboxFlyoutClasses=e)}renderWorkspaceBlocks(){if(!(!this.workspace||!this.mountConfig))for(const e of this.workspace.getAllBlocks(!1)){const t=e,n=this.definitions.get(G(t.type));n&&this.applyView(t,n,this.mountConfig.workspaceElement,"workspace")}}renderFlyoutBlocks(){if(!(!this.flyoutWorkspace||!this.mountConfig)){for(const e of this.flyoutWorkspace.getAllBlocks(!1)){const t=e,n=this.definitions.get(G(t.type));n&&this.applyView(t,n,this.mountConfig.toolboxMode,"toolbox")}this.applyFlyoutClass()}}refreshToolbox(){var e;!this.workspace||!this.toolboxDefinition||(e=this.mountConfig)!=null&&e.canvasToolbox||this.workspace.options.readOnly||this.workspace.updateToolbox(this.toolboxDefinition)}bindFlyoutWorkspace(){var t;if(this.flyoutWorkspace&&(this.flyoutWorkspace.removeChangeListener(this.onFlyoutChange),this.flyoutWorkspace=void 0),!this.workspace)return;const e=(t=this.workspace.getFlyout())==null?void 0:t.getWorkspace();e&&(this.flyoutWorkspace=e,le.set(e,this),this.flyoutWorkspace.addChangeListener(this.onFlyoutChange),this.applyFlyoutClass())}resolveToolboxDefinition(e){if(e.toolbox){const s=this.resolveToolboxKind(e.toolboxLayout),r=s?{...e.toolbox,kind:s}:e.toolbox;return Lt(r,this.definitions)}const t=e.blockly;if(t!=null&&t.toolbox)return t.toolbox;const n=this.resolveToolboxKind(e.toolboxLayout);return Lt({...n!==void 0?{kind:n}:{},blocks:[...this.definitions.keys()]},this.definitions)}createBehaviorContext(e,t,n,s,r){return{Blockly:T,workspace:e.workspace,element:n,...s==="toolbox"?{mode:r}:{},context:s,definition:t}}resolveClassNames(e){return e?(Array.isArray(e)?e.join(" "):e).split(/\s+/).map(n=>n.trim()).filter((n,s,r)=>!!n&&r.indexOf(n)===s):[]}replaceUserClasses(e,t,n){for(const s of t)e.classList.remove(s);for(const s of n)e.classList.add(s)}buildBlockColorMap(){var t;const e=new Map;for(const[n,s]of this.definitions){const r=s.color??((t=this.blockCategoryIndex.get(n))==null?void 0:t.color);r!==void 0&&e.set(n,String(r))}return e}resolveToolboxKind(e){if(e)return e==="category"?"categoryToolbox":"flyoutToolbox"}createCategoryIndex(e,t){const n=new Map,s=(e==null?void 0:e.categories)??[],r=new Map;for(const a of s){const l=H(a.name);if(r.set(a.name.toLowerCase(),{token:l,color:a.color}),a.blocks)for(const d of a.blocks)n.has(d)||n.set(d,{token:l,color:a.color})}const c=t?this.definitions:new Map;for(const a of c.values()){if(!a.category||n.has(a.identifier))continue;const l=r.get(a.category.toLowerCase());l&&n.set(a.identifier,l)}return n}deferApplyView(e,t,n){const s=n==="toolbox"?this.flyoutWorkspace:this.workspace;s&&requestAnimationFrame(()=>{const r=s.getBlockById(e);if(!r)return;const c=this.definitions.get(G(r.type));c&&this.applyView(r,c,t,n)})}}function On(i,o,e){return Math.min(Math.max(i,o),e)}function Dn(i,o){const{target:e,axis:t,invert:n=!1,onResize:s}=o,r=o.min??0,c=o.max??Number.POSITIVE_INFINITY,a=o.step??10,l=()=>{const k=e.getBoundingClientRect();return t==="x"?k.width:k.height},d=k=>i.setAttribute("aria-valuenow",String(Math.round(k)));i.setAttribute("role","separator"),i.setAttribute("aria-orientation",t==="x"?"vertical":"horizontal"),i.setAttribute("aria-valuemin",String(r)),Number.isFinite(c)&&i.setAttribute("aria-valuemax",String(c)),e.id&&!i.hasAttribute("aria-controls")&&i.setAttribute("aria-controls",e.id),d(l());const h=k=>{const B=On(k,r,c);e.style.flexBasis=`${B}px`,d(B),s==null||s(B)},u=k=>{if(k.button!==0)return;k.preventDefault();const B=l(),L=t==="x"?k.clientX:k.clientY,E=document.body.style.userSelect,x=document.body.style.cursor;document.body.style.userSelect="none",document.body.style.cursor=t==="x"?"col-resize":"row-resize",i.setPointerCapture(k.pointerId);const g=f=>{const S=(t==="x"?f.clientX:f.clientY)-L;h(B+(n?-S:S))},C=()=>{i.removeEventListener("pointermove",g),i.removeEventListener("pointerup",C),i.removeEventListener("lostpointercapture",C),document.body.style.userSelect=E,document.body.style.cursor=x};i.addEventListener("pointermove",g),i.addEventListener("pointerup",C),i.addEventListener("lostpointercapture",C)},[p,m]=t==="x"?["ArrowLeft","ArrowRight"]:["ArrowUp","ArrowDown"],w=k=>{const B=k.shiftKey?a*5:a;if(k.key===p||k.key===m){const L=k.key===m?B:-B;h(l()+(n?-L:L))}else if(k.key==="Home")h(r);else if(k.key==="End"&&Number.isFinite(c))h(c);else return;k.preventDefault()};i.hasAttribute("tabindex")||(i.tabIndex=0);const b=()=>d(l());return i.addEventListener("pointerdown",u),i.addEventListener("keydown",w),i.addEventListener("focus",b),{dispose:()=>{i.removeEventListener("pointerdown",u),i.removeEventListener("keydown",w),i.removeEventListener("focus",b)}}}const Nn=Object.freeze(Object.defineProperty({__proto__:null,default:".morphic-placeholder-default,.morphic-placeholder-set{border-radius:2px;padding:0 .2em}.morphic-placeholder-default{font-style:italic;opacity:.55}"},Symbol.toStringTag,{value:"Module"})),Vn=Object.freeze(Object.defineProperty({__proto__:null,default:".morphic-toolbar{display:flex;align-items:center;gap:var(--morphic-toolbar-gap, .5em);padding:var(--morphic-toolbar-padding, 4px 8px);background:var(--morphic-toolbar-bg, inherit);color:var(--morphic-toolbar-fg, inherit);font:var(--morphic-toolbar-font, inherit);border-bottom:var(--morphic-toolbar-border, 1px solid rgba(127, 127, 127, .2));box-sizing:border-box}.morphic-toolbar-left,.morphic-toolbar-right{display:flex;align-items:center;gap:var(--morphic-toolbar-gap, .5em)}.morphic-toolbar-right{margin-left:auto}.morphic-toolbar-item{display:inline-flex;align-items:center;gap:4px;background:var(--morphic-toolbar-item-bg, transparent);color:inherit;border:var(--morphic-toolbar-item-border, none);padding:var(--morphic-toolbar-item-padding, 2px 6px);border-radius:var(--morphic-toolbar-item-radius, 3px);cursor:pointer;font:inherit;line-height:1}.morphic-toolbar-item:hover:not(:disabled){background:var(--morphic-toolbar-item-hover-bg, rgba(127, 127, 127, .15))}.morphic-toolbar-item:disabled{opacity:.4;cursor:default}.morphic-toolbar-icon{display:inline-flex}.morphic-toolbar-label{opacity:.7;font-size:.9em}.morphic-toolbox-header{display:flex;align-items:center;padding:4px 6px 8px}.morphic-toolbar-badge{font-size:.85em;opacity:.6;padding:1px 6px;border:1px solid currentColor;border-radius:3px}.morphic-toolbar-spacer{flex:1}"},Symbol.toStringTag,{value:"Module"}));P.MorphicBlocks=An,P.MorphicToolboxCanvas=xt,P.makeResizable=Dn,P.renderToolbar=It,P.toCleanId=G,P.toolbarItems=N,P.validateDefinitions=vt,Object.defineProperty(P,Symbol.toStringTag,{value:"Module"})}));