morphic-blocks 0.0.1 → 0.2.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.
@@ -0,0 +1,30 @@
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 t;return this.previewWorkspace?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),this.previewWorkspace=L.inject(this.previewContainer,{scrollbars:!1}),(t=this.onPreviewWorkspace)==null||t.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"})}));
@@ -0,0 +1,4 @@
1
+ const o = ".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}";
2
+ export {
3
+ o as default
4
+ };
package/package.json CHANGED
@@ -1,8 +1,61 @@
1
1
  {
2
2
  "name": "morphic-blocks",
3
- "version": "0.0.1",
4
- "description": "Placeholder — work in progress, not yet ready for use.",
5
- "license": "MIT",
6
- "keywords": ["blockly", "block-based", "programming-education"],
7
- "homepage": "https://morphicblocks.com"
3
+ "version": "0.2.0",
4
+ "description": "Mode-driven wrapper framework around Google Blockly",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/morphicblocks/morphic-blocks.git",
8
+ "directory": "packages/morphic-blocks"
9
+ },
10
+ "homepage": "https://morphicblocks.com",
11
+ "bugs": "https://github.com/morphicblocks/morphic-blocks/issues",
12
+ "type": "module",
13
+ "main": "./dist/morphic-blocks.umd.cjs",
14
+ "module": "./dist/morphic-blocks.js",
15
+ "types": "./dist/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/morphic-blocks.js",
20
+ "require": "./dist/morphic-blocks.umd.cjs"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "definitions.schema.json",
26
+ "NOTICE"
27
+ ],
28
+ "scripts": {
29
+ "build": "vite build && tsc -p tsconfig.build.json",
30
+ "test": "vitest run"
31
+ },
32
+ "keywords": [
33
+ "blockly",
34
+ "framework",
35
+ "visual-programming",
36
+ "morphic"
37
+ ],
38
+ "license": "Apache-2.0",
39
+ "dependencies": {
40
+ "blockly": "^11.2.2"
41
+ },
42
+ "peerDependencies": {
43
+ "@codemirror/lang-javascript": "^6.0.0",
44
+ "@codemirror/state": "^6.0.0",
45
+ "@codemirror/view": "^6.0.0"
46
+ },
47
+ "peerDependenciesMeta": {
48
+ "@codemirror/lang-javascript": { "optional": true },
49
+ "@codemirror/state": { "optional": true },
50
+ "@codemirror/view": { "optional": true }
51
+ },
52
+ "devDependencies": {
53
+ "@codemirror/lang-javascript": "^6.2.3",
54
+ "@codemirror/state": "^6.5.2",
55
+ "@codemirror/view": "^6.36.5",
56
+ "jsdom": "25.0.1",
57
+ "typescript": "^5.8.2",
58
+ "vite": "^6.2.0",
59
+ "vitest": "^5.0.1"
60
+ }
8
61
  }