morphic-blocks 0.0.1 → 0.1.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/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +78 -6
- package/definitions.schema.json +278 -0
- package/dist/code-editor-YFXMCcWg.js +4 -0
- package/dist/index.d.ts +10 -0
- package/dist/morphic/MorphicBlocks.d.ts +308 -0
- package/dist/morphic/behavior-runtime.d.ts +3 -0
- package/dist/morphic/block-namespace.d.ts +34 -0
- package/dist/morphic/block-view.d.ts +45 -0
- package/dist/morphic/code-editor.d.ts +171 -0
- package/dist/morphic/codegen.d.ts +4 -0
- package/dist/morphic/constants.d.ts +7 -0
- package/dist/morphic/definitions.d.ts +2 -0
- package/dist/morphic/element-types.d.ts +20 -0
- package/dist/morphic/resize.d.ts +35 -0
- package/dist/morphic/selection-sync.d.ts +51 -0
- package/dist/morphic/styles.d.ts +22 -0
- package/dist/morphic/syntax-highlight.d.ts +14 -0
- package/dist/morphic/template-codegen.d.ts +16 -0
- package/dist/morphic/template.d.ts +45 -0
- package/dist/morphic/toolbar.d.ts +51 -0
- package/dist/morphic/toolbox-canvas.d.ts +43 -0
- package/dist/morphic/toolbox.d.ts +3 -0
- package/dist/morphic/types.d.ts +622 -0
- package/dist/morphic/validate-definitions.d.ts +31 -0
- package/dist/morphic/view-resolver.d.ts +17 -0
- package/dist/morphic-blocks.js +3973 -0
- package/dist/morphic-blocks.umd.cjs +27 -0
- package/dist/toolbar-kxlfr8TT.js +4 -0
- package/package.json +55 -5
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
(function(A,P){typeof exports=="object"&&typeof module<"u"?P(exports,require("blockly/blocks"),require("blockly"),require("blockly/javascript")):typeof define=="function"&&define.amd?define(["exports","blockly/blocks","blockly","blockly/javascript"],P):(A=typeof globalThis<"u"?globalThis:A||self,P(A.MorphicBlocks={},A.Blockly,A.Blockly,A.javascript))})(this,(function(A,P,W,j){"use strict";var wo=Object.defineProperty;var yo=(A,P,W)=>P in A?wo(A,P,{enumerable:!0,configurable:!0,writable:!0,value:W}):A[P]=W;var v=(A,P,W)=>yo(A,typeof P!="symbol"?P+"":P,W);function ze(i){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const e in i)if(e!=="default"){const o=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(t,e,o.get?o:{enumerable:!0,get:()=>i[e]})}}return t.default=i,Object.freeze(t)}const T=ze(W);function Q(i){if(!(!i||typeof i=="function"))return i}function We(i){if(i)return typeof i=="function"?i:i.generate}const ee="morphic-mode-",te="morphic-context-",be="morphic-category-",je="morphic-block-",Ke=-1,Ue=0,Ge=1;function G(i){if(i!==void 0)return typeof i=="string"?i:i.type}const K=16;function Xe(i){if(!i||typeof i=="string")return{width:K,height:K};const t=i.size;if(t===void 0)return{width:K,height:K};if(typeof t=="number")return{width:t,height:t};const e=/^(\d+)(?:x(\d+))?$/i.exec(t.trim());if(!e)return{width:K,height:K};const o=Number.parseInt(e[1],10),n=e[2]?Number.parseInt(e[2],10):o;return{width:o,height:n}}function Ye(i,t){if(i!=null&&i.default)return i.default;if(!t||typeof t=="string")return;const e=t.empty;if(!e)return;const o=i!=null&&i.check?Array.isArray(i.check)?i.check[0]:i.check:void 0;return(o?e[o]:void 0)??e.default}const oe=18;function X(i){const t=[];let e=0;for(;e<i.length;){const o=i[e];if(o==="<"&&/^<img\b/i.test(i.slice(e))){const r=i.indexOf(">",e);if(r===-1){Ee(t,i.slice(e));break}const s=i.slice(e,r+1),c=et(s);c&&t.push(c),e=r+1;continue}if(o==="%"&&/\d/.test(i[e+1]??"")){let r=e+1;for(;r<i.length&&/\d/.test(i[r]??"");)r+=1;const s=Number.parseInt(i.slice(e+1,r),10);Number.isNaN(s)||t.push({kind:"placeholder",index:s}),e=r;continue}if(o==="%"&&/[A-Z_]/.test(i[e+1]??"")){let r=e+1;for(;r<i.length&&/[A-Z0-9_]/.test(i[r]??"");)r+=1;const s=i.slice(e+1,r);t.push({kind:"field",name:s}),e=r;continue}let n=e+1;for(;n<i.length;){const r=i[n],s=r==="%"&&/\d/.test(i[n+1]??""),c=r==="%"&&/[A-Z_]/.test(i[n+1]??"");if(r==="<"&&/^<img\b/i.test(i.slice(n))||s||c)break;n+=1}Ee(t,i.slice(e,n)),e=n}return tt(t)}function Je(i){return i.replace(/\s+/g," ").trim()}function R(i){return i.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}function Ce(i){return i.map(t=>t.kind==="text"?qe(t.value):t.kind==="image"?`<img src="${ne(t.src)}" alt="${ne(t.alt)}" width="${t.width}" height="${t.height}">`:t.kind==="field"?`<span class="morphic-field-placeholder" data-field-name="${ne(t.name)}"></span>`:`<span class="morphic-toolbox-slot" data-slot-index="${t.index}"></span>`).join("")}function qe(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function ne(i){return i.replace(/"/g,""").replace(/'/g,"'")}const Ze=/\.(svg|png|jpe?g|gif|webp)(?:[#?].*)?$/i;function Qe(i,t){if(!i)return i;const e=i.trim();return/^<img\b/i.test(e)?i:Ze.test(e)?`<img src="${ne(e)}" width="${t.width}" height="${t.height}">`:i}function et(i){if(!/^<img\b/i.test(i))return null;const t=ie(i,"src");if(!t)return null;const e=ie(i,"alt")??"",o=Number.parseInt(ie(i,"width")??`${oe}`,10),n=Number.parseInt(ie(i,"height")??`${oe}`,10);return{kind:"image",src:t,alt:e,width:Number.isNaN(o)?oe:o,height:Number.isNaN(n)?oe:n}}function ie(i,t){const e=new RegExp(`${t}\\s*=\\s*(['"])(.*?)\\1`,"i").exec(i);if(e!=null&&e[2])return e[2];const o=new RegExp(`${t}\\s*=\\s*([^\\s>]+)`,"i").exec(i);return(o==null?void 0:o[1])??null}function Ee(i,t){t&&i.push({kind:"text",value:t})}function tt(i){const t=[];for(const e of i){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 xe(i){const{block:t,definition:e,view:o,mode:n,context:r,elementTypes:s,resolveBlocklyType:c}=i,a=pt(t);vt(t),ct(t,e,o),wt(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),mt(t,a),s&&ft(t,e,o,s,c),st(t,n,r);const l=t;l.__morphicMode=n,l.__morphicContext=r,t.rendered&&t.render()}function he(i,t,e,o){Y(i.classList,ee),Y(i.classList,te),i.classList.add(o),i.classList.add(`${ee}${R(t)}`),i.classList.add(`${te}${e}`)}function ot(i){return i.__morphicMode}function nt(i,t){const e=i.getSvgRoot();e&&(Y(e.classList,be),t&&e.classList.add(`${be}${t}`))}function it(i,t){const e=i.getSvgRoot();if(!e)return;const o=`${je}${R(t)}`;e.classList.contains(o)||e.classList.add(o)}function rt(i){const t=i.getSvgRoot();if(!t)return;const e=getComputedStyle(t).getPropertyValue("--morphic-block-color").trim();e&&(i.setColour(e),i.rendered&&i.render())}function st(i,t,e){const o=i.getSvgRoot();o&&(Y(o.classList,ee),Y(o.classList,te),o.classList.add(`${ee}${R(t)}`),o.classList.add(`${te}${e}`))}function ct(i,t,e){var s;const o=X(e.template),n=[],r=new Set;for(const c of o){if(c.kind==="text"){const d=Je(c.value);d&&n.push(d);continue}if(c.kind==="image"){n.push(new T.FieldImage(c.src,c.width,c.height,c.alt));continue}if(c.kind==="field"){const d=(s=t.fields)==null?void 0:s[c.name];d&&n.push({field:ht(d,e.elementName),name:c.name});continue}if(r.has(c.index)){const d=i.appendDummyInput(`DUPLICATE_${c.index}_${i.inputList.length}`);re(d,n),d.appendField(`%${c.index}`);continue}r.add(c.index);const a=at(t,e,c.index);if((a==null?void 0:a.kind)==="statement"&&n.length>0){const d=i.appendDummyInput(`PRE_STMT_${i.inputList.length}`);re(d,n)}const l=lt(i,a,c.index);re(l,n),a!=null&&a.label&&l.appendField(a.label)}if(n.length>0){const c=i.appendDummyInput(`TRAILING_${i.inputList.length}`);re(c,n)}i.inputList.length===0&&i.appendDummyInput("LABEL").appendField(t.identifier)}function at(i,t,e){var n,r;const o=`${e}`;return((n=t.inputSlots)==null?void 0:n[o])??((r=i.inputSlots)==null?void 0:r[o])}function lt(i,t,e){const o=(t==null?void 0:t.name)??`ARG${e}`,n=(t==null?void 0:t.kind)??"value";let r;return n==="statement"?(r=i.appendStatementInput(o),t!=null&&t.check&&r.setCheck(t.check)):(r=i.appendValueInput(o),t!=null&&t.check&&r.setCheck(t.check)),t!=null&&t.align&&r.setAlign(dt(t.align)),r}function dt(i){return i==="right"?Ge:i==="centre"?Ue:Ke}function re(i,t){for(const e of t)typeof e=="object"&&"field"in e?i.appendField(e.field,e.name):i.appendField(e);t.length=0}function ht(i,t){switch(i.type){case"dropdown":{const e=i.options.map(n=>ut(n,t)),o=new T.FieldDropdown(e);return i.default!==void 0&&o.setValue(i.default),o}case"number":return new T.FieldNumber(i.default??0,i.min,i.max,i.precision);case"checkbox":return new T.FieldCheckbox(i.default?"TRUE":"FALSE");case"text":default:return new T.FieldTextInput(i.default??"")}}function ut(i,t){var o;if(typeof i=="string")return[i,i];if(Array.isArray(i)){const[n,r]=i;return[r??n,n]}return[(t?(o=i.display)==null?void 0:o[t]:void 0)??i.label??i.value,i.value]}function pt(i){var e;const t=new Map;for(const o of i.inputList){const n=(e=o.connection)==null?void 0:e.targetBlock();n&&!n.isShadow()&&t.set(o.name,n)}return t}function ft(i,t,e,o,n=r=>r){var a,l;const r=e.elementName?o[e.elementName]:void 0,s=new Map;for(const d of Object.values(t.inputSlots??{}))d!=null&&d.name&&(d.kind??"value")==="value"&&s.set(d.name,d);if(s.size===0)return;const c=i.workspace;for(const d of i.inputList){const f=d.connection;if(!f||f.type!==T.INPUT_VALUE)continue;const w=s.get(d.name);if(!w)continue;const g=Ye(w,r);if(g){if(g.shadow&&!(((a=f.getShadowState)==null?void 0:a.call(f,!0))??((l=f.getShadowDom)==null?void 0:l.call(f))))try{f.setShadowState({type:n(g.shadow),fields:g.fieldValues??{}})}catch{}if(g.placeholder){const b=f.targetBlock();if(!b||b.isShadow())try{const y=c.newBlock(n(g.placeholder));if(g.fieldValues)for(const[p,h]of Object.entries(g.fieldValues)){const k=y.getField(p);k&&k.setValue(h)}i.rendered&&(y.initSvg(),y.render()),y.outputConnection&&f.connect(y.outputConnection)}catch{}}}}}function mt(i,t){for(const[e,o]of t){const n=i.getInput(e);if(!(n!=null&&n.connection)||n.connection.isConnected())continue;const r=[o.outputConnection,o.previousConnection];for(const s of r)if(s)try{n.connection.connect(s);break}catch{continue}}}function gt(i){const t=new Map;for(const e of i.inputList)for(const o of e.fieldRow)o.name&&t.set(o.name,o.getValue());return t}function kt(i,t){for(const[e,o]of t){const n=i.getField(e);if(n&&o!==void 0&&o!==null)try{n.setValue(o)}catch{}}}function vt(i){for(;i.inputList.length>0;){const t=i.inputList[0];if(!t)break;i.removeInput(t.name,!0)}}function wt(i,t){t.output!==void 0&&yt(i,t.output),t.previousStatement!==void 0&&bt(i,t.previousStatement),t.nextStatement!==void 0&&Ct(i,t.nextStatement)}function yt(i,t){if(t===!1){i.setOutput(!1);return}if(t===!0){i.setOutput(!0);return}i.setOutput(!0,t)}function bt(i,t){if(t===!1){i.setPreviousStatement(!1);return}if(t===!0){i.setPreviousStatement(!0);return}i.setPreviousStatement(!0,t)}function Ct(i,t){if(t===!1){i.setNextStatement(!1);return}if(t===!0){i.setNextStatement(!0);return}i.setNextStatement(!0,t)}function Y(i,t){const e=Array.from(i).filter(o=>o.startsWith(t));for(const o of e)i.remove(o)}function Se(i,t,e){if(!e)return[];const o=new Set(e.keywords??[]),n=e.strings??[],r=e.comment,s=e.numbers!==!1,c=i.Decoration.mark({class:"morphic-tok-keyword"}),a=i.Decoration.mark({class:"morphic-tok-string"}),l=i.Decoration.mark({class:"morphic-tok-number"}),d=i.Decoration.mark({class:"morphic-tok-comment"}),f=(h,k,E)=>{const u=h.length;let m=0;for(;m<u;){if(r&&h.startsWith(r,m)){E.add(k+m,k+u,d);return}let x=!1;for(const L of n)if(h.startsWith(L,m)){const I=m;for(m+=L.length;m<u;){if(h[m]==="\\"&&m+1<u){m+=2;continue}if(h.startsWith(L,m)){m+=L.length;break}m+=1}E.add(k+I,k+m,a),x=!0;break}if(x)continue;if(s){const L=/^\d+(?:\.\d+)?/.exec(h.slice(m));if(L){E.add(k+m,k+m+L[0].length,l),m+=L[0].length;continue}}const S=/^[A-Za-z_]\w*/.exec(h.slice(m));if(S){o.has(S[0])&&E.add(k+m,k+m+S[0].length,c),m+=S[0].length;continue}m+=1}},w=h=>{const k=new t.RangeSetBuilder,E=h.state.doc;for(const{from:u,to:m}of h.visibleRanges){let x=u;for(;x<=m;){const S=E.lineAt(x);if(f(S.text,S.from,k),S.to>=m)break;x=S.to+1}}return k.finish()},g=i.ViewPlugin.fromClass(class{constructor(h){v(this,"decorations");this.decorations=w(h)}update(h){(h.docChanged||h.viewportChanged)&&(this.decorations=w(h.view))}},{decorations:h=>h.decorations}),b=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"}}),C=e.colors??{},y={};C.keyword&&(y[".morphic-tok-keyword"]={color:C.keyword}),C.string&&(y[".morphic-tok-string"]={color:C.string}),C.number&&(y[".morphic-tok-number"]={color:C.number}),C.comment&&(y[".morphic-tok-comment"]={color:C.comment,fontStyle:"italic"});const p=[g,b];return Object.keys(y).length>0&&p.push(i.EditorView.theme(y)),p}const ue="morphic/block-id";let se;function Le(){return se}function Te(i){se=i}const Me={fontSize:"14px",fontFamily:"monospace",lineHeight:1.5,background:"#1e1e1e",foreground:"#d4d4d4",gutterBackground:"#1e1e1e",gutterForeground:"#858585",selectionBackground:"#264f78"},ce=(i,t)=>`color-mix(in srgb, ${i} ${t}%, transparent)`;let Be=!1;async function Et(){if(Be)return;Be=!0;const t=(await Promise.resolve().then(()=>ko)).default,e=document.createElement("style");e.dataset.morphicSource="code-editor",e.textContent=t,document.head.appendChild(e)}const xt=150,St=new Set(["create","delete","move","change"]);function Lt(i){return St.has(i.type)}async function Tt(){try{const[i,t,e]=await Promise.all([import("@codemirror/view"),import("@codemirror/state"),import("@codemirror/lang-javascript")]);return{view:i,state:t,langJs:e}}catch{throw new Error(`CodeMirror is required for the code editor. Install it:
|
|
2
|
+
bun add codemirror @codemirror/view @codemirror/state @codemirror/lang-javascript
|
|
3
|
+
# or: npm install codemirror @codemirror/view @codemirror/state @codemirror/lang-javascript`)}}function pe(i,t){const e={...Me,...t};return i.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:ce(e.foreground,70),backgroundColor:ce(e.foreground,12)},".morphic-delete-marker:hover":{color:e.foreground,backgroundColor:ce(e.foreground,22)},".morphic-grip-marker":{color:ce(e.foreground,75)},".morphic-grip-marker:hover":{color:e.foreground}})}class fe{constructor(t,e,o,n={}){v(this,"editorView");v(this,"container");v(this,"options");v(this,"workspace");v(this,"generateWithMetadata");v(this,"visible",!0);v(this,"syncTimer");v(this,"changeListener");v(this,"lastCode","");v(this,"metadata",new Map);v(this,"placeholders",[]);v(this,"placeholderEditorEl");v(this,"placeholderEditorScrollHandler");v(this,"placeholderEditorOutsideHandler");v(this,"onCursorLine");v(this,"onEmptyClick");v(this,"cm");v(this,"themeCompartment");v(this,"syntaxHighlightCompartment");v(this,"highlightEffect");v(this,"highlightColor","rgba(255, 255, 255, 0.07)");v(this,"metadataEffect");v(this,"placeholderEffect");v(this,"dropIndicatorEffect");v(this,"valueSlotHighlightEffect");v(this,"hoverHighlightEffect");v(this,"editableHoverHighlightEffect");v(this,"emptyClickListener");v(this,"zoomFactor",1);this.container=t,this.workspace=e,this.generateWithMetadata=o,this.options=n}getPlaceholders(){return this.placeholders}findPlaceholderAtPos(t){if(this.options.showPlaceholderMarkers===!1)return null;let e=null,o=1/0;for(const n of this.placeholders){if(n.start>t)break;if(t>=n.start&&t<=n.end){const r=n.end-n.start;r<o&&(o=r,e=n)}}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,n=o.coordsAtPos(t.start),r=o.coordsAtPos(t.end);if(!n||!r)return;const s=o.scrollDOM.getBoundingClientRect(),c=o.state.doc.sliceString(t.start,t.end),a=t.edit;let l;if(a.fieldType==="dropdown"){const b=document.createElement("select");for(const[C,y]of a.options??[]){const p=document.createElement("option");p.value=y,p.textContent=C,b.appendChild(p)}l=b}else{const b=document.createElement("input");b.type=a.fieldType==="number"?"number":"text",b.value=c,l=b}const d=getComputedStyle(o.contentDOM),f=(()=>{let b=o.dom;for(;b;){const C=getComputedStyle(b).backgroundColor;if(C&&C!=="rgba(0, 0, 0, 0)"&&C!=="transparent")return C;b=b.parentElement}return"#fff"})();Object.assign(l.style,{position:"absolute",left:`${n.left-s.left+o.scrollDOM.scrollLeft}px`,top:`${n.top-s.top+o.scrollDOM.scrollTop}px`,minWidth:`${Math.max(40,r.right-n.left+8)}px`,height:`${n.bottom-n.top}px`,font:d.font,lineHeight:d.lineHeight,padding:"0 2px",margin:"0",border:`1px solid ${d.color}`,borderRadius:"2px",background:f,color:d.color,boxSizing:"border-box",zIndex:"20"}),o.scrollDOM.appendChild(l),this.placeholderEditorEl=l;const w=()=>{const b=l.value;this.closePlaceholderEditor(),e(a,b)},g=()=>{this.closePlaceholderEditor()};if(l.addEventListener("keydown",b=>{const C=b.key;C==="Enter"?(b.preventDefault(),w()):C==="Escape"&&(b.preventDefault(),g())}),l.addEventListener("mousedown",b=>b.stopPropagation()),l.addEventListener("click",b=>b.stopPropagation()),a.fieldType==="dropdown"){l.addEventListener("change",()=>w());const b=this.workspace.getBlockById(a.blockId),C=b==null?void 0:b.getField(a.fieldName),y=C==null?void 0:C.getValue();y!=null&&(l.value=String(y)),requestAnimationFrame(()=>{this.placeholderEditorOutsideHandler=p=>{p.target instanceof Node&&!l.contains(p.target)&&g()},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(){Et(),this.cm=await Tt();const{view:t,state:e,langJs:o}=this.cm;this.themeCompartment=new e.Compartment,this.syntaxHighlightCompartment=new e.Compartment;const n=pe(t,this.options.theme??{}),r=Se(t,e,this.options.highlightRules),s=e.StateEffect.define();this.metadataEffect=s;const c=e.StateEffect.define();this.placeholderEffect=c;const a=e.StateField.define({create(){return t.Decoration.none},update(y,p){for(const h of p.effects)if(h.is(c)){const k=h.value;if(!k||k.length===0)return t.Decoration.none;const E=p.state.doc.length,u=[...k].filter(L=>L.start<L.end&&L.end<=E).sort((L,I)=>L.start-I.start||L.end-I.end),m=new e.RangeSetBuilder,x=t.Decoration.mark({class:"morphic-placeholder-default"}),S=t.Decoration.mark({class:"morphic-placeholder-set"});for(const L of u)m.add(L.start,L.end,L.kind==="default"?x:S);return m.finish()}return p.changes.empty?y:t.Decoration.none},provide(y){return t.EditorView.decorations.from(y)}}),l=e.StateEffect.define();this.highlightEffect=l;const d=this,f=e.StateField.define({create(){return t.Decoration.none},update(y,p){for(const h of p.effects)if(h.is(l)){const k=h.value;if(!k)return t.Decoration.none;const E=Array.isArray(k)?k:[k];if(E.length===0)return t.Decoration.none;const u=p.state.doc,m=t.Decoration.mark({class:"morphic-highlight",attributes:{style:`background: ${d.highlightColor}`}}),x=E.map(S=>{const L=u.line(Math.min(S.fromLine,u.lines)).from,I=u.line(Math.min(S.toLine,u.lines)).to;return m.range(L,I)}).sort((S,L)=>S.from-L.from);return t.Decoration.set(x)}return p.changes.empty?y:t.Decoration.none},provide(y){return t.EditorView.decorations.from(y)}}),w=t.EditorView.updateListener.of(y=>{var E;if(y.docChanged||y.transactions.some(u=>u.isUserEvent("select.pointer")))return;const p=y.state.selection.main.head,h=y.startState.selection.main.head;if(p===h)return;if(d.findPlaceholderAtPos(p)){(E=d.onEmptyClick)==null||E.call(d);return}if(!d.onCursorLine)return;const k=y.state.doc.lineAt(p).number;d.onCursorLine(k)}),g=this.options.showPlaceholderMarkers!==!1,b=[t.lineNumbers(),t.highlightSpecialChars(),e.EditorState.readOnly.of(!0),o.javascript(),f,...g?[a]:[],w,this.themeCompartment.of(n),this.syntaxHighlightCompartment.of(r),...this.buildDeleteExtensions(t,e,s),...this.buildGripExtensions(t,e,s),...this.buildDropIndicatorExtensions(t,e),...this.buildValueSlotHighlightExtensions(t,e),...this.buildHoverHighlightExtensions(t,e),...this.buildEditableHoverHighlightExtensions(t,e),...this.options.extensions??[]],C=this.generateWithMetadata();this.lastCode=C.code,this.metadata=C.metadata,this.placeholders=[...C.placeholders].sort((y,p)=>y.start-p.start),this.editorView=new t.EditorView({parent:this.container,state:e.EditorState.create({doc:this.lastCode,extensions:b})}),this.metadataEffect&&this.metadata.size>0&&this.editorView.dispatch({effects:this.metadataEffect.of(this.metadata)}),this.placeholderEffect&&C.placeholders.length>0&&this.editorView.dispatch({effects:this.placeholderEffect.of(C.placeholders)}),this.emptyClickListener=y=>{var h,k,E;if(this.isBelowLastLine(y.clientY)){(h=this.onEmptyClick)==null||h.call(this);return}const p=(k=this.editorView)==null?void 0:k.posAtCoords({x:y.clientX,y:y.clientY});if(typeof p=="number"){const u=this.findPlaceholderAtPos(p);if(u){(E=this.onEmptyClick)==null||E.call(this),u.edit&&this.options.onPlaceholderApply&&requestAnimationFrame(()=>this.openPlaceholderEditor(u));return}}if(this.onCursorLine){const u=this.getLineAtCoords(y.clientX,y.clientY);u!==null&&this.onCursorLine(u)}},this.editorView.scrollDOM.addEventListener("click",this.emptyClickListener),this.attachSyncListener()}buildDeleteExtensions(t,e,o){const n=this.options.onDelete;if(!n)return[];class r extends t.GutterMarker{toDOM(){const f=document.createElement("span");return f.textContent="✕",f.className="morphic-delete-marker",f.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(";"),f}}const s=new r,c=e.StateField.define({create(){return e.RangeSet.empty},update(d,f){for(const w of f.effects)if(w.is(o)){const g=w.value,b=f.state.doc,C=new Set;for(const{startLine:p}of g.values())p>=1&&p<=b.lines&&C.add(p);const y=Array.from(C).sort((p,h)=>p-h).map(p=>s.range(b.line(p).from));return e.RangeSet.of(y,!0)}return d.map(f.changes)}}),a=t.gutter({class:"morphic-delete-gutter",markers(d){return d.state.field(c)},initialSpacer:()=>s,domEventHandlers:{click(d,f){const w=d.state.doc.lineAt(f.from).number;return n(w),!0}}}),l=t.keymap.of([{key:"Delete",run:d=>{if(!d.state.selection.main.empty)return!1;const f=d.state.doc.lineAt(d.state.selection.main.head).number;return n(f),!0}},{key:"Backspace",run:d=>{if(!d.state.selection.main.empty)return!1;const f=d.state.doc.lineAt(d.state.selection.main.head).number;return n(f),!0}}]);return[c,a,e.Prec.highest(l)]}buildGripExtensions(t,e,o){const n=this.options.canDragBlock;if(!n)return[];class r extends t.GutterMarker{constructor(l){super(),this.blockId=l}eq(l){return l instanceof r&&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",f=>{f.dataTransfer&&(f.dataTransfer.setData(ue,d),f.dataTransfer.effectAllowed="move",l.style.cursor="grabbing",se=d)}),l.addEventListener("dragend",()=>{l.style.cursor="grab",se=void 0}),l}}const s=e.StateField.define({create(){return e.RangeSet.empty},update(a,l){for(const d of l.effects)if(d.is(o)){const f=d.value,w=l.state.doc,g=new Map;for(const[C,{startLine:y,startChar:p,endChar:h}]of f){if(y<1||y>w.lines||!n(C))continue;const k=(h??0)-(p??0),E=g.get(y);(!E||k>E.width)&&g.set(y,{id:C,width:k})}const b=Array.from(g.entries()).sort((C,y)=>C[0]-y[0]).map(([C,{id:y}])=>new r(y).range(w.line(C).from));return e.RangeSet.of(b,!0)}return a.map(l.changes)}}),c=t.gutter({class:"morphic-grip-gutter",markers(a){return a.state.field(s)},initialSpacer:()=>new r("")});return[s,c]}buildDropIndicatorExtensions(t,e){const o=e.StateEffect.define();this.dropIndicatorEffect=o;const n=e.StateField.define({create(){return t.Decoration.none},update(s,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,f=Math.max(1,Math.min(l.line,d.lines)),w=d.line(f),g=l.position==="above"?"morphic-drop-indicator-above":"morphic-drop-indicator-below",b=t.Decoration.line({class:g});return t.Decoration.set([b.range(w.from)])}return c.changes.empty?s:t.Decoration.none},provide(s){return t.EditorView.decorations.from(s)}}),r=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[n,r]}buildValueSlotHighlightExtensions(t,e){const o=e.StateEffect.define();this.valueSlotHighlightEffect=o;const n=t.Decoration.mark({class:"morphic-value-slot-target"}),r=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 f=a.state.doc.length,w=Math.max(0,Math.min(d.from,f)),g=Math.max(w,Math.min(d.to,f));return w===g?t.Decoration.none:t.Decoration.set([n.range(w,g)])}return a.changes.empty?c:t.Decoration.none},provide(c){return t.EditorView.decorations.from(c)}}),s=t.EditorView.baseTheme({".morphic-value-slot-target":{outline:"1px solid #5a86bc",outlineOffset:"1px",borderRadius:"2px"}});return[r,s]}buildHoverHighlightExtensions(t,e){const o=e.StateEffect.define();this.hoverHighlightEffect=o;const n=t.Decoration.mark({class:"morphic-hover-target"}),r=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 f=a.state.doc.length,w=Math.max(0,Math.min(d.from,f)),g=Math.max(w,Math.min(d.to,f));return w===g?t.Decoration.none:t.Decoration.set([n.range(w,g)])}return a.changes.empty?c:t.Decoration.none},provide(c){return t.EditorView.decorations.from(c)}}),s=t.EditorView.baseTheme({".morphic-hover-target":{backgroundColor:"rgba(127, 127, 127, 0.10)",borderRadius:"2px"}});return[r,s]}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 n=t.Decoration.mark({class:"morphic-editable-hover"}),r=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 f=a.state.doc.length,w=Math.max(0,Math.min(d.from,f)),g=Math.max(w,Math.min(d.to,f));return w===g?t.Decoration.none:t.Decoration.set([n.range(w,g)])}return a.changes.empty?c:t.Decoration.none},provide(c){return t.EditorView.decorations.from(c)}}),s=t.EditorView.baseTheme({".morphic-editable-hover":{outline:"1px solid #5a86bc",outlineOffset:"1px",borderRadius:"2px"}});return[r,s]}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,n=this.editorView.coordsAtPos(o);return n?t>n.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 n=o.line(t),r=this.editorView.coordsAtPos(n.from),s=this.editorView.coordsAtPos(n.to);return!r||!s?!1:e>(r.top+s.bottom)/2}setTheme(t){if(!this.editorView||!this.cm||!this.themeCompartment)return;const e=pe(this.cm.view,t);this.editorView.dispatch({effects:this.themeCompartment.reconfigure(e)})}setHighlightRules(t){if(!this.editorView||!this.cm||!this.syntaxHighlightCompartment)return;const e=Se(this.cm.view,this.cm.state,t);this.editorView.dispatch({effects:this.syntaxHighlightCompartment.reconfigure(e)})}dispose(){var t;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??Me.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 n={...e,fontSize:`${(o*this.zoomFactor).toFixed(2)}px`},r=pe(this.cm.view,n);this.editorView.dispatch({effects:this.themeCompartment.reconfigure(r)})}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,n)=>o.start-n.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()},xt)}attachSyncListener(){this.changeListener||(this.changeListener=t=>{Lt(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 me="morphic:";function ge(i){return me+i}function _(i){return i.startsWith(me)?i.slice(me.length):i}function z(i,t){return t.has(i)?ge(i):i}function Mt(i,t,e,o){const n={behaviors:e,definitions:t};return De(j.javascriptGenerator,n,o,!1),j.javascriptGenerator.workspaceToCode(i)}function Bt(i,t,e,o){const n={behaviors:e,definitions:t};De(j.javascriptGenerator,n,o,!0);const r=j.javascriptGenerator.workspaceToCode(i);return Vt(r)}const It="// __MORPHIC_BLOCK_START:",Dt="// __MORPHIC_BLOCK_END:",Ie="__";function De(i,t,e,o=!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,r]of t.definitions){const s=We(t.behaviors[n]);i.forBlock[ge(n)]=(c,a)=>{const l=At(c,a),d=s?s(l):$t(n,r);if(Nt(c,r))return[Ht(d),j.Order.NONE];const f=Ot(d);return o?`${It}${c.id}${Ie}
|
|
4
|
+
${f}${Dt}${c.id}${Ie}
|
|
5
|
+
`:f}}}function At(i,t){var r;const e={},o={},n=i.workspace.isFlyout?"toolbox":"workspace";for(const s of i.inputList){const c=(r=s.connection)==null?void 0:r.targetBlock();c&&(c.outputConnection?e[s.name]=t.valueToCode(i,s.name,j.Order.NONE)||"undefined":e[s.name]=t.statementToCode(i,s.name).trimEnd());for(const a of s.fieldRow)a.name&&(o[a.name]=Pt(a.getValue()))}return{blockId:i.id,blockType:_(i.type),mode:ot(i)??"default",context:n,inputs:e,fields:o}}function Nt(i,t){return i.outputConnection?!0:t.output===!1?!1:t.output!==void 0}function Ot(i){const t=i.trim();return t?t.endsWith(";")||t.endsWith("}")||t.endsWith(`
|
|
6
|
+
`)?`${t}
|
|
7
|
+
`:`${t};
|
|
8
|
+
`:""}function Ht(i){const t=i.trim();return t?t.endsWith(";")?t.slice(0,-1):t:"undefined"}function $t(i,t){return t.output!==void 0&&t.output!==!1?"undefined":`// No generator behavior defined for "${i}"`}function Pt(i){return typeof i=="number"||typeof i=="boolean"?String(i):typeof i=="string"?/^-?\d+(\.\d+)?$/.test(i)?i:i==="TRUE"?"true":i==="FALSE"?"false":JSON.stringify(i):JSON.stringify(String(i??""))}const Rt=/^\s*\/\/ __MORPHIC_BLOCK_START:(.+)__$/,Ft=/^\s*\/\/ __MORPHIC_BLOCK_END:(.+)__$/;function Vt(i){const t=i.split(`
|
|
9
|
+
`),e=[],o=new Map,n=new Map;let r=0;for(const s of t){const c=s.match(Rt);if(c){n.set(c[1],r+1);continue}const a=s.match(Ft);if(a){const l=a[1],d=n.get(l);d!==void 0&&(o.set(l,{startLine:d,endLine:r}),n.delete(l));continue}e.push(s),r++}return{code:e.join(`
|
|
10
|
+
`),metadata:o,placeholders:[]}}function ae(i,t={}){for(const e of i.elements)if(G(t[e])==="code")return e}function ke(i,t,e={},o=[]){const n=i.elements,r=o.find(c=>c.name===t);if(r){for(const c of r.elements)if(G(e[c])==="code"&&n[c]!==void 0)return{mode:t,template:n[c],elementName:c,inputSlots:i.inputSlots}}for(const[c,a]of Object.entries(n))if(G(e[c])==="code")return{mode:t,template:a,elementName:c,inputSlots:i.inputSlots};if(n.block!==void 0)return{mode:t,template:n.block,elementName:"block",inputSlots:i.inputSlots};const s=Object.entries(n)[0];if(s===void 0)throw new Error(`Block "${i.identifier}" does not have any elements.`);return{mode:t,template:s[1],elementName:s[0],inputSlots:i.inputSlots}}function V(i,t){if(t.length===0)return;if(i.indent===""||!t.includes(`
|
|
11
|
+
`)){i.output+=t;return}const e=t.split(`
|
|
12
|
+
`);i.output+=e[0];for(let o=1;o<e.length;o++)i.output+=`
|
|
13
|
+
`+i.indent+e[o]}function ve(i,t,e,o,n,r){const s={output:"",metadata:new Map,placeholders:[],indent:""},c={mode:t,definitions:e,elementTypes:o,modeDefs:n,elementOverride:r};let a=!0;for(const l of i.getTopBlocks(!0)){const d=s.output.length;a||(s.output+=`
|
|
14
|
+
`),Ae(l,c,s),s.output.length===d+(a?0:1)?s.output=s.output.slice(0,d):a=!1}return{code:s.output,metadata:s.metadata,placeholders:s.placeholders}}function Ae(i,t,e){const o=1+e.indent.length;let n=i,r=!0;for(;n;){const s=e.output.length;r||V(e,`
|
|
15
|
+
`),Ne(n,t,e),e.output.length===s+(r?0:o)?e.output=e.output.slice(0,s):r=!1,n=n.getNextBlock()}}function Ne(i,t,e){var C,y,p;const o=t.definitions.get(_(i.type));if(!o){const h=e.output.length,k=U(e.output);if(_t(i,e),e.output.length===h)return;const E=U(e.output),u=e.output.endsWith(`
|
|
16
|
+
`)?Math.max(k,E-1):E;let m=e.output.length;for(;m>h&&e.output[m-1]===`
|
|
17
|
+
`;)m--;const x=le(i);e.metadata.set(i.id,{startLine:k,endLine:u,startChar:h,endChar:m,atomic:!!x}),J(e,h,"set",x??void 0);return}let n,r;if(t.elementOverride){const h=o.elements[t.elementOverride];if(h===void 0)return;n=h,r=t.elementOverride}else try{const h=ke(o,t.mode,t.elementTypes,t.modeDefs);n=h.template,r=h.elementName}catch{return}const s=r?t.elementTypes[r]:void 0,c=e.output.length,a=U(e.output),l={},d=X(n);for(const h of d){if(h.kind==="text"){V(e,h.value);continue}if(h.kind==="field"){const I=i.getField(h.name);if(!I)continue;const D=e.output.length;V(e,He(o,r,h.name,I));const H=Oe(i,I,h.name);H&&J(e,D,"set",H);continue}if(h.kind==="image")continue;const k=(C=o.inputSlots)==null?void 0:C[String(h.index)],E=k==null?void 0:k.name;if(!E)continue;const u=i.getInput(E),m=((y=u==null?void 0:u.connection)==null?void 0:y.targetBlock())??null,x=m!=null&&m.isShadow()?null:m;if((k==null?void 0:k.kind)==="statement"){const I=U(e.output),D=e.indent,H=e.output.lastIndexOf(`
|
|
18
|
+
`)+1;e.indent=((p=/^[ \t]*/.exec(e.output.slice(H)))==null?void 0:p[0])??"",x&&Ae(x,t,e),e.indent=D;const F=U(e.output),Z=e.output.endsWith(`
|
|
19
|
+
`)?Math.max(I,F-1):F;l[E]={startLine:I,endLine:Z};continue}let S=!1;if(!x){const I=m!=null&&m.isShadow()?m.inputList.flatMap(B=>B.fieldRow).filter(B=>!!B.name):[],D=!(m!=null&&m.isShadow())&&u?u.fieldRow.filter(B=>{var N;return!!B.name&&!((N=o.fields)!=null&&N[B.name])}):[],H=I.length>0||D.length>0,F=H?Wt(k,s):void 0;F&&V(e,F);const Z=e.output.length;if(I.length>0){const B=m?t.definitions.get(_(m.type)):void 0;for(const N of I)V(e,B&&N.name?He(B,r,N.name,N):de(N))}else if(D.length>0)for(const B of D){const N=e.output.length;V(e,de(B));const $=Oe(i,B,B.name);$&&(J(e,N,"set",$),S=!0)}let M;if(H||(V(e,zt(k==null?void 0:k.check)),M={parentBlockId:i.id,inputName:E}),!S){const B=m!=null&&m.isShadow()?le(m)??void 0:void 0;J(e,Z,"default",B,M)}F&&V(e,F);continue}const L=e.output.length;Ne(x,t,e),J(e,L,"set",le(x)??void 0)}if(e.output.length===c)return;const f=U(e.output),w=e.output.endsWith(`
|
|
20
|
+
`)?Math.max(a,f-1):f;let g=e.output.length;for(;g>c&&e.output[g-1]===`
|
|
21
|
+
`;)g--;const b={startLine:a,endLine:w,startChar:c,endChar:g};Object.keys(l).length>0&&(b.statementSlots=l),le(i)&&(b.atomic=!0),e.metadata.set(i.id,b)}function _t(i,t){for(const e of i.inputList)for(const o of e.fieldRow)o.name&&V(t,de(o))}function J(i,t,e,o,n){const r=i.output.length;if(r>t){const s={start:t,end:r,kind:e};o&&(s.edit=o),n&&(s.emptySlot=n),i.placeholders.push(s)}}function zt(i){const t=Array.isArray(i)?i[0]:i;return t?`[${{Number:"NUMBER",String:"TEXT",Boolean:"BOOL"}[t]??t.toUpperCase()}]`:"[VALUE]"}function Wt(i,t){if(!(!(i!=null&&i.check)||(Array.isArray(i.check)?i.check[0]:i.check)!=="String")&&!(!t||typeof t=="string"))return t.stringQuote}function Oe(i,t,e){let o,n;if(t instanceof T.FieldNumber)o="number";else if(t instanceof T.FieldDropdown){o="dropdown";const r=t.getOptions();Array.isArray(r)&&(n=r.filter(s=>Array.isArray(s)&&s.length>=2).map(([s,c])=>[String(s),String(c)]))}else if(t instanceof T.FieldTextInput)o="text";else return null;return{blockId:i.id,fieldName:e,fieldType:o,options:n}}function le(i){let t=null,e=null,o=0;for(const c of i.inputList){if(c.connection&&c.connection.type===T.INPUT_VALUE)return null;for(const a of c.fieldRow)a.name&&(o++,t=a.name,e=a)}if(o!==1||!t||!e)return null;const n=e.constructor.name;let r="text",s;if(n.includes("Number"))r="number";else if(n.includes("Dropdown")){r="dropdown";const c=e.getOptions;if(typeof c=="function"){const a=c.call(e);Array.isArray(a)&&(s=a.filter(l=>Array.isArray(l)&&l.length>=2).map(([l,d])=>[String(l),String(d)]))}}return{blockId:i.id,fieldName:t,fieldType:r,options:s}}function He(i,t,e,o){var r,s;const n=(r=i.fields)==null?void 0:r[e];if((n==null?void 0:n.type)==="dropdown"&&t){const c=String(o.getValue());for(const a of n.options)if(!(typeof a!="object"||Array.isArray(a))&&a.value===c)return((s=a.display)==null?void 0:s[t])??c}return de(o)}function de(i){if(!i)return"";if(i instanceof T.FieldDropdown)return String(i.getValue());const t=i.getText;return typeof t=="function"?t.call(i):String(i.getValue())}function U(i){let t=1;for(let e=0;e<i.length;e++)i[e]===`
|
|
22
|
+
`&&t++;return t}const jt="rgba(255, 255, 255, 0.07)";class Kt{constructor(t,e,o={}){v(this,"workspace");v(this,"editors");v(this,"blockToCode");v(this,"codeToBlock");v(this,"blockListener");v(this,"cursorCallbacks",new Map);v(this,"emptyClickCallbacks",new Map);v(this,"guard",!1);this.workspace=t,this.editors=Array.isArray(e)?[...e]:[e],this.blockToCode=o.blockToCode!==!1,this.codeToBlock=o.codeToBlock!==!1;const n=o.highlightColor??jt;for(const r of this.editors)r.setHighlightColor(n)}enable(){this.blockToCode&&this.attachBlockListener(),this.codeToBlock&&this.attachCursorListeners()}disable(){this.detachBlockListener(),this.detachCursorListeners();for(const t of this.editors)t.clearHighlight()}attachBlockListener(){this.blockListener||(this.blockListener=t=>{if(t.type!=="selected"||this.guard)return;const e=t.newElementId??void 0;this.guard=!0,this.broadcastHighlight(e),this.guard=!1},this.workspace.addChangeListener(this.blockListener))}detachBlockListener(){this.blockListener&&(this.workspace.removeChangeListener(this.blockListener),this.blockListener=void 0)}broadcastHighlight(t){for(const e of this.editors){if(!t){e.clearHighlight();continue}const o=this.computeOwnSpans(t,e.metadata);o?e.highlightLines(o):e.clearHighlight()}}attachCursorListeners(){for(const t of this.editors){if(!this.cursorCallbacks.has(t)){const e=o=>{if(this.guard)return;const n=this.findBlockAtLine(o,t.metadata);if(!n){this.clearAll();return}const r=this.workspace.getBlockById(n);r&&T.common.getSelected()!==r&&(this.guard=!0,T.common.setSelected(r),this.broadcastHighlight(n),this.guard=!1)};this.cursorCallbacks.set(t,e),t.onCursorLine=e}if(!this.emptyClickCallbacks.has(t)){const e=()=>{this.guard||this.clearAll()};this.emptyClickCallbacks.set(t,e),t.onEmptyClick=e}}}detachCursorListeners(){for(const[t,e]of this.cursorCallbacks)t.onCursorLine===e&&(t.onCursorLine=void 0);this.cursorCallbacks.clear();for(const[t,e]of this.emptyClickCallbacks)t.onEmptyClick===e&&(t.onEmptyClick=void 0);this.emptyClickCallbacks.clear()}clearAll(){this.guard=!0,T.common.setSelected(null);for(const t of this.editors)t.clearHighlight();this.guard=!1}computeOwnSpans(t,e){const o=e.get(t);if(!o)return;const n=[];for(const[c,a]of e)c!==t&&a.startLine>=o.startLine&&a.endLine<=o.endLine&&n.push(a);if(n.length===0)return[{fromLine:o.startLine,toLine:o.endLine}];n.sort((c,a)=>c.startLine-a.startLine);const r=[];let s=o.startLine;for(const c of n)s<c.startLine&&r.push({fromLine:s,toLine:c.startLine-1}),s=Math.max(s,c.endLine+1);return s<=o.endLine&&r.push({fromLine:s,toLine:o.endLine}),r.length>0?r:void 0}findBlockAtLine(t,e){let o;for(const[n,r]of e)if(t>=r.startLine&&t<=r.endLine){const s=r.endLine-r.startLine;(!o||s<o.size)&&(o={id:n,size:s})}return o==null?void 0:o.id}}function Ut(i){const t=new Map,e=Array.isArray(i)?i:[i];for(const o of e)Gt(o,t),t.set(o.identifier,o);return t}function Gt(i,t){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(t.has(i.identifier))throw new Error(`Duplicate block identifier "${i.identifier}".`)}function $e(i){var p,h,k,E;const{definitions:t,elementTypes:e,behaviors:o,modes:n,presets:r,highlighting:s,categories:c}=i,a=[],l=[],d=new Set(Object.keys(e)),f=new Set(Object.keys(e).filter(u=>G(e[u])==="code")),w=new Set((c??[]).map(u=>u.name)),g=u=>t.has(u)||T.Blocks[u]!==void 0;for(const u of t.values()){const m=u.identifier,x=Q(o[m]),S=!!(x!=null&&x.onViewApplied);for(const M of Object.keys(u.elements))d.has(M)||l.push(`Block "${m}": element "${M}" is not declared in elementTypes — it renders with no known type.`);const L=new Map,I=new Set,D=new Set;for(const[M,B]of Object.entries(u.elements)){if(!f.has(M))continue;const N=new Set;for(const $ of X(B))$.kind==="placeholder"?(N.add($.index),I.add($.index)):$.kind==="field"&&D.add($.name);L.set(M,N)}const H=[...L.entries()];if(H.length>1){const[M,B]=H[0];for(const[N,$]of H.slice(1))Xt(B,$)||a.push(`Block "${m}": code elements "${M}" and "${N}" use different placeholders (${Pe(B)} vs ${Pe($)}). All code elements must share the same %N set, or an input disappears when switching to the differing mode.`)}const F=new Set(Object.keys(u.inputSlots??{}).map(M=>Number(M)).filter(M=>Number.isInteger(M)));for(const M of I)(p=u.inputSlots)!=null&&p[String(M)]||l.push(`Block "${m}": placeholder %${M} has no inputSlots["${M}"] entry — the input is auto-named ARG${M} and can't be read by name in behaviors.`);for(const M of F)I.has(M)||l.push(`Block "${m}": inputSlots["${M}"] has no matching %${M} placeholder in any code element — the config is ignored.`);const Z=new Set(Object.keys(u.fields??{}));for(const M of D)!((h=u.fields)!=null&&h[M])&&!S&&a.push(`Block "${m}": field token %${M} has no fields["${M}"] entry and the block has no onViewApplied behavior to create it — the field will never appear.`);for(const M of Z)D.has(M)||l.push(`Block "${m}": fields["${M}"] has no matching %${M} token in any code element — the config is ignored.`);for(const[M,B]of Object.entries(u.fields??{}))if((B==null?void 0:B.type)==="dropdown"){for(const N of B.options)if(!(typeof N!="object"||Array.isArray(N)||!N.display))for(const $ of Object.keys(N.display))f.has($)||l.push(`Block "${m}": fields["${M}"] option "${N.value}" has display for "${$}", which is not a code element — that entry never applies.`)}u.category!==void 0&&w.size>0&&!w.has(u.category)&&l.push(`Block "${m}": category "${u.category}" is not declared in categories — the block loses its colour and grouping.`);for(const[M,B]of Object.entries(u.inputSlots??{}))y((k=B==null?void 0:B.default)==null?void 0:k.shadow,`Block "${m}": inputSlots["${M}"].default.shadow`),y((E=B==null?void 0:B.default)==null?void 0:E.placeholder,`Block "${m}": inputSlots["${M}"].default.placeholder`)}for(const[u,m]of Object.entries(e)){if(typeof m=="string")continue;const x=m.empty;if(x)for(const[S,L]of Object.entries(x))y(L.shadow,`elementTypes.${u}.empty.${S}.shadow`),y(L.placeholder,`elementTypes.${u}.empty.${S}.placeholder`)}for(const[u,m]of Object.entries(e)){if(typeof m=="string")continue;const x=m.type;m.size!==void 0&&x!=="image"&&l.push(`elementTypes."${u}": "size" applies only to image elements — ignored for a ${x} element.`),m.stringQuote!==void 0&&x!=="code"&&l.push(`elementTypes."${u}": "stringQuote" applies only to code elements — ignored for a ${x} element.`),m.empty!==void 0&&x!=="code"&&l.push(`elementTypes."${u}": "empty" applies only to code elements — ignored for a ${x} element.`)}for(const u of n??[])for(const m of u.elements)d.has(m)||l.push(`Mode "${u.name}": element "${m}" is not declared in elementTypes — it renders nothing.`);for(const u of Object.keys(s??{}))f.has(u)||l.push(`highlighting["${u}"] is not a code element — its rules will never apply.`);const b=new Map,C=(u,m)=>{const x=b.get(u)??new Set;x.add(m),b.set(u,x)};for(const u of d)C(u,"element");for(const u of n??[])C(u.name,"mode");for(const u of r??[])C(u.name,"preset");for(const[u,m]of b)m.size>1&&l.push(`Name "${u}" is used as ${[...m].sort().join(" and ")} — reusing a name across element / mode / preset is allowed but confusing; consider distinct names.`);return{errors:a,warnings:l};function y(u,m){!u||g(u)||a.push(`${m}: "${u}" is neither a defined block nor a registered Blockly block type.`)}}function Xt(i,t){if(i.size!==t.size)return!1;for(const e of i)if(!t.has(e))return!1;return!0}function Pe(i){const t=[...i].sort((e,o)=>e-o);return t.length?t.map(e=>`%${e}`).join(" "):"(none)"}class Yt{constructor(){v(this,"loadedStyleKeys",new Set)}ensureModeVisibilityStyles(t){const e=`mode-visibility:${t.map(r=>`${r.name}:${r.elements.join(",")}`).join(";")}`;if(this.loadedStyleKeys.has(e))return;const o=['[class^="morphic-element-"] { display: none; }'];for(const r of t){const s=R(r.name);for(const c of r.elements){const a=R(c);o.push(`.morphic-mode-${s} > .morphic-element-${a} { display: block; }`)}}const n=document.createElement("style");n.dataset.morphicSource="mode-visibility",n.textContent=o.join(`
|
|
23
|
+
`),document.head.appendChild(n),this.loadedStyleKeys.add(e)}ensureStyles(t,e){this.ensureStyleBundle(t,"base");for(const o of e)this.ensureStyleBundle(o,`mode:${o.mode}`)}async ensureToolbarStyles(){const t="toolbar";if(this.loadedStyleKeys.has(t))return;const o=(await Promise.resolve().then(()=>vo)).default,n=document.createElement("style");n.dataset.morphicSource="toolbar",n.textContent=o,document.head.appendChild(n),this.loadedStyleKeys.add(t)}ensureCategoryStyles(t){for(const e of t){if(!e.color)continue;const o=R(e.name),n=`category:${o}:${e.color}`;if(this.loadedStyleKeys.has(n))continue;const r=document.createElement("style");r.dataset.morphicSource=`category:${o}`,r.textContent=`.morphic-category-${o} { --morphic-category-color: ${e.color}; }`,document.head.appendChild(r),this.loadedStyleKeys.add(n)}}validateModeCoverage(t,e){const o=new Set(t.map(r=>r.mode)),n=e.filter(r=>!o.has(r));n.length>0&&console.warn(`[MorphicBlocks] Modes without explicit CSS definition: ${n.join(", ")}.`)}ensureStyleBundle(t,e){if(t){if(t.href){const o=`href:${t.href}`;if(!this.loadedStyleKeys.has(o)){const n=document.createElement("link");n.rel="stylesheet",n.href=t.href,n.dataset.morphicSource=e,document.head.appendChild(n),this.loadedStyleKeys.add(o)}}if(t.cssText){const o=`text:${e}:${t.cssText}`;if(!this.loadedStyleKeys.has(o)){const n=document.createElement("style");n.dataset.morphicSource=e,n.textContent=t.cssText,document.head.appendChild(n),this.loadedStyleKeys.add(o)}}}}}const q="morphic/block-type";class Re{constructor(t){v(this,"container");v(this,"workspaceContainer");v(this,"workspace");v(this,"definitions");v(this,"blockColors");v(this,"behaviors");v(this,"elementTypes");v(this,"options");v(this,"modes");v(this,"currentMode");v(this,"renderOverride");v(this,"previewWorkspace");v(this,"previewContainer");v(this,"onDragOver");v(this,"onDrop");this.container=t.container,this.workspaceContainer=t.workspaceContainer,this.workspace=t.workspace,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(q)&&e.preventDefault()},this.onDrop=e=>{var n;const o=(n=e.dataTransfer)==null?void 0:n.getData(q);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),(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 n=document.createElement("div");n.className="morphic-toolbox-header";const r=document.createElement("span");r.className="morphic-toolbar-label",r.textContent=`Mode: ${this.currentMode}`,n.appendChild(r),this.container.appendChild(n)}const t=this.resolveBlockIds(),e=this.options.categories??[];if(e.length===0){for(const n of t){const r=this.definitions.get(n);r&&this.container.appendChild(this.createTile(r))}return}const o=new Set;for(const n of e){const r=this.resolveCategoryBlockIds(n,t);if(r.length===0)continue;const s=document.createElement("div");s.setAttribute("data-category",R(n.name)),n.color&&s.style.setProperty("--morphic-category-color",n.color);for(const c of r){const a=this.definitions.get(c);a&&(s.appendChild(this.createTile(a)),o.add(c))}this.container.appendChild(s)}for(const n of t)if(!o.has(n)){const r=this.definitions.get(n);r&&this.container.appendChild(this.createTile(r))}}createTile(t){var d;const e=R(this.currentMode),o=R(t.identifier),n=this.blockColors.get(t.identifier),r=document.createElement("div");r.setAttribute("draggable","true"),r.setAttribute("data-block-type",t.identifier),r.className=`morphic-block morphic-mode-${e} morphic-block-${o}`,n&&r.style.setProperty("--morphic-block-color",n);const s=this.modes.find(f=>f.name===this.currentMode),c=(s==null?void 0:s.elements)??[],a=Object.entries(t.elements),l=[...c.map(f=>a.find(([w])=>w===f)).filter(f=>f!==void 0),...a.filter(([f])=>!c.includes(f))];for(const[f,w]of l){const g=document.createElement("div");g.className=`morphic-element-${R(f)}`;const b=this.elementTypes[f],C=G(b),y=C==="code",p=C==="image",h=((d=this.renderOverride)==null?void 0:d[f])??(y?"block":"text"),k=p?Qe(w,Xe(b)):w;if(y&&h==="block"){const E=this.createBlockPreviewSvg(t,this.currentMode);E?g.appendChild(E):g.innerHTML=Ce(X(k))}else g.innerHTML=Ce(X(k));r.appendChild(g)}return r.addEventListener("dragstart",f=>{var w;(w=f.dataTransfer)==null||w.setData(q,t.identifier)}),r}ensurePreviewWorkspace(){return this.previewWorkspace?this.previewWorkspace:(this.previewContainer=document.createElement("div"),this.previewContainer.style.cssText="position:absolute;left:-9999px;top:-9999px;width:800px;height:600px;overflow:hidden;",document.body.appendChild(this.previewContainer),this.previewWorkspace=T.inject(this.previewContainer,{scrollbars:!1}),this.previewWorkspace)}createBlockPreviewSvg(t,e){var o;try{const n=this.ensurePreviewWorkspace(),r=n.newBlock(z(t.identifier,this.definitions)),s=this.blockColors.get(t.identifier);s&&r.setColour(s);const c=ke(t,e,this.elementTypes,this.modes);xe({block:r,definition:t,view:c,mode:"block",context:"toolbox"});const a=Q(this.behaviors[t.identifier]);(o=a==null?void 0:a.onViewApplied)==null||o.call(a,r,{Blockly:T,workspace:n,mode:e,context:"toolbox",definition:t}),r.initSvg(),r.render();const l=r.getSvgRoot();if(!l)return r.dispose(!1),null;const d=l.getBBox(),f=l.cloneNode(!0),w=4,g=document.createElementNS("http://www.w3.org/2000/svg","svg");return g.setAttribute("width",String(Math.ceil(d.width+w*2))),g.setAttribute("height",String(Math.ceil(d.height+w*2))),g.setAttribute("viewBox",`${d.x-w} ${d.y-w} ${d.width+w*2} ${d.height+w*2}`),g.appendChild(f),r.dispose(!1),g}catch{return null}}createBlockAtPosition(t,e,o){const n=this.workspace,r=n.getInjectionDiv().getBoundingClientRect(),s=(e-r.left-n.scrollX)/n.scale,c=(o-r.top-n.scrollY)/n.scale,a=n.newBlock(z(t,this.definitions));a.initSvg(),a.render(),a.moveTo(new T.utils.Coordinate(s,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 n,r;return((r=(n=this.definitions.get(o))==null?void 0:n.category)==null?void 0:r.toLowerCase())===t.name.toLowerCase()})}}function we(i,t){var o;if(i.blocks&&i.blocks.length>0)return i.blocks;const e=[];for(const n of t.values())((o=n.category)==null?void 0:o.toLowerCase())===i.name.toLowerCase()&&e.push(n.identifier);return e}function Fe(i,t){var n,r,s;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:we(a,t).map(l=>({kind:"block",type:z(l,t)}))}))};if((r=i.categories)!=null&&r.length){const c=i.categories,a=[];return c.forEach((d,f)=>{const w=R(d.name);a.push({kind:"label",id:`morphic-category-${w}`,text:d.name,"web-class":`morphic-flyout-category-label morphic-category-${w}`});for(const g of Ve(we(d,t)))a.push({kind:"block",type:z(g,t)});f<c.length-1&&a.push({kind:"sep",gap:14})}),{kind:"flyoutToolbox",contents:a}}return{kind:"flyoutToolbox",contents:(i.blocks??Ve(((s=i.categories)==null?void 0:s.flatMap(c=>we(c,t)))??[...t.keys()])).map(c=>({kind:"block",type:z(c,t)}))}}function Ve(i){return i.filter((t,e,o)=>o.indexOf(t)===e)}const Jt='<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>',qt='<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>',Zt='<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>',Qt='<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>',eo='<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>',to='<svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor"><polygon points="4,3 13,8 4,13"/></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"><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>',no='<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>',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"><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>',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 2h8l2 2v10H3z"/><rect x="5" y="2" width="6" height="4"/><rect x="5" y="9" width="6" height="4"/></svg>',so='<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>',co='<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>',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="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:i=>{const t=document.createElement("span");return t.className="morphic-toolbar-label",t.textContent=lo(i),t}}},copy(){return{id:"copy",label:"Copy",title:"Copy block",icon:Jt,onClick:i=>{i.engine.copyActiveBlock(i.pane)}}},paste(){return{id:"paste",label:"Paste",title:"Paste block",icon:qt,disabled:i=>!i.engine.hasClipboardContents(),onClick:i=>{i.engine.pasteActiveBlock(i.pane)}}},undo(){return{id:"undo",label:"Undo",title:"Undo (block model)",icon:Zt,onClick:i=>{var t;(t=i.engine.getWorkspace())==null||t.undo(!1)},disabled:i=>{var t;return!((t=i.engine.getWorkspace())!=null&&t.getUndoStack().length)}}},redo(){return{id:"redo",label:"Redo",title:"Redo (block model)",icon:Qt,onClick:i=>{var t;(t=i.engine.getWorkspace())==null||t.undo(!0)},disabled:i=>{var t;return!((t=i.engine.getWorkspace())!=null&&t.getRedoStack().length)}}},zoomIn(){return{id:"zoom-in",label:"Zoom in",title:"Zoom in",icon:oo,onClick:i=>i.engine.zoomPane(i.pane,"in")}},zoomOut(){return{id:"zoom-out",label:"Zoom out",title:"Zoom out",icon:no,onClick:i=>i.engine.zoomPane(i.pane,"out")}},zoomFit(){return{id:"zoom-fit",label:"Fit",title:"Reset zoom",icon:io,onClick:i=>i.engine.zoomPane(i.pane,"fit")}},clear(){return{id:"clear",label:"Clear",title:"Clear workspace",icon:eo,onClick:i=>{var t;window.confirm("Clear workspace? This cannot be undone.")&&((t=i.engine.getWorkspace())==null||t.clear())}}},runCode(){return{id:"run",label:"Run",title:"Run generated code",icon:to,onClick:i=>{i.engine.runJavaScript()}}},save(){return{id:"save",label:"Save",title:"Save workspace as JSON",icon:ro,onClick:i=>{if(!i.engine.getWorkspace())return;const e=i.engine.serializeWorkspace(),o=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),n=URL.createObjectURL(o),r=document.createElement("a");r.href=n,r.download="workspace.json",r.click(),URL.revokeObjectURL(n)}}},load(){return{id:"load",label:"Load",title:"Load workspace JSON",icon:so,onClick:i=>{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 n=await e.text(),r=JSON.parse(n);i.engine.loadWorkspace(r)}catch(n){window.alert(`Load failed: ${n instanceof Error?n.message:String(n)}`)}}),t.click()}}},reset(){return{id:"reset",label:"Reset",title:"Reset workspace",icon:co,onClick:i=>{var t;window.confirm("Reset workspace to empty? This cannot be undone.")&&((t=i.engine.getWorkspace())==null||t.clear())}}},togglePreview(){return{id:"toggle-preview",label:"Preview",title:"Toggle preview pane",icon:ao,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}}},defaultsFor(i){switch(i){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 lo(i){const t=i.engine,e=i.pane==="workspace"?t.getWorkspaceMode():i.pane==="codespace"?t.getCodespaceMode():t.getPreviewMode();return e?`Mode: ${e}`:""}function _e(i,t,e){const o=t.items??O.defaultsFor(t.pane),n=t.display??"icon";i.classList.add("morphic-toolbar"),i.setAttribute("data-morphic-pane",t.pane);const r=document.createElement("div");r.className="morphic-toolbar-left";const s=document.createElement("div");s.className="morphic-toolbar-right";const c=()=>{r.replaceChildren(),s.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"?s:r).appendChild(ho(l,n,e))}};return i.replaceChildren(r,s),c(),{refresh:c,pane:t.pane,dispose:()=>i.replaceChildren()}}function ho(i,t,e){if(i.render){const n=i.render(e);if(typeof n=="string"){const r=document.createElement("span");return r.className="morphic-toolbar-item",r.dataset.toolbarId=i.id,r.textContent=n,r}return n.classList.add("morphic-toolbar-item"),n.dataset.toolbarId=i.id,n}const o=document.createElement("button");return o.className="morphic-toolbar-item",o.dataset.toolbarId=i.id,o.type="button",i.title&&(o.title=i.title),uo(o,i,t),i.disabled&&i.disabled(e)&&(o.disabled=!0),i.onClick&&o.addEventListener("click",()=>i.onClick(e)),o}function uo(i,t,e){const o=e!=="label"&&!!t.icon,n=e!=="icon"&&!!t.label,r=o||e==="icon"&&!t.label,s=n||e==="label"&&!t.icon;if(r&&t.icon){const c=document.createElement("span");c.className="morphic-toolbar-icon",c.innerHTML=t.icon,i.appendChild(c)}if(s&&t.label){const c=document.createElement("span");c.className="morphic-toolbar-text",c.textContent=t.label,i.appendChild(c)}!i.title&&t.label&&(i.title=t.label),!i.childNodes.length&&t.label&&(i.textContent=t.label)}function po(i){return Object.entries(i).map(([t,e])=>{const n=(t.split("/").pop()??t).replace(/\.css$/i,""),r=typeof e=="string"?e:typeof e=="object"&&e!==null&&"default"in e?String(e.default):void 0;return{mode:n,href:r}}).filter(t=>!!t.href).map(t=>t)}function ye(i){return typeof i=="string"?{mode:i}:{mode:i.mode,render:i.render}}class fo extends EventTarget{constructor(e,o={}){super();v(this,"definitions");v(this,"behaviors");v(this,"elementTypes");v(this,"styles",new Yt);v(this,"registeredBlockTypes",new Set);v(this,"toolbars",new Set);v(this,"toolbarsBlocklyListener");v(this,"lastCopyData");v(this,"mountConfig");v(this,"workspace");v(this,"flyoutWorkspace");v(this,"toolboxCanvas");v(this,"codeEditor");v(this,"codespace");v(this,"previewEditor");v(this,"selectionSync");v(this,"toolboxDefinition");v(this,"blockCategoryIndex",new Map);v(this,"appliedWorkspaceClasses",[]);v(this,"appliedToolboxFlyoutClasses",[]);v(this,"appliedToolboxShellClasses",[]);v(this,"headlessWorkspaceHost");v(this,"codespaceDropTeardown");v(this,"formatModes");v(this,"formatPresets");v(this,"formatHighlighting");v(this,"formatCategories");v(this,"onWorkspaceChange",e=>{if(!this.workspace||!this.mountConfig||e.workspaceId!==this.workspace.id||e.type!==T.Events.BLOCK_CREATE)return;const o=e;for(const n of o.ids??[]){const r=this.workspace.getBlockById(n);if(!r)continue;const s=this.definitions.get(_(r.type));s&&(this.applyView(r,s,this.mountConfig.workspaceMode,"workspace"),r.getSvgRoot()||this.deferApplyView(n,this.mountConfig.workspaceMode,"workspace"))}});v(this,"onFlyoutChange",e=>{if(!this.flyoutWorkspace||!this.mountConfig||e.workspaceId!==this.flyoutWorkspace.id||e.type!==T.Events.BLOCK_CREATE)return;const o=e;for(const n of o.ids??[]){const r=this.flyoutWorkspace.getBlockById(n);if(!r)continue;const s=this.definitions.get(_(r.type));s&&(this.applyView(r,s,this.mountConfig.toolboxMode,"toolbox"),r.getSvgRoot()||this.deferApplyView(n,this.mountConfig.toolboxMode,"toolbox"))}});this.definitions=Ut(e.blocks),this.behaviors=o,this.elementTypes=e.elementTypes??{},this.formatModes=e.modes,this.formatPresets=e.presets,this.formatHighlighting=e.highlighting,this.formatCategories=e.categories}mount(e){var k,E,u,m,x;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:((k=e.toolbox)==null?void 0:k.categories)??this.formatCategories}:void 0},n=o.modesFolder?po(o.modesFolder):[],r=[...n,...(o.modeStyles??[]).filter(S=>!n.some(L=>L.mode===S.mode))];this.validateDefinitions(o),this.validatePresets(o);const s=(E=o.presets)!=null&&E.length?o.presets.find(S=>S.name===o.preset)??o.presets[0]:void 0;if(o.preset&&!s)throw new Error(`MorphicBlocks.mount: unknown preset "${o.preset}".`);const c=(o.modes??[]).map(S=>S.name),l=r.map(S=>S.mode)[0]??c[0]??"default",d=s?ye(s.toolbox):void 0,f=s?s.workspace??s.codespace??l:o.workspaceMode??l,w=d?d.mode:o.toolboxMode??l,g=d==null?void 0:d.render,b=s?s.codespace:o.codespaceMode,C=s?s.preview:o.previewMode;this.validateContainers({...o,codespaceMode:b});const y=o.workspaceContainer??this.createHeadlessHost(),p={...o,modeStyles:r,workspaceMode:f,toolboxMode:w,toolboxRender:g,codespaceMode:b,previewMode:C,workspaceHost:y};this.mountConfig=p,this.styles.validateModeCoverage(r,c),(u=p.modes)!=null&&u.length&&this.styles.ensureModeVisibilityStyles(p.modes),this.styles.ensureStyles(p.baseStyle,r),this.blockCategoryIndex=this.createCategoryIndex(p.toolbox,p),this.styles.ensureCategoryStyles(((m=p.toolbox)==null?void 0:m.categories)??[]),this.registerBlocks(),this.toolboxDefinition=this.resolveToolboxDefinition(p);const h=p.blockly??p.blocklyOptions??{};return this.workspace=T.inject(p.workspaceHost,{...h,...p.canvasToolbox?{}:{toolbox:this.toolboxDefinition}}),this.workspace.addChangeListener(this.onWorkspaceChange),this.applyWorkspaceContainerClass(),this.refreshToolbox(),this.bindFlyoutWorkspace(),this.renderWorkspaceBlocks(),this.renderFlyoutBlocks(),s&&((x=p.onPresetApplied)==null||x.call(p,s)),this.workspace}getPresets(){var e;return[...((e=this.mountConfig)==null?void 0:e.presets)??[]]}applyPreset(e){var s,c;if(!this.mountConfig||!this.workspace)throw new Error("MorphicBlocks must be mounted before applyPreset can be used.");const o=this.mountConfig.presets??[],n=typeof e=="number"?o[e]:o.find(a=>a.name===e);if(!n)throw new Error(`applyPreset: unknown preset "${e}".`);const r=ye(n.toolbox);return this.setModes({toolboxMode:r.mode,toolboxRender:r.render??null,workspaceMode:n.workspace??n.codespace,codespaceMode:n.codespace??null,previewMode:n.preview??null}),(c=(s=this.mountConfig).onPresetApplied)==null||c.call(s,n),n}validateDefinitions(e){var r;const{errors:o,warnings:n}=$e({definitions:this.definitions,elementTypes:this.elementTypes,behaviors:this.behaviors,modes:e.modes,presets:e.presets,highlighting:e.highlighting,categories:(r=e.toolbox)==null?void 0:r.categories});if(n.length>0&&console.warn(`[MorphicBlocks] Definition warnings:
|
|
24
|
+
- ${n.join(`
|
|
25
|
+
- `)}`),o.length>0)throw new Error(`[MorphicBlocks] Invalid definitions:
|
|
26
|
+
- ${o.join(`
|
|
27
|
+
- `)}`)}validatePresets(e){const o=e.presets??[];if(o.length===0)return;const n=e.modes??[],r=new Map(n.map(c=>[c.name,c])),s=new Set;for(const c of o){if(s.has(c.name))throw new Error(`Preset "${c.name}" is defined more than once.`);if(s.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=ye(c.toolbox),l=[["toolbox",a.mode],["workspace",c.workspace],["codespace",c.codespace],["preview",c.preview]];for(const[d,f]of l){if(f===void 0)continue;const w=r.get(f);if(!w)throw new Error(`Preset "${c.name}": unknown mode "${f}" for ${d}.`);if((d==="codespace"||d==="preview")&&ae(w,this.elementTypes)===void 0)throw new Error(`Preset "${c.name}": mode "${f}" 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,n,r,s,c;(e=this.selectionSync)==null||e.disable(),this.selectionSync=void 0,(o=this.codeEditor)==null||o.dispose(),this.codeEditor=void 0,(n=this.codespaceDropTeardown)==null||n.call(this),this.codespaceDropTeardown=void 0,(r=this.codespace)==null||r.dispose(),this.codespace=void 0,(s=this.previewEditor)==null||s.dispose(),this.previewEditor=void 0,(c=this.toolboxCanvas)==null||c.dispose(),this.toolboxCanvas=void 0,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.toolboxDefinition=void 0,this.blockCategoryIndex.clear(),this.appliedWorkspaceClasses=[],this.appliedToolboxFlyoutClasses=[],this.appliedToolboxShellClasses=[]}mountToolbox(e,o){var r,s;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={...o,categories:(o==null?void 0:o.categories)??((s=this.mountConfig.toolbox)==null?void 0:s.categories)};this.toolboxCanvas=new Re({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:n})}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(n=>n.name===e)}getActivePrimarySourceElement(){const e=this.modeDef(this.getCodespaceMode());if(e)return ae(e,this.elementTypes)}getActivePreviewElement(){var o;const e=this.modeDef((o=this.mountConfig)==null?void 0:o.previewMode);if(e)return ae(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 n=_e(e,o,{engine:this,pane:o.pane,getText:()=>this.toolbarTextFor(o.pane),refresh:()=>this.toolbarRefreshFor(o.pane)});this.toolbars.add(n),this.ensureToolbarBlocklyListener();const r=n.dispose;return n.dispose=()=>{this.toolbars.delete(n),this.toolbars.size===0&&this.teardownToolbarBlocklyListener(),r()},n}toolbarTextFor(e){var o,n;if(e==="codespace")return((o=this.codespace)==null?void 0:o.getValue())??this.generateCodespaceText().code;if(e==="preview")return((n=this.previewEditor)==null?void 0:n.getValue())??"";if(this.codespace)return this.codespace.getValue();try{return this.generateJavaScript()}catch{return""}}toolbarRefreshFor(e){var o,n;e==="codespace"?(o=this.codespace)==null||o.refresh():e==="preview"&&((n=this.previewEditor)==null||n.refresh())}runJavaScript(e){let o="",n,r=null;try{o=this.generateJavaScript();const c=(e==null?void 0:e.console)??console;n=new Function("console",o)(c)}catch(c){r=c instanceof Error?c:new Error(String(c))}const s={code:o,result:n,error:r};return this.dispatchEvent(new CustomEvent("morphic-run",{detail:s})),s}hasClipboardContents(){return!!this.lastCopyData}copyActiveBlock(e){var r;const o=this.resolveActiveBlock(e);if(!o)return!1;const n=o.toCopyData();if(!n)return!1;this.lastCopyData=n;try{const s=this.toolbarTextFor(e==="workspace"?"codespace":e);s&&((r=navigator.clipboard)==null||r.writeText(s))}catch{}for(const s of this.toolbars)s.refresh();return!0}pasteActiveBlock(e){return!this.lastCopyData||!this.workspace?!1:T.clipboard.paste(this.lastCopyData,this.workspace)!==null}resolveActiveBlock(e){var n,r;const o=T.common.getSelected();if(o&&"id"in o&&((n=this.workspace)!=null&&n.getBlockById(o.id)))return o;if(e==="codespace"||e==="preview"){const s=e==="codespace"?this.codespace:this.previewEditor;if(s){const c=s.metadata,a=s.getCursorLine();let l=null;for(const[d,f]of c)if(f.startLine<=a&&f.endLine>=a){const w=f.endLine-f.startLine;(!l||w<l.size)&&(l={id:d,size:w})}if(l){const d=(r=this.workspace)==null?void 0:r.getBlockById(l.id);if(d)return d}}}return null}serializeWorkspace(){return this.workspace?T.serialization.workspaces.save(this.workspace):null}loadWorkspace(e){this.workspace&&(this.workspace.clear(),T.serialization.workspaces.load(e,this.workspace))}zoomPane(e,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 n=e==="codespace"?this.codespace:this.previewEditor;n==null||n.adjustZoom(o)}ensureToolbarBlocklyListener(){if(this.toolbarsBlocklyListener||!this.workspace)return;const e=o=>{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 o,n,r,s,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.refreshToolbox(),this.bindFlyoutWorkspace(),this.renderWorkspaceBlocks(),this.renderFlyoutBlocks(),(n=this.codespace)==null||n.setHighlightRules(this.resolveHighlightRules("codespace")),(r=this.previewEditor)==null||r.setHighlightRules(this.resolveHighlightRules("preview")),(s=this.codespace)==null||s.refresh(),(c=this.previewEditor)==null||c.refresh();for(const l of this.toolbars)l.refresh();(a=this.selectionSync)==null||a.clearAll()}resolveHighlightRules(e){var n;if(!this.mountConfig)return;const o=e==="codespace"?this.getActivePrimarySourceElement():this.getActivePreviewElement();if(o)return(n=this.mountConfig.highlighting)==null?void 0:n[o]}generateJavaScript(){if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before generateJavaScript can be used.");return Mt(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 Bt(this.workspace,this.definitions,this.behaviors,this.mountConfig.javascript)}async mountCodeEditor(e,o){var n;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before mountCodeEditor can be used.");(n=this.codeEditor)==null||n.dispose(),this.codeEditor=new fe(e,this.workspace,()=>this.generateJavaScriptWithMetadata(),o),await this.codeEditor.mount()}async mountCodespace(e){var n,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().");(n=this.codespace)==null||n.dispose(),(r=this.codespaceDropTeardown)==null||r.call(this);const o={...e,onDelete:(e==null?void 0:e.onDelete)??(s=>this.deleteBlockAtCodespaceLine(s)),canDragBlock:(e==null?void 0:e.canDragBlock)??(s=>{var a;const c=(a=this.workspace)==null?void 0:a.getBlockById(s);return!!(c!=null&&c.previousConnection||c!=null&&c.outputConnection)}),highlightRules:(e==null?void 0:e.highlightRules)??this.resolveHighlightRules("codespace"),onPlaceholderApply:(e==null?void 0:e.onPlaceholderApply)??((s,c)=>this.applyPlaceholderEdit(s,c))};this.codespace=new fe(this.mountConfig.codespaceContainer,this.workspace,()=>this.generateCodespaceText(),o),await this.codespace.mount(),this.codespaceDropTeardown=this.attachCodespaceDropTarget(this.mountConfig.codespaceContainer,this.workspace)}attachCodespaceDropTarget(e,o){const n=p=>{var k;const h=(k=p.dataTransfer)==null?void 0:k.types;return h?h.includes(q)||h.includes(ue):!1},r=p=>{var k,E,u,m,x,S;if(!n(p))return;p.preventDefault();const h=this.computeCodespaceDrop(p.clientX,p.clientY);if(!h){(k=this.codespace)==null||k.hideDropIndicator(),(E=this.codespace)==null||E.hideValueSlotHighlight();return}h.indicator.kind==="line"?((u=this.codespace)==null||u.showDropIndicator(h.indicator.line,h.indicator.position),(m=this.codespace)==null||m.hideValueSlotHighlight()):((x=this.codespace)==null||x.showValueSlotHighlight(h.indicator.from,h.indicator.to),(S=this.codespace)==null||S.hideDropIndicator())},s=p=>{var k,E;const h=p.relatedTarget;h&&e.contains(h)||((k=this.codespace)==null||k.hideDropIndicator(),(E=this.codespace)==null||E.hideValueSlotHighlight())},c=p=>{var x,S,L,I;if(!n(p))return;p.preventDefault(),(x=this.codespace)==null||x.hideDropIndicator(),(S=this.codespace)==null||S.hideValueSlotHighlight();const h=this.computeCodespaceDrop(p.clientX,p.clientY);if(!h)return;const k=(L=p.dataTransfer)==null?void 0:L.getData(q),E=(I=p.dataTransfer)==null?void 0:I.getData(ue);let u=null;if(k)u=o.newBlock(z(k,this.definitions)),u.initSvg(),u.render();else if(E){if(u=o.getBlockById(E),!u)return}else return;let m=!1;T.Events.setGroup(!0);try{if(E&&u.getParent()&&u.unplug(!0),h.target.kind==="top")this.placeAtTopIndex(o,u,h.target.index),m=!0;else if(h.target.kind==="statement"){if(u.previousConnection){const D=o.getBlockById(h.target.targetBlockId);D&&D!==u&&(this.connectStatement(u,D,h.target.position),m=!0)}}else if(h.target.kind==="into-slot"){if(u.previousConnection){const D=o.getBlockById(h.target.parentBlockId);D&&D!==u&&(this.connectIntoSlot(u,D,h.target.inputName),m=!0)}}else if(h.target.kind==="value-slot"){if(u.outputConnection){const D=o.getBlockById(h.target.parentBlockId);D&&D!==u&&!this.isDescendantOf(D,u)&&(m=this.connectIntoValueSlot(u,D,h.target.inputName))}!m&&k&&u.dispose(!1)}}finally{T.Events.setGroup(!1)}!m&&u.workspace&&!u.getParent()&&this.placeOrphanBelowTops(u),T.svgResize(o)};let a=null;const l=3,d=p=>p.button===2||p.button===0&&p.ctrlKey,f=p=>{var k,E,u,m,x,S;if(!a)return;if(!a.dragging){const L=Math.abs(p.clientX-a.startX),I=Math.abs(p.clientY-a.startY);if(L+I<l)return;a.dragging=!0}const h=this.computeCodespaceDrop(p.clientX,p.clientY);if(!h){(k=this.codespace)==null||k.hideDropIndicator(),(E=this.codespace)==null||E.hideValueSlotHighlight();return}h.indicator.kind==="line"?((u=this.codespace)==null||u.showDropIndicator(h.indicator.line,h.indicator.position),(m=this.codespace)==null||m.hideValueSlotHighlight()):((x=this.codespace)==null||x.showValueSlotHighlight(h.indicator.from,h.indicator.to),(S=this.codespace)==null||S.hideDropIndicator())},w=p=>{var u,m;window.removeEventListener("mousemove",f),window.removeEventListener("mouseup",w),(u=this.codespace)==null||u.hideDropIndicator(),(m=this.codespace)==null||m.hideValueSlotHighlight();const h=a;if(a=null,Te(void 0),!(h!=null&&h.dragging))return;const k=this.computeCodespaceDrop(p.clientX,p.clientY);if(!k)return;const E=o.getBlockById(h.sourceId);E&&this.applyRightDragMove(o,E,k)},g=p=>{var E;if(!d(p))return;const h=(E=this.codespace)==null?void 0:E.charAtCoords(p.clientX,p.clientY);if(h==null)return;const k=this.findInnermostBlockAtChar(h);k&&(p.preventDefault(),p.stopPropagation(),a={sourceId:k.id,startX:p.clientX,startY:p.clientY,dragging:!1},Te(k.id),window.addEventListener("mousemove",f),window.addEventListener("mouseup",w))},b=p=>{p.preventDefault()},C=p=>{var m,x,S,L,I,D,H,F;if(a)return;const h=(m=this.codespace)==null?void 0:m.charAtCoords(p.clientX,p.clientY);if(h==null){(x=this.codespace)==null||x.setHoverHighlight(null),(S=this.codespace)==null||S.setEditableHoverHighlight(null);return}const k=this.findInnermostEditablePlaceholderAtChar(h);(L=this.codespace)==null||L.setEditableHoverHighlight(k?{from:k.start,to:k.end}:null);const E=this.findHoverBlockAtChar(h);if(!E){(I=this.codespace)==null||I.setHoverHighlight(null);return}const u=(D=this.codespace)==null?void 0:D.metadata.get(E.id);if(!u||u.startChar===void 0||u.endChar===void 0){(H=this.codespace)==null||H.setHoverHighlight(null);return}(F=this.codespace)==null||F.setHoverHighlight({from:u.startChar,to:u.endChar})},y=()=>{var p,h;(p=this.codespace)==null||p.setHoverHighlight(null),(h=this.codespace)==null||h.setEditableHoverHighlight(null)};return e.addEventListener("dragover",r),e.addEventListener("dragleave",s),e.addEventListener("drop",c),e.addEventListener("mousedown",g,!0),e.addEventListener("contextmenu",b),e.addEventListener("mousemove",C),e.addEventListener("mouseleave",y),()=>{e.removeEventListener("dragover",r),e.removeEventListener("dragleave",s),e.removeEventListener("drop",c),e.removeEventListener("mousedown",g,!0),e.removeEventListener("contextmenu",b),e.removeEventListener("mousemove",C),e.removeEventListener("mouseleave",y),window.removeEventListener("mousemove",f),window.removeEventListener("mouseup",w)}}findInnermostBlockAtChar(e){if(!this.workspace||!this.codespace)return null;let o=null;for(const[n,r]of this.codespace.metadata){if(r.startChar===void 0||r.endChar===void 0||e<r.startChar||e>=r.endChar)continue;const s=r.endChar-r.startChar;(o===null||s<o.size)&&(o={id:n,size:s})}return o?this.workspace.getBlockById(o.id):null}findHoverBlockAtChar(e){if(!this.workspace||!this.codespace)return null;let o=null,n=null;for(const[s,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;(n===null||a<n.size)&&(n={id:s,size:a}),!c.atomic&&(o===null||a<o.size)&&(o={id:s,size:a})}const r=o??n;return r?this.workspace.getBlockById(r.id):null}findInnermostEditablePlaceholderAtChar(e){if(!this.codespace)return null;let o=null;for(const n of this.codespace.getPlaceholders()){if(!n.edit||e<n.start||e>=n.end)continue;const r=n.end-n.start;(o===null||r<o.size)&&(o={ph:n,size:r})}return o?{start:o.ph.start,end:o.ph.end}:null}applyRightDragMove(e,o,n){if(!n)return;let r=!1;T.Events.setGroup(!0);try{if(o.getParent()&&o.unplug(!0),n.target.kind==="top")this.placeAtTopIndex(e,o,n.target.index),r=!0;else if(n.target.kind==="statement"){if(o.previousConnection){const s=e.getBlockById(n.target.targetBlockId);s&&s!==o&&(this.connectStatement(o,s,n.target.position),r=!0)}}else if(n.target.kind==="into-slot"){if(o.previousConnection){const s=e.getBlockById(n.target.parentBlockId);s&&s!==o&&(this.connectIntoSlot(o,s,n.target.inputName),r=!0)}}else if(n.target.kind==="value-slot"&&o.outputConnection){const s=e.getBlockById(n.target.parentBlockId);s&&s!==o&&!this.isDescendantOf(s,o)&&(r=this.connectIntoValueSlot(o,s,n.target.inputName))}}finally{T.Events.setGroup(!1)}!r&&o.workspace&&!o.getParent()&&this.placeOrphanBelowTops(o),T.svgResize(e)}computeCodespaceDrop(e,o){var f,w;if(!this.workspace||!this.codespace)return null;const n=this.workspace.getTopBlocks(!0),r=this.codespace.metadata,s=this.codespace.getLineCount();if(n.length===0)return{indicator:{kind:"line",line:1,position:"above"},target:{kind:"top",index:0}};if(this.codespace.isBelowLastLine(o)){const g=r.get(n[n.length-1].id);return{indicator:{kind:"line",line:(g==null?void 0:g.endLine)??s,position:"below"},target:{kind:"top",index:n.length}}}const c=this.codespace.getLineAtCoords(e,o);if(c===null){const g=r.get(n[0].id);return{indicator:{kind:"line",line:(g==null?void 0:g.startLine)??1,position:"above"},target:{kind:"top",index:0}}}const a=this.codespace.charAtCoords(e,o);if(a!==null){const g=this.findValueSlotDropAtChar(a);if(g)return{indicator:{kind:"value-slot",from:g.highlight.from,to:g.highlight.to},target:{kind:"value-slot",parentBlockId:g.parentBlockId,inputName:g.inputName}}}const l=this.findInnermostStatementSlotAtLine(c,r);if(l){const g=this.workspace.getBlockById(l.blockId);if(g){const b=Le(),C=[];let y=(w=(f=g.getInput(l.inputName))==null?void 0:f.connection)==null?void 0:w.targetBlock();for(;y;)y.id!==b&&C.push(y),y=y.getNextBlock();for(const p of C){const h=r.get(p.id);if(!h||c<h.startLine||c>h.endLine)continue;const k=c===h.endLine,E=this.codespace.isInLowerHalfOfLine(c,o);return k&&E?{indicator:{kind:"line",line:h.endLine,position:"below"},target:{kind:"statement",targetBlockId:p.id,position:"after"}}:{indicator:{kind:"line",line:h.startLine,position:"above"},target:{kind:"statement",targetBlockId:p.id,position:"before"}}}if(C.length>0){const p=C[C.length-1],h=r.get(p.id);return{indicator:{kind:"line",line:(h==null?void 0:h.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 g=0;g<n.length;g++){const b=r.get(n[g].id);if(!b||c<b.startLine||c>b.endLine)continue;const C=c===b.endLine,y=this.codespace.isInLowerHalfOfLine(c,o);return C&&y?{indicator:{kind:"line",line:b.endLine,position:"below"},target:{kind:"top",index:g+1}}:{indicator:{kind:"line",line:b.startLine,position:"above"},target:{kind:"top",index:g}}}const d=r.get(n[n.length-1].id);return{indicator:{kind:"line",line:(d==null?void 0:d.endLine)??s,position:"below"},target:{kind:"top",index:n.length}}}findInnermostStatementSlotAtLine(e,o){let n=null;for(const[r,s]of o)if(s.statementSlots)for(const[c,a]of Object.entries(s.statementSlots)){if(e<a.startLine||e>a.endLine)continue;const l=a.endLine-a.startLine,d=this.computeBlockDepth(r);(n===null||l<n.size||l===n.size&&d>n.depth)&&(n={blockId:r,inputName:c,range:a,size:l,depth:d})}return n?{blockId:n.blockId,inputName:n.inputName,range:n.range}:null}connectIntoSlot(e,o,n){if(!e.previousConnection)return;const r=o.getInput(n),s=r==null?void 0:r.connection;if(!s)return;const c=s.targetBlock();if(!c){s.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 r,s;if(!this.workspace||!this.codespace)return null;const o=Le();for(const c of this.codespace.getPlaceholders()){if(e<c.start||e>=c.end)continue;if(c.emptySlot){const{parentBlockId:f,inputName:w}=c.emptySlot;if(f===o)continue;const g=this.workspace.getBlockById(f);if(!((r=g==null?void 0:g.getInput(w))!=null&&r.connection))continue;return{parentBlockId:f,inputName:w,highlight:{from:c.start,to:c.end}}}const a=(s=c.edit)==null?void 0:s.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 n=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;(n===null||d<n.size)&&(n={id:c,size:d,from:a.startChar,to:a.endChar})}if(n){const c=this.workspace.getBlockById(n.id);if(c){const a=this.resolveValueParent(c);if(a)return{parentBlockId:a.parentBlockId,inputName:a.inputName,highlight:{from:n.from,to:n.to}}}}return null}resolveValueParent(e){var r;const o=(r=e.outputConnection)==null?void 0:r.targetConnection;if(!o)return null;const n=o.getSourceBlock();if(!n)return null;for(const s of n.inputList)if(s.connection===o)return{parentBlockId:n.id,inputName:s.name};return null}placeOrphanBelowTops(e){var r,s;if(!this.workspace)return;const o=this.workspace.getTopBlocks(!0).filter(c=>c.id!==e.id);if(o.length===0){e.moveTo(new T.utils.Coordinate(20,20));return}let n=0;for(const c of o){const a=c.getRelativeToSurfaceXY(),l=((s=(r=c.getHeightWidth)==null?void 0:r.call(c))==null?void 0:s.height)??50;n=Math.max(n,a.y+l)}e.moveTo(new T.utils.Coordinate(20,n+20))}isDescendantOf(e,o){let n=e;for(;n;){if(n===o)return!0;n=n.getParent()}return!1}connectIntoValueSlot(e,o,n){if(!e.outputConnection)return!1;const r=o.getInput(n),s=r==null?void 0:r.connection;if(!s)return!1;const c=s.targetBlock(),a=!!c&&!c.isShadow();a&&(c.unplug(!1),this.placeOrphanBelowTops(c));const d=s.check_;s.setCheck(null);try{return s.connect(e.outputConnection),!0}catch{if(a&&(c!=null&&c.outputConnection))try{s.connect(c.outputConnection)}catch{}return!1}finally{s.setCheck(d)}}computeBlockDepth(e){var r,s;let o=0,n=((s=(r=this.workspace)==null?void 0:r.getBlockById(e))==null?void 0:s.getParent())??null;for(;n;)o++,n=n.getParent();return o}placeAtTopIndex(e,o,n){const r=e.getTopBlocks(!0).map(c=>c.id).filter(c=>c!==o.id),s=Math.max(0,Math.min(n,r.length));r.splice(s,0,o.id),this.applyTopBlockOrder(e,r)}connectStatement(e,o,n){var r,s,c;if(e.previousConnection)if(n==="before"){const a=((r=o.previousConnection)==null?void 0:r.targetConnection)??null;(s=o.previousConnection)==null||s.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 r,s,c;const n=T.Events.disable!==void 0;n&&T.Events.disable();try{for(let a=0;a<o.length;a++){const l=e.getBlockById(o[a]);l&&l.moveTo(new T.utils.Coordinate(20,20+a*100))}}finally{n&&T.Events.enable()}T.svgResize(e),(r=this.codespace)==null||r.refresh(),(s=this.previewEditor)==null||s.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 n={...o,highlightRules:(o==null?void 0:o.highlightRules)??this.resolveHighlightRules("preview"),showPlaceholderMarkers:(o==null?void 0:o.showPlaceholderMarkers)??!1};this.previewEditor=new fe(e,this.workspace,()=>this.generatePreviewText(),n),await this.previewEditor.mount()}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:[]}:ve(this.workspace,e,this.definitions,this.elementTypes,this.mountConfig.modes??[],o)}applyPlaceholderEdit(e,o){var a;if(!this.workspace)return;let n=this.workspace.getBlockById(e.blockId);if(!n)return;if(n.isShadow()){const l=(a=n.outputConnection)==null?void 0:a.targetConnection;if(l){const d=this.workspace.newBlock(n.type);for(const f of n.inputList)for(const w of f.fieldRow){if(!w.name)continue;const g=d.getField(w.name);g&&g.setValue(w.getValue())}n.rendered&&(d.initSvg(),d.render()),l.connect(d.outputConnection),n=d}}const r=n.getField(e.fieldName);if(!r)return;r.setValue(o);const s=n;s.rendered&&typeof s.render=="function"&&s.render();const c=n.getParent();if(c){const l=c;l.rendered&&typeof l.render=="function"&&l.render()}}deleteBlockAtCodespaceLine(e){var s,c;const o=(s=this.codespace)==null?void 0:s.metadata;if(!this.workspace||!o||o.size===0)return;let n=null,r=1/0;for(const[a,{startLine:l,endLine:d}]of o){if(e<l||e>d)continue;const f=d-l;f<r&&(r=f,n=a)}n&&((c=this.workspace.getBlockById(n))==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),n=o?ae(o,this.elementTypes):void 0;return ve(this.workspace,e,this.definitions,this.elementTypes,this.mountConfig.modes??[],n)}return ve(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 n;if(!this.workspace)throw new Error("MorphicBlocks must be mounted before enableSelectionSync can be used.");const o=[this.codeEditor,this.codespace,this.previewEditor].filter(r=>r!==void 0);if(o.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.selectionSync=new Kt(this.workspace,o,e),this.selectionSync.enable()}disableSelectionSync(){var e;(e=this.selectionSync)==null||e.disable(),this.selectionSync=void 0}registerBlocks(){for(const e of this.definitions.values()){const o=ge(e.identifier);if(this.registeredBlockTypes.has(o))continue;const n=this;T.Blocks[o]={init(){var a;const r=this.workspace.isFlyout?"toolbox":"workspace",s=n.resolveMode(r);n.applyView(this,e,s,r);const c=Q(n.behaviors[e.identifier]);(a=c==null?void 0:c.init)==null||a.call(c,this,n.createBehaviorContext(this,e,s,r))}},this.registeredBlockTypes.add(o)}}validateContainers(e){if(!e.workspaceContainer&&!e.codespaceContainer)throw new Error("MorphicBlocks.mount requires at least one of workspaceContainer or codespaceContainer.");if(e.codespaceMode&&!e.codespaceContainer)throw new Error("MorphicBlocks.mount: codespaceMode requires a 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,n,r){var f,w;if(e.isDeadOrDying())return;const s=this.blockCategoryIndex.get(o.identifier);o.color===void 0&&(s==null?void 0:s.color)!==void 0&&e.setColour(s.color);const c=gt(e),a=ke(o,n,this.elementTypes,((f=this.mountConfig)==null?void 0:f.modes)??[]),l=e.workspace===this.workspace;xe({block:e,definition:o,view:a,mode:n,context:r,elementTypes:l?this.elementTypes:void 0,resolveBlocklyType:g=>z(g,this.definitions)}),nt(e,s==null?void 0:s.token),it(e,o.identifier),rt(e),o.color!==void 0&&(e.setColour(o.color),e.rendered&&e.render());const d=Q(this.behaviors[o.identifier]);(w=d==null?void 0:d.onViewApplied)==null||w.call(d,e,this.createBehaviorContext(e,o,n,r)),kt(e,c)}applyWorkspaceContainerClass(){var n;if(!this.mountConfig)return;const e=this.mountConfig.workspaceHost;he(e,this.mountConfig.workspaceMode,"workspace","morphic-workspace-root");const o=this.resolveClassNames((n=this.mountConfig.ui)==null?void 0:n.workspaceClassName);this.replaceUserClasses(e,this.appliedWorkspaceClasses,o),this.appliedWorkspaceClasses=o}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(),n=((a=o==null?void 0:o.getDiv)==null?void 0:a.call(o))??null;n&&(he(n,this.mountConfig.toolboxMode,"toolbox","morphic-toolbox-shell"),this.replaceUserClasses(n,this.appliedToolboxShellClasses,e),this.appliedToolboxShellClasses=e);const r=(l=this.workspace.getFlyout())==null?void 0:l.getWorkspace(),s=r==null?void 0:r.getParentSvg();s&&(he(s,this.mountConfig.toolboxMode,"toolbox","morphic-toolbox-root"),this.replaceUserClasses(s,this.appliedToolboxFlyoutClasses,e),this.appliedToolboxFlyoutClasses=e)}renderWorkspaceBlocks(){if(!(!this.workspace||!this.mountConfig))for(const e of this.workspace.getAllBlocks(!1)){const o=e,n=this.definitions.get(_(o.type));n&&this.applyView(o,n,this.mountConfig.workspaceMode,"workspace")}}renderFlyoutBlocks(){if(!(!this.flyoutWorkspace||!this.mountConfig)){for(const e of this.flyoutWorkspace.getAllBlocks(!1)){const o=e,n=this.definitions.get(_(o.type));n&&this.applyView(o,n,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,this.flyoutWorkspace.addChangeListener(this.onFlyoutChange),this.applyFlyoutClass())}resolveToolboxDefinition(e){if(e.toolbox){const r=this.resolveToolboxKind(e.toolboxLayout),s=r?{...e.toolbox,kind:r}:e.toolbox;return Fe(s,this.definitions)}const o=e.blockly??e.blocklyOptions;if(o!=null&&o.toolbox)return o.toolbox;const n=this.resolveToolboxKind(e.toolboxLayout);return Fe({...n!==void 0?{kind:n}:{},blocks:[...this.definitions.keys()]},this.definitions)}createBehaviorContext(e,o,n,r){return{Blockly:T,workspace:e.workspace,mode:n,context:r,definition:o}}resolveClassNames(e){return e?(Array.isArray(e)?e.join(" "):e).split(/\s+/).map(n=>n.trim()).filter((n,r,s)=>!!n&&s.indexOf(n)===r):[]}replaceUserClasses(e,o,n){for(const r of o)e.classList.remove(r);for(const r of n)e.classList.add(r)}buildBlockColorMap(){var o;const e=new Map;for(const[n,r]of this.definitions){const s=r.color??((o=this.blockCategoryIndex.get(n))==null?void 0:o.color);s!==void 0&&e.set(n,String(s))}return e}resolveToolboxKind(e){if(e)return e==="category"?"categoryToolbox":"flyoutToolbox"}createCategoryIndex(e,o){const n=new Map,r=(e==null?void 0:e.categories)??[],s=new Map;for(const a of r){const l=R(a.name);if(s.set(a.name.toLowerCase(),{token:l,color:a.color}),a.blocks)for(const d of a.blocks)n.has(d)||n.set(d,{token:l,color:a.color})}const c=o?this.definitions:new Map;for(const a of c.values()){if(!a.category||n.has(a.identifier))continue;const l=s.get(a.category.toLowerCase());l&&n.set(a.identifier,l)}return n}deferApplyView(e,o,n){const r=n==="toolbox"?this.flyoutWorkspace:this.workspace;r&&requestAnimationFrame(()=>{const s=r.getBlockById(e);if(!s)return;const c=this.definitions.get(_(s.type));c&&this.applyView(s,c,o,n)})}}function mo(i,t,e){return Math.min(Math.max(i,t),e)}function go(i,t){const{target:e,axis:o,invert:n=!1,onResize:r}=t,s=t.min??0,c=t.max??Number.POSITIVE_INFINITY,a=l=>{if(l.button!==0)return;l.preventDefault();const d=e.getBoundingClientRect(),f=o==="x"?d.width:d.height,w=o==="x"?l.clientX:l.clientY,g=document.body.style.userSelect,b=document.body.style.cursor;document.body.style.userSelect="none",document.body.style.cursor=o==="x"?"col-resize":"row-resize",i.setPointerCapture(l.pointerId);const C=p=>{const k=(o==="x"?p.clientX:p.clientY)-w,E=mo(f+(n?-k:k),s,c);e.style.flexBasis=`${E}px`,r==null||r(E)},y=()=>{i.removeEventListener("pointermove",C),i.removeEventListener("pointerup",y),i.removeEventListener("lostpointercapture",y),document.body.style.userSelect=g,document.body.style.cursor=b};i.addEventListener("pointermove",C),i.addEventListener("pointerup",y),i.addEventListener("lostpointercapture",y)};return i.addEventListener("pointerdown",a),{dispose:()=>i.removeEventListener("pointerdown",a)}}const ko=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"})),vo=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=fo,A.MorphicToolboxCanvas=Re,A.makeResizable=go,A.renderToolbar=_e,A.toolbarItems=O,A.validateDefinitions=$e,Object.defineProperty(A,Symbol.toStringTag,{value:"Module"})}));
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
const o = ".morphic-toolbar{display:flex;align-items:center;gap:var(--morphic-toolbar-gap, .5em);padding:var(--morphic-toolbar-padding, 4px 8px);background:var(--morphic-toolbar-bg, inherit);color:var(--morphic-toolbar-fg, inherit);font:var(--morphic-toolbar-font, inherit);border-bottom:var(--morphic-toolbar-border, 1px solid rgba(127, 127, 127, .2));box-sizing:border-box}.morphic-toolbar-left,.morphic-toolbar-right{display:flex;align-items:center;gap:var(--morphic-toolbar-gap, .5em)}.morphic-toolbar-right{margin-left:auto}.morphic-toolbar-item{display:inline-flex;align-items:center;gap:4px;background:var(--morphic-toolbar-item-bg, transparent);color:inherit;border:var(--morphic-toolbar-item-border, none);padding:var(--morphic-toolbar-item-padding, 2px 6px);border-radius:var(--morphic-toolbar-item-radius, 3px);cursor:pointer;font:inherit;line-height:1}.morphic-toolbar-item:hover:not(:disabled){background:var(--morphic-toolbar-item-hover-bg, rgba(127, 127, 127, .15))}.morphic-toolbar-item:disabled{opacity:.4;cursor:default}.morphic-toolbar-icon{display:inline-flex}.morphic-toolbar-label{opacity:.7;font-size:.9em}.morphic-toolbox-header{display:flex;align-items:center;padding:4px 6px 8px}.morphic-toolbar-badge{font-size:.85em;opacity:.6;padding:1px 6px;border:1px solid currentColor;border-radius:3px}.morphic-toolbar-spacer{flex:1}";
|
|
2
|
+
export {
|
|
3
|
+
o as default
|
|
4
|
+
};
|
package/package.json
CHANGED
|
@@ -1,8 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "morphic-blocks",
|
|
3
|
-
"version": "0.0
|
|
4
|
-
"description": "
|
|
5
|
-
"
|
|
6
|
-
|
|
7
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Mode-driven wrapper framework around Google Blockly",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/morphicblocks/morphic-blocks.git",
|
|
8
|
+
"directory": "packages/morphic-blocks"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/morphicblocks/morphic-blocks#readme",
|
|
11
|
+
"bugs": "https://github.com/morphicblocks/morphic-blocks/issues",
|
|
12
|
+
"type": "module",
|
|
13
|
+
"main": "./dist/morphic-blocks.umd.cjs",
|
|
14
|
+
"module": "./dist/morphic-blocks.js",
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"import": "./dist/morphic-blocks.js",
|
|
20
|
+
"require": "./dist/morphic-blocks.umd.cjs"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"definitions.schema.json",
|
|
26
|
+
"NOTICE"
|
|
27
|
+
],
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "vite build && tsc -p tsconfig.build.json"
|
|
30
|
+
},
|
|
31
|
+
"keywords": [
|
|
32
|
+
"blockly",
|
|
33
|
+
"framework",
|
|
34
|
+
"visual-programming",
|
|
35
|
+
"morphic"
|
|
36
|
+
],
|
|
37
|
+
"license": "Apache-2.0",
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"blockly": "^11.2.2"
|
|
40
|
+
},
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"@codemirror/lang-javascript": "^6.0.0",
|
|
43
|
+
"@codemirror/state": "^6.0.0",
|
|
44
|
+
"@codemirror/view": "^6.0.0"
|
|
45
|
+
},
|
|
46
|
+
"peerDependenciesMeta": {
|
|
47
|
+
"@codemirror/lang-javascript": { "optional": true },
|
|
48
|
+
"@codemirror/state": { "optional": true },
|
|
49
|
+
"@codemirror/view": { "optional": true }
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@codemirror/lang-javascript": "^6.2.3",
|
|
53
|
+
"@codemirror/state": "^6.5.2",
|
|
54
|
+
"@codemirror/view": "^6.36.5",
|
|
55
|
+
"typescript": "^5.8.2",
|
|
56
|
+
"vite": "^6.2.0"
|
|
57
|
+
}
|
|
8
58
|
}
|