morphic-blocks 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +88 -53
- package/definitions.schema.json +63 -14
- package/dist/cli.js +36 -0
- package/dist/index.d.ts +2 -1
- package/dist/morphic/MorphicBlocks.d.ts +106 -9
- package/dist/morphic/block-view.d.ts +18 -0
- package/dist/morphic/code-editor.d.ts +12 -4
- package/dist/morphic/element-types.d.ts +11 -3
- package/dist/morphic/styles.d.ts +21 -3
- package/dist/morphic/syntax-highlight.d.ts +13 -0
- package/dist/morphic/template-codegen.d.ts +5 -1
- package/dist/morphic/toolbar.d.ts +5 -0
- package/dist/morphic/toolbox-canvas.d.ts +56 -1
- package/dist/morphic/types.d.ts +171 -31
- package/dist/morphic/validate-definitions.d.ts +3 -3
- package/dist/morphic/value-format.d.ts +8 -0
- package/dist/morphic-blocks.js +3014 -2224
- package/dist/morphic-blocks.umd.cjs +34 -30
- package/package.json +20 -7
|
@@ -1,30 +1,34 @@
|
|
|
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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function se(n){return n.replace(/"/g,""").replace(/'/g,"'")}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
|
-
|
|
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
|
-
${
|
|
5
|
-
`:
|
|
6
|
-
`)?`${
|
|
7
|
-
`:`${
|
|
8
|
-
`:""}function
|
|
9
|
-
`),e=[],
|
|
10
|
-
`),metadata:
|
|
11
|
-
`)){
|
|
12
|
-
`);
|
|
13
|
-
`+
|
|
14
|
-
`),
|
|
15
|
-
`),
|
|
16
|
-
`)?Math.max(
|
|
17
|
-
`;)
|
|
18
|
-
`)+1;e.indent=((
|
|
19
|
-
`)?Math.max($,
|
|
20
|
-
`)?Math.max(
|
|
21
|
-
`;)
|
|
22
|
-
`&&
|
|
23
|
-
${
|
|
24
|
-
${
|
|
25
|
-
${
|
|
26
|
-
`))}ensureStyles(t,e){this.ensureStyleBundle(t,"base");for(const o of e)this.ensureStyleBundle(o,`mode:${o.mode}`)}async ensureToolbarStyles(){const t=await Promise.resolve().then(()=>Jo);fe("toolbar",t.default)}ensureCategoryStyles(t){for(const e of t){if(!e.color)continue;const o=H(e.name);fe(`category:${o}`,`.morphic-category-${o} { --morphic-category-color: ${e.color}; }`)}}validateModeCoverage(t,e){const o=new Set(t.map(s=>s.mode)),i=e.filter(s=>!o.has(s));i.length>0&&console.warn(`[MorphicBlocks] Modes without explicit CSS definition: ${i.join(", ")}.`)}ensureStyleBundle(t,e){t&&(t.href&&Bo(e,t.href),t.cssText&&fe(e,t.cssText))}}function fe(n,t){for(const o of Array.from(document.head.querySelectorAll("style[data-morphic-source]")))if(o.dataset.morphicSource===n&&o.textContent===t)return;const e=document.createElement("style");e.dataset.morphicSource=n,e.textContent=t,document.head.appendChild(e)}function Bo(n,t){for(const o of Array.from(document.head.querySelectorAll("link[data-morphic-source]")))if(o.getAttribute("href")===t)return;const e=document.createElement("link");e.rel="stylesheet",e.href=t,e.dataset.morphicSource=n,document.head.appendChild(e)}const ee="morphic/block-type";class ot{constructor(t){g(this,"container");g(this,"workspaceContainer");g(this,"workspace");g(this,"definitions");g(this,"blockColors");g(this,"behaviors");g(this,"elementTypes");g(this,"options");g(this,"modes");g(this,"currentMode");g(this,"renderOverride");g(this,"previewWorkspace");g(this,"onPreviewWorkspace");g(this,"previewContainer");g(this,"previewBase");g(this,"onDragOver");g(this,"onDrop");this.container=t.container,this.workspaceContainer=t.workspaceContainer,this.workspace=t.workspace,this.onPreviewWorkspace=t.onPreviewWorkspace,this.definitions=t.definitions,this.blockColors=t.blockColors,this.behaviors=t.behaviors,this.elementTypes=t.elementTypes??{},this.currentMode=t.mode,this.renderOverride=t.render,this.modes=t.modes??[],this.options=t.options??{},this.onDragOver=e=>{var o;(o=e.dataTransfer)!=null&&o.types.includes(ee)&&e.preventDefault()},this.onDrop=e=>{var i;const o=(i=e.dataTransfer)==null?void 0:i.getData(ee);o&&(e.preventDefault(),this.createBlockAtPosition(o,e.clientX,e.clientY))},this.workspaceContainer.addEventListener("dragover",this.onDragOver),this.workspaceContainer.addEventListener("drop",this.onDrop),this.render()}rerender(t,e){this.currentMode=t,this.renderOverride=e,this.render()}dispose(){var t;this.workspaceContainer.removeEventListener("dragover",this.onDragOver),this.workspaceContainer.removeEventListener("drop",this.onDrop),this.container.innerHTML="",this.previewWorkspace&&(this.previewWorkspace.dispose(),this.previewWorkspace=void 0,this.previewBase=void 0),(t=this.previewContainer)!=null&&t.parentNode&&(this.previewContainer.parentNode.removeChild(this.previewContainer),this.previewContainer=void 0)}render(){if(this.container.innerHTML="",this.options.modeLabel!==!1){const i=document.createElement("div");i.className="morphic-toolbox-header";const s=document.createElement("span");s.className="morphic-toolbar-label",s.textContent=`Mode: ${this.currentMode}`,i.appendChild(s),this.container.appendChild(i)}const t=this.resolveBlockIds(),e=this.options.categories??[];if(e.length===0){for(const i of t){const s=this.definitions.get(i);s&&this.container.appendChild(this.createTile(s))}return}const o=new Set;for(const i of e){const s=this.resolveCategoryBlockIds(i,t);if(s.length===0)continue;const r=document.createElement("div");r.setAttribute("data-category",H(i.name)),i.color&&r.style.setProperty("--morphic-category-color",i.color);for(const c of s){const a=this.definitions.get(c);a&&(r.appendChild(this.createTile(a)),o.add(c))}this.container.appendChild(r)}for(const i of t)if(!o.has(i)){const s=this.definitions.get(i);s&&this.container.appendChild(this.createTile(s))}}createTile(t){var d;const e=H(this.currentMode),o=H(t.identifier),i=this.blockColors.get(t.identifier),s=document.createElement("div");s.setAttribute("draggable","true"),s.setAttribute("data-block-type",t.identifier),s.className=`morphic-block morphic-mode-${e} morphic-block-${o}`,i&&s.style.setProperty("--morphic-block-color",i);const r=this.modes.find(u=>u.name===this.currentMode),c=(r==null?void 0:r.elements)??[],a=Object.entries(t.elements),l=[...c.map(u=>a.find(([w])=>w===u)).filter(u=>u!==void 0),...a.filter(([u])=>!c.includes(u))];for(const[u,w]of l){const v=document.createElement("div");v.className=`morphic-element-${H(u)}`;const C=this.elementTypes[u],E=U(C),k=E==="code",m=E==="image",p=((d=this.renderOverride)==null?void 0:d[u])??(k?"block":"text"),y=m?wt(w,ft(C)):w;if(k&&p==="block"){this.syncPreviewFont(u);const S=this.createBlockPreviewSvg(t,this.currentMode);S?v.appendChild(S):v.innerHTML=Me(q(y))}else v.innerHTML=Me(q(y));s.appendChild(v)}return s.addEventListener("dragstart",u=>{var w;(w=u.dataTransfer)==null||w.setData(ee,t.identifier)}),s}ensurePreviewWorkspace(){var e;if(this.previewWorkspace)return this.previewWorkspace;this.previewContainer=document.createElement("div"),this.previewContainer.style.cssText="position:absolute;left:-9999px;top:-9999px;width:800px;height:600px;overflow:hidden;",document.body.appendChild(this.previewContainer);const t=this.workspace.options;return this.previewWorkspace=L.inject(this.previewContainer,{scrollbars:!1,media:t.pathToMedia,sounds:!1,renderer:t.renderer,rendererOverrides:t.rendererOverrides??void 0,theme:t.theme,rtl:t.RTL}),(e=this.onPreviewWorkspace)==null||e.call(this,this.previewWorkspace),this.previewWorkspace}syncPreviewFont(t){const e=this.ensurePreviewWorkspace();this.previewBase??(this.previewBase={theme:e.getTheme(),font:Xe(e)});const o=Ke(this.container,[["morphic-block",`morphic-mode-${H(this.currentMode)}`],[`morphic-element-${H(t)}`]],this.previewBase.font);Ye(e,this.previewBase.theme,this.previewBase.font,o)}createBlockPreviewSvg(t,e){var o;try{const i=this.ensurePreviewWorkspace(),s=i.newBlock(G(t.identifier,this.definitions)),r=this.blockColors.get(t.identifier);r&&s.setColour(r);const c=Ee(t,e,this.elementTypes,this.modes);De({block:s,definition:t,view:c,mode:"block",context:"toolbox"});const a=te(this.behaviors[t.identifier]);(o=a==null?void 0:a.onViewApplied)==null||o.call(a,s,{Blockly:L,workspace:i,mode:e,context:"toolbox",definition:t}),s.initSvg(),s.render();const l=s.getSvgRoot();if(!l)return s.dispose(!1),null;const d=l.getBBox(),u=l.cloneNode(!0),w=4,v=document.createElementNS("http://www.w3.org/2000/svg","svg");return v.setAttribute("width",String(Math.ceil(d.width+w*2))),v.setAttribute("height",String(Math.ceil(d.height+w*2))),v.setAttribute("viewBox",`${d.x-w} ${d.y-w} ${d.width+w*2} ${d.height+w*2}`),v.appendChild(u),s.dispose(!1),v}catch{return null}}createBlockAtPosition(t,e,o){const i=this.workspace,s=i.getInjectionDiv().getBoundingClientRect(),r=(e-s.left-i.scrollX)/i.scale,c=(o-s.top-i.scrollY)/i.scale,a=i.newBlock(G(t,this.definitions));a.initSvg(),a.render(),a.moveTo(new L.utils.Coordinate(r,c))}resolveBlockIds(){return this.options.blocks??[...this.definitions.keys()]}resolveCategoryBlockIds(t,e){return t.blocks&&t.blocks.length>0?t.blocks.filter(o=>e.includes(o)):e.filter(o=>{var i,s;return((s=(i=this.definitions.get(o))==null?void 0:i.category)==null?void 0:s.toLowerCase())===t.name.toLowerCase()})}}function Te(n,t){var o;if(n.blocks&&n.blocks.length>0)return n.blocks;const e=[];for(const i of t.values())((o=i.category)==null?void 0:o.toLowerCase())===n.name.toLowerCase()&&e.push(i.identifier);return e}function nt(n,t){var i,s,r;if((n.kind??((i=n.categories)!=null&&i.length?"categoryToolbox":"flyoutToolbox"))==="categoryToolbox")return{kind:"categoryToolbox",contents:(n.categories??[]).map(a=>({kind:"category",name:a.name,colour:a.color,contents:Te(a,t).map(l=>({kind:"block",type:G(l,t)}))}))};if((s=n.categories)!=null&&s.length){const c=n.categories,a=[];return c.forEach((d,u)=>{const w=H(d.name);a.push({kind:"label",id:`morphic-category-${w}`,text:d.name,"web-class":`morphic-flyout-category-label morphic-category-${w}`});for(const v of it(Te(d,t)))a.push({kind:"block",type:G(v,t)});u<c.length-1&&a.push({kind:"sep",gap:14})}),{kind:"flyoutToolbox",contents:a}}return{kind:"flyoutToolbox",contents:(n.blocks??it(((r=n.categories)==null?void 0:r.flatMap(c=>Te(c,t)))??[...t.keys()])).map(c=>({kind:"block",type:G(c,t)}))}}function it(n){return n.filter((t,e,o)=>o.indexOf(t)===e)}const Mo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="4" y="4" width="9" height="10" rx="1.5"/><path d="M3 11V3a1 1 0 0 1 1-1h7"/></svg>',Io='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 3h6v2H5z"/><path d="M4 3H3a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V4a1 1 0 0 0-1-1h-1"/></svg>',Do='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8h7a3 3 0 0 1 0 6H6"/><polyline points="5 5 2 8 5 11"/></svg>',Ao='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M13 8H6a3 3 0 0 0 0 6h4"/><polyline points="11 5 14 8 11 11"/></svg>',Oo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 4 13 4"/><path d="M5 4V3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v1"/><path d="M4 4l1 9a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1l1-9"/></svg>',No='<svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor"><polygon points="4,3 13,8 4,13"/></svg>',$o='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="7" r="4"/><line x1="10" y1="10" x2="14" y2="14"/><line x1="5" y1="7" x2="9" y2="7"/><line x1="7" y1="5" x2="7" y2="9"/></svg>',Po='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="7" r="4"/><line x1="10" y1="10" x2="14" y2="14"/><line x1="5" y1="7" x2="9" y2="7"/></svg>',Ho='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 3 3 6 3"/><polyline points="13 6 13 3 10 3"/><polyline points="3 10 3 13 6 13"/><polyline points="13 10 13 13 10 13"/></svg>',Fo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 2h8l2 2v10H3z"/><rect x="5" y="2" width="6" height="4"/><rect x="5" y="9" width="6" height="4"/></svg>',Ro='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8v5a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V8"/><polyline points="5 5 8 2 11 5"/><line x1="8" y1="2" x2="8" y2="10"/></svg>',_o='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8a5 5 0 1 0 1.5-3.5"/><polyline points="3 2 3 5 6 5"/></svg>',Vo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2 8s2-4 6-4 6 4 6 4-2 4-6 4-6-4-6-4z"/><circle cx="8" cy="8" r="1.5"/></svg>',O={modeLabel(){return{id:"mode-label",render:n=>{const t=document.createElement("span");return t.className="morphic-toolbar-label",t.textContent=zo(n),t}}},copy(){return{id:"copy",label:"Copy",title:"Copy block",icon:Mo,onClick:n=>{n.engine.copyActiveBlock(n.pane)}}},paste(){return{id:"paste",label:"Paste",title:"Paste block",icon:Io,disabled:n=>!n.engine.hasClipboardContents(),onClick:n=>{n.engine.pasteActiveBlock(n.pane)}}},undo(){return{id:"undo",label:"Undo",title:"Undo (block model)",icon:Do,onClick:n=>{var t;(t=n.engine.getWorkspace())==null||t.undo(!1)},disabled:n=>{var t;return!((t=n.engine.getWorkspace())!=null&&t.getUndoStack().length)}}},redo(){return{id:"redo",label:"Redo",title:"Redo (block model)",icon:Ao,onClick:n=>{var t;(t=n.engine.getWorkspace())==null||t.undo(!0)},disabled:n=>{var t;return!((t=n.engine.getWorkspace())!=null&&t.getRedoStack().length)}}},zoomIn(){return{id:"zoom-in",label:"Zoom in",title:"Zoom in",icon:$o,onClick:n=>n.engine.zoomPane(n.pane,"in")}},zoomOut(){return{id:"zoom-out",label:"Zoom out",title:"Zoom out",icon:Po,onClick:n=>n.engine.zoomPane(n.pane,"out")}},zoomFit(){return{id:"zoom-fit",label:"Fit",title:"Reset zoom",icon:Ho,onClick:n=>n.engine.zoomPane(n.pane,"fit")}},clear(){return{id:"clear",label:"Clear",title:"Clear workspace",icon:Oo,onClick:n=>{var t;window.confirm("Clear workspace? This cannot be undone.")&&((t=n.engine.getWorkspace())==null||t.clear())}}},runCode(){return{id:"run",label:"Run",title:"Run generated code",icon:No,onClick:n=>{n.engine.runJavaScript()}}},save(){return{id:"save",label:"Save",title:"Save workspace as JSON",icon:Fo,onClick:n=>{if(!n.engine.getWorkspace())return;const e=n.engine.serializeWorkspace(),o=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),i=URL.createObjectURL(o),s=document.createElement("a");s.href=i,s.download="workspace.json",s.click(),URL.revokeObjectURL(i)}}},load(){return{id:"load",label:"Load",title:"Load workspace JSON",icon:Ro,onClick:n=>{const t=document.createElement("input");t.type="file",t.accept="application/json",t.addEventListener("change",async()=>{var o;const e=(o=t.files)==null?void 0:o[0];if(e)try{const i=await e.text(),s=JSON.parse(i);n.engine.loadWorkspace(s)}catch(i){window.alert(`Load failed: ${i instanceof Error?i.message:String(i)}`)}}),t.click()}}},reset(){return{id:"reset",label:"Reset",title:"Reset workspace",icon:_o,onClick:n=>{var t;window.confirm("Reset workspace to empty? This cannot be undone.")&&((t=n.engine.getWorkspace())==null||t.clear())}}},togglePreview(){return{id:"toggle-preview",label:"Preview",title:"Toggle preview pane",icon:Vo,onClick:()=>{const n=document.querySelector("[data-morphic-preview-host]");n&&(n.hidden=!n.hidden)}}},readOnlyBadge(){return{id:"read-only",align:"right",render:()=>{const n=document.createElement("span");return n.className="morphic-toolbar-badge",n.textContent="read-only",n}}},spacer(){return{id:"spacer",render:()=>{const n=document.createElement("span");return n.className="morphic-toolbar-spacer",n}}},defaultsFor(n){switch(n){case"workspace":case"codespace":return[O.modeLabel(),O.spacer(),O.undo(),O.redo(),O.copy(),O.paste(),O.zoomIn(),O.zoomOut(),O.zoomFit(),O.clear()];case"preview":return[O.modeLabel(),O.spacer(),O.copy(),O.zoomIn(),O.zoomOut(),O.zoomFit(),O.readOnlyBadge()]}}};function zo(n){const t=n.engine,e=n.pane==="workspace"?t.getWorkspaceMode():n.pane==="codespace"?t.getCodespaceMode():t.getPreviewMode();return e?`Mode: ${e}`:""}function st(n,t,e){const o=t.items??O.defaultsFor(t.pane),i=t.display??"icon";n.classList.add("morphic-toolbar"),n.setAttribute("data-morphic-pane",t.pane);const s=document.createElement("div");s.className="morphic-toolbar-left";const r=document.createElement("div");r.className="morphic-toolbar-right";const c=()=>{s.replaceChildren(),r.replaceChildren();let a=!1;for(const l of o){if(l.visible&&!l.visible(e))continue;if(l.id==="spacer"){a=!0;continue}(l.align==="right"||a&&l.align!=="left"?r:s).appendChild(Wo(l,i,e))}};return n.replaceChildren(s,r),c(),{refresh:c,pane:t.pane,dispose:()=>n.replaceChildren()}}function Wo(n,t,e){if(n.render){const i=n.render(e);if(typeof i=="string"){const s=document.createElement("span");return s.className="morphic-toolbar-item",s.dataset.toolbarId=n.id,s.textContent=i,s}return i.classList.add("morphic-toolbar-item"),i.dataset.toolbarId=n.id,i}const o=document.createElement("button");return o.className="morphic-toolbar-item",o.dataset.toolbarId=n.id,o.type="button",n.title&&(o.title=n.title),jo(o,n,t),n.disabled&&n.disabled(e)&&(o.disabled=!0),n.onClick&&o.addEventListener("click",()=>n.onClick(e)),o}function jo(n,t,e){const o=e!=="label"&&!!t.icon,i=e!=="icon"&&!!t.label,s=o||e==="icon"&&!t.label,r=i||e==="label"&&!t.icon;if(s&&t.icon){const c=document.createElement("span");c.className="morphic-toolbar-icon",c.innerHTML=t.icon,n.appendChild(c)}if(r&&t.label){const c=document.createElement("span");c.className="morphic-toolbar-text",c.textContent=t.label,n.appendChild(c)}!n.title&&t.label&&(n.title=t.label),!n.childNodes.length&&t.label&&(n.textContent=t.label)}function rt(n,t){return t.includes("{")?{mode:n,cssText:t}:{mode:n,href:t}}function Uo(n){const t=[];for(const[e,o]of Object.entries(n)){const s=(e.split("/").pop()??e).replace(/\.css$/i,""),r=typeof o=="string"?o:typeof o=="object"&&o!==null&&"default"in o?String(o.default):void 0;r&&t.push(rt(s,r))}return t}function Le(n){return typeof n=="string"?{mode:n}:{mode:n.mode,render:n.render}}const me=new WeakMap,ge=new Map;class Go extends EventTarget{constructor(e,o={}){super();g(this,"definitions");g(this,"behaviors");g(this,"elementTypes");g(this,"styles",new Lo);g(this,"registeredBlockTypes",new Set);g(this,"toolbars",new Set);g(this,"toolbarsBlocklyListener");g(this,"lastCopyData");g(this,"mountConfig");g(this,"workspace");g(this,"flyoutWorkspace");g(this,"toolboxCanvas");g(this,"codeEditor");g(this,"codespace");g(this,"previewEditor");g(this,"selectionSync");g(this,"toolboxDefinition");g(this,"blockCategoryIndex",new Map);g(this,"appliedWorkspaceClasses",[]);g(this,"appliedToolboxFlyoutClasses",[]);g(this,"appliedToolboxShellClasses",[]);g(this,"headlessWorkspaceHost");g(this,"codespaceDropTeardown");g(this,"workspaceResizeObserver");g(this,"activePreset");g(this,"baseTheme");g(this,"baseFont");g(this,"mountGeneration",0);g(this,"selectionSyncOptions");g(this,"formatModes");g(this,"formatPresets");g(this,"formatHighlighting");g(this,"formatCategories");g(this,"onWorkspaceChange",e=>{if(!this.workspace||!this.mountConfig||e.workspaceId!==this.workspace.id||e.type!==L.Events.BLOCK_CREATE)return;const o=e;for(const i of o.ids??[]){const s=this.workspace.getBlockById(i);if(!s)continue;const r=this.definitions.get(W(s.type));r&&(this.applyView(s,r,this.mountConfig.workspaceMode,"workspace"),s.getSvgRoot()||this.deferApplyView(i,this.mountConfig.workspaceMode,"workspace"))}});g(this,"onFlyoutChange",e=>{if(!this.flyoutWorkspace||!this.mountConfig||e.workspaceId!==this.flyoutWorkspace.id||e.type!==L.Events.BLOCK_CREATE)return;const o=e;for(const i of o.ids??[]){const s=this.flyoutWorkspace.getBlockById(i);if(!s)continue;const r=this.definitions.get(W(s.type));r&&(this.applyView(s,r,this.mountConfig.toolboxMode,"toolbox"),s.getSvgRoot()||this.deferApplyView(i,this.mountConfig.toolboxMode,"toolbox"))}});g(this,"onStylesLoaded",()=>{var e;!this.workspace||!this.mountConfig||(this.syncWorkspaceFont(),Je(this.workspace),(e=this.toolboxCanvas)==null||e.rerender(this.mountConfig.toolboxMode,this.mountConfig.toolboxRender))});const i=e;this.definitions=wo(ko(vo(i.blocks,i.elementTypes??{}))),this.behaviors=o,this.elementTypes=i.elementTypes??{},this.formatModes=i.modes,this.formatPresets=i.presets,this.formatHighlighting=i.highlighting,this.formatCategories=i.categories}mount(e){var p,y,S,h,f,x,B;this.dispose();const o={...e,modes:e.modes??this.formatModes,presets:e.presets??this.formatPresets,highlighting:e.highlighting??this.formatHighlighting,toolbox:e.toolbox||this.formatCategories?{...e.toolbox,categories:((p=e.toolbox)==null?void 0:p.categories)??this.formatCategories}:void 0},i=o.modesFolder?Uo(o.modesFolder):[],s=[...i,...Object.entries(o.modeStyles??{}).filter(([b])=>!i.some(I=>I.mode===b)).map(([b,I])=>rt(b,I))];this.validateDefinitions(o),this.validatePresets(o);const r=(y=o.presets)!=null&&y.length?o.presets.find(b=>b.name===o.preset)??o.presets[0]:void 0;if(o.preset&&!r)throw new Error(`MorphicBlocks.mount: unknown preset "${o.preset}".`);const c=(o.modes??[]).map(b=>b.name),a=c[0]??((S=s[0])==null?void 0:S.mode)??"default",l=r?Le(r.toolbox):void 0,d=r?r.workspace??r.codespace??a:a,u=l?l.mode:a,w=l==null?void 0:l.render,v=r==null?void 0:r.codespace,C=r==null?void 0:r.preview;this.validateContainers(o);const E=o.workspaceContainer??this.createHeadlessHost(),k={...o,modeStyles:s,workspaceMode:d,toolboxMode:u,toolboxRender:w,codespaceMode:v,previewMode:C,workspaceHost:E,canvasToolbox:o.canvasToolbox??!!o.toolboxContainer};this.mountConfig=k,this.styles.validateModeCoverage(s,c),(h=k.modes)!=null&&h.length&&this.styles.ensureModeVisibilityStyles(k.modes),this.styles.ensureStyles(k.baseStyle,s);for(const b of Array.from(document.head.querySelectorAll('link[data-morphic-source^="mode:"]')))b.sheet||b.addEventListener("load",this.onStylesLoaded,{once:!0});(f=document.fonts)==null||f.addEventListener("loadingdone",this.onStylesLoaded),this.blockCategoryIndex=this.createCategoryIndex(k.toolbox,k),this.styles.ensureCategoryStyles(((x=k.toolbox)==null?void 0:x.categories)??[]),this.registerBlocks(),this.toolboxDefinition=this.resolveToolboxDefinition(k);const m=k.blockly??{};if(this.workspace=L.inject(k.workspaceHost,{...m,...k.canvasToolbox?{}:{toolbox:this.toolboxDefinition}}),this.workspace.addChangeListener(this.onWorkspaceChange),me.set(this.workspace,this),this.baseTheme=this.workspace.getTheme(),this.baseFont=Xe(this.workspace),o.workspaceContainer&&typeof ResizeObserver<"u"){const b=this.workspace;this.workspaceResizeObserver=new ResizeObserver(()=>L.svgResize(b)),this.workspaceResizeObserver.observe(o.workspaceContainer)}return this.applyWorkspaceContainerClass(),this.syncWorkspaceFont(),this.refreshToolbox(),this.bindFlyoutWorkspace(),this.renderWorkspaceBlocks(),this.renderFlyoutBlocks(),o.toolboxContainer&&this.mountToolbox(o.toolboxContainer),this.activePreset=r,r&&((B=k.onPresetApplied)==null||B.call(k,r)),this.mountViews(o,++this.mountGeneration)}async mountViews(e,o){const i=e.editorTheme?{theme:e.editorTheme}:void 0,s=e.previewTheme??e.editorTheme,r=[];if(e.codespaceContainer&&r.push(this.mountCodespace(i)),e.previewContainer&&r.push(this.mountPreview(e.previewContainer,s?{theme:s}:void 0)),e.codeEditorContainer&&r.push(this.mountCodeEditor(e.codeEditorContainer,i).then(()=>{o===this.mountGeneration&&this.hideCodeEditor()})),await Promise.all(r),o!==this.mountGeneration||!this.workspace)return;for(const[l,d]of Object.entries(e.toolbarContainers??{}))d&&this.mountToolbar(d,{pane:l});const c=(e.workspaceContainer?1:0)+r.length,a=e.selectionSync??c>1;a&&r.length>0&&this.enableSelectionSync(typeof a=="object"?a:void 0)}getPresets(){var e;return[...((e=this.mountConfig)==null?void 0:e.presets)??[]]}getActivePreset(){return this.activePreset}applyPreset(e){var r,c;if(!this.mountConfig||!this.workspace)throw new Error("MorphicBlocks must be mounted before applyPreset can be used.");const o=this.mountConfig.presets??[],i=typeof e=="number"?o[e]:o.find(a=>a.name===e);if(!i)throw new Error(`applyPreset: unknown preset "${e}".`);const s=Le(i.toolbox);return this.setModes({toolboxMode:s.mode,toolboxRender:s.render??null,workspaceMode:i.workspace??i.codespace,codespaceMode:i.codespace??null,previewMode:i.preview??null}),this.activePreset=i,(c=(r=this.mountConfig).onPresetApplied)==null||c.call(r,i),i}validateDefinitions(e){var s;const{errors:o,warnings:i}=qe({definitions:this.definitions,elementTypes:this.elementTypes,behaviors:this.behaviors,modes:e.modes,presets:e.presets,highlighting:e.highlighting,categories:(s=e.toolbox)==null?void 0:s.categories});if(i.length>0&&console.warn(`[MorphicBlocks] Definition warnings:
|
|
27
|
-
-
|
|
28
|
-
|
|
29
|
-
-
|
|
30
|
-
- `)}`)}validatePresets(e){const o=e.presets??[];if(o.length===0)return;const i=e.modes??[],s=new Map(i.map(c=>[c.name,c])),r=new Set;for(const c of o){if(r.has(c.name))throw new Error(`Preset "${c.name}" is defined more than once.`);if(r.add(c.name),!c.workspace&&!c.codespace)throw new Error(`Preset "${c.name}": at least one of workspace or codespace must be set.`);if(c.codespace&&!e.codespaceContainer)throw new Error(`Preset "${c.name}" uses a codespace but no codespaceContainer was provided.`);const a=Le(c.toolbox),l=[["toolbox",a.mode],["workspace",c.workspace],["codespace",c.codespace],["preview",c.preview]];for(const[d,u]of l){if(u===void 0)continue;const w=s.get(u);if(!w)throw new Error(`Preset "${c.name}": unknown mode "${u}" for ${d}.`);if((d==="codespace"||d==="preview")&&de(w,this.elementTypes)===void 0)throw new Error(`Preset "${c.name}": mode "${u}" has no code element to render in the ${d}.`)}for(const d of Object.values(a.render??{}))if(d!=="block"&&d!=="text")throw new Error(`Preset "${c.name}": toolbox render values must be "block" or "text".`)}}dispose(){var e,o,i,s,r,c,a,l;for(const[d,u]of ge)u===this&&ge.delete(d);(e=this.workspaceResizeObserver)==null||e.disconnect(),this.workspaceResizeObserver=void 0,(o=document.fonts)==null||o.removeEventListener("loadingdone",this.onStylesLoaded),this.activePreset=void 0,(i=this.selectionSync)==null||i.disable(),this.selectionSync=void 0,(s=this.codeEditor)==null||s.dispose(),this.codeEditor=void 0,(r=this.codespaceDropTeardown)==null||r.call(this),this.codespaceDropTeardown=void 0,(c=this.codespace)==null||c.dispose(),this.codespace=void 0,(a=this.previewEditor)==null||a.dispose(),this.previewEditor=void 0,(l=this.toolboxCanvas)==null||l.dispose(),this.toolboxCanvas=void 0;for(const d of[...this.toolbars])d.dispose();this.flyoutWorkspace&&(this.flyoutWorkspace.removeChangeListener(this.onFlyoutChange),this.flyoutWorkspace=void 0),this.workspace&&(this.workspace.removeChangeListener(this.onWorkspaceChange),this.workspace.dispose(),this.workspace=void 0),this.headlessWorkspaceHost&&(this.headlessWorkspaceHost.remove(),this.headlessWorkspaceHost=void 0),this.mountConfig=void 0,this.baseTheme=void 0,this.baseFont=void 0,this.toolboxDefinition=void 0,this.blockCategoryIndex.clear(),this.appliedWorkspaceClasses=[],this.appliedToolboxFlyoutClasses=[],this.appliedToolboxShellClasses=[]}mountToolbox(e,o){var s,r;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before mountToolbox can be used.");(s=this.toolboxCanvas)==null||s.dispose(),this.styles.ensureToolbarStyles(),this.mountConfig.canvasToolbox||this.workspace.updateToolbox({kind:"flyoutToolbox",contents:[]});const i={...o,categories:(o==null?void 0:o.categories)??((r=this.mountConfig.toolbox)==null?void 0:r.categories)};this.toolboxCanvas=new ot({container:e,workspaceContainer:this.mountConfig.workspaceHost,workspace:this.workspace,definitions:this.definitions,blockColors:this.buildBlockColorMap(),behaviors:this.behaviors,elementTypes:this.elementTypes,mode:this.mountConfig.toolboxMode,render:this.mountConfig.toolboxRender,modes:this.mountConfig.modes,options:i,onPreviewWorkspace:c=>me.set(c,this)})}getWorkspace(){return this.workspace}getAvailableModes(){var e;return(((e=this.mountConfig)==null?void 0:e.modes)??[]).map(o=>o.name)}getWorkspaceMode(){var e;return(e=this.mountConfig)==null?void 0:e.workspaceMode}getCodespaceMode(){var e,o;return((e=this.mountConfig)==null?void 0:e.codespaceMode)??((o=this.mountConfig)==null?void 0:o.workspaceMode)}getPreviewMode(){var e;return(e=this.mountConfig)==null?void 0:e.previewMode}modeDef(e){var o;if(e)return(((o=this.mountConfig)==null?void 0:o.modes)??[]).find(i=>i.name===e)}getActivePrimarySourceElement(){const e=this.modeDef(this.getCodespaceMode());if(e)return de(e,this.elementTypes)}getActivePreviewElement(){var o;const e=this.modeDef((o=this.mountConfig)==null?void 0:o.previewMode);if(e)return de(e,this.elementTypes)}mountToolbar(e,o){if(!this.workspace)throw new Error("MorphicBlocks must be mounted before mountToolbar can be used.");this.styles.ensureToolbarStyles();const i=st(e,o,{engine:this,pane:o.pane,getText:()=>this.toolbarTextFor(o.pane),refresh:()=>this.toolbarRefreshFor(o.pane)});this.toolbars.add(i),this.ensureToolbarBlocklyListener();const s=i.dispose;return i.dispose=()=>{this.toolbars.delete(i),this.toolbars.size===0&&this.teardownToolbarBlocklyListener(),s()},i}toolbarTextFor(e){var o,i;if(e==="codespace")return((o=this.codespace)==null?void 0:o.getValue())??this.generateCodespaceText().code;if(e==="preview")return((i=this.previewEditor)==null?void 0:i.getValue())??"";if(this.codespace)return this.codespace.getValue();try{return this.generateJavaScript()}catch{return""}}toolbarRefreshFor(e){var o,i;e==="codespace"?(o=this.codespace)==null||o.refresh():e==="preview"&&((i=this.previewEditor)==null||i.refresh())}runJavaScript(e){let o="",i,s=null;const r=[],c=(e==null?void 0:e.console)??(e!=null&&e.logToConsole?console:void 0),a=u=>(...w)=>{r.push({level:u,text:w.map(String).join(" ")}),c&&(c[u]??c.log).apply(c,w)},l={log:a("log"),warn:a("warn"),error:a("error")};try{o=this.generateJavaScript(),i=new Function("console",o)(l)}catch(u){s=u instanceof Error?u:new Error(String(u))}const d={code:o,result:i,error:s,output:r};return this.dispatchEvent(new CustomEvent("morphic-run",{detail:d})),d}hasClipboardContents(){return!!this.lastCopyData}copyActiveBlock(e){var s;const o=this.resolveActiveBlock(e);if(!o)return!1;const i=o.toCopyData();if(!i)return!1;this.lastCopyData=i;try{const r=this.toolbarTextFor(e==="workspace"?"codespace":e);r&&((s=navigator.clipboard)==null||s.writeText(r))}catch{}for(const r of this.toolbars)r.refresh();return!0}pasteActiveBlock(e){return!this.lastCopyData||!this.workspace?!1:L.clipboard.paste(this.lastCopyData,this.workspace)!==null}resolveActiveBlock(e){var i,s;const o=L.common.getSelected();if(o&&"id"in o&&((i=this.workspace)!=null&&i.getBlockById(o.id)))return o;if(e==="codespace"||e==="preview"){const r=e==="codespace"?this.codespace:this.previewEditor;if(r){const c=r.metadata,a=r.getCursorLine();let l=null;for(const[d,u]of c)if(u.startLine<=a&&u.endLine>=a){const w=u.endLine-u.startLine;(!l||w<l.size)&&(l={id:d,size:w})}if(l){const d=(s=this.workspace)==null?void 0:s.getBlockById(l.id);if(d)return d}}}return null}serializeWorkspace(){return this.workspace?L.serialization.workspaces.save(this.workspace):null}loadWorkspace(e){this.workspace&&(this.workspace.clear(),L.serialization.workspaces.load(e,this.workspace))}zoomPane(e,o){if(e==="workspace"){if(!this.workspace)return;o==="in"?this.workspace.zoomCenter(1):o==="out"?this.workspace.zoomCenter(-1):this.workspace.zoomToFit();return}const i=e==="codespace"?this.codespace:this.previewEditor;i==null||i.adjustZoom(o)}ensureToolbarBlocklyListener(){if(this.toolbarsBlocklyListener||!this.workspace)return;const e=o=>{for(const i of this.toolbars)i.refresh()};this.toolbarsBlocklyListener=e,this.workspace.addChangeListener(e)}teardownToolbarBlocklyListener(){!this.toolbarsBlocklyListener||!this.workspace||(this.workspace.removeChangeListener(this.toolbarsBlocklyListener),this.toolbarsBlocklyListener=void 0)}setModes(e){var o,i,s,r,c,a;if(!this.mountConfig||!this.workspace)throw new Error("MorphicBlocks must be mounted before setModes can be used.");for(const[l,d]of[["workspaceMode",e.workspaceMode],["toolboxMode",e.toolboxMode],["codespaceMode",e.codespaceMode],["previewMode",e.previewMode]])if(typeof d=="string"&&!this.modeDef(d))throw new Error(`setModes: unknown mode "${d}" for ${l}.`);if(typeof e.codespaceMode=="string"&&!this.mountConfig.codespaceContainer)throw new Error("setModes: codespaceMode requires a codespaceContainer at mount.");e.workspaceMode&&(this.mountConfig.workspaceMode=e.workspaceMode),e.codespaceMode!==void 0&&(this.mountConfig.codespaceMode=e.codespaceMode??void 0),e.previewMode!==void 0&&(this.mountConfig.previewMode=e.previewMode??void 0),e.toolboxRender!==void 0&&(this.mountConfig.toolboxRender=e.toolboxRender??void 0),(e.toolboxMode||e.toolboxRender!==void 0)&&(e.toolboxMode&&(this.mountConfig.toolboxMode=e.toolboxMode),(o=this.toolboxCanvas)==null||o.rerender(this.mountConfig.toolboxMode,this.mountConfig.toolboxRender)),this.applyWorkspaceContainerClass(),this.syncWorkspaceFont(),this.refreshToolbox(),this.bindFlyoutWorkspace(),this.renderWorkspaceBlocks(),this.renderFlyoutBlocks(),(i=this.codespace)==null||i.setHighlightRules(this.resolveHighlightRules("codespace")),(s=this.previewEditor)==null||s.setHighlightRules(this.resolveHighlightRules("preview")),(r=this.codespace)==null||r.refresh(),(c=this.previewEditor)==null||c.refresh();for(const l of this.toolbars)l.refresh();(a=this.selectionSync)==null||a.clearAll()}resolveHighlightRules(e){var i;if(!this.mountConfig)return;const o=e==="codespace"?this.getActivePrimarySourceElement():this.getActivePreviewElement();if(o)return(i=this.mountConfig.highlighting)==null?void 0:i[o]}generateJavaScript(){if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before generateJavaScript can be used.");return Kt(this.workspace,this.definitions,this.behaviors,this.mountConfig.javascript)}generateJavaScriptWithMetadata(){if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before generateJavaScriptWithMetadata can be used.");return Yt(this.workspace,this.definitions,this.behaviors,this.mountConfig.javascript)}async mountCodeEditor(e,o){var s;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before mountCodeEditor can be used.");(s=this.codeEditor)==null||s.dispose(),this.codeEditor=new ye(e,this.workspace,()=>this.generateJavaScriptWithMetadata(),o);const i=this.codeEditor;await i.mount(),this.codeEditor===i&&this.refreshSelectionSync()}async mountCodespace(e){var s,r;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before mountCodespace can be used.");if(!this.mountConfig.codespaceContainer)throw new Error("mountCodespace requires a codespaceContainer to be passed to mount().");(s=this.codespace)==null||s.dispose(),(r=this.codespaceDropTeardown)==null||r.call(this);const o={...e,onDelete:(e==null?void 0:e.onDelete)??(c=>this.deleteBlockAtCodespaceLine(c)),canDragBlock:(e==null?void 0:e.canDragBlock)??(c=>{var l;const a=(l=this.workspace)==null?void 0:l.getBlockById(c);return!!(a!=null&&a.previousConnection||a!=null&&a.outputConnection)}),highlightRules:(e==null?void 0:e.highlightRules)??this.resolveHighlightRules("codespace"),onPlaceholderApply:(e==null?void 0:e.onPlaceholderApply)??((c,a)=>this.applyPlaceholderEdit(c,a))};this.codespace=new ye(this.mountConfig.codespaceContainer,this.workspace,()=>this.generateCodespaceText(),o);const i=this.codespace;await i.mount(),this.codespace===i&&(this.codespaceDropTeardown=this.attachCodespaceDropTarget(this.mountConfig.codespaceContainer,this.workspace),this.refreshSelectionSync())}attachCodespaceDropTarget(e,o){const i=m=>{var y;const p=(y=m.dataTransfer)==null?void 0:y.types;return p?p.includes(ee)||p.includes(ve):!1},s=m=>{var y,S,h,f,x,B;if(!i(m))return;m.preventDefault();const p=this.computeCodespaceDrop(m.clientX,m.clientY);if(!p){(y=this.codespace)==null||y.hideDropIndicator(),(S=this.codespace)==null||S.hideValueSlotHighlight();return}p.indicator.kind==="line"?((h=this.codespace)==null||h.showDropIndicator(p.indicator.line,p.indicator.position),(f=this.codespace)==null||f.hideValueSlotHighlight()):((x=this.codespace)==null||x.showValueSlotHighlight(p.indicator.from,p.indicator.to),(B=this.codespace)==null||B.hideDropIndicator())},r=m=>{var y,S;const p=m.relatedTarget;p&&e.contains(p)||((y=this.codespace)==null||y.hideDropIndicator(),(S=this.codespace)==null||S.hideValueSlotHighlight())},c=m=>{var x,B,b,I;if(!i(m))return;m.preventDefault(),(x=this.codespace)==null||x.hideDropIndicator(),(B=this.codespace)==null||B.hideValueSlotHighlight();const p=this.computeCodespaceDrop(m.clientX,m.clientY);if(!p)return;const y=(b=m.dataTransfer)==null?void 0:b.getData(ee),S=(I=m.dataTransfer)==null?void 0:I.getData(ve);let h=null;if(y)h=o.newBlock(G(y,this.definitions)),h.initSvg(),h.render();else if(S){if(h=o.getBlockById(S),!h)return}else return;let f=!1;L.Events.setGroup(!0);try{if(S&&h.getParent()&&h.unplug(!0),p.target.kind==="top")this.placeAtTopIndex(o,h,p.target.index),f=!0;else if(p.target.kind==="statement"){if(h.previousConnection){const D=o.getBlockById(p.target.targetBlockId);D&&D!==h&&(this.connectStatement(h,D,p.target.position),f=!0)}}else if(p.target.kind==="into-slot"){if(h.previousConnection){const D=o.getBlockById(p.target.parentBlockId);D&&D!==h&&(this.connectIntoSlot(h,D,p.target.inputName),f=!0)}}else if(p.target.kind==="value-slot"){if(h.outputConnection){const D=o.getBlockById(p.target.parentBlockId);D&&D!==h&&!this.isDescendantOf(D,h)&&(f=this.connectIntoValueSlot(h,D,p.target.inputName))}!f&&y&&h.dispose(!1)}}finally{L.Events.setGroup(!1)}!f&&h.workspace&&!h.getParent()&&this.placeOrphanBelowTops(h),L.svgResize(o)};let a=null;const l=3,d=m=>m.button===2||m.button===0&&m.ctrlKey,u=m=>{var y,S,h,f,x,B;if(!a)return;if(!a.dragging){const b=Math.abs(m.clientX-a.startX),I=Math.abs(m.clientY-a.startY);if(b+I<l)return;a.dragging=!0}const p=this.computeCodespaceDrop(m.clientX,m.clientY);if(!p){(y=this.codespace)==null||y.hideDropIndicator(),(S=this.codespace)==null||S.hideValueSlotHighlight();return}p.indicator.kind==="line"?((h=this.codespace)==null||h.showDropIndicator(p.indicator.line,p.indicator.position),(f=this.codespace)==null||f.hideValueSlotHighlight()):((x=this.codespace)==null||x.showValueSlotHighlight(p.indicator.from,p.indicator.to),(B=this.codespace)==null||B.hideDropIndicator())},w=m=>{var h,f;window.removeEventListener("mousemove",u),window.removeEventListener("mouseup",w),(h=this.codespace)==null||h.hideDropIndicator(),(f=this.codespace)==null||f.hideValueSlotHighlight();const p=a;if(a=null,Ne(void 0),!(p!=null&&p.dragging))return;const y=this.computeCodespaceDrop(m.clientX,m.clientY);if(!y)return;const S=o.getBlockById(p.sourceId);S&&this.applyRightDragMove(o,S,y)},v=m=>{var S;if(!d(m))return;const p=(S=this.codespace)==null?void 0:S.charAtCoords(m.clientX,m.clientY);if(p==null)return;const y=this.findInnermostBlockAtChar(p);y&&(m.preventDefault(),m.stopPropagation(),a={sourceId:y.id,startX:m.clientX,startY:m.clientY,dragging:!1},Ne(y.id),window.addEventListener("mousemove",u),window.addEventListener("mouseup",w))},C=m=>{m.preventDefault()},E=m=>{var f,x,B,b,I,D,j,$;if(a)return;const p=(f=this.codespace)==null?void 0:f.charAtCoords(m.clientX,m.clientY);if(p==null){(x=this.codespace)==null||x.setHoverHighlight(null),(B=this.codespace)==null||B.setEditableHoverHighlight(null);return}const y=this.findInnermostEditablePlaceholderAtChar(p);(b=this.codespace)==null||b.setEditableHoverHighlight(y?{from:y.start,to:y.end}:null);const S=this.findHoverBlockAtChar(p);if(!S){(I=this.codespace)==null||I.setHoverHighlight(null);return}const h=(D=this.codespace)==null?void 0:D.metadata.get(S.id);if(!h||h.startChar===void 0||h.endChar===void 0){(j=this.codespace)==null||j.setHoverHighlight(null);return}($=this.codespace)==null||$.setHoverHighlight({from:h.startChar,to:h.endChar})},k=()=>{var m,p;(m=this.codespace)==null||m.setHoverHighlight(null),(p=this.codespace)==null||p.setEditableHoverHighlight(null)};return e.addEventListener("dragover",s),e.addEventListener("dragleave",r),e.addEventListener("drop",c),e.addEventListener("mousedown",v,!0),e.addEventListener("contextmenu",C),e.addEventListener("mousemove",E),e.addEventListener("mouseleave",k),()=>{e.removeEventListener("dragover",s),e.removeEventListener("dragleave",r),e.removeEventListener("drop",c),e.removeEventListener("mousedown",v,!0),e.removeEventListener("contextmenu",C),e.removeEventListener("mousemove",E),e.removeEventListener("mouseleave",k),window.removeEventListener("mousemove",u),window.removeEventListener("mouseup",w)}}findInnermostBlockAtChar(e){if(!this.workspace||!this.codespace)return null;let o=null;for(const[i,s]of this.codespace.metadata){if(s.startChar===void 0||s.endChar===void 0||e<s.startChar||e>=s.endChar)continue;const r=s.endChar-s.startChar;(o===null||r<o.size)&&(o={id:i,size:r})}return o?this.workspace.getBlockById(o.id):null}findHoverBlockAtChar(e){if(!this.workspace||!this.codespace)return null;let o=null,i=null;for(const[r,c]of this.codespace.metadata){if(c.startChar===void 0||c.endChar===void 0||e<c.startChar||e>=c.endChar)continue;const a=c.endChar-c.startChar;(i===null||a<i.size)&&(i={id:r,size:a}),!c.atomic&&(o===null||a<o.size)&&(o={id:r,size:a})}const s=o??i;return s?this.workspace.getBlockById(s.id):null}findInnermostEditablePlaceholderAtChar(e){if(!this.codespace)return null;let o=null;for(const i of this.codespace.getPlaceholders()){if(!i.edit||e<i.start||e>=i.end)continue;const s=i.end-i.start;(o===null||s<o.size)&&(o={ph:i,size:s})}return o?{start:o.ph.start,end:o.ph.end}:null}applyRightDragMove(e,o,i){if(!i)return;let s=!1;L.Events.setGroup(!0);try{if(o.getParent()&&o.unplug(!0),i.target.kind==="top")this.placeAtTopIndex(e,o,i.target.index),s=!0;else if(i.target.kind==="statement"){if(o.previousConnection){const r=e.getBlockById(i.target.targetBlockId);r&&r!==o&&(this.connectStatement(o,r,i.target.position),s=!0)}}else if(i.target.kind==="into-slot"){if(o.previousConnection){const r=e.getBlockById(i.target.parentBlockId);r&&r!==o&&(this.connectIntoSlot(o,r,i.target.inputName),s=!0)}}else if(i.target.kind==="value-slot"&&o.outputConnection){const r=e.getBlockById(i.target.parentBlockId);r&&r!==o&&!this.isDescendantOf(r,o)&&(s=this.connectIntoValueSlot(o,r,i.target.inputName))}}finally{L.Events.setGroup(!1)}!s&&o.workspace&&!o.getParent()&&this.placeOrphanBelowTops(o),L.svgResize(e)}computeCodespaceDrop(e,o){var u,w;if(!this.workspace||!this.codespace)return null;const i=this.workspace.getTopBlocks(!0),s=this.codespace.metadata,r=this.codespace.getLineCount();if(i.length===0)return{indicator:{kind:"line",line:1,position:"above"},target:{kind:"top",index:0}};if(this.codespace.isBelowLastLine(o)){const v=s.get(i[i.length-1].id);return{indicator:{kind:"line",line:(v==null?void 0:v.endLine)??r,position:"below"},target:{kind:"top",index:i.length}}}const c=this.codespace.getLineAtCoords(e,o);if(c===null){const v=s.get(i[0].id);return{indicator:{kind:"line",line:(v==null?void 0:v.startLine)??1,position:"above"},target:{kind:"top",index:0}}}const a=this.codespace.charAtCoords(e,o);if(a!==null){const v=this.findValueSlotDropAtChar(a);if(v)return{indicator:{kind:"value-slot",from:v.highlight.from,to:v.highlight.to},target:{kind:"value-slot",parentBlockId:v.parentBlockId,inputName:v.inputName}}}const l=this.findInnermostStatementSlotAtLine(c,s);if(l){const v=this.workspace.getBlockById(l.blockId);if(v){const C=Oe(),E=[];let k=(w=(u=v.getInput(l.inputName))==null?void 0:u.connection)==null?void 0:w.targetBlock();for(;k;)k.id!==C&&E.push(k),k=k.getNextBlock();for(const m of E){const p=s.get(m.id);if(!p||c<p.startLine||c>p.endLine)continue;const y=c===p.endLine,S=this.codespace.isInLowerHalfOfLine(c,o);return y&&S?{indicator:{kind:"line",line:p.endLine,position:"below"},target:{kind:"statement",targetBlockId:m.id,position:"after"}}:{indicator:{kind:"line",line:p.startLine,position:"above"},target:{kind:"statement",targetBlockId:m.id,position:"before"}}}if(E.length>0){const m=E[E.length-1],p=s.get(m.id);return{indicator:{kind:"line",line:(p==null?void 0:p.endLine)??l.range.endLine,position:"below"},target:{kind:"into-slot",parentBlockId:l.blockId,inputName:l.inputName}}}return{indicator:{kind:"line",line:l.range.startLine,position:"above"},target:{kind:"into-slot",parentBlockId:l.blockId,inputName:l.inputName}}}}for(let v=0;v<i.length;v++){const C=s.get(i[v].id);if(!C||c<C.startLine||c>C.endLine)continue;const E=c===C.endLine,k=this.codespace.isInLowerHalfOfLine(c,o);return E&&k?{indicator:{kind:"line",line:C.endLine,position:"below"},target:{kind:"top",index:v+1}}:{indicator:{kind:"line",line:C.startLine,position:"above"},target:{kind:"top",index:v}}}const d=s.get(i[i.length-1].id);return{indicator:{kind:"line",line:(d==null?void 0:d.endLine)??r,position:"below"},target:{kind:"top",index:i.length}}}findInnermostStatementSlotAtLine(e,o){let i=null;for(const[s,r]of o)if(r.statementSlots)for(const[c,a]of Object.entries(r.statementSlots)){if(e<a.startLine||e>a.endLine)continue;const l=a.endLine-a.startLine,d=this.computeBlockDepth(s);(i===null||l<i.size||l===i.size&&d>i.depth)&&(i={blockId:s,inputName:c,range:a,size:l,depth:d})}return i?{blockId:i.blockId,inputName:i.inputName,range:i.range}:null}connectIntoSlot(e,o,i){if(!e.previousConnection)return;const s=o.getInput(i),r=s==null?void 0:s.connection;if(!r)return;const c=r.targetBlock();if(!c){r.connect(e.previousConnection);return}let a=c,l=a.getNextBlock();for(;l;)a=l,l=a.getNextBlock();a.nextConnection&&a.nextConnection.connect(e.previousConnection)}findValueSlotDropAtChar(e){var s,r;if(!this.workspace||!this.codespace)return null;const o=Oe();for(const c of this.codespace.getPlaceholders()){if(e<c.start||e>=c.end)continue;if(c.emptySlot){const{parentBlockId:u,inputName:w}=c.emptySlot;if(u===o)continue;const v=this.workspace.getBlockById(u);if(!((s=v==null?void 0:v.getInput(w))!=null&&s.connection))continue;return{parentBlockId:u,inputName:w,highlight:{from:c.start,to:c.end}}}const a=(r=c.edit)==null?void 0:r.blockId;if(!a||a===o)continue;const l=this.workspace.getBlockById(a);if(!l)continue;const d=this.resolveValueParent(l);if(d)return{parentBlockId:d.parentBlockId,inputName:d.inputName,highlight:{from:c.start,to:c.end}}}let i=null;for(const[c,a]of this.codespace.metadata){if(a.startChar===void 0||a.endChar===void 0||e<a.startChar||e>=a.endChar||c===o)continue;const l=this.workspace.getBlockById(c);if(!(l!=null&&l.outputConnection))continue;const d=a.endChar-a.startChar;(i===null||d<i.size)&&(i={id:c,size:d,from:a.startChar,to:a.endChar})}if(i){const c=this.workspace.getBlockById(i.id);if(c){const a=this.resolveValueParent(c);if(a)return{parentBlockId:a.parentBlockId,inputName:a.inputName,highlight:{from:i.from,to:i.to}}}}return null}resolveValueParent(e){var s;const o=(s=e.outputConnection)==null?void 0:s.targetConnection;if(!o)return null;const i=o.getSourceBlock();if(!i)return null;for(const r of i.inputList)if(r.connection===o)return{parentBlockId:i.id,inputName:r.name};return null}placeOrphanBelowTops(e){var s,r;if(!this.workspace)return;const o=this.workspace.getTopBlocks(!0).filter(c=>c.id!==e.id);if(o.length===0){e.moveTo(new L.utils.Coordinate(20,20));return}let i=0;for(const c of o){const a=c.getRelativeToSurfaceXY(),l=((r=(s=c.getHeightWidth)==null?void 0:s.call(c))==null?void 0:r.height)??50;i=Math.max(i,a.y+l)}e.moveTo(new L.utils.Coordinate(20,i+20))}isDescendantOf(e,o){let i=e;for(;i;){if(i===o)return!0;i=i.getParent()}return!1}connectIntoValueSlot(e,o,i){if(!e.outputConnection)return!1;const s=o.getInput(i),r=s==null?void 0:s.connection;if(!r)return!1;const c=r.targetBlock(),a=!!c&&!c.isShadow();a&&(c.unplug(!1),this.placeOrphanBelowTops(c));const d=r.check_;r.setCheck(null);try{return r.connect(e.outputConnection),!0}catch{if(a&&(c!=null&&c.outputConnection))try{r.connect(c.outputConnection)}catch{}return!1}finally{r.setCheck(d)}}computeBlockDepth(e){var s,r;let o=0,i=((r=(s=this.workspace)==null?void 0:s.getBlockById(e))==null?void 0:r.getParent())??null;for(;i;)o++,i=i.getParent();return o}placeAtTopIndex(e,o,i){const s=e.getTopBlocks(!0).map(c=>c.id).filter(c=>c!==o.id),r=Math.max(0,Math.min(i,s.length));s.splice(r,0,o.id),this.applyTopBlockOrder(e,s)}connectStatement(e,o,i){var s,r,c;if(e.previousConnection)if(i==="before"){const a=((s=o.previousConnection)==null?void 0:s.targetConnection)??null;(r=o.previousConnection)==null||r.disconnect(),a&&a.connect(e.previousConnection),e.nextConnection&&o.previousConnection&&e.nextConnection.connect(o.previousConnection)}else{const a=o.getNextBlock();(c=a==null?void 0:a.previousConnection)==null||c.disconnect(),o.nextConnection&&o.nextConnection.connect(e.previousConnection),a!=null&&a.previousConnection&&e.nextConnection&&e.nextConnection.connect(a.previousConnection)}}applyTopBlockOrder(e,o){var s,r,c;const i=L.Events.disable!==void 0;i&&L.Events.disable();try{for(let a=0;a<o.length;a++){const l=e.getBlockById(o[a]);l&&l.moveTo(new L.utils.Coordinate(20,20+a*100))}}finally{i&&L.Events.enable()}L.svgResize(e),(s=this.codespace)==null||s.refresh(),(r=this.previewEditor)==null||r.refresh(),(c=this.codeEditor)==null||c.refresh()}async mountPreview(e,o){var r;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before mountPreview can be used.");(r=this.previewEditor)==null||r.dispose();const i={...o,highlightRules:(o==null?void 0:o.highlightRules)??this.resolveHighlightRules("preview"),showPlaceholderMarkers:(o==null?void 0:o.showPlaceholderMarkers)??!1};this.previewEditor=new ye(e,this.workspace,()=>this.generatePreviewText(),i);const s=this.previewEditor;await s.mount(),this.previewEditor===s&&this.refreshSelectionSync()}generatePreviewText(){if(!this.workspace||!this.mountConfig)return{code:"",metadata:new Map,placeholders:[]};const e=this.mountConfig.previewMode,o=this.getActivePreviewElement();return!e||!o?{code:"",metadata:new Map,placeholders:[]}:Se(this.workspace,e,this.definitions,this.elementTypes,this.mountConfig.modes??[],o)}applyPlaceholderEdit(e,o){var a;if(!this.workspace)return;let i=this.workspace.getBlockById(e.blockId);if(!i)return;if(i.isShadow()){const l=(a=i.outputConnection)==null?void 0:a.targetConnection;if(l){const d=this.workspace.newBlock(i.type);for(const u of i.inputList)for(const w of u.fieldRow){if(!w.name)continue;const v=d.getField(w.name);v&&v.setValue(w.getValue())}i.rendered&&(d.initSvg(),d.render()),l.connect(d.outputConnection),i=d}}const s=i.getField(e.fieldName);if(!s)return;s.setValue(o);const r=i;r.rendered&&typeof r.render=="function"&&r.render();const c=i.getParent();if(c){const l=c;l.rendered&&typeof l.render=="function"&&l.render()}}deleteBlockAtCodespaceLine(e){var r,c;const o=(r=this.codespace)==null?void 0:r.metadata;if(!this.workspace||!o||o.size===0)return;let i=null,s=1/0;for(const[a,{startLine:l,endLine:d}]of o){if(e<l||e>d)continue;const u=d-l;u<s&&(s=u,i=a)}i&&((c=this.workspace.getBlockById(i))==null||c.dispose(!0))}generateCodespaceText(){if(!this.workspace||!this.mountConfig)return{code:"",metadata:new Map,placeholders:[]};const e=this.mountConfig.codespaceMode;if(e){const o=this.modeDef(e),i=o?de(o,this.elementTypes):void 0;return Se(this.workspace,e,this.definitions,this.elementTypes,this.mountConfig.modes??[],i)}return Se(this.workspace,this.mountConfig.workspaceMode,this.definitions,this.elementTypes,this.mountConfig.modes??[])}showCodeEditor(){var e;(e=this.codeEditor)==null||e.show()}hideCodeEditor(){var e;(e=this.codeEditor)==null||e.hide()}isCodeEditorVisible(){var e;return((e=this.codeEditor)==null?void 0:e.isVisible())??!1}setCodeEditorTheme(e){var o;(o=this.codeEditor)==null||o.setTheme(e)}setCodespaceTheme(e){var o;(o=this.codespace)==null||o.setTheme(e)}setPreviewTheme(e){var o;(o=this.previewEditor)==null||o.setTheme(e)}enableSelectionSync(e){var i;if(!this.workspace)throw new Error("MorphicBlocks must be mounted before enableSelectionSync can be used.");const o=[this.codeEditor,this.codespace,this.previewEditor].filter(s=>s!==void 0);if(o.length===0)throw new Error("enableSelectionSync requires at least one of mountCodeEditor, mountCodespace, or mountPreview to have been called first.");(i=this.selectionSync)==null||i.disable(),this.selectionSyncOptions=e,this.selectionSync=new go(this.workspace,o,e),this.selectionSync.enable()}refreshSelectionSync(){this.selectionSync&&this.enableSelectionSync(this.selectionSyncOptions)}disableSelectionSync(){var e;(e=this.selectionSync)==null||e.disable(),this.selectionSync=void 0,this.selectionSyncOptions=void 0}registerBlocks(){for(const e of this.definitions.values()){const o=Ce(e.identifier);if(ge.set(o,this),this.registeredBlockTypes.has(o))continue;const i=e.identifier;L.Blocks[o]={init(){const s=me.get(this.workspace)??ge.get(o);s==null||s.initManagedBlock(this,i)}},this.registeredBlockTypes.add(o)}}initManagedBlock(e,o){var a;const i=this.definitions.get(o);if(!i)return;const s=e.workspace.isFlyout?"toolbox":"workspace",r=this.resolveMode(s);this.applyView(e,i,r,s);const c=te(this.behaviors[i.identifier]);(a=c==null?void 0:c.init)==null||a.call(c,e,this.createBehaviorContext(e,i,r,s))}validateContainers(e){if(!e.workspaceContainer&&!e.codespaceContainer)throw new Error("MorphicBlocks.mount requires at least one of workspaceContainer or codespaceContainer.")}createHeadlessHost(){const e=document.createElement("div");return e.style.cssText="position:absolute;left:-9999px;top:-9999px;width:800px;height:600px;overflow:hidden;",document.body.appendChild(e),this.headlessWorkspaceHost=e,e}resolveMode(e){return this.mountConfig?e==="toolbox"?this.mountConfig.toolboxMode:this.mountConfig.workspaceMode:"default"}applyView(e,o,i,s){var u,w;if(e.isDeadOrDying())return;const r=this.blockCategoryIndex.get(o.identifier);o.color===void 0&&(r==null?void 0:r.color)!==void 0&&e.setColour(r.color);const c=Pt(e),a=Ee(o,i,this.elementTypes,((u=this.mountConfig)==null?void 0:u.modes)??[]),l=e.workspace===this.workspace;De({block:e,definition:o,view:a,mode:i,context:s,elementTypes:l?this.elementTypes:void 0,resolveBlocklyType:v=>G(v,this.definitions)}),Et(e,r==null?void 0:r.token),St(e,o.identifier),xt(e),o.color!==void 0&&(e.setColour(o.color),e.rendered&&e.render());const d=te(this.behaviors[o.identifier]);(w=d==null?void 0:d.onViewApplied)==null||w.call(d,e,this.createBehaviorContext(e,o,i,s)),Ht(e,c)}applyWorkspaceContainerClass(){var i;if(!this.mountConfig)return;const e=this.mountConfig.workspaceHost;ke(e,this.mountConfig.workspaceMode,"workspace","morphic-workspace-root");const o=this.resolveClassNames((i=this.mountConfig.ui)==null?void 0:i.workspaceClassName);this.replaceUserClasses(e,this.appliedWorkspaceClasses,o),this.appliedWorkspaceClasses=o}syncWorkspaceFont(){var s;const e=this.workspace,o=(s=this.mountConfig)==null?void 0:s.workspaceHost;if(!e||!o||!this.baseTheme||!this.baseFont)return;const i=Ke(o,[[e.getRenderer().getClassName(),this.baseTheme.getClassName()]],this.baseFont);Ye(e,this.baseTheme,this.baseFont,i)&&Je(e)}applyFlyoutClass(){var c,a,l;if(!this.workspace||!this.mountConfig)return;const e=this.resolveClassNames((c=this.mountConfig.ui)==null?void 0:c.toolboxClassName),o=this.workspace.getToolbox(),i=((a=o==null?void 0:o.getDiv)==null?void 0:a.call(o))??null;i&&(ke(i,this.mountConfig.toolboxMode,"toolbox","morphic-toolbox-shell"),this.replaceUserClasses(i,this.appliedToolboxShellClasses,e),this.appliedToolboxShellClasses=e);const s=(l=this.workspace.getFlyout())==null?void 0:l.getWorkspace(),r=s==null?void 0:s.getParentSvg();r&&(ke(r,this.mountConfig.toolboxMode,"toolbox","morphic-toolbox-root"),this.replaceUserClasses(r,this.appliedToolboxFlyoutClasses,e),this.appliedToolboxFlyoutClasses=e)}renderWorkspaceBlocks(){if(!(!this.workspace||!this.mountConfig))for(const e of this.workspace.getAllBlocks(!1)){const o=e,i=this.definitions.get(W(o.type));i&&this.applyView(o,i,this.mountConfig.workspaceMode,"workspace")}}renderFlyoutBlocks(){if(!(!this.flyoutWorkspace||!this.mountConfig)){for(const e of this.flyoutWorkspace.getAllBlocks(!1)){const o=e,i=this.definitions.get(W(o.type));i&&this.applyView(o,i,this.mountConfig.toolboxMode,"toolbox")}this.applyFlyoutClass()}}refreshToolbox(){var e;!this.workspace||!this.toolboxDefinition||(e=this.mountConfig)!=null&&e.canvasToolbox||this.workspace.updateToolbox(this.toolboxDefinition)}bindFlyoutWorkspace(){var o;if(this.flyoutWorkspace&&(this.flyoutWorkspace.removeChangeListener(this.onFlyoutChange),this.flyoutWorkspace=void 0),!this.workspace)return;const e=(o=this.workspace.getFlyout())==null?void 0:o.getWorkspace();e&&(this.flyoutWorkspace=e,me.set(e,this),this.flyoutWorkspace.addChangeListener(this.onFlyoutChange),this.applyFlyoutClass())}resolveToolboxDefinition(e){if(e.toolbox){const s=this.resolveToolboxKind(e.toolboxLayout),r=s?{...e.toolbox,kind:s}:e.toolbox;return nt(r,this.definitions)}const o=e.blockly;if(o!=null&&o.toolbox)return o.toolbox;const i=this.resolveToolboxKind(e.toolboxLayout);return nt({...i!==void 0?{kind:i}:{},blocks:[...this.definitions.keys()]},this.definitions)}createBehaviorContext(e,o,i,s){return{Blockly:L,workspace:e.workspace,mode:i,context:s,definition:o}}resolveClassNames(e){return e?(Array.isArray(e)?e.join(" "):e).split(/\s+/).map(i=>i.trim()).filter((i,s,r)=>!!i&&r.indexOf(i)===s):[]}replaceUserClasses(e,o,i){for(const s of o)e.classList.remove(s);for(const s of i)e.classList.add(s)}buildBlockColorMap(){var o;const e=new Map;for(const[i,s]of this.definitions){const r=s.color??((o=this.blockCategoryIndex.get(i))==null?void 0:o.color);r!==void 0&&e.set(i,String(r))}return e}resolveToolboxKind(e){if(e)return e==="category"?"categoryToolbox":"flyoutToolbox"}createCategoryIndex(e,o){const i=new Map,s=(e==null?void 0:e.categories)??[],r=new Map;for(const a of s){const l=H(a.name);if(r.set(a.name.toLowerCase(),{token:l,color:a.color}),a.blocks)for(const d of a.blocks)i.has(d)||i.set(d,{token:l,color:a.color})}const c=o?this.definitions:new Map;for(const a of c.values()){if(!a.category||i.has(a.identifier))continue;const l=r.get(a.category.toLowerCase());l&&i.set(a.identifier,l)}return i}deferApplyView(e,o,i){const s=i==="toolbox"?this.flyoutWorkspace:this.workspace;s&&requestAnimationFrame(()=>{const r=s.getBlockById(e);if(!r)return;const c=this.definitions.get(W(r.type));c&&this.applyView(r,c,o,i)})}}function Xo(n,t,e){return Math.min(Math.max(n,t),e)}function Ko(n,t){const{target:e,axis:o,invert:i=!1,onResize:s}=t,r=t.min??0,c=t.max??Number.POSITIVE_INFINITY,a=l=>{if(l.button!==0)return;l.preventDefault();const d=e.getBoundingClientRect(),u=o==="x"?d.width:d.height,w=o==="x"?l.clientX:l.clientY,v=document.body.style.userSelect,C=document.body.style.cursor;document.body.style.userSelect="none",document.body.style.cursor=o==="x"?"col-resize":"row-resize",n.setPointerCapture(l.pointerId);const E=m=>{const y=(o==="x"?m.clientX:m.clientY)-w,S=Xo(u+(i?-y:y),r,c);e.style.flexBasis=`${S}px`,s==null||s(S)},k=()=>{n.removeEventListener("pointermove",E),n.removeEventListener("pointerup",k),n.removeEventListener("lostpointercapture",k),document.body.style.userSelect=v,document.body.style.cursor=C};n.addEventListener("pointermove",E),n.addEventListener("pointerup",k),n.addEventListener("lostpointercapture",k)};return n.addEventListener("pointerdown",a),{dispose:()=>n.removeEventListener("pointerdown",a)}}const Yo=Object.freeze(Object.defineProperty({__proto__:null,default:".morphic-placeholder-default,.morphic-placeholder-set{border-radius:2px;padding:0 .2em}.morphic-placeholder-default{font-style:italic;opacity:.55}"},Symbol.toStringTag,{value:"Module"})),Jo=Object.freeze(Object.defineProperty({__proto__:null,default:".morphic-toolbar{display:flex;align-items:center;gap:var(--morphic-toolbar-gap, .5em);padding:var(--morphic-toolbar-padding, 4px 8px);background:var(--morphic-toolbar-bg, inherit);color:var(--morphic-toolbar-fg, inherit);font:var(--morphic-toolbar-font, inherit);border-bottom:var(--morphic-toolbar-border, 1px solid rgba(127, 127, 127, .2));box-sizing:border-box}.morphic-toolbar-left,.morphic-toolbar-right{display:flex;align-items:center;gap:var(--morphic-toolbar-gap, .5em)}.morphic-toolbar-right{margin-left:auto}.morphic-toolbar-item{display:inline-flex;align-items:center;gap:4px;background:var(--morphic-toolbar-item-bg, transparent);color:inherit;border:var(--morphic-toolbar-item-border, none);padding:var(--morphic-toolbar-item-padding, 2px 6px);border-radius:var(--morphic-toolbar-item-radius, 3px);cursor:pointer;font:inherit;line-height:1}.morphic-toolbar-item:hover:not(:disabled){background:var(--morphic-toolbar-item-hover-bg, rgba(127, 127, 127, .15))}.morphic-toolbar-item:disabled{opacity:.4;cursor:default}.morphic-toolbar-icon{display:inline-flex}.morphic-toolbar-label{opacity:.7;font-size:.9em}.morphic-toolbox-header{display:flex;align-items:center;padding:4px 6px 8px}.morphic-toolbar-badge{font-size:.85em;opacity:.6;padding:1px 6px;border:1px solid currentColor;border-radius:3px}.morphic-toolbar-spacer{flex:1}"},Symbol.toStringTag,{value:"Module"}));A.MorphicBlocks=Go,A.MorphicToolboxCanvas=ot,A.makeResizable=Ko,A.renderToolbar=st,A.toolbarItems=O,A.validateDefinitions=qe,Object.defineProperty(A,Symbol.toStringTag,{value:"Module"})}));
|
|
1
|
+
(function(N,_){typeof exports=="object"&&typeof module<"u"?_(exports,require("blockly/blocks"),require("blockly"),require("blockly/javascript")):typeof define=="function"&&define.amd?define(["exports","blockly/blocks","blockly","blockly/javascript"],_):(N=typeof globalThis<"u"?globalThis:N||self,_(N.MorphicBlocks={},N.Blockly,N.Blockly,N.javascript))})(this,(function(N,_,q,J){"use strict";var gn=Object.defineProperty;var kn=(N,_,q)=>_ in N?gn(N,_,{enumerable:!0,configurable:!0,writable:!0,value:q}):N[_]=q;var m=(N,_,q)=>kn(N,typeof _!="symbol"?_+"":_,q);function bt(i){const o=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const e in i)if(e!=="default"){const t=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(o,e,t.get?t:{enumerable:!0,get:()=>i[e]})}}return o.default=i,Object.freeze(o)}const x=bt(q);function ce(i){if(!(!i||typeof i=="function"))return i}function Ct(i){if(i)return typeof i=="function"?i:i.generate}const Z="morphic-mode-",ae="morphic-context-",Pe="morphic-category-",Et="morphic-block-",St=-1,xt=0,Tt=1;function j(i){if(i!==void 0)return typeof i=="string"?i:i.type}function Fe(i,o){const e={...i};for(const[t,n]of Object.entries(o??{})){const s=i[t];if(j(s)!=="code")continue;const{empty:r,stringQuote:c,emptyStatement:a}=n;if(r===void 0&&c===void 0&&a===void 0)continue;const l={...typeof s=="string"?{type:s}:s,empty:r,stringQuote:c,emptyStatement:a};e[t]=l}return e}const Q=16;function Re(i){if(!i||typeof i=="string")return{width:Q,height:Q};const o=i.size;if(o===void 0)return{width:Q,height:Q};if(typeof o=="number")return{width:o,height:o};const e=/^(\d+)(?:x(\d+))?$/i.exec(o.trim());if(!e)return{width:Q,height:Q};const t=Number.parseInt(e[1],10),n=e[2]?Number.parseInt(e[2],10):t;return{width:t,height:n}}function Lt(i,o){if(i!=null&&i.default)return i.default;if(!o||typeof o=="string")return;const e=o.empty;if(!e)return;const t=i!=null&&i.check?Array.isArray(i.check)?i.check[0]:i.check:void 0;return(t?e[t]:void 0)??e.default}const le=18;function ee(i){const o=[];let e=0;for(;e<i.length;){const t=i[e];if(t==="<"&&/^<img\b/i.test(i.slice(e))){const s=i.indexOf(">",e);if(s===-1){_e(o,i.slice(e));break}const r=i.slice(e,s+1),c=Dt(r);c&&o.push(c),e=s+1;continue}if(t==="%"&&/\d/.test(i[e+1]??"")){let s=e+1;for(;s<i.length&&/\d/.test(i[s]??"");)s+=1;const r=Number.parseInt(i.slice(e+1,s),10);Number.isNaN(r)||o.push({kind:"placeholder",index:r}),e=s;continue}if(t==="%"&&/[A-Z_]/.test(i[e+1]??"")){let s=e+1;for(;s<i.length&&/[A-Z0-9_]/.test(i[s]??"");)s+=1;const r=i.slice(e+1,s);o.push({kind:"field",name:r}),e=s;continue}let n=e+1;for(;n<i.length;){const s=i[n],r=s==="%"&&/\d/.test(i[n+1]??""),c=s==="%"&&/[A-Z_]/.test(i[n+1]??"");if(s==="<"&&/^<img\b/i.test(i.slice(n))||r||c)break;n+=1}_e(o,i.slice(e,n)),e=n}return At(o)}function Mt(i){return i.replace(/\s+/g," ").trim()}function V(i){return i.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}function Ce(i){return i.map(o=>o.kind==="text"?Bt(o.value):o.kind==="image"?`<img src="${de(o.src)}" alt="${de(o.alt)}" width="${o.width}" height="${o.height}">`:o.kind==="field"?`<span class="morphic-field-placeholder" data-field-name="${de(o.name)}"></span>`:`<span class="morphic-toolbox-slot" data-slot-index="${o.index}"></span>`).join("")}function Bt(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function de(i){return i.replace(/"/g,""").replace(/'/g,"'")}const It=/\.(svg|png|jpe?g|gif|webp)(?:[#?].*)?$/i;function Ve(i,o){if(!i)return i;const e=i.trim();return/^<img\b/i.test(e)?i:It.test(e)?`<img src="${de(e)}" width="${o.width}" height="${o.height}">`:i}function Dt(i){if(!/^<img\b/i.test(i))return null;const o=he(i,"src");if(!o)return null;const e=he(i,"alt")??"",t=Number.parseInt(he(i,"width")??`${le}`,10),n=Number.parseInt(he(i,"height")??`${le}`,10);return{kind:"image",src:o,alt:e,width:Number.isNaN(t)?le:t,height:Number.isNaN(n)?le:n}}function he(i,o){const e=new RegExp(`${o}\\s*=\\s*(['"])(.*?)\\1`,"i").exec(i);if(e!=null&&e[2])return e[2];const t=new RegExp(`${o}\\s*=\\s*([^\\s>]+)`,"i").exec(i);return(t==null?void 0:t[1])??null}function _e(i,o){o&&i.push({kind:"text",value:o})}function At(i){const o=[];for(const e of i){const t=o[o.length-1];if(e.kind==="text"&&(t==null?void 0:t.kind)==="text"){t.value+=e.value;continue}o.push(e)}return o}function We(i){const{block:o,definition:e,view:t,mode:n,context:s,elementTypes:r,resolveBlocklyType:c}=i,a=zt(o),d=jt(o);qt(o),Pt(o,e,t),Jt(o,e),typeof e.inputsInline=="boolean"&&o.setInputsInline(e.inputsInline),e.color!==void 0&&o.setColour(e.color),e.tooltip&&o.setTooltip(e.tooltip),e.helpUrl&&o.setHelpUrl(e.helpUrl),Xt(o,a),Ut(o,d),r&&Gt(o,e,t,r,c),ze(o,n,s);const l=o;l.__morphicMode=n,l.__morphicContext=s,Ee(o)&&o.render()}function Ee(i){var o;return i.rendered&&!!((o=i.getSvgRoot())!=null&&o.parentNode)}function ue(i,o,e,t){te(i.classList,Z),te(i.classList,ae),i.classList.add(t),i.classList.add(`${Z}${V(o)}`),i.classList.add(`${ae}${e}`)}function Ot(i){return i.__morphicMode}function $t(i,o){const e=i.getSvgRoot();e&&(te(e.classList,Pe),o&&e.classList.add(`${Pe}${o}`))}function Nt(i,o){const e=i.getSvgRoot();if(!e)return;const t=`${Et}${V(o)}`;e.classList.contains(t)||e.classList.add(t)}function Ht(i){const o=i.getSvgRoot();if(!o)return;const e=getComputedStyle(o).getPropertyValue("--morphic-block-color").trim();e&&(i.setColour(e),Ee(i)&&i.render())}function fe(i,o,e){te(i.classList,Z),i.classList.add(e),o&&i.classList.add(`${Z}${V(o)}`)}function ze(i,o,e){const t=i.getSvgRoot();t&&(te(t.classList,Z),te(t.classList,ae),t.classList.add(`${Z}${V(o)}`),t.classList.add(`${ae}${e}`))}function Pt(i,o,e){var r;const t=ee(e.template),n=[],s=new Set;for(const c of t){if(c.kind==="text"){const l=Mt(c.value);l&&n.push(l);continue}if(c.kind==="image"){n.push(new x.FieldImage(c.src,c.width,c.height,c.alt));continue}if(c.kind==="field"){const l=(r=o.fields)==null?void 0:r[c.name];l&&n.push({field:_t(l,e.elementName),name:c.name});continue}if(s.has(c.index)){const l=i.appendDummyInput(`DUPLICATE_${c.index}_${i.inputList.length}`);pe(l,n),l.appendField(`%${c.index}`);continue}s.add(c.index);const a=Ft(o,e,c.index);if((a==null?void 0:a.kind)==="statement"&&n.length>0){const l=i.appendDummyInput(`PRE_STMT_${i.inputList.length}`);pe(l,n)}const d=Rt(i,a,c.index);pe(d,n),a!=null&&a.label&&d.appendField(a.label)}if(n.length>0){const c=i.appendDummyInput(`TRAILING_${i.inputList.length}`);pe(c,n)}i.inputList.length===0&&i.appendDummyInput("LABEL").appendField(o.identifier)}function Ft(i,o,e){var n,s;const t=`${e}`;return((n=o.inputSlots)==null?void 0:n[t])??((s=i.inputSlots)==null?void 0:s[t])}function Rt(i,o,e){const t=(o==null?void 0:o.name)??`ARG${e}`,n=(o==null?void 0:o.kind)??"value";let s;return n==="statement"?(s=i.appendStatementInput(t),o!=null&&o.check&&s.setCheck(o.check)):(s=i.appendValueInput(t),o!=null&&o.check&&s.setCheck(o.check)),o!=null&&o.align&&s.setAlign(Vt(o.align)),s}function Vt(i){return i==="right"?Tt:i==="centre"?xt:St}function pe(i,o){for(const e of o)typeof e=="object"&&"field"in e?i.appendField(e.field,e.name):i.appendField(e);o.length=0}function _t(i,o){switch(i.type){case"dropdown":{const e=i.options.map(n=>Wt(n,o)),t=new x.FieldDropdown(e);return i.default!==void 0&&t.setValue(i.default),t}case"number":return new x.FieldNumber(i.default??0,i.min,i.max,i.precision);case"checkbox":return new x.FieldCheckbox(i.default?"TRUE":"FALSE");case"text":default:return new x.FieldTextInput(i.default??"")}}function Wt(i,o){var t;if(typeof i=="string")return[i,i];if(Array.isArray(i)){const[n,s]=i;return[s??n,n]}return[(o?(t=i.display)==null?void 0:t[o]:void 0)??i.label??i.value,i.value]}function zt(i){var e;const o=new Map;for(const t of i.inputList){const n=(e=t.connection)==null?void 0:e.targetBlock();n&&!n.isShadow()&&o.set(t.name,n)}return o}function jt(i){var e;const o=new Map;for(const t of i.inputList){const n=(e=t.connection)==null?void 0:e.getShadowState(!0);n&&o.set(t.name,n)}return o}function Ut(i,o){var e;for(const[t,n]of o){const s=(e=i.getInput(t))==null?void 0:e.connection;if(!(!s||s.getShadowState()))try{s.setShadowState(n)}catch{}}}function Gt(i,o,e,t,n=s=>s){var a,d;const s=e.elementName?t[e.elementName]:void 0,r=new Map;for(const l of Object.values(o.inputSlots??{}))l!=null&&l.name&&(l.kind??"value")==="value"&&r.set(l.name,l);if(r.size===0)return;const c=i.workspace;for(const l of i.inputList){const h=l.connection;if(!h||h.type!==x.INPUT_VALUE)continue;const u=r.get(l.name);if(!u)continue;const k=Lt(u,s);if(k){if(k.shadow&&!(((a=h.getShadowState)==null?void 0:a.call(h,!0))??((d=h.getShadowDom)==null?void 0:d.call(h))))try{h.setShadowState({type:n(k.shadow),fields:k.fieldValues??{}})}catch{}if(k.placeholder){const v=i,w=v.__morphicPlaceholderSlots??(v.__morphicPlaceholderSlots=new Set),b=h.targetBlock(),g=!b||b.isShadow(),y=w.has(l.name);if(w.add(l.name),g&&!y)try{const C=c.newBlock(n(k.placeholder));if(k.fieldValues)for(const[E,f]of Object.entries(k.fieldValues)){const p=C.getField(E);p&&p.setValue(f)}C.outputConnection&&h.connect(C.outputConnection),i.rendered&&(C.initSvg(),C.queueRender())}catch{}}}}}function Xt(i,o){for(const[e,t]of o){const n=i.getInput(e);if(!(n!=null&&n.connection)||n.connection.isConnected())continue;const s=[t.outputConnection,t.previousConnection];for(const r of s)if(r)try{n.connection.connect(r);break}catch{continue}}}function Yt(i){const o=new Map;for(const e of i.inputList)for(const t of e.fieldRow)t.name&&o.set(t.name,t.getValue());return o}function Kt(i,o){for(const[e,t]of o){const n=i.getField(e);if(n&&t!==void 0&&t!==null)try{n.setValue(t)}catch{}}}function qt(i){for(;i.inputList.length>0;){const o=i.inputList[0];if(!o)break;i.removeInput(o.name,!0)}}function Jt(i,o){o.output!==void 0&&Zt(i,o.output),o.previousStatement!==void 0&&Qt(i,o.previousStatement),o.nextStatement!==void 0&&eo(i,o.nextStatement)}function Zt(i,o){if(o===!1){i.setOutput(!1);return}if(o===!0){i.setOutput(!0);return}i.setOutput(!0,o)}function Qt(i,o){if(o===!1){i.setPreviousStatement(!1);return}if(o===!0){i.setPreviousStatement(!0);return}i.setPreviousStatement(!0,o)}function eo(i,o){if(o===!1){i.setNextStatement(!1);return}if(o===!0){i.setNextStatement(!0);return}i.setNextStatement(!0,o)}function te(i,o){const e=Array.from(i).filter(t=>t.startsWith(o));for(const t of e)i.remove(t)}function je(i,o,e){if(!e)return[];const t={keyword:i.Decoration.mark({class:"morphic-tok-keyword"}),string:i.Decoration.mark({class:"morphic-tok-string"}),number:i.Decoration.mark({class:"morphic-tok-number"}),comment:i.Decoration.mark({class:"morphic-tok-comment"})},n=Ue(e),s=(u,k,v)=>{for(const w of n(u))v.add(k+w.from,k+w.to,t[w.kind])},r=u=>{const k=new o.RangeSetBuilder,v=u.state.doc;for(const{from:w,to:b}of u.visibleRanges){let g=w;for(;g<=b;){const y=v.lineAt(g);if(s(y.text,y.from,k),y.to>=b)break;g=y.to+1}}return k.finish()},c=i.ViewPlugin.fromClass(class{constructor(u){m(this,"decorations");this.decorations=r(u)}update(u){(u.docChanged||u.viewportChanged)&&(this.decorations=r(u.view))}},{decorations:u=>u.decorations}),a=i.EditorView.baseTheme({".morphic-tok-keyword":{color:"#cc7832"},".morphic-tok-string":{color:"#6a8759"},".morphic-tok-number":{color:"#6897bb"},".morphic-tok-comment":{color:"#808080",fontStyle:"italic"}}),d=e.colors??{},l={};d.keyword&&(l[".cm-content .morphic-tok-keyword"]={color:d.keyword}),d.string&&(l[".cm-content .morphic-tok-string"]={color:d.string}),d.number&&(l[".cm-content .morphic-tok-number"]={color:d.number}),d.comment&&(l[".cm-content .morphic-tok-comment"]={color:d.comment,fontStyle:"italic"});const h=[c,a];return Object.keys(l).length>0&&h.push(i.EditorView.theme(l)),h}function Ue(i){const o=new Set(i.keywords??[]),e=(i.strings??[]).map(s=>typeof s=="string"?{open:s,close:s}:{open:s[0],close:s[1]}),t=i.comment,n=i.numbers!==!1;return s=>{const r=[],c=s.length;let a=0;for(;a<c;){if(t&&s.startsWith(t,a))return r.push({from:a,to:c,kind:"comment"}),r;let d=!1;for(const h of e)if(s.startsWith(h.open,a)){const u=a;for(a+=h.open.length;a<c;){if(s[a]==="\\"&&a+1<c){a+=2;continue}if(s.startsWith(h.close,a)){a+=h.close.length;break}a+=1}r.push({from:u,to:a,kind:"string"}),d=!0;break}if(d)continue;if(n){const h=/^\d+(?:\.\d+)?/.exec(s.slice(a));if(h){r.push({from:a,to:a+h[0].length,kind:"number"}),a+=h[0].length;continue}}const l=/^[\p{L}\p{M}_][\p{L}\p{M}\p{N}_]*/u.exec(s.slice(a));if(l){o.has(l[0])&&r.push({from:a,to:a+l[0].length,kind:"keyword"}),a+=l[0].length;continue}a+=1}return r}}const Se="morphic/block-id";let me;function xe(){return me}function Ge(i){me=i}const ne={fontSize:"14px",fontFamily:"monospace",lineHeight:1.5,background:"#1e1e1e",foreground:"#d4d4d4",gutterBackground:"#1e1e1e",gutterForeground:"#858585",selectionBackground:"#264f78"},ie=(i,o)=>`color-mix(in srgb, ${i} ${o}%, transparent)`;let Xe=!1;async function to(){if(Xe)return;Xe=!0;const o=(await Promise.resolve().then(()=>pn)).default,e=document.createElement("style");e.dataset.morphicSource="code-editor",e.textContent=o,document.head.appendChild(e)}const oo=150,no=new Set(["create","delete","move","change"]);function io(i){return no.has(i.type)}async function so(i){let o,e;try{[o,e]=await Promise.all([import("@codemirror/view"),import("@codemirror/state")])}catch{throw new Error(`CodeMirror is required for the codespace, preview and code editor. Install it:
|
|
2
|
+
npm install @codemirror/view @codemirror/state`)}if(!i)return{view:o,state:e,langJs:void 0};try{return{view:o,state:e,langJs:await import("@codemirror/lang-javascript")}}catch{throw new Error(`The code editor also needs JavaScript language support. Install it:
|
|
3
|
+
npm install @codemirror/lang-javascript`)}}function Te(i,o){const e={...ne,...o};return i.EditorView.theme({"&":{fontSize:e.fontSize,fontFamily:e.fontFamily,backgroundColor:e.background,color:e.foreground},".cm-scroller":{fontFamily:e.fontFamily},".cm-content":{lineHeight:String(e.lineHeight)},".cm-gutters":{backgroundColor:e.gutterBackground,color:e.gutterForeground,border:"none"},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground":{backgroundColor:`${e.selectionBackground} !important`},".morphic-delete-marker":{color:ie(e.foreground,70),backgroundColor:ie(e.foreground,12)},".morphic-delete-marker:hover":{color:e.foreground,backgroundColor:ie(e.foreground,22)},".morphic-grip-marker":{color:ie(e.foreground,75)},".morphic-grip-marker:hover":{color:e.foreground}})}class ge{constructor(o,e,t,n={},s=!1){m(this,"editorView");m(this,"container");m(this,"options");m(this,"workspace");m(this,"generateWithMetadata");m(this,"visible",!0);m(this,"syncTimer");m(this,"changeListener");m(this,"lastCode","");m(this,"metadata",new Map);m(this,"placeholders",[]);m(this,"placeholderEditorEl");m(this,"placeholderEditorScrollHandler");m(this,"placeholderEditorOutsideHandler");m(this,"onCursorLine");m(this,"onEmptyClick");m(this,"cm");m(this,"themeCompartment");m(this,"syntaxHighlightCompartment");m(this,"highlightEffect");m(this,"highlightColor");m(this,"themeSelection",ne.selectionBackground);m(this,"activeHighlight");m(this,"metadataEffect");m(this,"placeholderEffect");m(this,"dropIndicatorEffect");m(this,"valueSlotHighlightEffect");m(this,"hoverHighlightEffect");m(this,"editableHoverHighlightEffect");m(this,"emptyClickListener");m(this,"disposed",!1);m(this,"zoomFactor",1);this.javascript=s,this.container=o,this.workspace=e,this.generateWithMetadata=t,this.options=n}getPlaceholders(){return this.placeholders}findPlaceholderAtPos(o){if(this.options.showPlaceholderMarkers===!1)return null;let e=null,t=1/0;for(const n of this.placeholders){if(n.start>o)break;if(o>=n.start&&o<=n.end){const s=n.end-n.start;s<t&&(t=s,e=n)}}return e}closePlaceholderEditor(){const o=this.placeholderEditorEl;o&&(this.placeholderEditorEl=void 0,this.placeholderEditorScrollHandler&&this.editorView&&(this.editorView.scrollDOM.removeEventListener("scroll",this.placeholderEditorScrollHandler),this.placeholderEditorScrollHandler=void 0),this.placeholderEditorOutsideHandler&&(document.removeEventListener("mousedown",this.placeholderEditorOutsideHandler),this.placeholderEditorOutsideHandler=void 0),o.parentNode&&o.parentNode.removeChild(o))}openPlaceholderEditor(o){if(!this.editorView||!o.edit)return;const e=this.options.onPlaceholderApply;if(!e)return;this.closePlaceholderEditor();const t=this.editorView,n=t.coordsAtPos(o.start),s=t.coordsAtPos(o.end);if(!n||!s)return;const r=t.scrollDOM.getBoundingClientRect(),c=t.state.doc.sliceString(o.start,o.end),a=o.edit;let d;if(a.fieldType==="dropdown"){const v=document.createElement("select");for(const[w,b]of a.options??[]){const g=document.createElement("option");g.value=b,g.textContent=w,v.appendChild(g)}d=v}else{const v=document.createElement("input");v.type=a.fieldType==="number"?"number":"text",v.value=c,d=v}const l=getComputedStyle(t.contentDOM),h=(()=>{let v=t.dom;for(;v;){const w=getComputedStyle(v).backgroundColor;if(w&&w!=="rgba(0, 0, 0, 0)"&&w!=="transparent")return w;v=v.parentElement}return"#fff"})();Object.assign(d.style,{position:"absolute",left:`${n.left-r.left+t.scrollDOM.scrollLeft}px`,top:`${n.top-r.top+t.scrollDOM.scrollTop}px`,minWidth:`${Math.max(40,s.right-n.left+8)}px`,height:`${n.bottom-n.top}px`,font:l.font,lineHeight:l.lineHeight,padding:"0 2px",margin:"0",border:`1px solid ${l.color}`,borderRadius:"2px",background:h,color:l.color,boxSizing:"border-box",zIndex:"20"}),t.scrollDOM.appendChild(d),this.placeholderEditorEl=d;const u=()=>{const v=d.value;this.closePlaceholderEditor(),e(a,v)},k=()=>{this.closePlaceholderEditor()};if(d.addEventListener("keydown",v=>{const w=v.key;w==="Enter"?(v.preventDefault(),u()):w==="Escape"&&(v.preventDefault(),k())}),d.addEventListener("mousedown",v=>v.stopPropagation()),d.addEventListener("click",v=>v.stopPropagation()),a.fieldType==="dropdown"){d.addEventListener("change",()=>u());const v=this.workspace.getBlockById(a.blockId),w=v==null?void 0:v.getField(a.fieldName),b=w==null?void 0:w.getValue();b!=null&&(d.value=String(b)),requestAnimationFrame(()=>{this.placeholderEditorOutsideHandler=g=>{g.target instanceof Node&&!d.contains(g.target)&&k()},document.addEventListener("mousedown",this.placeholderEditorOutsideHandler)})}else d.addEventListener("blur",()=>u());this.placeholderEditorScrollHandler=()=>this.closePlaceholderEditor(),t.scrollDOM.addEventListener("scroll",this.placeholderEditorScrollHandler),requestAnimationFrame(()=>{d.focus({preventScroll:!0}),d instanceof HTMLInputElement&&d.select()})}async mount(){var b;if(to(),this.cm=await so(this.javascript),this.disposed)return;const{view:o,state:e,langJs:t}=this.cm;this.themeCompartment=new e.Compartment,this.syntaxHighlightCompartment=new e.Compartment;const n=Te(o,this.options.theme??{});this.themeSelection=((b=this.options.theme)==null?void 0:b.selectionBackground)??ne.selectionBackground;const s=je(o,e,this.options.highlightRules),r=e.StateEffect.define();this.metadataEffect=r;const c=e.StateEffect.define();this.placeholderEffect=c;const a=e.StateField.define({create(){return o.Decoration.none},update(g,y){for(const C of y.effects)if(C.is(c)){const E=C.value;if(!E||E.length===0)return o.Decoration.none;const f=y.state.doc.length,p=[...E].filter(B=>B.start<B.end&&B.end<=f).sort((B,D)=>B.start-D.start||B.end-D.end),S=new e.RangeSetBuilder,T=o.Decoration.mark({class:"morphic-placeholder-default"}),M=o.Decoration.mark({class:"morphic-placeholder-set"});for(const B of p)S.add(B.start,B.end,B.kind==="default"?T:M);return S.finish()}return y.changes.empty?g:o.Decoration.none},provide(g){return o.EditorView.decorations.from(g)}}),d=e.StateEffect.define();this.highlightEffect=d;const l=this,h=e.StateField.define({create(){return o.Decoration.none},update(g,y){for(const C of y.effects)if(C.is(d)){const E=C.value;if(!E)return o.Decoration.none;const f=Array.isArray(E)?E:[E];if(f.length===0)return o.Decoration.none;const p=y.state.doc,S=o.Decoration.mark({class:"morphic-highlight",attributes:{style:`background: ${l.highlightColor??ie(l.themeSelection,60)}`}}),T=f.map(M=>{const B=p.line(Math.min(M.fromLine,p.lines)).from,D=p.line(Math.min(M.toLine,p.lines)).to;return S.range(B,D)}).sort((M,B)=>M.from-B.from);return o.Decoration.set(T)}return y.changes.empty?g:o.Decoration.none},provide(g){return o.EditorView.decorations.from(g)}}),u=o.EditorView.updateListener.of(g=>{var f;if(g.docChanged||g.transactions.some(p=>p.isUserEvent("select.pointer")))return;const y=g.state.selection.main.head,C=g.startState.selection.main.head;if(y===C)return;if(l.findPlaceholderAtPos(y)){(f=l.onEmptyClick)==null||f.call(l);return}if(!l.onCursorLine)return;const E=g.state.doc.lineAt(y).number;l.onCursorLine(E)}),k=this.options.showPlaceholderMarkers!==!1,v=[o.lineNumbers(),o.highlightSpecialChars(),e.EditorState.readOnly.of(!0),...t?[t.javascript()]:[],h,...k?[a]:[],u,this.themeCompartment.of(n),this.syntaxHighlightCompartment.of(s),...this.buildDeleteExtensions(o,e,r),...this.buildGripExtensions(o,e,r),...this.buildDropIndicatorExtensions(o,e),...this.buildValueSlotHighlightExtensions(o,e),...this.buildHoverHighlightExtensions(o,e),...this.buildEditableHoverHighlightExtensions(o,e),...this.options.extensions??[]],w=this.generateWithMetadata();this.lastCode=w.code,this.metadata=w.metadata,this.placeholders=[...w.placeholders].sort((g,y)=>g.start-y.start),this.editorView=new o.EditorView({parent:this.container,state:e.EditorState.create({doc:this.lastCode,extensions:v})}),this.metadataEffect&&this.metadata.size>0&&this.editorView.dispatch({effects:this.metadataEffect.of(this.metadata)}),this.placeholderEffect&&w.placeholders.length>0&&this.editorView.dispatch({effects:this.placeholderEffect.of(w.placeholders)}),this.emptyClickListener=g=>{var C,E,f;if(this.isBelowLastLine(g.clientY)){(C=this.onEmptyClick)==null||C.call(this);return}const y=(E=this.editorView)==null?void 0:E.posAtCoords({x:g.clientX,y:g.clientY});if(typeof y=="number"){const p=this.findPlaceholderAtPos(y);if(p){(f=this.onEmptyClick)==null||f.call(this),p.edit&&this.options.onPlaceholderApply&&requestAnimationFrame(()=>this.openPlaceholderEditor(p));return}}if(this.onCursorLine){const p=this.getLineAtCoords(g.clientX,g.clientY);p!==null&&this.onCursorLine(p)}},this.editorView.scrollDOM.addEventListener("click",this.emptyClickListener),this.attachSyncListener()}buildDeleteExtensions(o,e,t){const n=this.options.onDelete;if(!n)return[];class s extends o.GutterMarker{toDOM(){const h=document.createElement("span");return h.textContent="✕",h.className="morphic-delete-marker",h.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(";"),h}}const r=new s,c=e.StateField.define({create(){return e.RangeSet.empty},update(l,h){for(const u of h.effects)if(u.is(t)){const k=u.value,v=h.state.doc,w=new Set;for(const{startLine:g}of k.values())g>=1&&g<=v.lines&&w.add(g);const b=Array.from(w).sort((g,y)=>g-y).map(g=>r.range(v.line(g).from));return e.RangeSet.of(b,!0)}return l.map(h.changes)}}),a=o.gutter({class:"morphic-delete-gutter",markers(l){return l.state.field(c)},initialSpacer:()=>r,domEventHandlers:{click(l,h){const u=l.state.doc.lineAt(h.from).number;return n(u),!0}}}),d=o.keymap.of([{key:"Delete",run:l=>{if(!l.state.selection.main.empty)return!1;const h=l.state.doc.lineAt(l.state.selection.main.head).number;return n(h),!0}},{key:"Backspace",run:l=>{if(!l.state.selection.main.empty)return!1;const h=l.state.doc.lineAt(l.state.selection.main.head).number;return n(h),!0}}]);return[c,a,e.Prec.highest(d)]}buildGripExtensions(o,e,t){const n=this.options.canDragBlock;if(!n)return[];class s extends o.GutterMarker{constructor(d){super(),this.blockId=d}eq(d){return d instanceof s&&d.blockId===this.blockId}toDOM(){const d=document.createElement("span");d.textContent="⠿",d.draggable=!0,d.className="morphic-grip-marker",d.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 l=this.blockId;return d.addEventListener("dragstart",h=>{h.dataTransfer&&(h.dataTransfer.setData(Se,l),h.dataTransfer.effectAllowed="move",d.style.cursor="grabbing",me=l)}),d.addEventListener("dragend",()=>{d.style.cursor="grab",me=void 0}),d}}const r=e.StateField.define({create(){return e.RangeSet.empty},update(a,d){for(const l of d.effects)if(l.is(t)){const h=l.value,u=d.state.doc,k=new Map;for(const[w,{startLine:b,startChar:g,endChar:y}]of h){if(b<1||b>u.lines||!n(w))continue;const C=(y??0)-(g??0),E=k.get(b);(!E||C>E.width)&&k.set(b,{id:w,width:C})}const v=Array.from(k.entries()).sort((w,b)=>w[0]-b[0]).map(([w,{id:b}])=>new s(b).range(u.line(w).from));return e.RangeSet.of(v,!0)}return a.map(d.changes)}}),c=o.gutter({class:"morphic-grip-gutter",markers(a){return a.state.field(r)},initialSpacer:()=>new s("")});return[r,c]}buildDropIndicatorExtensions(o,e){const t=e.StateEffect.define();this.dropIndicatorEffect=t;const n=e.StateField.define({create(){return o.Decoration.none},update(r,c){for(const a of c.effects)if(a.is(t)){const d=a.value;if(!d)return o.Decoration.none;const l=c.state.doc,h=Math.max(1,Math.min(d.line,l.lines)),u=l.line(h),k=d.position==="above"?"morphic-drop-indicator-above":"morphic-drop-indicator-below",v=o.Decoration.line({class:k});return o.Decoration.set([v.range(u.from)])}return c.changes.empty?r:o.Decoration.none},provide(r){return o.EditorView.decorations.from(r)}}),s=o.EditorView.baseTheme({".morphic-drop-indicator-above":{boxShadow:"inset 0 2px 0 0 #5a86bc"},".morphic-drop-indicator-below":{boxShadow:"inset 0 -2px 0 0 #5a86bc"}});return[n,s]}buildValueSlotHighlightExtensions(o,e){const t=e.StateEffect.define();this.valueSlotHighlightEffect=t;const n=o.Decoration.mark({class:"morphic-value-slot-target"}),s=e.StateField.define({create(){return o.Decoration.none},update(c,a){for(const d of a.effects)if(d.is(t)){const l=d.value;if(!l)return o.Decoration.none;const h=a.state.doc.length,u=Math.max(0,Math.min(l.from,h)),k=Math.max(u,Math.min(l.to,h));return u===k?o.Decoration.none:o.Decoration.set([n.range(u,k)])}return a.changes.empty?c:o.Decoration.none},provide(c){return o.EditorView.decorations.from(c)}}),r=o.EditorView.baseTheme({".morphic-value-slot-target":{outline:"1px solid #5a86bc",outlineOffset:"1px",borderRadius:"2px"}});return[s,r]}buildHoverHighlightExtensions(o,e){const t=e.StateEffect.define();this.hoverHighlightEffect=t;const n=o.Decoration.mark({class:"morphic-hover-target"}),s=e.StateField.define({create(){return o.Decoration.none},update(c,a){for(const d of a.effects)if(d.is(t)){const l=d.value;if(!l)return o.Decoration.none;const h=a.state.doc.length,u=Math.max(0,Math.min(l.from,h)),k=Math.max(u,Math.min(l.to,h));return u===k?o.Decoration.none:o.Decoration.set([n.range(u,k)])}return a.changes.empty?c:o.Decoration.none},provide(c){return o.EditorView.decorations.from(c)}}),r=o.EditorView.baseTheme({".morphic-hover-target":{backgroundColor:"rgba(127, 127, 127, 0.10)",borderRadius:"2px"}});return[s,r]}setHoverHighlight(o){!this.editorView||!this.hoverHighlightEffect||this.editorView.dispatch({effects:this.hoverHighlightEffect.of(o)})}buildEditableHoverHighlightExtensions(o,e){const t=e.StateEffect.define();this.editableHoverHighlightEffect=t;const n=o.Decoration.mark({class:"morphic-editable-hover"}),s=e.StateField.define({create(){return o.Decoration.none},update(c,a){for(const d of a.effects)if(d.is(t)){const l=d.value;if(!l)return o.Decoration.none;const h=a.state.doc.length,u=Math.max(0,Math.min(l.from,h)),k=Math.max(u,Math.min(l.to,h));return u===k?o.Decoration.none:o.Decoration.set([n.range(u,k)])}return a.changes.empty?c:o.Decoration.none},provide(c){return o.EditorView.decorations.from(c)}}),r=o.EditorView.baseTheme({".morphic-editable-hover":{outline:"1px solid #5a86bc",outlineOffset:"1px",borderRadius:"2px"}});return[s,r]}setEditableHoverHighlight(o){!this.editorView||!this.editableHoverHighlightEffect||this.editorView.dispatch({effects:this.editableHoverHighlightEffect.of(o)})}show(){this.visible||(this.visible=!0,this.container.style.display="",this.syncNow(),this.attachSyncListener())}hide(){this.visible&&(this.visible=!1,this.container.style.display="none",this.detachSyncListener())}isVisible(){return this.visible}highlightLines(o){!this.editorView||!this.highlightEffect||(this.activeHighlight=o,this.editorView.dispatch({effects:this.highlightEffect.of(o)}))}clearHighlight(){!this.editorView||!this.highlightEffect||(this.activeHighlight=void 0,this.editorView.dispatch({effects:this.highlightEffect.of(null)}))}setHighlightColor(o){this.highlightColor=o,this.activeHighlight&&this.highlightLines(this.activeHighlight)}showDropIndicator(o,e="above"){!this.editorView||!this.dropIndicatorEffect||this.editorView.dispatch({effects:this.dropIndicatorEffect.of({line:o,position:e})})}hideDropIndicator(){!this.editorView||!this.dropIndicatorEffect||this.editorView.dispatch({effects:this.dropIndicatorEffect.of(null)})}showValueSlotHighlight(o,e){!this.editorView||!this.valueSlotHighlightEffect||this.editorView.dispatch({effects:this.valueSlotHighlightEffect.of({from:o,to:e})})}hideValueSlotHighlight(){!this.editorView||!this.valueSlotHighlightEffect||this.editorView.dispatch({effects:this.valueSlotHighlightEffect.of(null)})}getLineAtCoords(o,e){if(!this.editorView)return null;const t=this.editorView.posAtCoords({x:o,y:e});return t===null?null:this.editorView.state.doc.lineAt(t).number}charAtCoords(o,e){return this.editorView?this.editorView.posAtCoords({x:o,y:e})??null:null}getLineCount(){var o;return((o=this.editorView)==null?void 0:o.state.doc.lines)??0}isBelowLastLine(o){if(!this.editorView)return!1;const e=this.editorView.state.doc,t=e.line(e.lines).to,n=this.editorView.coordsAtPos(t);return n?o>n.bottom:!1}isInLowerHalfOfLine(o,e){if(!this.editorView)return!1;const t=this.editorView.state.doc;if(o<1||o>t.lines)return!1;const n=t.line(o),s=this.editorView.coordsAtPos(n.from),r=this.editorView.coordsAtPos(n.to);return!s||!r?!1:e>(s.top+r.bottom)/2}setTheme(o){if(!this.editorView||!this.cm||!this.themeCompartment)return;this.themeSelection=o.selectionBackground??ne.selectionBackground,this.activeHighlight&&this.highlightLines(this.activeHighlight);const e=Te(this.cm.view,o);this.editorView.dispatch({effects:this.themeCompartment.reconfigure(e)})}setHighlightRules(o){if(!this.editorView||!this.cm||!this.syntaxHighlightCompartment)return;const e=je(this.cm.view,this.cm.state,o);this.editorView.dispatch({effects:this.syntaxHighlightCompartment.reconfigure(e)})}dispose(){var o;this.disposed=!0,this.detachSyncListener(),this.syncTimer!==void 0&&(clearTimeout(this.syncTimer),this.syncTimer=void 0),this.emptyClickListener&&this.editorView&&(this.editorView.scrollDOM.removeEventListener("click",this.emptyClickListener),this.emptyClickListener=void 0),(o=this.editorView)==null||o.destroy(),this.editorView=void 0,this.metadata=new Map,this.placeholders=[],this.lastCode=""}refresh(){this.syncNow()}getValue(){var o;return((o=this.editorView)==null?void 0:o.state.doc.toString())??this.lastCode??""}getCursorLine(){if(!this.editorView)return 1;const o=this.editorView.state.selection.main.head;return this.editorView.state.doc.lineAt(o).number}adjustZoom(o){if(!this.editorView||!this.cm||!this.themeCompartment)return;const e=this.options.theme??{},t=parseFloat(e.fontSize??ne.fontSize);o==="fit"?this.zoomFactor=1:o==="in"?this.zoomFactor=Math.min(4,this.zoomFactor*1.2):this.zoomFactor=Math.max(.25,this.zoomFactor/1.2);const n={...e,fontSize:`${(t*this.zoomFactor).toFixed(2)}px`},s=Te(this.cm.view,n);this.editorView.dispatch({effects:this.themeCompartment.reconfigure(s)})}syncNow(){if(!this.editorView||!this.cm)return;const o=this.generateWithMetadata();if(o.code===this.lastCode)return;this.closePlaceholderEditor(),this.lastCode=o.code,this.metadata=o.metadata,this.placeholders=[...o.placeholders].sort((t,n)=>t.start-n.start);const e=[];this.metadataEffect&&e.push(this.metadataEffect.of(o.metadata)),this.placeholderEffect&&e.push(this.placeholderEffect.of(o.placeholders)),this.editorView.dispatch({changes:{from:0,to:this.editorView.state.doc.length,insert:o.code},effects:e.length>0?e:void 0})}scheduleDebouncedSync(){this.syncTimer!==void 0&&clearTimeout(this.syncTimer),this.syncTimer=setTimeout(()=>{this.syncTimer=void 0,this.syncNow()},oo)}attachSyncListener(){this.changeListener||(this.changeListener=o=>{io(o)&&this.scheduleDebouncedSync()},this.workspace.addChangeListener(this.changeListener))}detachSyncListener(){this.changeListener&&(this.workspace.removeChangeListener(this.changeListener),this.changeListener=void 0,this.syncTimer!==void 0&&(clearTimeout(this.syncTimer),this.syncTimer=void 0))}}const Le="morphic:";function Me(i){return Le+i}function W(i){return i.startsWith(Le)?i.slice(Le.length):i}function U(i,o){return o.has(i)?Me(i):i}function ro(i,o,e,t){const n={behaviors:e,definitions:o};return Ke(J.javascriptGenerator,n,t,!1),J.javascriptGenerator.workspaceToCode(i)}function co(i,o,e,t){const n={behaviors:e,definitions:o};Ke(J.javascriptGenerator,n,t,!0);const s=J.javascriptGenerator.workspaceToCode(i);return bo(s)}const ao="// __MORPHIC_BLOCK_START:",lo="// __MORPHIC_BLOCK_END:",Ye="__";function Ke(i,o,e,t=!1){i.STATEMENT_PREFIX=(e==null?void 0:e.statementPrefix)??null,i.STATEMENT_SUFFIX=(e==null?void 0:e.statementSuffix)??null,i.INFINITE_LOOP_TRAP=(e==null?void 0:e.infiniteLoopTrap)??null,e!=null&&e.reservedWords&&i.addReservedWords(e.reservedWords);for(const[n,s]of o.definitions){const r=Ct(o.behaviors[n]);i.forBlock[Me(n)]=(c,a)=>{const d=ho(c,a),l=r?r(d):wo(n,s);if(mo(c,s))return[ko(l),J.Order.NONE];const h=go(l);return t?`${ao}${c.id}${Ye}
|
|
4
|
+
${h}${lo}${c.id}${Ye}
|
|
5
|
+
`:h}}}function ho(i,o){var c;const e={},t={},n={},s=i.workspace.isFlyout?"toolbox":"workspace",r=qe(i)>=2;for(const a of i.inputList){const d=(c=a.connection)==null?void 0:c.targetBlock();if(d)if(d.outputConnection){const l=o.valueToCode(i,a.name,J.Order.NONE)||"undefined";e[a.name]=r?uo(l,d):l}else e[a.name]=o.statementToCode(i,a.name).trimEnd();for(const l of a.fieldRow){if(!l.name)continue;const h=String(l.getValue()??"");t[l.name]=h,n[l.name]=JSON.stringify(h)}}return{blockId:i.id,blockType:W(i.type),mode:Ot(i)??"default",context:s,inputs:e,fields:t,quoted:n}}function uo(i,o){return!fo(o)||po(i)?i:`(${i})`}function fo(i){return qe(i)>0}function qe(i){return i.inputList.filter(o=>{var e;return((e=o.connection)==null?void 0:e.type)===x.INPUT_VALUE}).length}function po(i){if(!i.startsWith("(")||!i.endsWith(")"))return!1;let o=0;for(let e=0;e<i.length;e++){const t=i[e];if(t==="(")o++;else if(t===")"&&(o--,o===0))return e===i.length-1}return!1}function mo(i,o){return i.outputConnection?!0:o.output===!1?!1:o.output!==void 0}function go(i){const o=i.trim();return o?o.endsWith(";")||o.endsWith("}")||o.endsWith(`
|
|
6
|
+
`)?`${o}
|
|
7
|
+
`:`${o};
|
|
8
|
+
`:""}function ko(i){const o=i.trim();return o?o.endsWith(";")?o.slice(0,-1):o:"undefined"}function wo(i,o){return o.output!==void 0&&o.output!==!1?"undefined":`// No generator behavior defined for "${i}"`}const vo=/^\s*\/\/ __MORPHIC_BLOCK_START:(.+)__$/,yo=/^\s*\/\/ __MORPHIC_BLOCK_END:(.+)__$/;function bo(i){const o=i.split(`
|
|
9
|
+
`),e=[],t=new Map,n=new Map;let s=0;for(const r of o){const c=r.match(vo);if(c){n.set(c[1],s+1);continue}const a=r.match(yo);if(a){const d=a[1],l=n.get(d);l!==void 0&&(t.set(d,{startLine:l,endLine:s}),n.delete(d));continue}e.push(r),s++}return{code:e.join(`
|
|
10
|
+
`),metadata:t,placeholders:[]}}function X(i,o={}){for(const e of i.elements)if(j(o[e])==="code")return e}function Be(i,o,e={},t=[]){const n=i.elements,s=t.find(c=>c.name===o);if(s){for(const c of s.elements)if(j(e[c])==="code"&&n[c]!==void 0)return{mode:o,template:n[c],elementName:c,inputSlots:i.inputSlots}}for(const[c,a]of Object.entries(n))if(j(e[c])==="code")return{mode:o,template:a,elementName:c,inputSlots:i.inputSlots};if(n.block!==void 0)return{mode:o,template:n.block,elementName:"block",inputSlots:i.inputSlots};const r=Object.entries(n)[0];if(r===void 0)throw new Error(`Block "${i.identifier}" does not have any elements.`);return{mode:o,template:r[1],elementName:r[0],inputSlots:i.inputSlots}}function z(i,o){if(o.length===0)return;if(i.indent===""||!o.includes(`
|
|
11
|
+
`)){i.output+=o;return}const e=o.split(`
|
|
12
|
+
`);i.output+=e[0];for(let t=1;t<e.length;t++)i.output+=`
|
|
13
|
+
`+i.indent+e[t]}function ke(i,o,e,t,n,s,r={}){const c={output:"",metadata:new Map,placeholders:[],indent:""},a={mode:o,definitions:e,elementTypes:t,modeDefs:n,elementOverride:s,emptyStatements:r.emptyStatements!==!1};let d=!0;for(const l of i.getTopBlocks(!0)){const h=c.output.length;d||(c.output+=`
|
|
14
|
+
`),Je(l,a,c),c.output.length===h+(d?0:1)?c.output=c.output.slice(0,h):d=!1}return{code:c.output,metadata:c.metadata,placeholders:c.placeholders}}function Je(i,o,e){const t=1+e.indent.length;let n=i,s=!0;for(;n;){const r=e.output.length;s||z(e,`
|
|
15
|
+
`),Ie(n,o,e),e.output.length===r+(s?0:t)?e.output=e.output.slice(0,r):s=!1,n=n.getNextBlock()}}function Ze(i){return i.inputList.some(o=>{var e;return((e=o.connection)==null?void 0:e.type)===x.INPUT_VALUE})}function Co(i,o){var t;let e=0;for(const n of i){if(n.kind!=="placeholder")continue;const s=(t=o.inputSlots)==null?void 0:t[String(n.index)];((s==null?void 0:s.kind)??"value")==="value"&&e++}return e}function Ie(i,o,e,t=!1){var y,C,E;const n=o.definitions.get(W(i.type));if(!n){const f=e.output.length,p=oe(e.output);if(Eo(i,e),e.output.length===f)return;const S=oe(e.output),T=e.output.endsWith(`
|
|
16
|
+
`)?Math.max(p,S-1):S;let M=e.output.length;for(;M>f&&e.output[M-1]===`
|
|
17
|
+
`;)M--;const B=we(i);e.metadata.set(i.id,{startLine:p,endLine:T,startChar:f,endChar:M,atomic:!!B}),Y(e,f,"set",B??void 0);return}let s,r;if(o.elementOverride){const f=n.elements[o.elementOverride];if(f===void 0)return;s=f,r=o.elementOverride}else try{const f=Be(n,o.mode,o.elementTypes,o.modeDefs);s=f.template,r=f.elementName}catch{return}const c=r?o.elementTypes[r]:void 0,a=e.output.length;t&&z(e,"(");const d=e.output.length,l=oe(e.output),h={},u=ee(s),k=Co(u,n)>=2;for(const f of u){if(f.kind==="text"){z(e,f.value);continue}if(f.kind==="field"){const $=i.getField(f.name);if(!$)continue;const O=e.output.length;z(e,et(n,r,f.name,$));const L=De(Qe(i,$,f.name),i,o);L&&Y(e,O,"set",L);continue}if(f.kind==="image")continue;const p=(y=n.inputSlots)==null?void 0:y[String(f.index)],S=p==null?void 0:p.name;if(!S)continue;const T=i.getInput(S),M=((C=T==null?void 0:T.connection)==null?void 0:C.targetBlock())??null,B=M!=null&&M.isShadow()?null:M;if((p==null?void 0:p.kind)==="statement"){const $=oe(e.output),O=e.indent,L=e.output.lastIndexOf(`
|
|
18
|
+
`)+1;if(e.indent=((E=/^[ \t]*/.exec(e.output.slice(L)))==null?void 0:E[0])??"",B)Je(B,o,e);else{const F=o.emptyStatements&&typeof c=="object"?c.emptyStatement:void 0;if(F){const R=e.output.length;z(e,F),Y(e,R,"default")}}e.indent=O;const I=oe(e.output),H=e.output.endsWith(`
|
|
19
|
+
`)?Math.max($,I-1):I;h[S]={startLine:$,endLine:H};continue}let D=!1;if(!B&&M&&o.definitions.has(W(M.type))){const $=e.output.length,O=e.placeholders.length;Ie(M,o,e,k&&Ze(M));for(const L of M.getDescendants(!1))e.metadata.delete(L.id);if(e.output.length>$){const L=e.placeholders.splice(O);for(const I of L)e.placeholders.push({...I,kind:"default"});L.length===0&&Y(e,$,"default");continue}}if(!B){const $=M!=null&&M.isShadow()?M.inputList.flatMap(R=>R.fieldRow).filter(R=>!!R.name):[],O=!(M!=null&&M.isShadow())&&T?T.fieldRow.filter(R=>{var G;return!!R.name&&!((G=n.fields)!=null&&G[R.name])}):[],L=$.length>0||O.length>0,I=L?xo(p,c):void 0;I&&z(e,I);const H=e.output.length;if($.length>0){const R=M?o.definitions.get(W(M.type)):void 0;for(const G of $)z(e,R&&G.name?et(R,r,G.name,G):ve(G))}else if(O.length>0)for(const R of O){const G=e.output.length;z(e,ve(R));const yt=Qe(i,R,R.name);yt&&(Y(e,G,"set",yt),D=!0)}let F;if(L||(z(e,So(p==null?void 0:p.check)),F={parentBlockId:i.id,inputName:S}),!D){const R=M!=null&&M.isShadow()?De(we(M),M,o)??void 0:void 0;Y(e,H,"default",R,F)}I&&z(e,I);continue}const P=e.output.length;Ie(B,o,e,k&&Ze(B)),Y(e,P,"set",De(we(B),B,o)??void 0)}if(e.output.length===d){e.output=e.output.slice(0,a);return}t&&z(e,")");const v=oe(e.output),w=e.output.endsWith(`
|
|
20
|
+
`)?Math.max(l,v-1):v;let b=e.output.length;for(;b>a&&e.output[b-1]===`
|
|
21
|
+
`;)b--;const g={startLine:l,endLine:w,startChar:a,endChar:b};Object.keys(h).length>0&&(g.statementSlots=h),we(i)&&(g.atomic=!0),e.metadata.set(i.id,g)}function Eo(i,o){for(const e of i.inputList)for(const t of e.fieldRow)t.name&&z(o,ve(t))}function Y(i,o,e,t,n){const s=i.output.length;if(s>o){const r={start:o,end:s,kind:e};t&&(r.edit=t),n&&(r.emptySlot=n),i.placeholders.push(r)}}function So(i){const o=Array.isArray(i)?i[0]:i;return o?`[${{Number:"NUMBER",String:"TEXT",Boolean:"BOOL"}[o]??o.toUpperCase()}]`:"[VALUE]"}function xo(i,o){if(!(!(i!=null&&i.check)||(Array.isArray(i.check)?i.check[0]:i.check)!=="String")&&!(!o||typeof o=="string"))return o.stringQuote}function Qe(i,o,e){let t,n;if(o instanceof x.FieldNumber)t="number";else if(o instanceof x.FieldDropdown){t="dropdown";const s=o.getOptions();Array.isArray(s)&&(n=s.filter(r=>Array.isArray(r)&&r.length>=2).map(([r,c])=>[String(r),String(c)]))}else if(o instanceof x.FieldTextInput)t="text";else return null;return{blockId:i.id,fieldName:e,fieldType:t,options:n}}function De(i,o,e){var c;if(!(i!=null&&i.options))return i;const t=e.definitions.get(W(o.type)),n=(c=t==null?void 0:t.fields)==null?void 0:c[i.fieldName];if(!t||(n==null?void 0:n.type)!=="dropdown")return i;let s=e.elementOverride;if(!s)try{s=Be(t,e.mode,e.elementTypes,e.modeDefs).elementName}catch{return i}const r=a=>{var d;for(const l of n.options)if(typeof l=="object"&&!Array.isArray(l)&&l.value===a)return(s&&((d=l.display)==null?void 0:d[s]))??a;return a};return{...i,options:i.options.map(([,a])=>[r(a),a])}}function we(i){let o=null,e=null,t=0;for(const c of i.inputList){if(c.connection&&c.connection.type===x.INPUT_VALUE)return null;for(const a of c.fieldRow)a.name&&(t++,o=a.name,e=a)}if(t!==1||!o||!e)return null;const n=e.constructor.name;let s="text",r;if(n.includes("Number"))s="number";else if(n.includes("Dropdown")){s="dropdown";const c=e.getOptions;if(typeof c=="function"){const a=c.call(e);Array.isArray(a)&&(r=a.filter(d=>Array.isArray(d)&&d.length>=2).map(([d,l])=>[String(d),String(l)]))}}return{blockId:i.id,fieldName:o,fieldType:s,options:r}}function et(i,o,e,t){var s,r;const n=(s=i.fields)==null?void 0:s[e];if((n==null?void 0:n.type)==="dropdown"&&o){const c=String(t.getValue());for(const a of n.options)if(!(typeof a!="object"||Array.isArray(a))&&a.value===c)return((r=a.display)==null?void 0:r[o])??c}return ve(t)}function ve(i){if(!i)return"";if(i instanceof x.FieldDropdown)return String(i.getValue());const o=i.getText;return typeof o=="function"?o.call(i):String(i.getValue())}function oe(i){let o=1;for(let e=0;e<i.length;e++)i[e]===`
|
|
22
|
+
`&&o++;return o}class To{constructor(o,e,t={}){m(this,"workspace");m(this,"editors");m(this,"blockToCode");m(this,"codeToBlock");m(this,"blockListener");m(this,"cursorCallbacks",new Map);m(this,"emptyClickCallbacks",new Map);m(this,"guard",!1);this.workspace=o,this.editors=Array.isArray(e)?[...e]:[e],this.blockToCode=t.blockToCode!==!1,this.codeToBlock=t.codeToBlock!==!1;for(const n of this.editors)n.setHighlightColor(t.highlightColor)}enable(){this.blockToCode&&this.attachBlockListener(),this.codeToBlock&&this.attachCursorListeners()}disable(){this.detachBlockListener(),this.detachCursorListeners();for(const o of this.editors)o.clearHighlight()}attachBlockListener(){this.blockListener||(this.blockListener=o=>{if(o.type!=="selected"||this.guard)return;const e=o.newElementId??void 0;this.guard=!0,this.broadcastHighlight(e),this.guard=!1},this.workspace.addChangeListener(this.blockListener))}detachBlockListener(){this.blockListener&&(this.workspace.removeChangeListener(this.blockListener),this.blockListener=void 0)}broadcastHighlight(o){for(const e of this.editors){if(!o){e.clearHighlight();continue}const t=this.computeOwnSpans(o,e.metadata);t?e.highlightLines(t):e.clearHighlight()}}attachCursorListeners(){for(const o of this.editors){if(!this.cursorCallbacks.has(o)){const e=t=>{if(this.guard)return;const n=this.findBlockAtLine(t,o.metadata);if(!n){this.clearAll();return}const s=this.workspace.getBlockById(n);s&&x.common.getSelected()!==s&&(this.guard=!0,x.common.setSelected(s),this.broadcastHighlight(n),this.guard=!1)};this.cursorCallbacks.set(o,e),o.onCursorLine=e}if(!this.emptyClickCallbacks.has(o)){const e=()=>{this.guard||this.clearAll()};this.emptyClickCallbacks.set(o,e),o.onEmptyClick=e}}}detachCursorListeners(){for(const[o,e]of this.cursorCallbacks)o.onCursorLine===e&&(o.onCursorLine=void 0);this.cursorCallbacks.clear();for(const[o,e]of this.emptyClickCallbacks)o.onEmptyClick===e&&(o.onEmptyClick=void 0);this.emptyClickCallbacks.clear()}clearAll(){this.guard=!0,x.common.setSelected(null);for(const o of this.editors)o.clearHighlight();this.guard=!1}computeOwnSpans(o,e){const t=e.get(o);if(!t)return;const n=[];for(const[c,a]of e)c!==o&&a.startLine>=t.startLine&&a.endLine<=t.endLine&&n.push(a);if(n.length===0)return[{fromLine:t.startLine,toLine:t.endLine}];n.sort((c,a)=>c.startLine-a.startLine);const s=[];let r=t.startLine;for(const c of n)r<c.startLine&&s.push({fromLine:r,toLine:c.startLine-1}),r=Math.max(r,c.endLine+1);return r<=t.endLine&&s.push({fromLine:r,toLine:t.endLine}),s.length>0?s:void 0}findBlockAtLine(o,e){let t;for(const[n,s]of e)if(o>=s.startLine&&o<=s.endLine){const r=s.endLine-s.startLine;(!t||r<t.size)&&(t={id:n,size:r})}return t==null?void 0:t.id}}const tt={statement:{above:!0,below:!0},start:{above:!1,below:!0},end:{above:!0,below:!1},standalone:{above:!1,below:!1}},ot=Object.keys(tt);function Lo(i){return i.map(o=>{const e=o.shape?tt[o.shape]:void 0;if(!e)return o;const t={...o};return e.above&&t.previousStatement===void 0&&(t.previousStatement=!0),e.below&&t.nextStatement===void 0&&(t.nextStatement=!0),t})}const ye="default";function Mo(i,o){const e=Object.keys(o).filter(t=>j(o[t])==="code");return i.map(t=>{var a;const n=(a=t.elements)==null?void 0:a[ye];if(n===void 0||e.length===0)return t;const{[ye]:s,...r}=t.elements,c={...r};for(const d of e)c[d]===void 0&&(c[d]=n);return{...t,elements:c}})}function Bo(i){const o=new Map,e=Array.isArray(i)?i:[i];for(const t of e)Io(t,o),o.set(t.identifier,t);return o}function Io(i,o){if(!i.identifier.trim())throw new Error("Each block definition must include a non-empty identifier.");if(Object.keys(i.elements).length===0)throw new Error(`Block "${i.identifier}" must define at least one element.`);if(o.has(i.identifier))throw new Error(`Duplicate block identifier "${i.identifier}".`)}const Do=4/3,Ao={normal:"400",bold:"700"},nt=i=>Ao[i]??i;function Oo(i){const o=parseFloat(i);if(!Number.isFinite(o)||o<=0)return;const e=i.trim().endsWith("pt")?o:o/Do;return Math.round(e*100)/100}function it(i){const o=i.getRenderer().getConstants();return{family:o.FIELD_TEXT_FONTFAMILY,size:o.FIELD_TEXT_FONTSIZE,weight:nt(o.FIELD_TEXT_FONTWEIGHT)}}function st(i,o,e){const t=document.createElement("div");t.setAttribute("aria-hidden","true"),t.style.cssText="position:absolute;visibility:hidden;width:0;height:0;overflow:hidden;";let n=t;for(const d of o){const l=document.createElement("div");l.className=d.join(" "),n.appendChild(l),n=l}const s=document.createElementNS("http://www.w3.org/2000/svg","svg"),r=document.createElementNS("http://www.w3.org/2000/svg","text");r.setAttribute("class","blocklyText"),s.appendChild(r),n.appendChild(s),i.appendChild(t);const c=getComputedStyle(r),a={family:c.fontFamily||e.family,size:Oo(c.fontSize)??e.size,weight:c.fontWeight?nt(c.fontWeight):e.weight};return t.remove(),a}const $o=(i,o)=>i.family===o.family&&i.size===o.size&&i.weight===o.weight,Ae=new Map;function No(i,o){const e=`${i.name}
|
|
23
|
+
${o.family}
|
|
24
|
+
${o.size}
|
|
25
|
+
${o.weight}`;let t=Ae.get(e);if(!t){const n=`${i.name}-morphic-font-${Ae.size+1}`;t=x.Theme.defineTheme(n,{name:n,base:i,fontStyle:{family:o.family,size:o.size,weight:o.weight},...i.startHats!==void 0&&{startHats:i.startHats}}),Ae.set(e,t)}return t}function rt(i,o,e,t){const n=$o(t,e)?o:No(o,t);return i.getTheme()===n?!1:(i.setTheme(n),!0)}function Oe(i){for(const o of i.getAllBlocks(!1)){o.markDirty();for(const e of o.inputList)for(const t of e.fieldRow)t.getConstants()}i.render()}function ct(i){var g,y,C,E;const{definitions:o,elementTypes:e,behaviors:t,modes:n,presets:s,code:r,categories:c}=i,a=[],d=[],l=new Set(Object.keys(e)),h=new Set(Object.keys(e).filter(f=>j(e[f])==="code")),u=new Set((c??[]).map(f=>f.name));l.has(ye)&&a.push(`elementTypes declares "${ye}", which is reserved for a block's fallback template. Rename the element.`);const k=f=>o.has(f)||x.Blocks[f]!==void 0;for(const f of o.values()){const p=f.identifier;if(f.shape!==void 0)if(!ot.includes(f.shape))a.push(`Block "${p}": unknown shape "${f.shape}". Use one of: ${ot.join(", ")}.`);else{const L=H=>H!==void 0&&H!==!1,I=[];L(f.output)&&I.push("it also has an output, which makes it a value block"),(f.shape==="start"||f.shape==="standalone")&&L(f.previousStatement)&&I.push("it also connects above (previousStatement)"),(f.shape==="end"||f.shape==="standalone")&&L(f.nextStatement)&&I.push("it also connects below (nextStatement)"),f.shape==="statement"&&(f.previousStatement===!1||f.nextStatement===!1)&&I.push("a connection flag is set to false");for(const H of I)d.push(`Block "${p}": shape "${f.shape}" contradicts its flags: ${H}. The flags win.`)}const S=ce(t[p]),T=!!(S!=null&&S.onViewApplied);for(const L of Object.keys(f.elements))l.has(L)||d.push(`Block "${p}": element "${L}" is not declared in elementTypes — it renders with no known type.`);const M=new Map,B=new Set,D=new Set;for(const[L,I]of Object.entries(f.elements)){if(!h.has(L))continue;const H=new Set;for(const F of ee(I))F.kind==="placeholder"?(H.add(F.index),B.add(F.index)):F.kind==="field"&&D.add(F.name);M.set(L,H)}const P=[...M.entries()];if(P.length>1){const[L,I]=P[0];for(const[H,F]of P.slice(1))Ho(I,F)||a.push(`Block "${p}": code elements "${L}" and "${H}" use different placeholders (${ht(I)} vs ${ht(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(f.inputSlots??{}).map(L=>Number(L)).filter(L=>Number.isInteger(L)));for(const L of B)(g=f.inputSlots)!=null&&g[String(L)]||d.push(`Block "${p}": placeholder %${L} has no inputSlots["${L}"] entry — the input is auto-named ARG${L} and can't be read by name in behaviors.`);for(const L of $)B.has(L)||d.push(`Block "${p}": inputSlots["${L}"] has no matching %${L} placeholder in any code element — the config is ignored.`);const O=new Set(Object.keys(f.fields??{}));for(const L of D)!((y=f.fields)!=null&&y[L])&&!T&&a.push(`Block "${p}": field token %${L} has no fields["${L}"] entry and the block has no onViewApplied behavior to create it — the field will never appear.`);for(const L of O)D.has(L)||d.push(`Block "${p}": fields["${L}"] has no matching %${L} token in any code element — the config is ignored.`);for(const[L,I]of Object.entries(f.fields??{}))if((I==null?void 0:I.type)==="dropdown"){for(const H of I.options)if(!(typeof H!="object"||Array.isArray(H)||!H.display))for(const F of Object.keys(H.display))h.has(F)||d.push(`Block "${p}": fields["${L}"] option "${H.value}" has display for "${F}", which is not a code element — that entry never applies.`)}f.category!==void 0&&u.size>0&&!u.has(f.category)&&d.push(`Block "${p}": category "${f.category}" is not declared in categories — the block loses its colour and grouping.`);for(const[L,I]of Object.entries(f.inputSlots??{}))(I==null?void 0:I.kind)!==void 0&&!lt.includes(I.kind)&&a.push(`Block "${p}": inputSlots["${L}"] has unknown kind "${I.kind}". Use one of: ${lt.join(", ")}.`);for(const[L,I]of Object.entries(f.fields??{}))dt.includes(I==null?void 0:I.type)||a.push(`Block "${p}": fields["${L}"] has unknown type "${I==null?void 0:I.type}". Use one of: ${dt.join(", ")}.`);for(const[L,I]of Object.entries(f.inputSlots??{}))b((C=I==null?void 0:I.default)==null?void 0:C.shadow,`Block "${p}": inputSlots["${L}"].default.shadow`),b((E=I==null?void 0:I.default)==null?void 0:E.placeholder,`Block "${p}": inputSlots["${L}"].default.placeholder`)}for(const[f,p]of Object.entries(e)){const S=j(p);at.includes(S)||a.push(`elementTypes."${f}": unknown type "${S}". Use one of: ${at.join(", ")}.`)}for(const[f,p]of Object.entries(r??{}))for(const[S,T]of Object.entries(p.empty??{}))b(T.shadow,`code.${f}.empty.${S}.shadow`),b(T.placeholder,`code.${f}.empty.${S}.placeholder`);for(const[f,p]of Object.entries(e)){if(typeof p=="string")continue;const S=p.type;p.size!==void 0&&S!=="image"&&d.push(`elementTypes."${f}": "size" applies only to image elements — ignored for a ${S} element.`);for(const T of["empty","stringQuote"])T in p&&a.push(`elementTypes."${f}": "${T}" moved into the "code" section: "code": { "${f}": { "${T}": … } }.`)}for(const f of n??[])for(const p of f.elements)l.has(p)||d.push(`Mode "${f.name}": element "${p}" is not declared in elementTypes — it renders nothing.`);for(const f of Object.keys(r??{}))h.has(f)||d.push(`code["${f}"] is not a code element — its settings will never apply.`);const v=new Map,w=(f,p)=>{const S=v.get(f)??new Set;S.add(p),v.set(f,S)};for(const f of l)w(f,"element");for(const f of n??[])w(f.name,"mode");for(const f of s??[])w(f.name,"preset");for(const[f,p]of v)p.size>1&&d.push(`Name "${f}" is used as ${[...p].sort().join(" and ")} — reusing a name across element / mode / preset is allowed but confusing; consider distinct names.`);return{errors:a,warnings:d};function b(f,p){!f||k(f)||a.push(`${p}: "${f}" is neither a defined block nor a registered Blockly block type.`)}}const at=["text","code","image"],lt=["value","statement"],dt=["dropdown","text","number","checkbox"];function Ho(i,o){if(i.size!==o.size)return!1;for(const e of i)if(!o.has(e))return!1;return!0}function ht(i){const o=[...i].sort((e,t)=>e-t);return o.length?o.map(e=>`%${e}`).join(" "):"(none)"}function ut(i,o,e=!1){var t;if(!o)return String(i);if(typeof i=="string"){const n=e?(t=o.list)==null?void 0:t.quote:void 0;return n?`${n}${i}${n}`:i}if(typeof i=="boolean")return(i?o.true:o.false)??String(i);if(i===null)return o.null??"null";if(i===void 0)return o.undefined??"undefined";if(typeof i=="number")return Number.isNaN(i)?o.NaN??"NaN":i===1/0?o.Infinity??"Infinity":i===-1/0?o["-Infinity"]??"-Infinity":String(i);if(Array.isArray(i)&&o.list){const{open:n="[",close:s="]",separator:r=", "}=o.list;return`${n}${i.map(c=>ut(c,o,!0)).join(r)}${s}`}return String(i)}class Po{ensureModeVisibilityStyles(o,e){const t=ft(o);if(e){const n=ft(e);for(const s of Array.from(document.head.querySelectorAll("style[data-morphic-source]")))if(s.dataset.morphicSource==="mode-visibility"&&s.textContent===n){s.textContent=t;return}}K("mode-visibility",t)}ensureStyles(o,e){this.ensureStyleBundle(o,"base");for(const t of e)this.ensureStyleBundle(t,`mode:${t.mode}`)}async ensureToolbarStyles(){const o=await Promise.resolve().then(()=>mn);K("toolbar",o.default)}ensureWorkspaceStyles(){K("workspace",[".morphic-workspace-root .blocklyMainBackground {"," stroke: var(--morphic-workspace-border-color, transparent);"," stroke-width: var(--morphic-workspace-border-width, 1px);","}"].join(`
|
|
26
|
+
`))}ensureCategoryStyles(o){for(const e of o){if(!e.color)continue;const t=V(e.name);K(`category:${t}`,`.morphic-category-${t} { --morphic-category-color: ${e.color}; }`)}}validateModeCoverage(o,e,t=console.warn){const n=new Set(o.map(r=>r.mode)),s=e.filter(r=>!n.has(r));s.length>0&&t(`[MorphicBlocks] Modes without explicit CSS definition: ${s.join(", ")}.`)}ensureStyleBundle(o,e){o&&(o.href&&Vo(e,o.href),o.cssText&&K(e,o.cssText))}}function Fo(i,o={}){const e=`.morphic-block .morphic-element-${V(i)}`;K(`tile-highlight:${i}`,[`${e} .morphic-tok-keyword { color: ${o.keyword??"#cc7832"}; }`,`${e} .morphic-tok-string { color: ${o.string??"#6a8759"}; }`,`${e} .morphic-tok-number { color: ${o.number??"#6897bb"}; }`,`${e} .morphic-tok-comment { color: ${o.comment??"#808080"}; font-style: italic; }`].join(`
|
|
27
|
+
`))}function Ro(){K("tile-touch",".morphic-block[data-block-type] { touch-action: pan-y; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; }")}function ft(i){const o=['[class^="morphic-element-"] { display: none; }'];for(const e of i){const t=V(e.name);for(const n of e.elements){const s=V(n);o.push(`.morphic-mode-${t} > .morphic-element-${s} { display: block; }`)}}return o.join(`
|
|
28
|
+
`)}function K(i,o){for(const t of Array.from(document.head.querySelectorAll("style[data-morphic-source]")))if(t.dataset.morphicSource===i&&t.textContent===o)return;const e=document.createElement("style");e.dataset.morphicSource=i,e.textContent=o,document.head.appendChild(e)}function Vo(i,o){for(const t of Array.from(document.head.querySelectorAll("link[data-morphic-source]")))if(t.getAttribute("href")===o)return;const e=document.createElement("link");e.rel="stylesheet",e.href=o,e.dataset.morphicSource=i,document.head.appendChild(e)}const se="morphic/block-type",_o=8,Wo=350;function zo(i,o){const e=Ue(o),t=n=>n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");return i.split(`
|
|
29
|
+
`).map(n=>{let s="",r=0;for(const c of e(n))s+=t(n.slice(r,c.from)),s+=`<span class="morphic-tok-${c.kind}">${t(n.slice(c.from,c.to))}</span>`,r=c.to;return s+t(n.slice(r))}).join(`
|
|
30
|
+
`)}class pt{constructor(o){m(this,"container");m(this,"workspaceContainer");m(this,"workspace");m(this,"definitions");m(this,"blockColors");m(this,"behaviors");m(this,"elementTypes");m(this,"options");m(this,"modes");m(this,"currentMode");m(this,"code");m(this,"renderOverride");m(this,"previewWorkspace");m(this,"onPreviewWorkspace");m(this,"previewContainer");m(this,"previewBase");m(this,"onDragOver");m(this,"onDrop");m(this,"dropTargets");m(this,"onChoose");m(this,"widestBlock",0);this.container=o.container,this.workspaceContainer=o.workspaceContainer,this.workspace=o.workspace,this.onPreviewWorkspace=o.onPreviewWorkspace,this.definitions=o.definitions,this.blockColors=o.blockColors,this.behaviors=o.behaviors,this.elementTypes=o.elementTypes??{},this.code=o.code??{},this.currentMode=o.mode,this.renderOverride=o.render,this.modes=o.modes??[],this.options=o.options??{},this.dropTargets=o.dropTargets??(()=>[]),this.onChoose=o.onChoose,this.onDragOver=e=>{var t;(t=e.dataTransfer)!=null&&t.types.includes(se)&&e.preventDefault()},this.onDrop=e=>{var n;const t=(n=e.dataTransfer)==null?void 0:n.getData(se);t&&(e.preventDefault(),this.createBlockAtPosition(t,e.clientX,e.clientY))},this.workspaceContainer.addEventListener("dragover",this.onDragOver),this.workspaceContainer.addEventListener("drop",this.onDrop),this.render()}rerender(o,e){this.currentMode=o,this.renderOverride=e,this.render()}dispose(){var o;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),(o=this.previewContainer)!=null&&o.parentNode&&(this.previewContainer.parentNode.removeChild(this.previewContainer),this.previewContainer=void 0)}render(){this.widestBlock=0,this.renderTiles(),this.container.style.setProperty("--morphic-toolbox-block-width",`${Math.ceil(this.widestBlock)}px`)}renderTiles(){this.container.innerHTML="";const o=this.options.modeLabel??!0,e=typeof o=="function"?o(this.currentMode):typeof o=="string"?o:o?`Mode: ${this.currentMode}`:"";if(e){const r=document.createElement("div");r.className="morphic-toolbox-header";const c=document.createElement("span");c.className="morphic-toolbar-label",c.textContent=e,r.appendChild(c),this.container.appendChild(r)}const t=this.resolveBlockIds(),n=this.options.categories??[];if(n.length===0){for(const r of t){const c=this.definitions.get(r);c&&this.container.appendChild(this.createTile(c))}return}const s=new Set;for(const r of n){const c=this.resolveCategoryBlockIds(r,t);if(c.length===0)continue;const a=document.createElement("div");a.setAttribute("data-category",V(r.name)),r.color&&a.style.setProperty("--morphic-category-color",r.color);for(const d of c){const l=this.definitions.get(d);l&&(a.appendChild(this.createTile(l)),s.add(d))}this.container.appendChild(a)}for(const r of t)if(!s.has(r)){const c=this.definitions.get(r);c&&this.container.appendChild(this.createTile(c))}}createTile(o){var l,h;const e=V(this.currentMode),t=V(o.identifier),n=this.blockColors.get(o.identifier),s=document.createElement("div");s.setAttribute("draggable","true"),s.setAttribute("data-block-type",o.identifier),s.className=`morphic-block morphic-mode-${e} morphic-block-${t}`,n&&s.style.setProperty("--morphic-block-color",n);const r=this.modes.find(u=>u.name===this.currentMode),c=(r==null?void 0:r.elements)??[],a=Object.entries(o.elements),d=[...c.map(u=>a.find(([k])=>k===u)).filter(u=>u!==void 0),...a.filter(([u])=>!c.includes(u))];for(const[u,k]of d){const v=document.createElement("div");v.className=`morphic-element-${V(u)}`;const w=this.elementTypes[u],b=j(w),g=b==="code",y=b==="image",C=((l=this.renderOverride)==null?void 0:l[u])??(g?"block":"text"),E=y?Ve(k,Re(w)):k;if(g&&C==="block"){this.syncPreviewFont(u);const f=this.createBlockPreviewSvg(o,this.currentMode,u);f?v.appendChild(f):v.innerHTML=Ce(ee(E))}else if(g){const f=this.createCodeText(o,this.currentMode,u),p=this.options.highlight===!1||(h=this.code[u])==null?void 0:h.highlighting;f!==null&&p?(Fo(u,p.colors),v.innerHTML=zo(f,p)):f!==null?v.textContent=f:v.innerHTML=Ce(ee(E))}else v.innerHTML=Ce(ee(E));s.appendChild(v)}return s.addEventListener("dragstart",u=>{var k;(k=u.dataTransfer)==null||k.setData(se,o.identifier)}),this.options.touch!==!1&&(Ro(),this.attachTouchDrag(s,o.identifier)),this.options.keyboard!==!1&&(s.tabIndex=0,s.setAttribute("role","button"),s.setAttribute("aria-label",this.tileName(o,c)),s.addEventListener("keydown",u=>{var k;u.key!=="Enter"&&u.key!==" "||(u.preventDefault(),(k=this.onChoose)==null||k.call(this,o.identifier))})),s}tileName(o,e){var n;const t=[];for(const s of e){const r=o.elements[s];if(r===void 0)continue;const c=j(this.elementTypes[s]);if(c==="code"){const l=this.createCodeText(o,this.currentMode,s);l!=null&&l.trim()&&t.push(l.trim());continue}const a=document.createElement("div");a.innerHTML=c==="image"?Ve(r,Re(this.elementTypes[s])):r;const d=c==="image"?Array.from(a.querySelectorAll("img"),l=>l.alt).join(" ").trim():(n=a.textContent)==null?void 0:n.trim();d&&t.push(d)}return t.join(", ")||o.identifier}dropTargetAt(o,e){const t=document.elementFromPoint(o,e);if(!t)return;const n={element:this.workspaceContainer,drop:(s,r,c)=>this.createBlockAtPosition(s,r,c)};return[...this.dropTargets(),n].find(s=>s.element.contains(t))}attachTouchDrag(o,e){o.addEventListener("pointerdown",t=>{var y;if(t.pointerType==="mouse"||!t.isPrimary)return;const n=o.getBoundingClientRect();let s,r,c={x:t.clientX,y:t.clientY};o.draggable=!1;let a={x:0,y:0},d=1,l=0;const h=()=>{if(s)return;s=o.cloneNode(!0),s.classList.add("morphic-drag-ghost"),s.removeAttribute("tabindex"),Object.assign(s.style,{position:"fixed",left:"0",top:"0",margin:"0",pointerEvents:"none",zIndex:"2147483647",transition:"none",animation:"none"}),this.container.appendChild(s);const C=s.getBoundingClientRect();s.style.left="100px",d=(s.getBoundingClientRect().left-C.left)/100||1,a={x:C.left,y:C.top},Object.assign(s.style,{left:`${(n.left-a.x)/d}px`,top:`${(n.top-a.y)/d}px`,width:`${n.width/d}px`}),k()},u=window.setTimeout(h,Wo),k=()=>{!s||l||(l=requestAnimationFrame(()=>{var E,f;if(l=0,!s)return;s.style.transform=`translate(${(c.x-t.clientX)/d}px, ${(c.y-t.clientY)/d}px)`;const C=this.dropTargetAt(c.x,c.y);C!==r&&((E=r==null?void 0:r.leave)==null||E.call(r)),r=C,(f=r==null?void 0:r.over)==null||f.call(r,c.x,c.y)}))},v=C=>{if(C.pointerId!==t.pointerId)return;c={x:C.clientX,y:C.clientY};const E=Math.abs(C.clientX-t.clientX),f=Math.abs(C.clientY-t.clientY);!s&&(E<_o||f>E)||(window.clearTimeout(u),h(),k())},w=C=>{s&&C.preventDefault()},b=C=>C.preventDefault(),g=C=>{var E,f;C.pointerId===t.pointerId&&(window.clearTimeout(u),o.removeEventListener("pointermove",v),o.removeEventListener("pointerup",g),o.removeEventListener("pointercancel",g),o.removeEventListener("touchmove",w),o.removeEventListener("contextmenu",b),o.draggable=!0,cancelAnimationFrame(l),(E=r==null?void 0:r.leave)==null||E.call(r),s&&(s.remove(),C.type==="pointerup"&&((f=this.dropTargetAt(C.clientX,C.clientY))==null||f.drop(e,C.clientX,C.clientY))))};(y=o.setPointerCapture)==null||y.call(o,t.pointerId),o.addEventListener("pointermove",v),o.addEventListener("pointerup",g),o.addEventListener("pointercancel",g),o.addEventListener("touchmove",w,{passive:!1}),o.addEventListener("contextmenu",b)})}ensurePreviewWorkspace(){var e;if(this.previewWorkspace)return this.previewWorkspace;this.previewContainer=document.createElement("div"),this.previewContainer.style.cssText="position:absolute;left:-9999px;top:-9999px;width:800px;height:600px;overflow:hidden;",document.body.appendChild(this.previewContainer);const o=this.workspace.options;return this.previewWorkspace=x.inject(this.previewContainer,{scrollbars:!1,media:o.pathToMedia,sounds:!1,renderer:o.renderer,rendererOverrides:o.rendererOverrides??void 0,theme:o.theme,rtl:o.RTL}),(e=this.onPreviewWorkspace)==null||e.call(this,this.previewWorkspace),this.previewWorkspace}syncPreviewFont(o){const e=this.ensurePreviewWorkspace();this.previewBase??(this.previewBase={theme:e.getTheme(),font:it(e)});const t=st(this.container,[["morphic-block",`morphic-mode-${V(this.currentMode)}`],[`morphic-element-${V(o)}`],[e.getRenderer().getClassName(),e.getTheme().getClassName()]],this.previewBase.font);rt(e,this.previewBase.theme,this.previewBase.font,t)}createPreviewBlock(o,e,t){var d;const n=this.ensurePreviewWorkspace(),s=n.newBlock(U(o.identifier,this.definitions)),r=this.blockColors.get(o.identifier);r&&s.setColour(r);const c={mode:e,template:o.elements[t]??"",elementName:t,inputSlots:o.inputSlots};We({block:s,definition:o,view:c,mode:"block",context:"toolbox",elementTypes:this.elementTypes,resolveBlocklyType:l=>U(l,this.definitions)});const a=ce(this.behaviors[o.identifier]);return(d=a==null?void 0:a.onViewApplied)==null||d.call(a,s,{Blockly:x,workspace:n,mode:e,context:"toolbox",definition:o}),s}createCodeText(o,e,t){try{const n=this.createPreviewBlock(o,e,t),{code:s}=ke(n.workspace,e,this.definitions,this.elementTypes,this.modes,t,{emptyStatements:!1});return n.dispose(!1),s}catch{return null}}createBlockPreviewSvg(o,e,t){try{const n=this.ensurePreviewWorkspace(),s=this.createPreviewBlock(o,e,t);for(const u of s.getDescendants(!1))u.initSvg(),u.queueRender();s.render();const r=s.getSvgRoot();if(!r)return s.dispose(!1),null;const c=r.getBBox(),a=r.cloneNode(!0),d=4,l=document.createElementNS("http://www.w3.org/2000/svg","svg"),h=Math.ceil(c.width+d*2);return this.widestBlock=Math.max(this.widestBlock,h),l.setAttribute("width",String(h)),l.setAttribute("height",String(Math.ceil(c.height+d*2))),l.setAttribute("viewBox",`${c.x-d} ${c.y-d} ${c.width+d*2} ${c.height+d*2}`),l.setAttribute("class",`${n.getRenderer().getClassName()} ${n.getTheme().getClassName()}`),l.style.direction="ltr",l.appendChild(a),s.dispose(!1),l}catch{return null}}createBlockAtPosition(o,e,t){const n=this.workspace,s=n.getInjectionDiv().getBoundingClientRect(),r=(e-s.left-n.scrollX)/n.scale,c=(t-s.top-n.scrollY)/n.scale,a=n.newBlock(U(o,this.definitions));a.moveTo(new x.utils.Coordinate(r,c)),a.initSvg(),a.render()}resolveBlockIds(){return this.options.blocks??[...this.definitions.keys()]}resolveCategoryBlockIds(o,e){return o.blocks&&o.blocks.length>0?o.blocks.filter(t=>e.includes(t)):e.filter(t=>{var n,s;return((s=(n=this.definitions.get(t))==null?void 0:n.category)==null?void 0:s.toLowerCase())===o.name.toLowerCase()})}}function $e(i,o){var t;if(i.blocks&&i.blocks.length>0)return i.blocks;const e=[];for(const n of o.values())((t=n.category)==null?void 0:t.toLowerCase())===i.name.toLowerCase()&&e.push(n.identifier);return e}function mt(i,o){var n,s,r;if((i.kind??((n=i.categories)!=null&&n.length?"categoryToolbox":"flyoutToolbox"))==="categoryToolbox")return{kind:"categoryToolbox",contents:(i.categories??[]).map(a=>({kind:"category",name:a.name,colour:a.color,contents:$e(a,o).map(d=>({kind:"block",type:U(d,o)}))}))};if((s=i.categories)!=null&&s.length){const c=i.categories,a=[];return c.forEach((l,h)=>{const u=V(l.name);a.push({kind:"label",id:`morphic-category-${u}`,text:l.name,"web-class":`morphic-flyout-category-label morphic-category-${u}`});for(const k of gt($e(l,o)))a.push({kind:"block",type:U(k,o)});h<c.length-1&&a.push({kind:"sep",gap:14})}),{kind:"flyoutToolbox",contents:a}}return{kind:"flyoutToolbox",contents:(i.blocks??gt(((r=i.categories)==null?void 0:r.flatMap(c=>$e(c,o)))??[...o.keys()])).map(c=>({kind:"block",type:U(c,o)}))}}function gt(i){return i.filter((o,e,t)=>t.indexOf(o)===e)}const jo='<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>',Uo='<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>',Go='<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>',Xo='<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>',Yo='<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>',Ko='<svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor"><polygon points="4,3 13,8 4,13"/></svg>',qo='<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>',Jo='<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>',Zo='<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>',Qo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 2h8l2 2v10H3z"/><rect x="5" y="2" width="6" height="4"/><rect x="5" y="9" width="6" height="4"/></svg>',en='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8v5a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V8"/><polyline points="5 5 8 2 11 5"/><line x1="8" y1="2" x2="8" y2="10"/></svg>',tn='<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>',on='<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>',A={modeLabel(){return{id:"mode-label",render:i=>{const o=document.createElement("span");return o.className="morphic-toolbar-label",o.textContent=nn(i),o}}},copy(){return{id:"copy",label:"Copy",title:"Copy block",icon:jo,onClick:i=>{i.engine.copyActiveBlock(i.view)}}},paste(){return{id:"paste",label:"Paste",title:"Paste block",icon:Uo,disabled:i=>!i.engine.hasClipboardContents(),onClick:i=>{i.engine.pasteActiveBlock(i.view)}}},undo(){return{id:"undo",label:"Undo",title:"Undo (block model)",icon:Go,onClick:i=>{var o;(o=i.engine.getWorkspace())==null||o.undo(!1)},disabled:i=>{var o;return!((o=i.engine.getWorkspace())!=null&&o.getUndoStack().length)}}},redo(){return{id:"redo",label:"Redo",title:"Redo (block model)",icon:Xo,onClick:i=>{var o;(o=i.engine.getWorkspace())==null||o.undo(!0)},disabled:i=>{var o;return!((o=i.engine.getWorkspace())!=null&&o.getRedoStack().length)}}},zoomIn(){return{id:"zoom-in",label:"Zoom in",title:"Zoom in",icon:qo,onClick:i=>i.engine.zoomPane(i.view,"in")}},zoomOut(){return{id:"zoom-out",label:"Zoom out",title:"Zoom out",icon:Jo,onClick:i=>i.engine.zoomPane(i.view,"out")}},zoomFit(){return{id:"zoom-fit",label:"Fit",title:"Reset zoom",icon:Zo,onClick:i=>i.engine.zoomPane(i.view,"fit")}},clear(){return{id:"clear",label:"Clear",title:"Clear workspace",icon:Yo,onClick:i=>{var o;window.confirm("Clear workspace? This cannot be undone.")&&((o=i.engine.getWorkspace())==null||o.clear())}}},runCode(){return{id:"run",label:"Run",title:"Run generated code",icon:Ko,onClick:i=>{i.engine.runJavaScript()}}},save(){return{id:"save",label:"Save",title:"Save workspace as JSON",icon:Qo,onClick:i=>{if(!i.engine.getWorkspace())return;const e=i.engine.serializeWorkspace(),t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),n=URL.createObjectURL(t),s=document.createElement("a");s.href=n,s.download="workspace.json",s.click(),URL.revokeObjectURL(n)}}},load(){return{id:"load",label:"Load",title:"Load workspace JSON",icon:en,onClick:i=>{const o=document.createElement("input");o.type="file",o.accept="application/json",o.addEventListener("change",async()=>{var t;const e=(t=o.files)==null?void 0:t[0];if(e)try{const n=await e.text(),s=JSON.parse(n);i.engine.loadWorkspace(s)}catch(n){window.alert(`Load failed: ${n instanceof Error?n.message:String(n)}`)}}),o.click()}}},reset(){return{id:"reset",label:"Reset",title:"Reset workspace",icon:tn,onClick:i=>{var o;window.confirm("Reset workspace to empty? This cannot be undone.")&&((o=i.engine.getWorkspace())==null||o.clear())}}},togglePreview(){return{id:"toggle-preview",label:"Preview",title:"Toggle preview pane",icon:on,onClick:()=>{const i=document.querySelector("[data-morphic-preview-host]");i&&(i.hidden=!i.hidden)}}},readOnlyBadge(){return{id:"read-only",align:"right",render:()=>{const i=document.createElement("span");return i.className="morphic-toolbar-badge",i.textContent="read-only",i}}},spacer(){return{id:"spacer",render:()=>{const i=document.createElement("span");return i.className="morphic-toolbar-spacer",i}}},readOnlyDefaults(){return[A.modeLabel(),A.spacer(),A.copy(),A.zoomIn(),A.zoomOut(),A.zoomFit(),A.readOnlyBadge()]},defaultsFor(i){switch(i){case"workspace":case"codespace":return[A.modeLabel(),A.spacer(),A.undo(),A.redo(),A.copy(),A.paste(),A.zoomIn(),A.zoomOut(),A.zoomFit(),A.clear()];case"preview":return[A.modeLabel(),A.spacer(),A.copy(),A.zoomIn(),A.zoomOut(),A.zoomFit(),A.readOnlyBadge()]}}};function nn(i){const o=i.engine.getViewMode(i.view);return o?`Mode: ${o}`:""}function kt(i,o,e){const t=o.items??A.defaultsFor(e.pane),n=o.display??"icon";i.classList.add("morphic-toolbar"),i.setAttribute("data-morphic-pane",e.pane),i.setAttribute("data-morphic-view",e.view);const s=document.createElement("div");s.className="morphic-toolbar-left";const r=document.createElement("div");r.className="morphic-toolbar-right";const c=()=>{s.replaceChildren(),r.replaceChildren();let a=!1;for(const d of t){if(d.visible&&!d.visible(e))continue;if(d.id==="spacer"){a=!0;continue}(d.align==="right"||a&&d.align!=="left"?r:s).appendChild(sn(d,n,e))}};return i.replaceChildren(s,r),c(),{refresh:c,pane:e.pane,view:e.view,dispose:()=>i.replaceChildren()}}function sn(i,o,e){if(i.render){const n=i.render(e);if(typeof n=="string"){const s=document.createElement("span");return s.className="morphic-toolbar-item",s.dataset.toolbarId=i.id,s.textContent=n,s}return n.classList.add("morphic-toolbar-item"),n.dataset.toolbarId=i.id,n}const t=document.createElement("button");return t.className="morphic-toolbar-item",t.dataset.toolbarId=i.id,t.type="button",i.title&&(t.title=i.title),rn(t,i,o),i.disabled&&i.disabled(e)&&(t.disabled=!0),i.onClick&&t.addEventListener("click",()=>i.onClick(e)),t}function rn(i,o,e){const t=e!=="label"&&!!o.icon,n=e!=="icon"&&!!o.label,s=t||e==="icon"&&!o.label,r=n||e==="label"&&!o.icon;if(s&&o.icon){const c=document.createElement("span");c.className="morphic-toolbar-icon",c.innerHTML=o.icon,i.appendChild(c)}if(r&&o.label){const c=document.createElement("span");c.className="morphic-toolbar-text",c.textContent=o.label,i.appendChild(c)}!i.title&&o.label&&(i.title=o.label),!i.childNodes.length&&o.label&&(i.textContent=o.label)}function wt(i,o){return o.includes("{")?{mode:i,cssText:o}:{mode:i,href:o}}function cn(i){const o=[];for(const[e,t]of Object.entries(i)){const s=(e.split("/").pop()??e).replace(/\.css$/i,""),r=typeof t=="string"?t:typeof t=="object"&&t!==null&&"default"in t?String(t.default):void 0;r&&o.push(wt(s,r))}return o}function Ne(i){return typeof i=="string"?{mode:i}:{mode:i.mode,render:i.render}}const an="blockly-media/",vt=new Set;function ln(i,o){if(vt.has(i)||typeof Image>"u")return;vt.add(i);const e=new Image;e.onerror=()=>{o(`[MorphicBlocks] Blockly's media is missing at "${i}", so icons are not shown and sounds stay silent. Copy it there with "morphic-blocks copy-media <folder>", or point blockly.media to where it is.`)},e.src=`${i}sprites.png`}const He=i=>i.onWarning??(o=>console.warn(o)),re=new WeakMap,be=new Map;function dn(i){const o=i.setInsertionMarker;i.setInsertionMarker=function(e){var t;if(o.call(this,e),!!e)for(const n of this.inputList)(t=n.connection)==null||t.setShadowState(null)}}class hn extends EventTarget{constructor(e,t={}){super();m(this,"definitions");m(this,"behaviors");m(this,"elementTypes");m(this,"formatElementTypes");m(this,"styles",new Po);m(this,"registeredBlockTypes",new Set);m(this,"toolbars",new Set);m(this,"toolbarsBlocklyListener");m(this,"lastCopyData");m(this,"mountConfig");m(this,"workspace");m(this,"flyoutWorkspace");m(this,"toolboxCanvas");m(this,"tileDropTargets",new Set);m(this,"codeEditor");m(this,"codespace");m(this,"previewEditor");m(this,"views",new Set);m(this,"viewWorkspaceModes",new WeakMap);m(this,"viewCount",0);m(this,"selectionSync");m(this,"toolboxDefinition");m(this,"previewHost");m(this,"blockCategoryIndex",new Map);m(this,"appliedWorkspaceClasses",[]);m(this,"appliedToolboxFlyoutClasses",[]);m(this,"appliedToolboxShellClasses",[]);m(this,"headlessWorkspaceHost");m(this,"codespaceDropTeardown");m(this,"workspaceResizeObserver");m(this,"activePreset");m(this,"baseTheme");m(this,"baseFont");m(this,"mountGeneration",0);m(this,"selectionSyncOptions");m(this,"formatModes");m(this,"formatPresets");m(this,"formatCode");m(this,"formatHasHighlighting");m(this,"formatCategories");m(this,"onWorkspaceChange",e=>{if(!this.workspace||!this.mountConfig||e.workspaceId!==this.workspace.id||e.type!==x.Events.BLOCK_CREATE)return;const t=e;for(const n of t.ids??[]){const s=this.workspace.getBlockById(n);if(!s)continue;const r=this.definitions.get(W(s.type));if(!r)continue;const c=this.mountConfig.workspaceMode,a=s;if(a.__morphicMode===c&&a.__morphicContext==="workspace"&&s.getSvgRoot()){ze(s,c,"workspace"),this.styleBlock(s,r);continue}this.applyView(s,r,c,"workspace"),s.getSvgRoot()||this.deferApplyView(n,c,"workspace")}});m(this,"onFlyoutChange",e=>{if(!this.flyoutWorkspace||!this.mountConfig||e.workspaceId!==this.flyoutWorkspace.id||e.type!==x.Events.BLOCK_CREATE)return;const t=e;for(const n of t.ids??[]){const s=this.flyoutWorkspace.getBlockById(n);if(!s)continue;const r=this.definitions.get(W(s.type));r&&(this.applyView(s,r,this.mountConfig.toolboxMode,"toolbox"),s.getSvgRoot()||this.deferApplyView(n,this.mountConfig.toolboxMode,"toolbox"))}});m(this,"onStylesLoaded",()=>this.refresh());const n=e;this.definitions=Bo(Lo(Mo(n.blocks,n.elementTypes??{}))),this.behaviors=t,this.formatElementTypes=n.elementTypes??{},this.elementTypes=Fe(this.formatElementTypes,n.code),this.formatModes=n.modes,this.formatPresets=n.presets,this.formatCode=n.code,this.formatHasHighlighting="highlighting"in n,this.formatCategories=n.categories}mount(e){var y,C,E,f,p,S,T,M;this.dispose();const t={...e,modes:(y=e.modes??this.formatModes)==null?void 0:y.slice(),presets:e.presets??this.formatPresets,code:e.code??this.formatCode,toolbox:e.toolbox||this.formatCategories?{...e.toolbox,categories:((C=e.toolbox)==null?void 0:C.categories)??this.formatCategories}:void 0},n=t.modesFolder?cn(t.modesFolder):[],s=[...n,...Object.entries(t.modeStyles??{}).filter(([B])=>!n.some(D=>D.mode===B)).map(([B,D])=>wt(B,D))];this.elementTypes=Fe(this.formatElementTypes,t.code),this.validateDefinitions(t),this.validatePresets(t);const r=(E=t.presets)!=null&&E.length?t.presets.find(B=>B.name===t.preset)??t.presets[0]:void 0;if(t.preset&&!r)throw new Error(`MorphicBlocks.mount: unknown preset "${t.preset}".`);const c=(t.modes??[]).map(B=>B.name),a=c[0]??((f=s[0])==null?void 0:f.mode)??"default",d=r?Ne(r.toolbox):void 0,l=r?r.workspace??r.codespace??a:a,h=d?d.mode:a,u=d==null?void 0:d.render,k=r==null?void 0:r.codespace,v=r==null?void 0:r.preview;this.validateContainers(t);const w=t.workspaceContainer??this.createHeadlessHost(),b={...t,modeStyles:s,workspaceMode:l,toolboxMode:h,toolboxRender:u,codespaceMode:k,previewMode:v,workspaceHost:w,canvasToolbox:t.canvasToolbox??!!t.toolboxContainer};this.mountConfig=b,this.styles.validateModeCoverage(s,c,He(t)),(p=b.modes)!=null&&p.length&&this.styles.ensureModeVisibilityStyles(b.modes),this.styles.ensureStyles(b.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});(S=document.fonts)==null||S.addEventListener("loadingdone",this.onStylesLoaded),this.blockCategoryIndex=this.createCategoryIndex(b.toolbox,b),this.styles.ensureCategoryStyles(((T=b.toolbox)==null?void 0:T.categories)??[]),this.styles.ensureWorkspaceStyles(),this.registerBlocks(),this.toolboxDefinition=this.resolveToolboxDefinition(b);const g=b.blockly??{};if(this.workspace=x.inject(b.workspaceHost,{...g,media:g.media??an,...b.canvasToolbox?{}:{toolbox:this.toolboxDefinition}}),this.workspace.addChangeListener(this.onWorkspaceChange),re.set(this.workspace,this),this.baseTheme=this.workspace.getTheme(),this.baseFont=it(this.workspace),t.workspaceContainer&&ln(this.workspace.options.pathToMedia,He(t)),t.workspaceContainer&&typeof ResizeObserver<"u"){const B=this.workspace;this.workspaceResizeObserver=new ResizeObserver(()=>x.svgResize(B)),this.workspaceResizeObserver.observe(t.workspaceContainer)}return this.applyWorkspaceContainerClass(),this.syncWorkspaceFont(),this.refreshToolbox(),this.bindFlyoutWorkspace(),this.renderWorkspaceBlocks(),this.renderFlyoutBlocks(),t.toolboxContainer&&this.mountToolbox(t.toolboxContainer),this.activePreset=r,r&&((M=b.onPresetApplied)==null||M.call(b,r)),this.mountViews(t,++this.mountGeneration)}async mountViews(e,t){const n=e.editorTheme?{theme:e.editorTheme}:void 0,s=e.previewTheme??e.editorTheme,r=[];if(e.codespaceContainer&&r.push(this.mountCodespace(n)),e.previewContainer&&r.push(this.mountPreview(e.previewContainer,s?{theme:s}:void 0)),e.codeEditorContainer&&r.push(this.mountCodeEditor(e.codeEditorContainer,n).then(()=>{t===this.mountGeneration&&this.hideCodeEditor()})),await Promise.all(r),t!==this.mountGeneration||!this.workspace)return;for(const[d,l]of Object.entries(e.toolbarContainers??{}))l&&this.mountToolbar(l,{pane:d});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,a,d;if(!this.mountConfig||!this.workspace)throw new Error("MorphicBlocks must be mounted before applyPreset can be used.");const t=this.mountConfig.presets??[],n=typeof e=="number"?t[e]:t.find(l=>l.name===e);if(!n)throw new Error(`applyPreset: unknown preset "${e}".`);const s=Ne(n.toolbox);this.setModes({toolboxMode:s.mode,toolboxRender:s.render??null,workspaceMode:n.workspace??n.codespace,codespaceMode:n.codespace??null,previewMode:n.preview??null});for(const l of this.views){const h=(r=n.views)==null?void 0:r[l.name];h!==void 0&&h!==l.mode&&((c=l.setMode)==null||c.call(l,h))}return this.activePreset=n,(d=(a=this.mountConfig).onPresetApplied)==null||d.call(a,n),n}validateDefinitions(e){var s;const{errors:t,warnings:n}=ct({definitions:this.definitions,elementTypes:this.formatElementTypes,behaviors:this.behaviors,modes:e.modes,presets:e.presets,code:e.code,categories:(s=e.toolbox)==null?void 0:s.categories});if((this.formatHasHighlighting||"highlighting"in e)&&t.push('The top level "highlighting" map moved into the "code" section: "code": { "<element>": { "highlighting": { … } } }.'),n.length>0&&He(e)(`[MorphicBlocks] Definition warnings:
|
|
31
|
+
- ${n.join(`
|
|
32
|
+
- `)}`),t.length>0)throw new Error(`[MorphicBlocks] Invalid definitions:
|
|
33
|
+
- ${t.join(`
|
|
34
|
+
- `)}`)}validatePresets(e){const t=e.presets??[];if(t.length===0)return;const n=e.modes??[],s=new Map(n.map(c=>[c.name,c])),r=new Set;for(const c of t){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=Ne(c.toolbox),d=[["toolbox",a.mode],["workspace",c.workspace],["codespace",c.codespace],["preview",c.preview]];for(const[l,h]of d){if(h===void 0)continue;const u=s.get(h);if(!u)throw new Error(`Preset "${c.name}": unknown mode "${h}" for ${l}.`);if((l==="codespace"||l==="preview")&&X(u,this.elementTypes)===void 0)throw new Error(`Preset "${c.name}": mode "${h}" has no code element to render in the ${l}.`)}for(const[l,h]of Object.entries(c.views??{}))if(!s.has(h))throw new Error(`Preset "${c.name}": unknown mode "${h}" for view "${l}".`);for(const l of Object.values(a.render??{}))if(l!=="block"&&l!=="text")throw new Error(`Preset "${c.name}": toolbox render values must be "block" or "text".`)}}dispose(){var e,t,n,s,r,c,a,d;for(const[l,h]of be)h===this&&be.delete(l);(e=this.workspaceResizeObserver)==null||e.disconnect(),this.workspaceResizeObserver=void 0,(t=document.fonts)==null||t.removeEventListener("loadingdone",this.onStylesLoaded),this.activePreset=void 0,(n=this.selectionSync)==null||n.disable(),this.selectionSync=void 0,(s=this.codeEditor)==null||s.dispose(),this.codeEditor=void 0,(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,this.previewHost=void 0;for(const l of this.views)this.disposeView(l);this.views.clear(),(d=this.toolboxCanvas)==null||d.dispose(),this.toolboxCanvas=void 0;for(const l of[...this.toolbars])l.dispose();this.flyoutWorkspace&&(this.flyoutWorkspace.removeChangeListener(this.onFlyoutChange),this.flyoutWorkspace=void 0),this.workspace&&(this.workspace.removeChangeListener(this.onWorkspaceChange),this.workspace.dispose(),this.workspace=void 0),this.headlessWorkspaceHost&&(this.headlessWorkspaceHost.remove(),this.headlessWorkspaceHost=void 0),this.mountConfig=void 0,this.baseTheme=void 0,this.baseFont=void 0,this.toolboxDefinition=void 0,this.blockCategoryIndex.clear(),this.appliedWorkspaceClasses=[],this.appliedToolboxFlyoutClasses=[],this.appliedToolboxShellClasses=[]}mountToolbox(e,t){var r;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before mountToolbox can be used.");(r=this.toolboxCanvas)==null||r.dispose(),this.styles.ensureToolbarStyles(),this.mountConfig.canvasToolbox||this.workspace.updateToolbox({kind:"flyoutToolbox",contents:[]});const n=this.mountConfig.toolbox,s={...t,blocks:(t==null?void 0:t.blocks)??(n==null?void 0:n.blocks),categories:(t==null?void 0:t.categories)??(n==null?void 0:n.categories),modeLabel:(t==null?void 0:t.modeLabel)??(n==null?void 0:n.modeLabel),highlight:(t==null?void 0:t.highlight)??(n==null?void 0:n.highlight),touch:(t==null?void 0:t.touch)??(n==null?void 0:n.touch),keyboard:(t==null?void 0:t.keyboard)??(n==null?void 0:n.keyboard)};this.toolboxCanvas=new pt({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,code:this.mountConfig.code,options:s,onPreviewWorkspace:c=>re.set(c,this),dropTargets:()=>[...this.tileDropTargets],onChoose:c=>this.addBlockFromTile(c)})}refresh(){var e;if(!(!this.workspace||!this.mountConfig)){this.syncWorkspaceFont(),Oe(this.workspace);for(const t of this.views)t.workspace&&(this.syncFontOf(t.workspace,t.container),Oe(t.workspace));(e=this.toolboxCanvas)==null||e.rerender(this.mountConfig.toolboxMode,this.mountConfig.toolboxRender)}}getWorkspace(){return this.workspace}getAvailableModes(){var e;return(((e=this.mountConfig)==null?void 0:e.modes)??[]).map(t=>t.name)}getWorkspaceMode(){var e;return(e=this.mountConfig)==null?void 0:e.workspaceMode}getCodespaceMode(){var e,t;return((e=this.mountConfig)==null?void 0:e.codespaceMode)??((t=this.mountConfig)==null?void 0:t.workspaceMode)}getPreviewMode(){var e;return(e=this.mountConfig)==null?void 0:e.previewMode}setModeElements(e,t){var h,u,k,v,w,b,g;if(!this.mountConfig||!this.workspace)throw new Error("MorphicBlocks must be mounted before setModeElements can be used.");const n=this.mountConfig.modes??[],s=n.findIndex(y=>y.name===e);if(s===-1)throw new Error(`setModeElements: unknown mode "${e}".`);const r=t.filter(y=>!(y in this.elementTypes));if(r.length>0)throw new Error(`setModeElements: unknown elements ${r.map(y=>`"${y}"`).join(", ")}.`);const c={...n[s],elements:[...t]};if((!!this.mountConfig.codespaceContainer&&e===this.getCodespaceMode()||e===this.mountConfig.previewMode||[...this.views].some(y=>y.mode===e))&&X(c,this.elementTypes)===void 0)throw new Error(`setModeElements: mode "${e}" is shown in a codespace or preview and needs a code element.`);const d=n.map((y,C)=>C===s?c:y);this.validatePresets({...this.mountConfig,modes:d});const l=n.slice();n[s]=c,this.styles.ensureModeVisibilityStyles(n,l),e===this.mountConfig.toolboxMode&&((h=this.toolboxCanvas)==null||h.rerender(this.mountConfig.toolboxMode,this.mountConfig.toolboxRender),this.renderFlyoutBlocks()),e===this.mountConfig.workspaceMode&&(this.syncWorkspaceFont(),this.renderWorkspaceBlocks()),(u=this.codespace)==null||u.setHighlightRules(this.resolveHighlightRules("codespace")),(k=this.previewEditor)==null||k.setHighlightRules(this.resolveHighlightRules("preview")),(v=this.codespace)==null||v.refresh(),(w=this.previewEditor)==null||w.refresh();for(const y of this.views)y.mode===e&&(y.workspace&&(this.styleWorkspaceView(y),this.renderWorkspaceView(y)),(b=y.editor)==null||b.setHighlightRules(this.highlightRulesFor(y.mode)),(g=y.editor)==null||g.refresh())}modeDef(e){var t;if(e)return(((t=this.mountConfig)==null?void 0:t.modes)??[]).find(n=>n.name===e)}getActivePrimarySourceElement(){const e=this.modeDef(this.getCodespaceMode());if(e)return X(e,this.elementTypes)}getActivePreviewElement(){var t;const e=this.modeDef((t=this.mountConfig)==null?void 0:t.previewMode);if(e)return X(e,this.elementTypes)}mountToolbar(e,t){if(!this.workspace)throw new Error("MorphicBlocks must be mounted before mountToolbar can be used.");const n=t.view??t.pane;if(!n)throw new Error("mountToolbar: set `view` (or `pane`).");const s=["workspace","codespace","preview"],r=this.resolveView(n),c=(r==null?void 0:r.kind)??s.find(h=>h===n);if(!c)throw new Error(`mountToolbar: no view named "${n}".`);this.styles.ensureToolbarStyles();const a=t.items??(c==="workspace"&&(r!=null&&r.readOnly)?A.readOnlyDefaults():void 0),d=kt(e,{...t,items:a},{engine:this,pane:c,view:n,getText:()=>this.toolbarTextFor(n),refresh:()=>this.toolbarRefreshFor(n)});this.toolbars.add(d),this.ensureToolbarBlocklyListener();const l=d.dispose;return d.dispose=()=>{this.toolbars.delete(d),this.toolbars.size===0&&this.teardownToolbarBlocklyListener(),l()},d}toolbarTextFor(e){var n,s;const t=this.resolveView(e);if((t==null?void 0:t.kind)==="codespace")return((n=t.editor)==null?void 0:n.getValue())??this.generateCodespaceText().code;if((t==null?void 0:t.kind)==="preview")return((s=t.editor)==null?void 0:s.getValue())??"";if((t==null?void 0:t.kind)==="workspace"&&t.readOnly)return this.generateModeText(t.mode).code;if(this.codespace)return this.codespace.getValue();try{return this.generateJavaScript()}catch{return""}}toolbarRefreshFor(e){var t,n;(n=(t=this.resolveView(e))==null?void 0:t.editor)==null||n.refresh()}runJavaScript(e){var k,v,w;let t="",n,s=null;const r=[],c=(e==null?void 0:e.console)??(e!=null&&e.logToConsole?console:void 0),a=this.getActivePrimarySourceElement(),d=a?(w=(v=(k=this.mountConfig)==null?void 0:k.code)==null?void 0:v[a])==null?void 0:w.values:void 0,l=b=>(...g)=>{r.push({level:b,text:g.map(y=>ut(y,d)).join(" ")}),c&&(c[b]??c.log).apply(c,g)},h={log:l("log"),warn:l("warn"),error:l("error")};try{t=this.generateJavaScript(),n=new Function("console",t)(h)}catch(b){s=b instanceof Error?b:new Error(String(b))}const u={code:t,result:n,error:s,output:r};return this.dispatchEvent(new CustomEvent("morphic-run",{detail:u})),u}hasClipboardContents(){return!!this.lastCopyData}copyActiveBlock(e){var s;const t=this.resolveActiveBlock(e);if(!t)return!1;const n=t.toCopyData();if(!n)return!1;this.lastCopyData=n;try{const r=this.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:x.clipboard.paste(this.lastCopyData,this.workspace)!==null}resolveActiveBlock(e){var a,d,l;const t=x.common.getSelected();if(t&&"id"in t&&((a=this.workspace)!=null&&a.getBlockById(t.id)))return t;const n=(d=this.resolveView(e))==null?void 0:d.editor;if(!n)return null;const s=n.getCursorLine();let r=null;for(const[h,u]of n.metadata)if(u.startLine<=s&&u.endLine>=s){const k=u.endLine-u.startLine;(!r||k<r.size)&&(r={id:h,size:k})}return(r?(l=this.workspace)==null?void 0:l.getBlockById(r.id):null)??null}serializeWorkspace(){return this.workspace?x.serialization.workspaces.save(this.workspace):null}loadWorkspace(e){this.workspace&&(this.workspace.clear(),x.serialization.workspaces.load(e,this.workspace))}zoomPane(e,t){var r;const n=this.resolveView(e),s=n==null?void 0:n.workspace;if(s){t==="in"?s.zoomCenter(1):t==="out"?s.zoomCenter(-1):s.zoomToFit();return}(r=n==null?void 0:n.editor)==null||r.adjustZoom(t)}ensureToolbarBlocklyListener(){if(this.toolbarsBlocklyListener||!this.workspace)return;const e=t=>{for(const n of this.toolbars)n.refresh()};this.toolbarsBlocklyListener=e,this.workspace.addChangeListener(e)}teardownToolbarBlocklyListener(){!this.toolbarsBlocklyListener||!this.workspace||(this.workspace.removeChangeListener(this.toolbarsBlocklyListener),this.toolbarsBlocklyListener=void 0)}setModes(e){var t,n,s,r,c,a;if(!this.mountConfig||!this.workspace)throw new Error("MorphicBlocks must be mounted before setModes can be used.");for(const[d,l]of[["workspaceMode",e.workspaceMode],["toolboxMode",e.toolboxMode],["codespaceMode",e.codespaceMode],["previewMode",e.previewMode]])if(typeof l=="string"&&!this.modeDef(l))throw new Error(`setModes: unknown mode "${l}" for ${d}.`);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),(t=this.toolboxCanvas)==null||t.rerender(this.mountConfig.toolboxMode,this.mountConfig.toolboxRender)),e.workspaceMode&&(this.applyWorkspaceContainerClass(),this.syncWorkspaceFont(),this.renderWorkspaceBlocks()),this.applyTextViewClasses(),this.refreshToolbox(),this.bindFlyoutWorkspace(),this.renderFlyoutBlocks(),(n=this.codespace)==null||n.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 d of this.toolbars)d.refresh();(a=this.selectionSync)==null||a.clearAll()}resolveHighlightRules(e){var n,s;if(!this.mountConfig)return;const t=e==="codespace"?this.getActivePrimarySourceElement():this.getActivePreviewElement();if(t)return(s=(n=this.mountConfig.code)==null?void 0:n[t])==null?void 0:s.highlighting}generateJavaScript(){if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before generateJavaScript can be used.");return ro(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 co(this.workspace,this.definitions,this.behaviors,this.mountConfig.javascript)}async mountCodeEditor(e,t){var s;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before mountCodeEditor can be used.");(s=this.codeEditor)==null||s.dispose(),this.codeEditor=new ge(e,this.workspace,()=>this.generateJavaScriptWithMetadata(),t,!0);const n=this.codeEditor;await n.mount(),this.codeEditor===n&&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 t={...e,onDelete:(e==null?void 0:e.onDelete)??(c=>this.codespace&&this.deleteBlockAtCodespaceLine(this.codespace,c)),canDragBlock:(e==null?void 0:e.canDragBlock)??(c=>this.canMoveInCodespace(c)),highlightRules:(e==null?void 0:e.highlightRules)??this.resolveHighlightRules("codespace"),onPlaceholderApply:(e==null?void 0:e.onPlaceholderApply)??((c,a)=>this.applyPlaceholderEdit(c,a))};this.applyTextViewClasses(),this.codespace=new ge(this.mountConfig.codespaceContainer,this.workspace,()=>this.generateCodespaceText(),t);const n=this.codespace;await n.mount(),this.codespace===n&&(this.codespaceDropTeardown=this.attachCodespaceDropTarget(n,this.mountConfig.codespaceContainer,this.workspace),this.refreshSelectionSync())}attachCodespaceDropTarget(e,t,n){const s=p=>{var T;const S=(T=p.dataTransfer)==null?void 0:T.types;return S?S.includes(se)||S.includes(Se):!1},r=()=>{e.hideDropIndicator(),e.hideValueSlotHighlight()},c=(p,S)=>{const T=this.computeCodespaceDrop(e,p,S);if(!T){r();return}T.indicator.kind==="line"?(e.showDropIndicator(T.indicator.line,T.indicator.position),e.hideValueSlotHighlight()):(e.showValueSlotHighlight(T.indicator.from,T.indicator.to),e.hideDropIndicator())},a=p=>{s(p)&&(p.preventDefault(),c(p.clientX,p.clientY))},d=p=>{const S=p.relatedTarget;S&&t.contains(S)||r()},l=p=>{var S,T;s(p)&&(p.preventDefault(),h(p.clientX,p.clientY,(S=p.dataTransfer)==null?void 0:S.getData(se),(T=p.dataTransfer)==null?void 0:T.getData(Se)))},h=(p,S,T,M)=>{r();const B=this.computeCodespaceDrop(e,p,S);if(!B)return;let D=null;if(T)D=n.newBlock(U(T,this.definitions)),this.placeOrphanBelowTops(D),D.initSvg(),D.render();else if(M){if(D=n.getBlockById(M),!D)return}else return;const P=this.fitOrLoose(n,D,B);if(!P){T&&D.dispose(!1);return}let $=!1;x.Events.setGroup(!0);try{if(M&&D.getParent()&&D.unplug(!0),P.target.kind==="top")this.placeAtTopIndex(n,D,P.target.index),$=!0;else if(P.target.kind==="statement"){if(D.previousConnection){const O=n.getBlockById(P.target.targetBlockId);O&&O!==D&&(this.connectStatement(D,O,P.target.position),$=!0)}}else if(P.target.kind==="into-slot"){if(D.previousConnection){const O=n.getBlockById(P.target.parentBlockId);O&&O!==D&&(this.connectIntoSlot(D,O,P.target.inputName),$=!0)}}else if(P.target.kind==="value-slot"){if(D.outputConnection){const O=n.getBlockById(P.target.parentBlockId);O&&O!==D&&!this.isDescendantOf(O,D)&&($=this.connectIntoValueSlot(D,O,P.target.inputName))}!$&&T&&D.dispose(!1)}}finally{x.Events.setGroup(!1)}!$&&D.workspace&&!D.getParent()&&this.placeOrphanBelowTops(D),x.svgResize(n)};let u=null;const k=3,v=p=>p.button===2||p.button===0&&p.ctrlKey,w=p=>{if(!u)return;if(!u.dragging){const T=Math.abs(p.clientX-u.startX),M=Math.abs(p.clientY-u.startY);if(T+M<k)return;u.dragging=!0}const S=this.computeCodespaceDrop(e,p.clientX,p.clientY);if(!S){e.hideDropIndicator(),e.hideValueSlotHighlight();return}S.indicator.kind==="line"?(e.showDropIndicator(S.indicator.line,S.indicator.position),e.hideValueSlotHighlight()):(e.showValueSlotHighlight(S.indicator.from,S.indicator.to),e.hideDropIndicator())},b=p=>{window.removeEventListener("mousemove",w),window.removeEventListener("mouseup",b),e.hideDropIndicator(),e.hideValueSlotHighlight();const S=u;if(u=null,Ge(void 0),!(S!=null&&S.dragging))return;const T=this.computeCodespaceDrop(e,p.clientX,p.clientY);if(!T)return;const M=n.getBlockById(S.sourceId);M&&this.applyRightDragMove(n,M,T)},g=p=>{if(!v(p))return;const S=e.charAtCoords(p.clientX,p.clientY);if(S==null)return;const T=this.findInnermostBlockAtChar(e,S);T&&(p.preventDefault(),p.stopPropagation(),u={sourceId:T.id,startX:p.clientX,startY:p.clientY,dragging:!1},Ge(T.id),window.addEventListener("mousemove",w),window.addEventListener("mouseup",b))},y=p=>{p.preventDefault()},C=p=>{if(u)return;const S=e.charAtCoords(p.clientX,p.clientY);if(S==null){e.setHoverHighlight(null),e.setEditableHoverHighlight(null);return}const T=this.findInnermostEditablePlaceholderAtChar(e,S);e.setEditableHoverHighlight(T?{from:T.start,to:T.end}:null);const M=this.findHoverBlockAtChar(e,S);if(!M){e.setHoverHighlight(null);return}const B=e.metadata.get(M.id);if(!B||B.startChar===void 0||B.endChar===void 0){e.setHoverHighlight(null);return}e.setHoverHighlight({from:B.startChar,to:B.endChar})},E=()=>{e.setHoverHighlight(null),e.setEditableHoverHighlight(null)},f={element:t,over:c,leave:r,drop:(p,S,T)=>h(S,T,p)};return this.tileDropTargets.add(f),t.addEventListener("dragover",a),t.addEventListener("dragleave",d),t.addEventListener("drop",l),t.addEventListener("mousedown",g,!0),t.addEventListener("contextmenu",y),t.addEventListener("mousemove",C),t.addEventListener("mouseleave",E),()=>{this.tileDropTargets.delete(f),t.removeEventListener("dragover",a),t.removeEventListener("dragleave",d),t.removeEventListener("drop",l),t.removeEventListener("mousedown",g,!0),t.removeEventListener("contextmenu",y),t.removeEventListener("mousemove",C),t.removeEventListener("mouseleave",E),window.removeEventListener("mousemove",w),window.removeEventListener("mouseup",b)}}findInnermostBlockAtChar(e,t){if(!this.workspace)return null;let n=null;for(const[s,r]of e.metadata){if(r.startChar===void 0||r.endChar===void 0||t<r.startChar||t>=r.endChar)continue;const c=r.endChar-r.startChar;(n===null||c<n.size)&&(n={id:s,size:c})}return n?this.workspace.getBlockById(n.id):null}findHoverBlockAtChar(e,t){if(!this.workspace)return null;let n=null,s=null;for(const[c,a]of e.metadata){if(a.startChar===void 0||a.endChar===void 0||t<a.startChar||t>=a.endChar)continue;const d=a.endChar-a.startChar;(s===null||d<s.size)&&(s={id:c,size:d}),!a.atomic&&(n===null||d<n.size)&&(n={id:c,size:d})}const r=n??s;return r?this.workspace.getBlockById(r.id):null}findInnermostEditablePlaceholderAtChar(e,t){let n=null;for(const s of e.getPlaceholders()){if(!s.edit||t<s.start||t>=s.end)continue;const r=s.end-s.start;(n===null||r<n.size)&&(n={ph:s,size:r})}return n?{start:n.ph.start,end:n.ph.end}:null}applyRightDragMove(e,t,n){if(!n||(n=this.fitOrLoose(e,t,n),!n))return;let s=!1;x.Events.setGroup(!0);try{if(t.getParent()&&t.unplug(!0),n.target.kind==="top")this.placeAtTopIndex(e,t,n.target.index),s=!0;else if(n.target.kind==="statement"){if(t.previousConnection){const r=e.getBlockById(n.target.targetBlockId);r&&r!==t&&(this.connectStatement(t,r,n.target.position),s=!0)}}else if(n.target.kind==="into-slot"){if(t.previousConnection){const r=e.getBlockById(n.target.parentBlockId);r&&r!==t&&(this.connectIntoSlot(t,r,n.target.inputName),s=!0)}}else if(n.target.kind==="value-slot"&&t.outputConnection){const r=e.getBlockById(n.target.parentBlockId);r&&r!==t&&!this.isDescendantOf(r,t)&&(s=this.connectIntoValueSlot(t,r,n.target.inputName))}}finally{x.Events.setGroup(!1)}!s&&t.workspace&&!t.getParent()&&this.placeOrphanBelowTops(t),x.svgResize(e)}computeCodespaceDrop(e,t,n){var k,v;if(!this.workspace)return null;const s=this.workspace.getTopBlocks(!0),r=e.metadata,c=e.getLineCount();if(s.length===0)return{indicator:{kind:"line",line:1,position:"above"},target:{kind:"top",index:0}};if(e.isBelowLastLine(n)){const w=r.get(s[s.length-1].id);return{indicator:{kind:"line",line:(w==null?void 0:w.endLine)??c,position:"below"},target:{kind:"top",index:s.length}}}const a=e.getLineAtCoords(t,n);if(a===null){const w=r.get(s[0].id);return{indicator:{kind:"line",line:(w==null?void 0:w.startLine)??1,position:"above"},target:{kind:"top",index:0}}}const d=e.charAtCoords(t,n);if(d!==null){const w=this.findValueSlotDropAtChar(e,d);if(w)return{indicator:{kind:"value-slot",from:w.highlight.from,to:w.highlight.to},target:{kind:"value-slot",parentBlockId:w.parentBlockId,inputName:w.inputName}}}const l=this.findInnermostStatementSlotAtLine(a,r);if(l){const w=this.workspace.getBlockById(l.blockId);if(w){const b=xe(),g=[];let y=(v=(k=w.getInput(l.inputName))==null?void 0:k.connection)==null?void 0:v.targetBlock();for(;y;)y.id!==b&&g.push(y),y=y.getNextBlock();for(const C of g){const E=r.get(C.id);if(!E||a<E.startLine||a>E.endLine)continue;const f=a===E.endLine,p=e.isInLowerHalfOfLine(a,n);return f&&p?{indicator:{kind:"line",line:E.endLine,position:"below"},target:{kind:"statement",targetBlockId:C.id,position:"after"}}:{indicator:{kind:"line",line:E.startLine,position:"above"},target:{kind:"statement",targetBlockId:C.id,position:"before"}}}if(g.length>0){const C=g[g.length-1],E=r.get(C.id);return{indicator:{kind:"line",line:(E==null?void 0:E.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}}}}const h=xe();for(let w=0;w<s.length;w++)for(let b=s[w];b;b=b.getNextBlock()){if(b.id===h)continue;const g=r.get(b.id);if(!g||a<g.startLine||a>g.endLine)continue;const y=a===g.endLine,C=e.isInLowerHalfOfLine(a,n),E=y&&C,f=E&&!b.getNextBlock();return{indicator:E?{kind:"line",line:g.endLine,position:"below"}:{kind:"line",line:g.startLine,position:"above"},target:{kind:"statement",targetBlockId:b.id,position:E?"after":"before",topIndex:f?w+1:w}}}const u=r.get(s[s.length-1].id);return{indicator:{kind:"line",line:(u==null?void 0:u.endLine)??c,position:"below"},target:{kind:"top",index:s.length}}}findInnermostStatementSlotAtLine(e,t){let n=null;for(const[s,r]of t)if(r.statementSlots)for(const[c,a]of Object.entries(r.statementSlots)){if(e<a.startLine||e>a.endLine)continue;const d=a.endLine-a.startLine,l=this.computeBlockDepth(s);(n===null||d<n.size||d===n.size&&l>n.depth)&&(n={blockId:s,inputName:c,range:a,size:d,depth:l})}return n?{blockId:n.blockId,inputName:n.inputName,range:n.range}:null}fitOrLoose(e,t,n){return this.codespaceDropAllowed(e,t,n.target)?n:n.target.kind==="statement"&&n.target.topIndex!==void 0?{...n,target:{kind:"top",index:n.target.topIndex}}:null}codespaceDropAllowed(e,t,n){var a,d,l;const s=(h,u)=>!!h&&!!u&&e.connectionChecker.canConnect(h,u,!1);if(n.kind==="top")return!0;if(n.kind==="value-slot"){const h=e.getBlockById(n.parentBlockId);return s((a=h==null?void 0:h.getInput(n.inputName))==null?void 0:a.connection,t.outputConnection)}if(n.kind==="into-slot"){const h=e.getBlockById(n.parentBlockId),u=(d=h==null?void 0:h.getInput(n.inputName))==null?void 0:d.connection;let k=u==null?void 0:u.targetBlock();for(;k!=null&&k.getNextBlock()&&k.getNextBlock()!==t;)k=k.getNextBlock();return s(k&&k!==t?k.nextConnection:u,t.previousConnection)}const r=e.getBlockById(n.targetBlockId);if(!r||r===t)return!1;if(n.position==="before"){const h=(l=r.previousConnection)==null?void 0:l.targetConnection;return h&&h.getSourceBlock()!==t&&!s(h,t.previousConnection)?!1:s(t.nextConnection,r.previousConnection)}const c=r.getNextBlock();return s(r.nextConnection,t.previousConnection)?!c||c===t||s(t.nextConnection,c.previousConnection):!1}connectIntoSlot(e,t,n){if(!e.previousConnection)return;const s=t.getInput(n),r=s==null?void 0:s.connection;if(!r)return;const c=r.targetBlock();if(!c){r.connect(e.previousConnection);return}let a=c,d=a.getNextBlock();for(;d;)a=d,d=a.getNextBlock();a.nextConnection&&a.nextConnection.connect(e.previousConnection)}findValueSlotDropAtChar(e,t){var r,c;if(!this.workspace)return null;const n=xe();for(const a of e.getPlaceholders()){if(t<a.start||t>=a.end)continue;if(a.emptySlot){const{parentBlockId:u,inputName:k}=a.emptySlot;if(u===n)continue;const v=this.workspace.getBlockById(u);if(!((r=v==null?void 0:v.getInput(k))!=null&&r.connection))continue;return{parentBlockId:u,inputName:k,highlight:{from:a.start,to:a.end}}}const d=(c=a.edit)==null?void 0:c.blockId;if(!d||d===n)continue;const l=this.workspace.getBlockById(d);if(!l)continue;const h=this.resolveValueParent(l);if(h)return{parentBlockId:h.parentBlockId,inputName:h.inputName,highlight:{from:a.start,to:a.end}}}let s=null;for(const[a,d]of e.metadata){if(d.startChar===void 0||d.endChar===void 0||t<d.startChar||t>=d.endChar||a===n)continue;const l=this.workspace.getBlockById(a);if(!(l!=null&&l.outputConnection))continue;const h=d.endChar-d.startChar;(s===null||h<s.size)&&(s={id:a,size:h,from:d.startChar,to:d.endChar})}if(s){const a=this.workspace.getBlockById(s.id);if(a){const d=this.resolveValueParent(a);if(d)return{parentBlockId:d.parentBlockId,inputName:d.inputName,highlight:{from:s.from,to:s.to}}}}return null}resolveValueParent(e){var s;const t=(s=e.outputConnection)==null?void 0:s.targetConnection;if(!t)return null;const n=t.getSourceBlock();if(!n)return null;for(const r of n.inputList)if(r.connection===t)return{parentBlockId:n.id,inputName:r.name};return null}addBlockFromTile(e){const t=this.workspace;if(!t)return;const n=x.common.getSelected(),s=n instanceof x.BlockSvg&&n.workspace===t?n:null;x.Events.setGroup(!0);try{const r=t.newBlock(U(e,this.definitions)),c=s&&!s.isShadow()?{kind:"statement",targetBlockId:s.id,position:"after"}:null,a=c!==null&&this.codespaceDropAllowed(t,r,c);a||this.placeOrphanBelowTops(r),r.initSvg(),r.render(),a&&s&&this.connectStatement(r,s,"after"),x.common.setSelected(r);const d=t.getMetricsManager().getViewMetrics(!0),l=r.getBoundingRectangle();l.left>=d.left&&l.top>=d.top&&l.right<=d.left+d.width&&l.bottom<=d.top+d.height||t.centerOnBlock(r.id)}finally{x.Events.setGroup(!1)}}placeOrphanBelowTops(e){var s,r;if(!this.workspace)return;const t=this.workspace.getTopBlocks(!0).filter(c=>c.id!==e.id);if(t.length===0){e.moveTo(new x.utils.Coordinate(20,20));return}let n=0;for(const c of t){const a=c.getRelativeToSurfaceXY(),d=((r=(s=c.getHeightWidth)==null?void 0:s.call(c))==null?void 0:r.height)??50;n=Math.max(n,a.y+d)}e.moveTo(new x.utils.Coordinate(20,n+20))}isDescendantOf(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.getParent()}return!1}connectIntoValueSlot(e,t,n){if(!e.outputConnection)return!1;const s=t.getInput(n),r=s==null?void 0:s.connection;if(!r)return!1;const c=r.targetBlock(),a=!!c&&!c.isShadow();a&&(c.unplug(!1),this.placeOrphanBelowTops(c));try{return r.connect(e.outputConnection),!0}catch{if(a&&(c!=null&&c.outputConnection))try{r.connect(c.outputConnection)}catch{}return!1}}computeBlockDepth(e){var s,r;let t=0,n=((r=(s=this.workspace)==null?void 0:s.getBlockById(e))==null?void 0:r.getParent())??null;for(;n;)t++,n=n.getParent();return t}placeAtTopIndex(e,t,n){const s=e.getTopBlocks(!0).map(c=>c.id).filter(c=>c!==t.id),r=Math.max(0,Math.min(n,s.length));s.splice(r,0,t.id),this.applyTopBlockOrder(e,s)}connectStatement(e,t,n){var s,r,c;if(e.previousConnection)if(n==="before"){const a=((s=t.previousConnection)==null?void 0:s.targetConnection)??null;(r=t.previousConnection)==null||r.disconnect(),a?a.connect(e.previousConnection):e.moveTo(t.getRelativeToSurfaceXY()),e.nextConnection&&t.previousConnection&&e.nextConnection.connect(t.previousConnection)}else{const a=t.getNextBlock();(c=a==null?void 0:a.previousConnection)==null||c.disconnect(),t.nextConnection&&t.nextConnection.connect(e.previousConnection),a!=null&&a.previousConnection&&e.nextConnection&&e.nextConnection.connect(a.previousConnection)}}applyTopBlockOrder(e,t){const n=x.Events.disable!==void 0;n&&x.Events.disable();try{let s=20;for(const r of t){const c=e.getBlockById(r);c&&(c.moveTo(new x.utils.Coordinate(20,s)),s+=c.getHeightWidth().height+20)}}finally{n&&x.Events.enable()}x.svgResize(e),this.refreshTextViews()}refreshTextViews(){var e,t,n,s;(e=this.codespace)==null||e.refresh(),(t=this.previewEditor)==null||t.refresh(),(n=this.codeEditor)==null||n.refresh();for(const r of this.views)(s=r.editor)==null||s.refresh()}async mountPreview(e,t){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 n={...t,highlightRules:(t==null?void 0:t.highlightRules)??this.resolveHighlightRules("preview"),showPlaceholderMarkers:(t==null?void 0:t.showPlaceholderMarkers)??!1};this.previewHost=e,this.applyTextViewClasses(),this.previewEditor=new ge(e,this.workspace,()=>this.generatePreviewText(),n);const s=this.previewEditor;await s.mount(),this.previewEditor===s&&this.refreshSelectionSync()}generatePreviewText(){var e;return this.generateModeText((e=this.mountConfig)==null?void 0:e.previewMode)}generateModeText(e){const t=this.modeDef(e),n=t?X(t,this.elementTypes):void 0;return!this.workspace||!this.mountConfig||!e||!n?{code:"",metadata:new Map,placeholders:[]}:ke(this.workspace,e,this.definitions,this.elementTypes,this.mountConfig.modes??[],n)}highlightRulesFor(e){var s,r,c;const t=this.modeDef(e),n=t?X(t,this.elementTypes):void 0;return n?(c=(r=(s=this.mountConfig)==null?void 0:s.code)==null?void 0:r[n])==null?void 0:c.highlighting:void 0}addView(e){if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before addView can be used.");if(e.kind!=="preview"&&e.kind!=="codespace"&&e.kind!=="workspace")throw new Error(`addView: unknown view kind "${String(e.kind)}".`);if(e.kind==="workspace"&&e.editable===!0)throw new Error("addView: an added workspace is read only for now (editable: false).");if(e.name!==void 0&&this.resolveView(e.name))throw new Error(`addView: a view named "${e.name}" already exists.`);if(e.kind==="workspace")return this.addWorkspaceView(e);this.checkTextViewMode("addView",e.mode);const t=e.kind==="codespace",n=new ge(e.container,this.workspace,()=>this.generateModeText(c.mode),{theme:e.theme,highlightRules:this.highlightRulesFor(e.mode),...t?{onDelete:l=>this.deleteBlockAtCodespaceLine(n,l),canDragBlock:l=>this.canMoveInCodespace(l),onPlaceholderApply:(l,h)=>this.applyPlaceholderEdit(l,h)}:{showPlaceholderMarkers:!1}}),s=t?"morphic-codespace-root":"morphic-preview-root";let r=e.name;for(;r===void 0||this.resolveView(r);)r=`view-${++this.viewCount}`;const c={kind:e.kind,name:r,container:e.container,mode:e.mode,editor:n};this.views.add(c),fe(c.container,c.mode,s);const a=e.toolbar?this.mountToolbar(e.toolbar.container,{view:r,items:e.toolbar.items,display:e.toolbar.display}):void 0,d={kind:c.kind,name:c.name,ready:n.mount().then(()=>{this.views.has(c)&&(t&&this.workspace&&(c.teardown=this.attachCodespaceDropTarget(n,c.container,this.workspace)),this.linkAddedView())}),getMode:()=>c.mode,setMode:l=>{if(this.views.has(c)){this.checkTextViewMode("setMode",l),c.mode=l,fe(c.container,l,s),n.setHighlightRules(this.highlightRulesFor(l)),n.refresh();for(const h of this.toolbars)h.refresh()}},setTheme:l=>n.setTheme(l),dispose:()=>{var l;this.views.delete(c)&&(a==null||a.dispose(),(l=c.teardown)==null||l.call(c),n.dispose(),this.refreshSelectionSync())}};return c.setMode=d.setMode,d}addWorkspaceView(e){const t=this.workspace;if(!this.modeDef(e.mode))throw new Error(`addView: unknown mode "${e.mode}".`);let n=e.name;for(;n===void 0||this.resolveView(n);)n=`view-${++this.viewCount}`;const s=t.options,r=x.inject(e.container,{readOnly:!0,media:s.pathToMedia,sounds:!1,renderer:s.renderer,rendererOverrides:s.rendererOverrides??void 0,theme:this.baseTheme??s.theme,rtl:s.RTL,move:{scrollbars:!0,drag:!0,wheel:!0}});re.set(r,this),this.viewWorkspaceModes.set(r,e.mode);const c={kind:"workspace",name:n,container:e.container,mode:e.mode,workspace:r};this.views.add(c),this.styleWorkspaceView(c);const a=()=>{const{scrollX:g,scrollY:y,scale:C}=r;x.Events.disable();try{x.serialization.workspaces.load(x.serialization.workspaces.save(t),r)}finally{x.Events.enable()}this.renderWorkspaceView(c),r.scale!==C&&r.setScale(C),r.scroll(g,y)};a();let d=null,l=!1;const h=()=>{var g;for(const y of r.getAllBlocks(!1))y.unselect();(g=r.getBlockById(d??""))==null||g.select()},u=g=>{if(g.workspaceId===t.id){if(g.type===x.Events.SELECTED){d=g.newElementId??null,h();return}g.isUiEvent||l||(l=!0,setTimeout(()=>{l=!1,this.views.has(c)&&(a(),h())},0))}};t.addChangeListener(u);const k=g=>{var f;const y=g.target,C=(f=y==null?void 0:y.closest)==null?void 0:f.call(y,"[data-id]");let E=C?t.getBlockById(C.getAttribute("data-id")??""):null;for(;E!=null&&E.isShadow();)E=E.getParent();E?x.common.setSelected(E):y!=null&&y.classList.contains("blocklyMainBackground")&&x.common.setSelected(null)};e.container.addEventListener("click",k);const v=typeof ResizeObserver<"u"?new ResizeObserver(()=>x.svgResize(r)):void 0;v==null||v.observe(e.container);const w=e.toolbar?this.mountToolbar(e.toolbar.container,{view:n,items:e.toolbar.items,display:e.toolbar.display}):void 0;c.teardown=()=>{t.removeChangeListener(u),e.container.removeEventListener("click",k),v==null||v.disconnect(),w==null||w.dispose()};const b={kind:"workspace",name:n,ready:Promise.resolve(),getMode:()=>c.mode,setMode:g=>{if(this.views.has(c)){if(!this.modeDef(g))throw new Error(`setMode: unknown mode "${g}".`);c.mode=g,this.viewWorkspaceModes.set(r,g),this.styleWorkspaceView(c),this.renderWorkspaceView(c);for(const y of this.toolbars)y.refresh()}},setTheme:()=>{},dispose:()=>{this.views.delete(c)&&this.disposeView(c)}};return c.setMode=b.setMode,b}styleWorkspaceView(e){e.workspace&&(ue(e.container,e.mode,"workspace","morphic-workspace-root"),this.syncFontOf(e.workspace,e.container))}renderWorkspaceView(e){var t;for(const n of((t=e.workspace)==null?void 0:t.getAllBlocks(!1))??[]){const s=this.definitions.get(W(n.type));s&&this.applyView(n,s,e.mode,"workspace")}}disposeView(e){var t,n,s;(t=e.teardown)==null||t.call(e),(n=e.editor)==null||n.dispose(),(s=e.workspace)==null||s.dispose()}linkAddedView(){var t,n;if(this.selectionSync){this.refreshSelectionSync();return}const e=(t=this.mountConfig)==null?void 0:t.selectionSync;e===!1||!((n=this.mountConfig)!=null&&n.workspaceContainer)||this.enableSelectionSync(typeof e=="object"?e:void 0)}resolveView(e){var t,n,s;if(e==="workspace")return this.workspace?{name:e,kind:"workspace",mode:(t=this.mountConfig)==null?void 0:t.workspaceMode,workspace:this.workspace,readOnly:!1}:void 0;if(e==="codespace")return(n=this.mountConfig)!=null&&n.codespaceContainer?{name:e,kind:"codespace",mode:this.getCodespaceMode(),editor:this.codespace,readOnly:!1}:void 0;if(e==="preview")return this.previewHost?{name:e,kind:"preview",mode:(s=this.mountConfig)==null?void 0:s.previewMode,editor:this.previewEditor,readOnly:!0}:void 0;for(const r of this.views)if(r.name===e)return{name:e,kind:r.kind,mode:r.mode,editor:r.editor,workspace:r.workspace,readOnly:r.kind!=="codespace"}}getViewMode(e){var t;return(t=this.resolveView(e))==null?void 0:t.mode}checkTextViewMode(e,t){const n=this.modeDef(t);if(!n)throw new Error(`${e}: unknown mode "${t}".`);if(X(n,this.elementTypes)===void 0)throw new Error(`${e}: mode "${t}" has no code element to render.`)}applyPlaceholderEdit(e,t){var a;if(!this.workspace)return;let n=this.workspace.getBlockById(e.blockId);if(!n)return;if(n.isShadow()){const d=(a=n.outputConnection)==null?void 0:a.targetConnection;if(d){const l=this.workspace.newBlock(n.type);for(const h of n.inputList)for(const u of h.fieldRow){if(!u.name)continue;const k=l.getField(u.name);k&&k.setValue(u.getValue())}n.rendered&&(l.initSvg(),l.render()),d.connect(l.outputConnection),n=l}}const s=n.getField(e.fieldName);if(!s)return;s.setValue(t);const r=n;r.rendered&&typeof r.render=="function"&&r.render();const c=n.getParent();if(c){const d=c;d.rendered&&typeof d.render=="function"&&d.render()}}canMoveInCodespace(e){var n;const t=(n=this.workspace)==null?void 0:n.getBlockById(e);return!!(t!=null&&t.previousConnection||t!=null&&t.outputConnection)}deleteBlockAtCodespaceLine(e,t){var c;const n=e.metadata;if(!this.workspace||!n||n.size===0)return;let s=null,r=1/0;for(const[a,{startLine:d,endLine:l}]of n){if(t<d||t>l)continue;const h=l-d;h<r&&(r=h,s=a)}s&&((c=this.workspace.getBlockById(s))==null||c.dispose(!0))}generateCodespaceText(){if(!this.workspace||!this.mountConfig)return{code:"",metadata:new Map,placeholders:[]};const e=this.mountConfig.codespaceMode;if(e){const t=this.modeDef(e),n=t?X(t,this.elementTypes):void 0;return ke(this.workspace,e,this.definitions,this.elementTypes,this.mountConfig.modes??[],n)}return ke(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 t;(t=this.codeEditor)==null||t.setTheme(e)}setCodespaceTheme(e){var t;(t=this.codespace)==null||t.setTheme(e)}setPreviewTheme(e){var t;(t=this.previewEditor)==null||t.setTheme(e)}enableSelectionSync(e){var n;if(!this.workspace)throw new Error("MorphicBlocks must be mounted before enableSelectionSync can be used.");const t=[this.codeEditor,this.codespace,this.previewEditor,...[...this.views].map(s=>s.editor)].filter(s=>s!==void 0);if(t.length===0)throw new Error("enableSelectionSync requires at least one of mountCodeEditor, mountCodespace, or mountPreview to have been called first.");(n=this.selectionSync)==null||n.disable(),this.selectionSyncOptions=e,this.selectionSync=new To(this.workspace,t,e),this.selectionSync.enable()}refreshSelectionSync(){if(!this.selectionSync)return;this.codeEditor||this.codespace||this.previewEditor||[...this.views].some(t=>t.editor)?this.enableSelectionSync(this.selectionSyncOptions):this.disableSelectionSync()}disableSelectionSync(){var e;(e=this.selectionSync)==null||e.disable(),this.selectionSync=void 0,this.selectionSyncOptions=void 0}registerBlocks(){for(const e of this.definitions.values()){const t=Me(e.identifier);if(be.set(t,this),this.registeredBlockTypes.has(t))continue;const n=e.identifier;x.Blocks[t]={init(){const s=re.get(this.workspace)??be.get(t);s==null||s.initManagedBlock(this,n)}},this.registeredBlockTypes.add(t)}}initManagedBlock(e,t){var a;const n=this.definitions.get(t);if(!n)return;const s=e.workspace.isFlyout?"toolbox":"workspace",r=this.viewWorkspaceModes.get(e.workspace)??this.resolveMode(s);this.applyView(e,n,r,s),dn(e);const c=ce(this.behaviors[n.identifier]);(a=c==null?void 0:c.init)==null||a.call(c,e,this.createBehaviorContext(e,n,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,t,n,s){var h,u;if(e.isDeadOrDying())return;const r=this.blockCategoryIndex.get(t.identifier);t.color===void 0&&(r==null?void 0:r.color)!==void 0&&e.setColour(r.color);const c=e.__morphicFieldMemory??(e.__morphicFieldMemory=new Map);for(const[k,v]of Yt(e))c.set(k,v);const a=Be(t,n,this.elementTypes,((h=this.mountConfig)==null?void 0:h.modes)??[]),d=e.workspace===this.workspace;We({block:e,definition:t,view:a,mode:n,context:s,elementTypes:d?this.elementTypes:void 0,resolveBlocklyType:k=>U(k,this.definitions)}),this.styleBlock(e,t);const l=ce(this.behaviors[t.identifier]);(u=l==null?void 0:l.onViewApplied)==null||u.call(l,e,this.createBehaviorContext(e,t,n,s)),Kt(e,c)}styleBlock(e,t){const n=this.blockCategoryIndex.get(t.identifier);$t(e,n==null?void 0:n.token),Nt(e,t.identifier),Ht(e),t.color!==void 0&&(e.setColour(t.color),Ee(e)&&e.render())}applyTextViewClasses(){this.mountConfig&&(this.mountConfig.codespaceContainer&&fe(this.mountConfig.codespaceContainer,this.getCodespaceMode(),"morphic-codespace-root"),this.previewHost&&fe(this.previewHost,this.mountConfig.previewMode,"morphic-preview-root"))}applyWorkspaceContainerClass(){var n;if(!this.mountConfig)return;const e=this.mountConfig.workspaceHost;ue(e,this.mountConfig.workspaceMode,"workspace","morphic-workspace-root");const t=this.resolveClassNames((n=this.mountConfig.ui)==null?void 0:n.workspaceClassName);this.replaceUserClasses(e,this.appliedWorkspaceClasses,t),this.appliedWorkspaceClasses=t}syncWorkspaceFont(){var e;this.workspace&&((e=this.mountConfig)!=null&&e.workspaceHost)&&this.syncFontOf(this.workspace,this.mountConfig.workspaceHost)}syncFontOf(e,t){if(!this.baseTheme||!this.baseFont)return;const n=st(t,[[e.getRenderer().getClassName(),this.baseTheme.getClassName()]],this.baseFont);rt(e,this.baseTheme,this.baseFont,n)&&Oe(e)}applyFlyoutClass(){var c,a,d;if(!this.workspace||!this.mountConfig)return;const e=this.resolveClassNames((c=this.mountConfig.ui)==null?void 0:c.toolboxClassName),t=this.workspace.getToolbox(),n=((a=t==null?void 0:t.getDiv)==null?void 0:a.call(t))??null;n&&(ue(n,this.mountConfig.toolboxMode,"toolbox","morphic-toolbox-shell"),this.replaceUserClasses(n,this.appliedToolboxShellClasses,e),this.appliedToolboxShellClasses=e);const s=(d=this.workspace.getFlyout())==null?void 0:d.getWorkspace(),r=s==null?void 0:s.getParentSvg();r&&(ue(r,this.mountConfig.toolboxMode,"toolbox","morphic-toolbox-root"),this.replaceUserClasses(r,this.appliedToolboxFlyoutClasses,e),this.appliedToolboxFlyoutClasses=e)}renderWorkspaceBlocks(){if(!(!this.workspace||!this.mountConfig))for(const e of this.workspace.getAllBlocks(!1)){const t=e,n=this.definitions.get(W(t.type));n&&this.applyView(t,n,this.mountConfig.workspaceMode,"workspace")}}renderFlyoutBlocks(){if(!(!this.flyoutWorkspace||!this.mountConfig)){for(const e of this.flyoutWorkspace.getAllBlocks(!1)){const t=e,n=this.definitions.get(W(t.type));n&&this.applyView(t,n,this.mountConfig.toolboxMode,"toolbox")}this.applyFlyoutClass()}}refreshToolbox(){var e;!this.workspace||!this.toolboxDefinition||(e=this.mountConfig)!=null&&e.canvasToolbox||this.workspace.options.readOnly||this.workspace.updateToolbox(this.toolboxDefinition)}bindFlyoutWorkspace(){var t;if(this.flyoutWorkspace&&(this.flyoutWorkspace.removeChangeListener(this.onFlyoutChange),this.flyoutWorkspace=void 0),!this.workspace)return;const e=(t=this.workspace.getFlyout())==null?void 0:t.getWorkspace();e&&(this.flyoutWorkspace=e,re.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 mt(r,this.definitions)}const t=e.blockly;if(t!=null&&t.toolbox)return t.toolbox;const n=this.resolveToolboxKind(e.toolboxLayout);return mt({...n!==void 0?{kind:n}:{},blocks:[...this.definitions.keys()]},this.definitions)}createBehaviorContext(e,t,n,s){return{Blockly:x,workspace:e.workspace,mode:n,context:s,definition:t}}resolveClassNames(e){return e?(Array.isArray(e)?e.join(" "):e).split(/\s+/).map(n=>n.trim()).filter((n,s,r)=>!!n&&r.indexOf(n)===s):[]}replaceUserClasses(e,t,n){for(const s of t)e.classList.remove(s);for(const s of n)e.classList.add(s)}buildBlockColorMap(){var t;const e=new Map;for(const[n,s]of this.definitions){const r=s.color??((t=this.blockCategoryIndex.get(n))==null?void 0:t.color);r!==void 0&&e.set(n,String(r))}return e}resolveToolboxKind(e){if(e)return e==="category"?"categoryToolbox":"flyoutToolbox"}createCategoryIndex(e,t){const n=new Map,s=(e==null?void 0:e.categories)??[],r=new Map;for(const a of s){const d=V(a.name);if(r.set(a.name.toLowerCase(),{token:d,color:a.color}),a.blocks)for(const l of a.blocks)n.has(l)||n.set(l,{token:d,color:a.color})}const c=t?this.definitions:new Map;for(const a of c.values()){if(!a.category||n.has(a.identifier))continue;const d=r.get(a.category.toLowerCase());d&&n.set(a.identifier,d)}return n}deferApplyView(e,t,n){const s=n==="toolbox"?this.flyoutWorkspace:this.workspace;s&&requestAnimationFrame(()=>{const r=s.getBlockById(e);if(!r)return;const c=this.definitions.get(W(r.type));c&&this.applyView(r,c,t,n)})}}function un(i,o,e){return Math.min(Math.max(i,o),e)}function fn(i,o){const{target:e,axis:t,invert:n=!1,onResize:s}=o,r=o.min??0,c=o.max??Number.POSITIVE_INFINITY,a=d=>{if(d.button!==0)return;d.preventDefault();const l=e.getBoundingClientRect(),h=t==="x"?l.width:l.height,u=t==="x"?d.clientX:d.clientY,k=document.body.style.userSelect,v=document.body.style.cursor;document.body.style.userSelect="none",document.body.style.cursor=t==="x"?"col-resize":"row-resize",i.setPointerCapture(d.pointerId);const w=g=>{const C=(t==="x"?g.clientX:g.clientY)-u,E=un(h+(n?-C:C),r,c);e.style.flexBasis=`${E}px`,s==null||s(E)},b=()=>{i.removeEventListener("pointermove",w),i.removeEventListener("pointerup",b),i.removeEventListener("lostpointercapture",b),document.body.style.userSelect=k,document.body.style.cursor=v};i.addEventListener("pointermove",w),i.addEventListener("pointerup",b),i.addEventListener("lostpointercapture",b)};return i.addEventListener("pointerdown",a),{dispose:()=>i.removeEventListener("pointerdown",a)}}const pn=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"})),mn=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"}));N.MorphicBlocks=hn,N.MorphicToolboxCanvas=pt,N.makeResizable=fn,N.renderToolbar=kt,N.toCleanId=W,N.toolbarItems=A,N.validateDefinitions=ct,Object.defineProperty(N,Symbol.toStringTag,{value:"Module"})}));
|