morphic-blocks 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -21
- package/definitions.schema.json +147 -14
- package/dist/cli.js +6 -17
- package/dist/copy-media-CllRyMqQ.js +21 -0
- package/dist/copy-media.d.ts +8 -0
- package/dist/esbuild.d.ts +3 -0
- package/dist/esbuild.js +10 -0
- package/dist/index.d.ts +4 -1
- package/dist/morphic/MorphicBlocks.d.ts +141 -66
- package/dist/morphic/asset-urls.d.ts +9 -0
- package/dist/morphic/block-sets.d.ts +12 -0
- package/dist/morphic/block-view.d.ts +72 -4
- package/dist/morphic/check-definitions.d.ts +31 -0
- package/dist/morphic/code-editor.d.ts +22 -3
- package/dist/morphic/constants.d.ts +6 -0
- package/dist/morphic/dropdown-fields.d.ts +72 -0
- package/dist/morphic/element-types.d.ts +1 -1
- package/dist/morphic/operators.d.ts +73 -0
- package/dist/morphic/parent-field.d.ts +7 -0
- package/dist/morphic/repeat-slots.d.ts +31 -0
- package/dist/morphic/resize.d.ts +7 -2
- package/dist/morphic/strict-slots.d.ts +10 -0
- package/dist/morphic/styles.d.ts +5 -0
- package/dist/morphic/template-codegen.d.ts +16 -0
- package/dist/morphic/template.d.ts +42 -1
- package/dist/morphic/text-to-blocks.d.ts +34 -0
- package/dist/morphic/toolbar.d.ts +8 -11
- package/dist/morphic/toolbox-canvas.d.ts +34 -11
- package/dist/morphic/types.d.ts +350 -67
- package/dist/morphic/validate-definitions.d.ts +4 -1
- package/dist/morphic/value-type.d.ts +13 -0
- package/dist/morphic/view-resolver.d.ts +5 -0
- package/dist/morphic-blocks.js +4432 -2511
- package/dist/morphic-blocks.umd.cjs +43 -23
- package/dist/plugin-h3QH8ods.js +19 -0
- package/dist/plugin.d.ts +9 -0
- package/dist/rollup.d.ts +3 -0
- package/dist/rollup.js +10 -0
- package/dist/rspack.d.ts +3 -0
- package/dist/rspack.js +10 -0
- package/dist/vite.d.ts +3 -0
- package/dist/vite.js +10 -0
- package/dist/webpack.d.ts +3 -0
- package/dist/webpack.js +10 -0
- package/package.json +24 -3
|
@@ -1,34 +1,54 @@
|
|
|
1
|
-
(function(N,_){typeof exports=="object"&&typeof module<"u"?_(exports,require("blockly/blocks"),require("blockly"),require("blockly/javascript")):typeof define=="function"&&define.amd?define(["exports","blockly/blocks","blockly","blockly/javascript"],_):(N=typeof globalThis<"u"?globalThis:N||self,_(N.MorphicBlocks={},N.Blockly,N.Blockly,N.javascript))})(this,(function(N,_,q,J){"use strict";var gn=Object.defineProperty;var kn=(N,_,q)=>_ in N?gn(N,_,{enumerable:!0,configurable:!0,writable:!0,value:q}):N[_]=q;var m=(N,_,q)=>kn(N,typeof _!="symbol"?_+"":_,q);function bt(i){const o=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const e in i)if(e!=="default"){const t=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(o,e,t.get?t:{enumerable:!0,get:()=>i[e]})}}return o.default=i,Object.freeze(o)}const x=bt(q);function ce(i){if(!(!i||typeof i=="function"))return i}function Ct(i){if(i)return typeof i=="function"?i:i.generate}const Z="morphic-mode-",ae="morphic-context-",Pe="morphic-category-",Et="morphic-block-",St=-1,xt=0,Tt=1;function j(i){if(i!==void 0)return typeof i=="string"?i:i.type}function Fe(i,o){const e={...i};for(const[t,n]of Object.entries(o??{})){const s=i[t];if(j(s)!=="code")continue;const{empty:r,stringQuote:c,emptyStatement:a}=n;if(r===void 0&&c===void 0&&a===void 0)continue;const l={...typeof s=="string"?{type:s}:s,empty:r,stringQuote:c,emptyStatement:a};e[t]=l}return e}const Q=16;function Re(i){if(!i||typeof i=="string")return{width:Q,height:Q};const o=i.size;if(o===void 0)return{width:Q,height:Q};if(typeof o=="number")return{width:o,height:o};const e=/^(\d+)(?:x(\d+))?$/i.exec(o.trim());if(!e)return{width:Q,height:Q};const t=Number.parseInt(e[1],10),n=e[2]?Number.parseInt(e[2],10):t;return{width:t,height:n}}function Lt(i,o){if(i!=null&&i.default)return i.default;if(!o||typeof o=="string")return;const e=o.empty;if(!e)return;const t=i!=null&&i.check?Array.isArray(i.check)?i.check[0]:i.check:void 0;return(t?e[t]:void 0)??e.default}const le=18;function ee(i){const o=[];let e=0;for(;e<i.length;){const t=i[e];if(t==="<"&&/^<img\b/i.test(i.slice(e))){const s=i.indexOf(">",e);if(s===-1){_e(o,i.slice(e));break}const r=i.slice(e,s+1),c=Dt(r);c&&o.push(c),e=s+1;continue}if(t==="%"&&/\d/.test(i[e+1]??"")){let s=e+1;for(;s<i.length&&/\d/.test(i[s]??"");)s+=1;const r=Number.parseInt(i.slice(e+1,s),10);Number.isNaN(r)||o.push({kind:"placeholder",index:r}),e=s;continue}if(t==="%"&&/[A-Z_]/.test(i[e+1]??"")){let s=e+1;for(;s<i.length&&/[A-Z0-9_]/.test(i[s]??"");)s+=1;const r=i.slice(e+1,s);o.push({kind:"field",name:r}),e=s;continue}let n=e+1;for(;n<i.length;){const s=i[n],r=s==="%"&&/\d/.test(i[n+1]??""),c=s==="%"&&/[A-Z_]/.test(i[n+1]??"");if(s==="<"&&/^<img\b/i.test(i.slice(n))||r||c)break;n+=1}_e(o,i.slice(e,n)),e=n}return At(o)}function Mt(i){return i.replace(/\s+/g," ").trim()}function V(i){return i.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-")}function Ce(i){return i.map(o=>o.kind==="text"?Bt(o.value):o.kind==="image"?`<img src="${de(o.src)}" alt="${de(o.alt)}" width="${o.width}" height="${o.height}">`:o.kind==="field"?`<span class="morphic-field-placeholder" data-field-name="${de(o.name)}"></span>`:`<span class="morphic-toolbox-slot" data-slot-index="${o.index}"></span>`).join("")}function Bt(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function de(i){return i.replace(/"/g,""").replace(/'/g,"'")}const It=/\.(svg|png|jpe?g|gif|webp)(?:[#?].*)?$/i;function Ve(i,o){if(!i)return i;const e=i.trim();return/^<img\b/i.test(e)?i:It.test(e)?`<img src="${de(e)}" width="${o.width}" height="${o.height}">`:i}function Dt(i){if(!/^<img\b/i.test(i))return null;const o=he(i,"src");if(!o)return null;const e=he(i,"alt")??"",t=Number.parseInt(he(i,"width")??`${le}`,10),n=Number.parseInt(he(i,"height")??`${le}`,10);return{kind:"image",src:o,alt:e,width:Number.isNaN(t)?le:t,height:Number.isNaN(n)?le:n}}function he(i,o){const e=new RegExp(`${o}\\s*=\\s*(['"])(.*?)\\1`,"i").exec(i);if(e!=null&&e[2])return e[2];const t=new RegExp(`${o}\\s*=\\s*([^\\s>]+)`,"i").exec(i);return(t==null?void 0:t[1])??null}function _e(i,o){o&&i.push({kind:"text",value:o})}function At(i){const o=[];for(const e of i){const t=o[o.length-1];if(e.kind==="text"&&(t==null?void 0:t.kind)==="text"){t.value+=e.value;continue}o.push(e)}return o}function We(i){const{block:o,definition:e,view:t,mode:n,context:s,elementTypes:r,resolveBlocklyType:c}=i,a=zt(o),d=jt(o);qt(o),Pt(o,e,t),Jt(o,e),typeof e.inputsInline=="boolean"&&o.setInputsInline(e.inputsInline),e.color!==void 0&&o.setColour(e.color),e.tooltip&&o.setTooltip(e.tooltip),e.helpUrl&&o.setHelpUrl(e.helpUrl),Xt(o,a),Ut(o,d),r&&Gt(o,e,t,r,c),ze(o,n,s);const l=o;l.__morphicMode=n,l.__morphicContext=s,Ee(o)&&o.render()}function Ee(i){var o;return i.rendered&&!!((o=i.getSvgRoot())!=null&&o.parentNode)}function ue(i,o,e,t){te(i.classList,Z),te(i.classList,ae),i.classList.add(t),i.classList.add(`${Z}${V(o)}`),i.classList.add(`${ae}${e}`)}function Ot(i){return i.__morphicMode}function $t(i,o){const e=i.getSvgRoot();e&&(te(e.classList,Pe),o&&e.classList.add(`${Pe}${o}`))}function Nt(i,o){const e=i.getSvgRoot();if(!e)return;const t=`${Et}${V(o)}`;e.classList.contains(t)||e.classList.add(t)}function Ht(i){const o=i.getSvgRoot();if(!o)return;const e=getComputedStyle(o).getPropertyValue("--morphic-block-color").trim();e&&(i.setColour(e),Ee(i)&&i.render())}function fe(i,o,e){te(i.classList,Z),i.classList.add(e),o&&i.classList.add(`${Z}${V(o)}`)}function ze(i,o,e){const t=i.getSvgRoot();t&&(te(t.classList,Z),te(t.classList,ae),t.classList.add(`${Z}${V(o)}`),t.classList.add(`${ae}${e}`))}function Pt(i,o,e){var r;const t=ee(e.template),n=[],s=new Set;for(const c of t){if(c.kind==="text"){const l=Mt(c.value);l&&n.push(l);continue}if(c.kind==="image"){n.push(new x.FieldImage(c.src,c.width,c.height,c.alt));continue}if(c.kind==="field"){const l=(r=o.fields)==null?void 0:r[c.name];l&&n.push({field:_t(l,e.elementName),name:c.name});continue}if(s.has(c.index)){const l=i.appendDummyInput(`DUPLICATE_${c.index}_${i.inputList.length}`);pe(l,n),l.appendField(`%${c.index}`);continue}s.add(c.index);const a=Ft(o,e,c.index);if((a==null?void 0:a.kind)==="statement"&&n.length>0){const l=i.appendDummyInput(`PRE_STMT_${i.inputList.length}`);pe(l,n)}const d=Rt(i,a,c.index);pe(d,n),a!=null&&a.label&&d.appendField(a.label)}if(n.length>0){const c=i.appendDummyInput(`TRAILING_${i.inputList.length}`);pe(c,n)}i.inputList.length===0&&i.appendDummyInput("LABEL").appendField(o.identifier)}function Ft(i,o,e){var n,s;const t=`${e}`;return((n=o.inputSlots)==null?void 0:n[t])??((s=i.inputSlots)==null?void 0:s[t])}function Rt(i,o,e){const t=(o==null?void 0:o.name)??`ARG${e}`,n=(o==null?void 0:o.kind)??"value";let s;return n==="statement"?(s=i.appendStatementInput(t),o!=null&&o.check&&s.setCheck(o.check)):(s=i.appendValueInput(t),o!=null&&o.check&&s.setCheck(o.check)),o!=null&&o.align&&s.setAlign(Vt(o.align)),s}function Vt(i){return i==="right"?Tt:i==="centre"?xt:St}function pe(i,o){for(const e of o)typeof e=="object"&&"field"in e?i.appendField(e.field,e.name):i.appendField(e);o.length=0}function _t(i,o){switch(i.type){case"dropdown":{const e=i.options.map(n=>Wt(n,o)),t=new x.FieldDropdown(e);return i.default!==void 0&&t.setValue(i.default),t}case"number":return new x.FieldNumber(i.default??0,i.min,i.max,i.precision);case"checkbox":return new x.FieldCheckbox(i.default?"TRUE":"FALSE");case"text":default:return new x.FieldTextInput(i.default??"")}}function Wt(i,o){var t;if(typeof i=="string")return[i,i];if(Array.isArray(i)){const[n,s]=i;return[s??n,n]}return[(o?(t=i.display)==null?void 0:t[o]:void 0)??i.label??i.value,i.value]}function zt(i){var e;const o=new Map;for(const t of i.inputList){const n=(e=t.connection)==null?void 0:e.targetBlock();n&&!n.isShadow()&&o.set(t.name,n)}return o}function jt(i){var e;const o=new Map;for(const t of i.inputList){const n=(e=t.connection)==null?void 0:e.getShadowState(!0);n&&o.set(t.name,n)}return o}function Ut(i,o){var e;for(const[t,n]of o){const s=(e=i.getInput(t))==null?void 0:e.connection;if(!(!s||s.getShadowState()))try{s.setShadowState(n)}catch{}}}function Gt(i,o,e,t,n=s=>s){var a,d;const s=e.elementName?t[e.elementName]:void 0,r=new Map;for(const l of Object.values(o.inputSlots??{}))l!=null&&l.name&&(l.kind??"value")==="value"&&r.set(l.name,l);if(r.size===0)return;const c=i.workspace;for(const l of i.inputList){const h=l.connection;if(!h||h.type!==x.INPUT_VALUE)continue;const u=r.get(l.name);if(!u)continue;const k=Lt(u,s);if(k){if(k.shadow&&!(((a=h.getShadowState)==null?void 0:a.call(h,!0))??((d=h.getShadowDom)==null?void 0:d.call(h))))try{h.setShadowState({type:n(k.shadow),fields:k.fieldValues??{}})}catch{}if(k.placeholder){const v=i,w=v.__morphicPlaceholderSlots??(v.__morphicPlaceholderSlots=new Set),b=h.targetBlock(),g=!b||b.isShadow(),y=w.has(l.name);if(w.add(l.name),g&&!y)try{const C=c.newBlock(n(k.placeholder));if(k.fieldValues)for(const[E,f]of Object.entries(k.fieldValues)){const p=C.getField(E);p&&p.setValue(f)}C.outputConnection&&h.connect(C.outputConnection),i.rendered&&(C.initSvg(),C.queueRender())}catch{}}}}}function Xt(i,o){for(const[e,t]of o){const n=i.getInput(e);if(!(n!=null&&n.connection)||n.connection.isConnected())continue;const s=[t.outputConnection,t.previousConnection];for(const r of s)if(r)try{n.connection.connect(r);break}catch{continue}}}function Yt(i){const o=new Map;for(const e of i.inputList)for(const t of e.fieldRow)t.name&&o.set(t.name,t.getValue());return o}function Kt(i,o){for(const[e,t]of o){const n=i.getField(e);if(n&&t!==void 0&&t!==null)try{n.setValue(t)}catch{}}}function qt(i){for(;i.inputList.length>0;){const o=i.inputList[0];if(!o)break;i.removeInput(o.name,!0)}}function Jt(i,o){o.output!==void 0&&Zt(i,o.output),o.previousStatement!==void 0&&Qt(i,o.previousStatement),o.nextStatement!==void 0&&eo(i,o.nextStatement)}function Zt(i,o){if(o===!1){i.setOutput(!1);return}if(o===!0){i.setOutput(!0);return}i.setOutput(!0,o)}function Qt(i,o){if(o===!1){i.setPreviousStatement(!1);return}if(o===!0){i.setPreviousStatement(!0);return}i.setPreviousStatement(!0,o)}function eo(i,o){if(o===!1){i.setNextStatement(!1);return}if(o===!0){i.setNextStatement(!0);return}i.setNextStatement(!0,o)}function te(i,o){const e=Array.from(i).filter(t=>t.startsWith(o));for(const t of e)i.remove(t)}function je(i,o,e){if(!e)return[];const t={keyword:i.Decoration.mark({class:"morphic-tok-keyword"}),string:i.Decoration.mark({class:"morphic-tok-string"}),number:i.Decoration.mark({class:"morphic-tok-number"}),comment:i.Decoration.mark({class:"morphic-tok-comment"})},n=Ue(e),s=(u,k,v)=>{for(const w of n(u))v.add(k+w.from,k+w.to,t[w.kind])},r=u=>{const k=new o.RangeSetBuilder,v=u.state.doc;for(const{from:w,to:b}of u.visibleRanges){let g=w;for(;g<=b;){const y=v.lineAt(g);if(s(y.text,y.from,k),y.to>=b)break;g=y.to+1}}return k.finish()},c=i.ViewPlugin.fromClass(class{constructor(u){m(this,"decorations");this.decorations=r(u)}update(u){(u.docChanged||u.viewportChanged)&&(this.decorations=r(u.view))}},{decorations:u=>u.decorations}),a=i.EditorView.baseTheme({".morphic-tok-keyword":{color:"#cc7832"},".morphic-tok-string":{color:"#6a8759"},".morphic-tok-number":{color:"#6897bb"},".morphic-tok-comment":{color:"#808080",fontStyle:"italic"}}),d=e.colors??{},l={};d.keyword&&(l[".cm-content .morphic-tok-keyword"]={color:d.keyword}),d.string&&(l[".cm-content .morphic-tok-string"]={color:d.string}),d.number&&(l[".cm-content .morphic-tok-number"]={color:d.number}),d.comment&&(l[".cm-content .morphic-tok-comment"]={color:d.comment,fontStyle:"italic"});const h=[c,a];return Object.keys(l).length>0&&h.push(i.EditorView.theme(l)),h}function Ue(i){const o=new Set(i.keywords??[]),e=(i.strings??[]).map(s=>typeof s=="string"?{open:s,close:s}:{open:s[0],close:s[1]}),t=i.comment,n=i.numbers!==!1;return s=>{const r=[],c=s.length;let a=0;for(;a<c;){if(t&&s.startsWith(t,a))return r.push({from:a,to:c,kind:"comment"}),r;let d=!1;for(const h of e)if(s.startsWith(h.open,a)){const u=a;for(a+=h.open.length;a<c;){if(s[a]==="\\"&&a+1<c){a+=2;continue}if(s.startsWith(h.close,a)){a+=h.close.length;break}a+=1}r.push({from:u,to:a,kind:"string"}),d=!0;break}if(d)continue;if(n){const h=/^\d+(?:\.\d+)?/.exec(s.slice(a));if(h){r.push({from:a,to:a+h[0].length,kind:"number"}),a+=h[0].length;continue}}const l=/^[\p{L}\p{M}_][\p{L}\p{M}\p{N}_]*/u.exec(s.slice(a));if(l){o.has(l[0])&&r.push({from:a,to:a+l[0].length,kind:"keyword"}),a+=l[0].length;continue}a+=1}return r}}const Se="morphic/block-id";let me;function xe(){return me}function Ge(i){me=i}const ne={fontSize:"14px",fontFamily:"monospace",lineHeight:1.5,background:"#1e1e1e",foreground:"#d4d4d4",gutterBackground:"#1e1e1e",gutterForeground:"#858585",selectionBackground:"#264f78"},ie=(i,o)=>`color-mix(in srgb, ${i} ${o}%, transparent)`;let Xe=!1;async function to(){if(Xe)return;Xe=!0;const o=(await Promise.resolve().then(()=>pn)).default,e=document.createElement("style");e.dataset.morphicSource="code-editor",e.textContent=o,document.head.appendChild(e)}const oo=150,no=new Set(["create","delete","move","change"]);function io(i){return no.has(i.type)}async function so(i){let o,e;try{[o,e]=await Promise.all([import("@codemirror/view"),import("@codemirror/state")])}catch{throw new Error(`CodeMirror is required for the codespace, preview and code editor. Install it:
|
|
1
|
+
(function(le,ge){typeof exports=="object"&&typeof module<"u"?ge(exports,require("blockly/blocks"),require("blockly"),require("blockly/javascript")):typeof define=="function"&&define.amd?define(["exports","blockly/blocks","blockly","blockly/javascript"],ge):(le=typeof globalThis<"u"?globalThis:le||self,ge(le.MorphicBlocks={},le.Blockly,le.Blockly,le.javascript))})(this,(function(le,ge,_e,Fe){"use strict";var Xs=Object.defineProperty;var Ks=(le,ge,_e)=>ge in le?Xs(le,ge,{enumerable:!0,configurable:!0,writable:!0,value:_e}):le[ge]=_e;var y=(le,ge,_e)=>Ks(le,typeof ge!="symbol"?ge+"":ge,_e);function Cn(i){const o=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const e in i)if(e!=="default"){const t=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(o,e,t.get?t:{enumerable:!0,get:()=>i[e]})}}return o.default=i,Object.freeze(o)}const S=Cn(_e);function Ge(i){if(!(!i||typeof i=="function"))return i}function Sn(i){if(i)return typeof i=="function"?i:i.generate}const Xe="morphic-mode-",ot="morphic-context-",nt="morphic-shows-",En="morphic-view-",Yt="morphic-preset-",Jt="morphic-category-",xn="morphic-block-",Tn=-1,Ln=0,Bn=1,wt="morphic:";function Ae(i){return wt+i}function he(i){return i.startsWith(wt)?i.slice(wt.length):i}function ke(i,o){return o.has(i)?Ae(i):i}class qt extends S.FieldDropdown{showEditor_(o){var t;super.showEditor_(o);const e=(t=this.menu_)==null?void 0:t.getElement();e==null||e.classList.add("morphic-menu"),this.name&&(e==null||e.classList.add(`morphic-menu-${this.name}`))}}function Zt(i){if(typeof i!="string")return null;const o=i.lastIndexOf(".");return o<=0||o===i.length-1?null:{block:i.slice(0,o),field:i.slice(o+1)}}class yt extends qt{constructor(e,t="",n=[]){super(function(){return this.nameOptions(t)});y(this,"targets");y(this,"scopes");this.initial=t,this.targets=(Array.isArray(e)?e:[e]).map(Zt).filter(s=>s!==null),this.scopes=(Array.isArray(n)?n:[n]).map(Ae)}refersTo(e,t){const n=he(e.type);return this.targets.some(s=>s.block===n&&s.field===t)&&this.sees(e)}scopeBlock(){var t,n;if(!((t=this.scopes)!=null&&t.length))return;let e=((n=this.getSourceBlock())==null?void 0:n.getSurroundParent())??null;for(;e&&!this.scopes.includes(e.type);)e=e.getSurroundParent();return e}isScoped(){return this.scopes.length>0}sees(e,t=this.scopeBlock()){if(t===void 0)return!0;for(let n=e.getSurroundParent();n;n=n.getSurroundParent())if(n===t)return!0;return!1}declaredNames(e){var l;const t=(l=this.getSourceBlock())==null?void 0:l.workspace;if(!t)return[];const n=this.scopeBlock(),s=`${n===void 0?"":(n==null?void 0:n.id)??"-"}|${(this.targets??[]).map(d=>`${d.block}.${d.field}`).join(",")}`,r=e==null?void 0:e.get(s);if(r)return r;const c=new Set;for(const d of this.targets??[])for(const h of t.getBlocksByType(Ae(d.block),!1)){if(h.isInsertionMarker()||!this.sees(h,n))continue;const u=h.getFieldValue(d.field);typeof u=="string"&&u!==""&&c.add(u)}const a=[...c].sort((d,h)=>d.localeCompare(h));return e==null||e.set(s,a),a}isMissing(e){return!this.declaredNames(e).includes(this.getValue()??"")}showMissing(e){var t;(t=this.fieldGroup_)==null||t.classList.toggle("morphic-reference-missing",this.isMissing(e))}initView(){super.initView(),this.showMissing()}pickDeclared(){const e=this.declaredNames(),t=this.getValue()??"";e.length===0||e.includes(t)||(t===""||t===this.initial)&&this.setValue(e[0])}nameOptions(e){const t=this.declaredNames(),n=this.getValue()??e;return t.includes(n)||t.push(n),t.map(s=>[s,s])}getOptions(){return super.getOptions(!1)}doClassValidation_(e){return typeof e=="string"?e:null}doValueUpdate_(e){super.doValueUpdate_(e),this.showMissing()}}const Ke=new Set;function $n(i){i&&(Ke.add(i),Ke.size>50&&Ke.delete(Ke.values().next().value))}function bt(i,o=i.getAllBlocks(!1)){return o.flatMap(e=>e.inputList.flatMap(t=>t.fieldRow.filter(n=>n instanceof yt)))}function In(i){i.addChangeListener(o=>{const e=r=>{const c=S.Events.getGroup();S.Events.setGroup(o.group||c);try{r()}finally{S.Events.setGroup(c)}},t=[S.Events.BLOCK_CREATE,S.Events.BLOCK_DELETE,S.Events.BLOCK_CHANGE,S.Events.BLOCK_MOVE];if(o.isUiEvent||!t.includes(o.type))return;const n=bt(i);if(n.length===0)return;const s=()=>{const r=new Map;for(const c of n)c.showMissing(r)};if(!o.recordUndo||Ke.has(o.group)){s();return}if(o.type===S.Events.BLOCK_CREATE){const r=(o.ids??[]).map(c=>i.getBlockById(c)).filter(c=>c!==null);e(()=>bt(i,r).forEach(c=>c.pickDeclared()))}if(o.type===S.Events.BLOCK_MOVE){const r=o,c=r.newParentId!==r.oldParentId?i.getBlockById(r.blockId??""):null;c&&e(()=>{for(const a of bt(i,c.getDescendants(!1)))a.isScoped()&&a.pickDeclared()})}if(o.type===S.Events.BLOCK_CHANGE){const r=o,c=r.blockId?i.getBlockById(r.blockId):null,a=String(r.oldValue??""),l=String(r.newValue??"");r.element==="field"&&r.name&&c&&a!==l&&e(()=>{for(const d of n)!d.refersTo(c,r.name)||d.getValue()!==a||d.declaredNames().includes(a)||d.setValue(l)})}s()})}function pe(i){if(i!==void 0)return typeof i=="string"?i:i.type}function Ct(i,o){const e={...i};for(const[t,n]of Object.entries(o??{})){const s=i[t];if(pe(s)!=="code")continue;const{empty:r,stringQuote:c,emptyStatement:a,types:l,operators:d}=n;if(r===void 0&&c===void 0&&a===void 0&&l===void 0&&d===void 0)continue;const u={...typeof s=="string"?{type:s}:s,empty:r,stringQuote:c,emptyStatement:a,types:l,operators:d};e[t]=u}return e}const Pe=16;function St(i){if(!i||typeof i=="string")return{width:Pe,height:Pe};const o=i.size;if(o===void 0)return{width:Pe,height:Pe};if(typeof o=="number")return{width:o,height:o};const e=/^(\d+)(?:x(\d+))?$/i.exec(o.trim());if(!e)return{width:Pe,height:Pe};const t=Number.parseInt(e[1],10),n=e[2]?Number.parseInt(e[2],10):t;return{width:t,height:n}}function Qt(i,o){if(i!=null&&i.default)return i.default;if(!o||typeof o=="string")return;const e=o.empty;if(!e)return;const t=i!=null&&i.check?Array.isArray(i.check)?i.check[0]:i.check:void 0;return(t?e[t]:void 0)??e.default}function eo(i,o){for(let e=i.getSurroundParent();e;e=e.getSurroundParent()){const t=e.getField(o);if(t)return t}return null}function ve(i){return!!(i!=null&&i.repeat)&&(i.kind??"value")==="value"}function Ce(i,o){return(i==null?void 0:i.name)??`ARG${o}`}function Se(i,o){return`${i}_${o}`}function Re(i){const o=new Map;for(const[e,t]of Object.entries(i.inputSlots??{}))t&&ve(t)&&o.set(Ce(t,e),t);return o}function Te(i,o,e){var t,n;return((t=i.__morphicRepeat)==null?void 0:t.get(o))??Math.max(0,Math.floor(((n=e.repeat)==null?void 0:n.count)??1))}function to(i,o,e){(i.__morphicRepeat??(i.__morphicRepeat=new Map)).set(o,Math.max(0,Math.floor(e)))}function oo(i,o,e){return Array.from({length:Te(i,o,e)},(t,n)=>Se(o,n))}function it(i,o){var t;const e=(t=i.repeat)==null?void 0:t.separator;return typeof e=="string"?e:(o!==void 0?e==null?void 0:e[o]:void 0)??", "}function no(i){return/[^\s,;]/.test(i)}function io(i,o){for(const[e,t]of Object.entries(i.inputSlots??{})){const n=Ce(t,e);if(n===o||t&&ve(t)&&o.startsWith(`${n}_`)&&/^\d+$/.test(o.slice(n.length+1)))return t}}function Et(i,o){const e=Re(o);if(e.size===0)return null;const t={};for(const[n,s]of e)t[n]=Te(i,n,s);return{repeat:t}}function Mn(i,o,e){const t=e==null?void 0:e.repeat;if(!t||typeof t!="object")return!1;let n=!1;for(const[s,r]of Re(o)){const c=t[s];typeof c!="number"||c===Te(i,s,r)||(to(i,s,c),n=!0)}return n}const so=new WeakSet,ro=new WeakSet;function On(i){so.add(i)}function An(i){for(const o of[i.previousConnection,i.outputConnection])o&&ro.add(o)}function co(i){const o=i.connectionChecker,e=o.doTypeChecks.bind(o);o.doTypeChecks=(t,n)=>e(t,n)&&Dn(t,n)}function Dn(i,o){const[e,t]=i.isSuperior()?[i,o]:[o,i];if(ro.has(t)&&!e.getCheck())return!1;const n=Nn(e);if(!n||!so.has(n))return!0;const s=n.getCheck();if(!s)return!1;const r=c=>{const a=c==null?void 0:c.getCheck();return!!a&&a.some(l=>s.includes(l))};if(t!==t.getSourceBlock().previousConnection)return r(t);for(let c=t.getSourceBlock();c;c=c.getNextBlock())if(!r(c.previousConnection))return!1;return!0}function Nn(i){var e;let o=i;for(;;){if(o.getParentInput())return o;const t=(e=o.getSourceBlock().previousConnection)==null?void 0:e.targetConnection;if(!t)return null;o=t}}const xt="MORPHIC_TYPE_",Ye=i=>{var o;return!!((o=i.name)!=null&&o.startsWith(xt))};function ao(i,o,e){var c,a,l;const t=typeof e=="object"?e.types:void 0;if(!t)return"";const n=o!=null&&o.name?(a=(c=i.getInput(o.name))==null?void 0:c.connection)==null?void 0:a.targetBlock():null,s=typeof(o==null?void 0:o.check)=="string"?[o.check]:(o==null?void 0:o.check)??[],r=n?((l=n.outputConnection)==null?void 0:l.getCheck())??[]:s.length===1?s:[];for(const d of r){const h=t[d];if(h!==void 0)return h}return t.default??""}const st=18,lo=":type",rt="%parent.";function ho(i,o){return i.startsWith(rt,o)&&/[A-Z_]/.test(i[o+rt.length]??"")}function we(i){const o=[];let e=0;for(;e<i.length;){const t=i[e];if(t==="<"&&/^<img\b/i.test(i.slice(e))){const s=i.indexOf(">",e);if(s===-1){mo(o,i.slice(e));break}const r=i.slice(e,s+1),c=Hn(r);c&&o.push(c),e=s+1;continue}if(t==="%"&&/\d/.test(i[e+1]??"")){let s=e+1;for(;s<i.length&&/\d/.test(i[s]??"");)s+=1;const r=Number.parseInt(i.slice(e+1,s),10);if(i.startsWith(lo,s)){o.push({kind:"valueType",index:r}),e=s+lo.length;continue}Number.isNaN(r)||o.push({kind:"placeholder",index:r}),e=s;continue}if(ho(i,e)){let s=e+rt.length;for(;s<i.length&&/[A-Z0-9_]/.test(i[s]??"");)s+=1;o.push({kind:"parentField",name:i.slice(e+rt.length,s)}),e=s;continue}if(t==="%"&&/[A-Z_]/.test(i[e+1]??"")){let s=e+1;for(;s<i.length&&/[A-Z0-9_]/.test(i[s]??"");)s+=1;const r=i.slice(e+1,s);o.push({kind:"field",name:r}),e=s;continue}let n=e+1;for(;n<i.length;){const s=i[n],r=s==="%"&&/\d/.test(i[n+1]??""),c=s==="%"&&/[A-Z_]/.test(i[n+1]??"");if(s==="<"&&/^<img\b/i.test(i.slice(n))||r||c||ho(i,n))break;n+=1}mo(o,i.slice(e,n)),e=n}return jn(o)}function Vn(i,o,e){const t=i.filter(l=>l.kind!=="image"),n=t.indexOf(i[o]),s=l=>{for(let d=n+l;d>=0&&d<t.length;d+=l){const h=t[d];if(h.kind!=="text")return null;const u=l===-1?h.value.trimEnd():h.value.trimStart();if(u)return l===-1?u.at(-1):u[0];if(h.value.includes(`
|
|
2
|
+
`))return`
|
|
3
|
+
`}return""},r=/[\p{L}\p{N}_$]/u,c=s(-1),a=s(1);return{before:c===""||c!==null&&(`([{,
|
|
4
|
+
`.includes(c)||e&&("=:;".includes(c)||r.test(c))),after:a===""||a!==null&&(`)]},;:{
|
|
5
|
+
`.includes(a)||e&&r.test(a))}}const _n="\"'`";function uo(i,o){const e=i==null?void 0:i.at(-1);return e&&_n.includes(e)&&(o==null?void 0:o[0])===e?e:null}function fo(i,o){return i.replaceAll("\\","\\\\").replaceAll(o,`\\${o}`)}function Fn(i,o,e){let t="";for(let n=o;n<i.length&&i[n]!==`
|
|
6
|
+
`;n++){const s=i[n];if(s===e)return{value:t,end:n};const r=i[n+1];s==="\\"&&(r==="\\"||r===e)?(t+=r,n++):t+=s}return null}function po(i){return i.replace(/\s+/g," ").trim()}function de(i){return i.trim().replace(/[^A-Za-z0-9_-]+/g,"-")}function Tt(i){return i.map(o=>o.kind==="text"?Pn(o.value):o.kind==="image"?`<img src="${ct(o.src)}" alt="${ct(o.alt)}" width="${o.width}" height="${o.height}">`:o.kind==="field"?`<span class="morphic-field-placeholder" data-field-name="${ct(o.name)}"></span>`:o.kind==="valueType"?`<span class="morphic-value-type" data-slot-index="${o.index}"></span>`:o.kind==="parentField"?"":`<span class="morphic-toolbox-slot" data-slot-index="${o.index}"></span>`).join("")}function Pn(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function ct(i){return i.replace(/"/g,""").replace(/'/g,"'")}const Rn=/\.(svg|png|jpe?g|gif|webp)(?:[#?].*)?$/i;function Lt(i,o){if(!i)return i;const e=i.trim();return/^<img\b/i.test(e)?i:Rn.test(e)?`<img src="${ct(e)}" width="${o.width}" height="${o.height}">`:i}function Hn(i){if(!/^<img\b/i.test(i))return null;const o=at(i,"src");if(!o)return null;const e=at(i,"alt")??"",t=Number.parseInt(at(i,"width")??`${st}`,10),n=Number.parseInt(at(i,"height")??`${st}`,10);return{kind:"image",src:o,alt:e,width:Number.isNaN(t)?st:t,height:Number.isNaN(n)?st:n}}function at(i,o){const e=new RegExp(`${o}\\s*=\\s*(['"])(.*?)\\1`,"i").exec(i);if(e!=null&&e[2])return e[2];const t=new RegExp(`${o}\\s*=\\s*([^\\s>]+)`,"i").exec(i);return(t==null?void 0:t[1])??null}function mo(i,o){o&&i.push({kind:"text",value:o})}function jn(i){const o=[];for(const e of i){const t=o[o.length-1];if(e.kind==="text"&&(t==null?void 0:t.kind)==="text"){t.value+=e.value;continue}o.push(e)}return o}const Wn="MORPHIC_OMITTED_FIELDS";function zn(i){const o=i.__morphicPlaceholderSlots;return o!=null&&o.size?[...o]:void 0}function Un(i,o){var t;const e=i;if(!e.__morphicFresh||!Array.isArray(o))return!1;for(const n of i.inputList){const s=(t=n.connection)==null?void 0:t.targetBlock();s&&!s.isShadow()&&s.dispose(!1)}return e.__morphicPlaceholderSlots=new Set(o.filter(n=>typeof n=="string")),!0}function Gn(i,o){var t,n;const e=i;(t=e.__morphicPlaceholderSlots)==null||t.delete(o),(n=e.__morphicShadowMemory)==null||n.delete(o)}function go(i){const{block:o,definition:e,view:t,mode:n,context:s,elementTypes:r,resolveBlocklyType:c}=i,a=ni(o),l=o.__morphicShadowMemory??(o.__morphicShadowMemory=new Map);for(const[u,f]of ii(o))l.set(u,f);hi(o),Jn(o,e,t,i.onRepeat);const d=qn(o,e);ui(o,e),typeof e.inputsInline=="boolean"&&o.setInputsInline(e.inputsInline),e.color!==void 0&&o.setColour(e.color),e.tooltip&&o.setTooltip(e.tooltip),e.helpUrl&&o.setHelpUrl(e.helpUrl),ci(o,a),si(o,l),r&&ri(o,e,t,r,c);for(const u of d)u.setVisible(!1);Zn(o,e,t,i.codeSettings??r),wo(o,n,s);const h=o;h.__morphicMode=n,h.__morphicContext=s,Bt(o)&&o.render()}function Bt(i){var o;return i.rendered&&!!((o=i.getSvgRoot())!=null&&o.parentNode)}function ko(i,o,e,t){Ee(i.classList,Xe),Ee(i.classList,ot),i.classList.add(t),i.classList.add(`${Xe}${de(o)}`),i.classList.add(`${ot}${e}`)}function vo(i){return i.__morphicMode}function Xn(i,o){const e=i.getSvgRoot();e&&(Ee(e.classList,Jt),o&&e.classList.add(`${Jt}${o}`))}function Kn(i,o){const e=i.getSvgRoot();if(!e)return;const t=`${xn}${de(o)}`;e.classList.contains(t)||e.classList.add(t)}function Yn(i){const o=i.getSvgRoot();if(!o)return;const e=getComputedStyle(o).getPropertyValue("--morphic-block-color").trim();e&&(i.setColour(e),Bt(i)&&i.render())}function lt(i,o){Ee(i.classList,Xe),Ee(i.classList,nt),i.classList.add("morphic-view",...o.classNames),o.name&&i.classList.add(`${En}${de(o.name)}`),o.element&&i.classList.add(`${nt}${de(o.element)}`)}function dt(i,o){Ee(i.classList,Yt),o&&i.classList.add(`${Yt}${de(o)}`)}function wo(i,o,e){const t=i.getSvgRoot();if(!t)return;Ee(t.classList,Xe),Ee(t.classList,nt),Ee(t.classList,ot);const n=e==="workspace"?nt:Xe;t.classList.add(`${n}${de(o)}`),t.classList.add(`${ot}${e}`)}function Jn(i,o,e,t){var l;const n=we(e.template),s=[],r=new Set,c=new Set,a=d=>bo(d,s);for(const d of n){if(d.kind==="text"){const f=po(d.value);f&&s.push(f);continue}if(d.kind==="image"){s.push(new S.FieldImage(d.src,d.width,d.height,d.alt));continue}if(d.kind==="valueType"){s.push({field:new S.FieldLabel(""),name:`${xt}${d.index}`});continue}if(d.kind==="parentField"){s.push(new Je(d.name,"parent"));continue}if(d.kind==="field"){const f=(l=o.fields)==null?void 0:l[d.name];f&&c.has(d.name)?s.push(new Je(d.name)):f&&(c.add(d.name),s.push({field:Co(f,e.elementName),name:d.name}));continue}if(r.has(d.index)){const f=$t(o,e,d.index);if(((f==null?void 0:f.kind)??"value")==="value"&&!(f&&ve(f))){s.push(new Je(Ce(f,d.index),"slot"));continue}const p=i.appendDummyInput(`DUPLICATE_${d.index}_${i.inputList.length}`);a(p),p.appendField(`%${d.index}`);continue}r.add(d.index);const h=$t(o,e,d.index);if(h&&ve(h)){const f=Ce(h,d.index),p=Te(i,f,h),g=po(it(h,e.elementName));for(let v=0;v<p;v++)v>0&&g&&s.push(g),bo(It(i,h,d.index,Se(f,v)),s);t&&(p>0&&s.push(new yo("remove",()=>t(f,-1))),s.push(new yo("add",()=>t(f,1))));continue}if((h==null?void 0:h.kind)==="statement"&&s.length>0){const f=i.appendDummyInput(`PRE_STMT_${i.inputList.length}`);a(f)}const u=It(i,h,d.index);a(u),h!=null&&h.label&&u.appendField(h.label)}if(s.length>0){const d=i.appendDummyInput(`TRAILING_${i.inputList.length}`);a(d)}i.inputList.length===0&&i.appendDummyInput("LABEL").appendField(o.identifier)}function qn(i,o){const e=[];for(const[t,n]of Object.entries(o.inputSlots??{})){if(!n)continue;const s=Ce(n,t),r=ve(n)?Array.from({length:Te(i,s,n)},(c,a)=>Se(s,a)):[s];for(const c of r)i.getInput(c)||e.push(It(i,n,Number(t),c))}return e}function Zn(i,o,e,t){const n=i.inputList.flatMap(l=>l.fieldRow),s=n.filter(Ye),r=n.some(l=>l instanceof Je);if(s.length===0&&!r){i.onchange&&i.setOnChange(()=>{});return}const c=e.elementName?t==null?void 0:t[e.elementName]:void 0,a=()=>{for(const l of s){const d=l.name.slice(xt.length),h=ao(i,$t(o,e,Number(d)),c);l.getValue()!==h&&l.setValue(h,!1)}};a(),Mt(i),i.setOnChange(l=>{(l.type===S.Events.BLOCK_MOVE||l.type===S.Events.BLOCK_CREATE)&&a(),r&&Mt(i)})}function $t(i,o,e){var n,s;const t=`${e}`;return((n=o.inputSlots)==null?void 0:n[t])??((s=i.inputSlots)==null?void 0:s[t])}function It(i,o,e,t=Ce(o,e)){const n=(o==null?void 0:o.kind)??"value";let s;return n==="statement"?(s=i.appendStatementInput(t),o!=null&&o.check&&s.setCheck(o.check)):(s=i.appendValueInput(t),o!=null&&o.check&&s.setCheck(o.check)),o!=null&&o.align&&s.setAlign(Qn(o.align)),o!=null&&o.strict&&s.connection&&On(s.connection),s}function Qn(i){return i==="right"?Bn:i==="centre"?Ln:Tn}class yo extends S.Field{constructor(e,t){super(e==="add"?"+":"−");y(this,"EDITABLE",!0);y(this,"SERIALIZABLE",!1);y(this,"CURSOR","pointer");this.action=e,this.press=t}initView(){var e;super.initView(),(e=this.fieldGroup_)==null||e.classList.add("morphic-repeat-button",`morphic-repeat-${this.action}`)}showEditor_(){this.press()}}class Je extends S.FieldLabel{constructor(o,e="field"){super(""),this.fieldName=o,this.source=e}}function ei(i,o){const e=i.getInputTargetBlock(o);if(!e)return"";const t=e.inputList.filter(s=>s.isVisible()),n=t.flatMap(s=>s.fieldRow).filter(s=>s.name&&!Ye(s));return n.length===1&&!t.some(s=>s.connection)?n[0].getText():"…"}function Mt(i){for(const o of i.inputList)for(const e of o.fieldRow){if(!(e instanceof Je))continue;const t=e.source==="parent"?eo(i,e.fieldName):i.getField(e.fieldName),n=e.source==="slot"?ei(i,e.fieldName):(t==null?void 0:t.getText())??"";e.getValue()!==n&&e.setValue(n,!1)}}function bo(i,o){for(const e of o)typeof e=="object"&&"field"in e?i.appendField(e.field,e.name):i.appendField(e);o.length=0}function Co(i,o){switch(i.type){case"dropdown":{const e=i.options.map(n=>ti(n,o)),t=new qt(e);return i.default!==void 0&&t.setValue(i.default),t}case"reference":return new yt(i.to,i.default,i.scope);case"number":return new S.FieldNumber(i.default??0,i.min,i.max,i.precision);case"checkbox":return new S.FieldCheckbox(i.default?"TRUE":"FALSE");case"text":default:return new S.FieldTextInput(i.default??"")}}function ti(i,o){var n;if(typeof i=="string")return[i,i];if(Array.isArray(i)){const[s,r]=i;return[r??s,s]}const e=o?(n=i.display)==null?void 0:n[o]:void 0;if(e!==void 0)return[e,i.value];const t=i.label;if(t&&typeof t=="object"){const s=t.width??16,r=t.height??16;return[{src:t.color!==void 0?oi(t.color,s,r):t.src,alt:t.alt??i.value,width:s,height:r},i.value]}return[t??i.value,i.value]}function oi(i,o,e){const t=`<svg xmlns="http://www.w3.org/2000/svg" width="${o}" height="${e}"><rect width="${o}" height="${e}" rx="3" fill="${i.replace(/["<>&]/g,"")}"/></svg>`;return`data:image/svg+xml,${encodeURIComponent(t)}`}function ni(i){var e;const o=new Map;for(const t of i.inputList){const n=(e=t.connection)==null?void 0:e.targetBlock();n&&!n.isShadow()&&o.set(t.name,n)}return o}function ii(i){var e;const o=new Map;for(const t of i.inputList){const n=(e=t.connection)==null?void 0:e.getShadowState(!0);n&&o.set(t.name,n)}return o}function si(i,o){var e;for(const[t,n]of o){const s=(e=i.getInput(t))==null?void 0:e.connection;if(!(!s||s.getShadowState()))try{s.setShadowState(n)}catch{}}}function ri(i,o,e,t,n=s=>s){var c,a;const s=e.elementName?t[e.elementName]:void 0,r=i.workspace;for(const l of i.inputList){const d=l.connection;if(!d||d.type!==S.INPUT_VALUE)continue;const h=io(o,l.name);if(!(h!=null&&h.name)||(h.kind??"value")!=="value")continue;const u=Qt(h,s);if(u){if(u.shadow&&!(((c=d.getShadowState)==null?void 0:c.call(d,!0))??((a=d.getShadowDom)==null?void 0:a.call(d))))try{d.setShadowState({type:n(u.shadow),fields:u.fieldValues??{}})}catch{}if(u.placeholder){const f=i,p=f.__morphicPlaceholderSlots??(f.__morphicPlaceholderSlots=new Set),g=d.targetBlock(),v=!g||g.isShadow(),w=p.has(l.name);if(p.add(l.name),v&&!w)try{const C=r.newBlock(n(u.placeholder));if(u.fieldValues)for(const[T,F]of Object.entries(u.fieldValues)){const $=C.getField(T);$&&$.setValue(F)}C.outputConnection&&d.connect(C.outputConnection),i.rendered&&(C.initSvg(),C.queueRender())}catch{}}}}}function ci(i,o){for(const[e,t]of o){const n=i.getInput(e);if(!(n!=null&&n.connection)||n.connection.isConnected())continue;const s=[t.outputConnection,t.previousConnection];for(const r of s)if(r)try{n.connection.connect(r);break}catch{continue}}}function ai(i,o,e){const t=Object.entries(o.fields??{}).filter(([s])=>!i.getField(s));if(t.length===0)return;const n=i.appendDummyInput(Wn);for(const[s,r]of t)n.appendField(Co(r,e),s);n.setVisible(!1)}function li(i){const o=new Map;for(const e of i.inputList)for(const t of e.fieldRow)t.name&&!Ye(t)&&o.set(t.name,t.getValue());return o}function di(i,o){for(const[e,t]of o){const n=i.getField(e);if(n&&t!==void 0&&t!==null)try{n.setValue(t)}catch{}}Mt(i)}function hi(i){for(;i.inputList.length>0;){const o=i.inputList[0];if(!o)break;i.removeInput(o.name,!0)}}function ui(i,o){o.output!==void 0&&fi(i,o.output),o.previousStatement!==void 0&&pi(i,o.previousStatement),o.nextStatement!==void 0&&mi(i,o.nextStatement),o.strict&&An(i)}function fi(i,o){if(o===!1){i.setOutput(!1);return}if(o===!0){i.setOutput(!0);return}i.setOutput(!0,o)}function pi(i,o){if(o===!1){i.setPreviousStatement(!1);return}if(o===!0){i.setPreviousStatement(!0);return}i.setPreviousStatement(!0,o)}function mi(i,o){if(o===!1){i.setNextStatement(!1);return}if(o===!0){i.setNextStatement(!0);return}i.setNextStatement(!0,o)}function Ee(i,o){const e=Array.from(i).filter(t=>t.startsWith(o));for(const t of e)i.remove(t)}function So(i,o,e){if(!e)return[];const t={keyword:i.Decoration.mark({class:"morphic-tok-keyword"}),string:i.Decoration.mark({class:"morphic-tok-string"}),number:i.Decoration.mark({class:"morphic-tok-number"}),comment:i.Decoration.mark({class:"morphic-tok-comment"})},n=Eo(e),s=(u,f,p)=>{for(const g of n(u))p.add(f+g.from,f+g.to,t[g.kind])},r=u=>{const f=new o.RangeSetBuilder,p=u.state.doc;for(const{from:g,to:v}of u.visibleRanges){let w=g;for(;w<=v;){const C=p.lineAt(w);if(s(C.text,C.from,f),C.to>=v)break;w=C.to+1}}return f.finish()},c=i.ViewPlugin.fromClass(class{constructor(u){y(this,"decorations");this.decorations=r(u)}update(u){(u.docChanged||u.viewportChanged)&&(this.decorations=r(u.view))}},{decorations:u=>u.decorations}),a=i.EditorView.baseTheme({".morphic-tok-keyword":{color:"#cc7832"},".morphic-tok-string":{color:"#6a8759"},".morphic-tok-number":{color:"#6897bb"},".morphic-tok-comment":{color:"#808080",fontStyle:"italic"}}),l=e.colors??{},d={};l.keyword&&(d[".cm-content .morphic-tok-keyword"]={color:l.keyword}),l.string&&(d[".cm-content .morphic-tok-string"]={color:l.string}),l.number&&(d[".cm-content .morphic-tok-number"]={color:l.number}),l.comment&&(d[".cm-content .morphic-tok-comment"]={color:l.comment,fontStyle:"italic"});const h=[c,a];return Object.keys(d).length>0&&h.push(i.EditorView.theme(d)),h}function Eo(i){const o=new Set(i.keywords??[]),e=(i.strings??[]).map(s=>typeof s=="string"?{open:s,close:s}:{open:s[0],close:s[1]}),t=i.comment,n=i.numbers!==!1;return s=>{const r=[],c=s.length;let a=0;for(;a<c;){if(t&&s.startsWith(t,a))return r.push({from:a,to:c,kind:"comment"}),r;let l=!1;for(const h of e)if(s.startsWith(h.open,a)){const u=a;for(a+=h.open.length;a<c;){if(s[a]==="\\"&&a+1<c){a+=2;continue}if(s.startsWith(h.close,a)){a+=h.close.length;break}a+=1}r.push({from:u,to:a,kind:"string"}),l=!0;break}if(l)continue;if(n){const h=/^\d+(?:\.\d+)?/.exec(s.slice(a));if(h){r.push({from:a,to:a+h[0].length,kind:"number"}),a+=h[0].length;continue}}const d=/^[\p{L}\p{M}_][\p{L}\p{M}\p{N}_]*/u.exec(s.slice(a));if(d){o.has(d[0])&&r.push({from:a,to:a+d[0].length,kind:"keyword"}),a+=d[0].length;continue}a+=1}return r}}const Ot="morphic/block-id";let ht;function At(i){const{from:o,to:e,empty:t}=i.selection.main;if(t)return null;const n=i.doc.lineAt(o).number,s=i.doc.lineAt(e),r=s.from===e&&s.number>n?s.number-1:s.number;return{first:n,last:r}}function Dt(){return ht}function xo(i){ht=i}const To={fontSize:"14px",fontFamily:"monospace",lineHeight:1.5},qe={...To,background:"#1e1e1e",foreground:"#d4d4d4",gutterBackground:"#1e1e1e",gutterForeground:"#858585",selectionBackground:"#264f78"};function gi(i){return typeof ResizeObserver>"u"?[]:[i.ViewPlugin.fromClass(class{constructor(o){y(this,"observer");y(this,"watched",new Set);y(this,"destroyed",!1);this.view=o,this.observer=new ResizeObserver(()=>{const e=this.view.viewState;e&&(e.mustMeasureContent=!0),this.view.requestMeasure()}),queueMicrotask(()=>this.watch())}update(){queueMicrotask(()=>this.watch())}destroy(){this.destroyed=!0,this.observer.disconnect()}watch(){if(this.destroyed)return;const o=new Set(Array.from(this.view.contentDOM.children));for(const e of this.watched)o.has(e)||(this.observer.unobserve(e),this.watched.delete(e));for(const e of o)this.watched.has(e)||(this.observer.observe(e,{box:"border-box"}),this.watched.add(e))}})]}const Le=(i,o)=>`color-mix(in srgb, ${i} ${o}%, transparent)`;let Lo=!1;async function ki(){if(Lo)return;Lo=!0;const o=(await Promise.resolve().then(()=>Us)).default,e=document.createElement("style");e.dataset.morphicSource="code-editor",e.textContent=o,document.head.appendChild(e)}const vi=150,wi=new Set(["create","delete","move","change"]);function yi(i){return wi.has(i.type)}async function bi(i){let o,e;try{[o,e]=await Promise.all([import("@codemirror/view"),import("@codemirror/state")])}catch{throw new Error(`CodeMirror is required for the codespace, preview and code editor. Install it:
|
|
2
7
|
npm install @codemirror/view @codemirror/state`)}if(!i)return{view:o,state:e,langJs:void 0};try{return{view:o,state:e,langJs:await import("@codemirror/lang-javascript")}}catch{throw new Error(`The code editor also needs JavaScript language support. Install it:
|
|
3
|
-
npm install @codemirror/lang-javascript`)}}function Te(i,o){const e={...ne,...o};return i.EditorView.theme({"&":{fontSize:e.fontSize,fontFamily:e.fontFamily,backgroundColor:e.background,color:e.foreground},".cm-scroller":{fontFamily:e.fontFamily},".cm-content":{lineHeight:String(e.lineHeight)},".cm-gutters":{backgroundColor:e.gutterBackground,color:e.gutterForeground,border:"none"},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground":{backgroundColor:`${e.selectionBackground} !important`},".morphic-delete-marker":{color:ie(e.foreground,70),backgroundColor:ie(e.foreground,12)},".morphic-delete-marker:hover":{color:e.foreground,backgroundColor:ie(e.foreground,22)},".morphic-grip-marker":{color:ie(e.foreground,75)},".morphic-grip-marker:hover":{color:e.foreground}})}class ge{constructor(o,e,t,n={},s=!1){m(this,"editorView");m(this,"container");m(this,"options");m(this,"workspace");m(this,"generateWithMetadata");m(this,"visible",!0);m(this,"syncTimer");m(this,"changeListener");m(this,"lastCode","");m(this,"metadata",new Map);m(this,"placeholders",[]);m(this,"placeholderEditorEl");m(this,"placeholderEditorScrollHandler");m(this,"placeholderEditorOutsideHandler");m(this,"onCursorLine");m(this,"onEmptyClick");m(this,"cm");m(this,"themeCompartment");m(this,"syntaxHighlightCompartment");m(this,"highlightEffect");m(this,"highlightColor");m(this,"themeSelection",ne.selectionBackground);m(this,"activeHighlight");m(this,"metadataEffect");m(this,"placeholderEffect");m(this,"dropIndicatorEffect");m(this,"valueSlotHighlightEffect");m(this,"hoverHighlightEffect");m(this,"editableHoverHighlightEffect");m(this,"emptyClickListener");m(this,"disposed",!1);m(this,"zoomFactor",1);this.javascript=s,this.container=o,this.workspace=e,this.generateWithMetadata=t,this.options=n}getPlaceholders(){return this.placeholders}findPlaceholderAtPos(o){if(this.options.showPlaceholderMarkers===!1)return null;let e=null,t=1/0;for(const n of this.placeholders){if(n.start>o)break;if(o>=n.start&&o<=n.end){const s=n.end-n.start;s<t&&(t=s,e=n)}}return e}closePlaceholderEditor(){const o=this.placeholderEditorEl;o&&(this.placeholderEditorEl=void 0,this.placeholderEditorScrollHandler&&this.editorView&&(this.editorView.scrollDOM.removeEventListener("scroll",this.placeholderEditorScrollHandler),this.placeholderEditorScrollHandler=void 0),this.placeholderEditorOutsideHandler&&(document.removeEventListener("mousedown",this.placeholderEditorOutsideHandler),this.placeholderEditorOutsideHandler=void 0),o.parentNode&&o.parentNode.removeChild(o))}openPlaceholderEditor(o){if(!this.editorView||!o.edit)return;const e=this.options.onPlaceholderApply;if(!e)return;this.closePlaceholderEditor();const t=this.editorView,n=t.coordsAtPos(o.start),s=t.coordsAtPos(o.end);if(!n||!s)return;const r=t.scrollDOM.getBoundingClientRect(),c=t.state.doc.sliceString(o.start,o.end),a=o.edit;let d;if(a.fieldType==="dropdown"){const v=document.createElement("select");for(const[w,b]of a.options??[]){const g=document.createElement("option");g.value=b,g.textContent=w,v.appendChild(g)}d=v}else{const v=document.createElement("input");v.type=a.fieldType==="number"?"number":"text",v.value=c,d=v}const l=getComputedStyle(t.contentDOM),h=(()=>{let v=t.dom;for(;v;){const w=getComputedStyle(v).backgroundColor;if(w&&w!=="rgba(0, 0, 0, 0)"&&w!=="transparent")return w;v=v.parentElement}return"#fff"})();Object.assign(d.style,{position:"absolute",left:`${n.left-r.left+t.scrollDOM.scrollLeft}px`,top:`${n.top-r.top+t.scrollDOM.scrollTop}px`,minWidth:`${Math.max(40,s.right-n.left+8)}px`,height:`${n.bottom-n.top}px`,font:l.font,lineHeight:l.lineHeight,padding:"0 2px",margin:"0",border:`1px solid ${l.color}`,borderRadius:"2px",background:h,color:l.color,boxSizing:"border-box",zIndex:"20"}),t.scrollDOM.appendChild(d),this.placeholderEditorEl=d;const u=()=>{const v=d.value;this.closePlaceholderEditor(),e(a,v)},k=()=>{this.closePlaceholderEditor()};if(d.addEventListener("keydown",v=>{const w=v.key;w==="Enter"?(v.preventDefault(),u()):w==="Escape"&&(v.preventDefault(),k())}),d.addEventListener("mousedown",v=>v.stopPropagation()),d.addEventListener("click",v=>v.stopPropagation()),a.fieldType==="dropdown"){d.addEventListener("change",()=>u());const v=this.workspace.getBlockById(a.blockId),w=v==null?void 0:v.getField(a.fieldName),b=w==null?void 0:w.getValue();b!=null&&(d.value=String(b)),requestAnimationFrame(()=>{this.placeholderEditorOutsideHandler=g=>{g.target instanceof Node&&!d.contains(g.target)&&k()},document.addEventListener("mousedown",this.placeholderEditorOutsideHandler)})}else d.addEventListener("blur",()=>u());this.placeholderEditorScrollHandler=()=>this.closePlaceholderEditor(),t.scrollDOM.addEventListener("scroll",this.placeholderEditorScrollHandler),requestAnimationFrame(()=>{d.focus({preventScroll:!0}),d instanceof HTMLInputElement&&d.select()})}async mount(){var b;if(to(),this.cm=await so(this.javascript),this.disposed)return;const{view:o,state:e,langJs:t}=this.cm;this.themeCompartment=new e.Compartment,this.syntaxHighlightCompartment=new e.Compartment;const n=Te(o,this.options.theme??{});this.themeSelection=((b=this.options.theme)==null?void 0:b.selectionBackground)??ne.selectionBackground;const s=je(o,e,this.options.highlightRules),r=e.StateEffect.define();this.metadataEffect=r;const c=e.StateEffect.define();this.placeholderEffect=c;const a=e.StateField.define({create(){return o.Decoration.none},update(g,y){for(const C of y.effects)if(C.is(c)){const E=C.value;if(!E||E.length===0)return o.Decoration.none;const f=y.state.doc.length,p=[...E].filter(B=>B.start<B.end&&B.end<=f).sort((B,D)=>B.start-D.start||B.end-D.end),S=new e.RangeSetBuilder,T=o.Decoration.mark({class:"morphic-placeholder-default"}),M=o.Decoration.mark({class:"morphic-placeholder-set"});for(const B of p)S.add(B.start,B.end,B.kind==="default"?T:M);return S.finish()}return y.changes.empty?g:o.Decoration.none},provide(g){return o.EditorView.decorations.from(g)}}),d=e.StateEffect.define();this.highlightEffect=d;const l=this,h=e.StateField.define({create(){return o.Decoration.none},update(g,y){for(const C of y.effects)if(C.is(d)){const E=C.value;if(!E)return o.Decoration.none;const f=Array.isArray(E)?E:[E];if(f.length===0)return o.Decoration.none;const p=y.state.doc,S=o.Decoration.mark({class:"morphic-highlight",attributes:{style:`background: ${l.highlightColor??ie(l.themeSelection,60)}`}}),T=f.map(M=>{const B=p.line(Math.min(M.fromLine,p.lines)).from,D=p.line(Math.min(M.toLine,p.lines)).to;return S.range(B,D)}).sort((M,B)=>M.from-B.from);return o.Decoration.set(T)}return y.changes.empty?g:o.Decoration.none},provide(g){return o.EditorView.decorations.from(g)}}),u=o.EditorView.updateListener.of(g=>{var f;if(g.docChanged||g.transactions.some(p=>p.isUserEvent("select.pointer")))return;const y=g.state.selection.main.head,C=g.startState.selection.main.head;if(y===C)return;if(l.findPlaceholderAtPos(y)){(f=l.onEmptyClick)==null||f.call(l);return}if(!l.onCursorLine)return;const E=g.state.doc.lineAt(y).number;l.onCursorLine(E)}),k=this.options.showPlaceholderMarkers!==!1,v=[o.lineNumbers(),o.highlightSpecialChars(),e.EditorState.readOnly.of(!0),...t?[t.javascript()]:[],h,...k?[a]:[],u,this.themeCompartment.of(n),this.syntaxHighlightCompartment.of(s),...this.buildDeleteExtensions(o,e,r),...this.buildGripExtensions(o,e,r),...this.buildDropIndicatorExtensions(o,e),...this.buildValueSlotHighlightExtensions(o,e),...this.buildHoverHighlightExtensions(o,e),...this.buildEditableHoverHighlightExtensions(o,e),...this.options.extensions??[]],w=this.generateWithMetadata();this.lastCode=w.code,this.metadata=w.metadata,this.placeholders=[...w.placeholders].sort((g,y)=>g.start-y.start),this.editorView=new o.EditorView({parent:this.container,state:e.EditorState.create({doc:this.lastCode,extensions:v})}),this.metadataEffect&&this.metadata.size>0&&this.editorView.dispatch({effects:this.metadataEffect.of(this.metadata)}),this.placeholderEffect&&w.placeholders.length>0&&this.editorView.dispatch({effects:this.placeholderEffect.of(w.placeholders)}),this.emptyClickListener=g=>{var C,E,f;if(this.isBelowLastLine(g.clientY)){(C=this.onEmptyClick)==null||C.call(this);return}const y=(E=this.editorView)==null?void 0:E.posAtCoords({x:g.clientX,y:g.clientY});if(typeof y=="number"){const p=this.findPlaceholderAtPos(y);if(p){(f=this.onEmptyClick)==null||f.call(this),p.edit&&this.options.onPlaceholderApply&&requestAnimationFrame(()=>this.openPlaceholderEditor(p));return}}if(this.onCursorLine){const p=this.getLineAtCoords(g.clientX,g.clientY);p!==null&&this.onCursorLine(p)}},this.editorView.scrollDOM.addEventListener("click",this.emptyClickListener),this.attachSyncListener()}buildDeleteExtensions(o,e,t){const n=this.options.onDelete;if(!n)return[];class s extends o.GutterMarker{toDOM(){const h=document.createElement("span");return h.textContent="✕",h.className="morphic-delete-marker",h.style.cssText=["display: inline-flex","align-items: center","justify-content: center","width: 16px","height: 16px","margin: 0 4px","border-radius: 50%","font-size: 10px","line-height: 1","cursor: pointer","transition: background 0.15s, color 0.15s"].join(";"),h}}const r=new s,c=e.StateField.define({create(){return e.RangeSet.empty},update(l,h){for(const u of h.effects)if(u.is(t)){const k=u.value,v=h.state.doc,w=new Set;for(const{startLine:g}of k.values())g>=1&&g<=v.lines&&w.add(g);const b=Array.from(w).sort((g,y)=>g-y).map(g=>r.range(v.line(g).from));return e.RangeSet.of(b,!0)}return l.map(h.changes)}}),a=o.gutter({class:"morphic-delete-gutter",markers(l){return l.state.field(c)},initialSpacer:()=>r,domEventHandlers:{click(l,h){const u=l.state.doc.lineAt(h.from).number;return n(u),!0}}}),d=o.keymap.of([{key:"Delete",run:l=>{if(!l.state.selection.main.empty)return!1;const h=l.state.doc.lineAt(l.state.selection.main.head).number;return n(h),!0}},{key:"Backspace",run:l=>{if(!l.state.selection.main.empty)return!1;const h=l.state.doc.lineAt(l.state.selection.main.head).number;return n(h),!0}}]);return[c,a,e.Prec.highest(d)]}buildGripExtensions(o,e,t){const n=this.options.canDragBlock;if(!n)return[];class s extends o.GutterMarker{constructor(d){super(),this.blockId=d}eq(d){return d instanceof s&&d.blockId===this.blockId}toDOM(){const d=document.createElement("span");d.textContent="⠿",d.draggable=!0,d.className="morphic-grip-marker",d.style.cssText=["display: inline-flex","align-items: center","justify-content: center","width: 16px","height: 16px","margin: 0 2px","font-size: 14px","line-height: 1","cursor: grab","user-select: none","transition: color 0.15s"].join(";");const l=this.blockId;return d.addEventListener("dragstart",h=>{h.dataTransfer&&(h.dataTransfer.setData(Se,l),h.dataTransfer.effectAllowed="move",d.style.cursor="grabbing",me=l)}),d.addEventListener("dragend",()=>{d.style.cursor="grab",me=void 0}),d}}const r=e.StateField.define({create(){return e.RangeSet.empty},update(a,d){for(const l of d.effects)if(l.is(t)){const h=l.value,u=d.state.doc,k=new Map;for(const[w,{startLine:b,startChar:g,endChar:y}]of h){if(b<1||b>u.lines||!n(w))continue;const C=(y??0)-(g??0),E=k.get(b);(!E||C>E.width)&&k.set(b,{id:w,width:C})}const v=Array.from(k.entries()).sort((w,b)=>w[0]-b[0]).map(([w,{id:b}])=>new s(b).range(u.line(w).from));return e.RangeSet.of(v,!0)}return a.map(d.changes)}}),c=o.gutter({class:"morphic-grip-gutter",markers(a){return a.state.field(r)},initialSpacer:()=>new s("")});return[r,c]}buildDropIndicatorExtensions(o,e){const t=e.StateEffect.define();this.dropIndicatorEffect=t;const n=e.StateField.define({create(){return o.Decoration.none},update(r,c){for(const a of c.effects)if(a.is(t)){const d=a.value;if(!d)return o.Decoration.none;const l=c.state.doc,h=Math.max(1,Math.min(d.line,l.lines)),u=l.line(h),k=d.position==="above"?"morphic-drop-indicator-above":"morphic-drop-indicator-below",v=o.Decoration.line({class:k});return o.Decoration.set([v.range(u.from)])}return c.changes.empty?r:o.Decoration.none},provide(r){return o.EditorView.decorations.from(r)}}),s=o.EditorView.baseTheme({".morphic-drop-indicator-above":{boxShadow:"inset 0 2px 0 0 #5a86bc"},".morphic-drop-indicator-below":{boxShadow:"inset 0 -2px 0 0 #5a86bc"}});return[n,s]}buildValueSlotHighlightExtensions(o,e){const t=e.StateEffect.define();this.valueSlotHighlightEffect=t;const n=o.Decoration.mark({class:"morphic-value-slot-target"}),s=e.StateField.define({create(){return o.Decoration.none},update(c,a){for(const d of a.effects)if(d.is(t)){const l=d.value;if(!l)return o.Decoration.none;const h=a.state.doc.length,u=Math.max(0,Math.min(l.from,h)),k=Math.max(u,Math.min(l.to,h));return u===k?o.Decoration.none:o.Decoration.set([n.range(u,k)])}return a.changes.empty?c:o.Decoration.none},provide(c){return o.EditorView.decorations.from(c)}}),r=o.EditorView.baseTheme({".morphic-value-slot-target":{outline:"1px solid #5a86bc",outlineOffset:"1px",borderRadius:"2px"}});return[s,r]}buildHoverHighlightExtensions(o,e){const t=e.StateEffect.define();this.hoverHighlightEffect=t;const n=o.Decoration.mark({class:"morphic-hover-target"}),s=e.StateField.define({create(){return o.Decoration.none},update(c,a){for(const d of a.effects)if(d.is(t)){const l=d.value;if(!l)return o.Decoration.none;const h=a.state.doc.length,u=Math.max(0,Math.min(l.from,h)),k=Math.max(u,Math.min(l.to,h));return u===k?o.Decoration.none:o.Decoration.set([n.range(u,k)])}return a.changes.empty?c:o.Decoration.none},provide(c){return o.EditorView.decorations.from(c)}}),r=o.EditorView.baseTheme({".morphic-hover-target":{backgroundColor:"rgba(127, 127, 127, 0.10)",borderRadius:"2px"}});return[s,r]}setHoverHighlight(o){!this.editorView||!this.hoverHighlightEffect||this.editorView.dispatch({effects:this.hoverHighlightEffect.of(o)})}buildEditableHoverHighlightExtensions(o,e){const t=e.StateEffect.define();this.editableHoverHighlightEffect=t;const n=o.Decoration.mark({class:"morphic-editable-hover"}),s=e.StateField.define({create(){return o.Decoration.none},update(c,a){for(const d of a.effects)if(d.is(t)){const l=d.value;if(!l)return o.Decoration.none;const h=a.state.doc.length,u=Math.max(0,Math.min(l.from,h)),k=Math.max(u,Math.min(l.to,h));return u===k?o.Decoration.none:o.Decoration.set([n.range(u,k)])}return a.changes.empty?c:o.Decoration.none},provide(c){return o.EditorView.decorations.from(c)}}),r=o.EditorView.baseTheme({".morphic-editable-hover":{outline:"1px solid #5a86bc",outlineOffset:"1px",borderRadius:"2px"}});return[s,r]}setEditableHoverHighlight(o){!this.editorView||!this.editableHoverHighlightEffect||this.editorView.dispatch({effects:this.editableHoverHighlightEffect.of(o)})}show(){this.visible||(this.visible=!0,this.container.style.display="",this.syncNow(),this.attachSyncListener())}hide(){this.visible&&(this.visible=!1,this.container.style.display="none",this.detachSyncListener())}isVisible(){return this.visible}highlightLines(o){!this.editorView||!this.highlightEffect||(this.activeHighlight=o,this.editorView.dispatch({effects:this.highlightEffect.of(o)}))}clearHighlight(){!this.editorView||!this.highlightEffect||(this.activeHighlight=void 0,this.editorView.dispatch({effects:this.highlightEffect.of(null)}))}setHighlightColor(o){this.highlightColor=o,this.activeHighlight&&this.highlightLines(this.activeHighlight)}showDropIndicator(o,e="above"){!this.editorView||!this.dropIndicatorEffect||this.editorView.dispatch({effects:this.dropIndicatorEffect.of({line:o,position:e})})}hideDropIndicator(){!this.editorView||!this.dropIndicatorEffect||this.editorView.dispatch({effects:this.dropIndicatorEffect.of(null)})}showValueSlotHighlight(o,e){!this.editorView||!this.valueSlotHighlightEffect||this.editorView.dispatch({effects:this.valueSlotHighlightEffect.of({from:o,to:e})})}hideValueSlotHighlight(){!this.editorView||!this.valueSlotHighlightEffect||this.editorView.dispatch({effects:this.valueSlotHighlightEffect.of(null)})}getLineAtCoords(o,e){if(!this.editorView)return null;const t=this.editorView.posAtCoords({x:o,y:e});return t===null?null:this.editorView.state.doc.lineAt(t).number}charAtCoords(o,e){return this.editorView?this.editorView.posAtCoords({x:o,y:e})??null:null}getLineCount(){var o;return((o=this.editorView)==null?void 0:o.state.doc.lines)??0}isBelowLastLine(o){if(!this.editorView)return!1;const e=this.editorView.state.doc,t=e.line(e.lines).to,n=this.editorView.coordsAtPos(t);return n?o>n.bottom:!1}isInLowerHalfOfLine(o,e){if(!this.editorView)return!1;const t=this.editorView.state.doc;if(o<1||o>t.lines)return!1;const n=t.line(o),s=this.editorView.coordsAtPos(n.from),r=this.editorView.coordsAtPos(n.to);return!s||!r?!1:e>(s.top+r.bottom)/2}setTheme(o){if(!this.editorView||!this.cm||!this.themeCompartment)return;this.themeSelection=o.selectionBackground??ne.selectionBackground,this.activeHighlight&&this.highlightLines(this.activeHighlight);const e=Te(this.cm.view,o);this.editorView.dispatch({effects:this.themeCompartment.reconfigure(e)})}setHighlightRules(o){if(!this.editorView||!this.cm||!this.syntaxHighlightCompartment)return;const e=je(this.cm.view,this.cm.state,o);this.editorView.dispatch({effects:this.syntaxHighlightCompartment.reconfigure(e)})}dispose(){var o;this.disposed=!0,this.detachSyncListener(),this.syncTimer!==void 0&&(clearTimeout(this.syncTimer),this.syncTimer=void 0),this.emptyClickListener&&this.editorView&&(this.editorView.scrollDOM.removeEventListener("click",this.emptyClickListener),this.emptyClickListener=void 0),(o=this.editorView)==null||o.destroy(),this.editorView=void 0,this.metadata=new Map,this.placeholders=[],this.lastCode=""}refresh(){this.syncNow()}getValue(){var o;return((o=this.editorView)==null?void 0:o.state.doc.toString())??this.lastCode??""}getCursorLine(){if(!this.editorView)return 1;const o=this.editorView.state.selection.main.head;return this.editorView.state.doc.lineAt(o).number}adjustZoom(o){if(!this.editorView||!this.cm||!this.themeCompartment)return;const e=this.options.theme??{},t=parseFloat(e.fontSize??ne.fontSize);o==="fit"?this.zoomFactor=1:o==="in"?this.zoomFactor=Math.min(4,this.zoomFactor*1.2):this.zoomFactor=Math.max(.25,this.zoomFactor/1.2);const n={...e,fontSize:`${(t*this.zoomFactor).toFixed(2)}px`},s=Te(this.cm.view,n);this.editorView.dispatch({effects:this.themeCompartment.reconfigure(s)})}syncNow(){if(!this.editorView||!this.cm)return;const o=this.generateWithMetadata();if(o.code===this.lastCode)return;this.closePlaceholderEditor(),this.lastCode=o.code,this.metadata=o.metadata,this.placeholders=[...o.placeholders].sort((t,n)=>t.start-n.start);const e=[];this.metadataEffect&&e.push(this.metadataEffect.of(o.metadata)),this.placeholderEffect&&e.push(this.placeholderEffect.of(o.placeholders)),this.editorView.dispatch({changes:{from:0,to:this.editorView.state.doc.length,insert:o.code},effects:e.length>0?e:void 0})}scheduleDebouncedSync(){this.syncTimer!==void 0&&clearTimeout(this.syncTimer),this.syncTimer=setTimeout(()=>{this.syncTimer=void 0,this.syncNow()},oo)}attachSyncListener(){this.changeListener||(this.changeListener=o=>{io(o)&&this.scheduleDebouncedSync()},this.workspace.addChangeListener(this.changeListener))}detachSyncListener(){this.changeListener&&(this.workspace.removeChangeListener(this.changeListener),this.changeListener=void 0,this.syncTimer!==void 0&&(clearTimeout(this.syncTimer),this.syncTimer=void 0))}}const Le="morphic:";function Me(i){return Le+i}function W(i){return i.startsWith(Le)?i.slice(Le.length):i}function U(i,o){return o.has(i)?Me(i):i}function ro(i,o,e,t){const n={behaviors:e,definitions:o};return Ke(J.javascriptGenerator,n,t,!1),J.javascriptGenerator.workspaceToCode(i)}function co(i,o,e,t){const n={behaviors:e,definitions:o};Ke(J.javascriptGenerator,n,t,!0);const s=J.javascriptGenerator.workspaceToCode(i);return bo(s)}const ao="// __MORPHIC_BLOCK_START:",lo="// __MORPHIC_BLOCK_END:",Ye="__";function Ke(i,o,e,t=!1){i.STATEMENT_PREFIX=(e==null?void 0:e.statementPrefix)??null,i.STATEMENT_SUFFIX=(e==null?void 0:e.statementSuffix)??null,i.INFINITE_LOOP_TRAP=(e==null?void 0:e.infiniteLoopTrap)??null,e!=null&&e.reservedWords&&i.addReservedWords(e.reservedWords);for(const[n,s]of o.definitions){const r=Ct(o.behaviors[n]);i.forBlock[Me(n)]=(c,a)=>{const d=ho(c,a),l=r?r(d):wo(n,s);if(mo(c,s))return[ko(l),J.Order.NONE];const h=go(l);return t?`${ao}${c.id}${Ye}
|
|
4
|
-
${h}${
|
|
5
|
-
`:h}}}function
|
|
8
|
+
npm install @codemirror/lang-javascript`)}}function Nt(i,o){const e={...o.codemirror?To:qe,...o},t=e.foreground??"currentColor",n=i.EditorView.theme({"&":{fontSize:e.fontSize??null,fontFamily:e.fontFamily??null,backgroundColor:e.background??null,color:e.foreground??null},".cm-scroller":{fontFamily:e.fontFamily??null},".cm-content":{lineHeight:String(e.lineHeight)},".cm-gutters":{backgroundColor:e.gutterBackground??null,color:e.gutterForeground??null,...o.codemirror?{}:{border:"none"}},...e.selectionBackground?{"&.cm-focused .cm-selectionBackground, .cm-selectionBackground":{backgroundColor:`${e.selectionBackground} !important`}}:{},".morphic-delete-marker":{color:Le(t,70),backgroundColor:Le(t,12)},".morphic-delete-marker:hover":{color:t,backgroundColor:Le(t,22)},".morphic-grip-marker":{color:Le(t,75)},".morphic-grip-marker:hover":{color:t},".morphic-repeat-buttons":{display:"none",gap:"2px",margin:"0 2px",verticalAlign:"middle"},".cm-line:hover .morphic-repeat-buttons, .cm-line.morphic-highlight .morphic-repeat-buttons":{display:"inline-flex"},".morphic-repeat-button":{width:"16px",height:"16px",padding:"0",border:"none",borderRadius:"50%",font:"inherit",fontSize:"12px",lineHeight:"16px",cursor:"pointer",color:Le(t,70),backgroundColor:Le(t,12)},".morphic-repeat-button:hover":{color:t,backgroundColor:Le(t,22)}});return o.codemirror?[n,o.codemirror]:n}class Bo{constructor(o,e,t,n={},s=!1){y(this,"editorView");y(this,"container");y(this,"options");y(this,"workspace");y(this,"generateWithMetadata");y(this,"visible",!0);y(this,"syncTimer");y(this,"changeListener");y(this,"lastCode","");y(this,"metadata",new Map);y(this,"placeholders",[]);y(this,"placeholderEditorEl");y(this,"placeholderEditorScrollHandler");y(this,"placeholderEditorOutsideHandler");y(this,"onCursorLine");y(this,"onEmptyClick");y(this,"cm");y(this,"themeCompartment");y(this,"syntaxHighlightCompartment");y(this,"highlightEffect");y(this,"themeSelection",qe.selectionBackground);y(this,"activeHighlight");y(this,"metadataEffect");y(this,"placeholderEffect");y(this,"repeatEffect");y(this,"dropIndicatorEffect");y(this,"valueSlotHighlightEffect");y(this,"hoverHighlightEffect");y(this,"groupsEffect");y(this,"editableHoverHighlightEffect");y(this,"emptyClickListener");y(this,"disposed",!1);y(this,"zoomFactor",1);this.javascript=s,this.container=o,this.workspace=e,this.generateWithMetadata=t,this.options=n}getPlaceholders(){return this.placeholders}findPlaceholderAtPos(o){if(this.options.showPlaceholderMarkers===!1)return null;let e=null,t=1/0;for(const n of this.placeholders){if(n.start>o)break;if(o>=n.start&&o<=n.end){const s=n.end-n.start;s<t&&(t=s,e=n)}}return e}closePlaceholderEditor(){const o=this.placeholderEditorEl;o&&(this.placeholderEditorEl=void 0,this.placeholderEditorScrollHandler&&this.editorView&&(this.editorView.scrollDOM.removeEventListener("scroll",this.placeholderEditorScrollHandler),this.placeholderEditorScrollHandler=void 0),this.placeholderEditorOutsideHandler&&(document.removeEventListener("mousedown",this.placeholderEditorOutsideHandler),this.placeholderEditorOutsideHandler=void 0),o.parentNode&&o.parentNode.removeChild(o))}openPlaceholderEditor(o){var p,g;if(!this.editorView||!o.edit)return;const e=this.options.onPlaceholderApply;if(!e)return;this.closePlaceholderEditor();const t=this.editorView,n=t.coordsAtPos(o.start),s=t.coordsAtPos(o.end);if(!n||!s)return;const r=t.scrollDOM.getBoundingClientRect(),c=t.state.doc.sliceString(o.start,o.end),a=o.edit;let l;if(a.fieldType==="dropdown"){const v=document.createElement("select");for(const[w,C]of a.options??[]){const T=document.createElement("option");T.value=C,T.textContent=w,v.appendChild(T)}l=v}else{const v=document.createElement("input");v.type=a.fieldType==="number"?"number":"text";const w=(g=(p=this.workspace.getBlockById(a.blockId))==null?void 0:p.getField(a.fieldName))==null?void 0:g.getValue();v.value=a.fieldType==="text"&&typeof w=="string"?w:c,l=v}const d=getComputedStyle(t.contentDOM),h=(()=>{let v=t.dom;for(;v;){const w=getComputedStyle(v).backgroundColor;if(w&&w!=="rgba(0, 0, 0, 0)"&&w!=="transparent")return w;v=v.parentElement}return"#fff"})();Object.assign(l.style,{position:"absolute",left:`${n.left-r.left+t.scrollDOM.scrollLeft}px`,top:`${n.top-r.top+t.scrollDOM.scrollTop}px`,minWidth:`${Math.max(40,s.right-n.left+8)}px`,height:`${n.bottom-n.top}px`,font:d.font,lineHeight:d.lineHeight,padding:"0 2px",margin:"0",border:`1px solid ${d.color}`,borderRadius:"2px",background:h,color:d.color,boxSizing:"border-box",zIndex:"20"}),t.scrollDOM.appendChild(l),this.placeholderEditorEl=l;const u=()=>{const v=l.value;this.closePlaceholderEditor(),e(a,v)},f=()=>{this.closePlaceholderEditor()};if(l.addEventListener("keydown",v=>{const w=v.key;w==="Enter"?(v.preventDefault(),u()):w==="Escape"&&(v.preventDefault(),f())}),l.addEventListener("mousedown",v=>v.stopPropagation()),l.addEventListener("click",v=>v.stopPropagation()),a.fieldType==="dropdown"){l.addEventListener("change",()=>u());const v=this.workspace.getBlockById(a.blockId),w=v==null?void 0:v.getField(a.fieldName),C=w==null?void 0:w.getValue();C!=null&&(l.value=String(C)),requestAnimationFrame(()=>{this.placeholderEditorOutsideHandler=T=>{T.target instanceof Node&&!l.contains(T.target)&&f()},document.addEventListener("mousedown",this.placeholderEditorOutsideHandler)})}else l.addEventListener("blur",()=>u());this.placeholderEditorScrollHandler=()=>this.closePlaceholderEditor(),t.scrollDOM.addEventListener("scroll",this.placeholderEditorScrollHandler),requestAnimationFrame(()=>{l.focus({preventScroll:!0}),l instanceof HTMLInputElement&&l.select()})}async mount(){var E,M,O;if(ki(),this.cm=await bi(this.javascript),this.disposed)return;const{view:o,state:e,langJs:t}=this.cm;this.themeCompartment=new e.Compartment,this.syntaxHighlightCompartment=new e.Compartment;const n=Nt(o,this.options.theme??{});this.themeSelection=((E=this.options.theme)==null?void 0:E.selectionBackground)??qe.selectionBackground;const s=So(o,e,this.options.highlightRules),r=e.StateEffect.define();this.metadataEffect=r;const c=e.StateEffect.define();this.placeholderEffect=c;const a=e.StateEffect.define();this.repeatEffect=a;const l=this.options.onRepeat;class d extends o.WidgetType{constructor(N){super(),this.range=N}eq(N){return N.range.blockId===this.range.blockId&&N.range.slotName===this.range.slotName&&N.range.count===this.range.count}toDOM(){const N=document.createElement("span");N.className="morphic-repeat-buttons";const{blockId:V,slotName:m,count:x}=this.range,B=(Q,P,ie)=>{const ce=document.createElement("button");ce.type="button",ce.className=`morphic-repeat-button morphic-repeat-${Q}`,ce.textContent=P,ce.addEventListener("mousedown",oe=>oe.preventDefault()),ce.addEventListener("click",oe=>{oe.stopPropagation(),l==null||l(V,m,ie)}),N.appendChild(ce)};return x>0&&B("remove","−",-1),B("add","+",1),N}ignoreEvent(){return!0}}const h=e.StateField.define({create(){return o.Decoration.none},update(A,N){for(const V of N.effects)if(V.is(a)){const m=N.state.doc.length;return o.Decoration.set(V.value.filter(x=>x.at<=m).sort((x,B)=>x.at-B.at).map(x=>o.Decoration.widget({widget:new d(x),side:1}).range(x.at)))}return N.changes.empty?A:o.Decoration.none},provide(A){return o.EditorView.decorations.from(A)}}),u=e.StateField.define({create(){return o.Decoration.none},update(A,N){for(const V of N.effects)if(V.is(c)){const m=V.value;if(!m||m.length===0)return o.Decoration.none;const x=N.state.doc.length,B=[...m].filter(oe=>oe.start<oe.end&&oe.end<=x).sort((oe,me)=>oe.start-me.start||oe.end-me.end),Q=new e.RangeSetBuilder,P=o.Decoration.mark({class:"morphic-placeholder-default"}),ie=o.Decoration.mark({class:"morphic-placeholder-set"}),ce=o.Decoration.mark({class:"morphic-placeholder-set morphic-reference-missing"});for(const oe of B)Q.add(oe.start,oe.end,oe.missing?ce:oe.kind==="default"?P:ie);return Q.finish()}return N.changes.empty?A:o.Decoration.none},provide(A){return o.EditorView.decorations.from(A)}}),f=e.StateEffect.define();this.highlightEffect=f;const p=this,g=e.StateField.define({create(){return o.Decoration.none},update(A,N){for(const V of N.effects)if(V.is(f)){const m=V.value;if(!m)return o.Decoration.none;const x=Array.isArray(m)?m:[m];if(x.length===0)return o.Decoration.none;const B=N.state.doc,Q=o.Decoration.mark({class:"morphic-highlight",attributes:{style:`background: var(--morphic-highlight-color, ${Le(p.themeSelection,60)})`}}),P=x.map(ie=>{const ce=B.line(Math.min(ie.fromLine,B.lines)).from,oe=B.line(Math.min(ie.toLine,B.lines)).to;return Q.range(ce,oe)}).sort((ie,ce)=>ie.from-ce.from);return o.Decoration.set(P)}return N.changes.empty?A:o.Decoration.none},provide(A){return o.EditorView.decorations.from(A)}}),v=o.EditorView.updateListener.of(A=>{var x;if(A.docChanged||A.transactions.some(B=>B.isUserEvent("select.pointer")))return;const N=A.state.selection.main.head,V=A.startState.selection.main.head;if(N===V)return;if(p.findPlaceholderAtPos(N)){(x=p.onEmptyClick)==null||x.call(p);return}if(!p.onCursorLine)return;const m=A.state.doc.lineAt(N).number;p.onCursorLine(m)});let w="";const C=o.EditorView.updateListener.of(A=>{var m,x;if(!A.selectionSet&&!A.docChanged)return;const N=At(A.state),V=N?`${N.first}-${N.last}`:"";V!==w&&(w=V,(x=(m=p.options).onLineSelection)==null||x.call(m))}),T=this.options.showPlaceholderMarkers!==!1,F=[o.lineNumbers(),o.highlightSpecialChars(),e.EditorState.readOnly.of(!0),...t?[t.javascript()]:[],g,...T?[u]:[],...l?[h]:[],v,C,this.themeCompartment.of(n),this.syntaxHighlightCompartment.of(s),...this.buildDeleteExtensions(o,e,r),...this.buildGripExtensions(o,e,r),...this.buildDropIndicatorExtensions(o,e),...this.buildValueSlotHighlightExtensions(o,e),...this.buildHoverHighlightExtensions(o,e),...this.buildGroupExtensions(o,e),...gi(o),...this.buildEditableHoverHighlightExtensions(o,e),...this.options.extensions??[]],$=this.generateWithMetadata();this.lastCode=$.code,this.metadata=$.metadata,this.placeholders=[...$.placeholders].sort((A,N)=>A.start-N.start),this.editorView=new o.EditorView({parent:this.container,state:e.EditorState.create({doc:this.lastCode,extensions:F})}),this.groupsEffect&&((M=$.groups)!=null&&M.length)&&this.editorView.dispatch({effects:this.groupsEffect.of($.groups)}),this.metadataEffect&&this.metadata.size>0&&this.editorView.dispatch({effects:this.metadataEffect.of(this.metadata)}),(O=$.repeats)!=null&&O.length&&this.editorView.dispatch({effects:a.of($.repeats)}),this.placeholderEffect&&$.placeholders.length>0&&this.editorView.dispatch({effects:this.placeholderEffect.of($.placeholders)}),this.emptyClickListener=A=>{var V,m,x;if(this.isBelowLastLine(A.clientY)){(V=this.onEmptyClick)==null||V.call(this);return}const N=(m=this.editorView)==null?void 0:m.posAtCoords({x:A.clientX,y:A.clientY});if(typeof N=="number"){const B=this.findPlaceholderAtPos(N);if(B){(x=this.onEmptyClick)==null||x.call(this),B.edit&&this.options.onPlaceholderApply&&requestAnimationFrame(()=>this.openPlaceholderEditor(B));return}}if(this.onCursorLine){const B=this.getLineAtCoords(A.clientX,A.clientY);B!==null&&this.onCursorLine(B)}},this.editorView.scrollDOM.addEventListener("click",this.emptyClickListener),this.attachSyncListener()}buildDeleteExtensions(o,e,t){const n=this.options.onDelete;if(!n)return[];class s extends o.GutterMarker{toDOM(){const u=document.createElement("span");return u.textContent="✕",u.className="morphic-delete-marker",u.style.cssText=["display: inline-flex","align-items: center","justify-content: center","width: 16px","height: 16px","margin: 0 4px","border-radius: 50%","font-size: 10px","line-height: 1","cursor: pointer","transition: background 0.15s, color 0.15s"].join(";"),u}}const r=new s,c=e.StateField.define({create(){return e.RangeSet.empty},update(h,u){for(const f of u.effects)if(f.is(t)){const p=f.value,g=u.state.doc,v=new Set;for(const{startLine:C}of p.values())C>=1&&C<=g.lines&&v.add(C);const w=Array.from(v).sort((C,T)=>C-T).map(C=>r.range(g.line(C).from));return e.RangeSet.of(w,!0)}return h.map(u.changes)}}),a=o.gutter({class:"morphic-delete-gutter",markers(h){return h.state.field(c)},initialSpacer:()=>r,domEventHandlers:{click(h,u){const f=h.state.doc.lineAt(u.from).number;return n(f),!0}}}),l=h=>{const u=At(h.state);return u?n(u.first,u.last):n(h.state.doc.lineAt(h.state.selection.main.head).number),!0},d=o.keymap.of([{key:"Delete",run:l},{key:"Backspace",run:l}]);return[...this.options.deleteButtons!==!1?[c,a]:[],...this.options.deleteKeys!==!1?[e.Prec.highest(d)]:[]]}buildGripExtensions(o,e,t){const n=this.options.canDragBlock;if(!n)return[];class s extends o.GutterMarker{constructor(l){super(),this.blockId=l}eq(l){return l instanceof s&&l.blockId===this.blockId}toDOM(){const l=document.createElement("span");l.textContent="⠿",l.draggable=!0,l.className="morphic-grip-marker",l.style.cssText=["display: inline-flex","align-items: center","justify-content: center","width: 16px","height: 16px","margin: 0 2px","font-size: 14px","line-height: 1","cursor: grab","user-select: none","transition: color 0.15s"].join(";");const d=this.blockId;return l.addEventListener("dragstart",h=>{h.dataTransfer&&(h.dataTransfer.setData(Ot,d),h.dataTransfer.effectAllowed="move",l.style.cursor="grabbing",ht=d)}),l.addEventListener("dragend",()=>{l.style.cursor="grab",ht=void 0}),l}}const r=e.StateField.define({create(){return e.RangeSet.empty},update(a,l){for(const d of l.effects)if(d.is(t)){const h=d.value,u=l.state.doc,f=new Map;for(const[g,{startLine:v,startChar:w,endChar:C}]of h){if(v<1||v>u.lines||!n(g))continue;const T=(C??0)-(w??0),F=f.get(v);(!F||T>F.width)&&f.set(v,{id:g,width:T})}const p=Array.from(f.entries()).sort((g,v)=>g[0]-v[0]).map(([g,{id:v}])=>new s(v).range(u.line(g).from));return e.RangeSet.of(p,!0)}return a.map(l.changes)}}),c=o.gutter({class:"morphic-grip-gutter",markers(a){return a.state.field(r)},initialSpacer:()=>new s("")});return[r,c]}buildDropIndicatorExtensions(o,e){const t=e.StateEffect.define();this.dropIndicatorEffect=t;const n=e.StateField.define({create(){return o.Decoration.none},update(r,c){for(const a of c.effects)if(a.is(t)){const l=a.value;if(!l)return o.Decoration.none;const d=c.state.doc,h=Math.max(1,Math.min(l.line,d.lines)),u=d.line(h),f=l.position==="above"?"morphic-drop-indicator-above":"morphic-drop-indicator-below",p=o.Decoration.line({class:f});return o.Decoration.set([p.range(u.from)])}return c.changes.empty?r:o.Decoration.none},provide(r){return o.EditorView.decorations.from(r)}}),s=o.EditorView.baseTheme({".morphic-drop-indicator-above":{boxShadow:"inset 0 2px 0 0 #5a86bc"},".morphic-drop-indicator-below":{boxShadow:"inset 0 -2px 0 0 #5a86bc"}});return[n,s]}buildValueSlotHighlightExtensions(o,e){const t=e.StateEffect.define();this.valueSlotHighlightEffect=t;const n=o.Decoration.mark({class:"morphic-value-slot-target"}),s=e.StateField.define({create(){return o.Decoration.none},update(c,a){for(const l of a.effects)if(l.is(t)){const d=l.value;if(!d)return o.Decoration.none;const h=a.state.doc.length,u=Math.max(0,Math.min(d.from,h)),f=Math.max(u,Math.min(d.to,h));return u===f?o.Decoration.none:o.Decoration.set([n.range(u,f)])}return a.changes.empty?c:o.Decoration.none},provide(c){return o.EditorView.decorations.from(c)}}),r=o.EditorView.baseTheme({".morphic-value-slot-target":{outline:"1px solid #5a86bc",outlineOffset:"1px",borderRadius:"2px"}});return[s,r]}buildGroupExtensions(o,e){const t=e.StateEffect.define(),n=e.StateEffect.define();this.groupsEffect=t;class s extends o.GutterMarker{constructor(f){super(),this.elementClass=f}eq(f){return f.elementClass===this.elementClass}}const r=e.StateField.define({create:()=>({groups:[],hover:null}),update(u,f){let p=u;for(const g of f.effects)g.is(t)&&(p={groups:g.value,hover:null}),g.is(n)&&(p={...p,hover:g.value});return p}}),c=u=>{const{groups:f,hover:p}=u.field(r),g=new Map;return f.forEach(({startLine:v,endLine:w},C)=>{for(let T=v;T<=Math.min(w,u.doc.lines);T++){const F=[C%2===0?"morphic-group-odd":"morphic-group-even"];T===v&&F.push("morphic-group-start"),T===w&&F.push("morphic-group-end"),w>v&&F.push("morphic-group-line"),C===p&&F.push("morphic-group-hover"),g.set(T,F.join(" "))}}),g},a=o.EditorView.decorations.compute([r,"doc"],u=>{const f=[...c(u)].map(([p,g])=>o.Decoration.line({class:g}).range(u.doc.line(p).from));return o.Decoration.set(f)}),l=o.gutterLineClass.compute([r,"doc"],u=>e.RangeSet.of([...c(u)].map(([f,p])=>new s(p).range(u.doc.line(f).from)))),d=(u,f)=>{const p=u.posAtCoords({x:f.clientX,y:f.clientY},!1),g=u.state.doc.lineAt(p).number,v=u.state.field(r).groups.findIndex(w=>g>=w.startLine&&g<=w.endLine);return v===-1?null:v},h=o.EditorView.domEventHandlers({mousemove(u,f){const p=d(f,u);p!==f.state.field(r).hover&&f.dispatch({effects:n.of(p)})},mouseleave(u,f){f.state.field(r).hover!==null&&f.dispatch({effects:n.of(null)})}});return[r,a,l,h]}buildHoverHighlightExtensions(o,e){const t=e.StateEffect.define();this.hoverHighlightEffect=t;const n=o.Decoration.mark({class:"morphic-hover-target"}),s=e.StateField.define({create(){return o.Decoration.none},update(c,a){for(const l of a.effects)if(l.is(t)){const d=l.value;if(!d)return o.Decoration.none;const h=a.state.doc.length,u=Math.max(0,Math.min(d.from,h)),f=Math.max(u,Math.min(d.to,h));return u===f?o.Decoration.none:o.Decoration.set([n.range(u,f)])}return a.changes.empty?c:o.Decoration.none},provide(c){return o.EditorView.decorations.from(c)}}),r=o.EditorView.baseTheme({".morphic-hover-target":{backgroundColor:"rgba(127, 127, 127, 0.10)",borderRadius:"2px"}});return[s,r]}setHoverHighlight(o){!this.editorView||!this.hoverHighlightEffect||this.editorView.dispatch({effects:this.hoverHighlightEffect.of(o)})}buildEditableHoverHighlightExtensions(o,e){const t=e.StateEffect.define();this.editableHoverHighlightEffect=t;const n=o.Decoration.mark({class:"morphic-editable-hover"}),s=e.StateField.define({create(){return o.Decoration.none},update(c,a){for(const l of a.effects)if(l.is(t)){const d=l.value;if(!d)return o.Decoration.none;const h=a.state.doc.length,u=Math.max(0,Math.min(d.from,h)),f=Math.max(u,Math.min(d.to,h));return u===f?o.Decoration.none:o.Decoration.set([n.range(u,f)])}return a.changes.empty?c:o.Decoration.none},provide(c){return o.EditorView.decorations.from(c)}}),r=o.EditorView.baseTheme({".morphic-editable-hover":{outline:"1px solid #5a86bc",outlineOffset:"1px",borderRadius:"2px"}});return[s,r]}setEditableHoverHighlight(o){!this.editorView||!this.editableHoverHighlightEffect||this.editorView.dispatch({effects:this.editableHoverHighlightEffect.of(o)})}show(){this.visible||(this.visible=!0,this.container.style.display="",this.syncNow(),this.attachSyncListener())}hide(){this.visible&&(this.visible=!1,this.container.style.display="none",this.detachSyncListener())}isVisible(){return this.visible}highlightLines(o){!this.editorView||!this.highlightEffect||(this.activeHighlight=o,this.editorView.dispatch({effects:this.highlightEffect.of(o)}))}clearHighlight(){!this.editorView||!this.highlightEffect||(this.activeHighlight=void 0,this.editorView.dispatch({effects:this.highlightEffect.of(null)}))}showDropIndicator(o,e="above"){!this.editorView||!this.dropIndicatorEffect||this.editorView.dispatch({effects:this.dropIndicatorEffect.of({line:o,position:e})})}hideDropIndicator(){!this.editorView||!this.dropIndicatorEffect||this.editorView.dispatch({effects:this.dropIndicatorEffect.of(null)})}showValueSlotHighlight(o,e){!this.editorView||!this.valueSlotHighlightEffect||this.editorView.dispatch({effects:this.valueSlotHighlightEffect.of({from:o,to:e})})}hideValueSlotHighlight(){!this.editorView||!this.valueSlotHighlightEffect||this.editorView.dispatch({effects:this.valueSlotHighlightEffect.of(null)})}getLineAtCoords(o,e){if(!this.editorView)return null;const t=this.editorView.posAtCoords({x:o,y:e});return t===null?null:this.editorView.state.doc.lineAt(t).number}charAtCoords(o,e){return this.editorView?this.editorView.posAtCoords({x:o,y:e})??null:null}getLineCount(){var o;return((o=this.editorView)==null?void 0:o.state.doc.lines)??0}isBelowLastLine(o){if(!this.editorView)return!1;const e=this.editorView.state.doc,t=e.line(e.lines).to,n=this.editorView.coordsAtPos(t);return n?o>n.bottom:!1}isInLowerHalfOfLine(o,e){if(!this.editorView)return!1;const t=this.editorView.state.doc;if(o<1||o>t.lines)return!1;const n=t.line(o),s=this.editorView.coordsAtPos(n.from),r=this.editorView.coordsAtPos(n.to);return!s||!r?!1:e>(s.top+r.bottom)/2}setTheme(o){if(!this.editorView||!this.cm||!this.themeCompartment)return;this.themeSelection=o.selectionBackground??qe.selectionBackground,this.activeHighlight&&this.highlightLines(this.activeHighlight);const e=Nt(this.cm.view,o);this.editorView.dispatch({effects:this.themeCompartment.reconfigure(e)})}setHighlightRules(o){if(!this.editorView||!this.cm||!this.syntaxHighlightCompartment)return;const e=So(this.cm.view,this.cm.state,o);this.editorView.dispatch({effects:this.syntaxHighlightCompartment.reconfigure(e)})}dispose(){var o;this.disposed=!0,this.detachSyncListener(),this.syncTimer!==void 0&&(clearTimeout(this.syncTimer),this.syncTimer=void 0),this.emptyClickListener&&this.editorView&&(this.editorView.scrollDOM.removeEventListener("click",this.emptyClickListener),this.emptyClickListener=void 0),(o=this.editorView)==null||o.destroy(),this.editorView=void 0,this.metadata=new Map,this.placeholders=[],this.lastCode=""}refresh(){this.syncNow()}getValue(){var o;return((o=this.editorView)==null?void 0:o.state.doc.toString())??this.lastCode??""}getSelectedLines(){return this.editorView?At(this.editorView.state):null}clearSelection(){const o=this.editorView;if(!o)return;o.dispatch({selection:{anchor:o.state.selection.main.from}});const e=document.getSelection();e!=null&&e.anchorNode&&o.contentDOM.contains(e.anchorNode)&&e.removeAllRanges()}getCursorLine(){if(!this.editorView)return 1;const o=this.editorView.state.selection.main.head;return this.editorView.state.doc.lineAt(o).number}adjustZoom(o){if(!this.editorView||!this.cm||!this.themeCompartment)return;const e=this.options.theme??{},t=parseFloat(e.fontSize??qe.fontSize);o==="fit"?this.zoomFactor=1:o==="in"?this.zoomFactor=Math.min(4,this.zoomFactor*1.2):this.zoomFactor=Math.max(.25,this.zoomFactor/1.2);const n={...e,fontSize:`${(t*this.zoomFactor).toFixed(2)}px`},s=Nt(this.cm.view,n);this.editorView.dispatch({effects:this.themeCompartment.reconfigure(s)})}syncNow(){if(!this.editorView||!this.cm)return;const o=this.generateWithMetadata();if(o.code===this.lastCode)return;this.closePlaceholderEditor(),this.lastCode=o.code,this.metadata=o.metadata,this.placeholders=[...o.placeholders].sort((t,n)=>t.start-n.start);const e=[];this.metadataEffect&&e.push(this.metadataEffect.of(o.metadata)),this.placeholderEffect&&e.push(this.placeholderEffect.of(o.placeholders)),this.repeatEffect&&e.push(this.repeatEffect.of(o.repeats??[])),this.groupsEffect&&e.push(this.groupsEffect.of(o.groups??[])),this.editorView.dispatch({changes:{from:0,to:this.editorView.state.doc.length,insert:o.code},effects:e.length>0?e:void 0})}scheduleDebouncedSync(){this.syncTimer!==void 0&&clearTimeout(this.syncTimer),this.syncTimer=setTimeout(()=>{this.syncTimer=void 0,this.syncNow()},vi)}attachSyncListener(){this.changeListener||(this.changeListener=o=>{yi(o)&&this.scheduleDebouncedSync()},this.workspace.addChangeListener(this.changeListener))}detachSyncListener(){this.changeListener&&(this.workspace.removeChangeListener(this.changeListener),this.changeListener=void 0,this.syncTimer!==void 0&&(clearTimeout(this.syncTimer),this.syncTimer=void 0))}}function Ci(i,o,e,t){const n={behaviors:e,definitions:o};return Io(Fe.javascriptGenerator,n,t,!1),Fe.javascriptGenerator.workspaceToCode(i)}function Si(i,o,e,t){const n={behaviors:e,definitions:o};Io(Fe.javascriptGenerator,n,t,!0);const s=Fe.javascriptGenerator.workspaceToCode(i);return _i(s)}const Ei="// __MORPHIC_BLOCK_START:",xi="// __MORPHIC_BLOCK_END:",$o="__";function Io(i,o,e,t=!1){i.STATEMENT_PREFIX=(e==null?void 0:e.statementPrefix)??null,i.STATEMENT_SUFFIX=(e==null?void 0:e.statementSuffix)??null,i.INFINITE_LOOP_TRAP=(e==null?void 0:e.infiniteLoopTrap)??null,e!=null&&e.reservedWords&&i.addReservedWords(e.reservedWords);for(const[n,s]of o.definitions){const r=Sn(o.behaviors[n]);i.forBlock[Ae(n)]=(c,a)=>{const l=Ti(c,a,s),d=r?r(l):Di(n,s);if(Mi(c,s))return[Ai(d),Fe.Order.NONE];const h=Oi(d);return t?`${Ei}${c.id}${$o}
|
|
9
|
+
${h}${xi}${c.id}${$o}
|
|
10
|
+
`:h}}}function Ti(i,o,e){var f;const t={},n={},s={},r=i.workspace.isFlyout?"toolbox":"workspace",c=Re(e),a=p=>!c.has(p)&&ve(io(e,p)),d=i.inputList.filter(p=>{var g;return((g=p.connection)==null?void 0:g.type)===S.INPUT_VALUE&&!a(p.name)}).length+c.size>=2,h=p=>d&&!a(p);for(const p of i.inputList){const g=(f=p.connection)==null?void 0:f.targetBlock();if(g)if(g.outputConnection){const v=o.valueToCode(i,p.name,Fe.Order.NONE)||"undefined";t[p.name]=h(p.name)?Li(v,g):v}else t[p.name]=o.statementToCode(i,p.name).trimEnd();for(const v of p.fieldRow){if(!v.name||Ye(v))continue;const w=String(v.getValue()??"");n[v.name]=w,s[v.name]=JSON.stringify(w)}}const u={};for(const[p,g]of Re(e))u[p]=oo(i,p,g).map(v=>t[v]).filter(v=>v!==void 0),t[p]=u[p].join(", ");return{blockId:i.id,blockType:he(i.type),element:vo(i)??"default",context:r,inputs:t,fields:n,quoted:s,lists:u}}function Li(i,o){return!Bi(o)||Ii(i)?i:`(${i})`}function Bi(i){return $i(i)>0}function $i(i){return i.inputList.filter(o=>{var e;return((e=o.connection)==null?void 0:e.type)===S.INPUT_VALUE}).length}function Ii(i){if(!i.startsWith("(")||!i.endsWith(")"))return!1;let o=0;for(let e=0;e<i.length;e++){const t=i[e];if(t==="(")o++;else if(t===")"&&(o--,o===0))return e===i.length-1}return!1}function Mi(i,o){return i.outputConnection?!0:o.output===!1?!1:o.output!==void 0}function Oi(i){const o=i.trim();return o?o.endsWith(";")||o.endsWith("}")||o.endsWith(`
|
|
6
11
|
`)?`${o}
|
|
7
12
|
`:`${o};
|
|
8
|
-
`:""}function
|
|
9
|
-
`),e=[],t=new Map,n=new Map;let s=0;for(const r of o){const c=r.match(
|
|
10
|
-
`),metadata:t,placeholders:[]}}function
|
|
13
|
+
`:""}function Ai(i){const o=i.trim();return o?o.endsWith(";")?o.slice(0,-1):o:"undefined"}function Di(i,o){return o.output!==void 0&&o.output!==!1?"undefined":`// No generator behavior defined for "${i}"`}const Ni=/^\s*\/\/ __MORPHIC_BLOCK_START:(.+)__$/,Vi=/^\s*\/\/ __MORPHIC_BLOCK_END:(.+)__$/;function _i(i){const o=i.split(`
|
|
14
|
+
`),e=[],t=new Map,n=new Map;let s=0;for(const r of o){const c=r.match(Ni);if(c){n.set(c[1],s+1);continue}const a=r.match(Vi);if(a){const l=a[1],d=n.get(l);d!==void 0&&(t.set(l,{startLine:d,endLine:s}),n.delete(l));continue}e.push(r),s++}return{code:e.join(`
|
|
15
|
+
`),metadata:t,placeholders:[]}}const Be={rank:40,direction:"none"},Mo={"||":10,or:10,"&&":20,and:20,not:{prefix:30},"==":Be,"!=":Be,"===":Be,"!==":Be,"<":Be,"<=":Be,">":Be,">=":Be,"+":{rank:50,prefix:70},"-":{rank:50,prefix:70},"*":60,"/":60,"%":60,"//":60,"!":{prefix:70},"**":{rank:80,direction:"right"}};function Vt(i,o){if(o===!1)return null;const e=o==null?void 0:o[i];if(e===null)return null;const t=Object.hasOwn(Mo,i)?Mo[i]:void 0;if(e===void 0&&t===void 0)return null;const n=s=>typeof s=="number"?{rank:s}:s??{};return{...n(t),...n(e)}}const He={rank:-1/0,above:!1},ut={rank:1/0,above:!1};function je(i,o,e){return e!==void 0&&e===i.sign?!0:i.above?o>i.rank:o>=i.rank}function Oo(i,o){return i.rank!==o.rank?i.rank>o.rank?i:o:i.above!==o.above?i.above?i:o:i.sign===o.sign?i:{rank:i.rank,above:i.above}}function Ao(i,o,e){if(o.output===void 0||o.output===!1)return null;const t=i.filter(u=>u.kind!=="image"),n=u=>{var f;return(u==null?void 0:u.kind)==="placeholder"?((f=o.inputSlots)==null?void 0:f[String(u.index)])??{}:void 0},s=u=>{const f=n(u);return(u==null?void 0:u.kind)==="placeholder"&&f&&(f.kind??"value")==="value"&&!ve(f)?u.index:null},r=t[0],c=t.at(-1);if(t.length===1){const u=n(r);if((r==null?void 0:r.kind)!=="placeholder"||!u||!ve(u))return null;const f=it(u,e).trim();return f?{kind:"chain",slot:r.index,sign:f}:null}const a=s(c);if(a===null)return null;const l=s(r),d=t.slice(l===null?0:1,-1);if(d.length===0)return null;const h=[];for(const u of d)if(u.kind==="text")h.push({text:u.value});else if(u.kind==="field")h.push({field:u.name});else return null;return l===null?{kind:"prefix",slot:a,sign:h}:l===a?null:{kind:"infix",left:l,right:a,sign:h}}function _t(i,o,e){let t;if(i.kind==="chain")t=i.sign;else{const a=i.sign.map(l=>"text"in l?l.text:o(l.field));if(a.some(l=>l===void 0))return null;t=a.join("").trim().replace(/\s+/g," ")}const n=Vt(t,e);if(!n)return null;if(i.kind==="prefix"){const a=n.prefix;return typeof a!="number"?null:{sign:t,rank:a,bound:()=>({rank:a,above:!1})}}const s=n.rank;if(typeof s!="number")return null;const r=n.direction??"left",c=r==="any"?{sign:t}:{};return i.kind==="chain"?{sign:t,rank:s,bound:()=>({rank:s,above:!0,...c})}:{sign:t,rank:s,bound:a=>a===i.left?{rank:s,above:r==="right"||r==="none"}:{rank:s,above:r!=="right",...c}}}const Fi=/[\p{L}\p{N}_$]$/u,Pi=/(?:[\p{L}\p{N}_$]+|[^\s\p{L}\p{N}_$()[\]{},;"'`]+)$/u,Ri=/^(?:[\p{L}\p{N}_$]+|[^\s\p{L}\p{N}_$()[\]{},;"'`]+)/u;function Do(i,o,e,t){const n=i.filter(l=>l.kind!=="image"),s=n.indexOf(i[o]),r=Vn(i,o,e),c=Hi(n,s,t)??(r.before?He:ut),a=ji(n,s,t)??(r.after?He:ut);return Oo(c,a)}function Hi(i,o,e){var f;const t=i[o-1];if((t==null?void 0:t.kind)!=="text")return null;const n=t.value.replace(/[ \t]+$/,""),s=(f=Pi.exec(n))==null?void 0:f[0],r=s?Vt(s,e):null;if(!s||!r)return null;const c=n.slice(0,n.length-s.length).trimEnd(),a=c===""?o>=2:/[)\]}"'`]$/.test(c),l=Fi.test(c),d=r.direction??"left",h=typeof r.rank=="number"&&(a||l)?{rank:r.rank,above:d!=="right",...d==="any"?{sign:s}:{}}:null,u=typeof r.prefix=="number"&&(!a||l)?{rank:r.prefix,above:!1}:null;return h&&u?Oo(h,u):h??u}function ji(i,o,e){var r;const t=i[o+1];if((t==null?void 0:t.kind)!=="text")return null;const n=(r=Ri.exec(t.value.replace(/^[ \t]+/,"")))==null?void 0:r[0],s=n?Vt(n,e):null;return typeof(s==null?void 0:s.rank)!="number"?null:{rank:s.rank,above:s.direction==="right"||s.direction==="none"}}function Wi(i,o={}){for(const e of i.elements)if(pe(o[e])==="code")return e}function Ze(i,o,e={},t=[]){const n=i.elements,s=t.find(c=>c.name===o);if(s){for(const c of s.elements)if(pe(e[c])==="code"&&n[c]!==void 0)return{mode:o,template:n[c],elementName:c,inputSlots:i.inputSlots}}for(const[c,a]of Object.entries(n))if(pe(e[c])==="code")return{mode:o,template:a,elementName:c,inputSlots:i.inputSlots};if(n.block!==void 0)return{mode:o,template:n.block,elementName:"block",inputSlots:i.inputSlots};const r=Object.entries(n)[0];if(r===void 0)throw new Error(`Block "${i.identifier}" does not have any elements.`);return{mode:o,template:r[1],elementName:r[0],inputSlots:i.inputSlots}}function No(i,o,e={}){const t=i.elements[o];return t!==void 0&&pe(e[o])==="code"?{mode:o,template:t,elementName:o,inputSlots:i.inputSlots}:Ze(i,o,e,[])}function ue(i,o){if(o.length===0)return;if(i.indent===""||!o.includes(`
|
|
11
16
|
`)){i.output+=o;return}const e=o.split(`
|
|
12
17
|
`);i.output+=e[0];for(let t=1;t<e.length;t++)i.output+=`
|
|
13
|
-
`+i.indent+e[t]}function
|
|
14
|
-
`)
|
|
15
|
-
`)
|
|
16
|
-
`)?
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
`)
|
|
20
|
-
`)?Math.max(
|
|
21
|
-
|
|
22
|
-
|
|
18
|
+
`+i.indent+e[t]}function Vo(i,o,e,t,n,s,r={}){const c={output:"",metadata:new Map,placeholders:[],repeats:[],indent:""},a={mode:o,definitions:e,elementTypes:t,modeDefs:n,elementOverride:s,emptyStatements:r.emptyStatements!==!1},l=[],d=()=>c.output.split(`
|
|
19
|
+
`).length;let h=!0;for(const u of i.getTopBlocks(!0)){const f=c.output.length;h||(c.output+=`
|
|
20
|
+
`);const p=d();_o(u,a,c),c.output.length===f+(h?0:1)?c.output=c.output.slice(0,f):(h=!1,l.push({startLine:p,endLine:d()}))}return{code:c.output,metadata:c.metadata,placeholders:c.placeholders,repeats:c.repeats,groups:l}}function _o(i,o,e){const t=1+e.indent.length;let n=i,s=!0;for(;n;){const r=e.output.length;s||ue(e,`
|
|
21
|
+
`),Ft(n,o,e),e.output.length===r+(s?0:t)?e.output=e.output.slice(0,r):s=!1,n=n.getNextBlock()}}function zi(i){return i.inputList.some(o=>{var e;return((e=o.connection)==null?void 0:e.type)===S.INPUT_VALUE})}function Fo(i,o){if(o.elementOverride){const e=i.elements[o.elementOverride];return e===void 0?null:{template:e,elementName:o.elementOverride}}try{const e=Ze(i,o.mode,o.elementTypes,o.modeDefs);return{template:e.template,elementName:e.elementName}}catch{return null}}function Po(i,o,e,t,n){const s=Ao(e,o,t);if(!s)return null;const r=Ro(t?n.elementTypes[t]:void 0);return _t(s,a=>{const l=i.getField(a);return l?pt(o,t,a,l):void 0},r)}function Ro(i){return typeof i=="object"?i.operators:void 0}function Ho(i,o,e){if(je(e,-1/0)||!zi(i))return!1;const t=o.definitions.get(he(i.type));if(!t)return!0;const n=Fo(t,o);if(!n)return!0;if(Ui(n.template)||Gi(n.template))return!1;const s=Po(i,t,we(n.template),n.elementName,o);return!s||!je(e,s.rank,s.sign)}function Ui(i){const o=we(i).map(n=>n.kind==="text"?n.value:n.kind==="image"?"":n.kind==="field"?"name":"").join("").trim();if(!/[)\]}]$/.test(o))return!1;const e={")":"(","]":"[","}":"{"},t=[];for(const n of o)if(n==="("||n==="["||n==="{")t.push(n);else if(n in e){if(t.pop()!==e[n])return!1}else if(t.length===0&&!/[\p{L}\p{N}_$.: "'!]/u.test(n))return!1;return t.length===0}function Gi(i){var s;const o=we(i).filter(r=>r.kind!=="image");if(((s=o[0])==null?void 0:s.kind)!=="placeholder")return!1;const e=o.slice(1).map(r=>r.kind==="text"?r.value:r.kind==="field"?"name":"").join("");if(!/^[.[(]/.test(e))return!1;const t={")":"(","]":"[","}":"{"},n=[];for(const r of e)if(r==="("||r==="["||r==="{")n.push(r);else if(r in t){if(n.pop()!==t[r])return!1}else if(n.length===0&&!/[\p{L}\p{N}_$.]/u.test(r))return!1;return n.length===0}function Ft(i,o,e,t=!1){var F,$,E,M,O;const n=o.definitions.get(he(i.type));if(!n){const A=e.output.length,N=We(e.output);if(Xi(i,e),e.output.length===A)return;const V=We(e.output),m=e.output.endsWith(`
|
|
22
|
+
`)?Math.max(N,V-1):V;let x=e.output.length;for(;x>A&&e.output[x-1]===`
|
|
23
|
+
`;)x--;const B=ft(i);e.metadata.set(i.id,{startLine:N,endLine:m,startChar:A,endChar:x,atomic:!!B}),De(e,A,"set",B??void 0);return}const s=Fo(n,o);if(!s)return;const{template:r,elementName:c}=s,a=c?o.elementTypes[c]:void 0,l=e.output.length;t&&ue(e,"(");const d=e.output.length,h=We(e.output),u={},f=we(r),p=Po(i,n,f,c,o),g=n.output===void 0||n.output===!1;for(const[A,N]of f.entries()){if(N.kind==="text"){ue(e,N.value);continue}if(N.kind==="field"){const B=i.getField(N.name);if(!B)continue;const Q=e.output.length,P=pt(n,c,N.name,B),ie=Ji(B)?uo(zo(f[A-1]),zo(f[A+1])):null;ue(e,ie?fo(P,ie):P);const ce=Pt(Wo(i,B,N.name),i,o);if(ce){De(e,Q,"set",ce);const oe=e.placeholders[e.placeholders.length-1];oe&&oe.start===Q&&B instanceof yt&&B.isMissing()&&(oe.missing=!0)}continue}if(N.kind==="image")continue;if(N.kind==="parentField"){const B=eo(i,N.name),Q=B==null?void 0:B.getSourceBlock(),P=Q?o.definitions.get(he(Q.type)):void 0;B&&ue(e,P?pt(P,c,N.name,B):Qe(B));continue}if(N.kind==="valueType"){ue(e,ao(i,(F=n.inputSlots)==null?void 0:F[String(N.index)],a));continue}const V=($=n.inputSlots)==null?void 0:$[String(N.index)],m=V==null?void 0:V.name;if(!m)continue;if((V==null?void 0:V.kind)==="statement"){const B=((M=(E=i.getInput(m))==null?void 0:E.connection)==null?void 0:M.targetBlock())??null,Q=We(e.output),P=e.indent,ie=e.output.lastIndexOf(`
|
|
24
|
+
`)+1;if(e.indent=((O=/^[ \t]*/.exec(e.output.slice(ie)))==null?void 0:O[0])??"",B)_o(B,o,e);else{const me=o.emptyStatements&&typeof a=="object"?a.emptyStatement:void 0;if(me){const ye=e.output.length;ue(e,me),De(e,ye,"default")}}e.indent=P;const ce=We(e.output),oe=e.output.endsWith(`
|
|
25
|
+
`)?Math.max(Q,ce-1):ce;u[m]={startLine:Q,endLine:oe};continue}if(V&&ve(V)){const B=it(V,c),Q=p?p.bound(N.index):no(B)?ut:He,P=oo(i,m,V);P.forEach((ie,ce)=>{ce>0&&ue(e,B),jo(i,n,V,ie,o,e,c,a,Q)}),e.repeats.push({blockId:i.id,slotName:m,count:P.length,at:e.output.length});continue}const x=p?p.bound(N.index):Do(f,A,g,Ro(a));jo(i,n,V,m,o,e,c,a,x)}if(e.output.length===d){e.output=e.output.slice(0,l);return}t&&ue(e,")");const v=We(e.output),w=e.output.endsWith(`
|
|
26
|
+
`)?Math.max(h,v-1):v;let C=e.output.length;for(;C>l&&e.output[C-1]===`
|
|
27
|
+
`;)C--;const T={startLine:h,endLine:w,startChar:l,endChar:C};Object.keys(u).length>0&&(T.statementSlots=u),ft(i)&&(T.atomic=!0),e.metadata.set(i.id,T)}function jo(i,o,e,t,n,s,r,c,a){var p;const l=i.getInput(t),d=((p=l==null?void 0:l.connection)==null?void 0:p.targetBlock())??null,h=d!=null&&d.isShadow()?null:d;let u=!1;if(!h&&d&&n.definitions.has(he(d.type))){const g=s.output.length,v=s.placeholders.length;Ft(d,n,s,Ho(d,n,a));for(const w of d.getDescendants(!1))s.metadata.delete(w.id);if(s.output.length>g){const w=s.placeholders.splice(v);for(const C of w)s.placeholders.push({...C,kind:"default"});w.length===0&&De(s,g,"default");return}}if(!h){const g=d!=null&&d.isShadow()?d.inputList.flatMap($=>$.fieldRow).filter($=>!!$.name):[],v=!(d!=null&&d.isShadow())&&l?l.fieldRow.filter($=>{var E;return!!$.name&&!((E=o.fields)!=null&&E[$.name])&&!Ye($)}):[],w=g.length>0||v.length>0,C=w?Yi(e,c):void 0;C&&ue(s,C);const T=s.output.length;if(g.length>0){const $=d?n.definitions.get(he(d.type)):void 0;for(const E of g){const M=$&&E.name?pt($,r,E.name,E):Qe(E);ue(s,C?fo(M,C):M)}}else if(v.length>0)for(const $ of v){const E=s.output.length;ue(s,Qe($));const M=Wo(i,$,$.name);M&&(De(s,E,"set",M),u=!0)}let F;if(w||(ue(s,Ki(e==null?void 0:e.check)),F={parentBlockId:i.id,inputName:t}),!u){const $=d!=null&&d.isShadow()?Pt(ft(d),d,n)??void 0:void 0;De(s,T,"default",$,F)}C&&ue(s,C);return}const f=s.output.length;Ft(h,n,s,Ho(h,n,a)),De(s,f,"set",Pt(ft(h),h,n)??void 0)}function Xi(i,o){for(const e of i.inputList)for(const t of e.fieldRow)t.name&&ue(o,Qe(t))}function De(i,o,e,t,n){const s=i.output.length;if(s>o){const r={start:o,end:s,kind:e};t&&(r.edit=t),n&&(r.emptySlot=n),i.placeholders.push(r)}}function Ki(i){const o=Array.isArray(i)?i[0]:i;return o?`[${{Number:"NUMBER",String:"TEXT",Boolean:"BOOL"}[o]??o.toUpperCase()}]`:"[VALUE]"}function Yi(i,o){if(!(!(i!=null&&i.check)||(Array.isArray(i.check)?i.check[0]:i.check)!=="String")&&!(!o||typeof o=="string"))return o.stringQuote}function Wo(i,o,e){let t,n;if(o instanceof S.FieldNumber)t="number";else if(o instanceof S.FieldDropdown){t="dropdown";const s=o.getOptions();Array.isArray(s)&&(n=s.filter(r=>Array.isArray(r)&&r.length>=2).map(([r,c])=>[typeof r=="string"?r:String(c),String(c)]))}else if(o instanceof S.FieldTextInput)t="text";else return null;return{blockId:i.id,fieldName:e,fieldType:t,options:n}}function Pt(i,o,e){var c;if(!(i!=null&&i.options))return i;const t=e.definitions.get(he(o.type)),n=(c=t==null?void 0:t.fields)==null?void 0:c[i.fieldName];if(!t||(n==null?void 0:n.type)!=="dropdown")return i;let s=e.elementOverride;if(!s)try{s=Ze(t,e.mode,e.elementTypes,e.modeDefs).elementName}catch{return i}const r=a=>{var l;for(const d of n.options)if(typeof d=="object"&&!Array.isArray(d)&&d.value===a)return(s&&((l=d.display)==null?void 0:l[s]))??a;return a};return{...i,options:i.options.map(([,a])=>[r(a),a])}}function ft(i){let o=null,e=null,t=0;for(const c of i.inputList){if(c.connection&&c.connection.type===S.INPUT_VALUE)return null;for(const a of c.fieldRow)a.name&&(t++,o=a.name,e=a)}if(t!==1||!o||!e)return null;const n=e.constructor.name;let s="text",r;if(n.includes("Number"))s="number";else if(n.includes("Dropdown")){s="dropdown";const c=e.getOptions;if(typeof c=="function"){const a=c.call(e);Array.isArray(a)&&(r=a.filter(l=>Array.isArray(l)&&l.length>=2).map(([l,d])=>[typeof l=="string"?l:String(d),String(d)]))}}return{blockId:i.id,fieldName:o,fieldType:s,options:r}}function pt(i,o,e,t){var s,r;const n=(s=i.fields)==null?void 0:s[e];if((n==null?void 0:n.type)==="dropdown"&&o){const c=String(t.getValue());for(const a of n.options)if(!(typeof a!="object"||Array.isArray(a))&&a.value===c)return((r=a.display)==null?void 0:r[o])??c}return Qe(t)}function Ji(i){return i instanceof S.FieldTextInput&&!(i instanceof S.FieldNumber)}function zo(i){return(i==null?void 0:i.kind)==="text"?i.value:void 0}function Qe(i){if(!i)return"";if(i instanceof S.FieldDropdown)return String(i.getValue());const o=i.getText;return typeof o=="function"?o.call(i):String(i.getValue())}function We(i){let o=1;for(let e=0;e<i.length;e++)i[e]===`
|
|
28
|
+
`&&o++;return o}class qi{constructor(o,e,t={}){y(this,"workspace");y(this,"editors");y(this,"blockToCode");y(this,"codeToBlock");y(this,"blockListener");y(this,"cursorCallbacks",new Map);y(this,"emptyClickCallbacks",new Map);y(this,"guard",!1);this.workspace=o,this.editors=Array.isArray(e)?[...e]:[e],this.blockToCode=t.blockToCode!==!1,this.codeToBlock=t.codeToBlock!==!1}enable(){this.blockToCode&&this.attachBlockListener(),this.codeToBlock&&this.attachCursorListeners()}disable(){this.detachBlockListener(),this.detachCursorListeners();for(const o of this.editors)o.clearHighlight()}attachBlockListener(){this.blockListener||(this.blockListener=o=>{if(o.type!=="selected"||this.guard)return;const e=o.newElementId??void 0;this.guard=!0,this.broadcastHighlight(e),this.guard=!1},this.workspace.addChangeListener(this.blockListener))}detachBlockListener(){this.blockListener&&(this.workspace.removeChangeListener(this.blockListener),this.blockListener=void 0)}broadcastHighlight(o){for(const e of this.editors){if(!o){e.clearHighlight();continue}const t=this.computeOwnSpans(o,e.metadata);t?e.highlightLines(t):e.clearHighlight()}}attachCursorListeners(){for(const o of this.editors){if(!this.cursorCallbacks.has(o)){const e=t=>{if(this.guard)return;const n=this.findBlockAtLine(t,o.metadata);if(!n){this.clearAll();return}const s=this.workspace.getBlockById(n);s&&S.common.getSelected()!==s&&(this.guard=!0,S.common.setSelected(s),this.broadcastHighlight(n),this.guard=!1)};this.cursorCallbacks.set(o,e),o.onCursorLine=e}if(!this.emptyClickCallbacks.has(o)){const e=()=>{this.guard||this.clearAll()};this.emptyClickCallbacks.set(o,e),o.onEmptyClick=e}}}detachCursorListeners(){for(const[o,e]of this.cursorCallbacks)o.onCursorLine===e&&(o.onCursorLine=void 0);this.cursorCallbacks.clear();for(const[o,e]of this.emptyClickCallbacks)o.onEmptyClick===e&&(o.onEmptyClick=void 0);this.emptyClickCallbacks.clear()}clearAll(){this.guard=!0,S.common.setSelected(null);for(const o of this.editors)o.clearHighlight();this.guard=!1}computeOwnSpans(o,e){const t=e.get(o);if(!t)return;const n=[];for(const[c,a]of e)c!==o&&a.startLine>=t.startLine&&a.endLine<=t.endLine&&n.push(a);if(n.length===0)return[{fromLine:t.startLine,toLine:t.endLine}];n.sort((c,a)=>c.startLine-a.startLine);const s=[];let r=t.startLine;for(const c of n)r<c.startLine&&s.push({fromLine:r,toLine:c.startLine-1}),r=Math.max(r,c.endLine+1);return r<=t.endLine&&s.push({fromLine:r,toLine:t.endLine}),s.length>0?s:void 0}findBlockAtLine(o,e){let t;for(const[n,s]of e)if(o>=s.startLine&&o<=s.endLine){const r=s.endLine-s.startLine;(!t||r<t.size)&&(t={id:n,size:r})}return t==null?void 0:t.id}}const Uo={statement:{above:!0,below:!0},start:{above:!1,below:!0},end:{above:!0,below:!1},standalone:{above:!1,below:!1}},Go=Object.keys(Uo);function Xo(i){return i.map(o=>{const e=o.shape?Uo[o.shape]:void 0;if(!e)return o;const t={...o};return e.above&&t.previousStatement===void 0&&(t.previousStatement=!0),e.below&&t.nextStatement===void 0&&(t.nextStatement=!0),t})}const mt="default";function Ko(i,o){const e=Object.keys(o).filter(t=>pe(o[t])==="code");return i.map(t=>{var a;const n=(a=t.elements)==null?void 0:a[mt];if(n===void 0||e.length===0)return t;const{[mt]:s,...r}=t.elements,c={...r};for(const l of e)c[l]===void 0&&(c[l]=n);return{...t,elements:c}})}function Yo(i){const o=new Map,e=Array.isArray(i)?i:[i];for(const t of e)Zi(t,o),o.set(t.identifier,t);return o}function Zi(i,o){if(!i.identifier.trim())throw new Error("Each block definition must include a non-empty identifier.");if(Object.keys(i.elements).length===0)throw new Error(`Block "${i.identifier}" must define at least one element.`);if(o.has(i.identifier))throw new Error(`Duplicate block identifier "${i.identifier}".`)}const Qi=4/3,es={normal:"400",bold:"700"},Jo=i=>es[i]??i;function ts(i){const o=parseFloat(i);if(!Number.isFinite(o)||o<=0)return;const e=i.trim().endsWith("pt")?o:o/Qi;return Math.round(e*100)/100}function qo(i){const o=i.getRenderer().getConstants();return{family:o.FIELD_TEXT_FONTFAMILY,size:o.FIELD_TEXT_FONTSIZE,weight:Jo(o.FIELD_TEXT_FONTWEIGHT)}}function Zo(i,o,e){const t=document.createElement("div");t.setAttribute("aria-hidden","true"),t.style.cssText="position:absolute;visibility:hidden;width:0;height:0;overflow:hidden;";let n=t;for(const l of o){const d=document.createElement("div");d.className=l.join(" "),n.appendChild(d),n=d}const s=document.createElementNS("http://www.w3.org/2000/svg","svg"),r=document.createElementNS("http://www.w3.org/2000/svg","text");r.setAttribute("class","blocklyText"),s.appendChild(r),n.appendChild(s),i.appendChild(t);const c=getComputedStyle(r),a={family:c.fontFamily||e.family,size:ts(c.fontSize)??e.size,weight:c.fontWeight?Jo(c.fontWeight):e.weight};return t.remove(),a}const os=(i,o)=>i.family===o.family&&i.size===o.size&&i.weight===o.weight,Rt=new Map;function ns(i,o){const e=`${i.name}
|
|
23
29
|
${o.family}
|
|
24
30
|
${o.size}
|
|
25
|
-
${o.weight}`;let t=Ae.get(e);if(!t){const n=`${i.name}-morphic-font-${Ae.size+1}`;t=x.Theme.defineTheme(n,{name:n,base:i,fontStyle:{family:o.family,size:o.size,weight:o.weight},...i.startHats!==void 0&&{startHats:i.startHats}}),Ae.set(e,t)}return t}function rt(i,o,e,t){const n=$o(t,e)?o:No(o,t);return i.getTheme()===n?!1:(i.setTheme(n),!0)}function Oe(i){for(const o of i.getAllBlocks(!1)){o.markDirty();for(const e of o.inputList)for(const t of e.fieldRow)t.getConstants()}i.render()}function ct(i){var g,y,C,E;const{definitions:o,elementTypes:e,behaviors:t,modes:n,presets:s,code:r,categories:c}=i,a=[],d=[],l=new Set(Object.keys(e)),h=new Set(Object.keys(e).filter(f=>j(e[f])==="code")),u=new Set((c??[]).map(f=>f.name));l.has(ye)&&a.push(`elementTypes declares "${ye}", which is reserved for a block's fallback template. Rename the element.`);const k=f=>o.has(f)||x.Blocks[f]!==void 0;for(const f of o.values()){const p=f.identifier;if(f.shape!==void 0)if(!ot.includes(f.shape))a.push(`Block "${p}": unknown shape "${f.shape}". Use one of: ${ot.join(", ")}.`);else{const L=H=>H!==void 0&&H!==!1,I=[];L(f.output)&&I.push("it also has an output, which makes it a value block"),(f.shape==="start"||f.shape==="standalone")&&L(f.previousStatement)&&I.push("it also connects above (previousStatement)"),(f.shape==="end"||f.shape==="standalone")&&L(f.nextStatement)&&I.push("it also connects below (nextStatement)"),f.shape==="statement"&&(f.previousStatement===!1||f.nextStatement===!1)&&I.push("a connection flag is set to false");for(const H of I)d.push(`Block "${p}": shape "${f.shape}" contradicts its flags: ${H}. The flags win.`)}const S=ce(t[p]),T=!!(S!=null&&S.onViewApplied);for(const L of Object.keys(f.elements))l.has(L)||d.push(`Block "${p}": element "${L}" is not declared in elementTypes — it renders with no known type.`);const M=new Map,B=new Set,D=new Set;for(const[L,I]of Object.entries(f.elements)){if(!h.has(L))continue;const H=new Set;for(const F of ee(I))F.kind==="placeholder"?(H.add(F.index),B.add(F.index)):F.kind==="field"&&D.add(F.name);M.set(L,H)}const P=[...M.entries()];if(P.length>1){const[L,I]=P[0];for(const[H,F]of P.slice(1))Ho(I,F)||a.push(`Block "${p}": code elements "${L}" and "${H}" use different placeholders (${ht(I)} vs ${ht(F)}). All code elements must share the same %N set, or an input disappears when switching to the differing mode.`)}const $=new Set(Object.keys(f.inputSlots??{}).map(L=>Number(L)).filter(L=>Number.isInteger(L)));for(const L of B)(g=f.inputSlots)!=null&&g[String(L)]||d.push(`Block "${p}": placeholder %${L} has no inputSlots["${L}"] entry — the input is auto-named ARG${L} and can't be read by name in behaviors.`);for(const L of $)B.has(L)||d.push(`Block "${p}": inputSlots["${L}"] has no matching %${L} placeholder in any code element — the config is ignored.`);const O=new Set(Object.keys(f.fields??{}));for(const L of D)!((y=f.fields)!=null&&y[L])&&!T&&a.push(`Block "${p}": field token %${L} has no fields["${L}"] entry and the block has no onViewApplied behavior to create it — the field will never appear.`);for(const L of O)D.has(L)||d.push(`Block "${p}": fields["${L}"] has no matching %${L} token in any code element — the config is ignored.`);for(const[L,I]of Object.entries(f.fields??{}))if((I==null?void 0:I.type)==="dropdown"){for(const H of I.options)if(!(typeof H!="object"||Array.isArray(H)||!H.display))for(const F of Object.keys(H.display))h.has(F)||d.push(`Block "${p}": fields["${L}"] option "${H.value}" has display for "${F}", which is not a code element — that entry never applies.`)}f.category!==void 0&&u.size>0&&!u.has(f.category)&&d.push(`Block "${p}": category "${f.category}" is not declared in categories — the block loses its colour and grouping.`);for(const[L,I]of Object.entries(f.inputSlots??{}))(I==null?void 0:I.kind)!==void 0&&!lt.includes(I.kind)&&a.push(`Block "${p}": inputSlots["${L}"] has unknown kind "${I.kind}". Use one of: ${lt.join(", ")}.`);for(const[L,I]of Object.entries(f.fields??{}))dt.includes(I==null?void 0:I.type)||a.push(`Block "${p}": fields["${L}"] has unknown type "${I==null?void 0:I.type}". Use one of: ${dt.join(", ")}.`);for(const[L,I]of Object.entries(f.inputSlots??{}))b((C=I==null?void 0:I.default)==null?void 0:C.shadow,`Block "${p}": inputSlots["${L}"].default.shadow`),b((E=I==null?void 0:I.default)==null?void 0:E.placeholder,`Block "${p}": inputSlots["${L}"].default.placeholder`)}for(const[f,p]of Object.entries(e)){const S=j(p);at.includes(S)||a.push(`elementTypes."${f}": unknown type "${S}". Use one of: ${at.join(", ")}.`)}for(const[f,p]of Object.entries(r??{}))for(const[S,T]of Object.entries(p.empty??{}))b(T.shadow,`code.${f}.empty.${S}.shadow`),b(T.placeholder,`code.${f}.empty.${S}.placeholder`);for(const[f,p]of Object.entries(e)){if(typeof p=="string")continue;const S=p.type;p.size!==void 0&&S!=="image"&&d.push(`elementTypes."${f}": "size" applies only to image elements — ignored for a ${S} element.`);for(const T of["empty","stringQuote"])T in p&&a.push(`elementTypes."${f}": "${T}" moved into the "code" section: "code": { "${f}": { "${T}": … } }.`)}for(const f of n??[])for(const p of f.elements)l.has(p)||d.push(`Mode "${f.name}": element "${p}" is not declared in elementTypes — it renders nothing.`);for(const f of Object.keys(r??{}))h.has(f)||d.push(`code["${f}"] is not a code element — its settings will never apply.`);const v=new Map,w=(f,p)=>{const S=v.get(f)??new Set;S.add(p),v.set(f,S)};for(const f of l)w(f,"element");for(const f of n??[])w(f.name,"mode");for(const f of s??[])w(f.name,"preset");for(const[f,p]of v)p.size>1&&d.push(`Name "${f}" is used as ${[...p].sort().join(" and ")} — reusing a name across element / mode / preset is allowed but confusing; consider distinct names.`);return{errors:a,warnings:d};function b(f,p){!f||k(f)||a.push(`${p}: "${f}" is neither a defined block nor a registered Blockly block type.`)}}const at=["text","code","image"],lt=["value","statement"],dt=["dropdown","text","number","checkbox"];function Ho(i,o){if(i.size!==o.size)return!1;for(const e of i)if(!o.has(e))return!1;return!0}function ht(i){const o=[...i].sort((e,t)=>e-t);return o.length?o.map(e=>`%${e}`).join(" "):"(none)"}function ut(i,o,e=!1){var t;if(!o)return String(i);if(typeof i=="string"){const n=e?(t=o.list)==null?void 0:t.quote:void 0;return n?`${n}${i}${n}`:i}if(typeof i=="boolean")return(i?o.true:o.false)??String(i);if(i===null)return o.null??"null";if(i===void 0)return o.undefined??"undefined";if(typeof i=="number")return Number.isNaN(i)?o.NaN??"NaN":i===1/0?o.Infinity??"Infinity":i===-1/0?o["-Infinity"]??"-Infinity":String(i);if(Array.isArray(i)&&o.list){const{open:n="[",close:s="]",separator:r=", "}=o.list;return`${n}${i.map(c=>ut(c,o,!0)).join(r)}${s}`}return String(i)}class Po{ensureModeVisibilityStyles(o,e){const t=ft(o);if(e){const n=ft(e);for(const s of Array.from(document.head.querySelectorAll("style[data-morphic-source]")))if(s.dataset.morphicSource==="mode-visibility"&&s.textContent===n){s.textContent=t;return}}K("mode-visibility",t)}ensureStyles(o,e){this.ensureStyleBundle(o,"base");for(const t of e)this.ensureStyleBundle(t,`mode:${t.mode}`)}async ensureToolbarStyles(){const o=await Promise.resolve().then(()=>mn);K("toolbar",o.default)}ensureWorkspaceStyles(){K("workspace",[".morphic-workspace-root .blocklyMainBackground {"," stroke: var(--morphic-workspace-border-color, transparent);"," stroke-width: var(--morphic-workspace-border-width, 1px);","}"].join(`
|
|
26
|
-
`)
|
|
27
|
-
`)
|
|
28
|
-
|
|
31
|
+
${o.weight}`;let t=Rt.get(e);if(!t){const n=`${i.name}-morphic-font-${Rt.size+1}`;t=S.Theme.defineTheme(n,{name:n,base:i,fontStyle:{family:o.family,size:o.size,weight:o.weight},...i.startHats!==void 0&&{startHats:i.startHats}}),Rt.set(e,t)}return t}function Qo(i,o,e,t){const n=os(t,e)?o:ns(o,t);return i.getTheme()===n?!1:(i.setTheme(n),!0)}function Ht(i){for(const o of i.getAllBlocks(!1)){o.markDirty();for(const e of o.inputList)for(const t of e.fieldRow)t.getConstants()}i.render()}function jt(i={},o){const e=new Map,t=[],n=[],s=(c,a)=>{for(const l of a)o(l)||t.push(`Block set "${c}": "${l}" is no block in the definitions.`)},r=(c,a)=>{const l=e.get(c);if(l)return l;const d=i[c];if(Array.isArray(d))return s(c,d),e.set(c,d),d;let h=[];d.extends===c||a.includes(d.extends)?t.push(`Block set "${c}": extends "${d.extends}", which extends it again (${[...a,c,d.extends].join(" → ")}).`):i[d.extends]?h=r(d.extends,[...a,c]):t.push(`Block set "${c}": extends "${d.extends}", which is no block set.`);const u=d.add??[],f=d.remove??[];s(c,[...u,...f]);for(const g of f)h.includes(g)||n.push(`Block set "${c}": removes "${g}", which "${d.extends}" does not have.`);const p=[...h.filter(g=>!f.includes(g)),...u.filter(g=>!h.includes(g))];return e.set(c,p),p};for(const c of Object.keys(i))r(c,[]);return{lists:e,errors:t,warnings:n}}function Wt(i){var F,$,E,M,O,A,N,V;const{definitions:o,elementTypes:e,behaviors:t,modes:n,presets:s,code:r,categories:c,views:a,blockSets:l}=i,d=[],h=[],u=new Set(Object.keys(e)),f=new Set(Object.keys(e).filter(m=>pe(e[m])==="code")),p=new Set((c??[]).map(m=>m.name));u.has(mt)&&d.push(`elementTypes declares "${mt}", which is reserved for a block's fallback template. Rename the element.`);const g=m=>o.has(m)||S.Blocks[m]!==void 0;for(const m of o.values()){const x=m.identifier;if(m.shape!==void 0)if(!Go.includes(m.shape))d.push(`Block "${x}": unknown shape "${m.shape}". Use one of: ${Go.join(", ")}.`);else{const H=se=>se!==void 0&&se!==!1,_=[];H(m.output)&&_.push("it also has an output, which makes it a value block"),(m.shape==="start"||m.shape==="standalone")&&H(m.previousStatement)&&_.push("it also connects above (previousStatement)"),(m.shape==="end"||m.shape==="standalone")&&H(m.nextStatement)&&_.push("it also connects below (nextStatement)"),m.shape==="statement"&&(m.previousStatement===!1||m.nextStatement===!1)&&_.push("a connection flag is set to false");for(const se of _)h.push(`Block "${x}": shape "${m.shape}" contradicts its flags: ${se}. The flags win.`)}const B=H=>typeof H=="string"||Array.isArray(H)&&H.length>0;m.strict&&!B(m.previousStatement)&&!B(m.output)&&d.push(`Block "${x}" is strict but has no check. Name its kind in "previousStatement" (or "output"), e.g. "previousStatement": "ClassField".`);const Q=Ge(t[x]),P=!!(Q!=null&&Q.onViewApplied);for(const H of Object.keys(m.elements))u.has(H)||h.push(`Block "${x}": element "${H}" is not declared in elementTypes — it renders with no known type.`);const ie=new Map,ce=new Set,oe=new Set,me=new Map;for(const[H,_]of Object.entries(m.elements)){if(!f.has(H))continue;const se=new Set,te=new Set;for(const ae of we(_))ae.kind==="placeholder"?(se.add(ae.index),ce.add(ae.index)):ae.kind==="field"?oe.add(ae.name):ae.kind==="valueType"&&(te.add(ae.index),ce.add(ae.index));ie.set(H,se),me.set(H,te)}for(const[H,_]of me)for(const se of _){const te=(F=m.inputSlots)==null?void 0:F[String(se)];te!=null&&te.repeat?d.push(`Block "${x}": element "${H}" uses %${se}:type, but %${se} repeats. A slot with several values has no one type.`):(!(($=ie.get(H))!=null&&$.has(se))&&!te||(te==null?void 0:te.kind)==="statement")&&d.push(`Block "${x}": element "${H}" uses %${se}:type, but %${se} is not a value slot in it — the type comes from the value in that slot.`)}const ye=[...ie.entries()];if(ye.length>1){const[H,_]=ye[0];for(const[se,te]of ye.slice(1)){const ae=[..._,...te].filter(be=>{var k;return _.has(be)!==te.has(be)&&!((k=m.inputSlots)!=null&&k[String(be)])});ae.length>0&&d.push(`Block "${x}": code elements "${H}" and "${se}" use different placeholders (${on(_)} vs ${on(te)}). Declare inputSlots["${ae[0]}"], so the block keeps the slot where a template leaves it out, or write %${ae[0]} in every code element.`)}}const Ue=new Set(Object.keys(m.inputSlots??{}).map(H=>Number(H)).filter(H=>Number.isInteger(H)));for(const H of ce)(E=m.inputSlots)!=null&&E[String(H)]||h.push(`Block "${x}": placeholder %${H} has no inputSlots["${H}"] entry — the input is auto-named ARG${H} and can't be read by name in behaviors.`);for(const H of Ue)ce.has(H)||h.push(`Block "${x}": inputSlots["${H}"] has no matching %${H} placeholder in any code element — the config is ignored.`);const tt=new Set(Object.keys(m.fields??{}));for(const H of oe)!((M=m.fields)!=null&&M[H])&&!P&&d.push(`Block "${x}": field token %${H} has no fields["${H}"] entry and the block has no onViewApplied behavior to create it — the field will never appear.`);for(const H of tt)oe.has(H)||h.push(`Block "${x}": fields["${H}"] has no matching %${H} token in any code element — it is never shown.`);for(const[H,_]of Object.entries(m.fields??{}))if((_==null?void 0:_.type)==="dropdown")for(const se of _.options){if(typeof se!="object"||Array.isArray(se))continue;const te=se.label;if(te&&typeof te=="object"&&typeof te.src!="string"&&typeof te.color!="string"&&d.push(`Block "${x}": fields["${H}"] option "${se.value}" has an image label without "src" or "color".`),!!se.display)for(const ae of Object.keys(se.display))f.has(ae)||h.push(`Block "${x}": fields["${H}"] option "${se.value}" has display for "${ae}", which is not a code element — that entry never applies.`)}m.category!==void 0&&p.size>0&&!p.has(m.category)&&h.push(`Block "${x}": category "${m.category}" is not declared in categories — the block loses its colour and grouping.`);for(const[H,_]of Object.entries(m.inputSlots??{})){(_==null?void 0:_.kind)!==void 0&&!en.includes(_.kind)&&d.push(`Block "${x}": inputSlots["${H}"] has unknown kind "${_.kind}". Use one of: ${en.join(", ")}.`),_!=null&&_.repeat&&(_.kind??"value")!=="value"&&d.push(`Block "${x}": inputSlots["${H}"] repeats, but it is a statement slot. Only value slots repeat; a statement slot already holds any number of blocks.`),_!=null&&_.repeat&&!_.name&&d.push(`Block "${x}": inputSlots["${H}"] repeats but has no name. Give it a "name"; its entries are named after it.`);const se=Object.values(m.inputSlots??{}).find(te=>{var ae;return(te==null?void 0:te.repeat)&&te.name&&((ae=_==null?void 0:_.name)==null?void 0:ae.startsWith(`${te.name}_`))&&/^\d+$/.test(_.name.slice(te.name.length+1))});se&&d.push(`Block "${x}": inputSlots["${H}"] is named "${_.name}", which is the name of an entry of the repeating slot "${se.name}". Give it another name.`),_!=null&&_.strict&&(_.check===void 0||_.check.length===0)&&d.push(`Block "${x}": inputSlots["${H}"] is strict but has no check. A strict slot takes only blocks whose check matches its own, so nothing would fit.`)}for(const[H,_]of Object.entries(m.fields??{}))tn.includes(_==null?void 0:_.type)||d.push(`Block "${x}": fields["${H}"] has unknown type "${_==null?void 0:_.type}". Use one of: ${tn.join(", ")}.`);for(const[H,_]of Object.entries(m.fields??{})){if((_==null?void 0:_.type)!=="reference")continue;for(const te of _.scope===void 0?[]:[_.scope].flat())o.has(te)||d.push(`Block "${x}": fields["${H}"] has the scope "${te}", but there is no block "${te}".`);const se=Array.isArray(_.to)?_.to:[_.to];se.length===0&&d.push(`Block "${x}": fields["${H}"] is a reference without "to". Name the field it lists, e.g. "class_define.NAME".`);for(const te of se){const ae=Zt(te),be=`Block "${x}": fields["${H}"] refers to "${te}"`;if(!ae){d.push(`${be}, which is not a block and a field. Write it as "block.FIELD", e.g. "class_define.NAME".`);continue}const k=o.get(ae.block);k?!((O=k.fields)!=null&&O[ae.field])&&!((A=Ge(t[ae.block]))!=null&&A.onViewApplied)&&d.push(`${be}, but block "${ae.block}" has no field "${ae.field}".`):d.push(`${be}, but there is no block "${ae.block}".`)}}for(const[H,_]of Object.entries(m.inputSlots??{}))T((N=_==null?void 0:_.default)==null?void 0:N.shadow,`Block "${x}": inputSlots["${H}"].default.shadow`),T((V=_==null?void 0:_.default)==null?void 0:V.placeholder,`Block "${x}": inputSlots["${H}"].default.placeholder`)}for(const[m,x]of Object.entries(e)){const B=pe(x);zt.includes(B)||d.push(`elementTypes."${m}": unknown type "${B}". Use one of: ${zt.join(", ")}.`)}for(const[m,x]of Object.entries(r??{}))for(const[B,Q]of Object.entries(x.empty??{}))T(Q.shadow,`code.${m}.empty.${B}.shadow`),T(Q.placeholder,`code.${m}.empty.${B}.placeholder`);for(const[m,x]of Object.entries(e)){if(typeof x=="string")continue;const B=x.type;x.size!==void 0&&B!=="image"&&h.push(`elementTypes."${m}": "size" applies only to image elements — ignored for a ${B} element.`);for(const Q of["empty","stringQuote"])Q in x&&d.push(`elementTypes."${m}": "${Q}" moved into the "code" section: "code": { "${m}": { "${Q}": … } }.`)}for(const m of n??[])for(const x of m.elements)u.has(x)||h.push(`Mode "${m.name}": element "${x}" is not declared in elementTypes — it renders nothing.`);for(const m of n??[])for(const[x,B]of Object.entries(m.render??{}))B==="block"||B==="text"?d.push(`Mode "${m.name}": render "${B}" is now "${B}-based" (render.${x}).`):B!=="block-based"&&B!=="text-based"?d.push(`Mode "${m.name}": render.${x} must be "block-based" or "text-based".`):f.has(x)||h.push(`Mode "${m.name}": render.${x} names no code element — it changes nothing.`);for(const m of s??[]){const x=m.toolbox;if(typeof x=="object"&&x!==null){const{mode:B,render:Q}=x,P=Object.keys(Q??{})[0]??"python";d.push(`Preset "${m.name}": the toolbox entry is a mode name since 0.4.0, and its "render" moved into the mode: "toolbox": "${B??"<mode>"}", and on that mode "render": { "${P}": "text-based" }.`)}}const v=jt(l,m=>o.has(m));d.push(...v.errors),h.push(...v.warnings);for(const m of s??[])m.blockSet!==void 0&&!(l!=null&&l[m.blockSet])&&d.push(`Preset "${m.name}": blockSet "${m.blockSet}" is no block set.`);for(const m of Object.keys(r??{}))f.has(m)||h.push(`code["${m}"] is not a code element — its settings will never apply.`);const w=new Map,C=(m,x)=>{const B=w.get(m)??new Set;B.add(x),w.set(m,B)};for(const m of u)C(m,"element");for(const m of n??[])C(m.name,"mode");for(const m of s??[])C(m.name,"preset");for(const m of a??[])C(m,"view");for(const m of c??[])C(m.name,"category");for(const m of Object.keys(l??{}))C(m,"block set");for(const[m,x]of w){x.size>1&&h.push(`Name "${m}" is used as ${[...x].sort().join(" and ")} — reusing a name across element / mode / preset / view / category / block set is allowed but confusing; consider distinct names.`);const B=[...x].filter(P=>P!=="category"&&P!=="block set");B.length>0&&/[^A-Za-z0-9_-]/.test(m)&&h.push(`Name "${m}" (${B.sort().join(", ")}) has characters a CSS class cannot hold; its classes use "${de(m)}".`);const Q=m.toLowerCase();is.includes(Q)&&!(x.size===1&&x.has("category"))&&h.push(`Name "${m}" (${[...x].sort().join(", ")}) is a Morphic Blocks word — name it after what it is in your app (e.g. "python", "icon-tiles", "editor-pane").`)}return{errors:d,warnings:h};function T(m,x){!m||g(m)||d.push(`${x}: "${m}" is neither a defined block nor a registered Blockly block type.`)}}const zt=["text","code","image","custom"],is=["workspace","codespace","preview","toolbox","mode","preset","view","element","block","blocks","blockset","block-set","tile","tiles","category",...zt],en=["value","statement"],tn=["dropdown","reference","text","number","checkbox"];function on(i){const o=[...i].sort((e,t)=>e-t);return o.length?o.map(e=>`%${e}`).join(" "):"(none)"}const ss={workspace:"workspace",codespace:"codespace"};function Ut(i){return Object.fromEntries(Object.entries(i??ss).map(([o,e])=>[o,typeof e=="string"?{kind:e}:e]))}function nn(i){const o=[];for(const[e,t]of Object.entries(i))t.kind==="preview"?o.push(`View "${e}": the preview is a codespace that cannot be edited since 0.4.0: { "kind": "codespace", "editable": false }.`):t.kind!=="workspace"&&t.kind!=="codespace"&&o.push(`View "${e}": unknown kind "${String(t.kind)}". Use "workspace" or "codespace".`);return o}function sn(i){const o=[],e=[],t=new Map((i.modes??[]).map(s=>[s.name,s])),n=new Set;for(const s of i.presets??[]){if(n.has(s.name)){o.push(`Preset "${s.name}" is defined more than once.`);continue}n.add(s.name),t.has(s.toolbox)||o.push(`Preset "${s.name}": unknown mode "${s.toolbox}" for the toolbox.`);const r=Object.entries(s.views??{});r.length===0&&o.push(`Preset "${s.name}": "views" must name at least one view.`);for(const[c,a]of r)i.views[c]||e.push(`Preset "${s.name}" names "${c}", which is no declared view (${Object.keys(i.views).join(", ")}).`),pe(i.elementTypes[a])!=="code"&&o.push(`Preset "${s.name}": view "${c}" shows "${a}", which is no code element.`+(t.has(a)?` Views show elements since 0.4.0, and "${a}" is a mode.`:""))}return{errors:o,warnings:e}}function rn(i,o){const e=[];for(const t of i??[]){const n=["workspace","codespace","preview"].filter(s=>s in t);n.length>0&&e.push(`Preset "${t.name}": ${n.map(s=>`"${s}"`).join(", ")} moved into "views" in 0.4.0, by view name: "views": { ${n.map(s=>`"${s}": "${t[s]}"`).join(", ")} }.`)}return o&&e.push('The top level "highlighting" map moved into the "code" section: "code": { "<element>": { "highlighting": { … } } }.'),e}function rs(i,o={},e={}){const t=i,n=t.elementTypes??{};let s;try{s=Yo(Xo(Ko(t.blocks,n)))}catch(h){return{errors:[h.message],warnings:[]}}const r=Ut(t.views),c=Wt({definitions:s,elementTypes:n,behaviors:o,modes:t.modes,presets:t.presets,code:t.code,categories:t.categories,views:Object.keys(t.views??{}),blockSets:t.blockSets}),a=sn({presets:t.presets,modes:t.modes,views:r,elementTypes:Ct(n,t.code)}),l=[...c.errors,...rn(t.presets,"highlighting"in t),...nn(r),...a.errors],d=[...c.warnings,...a.warnings];if(e.modeStyles){const h=new Set(e.modeStyles),u=(t.modes??[]).map(f=>f.name).filter(f=>!h.has(f));u.length>0&&d.push(`Modes without explicit CSS definition: ${u.join(", ")}.`)}return{errors:l,warnings:d}}function cn(i,o,e=!1){var t;if(!o)return String(i);if(typeof i=="string"){const n=e?(t=o.list)==null?void 0:t.quote:void 0;return n?`${n}${i}${n}`:i}if(typeof i=="boolean")return(i?o.true:o.false)??String(i);if(i===null)return o.null??"null";if(i===void 0)return o.undefined??"undefined";if(typeof i=="number")return Number.isNaN(i)?o.NaN??"NaN":i===1/0?o.Infinity??"Infinity":i===-1/0?o["-Infinity"]??"-Infinity":String(i);if(Array.isArray(i)&&o.list){const{open:n="[",close:s="]",separator:r=", "}=o.list;return`${n}${i.map(c=>cn(c,o,!0)).join(r)}${s}`}return String(i)}const an="Put brackets around the parts of this line: these operators have no order.",$e=/[\p{L}\p{M}\p{N}_$]/u,gt=/[\p{L}_$][\p{L}\p{M}\p{N}_$]*/uy,ln=/-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][-+]?\d+)?/y;function cs(i,o,e,t={}){var te,ae,be;const n=i.replace(/\r\n?/g,`
|
|
32
|
+
`),s=new Set(((te=t.highlighting)==null?void 0:te.keywords)??[]),r=(ae=t.highlighting)==null?void 0:ae.comment,c=Object.values(t.types??{}).sort((k,b)=>b.length-k.length),a=new Set;for(const k of e.values())for(const b of Object.values(k.fields??{}))if(b.type==="reference")for(const L of[b.to].flat())a.add(L);const l=[];for(const k of e.values()){const b=se(k,o);b&&l.push(b)}l.sort((k,b)=>b.weight-k.weight);const d=l.filter(k=>!k.isValue),h=l.filter(k=>k.isValue&&!k.continues),u=l.filter(k=>k.isValue&&k.continues),f=new Set;let p=new Set;const g=[],v=new Map,w=new Map;let C={pos:-1},T={pos:-1,message:""};const F=(k,b)=>{k>C.pos&&(C={pos:k,message:b}),b&&k>=T.pos&&(T={pos:k,message:b})},$=k=>n.slice(0,Math.max(0,k)).split(`
|
|
33
|
+
`).length,E=k=>{for(;n[k]===" "||n[k]===" ";)k++;return k},M=k=>{const b=n.indexOf(`
|
|
34
|
+
`,k);return b===-1?n.length:b},O=k=>{for(;;){const b=M(k);if(b>=n.length||n.slice(k,b).trim()!=="")return n.slice(k,b).trim()===""?n.length:k;k=b+1}},A=k=>{const b=E(k);return b>=n.length||n[b]===`
|
|
35
|
+
`||!!r&&b>k&&n.startsWith(r,b)},N=(k,b)=>{var L;return!k||k.kind==="text"||k.kind==="body"?!1:k.kind!=="field"||((L=k.field)==null?void 0:L.type)!=="dropdown"?!0:hn(k.field.options,o).some(({shown:J})=>$e.test(b==="start"?J[0]??"":J.at(-1)??""))};function V(k,b,L,J,j,W){const U=k.split(`
|
|
36
|
+
`);for(let D=0;D<U.length;D++){const K=U[D];if(D>0){if(!L){if(b=E(b),b<n.length&&n[b]!==`
|
|
37
|
+
`)return null;b=O(Math.min(b+1,n.length)),L=!0}if(K.trim()==="")continue;const ne=/^[ \t]*/.exec(K)[0];if(!n.startsWith(J+ne,b))return null;b+=J.length+ne.length,L=!1;const X=m(K.slice(ne.length),b,void 0,D===U.length-1?W:void 0);if(X===null)return null;b=X;continue}if(K==="")continue;if(L)return null;const z=m(K,b,j,U.length===1?W:void 0);if(z===null)return null;b=z}return{pos:b,lineStart:L}}function m(k,b,L,J){((L==null?void 0:L.kind)==="value"||(L==null?void 0:L.kind)==="repeat")&&/^[^\s\p{L}\p{N}_$]/u.test(k)&&(b=E(b));for(let j=0;j<k.length;){if(k[j]===" "||k[j]===" "){let W=j;for(;k[W]===" "||k[W]===" ";)W++;const U=j===0?N(L,"end"):$e.test(k[j-1]),D=W===k.length?N(J,"start"):$e.test(k[W]),K=b;if(b=E(b),U&&D&&b===K)return null;j=W;continue}if(n[b]!==k[j])return null;b++,j++}return b}function x(k,b,L){var U;const j=k.tokens[b].field;if((j==null?void 0:j.type)==="dropdown")return hn(j.options,o).filter(({shown:D})=>n.startsWith(D,L)&&!($e.test(D.at(-1)??"")&&$e.test(n[L+D.length]??""))).map(({value:D,shown:K})=>({value:D,shown:K,end:L+K.length}));if((j==null?void 0:j.type)==="number"){ln.lastIndex=L;const D=ln.exec(n);return D?[{value:D[0],shown:D[0],end:L+D[0].length}]:[]}if((j==null?void 0:j.type)==="text"){const D=k.tokens[b+1],K=k.tokens[b-1],z=(D==null?void 0:D.kind)==="text"?D.value[0]:void 0,ne=(K==null?void 0:K.kind)==="text"?K.value.at(-1):void 0,X=uo((K==null?void 0:K.kind)==="text"?K.value:void 0,(D==null?void 0:D.kind)==="text"?D.value:void 0);if(X){const I=Fn(n,L,X);return I?[{value:I.value,shown:n.slice(L,I.end),end:I.end}]:[]}if(z&&!$e.test(z)&&z!==" "&&z!==`
|
|
38
|
+
`&&ne&&!$e.test(ne)&&ne!==" "&&z!=="("){const I=n.indexOf(z,L);return I===-1||I>M(L)?[]:[{value:n.slice(L,I),shown:n.slice(L,I),end:I}]}const G=k.tokens[0];if(!D&&!k.isValue&&r&&(G==null?void 0:G.kind)==="text"&&G.value.trim()===r){const I=n.slice(L,M(L)).trimEnd();return[{value:I,shown:I,end:L+I.length}]}}gt.lastIndex=L;const W=(U=gt.exec(n))==null?void 0:U[0];return W&&!s.has(W)?[{value:W,shown:W,end:L+W.length}]:[]}const B=(k,b)=>k.form?_t(k.form,L=>b.shown[L],t.operators):null,Q=(k,b,L)=>{var j;const J=(j=B(k,L))==null?void 0:j.bound(b.number);return J?{rank:J.rank,above:J.above}:b.bound};function*P(k,b,L,J,j,W,U){var X,G;const{tokens:D,def:K}=k;if(b===D.length){yield{pos:L,lineStart:J,taken:U};return}const z=D[b],ne=()=>kt(W,[...Object.values(U.inputs).flatMap(I=>I.declares),...me(K,U.fields)]);if(z.kind==="text"){const I=V(z.value,L,J,j,D[b-1],D[b+1]);I?yield*P(k,b+1,I.pos,I.lineStart,j,W,U):F(L,"");return}if(!J){if(z.kind==="skip"&&!z.types){const I=((X=[...g].reverse().find(R=>z.field in R))==null?void 0:X[z.field])??"";n.startsWith(I,L)&&!(I&&$e.test(n[L+I.length]??""))&&(yield*P(k,b+1,L+I.length,!1,j,W,U));return}if(z.kind==="skip"){const I=c.find(q=>n.startsWith(q,L));gt.lastIndex=L;const R=I?L+I.length:L+(((G=gt.exec(n))==null?void 0:G[0].length)??0),Y=I&&z.slotName?{...U,types:{...U.types,[z.slotName]:I}}:U;R>L&&(yield*P(k,b+1,R,!1,j,W,Y));return}if(z.kind==="field"){for(const I of x(k,b,L)){if(z.name in U.fields&&U.shown[z.name]!==I.shown)continue;const R={...U,fields:{...U.fields,[z.name]:I.value},shown:{...U.shown,[z.name]:I.shown}};yield*P(k,b+1,I.end,!1,j,W,R)}return}if(z.kind==="value"){const I=E(L),R=U.written[z.name];if(R!==void 0){n.startsWith(R,I)&&(yield*P(k,b+1,I+R.length,!1,j,W,U));return}const Y=un(z.slot.check);if(n.startsWith(Y,I)){const q={...U,written:{...U.written,[z.name]:Y}};yield*P(k,b+1,I+Y.length,!1,j,W,q)}for(const q of Ue(I,Q(k,z,U),ne(),z.slot)){const Z={...U,inputs:{...U.inputs,[z.name]:q},written:{...U.written,[z.name]:n.slice(I,q.end)}};yield*P(k,b+1,q.end,!1,j,W,Z)}return}if(z.kind==="repeat"){yield*ie(k,b,z,L,0,j,W,U);return}}}function*ie(k,b,L,J,j,W,U,D){let K=J;if(j>0&&(K=m(L.separator,J,void 0,void 0)),K!==null){K=E(K);const ne=Se(L.name,j),X=un(L.slot.check),G=R=>({...D,inputs:R?{...D.inputs,[ne]:R}:D.inputs,repeat:{...D.repeat,[L.name]:j+1}}),I=kt(U,[...Object.values(D.inputs).flatMap(R=>R.declares),...me(k.def,D.fields)]);for(const R of Ue(K,Q(k,L,D),I,L.slot))yield*ie(k,b,L,R.end,j+1,W,U,G(R));n.startsWith(X,K)&&(yield*ie(k,b,L,K+X.length,j+1,W,U,G(void 0)))}const z={...D,repeat:{...D.repeat,[L.name]:j}};yield*P(k,b+1,J,!1,W,U,z)}function*ce(k,b,L,J,j,W,U){const D=k.tokens.findIndex((ne,X)=>X>=b&&ne.kind==="body");if(D===-1){yield*P(k,b,L,J,j,W,U);return}const K={...k,tokens:k.tokens.slice(0,D)},z=k.tokens[D];for(const ne of P(K,b,L,J,j,W,U)){if(!ne.lineStart)continue;const X=kt(W,[...Object.values(ne.taken.inputs).flatMap(R=>R.declares),...me(k.def,ne.taken.fields)]);g.push(ne.taken.shown);const G=tt(ne.pos,j+z.indent,z.slot,X);g.pop();const I=G.stacks[0]?{...ne.taken.inputs,[z.name]:G.stacks[0]}:ne.taken.inputs;yield*ce(k,D+1,G.pos,!0,j,W,{...ne.taken,inputs:I})}}function oe(k,b,L){var ne,X,G;const{def:J}=k,j=Object.values(b.inputs);let W=j.reduce((I,R)=>I+R.penalty,0);const U={};for(const[I,R]of Object.entries(b.fields)){const Y=(ne=J.fields)==null?void 0:ne[I];if(U[I]=(Y==null?void 0:Y.type)==="number"?Number(R):R,(Y==null?void 0:Y.type)==="reference"){const Z=[Y.to].flat().map(ee=>`${ee}=${R}`);Z.some(ee=>L.has(ee))?W-=Y.scope?.1:0:W+=Z.some(ee=>p.has(ee))?.5:1}const q=`${J.identifier}.${I}=${R}`;a.has(`${J.identifier}.${I}`)&&(L.has(q)&&W++,f.add(q))}const D=[];for(const[I,R]of Object.entries(J.inputSlots??{})){if((R.kind??"value")!=="value")continue;const Y=Ce(R,I);if(!ve(R))D.push(Y);else for(let q=0;q<(b.repeat[Y]??0);q++)D.push(Se(Y,q))}const K={type:Ae(J.identifier)};Object.keys(U).length>0&&(K.fields=U);const z=Object.entries(b.inputs).map(([I,R])=>[I,{block:R.state}]);for(const[I,R]of Object.entries(b.types)){const Y=(X=Object.entries(t.types??{}).find(([ee,fe])=>fe===R&&ee!=="default"))==null?void 0:X[0],q=Y?(G=t.empty)==null?void 0:G[Y]:void 0,Z=(q==null?void 0:q.shadow)??(q==null?void 0:q.placeholder);Z&&e.has(Z)&&!(I in b.inputs)&&z.push([I,{block:{type:Ae(Z),fields:q.fieldValues??{}}}])}return z.length>0&&(K.inputs=Object.fromEntries(z)),K.extraState={...Object.keys(b.repeat).length>0?{repeat:b.repeat}:{},defaults:D},{state:K,def:J,penalty:W,declares:me(J,b.fields),count:1+j.reduce((I,R)=>I+R.count,0)}}function me(k,b){return Object.entries(b).filter(([L])=>a.has(`${k.identifier}.${L}`)).map(([L,J])=>`${k.identifier}.${L}=${J}`)}const ye={fields:{},shown:{},inputs:{},repeat:{},types:{},written:{}};function Ue(k,b,L,J){var ne;const j=E(k),W=`${j}|${b.rank}${b.above?">":""}${b.sign??""}|${dn(J)}|${g.length}:${JSON.stringify(g.at(-1)??{})}|${L.key}`,U=v.get(W);if(U)return U;const D=[];if(n[j]==="(")for(const X of Ue(j+1,He,L)){const G=E(X.end);n[G]===")"&&D.push({...X,end:G+1,rank:1/0,open:void 0})}for(const X of h)for(const G of P(X,0,j,!1,"",L,ye)){if(G.lineStart)continue;const I=((ne=B(X,G.taken))==null?void 0:ne.rank)??1/0;je(b,I)&&D.push({...oe(X,G.taken,L),end:G.pos,rank:I})}for(let X=0;X<D.length;X++){const G=D[X];for(const I of u){if(I.tight?G.rank!==1/0:b.rank===1/0)continue;const R=I.tokens[0];if(!fn(R.slot,G.def))continue;const Y=R.kind==="repeat"?{...ye,inputs:{[Se(R.name,0)]:G},repeat:{[R.name]:1}}:{...ye,inputs:{[R.name]:G}},q=R.kind==="repeat"?ie(I,0,R,G.end,1,"",L,Y):P(I,1,G.end,!1,"",L,Y);for(const Z of q){if(Z.lineStart||Z.pos===G.end)continue;let ee;const fe=I.tight?null:B(I,Z.taken);if(I.tight)ee={...oe(I,Z.taken,L),end:Z.pos,rank:1/0};else if(fe){if(!je(b,fe.rank,fe.sign))continue;if(!je(fe.bound(R.number),G.rank)){(G.rank===fe.rank||G.rank===-1/0)&&F(G.end,an);continue}ee={...oe(I,Z.taken,L),end:Z.pos,rank:fe.rank}}else{if(!je(b,-1/0))continue;const xe=`${I.def.identifier}|${JSON.stringify(Z.taken.fields)}`;if(G.rank!==1/0&&G.open!==xe){F(G.end,an);continue}ee={...oe(I,Z.taken,L),end:Z.pos,rank:-1/0,open:xe}}D.some(xe=>xe.end===ee.end&&xe.def===ee.def&&xe.penalty<=ee.penalty)||D.push(ee)}}}const K=new Map;for(const X of D){if(J&&!fn(J,X.def))continue;const G=K.get(X.end);(!G||X.penalty<G.penalty)&&K.set(X.end,X)}const z=[...K.values()].sort((X,G)=>G.end-X.end);return v.set(W,z),z}function tt(k,b,L,J){const j=`${k}|${b}|${dn(L)}|${g.length}:${JSON.stringify(g.at(-1)??{})}|${J.key}`,W=w.get(j);if(W)return W;const U=[];let D;const K=[];for(;k=O(k),!(k>=n.length);){const ne=/^[ \t]*/.exec(n.slice(k,M(k)))[0];if(ne!==b){(ne.length>b.length||!b.startsWith(ne))&&F(k,"The line is indented differently from the lines around it.");break}const X=k+b.length;if(L&&U.length===0&&t.emptyStatement&&n.slice(X,M(X)).trim()===t.emptyStatement){const Z=O(Math.min(M(X)+1,n.length));if(Z>=n.length||/^[ \t]*/.exec(n.slice(Z,M(Z)))[0]!==b){k=Z;break}}const G=kt(J,K),I=D==null?void 0:D.read.def;let R;const Y=(Z,ee,fe)=>{if(!fe&&!A(ee))return;const Kt=I?ls(I,Z.def,L):L?as(L,Z.def):!1;if(L&&!Kt)return;const xe=Z.penalty+(!L&&Z.def.strict?100:0);(!R||xe<R.score)&&(R={read:Z,pos:fe?ee:Math.min(M(ee)+1,n.length),joins:Kt,score:xe})};for(const Z of d)for(const ee of ce(Z,0,X,!1,b,G,ye))Y(oe(Z,ee.taken,G),ee.pos,ee.lineStart);if(!R&&!L)for(const Z of Ue(X,He,G))Y(Z,Z.end,!1);if(!R){F(X,`No block writes "${n.slice(X,M(X)).trim()}".`);break}const q=R;if(q.joins&&D){D.state.next={block:q.read.state};const Z=U[U.length-1];Z.penalty+=q.read.penalty,Z.count+=q.read.count,Z.declares.push(...q.read.declares)}else U.push({...q.read,declares:[...q.read.declares]});D={read:q.read,state:q.read.state},K.push(...q.read.declares),k=q.pos}const z={stacks:U,pos:k};return w.set(j,z),z}const H={has:()=>!1,key:""};tt(0,"",null,H),p=new Set(f),v.clear(),w.clear(),C={pos:-1,message:""},T={pos:-1,message:""};const _=tt(0,"",null,H);if(O(_.pos)<n.length){const k=$(Math.max(C.pos,_.pos)),b=((be=n.split(`
|
|
39
|
+
`)[k-1])==null?void 0:be.trim())??"";return{ok:!1,line:k,message:$(T.pos)===k?T.message:`No block writes "${b}".`}}return{ok:!0,stacks:_.stacks.map(k=>k.state),blocks:_.stacks.reduce((k,b)=>k+b.count,0)};function se(k,b){var X,G,I;const L=k.elements[b];if(L===void 0)return null;const J=we(L).filter(R=>R.kind!=="image"),j=k.output!==void 0&&k.output!==!1,W=[];for(let R=0;R<J.length;R++){const Y=J[R];if(Y.kind==="text")W.push({kind:"text",value:Y.value});else if(Y.kind==="field")W.push({kind:"field",name:Y.name,field:(X=k.fields)==null?void 0:X[Y.name]});else if(Y.kind==="valueType")W.push({kind:"skip",types:!0,slotName:Ce((G=k.inputSlots)==null?void 0:G[String(Y.index)],Y.index)});else if(Y.kind==="parentField")W.push({kind:"skip",types:!1,field:Y.name});else if(Y.kind==="placeholder"){const q=((I=k.inputSlots)==null?void 0:I[String(Y.index)])??{},Z=Ce(q,Y.index);if(q.kind==="statement"){const ee=W[W.length-1],fe=(ee==null?void 0:ee.kind)==="text"?/\n([ \t]*)$/.exec(ee.value):null;if(!fe||(ee==null?void 0:ee.kind)!=="text")return null;ee.value=ee.value.slice(0,ee.value.length-fe[1].length),W.push({kind:"body",name:Z,slot:q,indent:fe[1]});continue}if(ve(q)){const ee=it(q,b);W.push({kind:"repeat",name:Z,number:Y.index,slot:q,separator:ee,bound:no(ee)?ut:He})}else W.push({kind:"value",name:Z,number:Y.index,slot:q,bound:Do(J,R,!j,t.operators)})}}if(W.length===0)return null;const U=W[0],D=W[1],K=j&&(U.kind==="value"||U.kind==="repeat"),z=Ao(J,k,b),ne=(z==null?void 0:z.kind)==="infix"&&z.sign.every(R=>"text"in R)&&_t(z,()=>{},t.operators);return{def:k,tokens:W,isValue:j,continues:K,form:z,tight:K&&!ne&&(D==null?void 0:D.kind)==="text"&&D.value[0]!==" "&&D.value[0]!==" ",weight:W.reduce((R,Y)=>R+(Y.kind==="text"?Y.value.replace(/\s/g,"").length:0),0)}}}function kt(i,o){if(o.length===0)return i;const e=new Set(o);return{has:t=>e.has(t)||i.has(t),key:`${i.key}|${[...e].sort().join(",")}`}}function dn(i){return i?`${JSON.stringify(i.check??null)}${i.strict?"!":""}`:"-"}function hn(i,o){return i.map(e=>{var t;return typeof e=="string"?{value:e,shown:e}:Array.isArray(e)?{value:e[0],shown:e[0]}:{value:e.value,shown:((t=e.display)==null?void 0:t[o])??e.value}}).sort((e,t)=>t.shown.length-e.shown.length)}function un(i){const o=Array.isArray(i)?i[0]:i;return o?`[${{Number:"NUMBER",String:"TEXT",Boolean:"BOOL"}[o]??o.toUpperCase()}]`:"[VALUE]"}const Ie=i=>typeof i=="string"?[i]:Array.isArray(i)?i:null,Gt=(i,o)=>!i||!o||i.some(e=>o.includes(e)),vt=(i,o)=>!!i&&!!o&&i.some(e=>o.includes(e));function fn(i,o){if(o.output===void 0||o.output===!1)return!1;const e=Ie(i.check),t=Ie(o.output);return i.strict||o.strict?vt(e,t):Gt(e,t)}function as(i,o){if(!o.previousStatement)return!1;const e=Ie(i.check),t=Ie(o.previousStatement);return i.strict||o.strict?vt(e,t):Gt(e,t)}function ls(i,o,e){if(!i.nextStatement||!o.previousStatement||e!=null&&e.strict&&!vt(Ie(e.check),Ie(o.previousStatement)))return!1;const t=Ie(i.nextStatement),n=Ie(o.previousStatement);return o.strict?vt(t,n):Gt(t,n)}class ds{ensureModeVisibilityStyles(o,e){const t=pn(o);if(e){const n=pn(e);for(const s of Array.from(document.head.querySelectorAll("style[data-morphic-source]")))if(s.dataset.morphicSource==="mode-visibility"&&s.textContent===n){s.textContent=t;return}}Me("mode-visibility",t)}ensureStyles(o,e){this.ensureStyleBundle(o,"base");for(const t of e)this.ensureStyleBundle(t,`mode:${t.mode}`)}async ensureToolbarStyles(){const o=await Promise.resolve().then(()=>Gs);Me("toolbar",o.default)}ensureWorkspaceStyles(){Me("workspace",[".morphic-workspace-root .blocklyMainBackground {"," stroke: var(--morphic-workspace-border-color, transparent);"," stroke-width: var(--morphic-workspace-border-width, 1px);","}"].join(`
|
|
40
|
+
`))}ensureCategoryStyles(o){for(const e of o){if(!e.color)continue;const t=de(e.name);Me(`category:${t}`,`.morphic-category-${t} { --morphic-category-color: ${e.color}; }`)}}validateModeCoverage(o,e,t=console.warn){const n=new Set(o.map(r=>r.mode)),s=e.filter(r=>!n.has(r));s.length>0&&t(`[MorphicBlocks] Modes without explicit CSS definition: ${s.join(", ")}.`)}ensureStyleBundle(o,e){o&&(o.href&&ps(e,o.href),o.cssText&&Me(e,o.cssText))}}function hs(i,o={}){const e=`.morphic-block .morphic-element-${de(i)}`;Me(`tile-highlight:${i}`,[`${e} .morphic-tok-keyword { color: ${o.keyword??"#cc7832"}; }`,`${e} .morphic-tok-string { color: ${o.string??"#6a8759"}; }`,`${e} .morphic-tok-number { color: ${o.number??"#6897bb"}; }`,`${e} .morphic-tok-comment { color: ${o.comment??"#808080"}; font-style: italic; }`].join(`
|
|
41
|
+
`))}function us(){Me("tile-touch",".morphic-block[data-block-type] { touch-action: pan-y; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; }")}function fs(){const i=":where(.morphic-toolbox-hide-scrollbar",o=e=>`mask-image: ${e}; -webkit-mask-image: ${e};`;Me("toolbox-scroll",[`${i}) { scrollbar-width: none; }`,`${i})::-webkit-scrollbar { display: none; }`,`${i}.morphic-toolbox-more-below) { ${o("linear-gradient(to bottom, #000 calc(100% - 2rem), transparent)")} }`,`${i}.morphic-toolbox-more-above) { ${o("linear-gradient(to top, #000 calc(100% - 2rem), transparent)")} }`,`${i}.morphic-toolbox-more-above.morphic-toolbox-more-below) { ${o("linear-gradient(transparent, #000 2rem, #000 calc(100% - 2rem), transparent)")} }`].join(`
|
|
42
|
+
`))}function pn(i){const o=['[class^="morphic-element-"] { display: none; }'];for(const e of i){const t=de(e.name);for(const n of e.elements){const s=de(n);o.push(`.morphic-mode-${t} > .morphic-element-${s} { display: block; }`)}}return o.join(`
|
|
43
|
+
`)}function Me(i,o){for(const t of Array.from(document.head.querySelectorAll("style[data-morphic-source]")))if(t.dataset.morphicSource===i&&t.textContent===o)return;const e=document.createElement("style");e.dataset.morphicSource=i,e.textContent=o,document.head.appendChild(e)}function ps(i,o){for(const t of Array.from(document.head.querySelectorAll("link[data-morphic-source]")))if(t.getAttribute("href")===o)return;const e=document.createElement("link");e.rel="stylesheet",e.href=o,e.dataset.morphicSource=i,document.head.appendChild(e)}const Ne="morphic/block-type";let ms=0;const gs=8,ks=350;function vs(i,o){const e=Eo(o),t=n=>n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");return i.split(`
|
|
29
44
|
`).map(n=>{let s="",r=0;for(const c of e(n))s+=t(n.slice(r,c.from)),s+=`<span class="morphic-tok-${c.kind}">${t(n.slice(c.from,c.to))}</span>`,r=c.to;return s+t(n.slice(r))}).join(`
|
|
30
|
-
`)}class pt{constructor(o){m(this,"container");m(this,"workspaceContainer");m(this,"workspace");m(this,"definitions");m(this,"blockColors");m(this,"behaviors");m(this,"elementTypes");m(this,"options");m(this,"modes");m(this,"currentMode");m(this,"code");m(this,"renderOverride");m(this,"previewWorkspace");m(this,"onPreviewWorkspace");m(this,"previewContainer");m(this,"previewBase");m(this,"onDragOver");m(this,"onDrop");m(this,"dropTargets");m(this,"onChoose");m(this,"widestBlock",0);this.container=o.container,this.workspaceContainer=o.workspaceContainer,this.workspace=o.workspace,this.onPreviewWorkspace=o.onPreviewWorkspace,this.definitions=o.definitions,this.blockColors=o.blockColors,this.behaviors=o.behaviors,this.elementTypes=o.elementTypes??{},this.code=o.code??{},this.currentMode=o.mode,this.renderOverride=o.render,this.modes=o.modes??[],this.options=o.options??{},this.dropTargets=o.dropTargets??(()=>[]),this.onChoose=o.onChoose,this.onDragOver=e=>{var t;(t=e.dataTransfer)!=null&&t.types.includes(se)&&e.preventDefault()},this.onDrop=e=>{var n;const t=(n=e.dataTransfer)==null?void 0:n.getData(se);t&&(e.preventDefault(),this.createBlockAtPosition(t,e.clientX,e.clientY))},this.workspaceContainer.addEventListener("dragover",this.onDragOver),this.workspaceContainer.addEventListener("drop",this.onDrop),this.render()}rerender(o,e){this.currentMode=o,this.renderOverride=e,this.render()}dispose(){var o;this.workspaceContainer.removeEventListener("dragover",this.onDragOver),this.workspaceContainer.removeEventListener("drop",this.onDrop),this.container.innerHTML="",this.previewWorkspace&&(this.previewWorkspace.dispose(),this.previewWorkspace=void 0,this.previewBase=void 0),(o=this.previewContainer)!=null&&o.parentNode&&(this.previewContainer.parentNode.removeChild(this.previewContainer),this.previewContainer=void 0)}render(){this.widestBlock=0,this.renderTiles(),this.container.style.setProperty("--morphic-toolbox-block-width",`${Math.ceil(this.widestBlock)}px`)}renderTiles(){this.container.innerHTML="";const o=this.options.modeLabel??!0,e=typeof o=="function"?o(this.currentMode):typeof o=="string"?o:o?`Mode: ${this.currentMode}`:"";if(e){const r=document.createElement("div");r.className="morphic-toolbox-header";const c=document.createElement("span");c.className="morphic-toolbar-label",c.textContent=e,r.appendChild(c),this.container.appendChild(r)}const t=this.resolveBlockIds(),n=this.options.categories??[];if(n.length===0){for(const r of t){const c=this.definitions.get(r);c&&this.container.appendChild(this.createTile(c))}return}const s=new Set;for(const r of n){const c=this.resolveCategoryBlockIds(r,t);if(c.length===0)continue;const a=document.createElement("div");a.setAttribute("data-category",V(r.name)),r.color&&a.style.setProperty("--morphic-category-color",r.color);for(const d of c){const l=this.definitions.get(d);l&&(a.appendChild(this.createTile(l)),s.add(d))}this.container.appendChild(a)}for(const r of t)if(!s.has(r)){const c=this.definitions.get(r);c&&this.container.appendChild(this.createTile(c))}}createTile(o){var l,h;const e=V(this.currentMode),t=V(o.identifier),n=this.blockColors.get(o.identifier),s=document.createElement("div");s.setAttribute("draggable","true"),s.setAttribute("data-block-type",o.identifier),s.className=`morphic-block morphic-mode-${e} morphic-block-${t}`,n&&s.style.setProperty("--morphic-block-color",n);const r=this.modes.find(u=>u.name===this.currentMode),c=(r==null?void 0:r.elements)??[],a=Object.entries(o.elements),d=[...c.map(u=>a.find(([k])=>k===u)).filter(u=>u!==void 0),...a.filter(([u])=>!c.includes(u))];for(const[u,k]of d){const v=document.createElement("div");v.className=`morphic-element-${V(u)}`;const w=this.elementTypes[u],b=j(w),g=b==="code",y=b==="image",C=((l=this.renderOverride)==null?void 0:l[u])??(g?"block":"text"),E=y?Ve(k,Re(w)):k;if(g&&C==="block"){this.syncPreviewFont(u);const f=this.createBlockPreviewSvg(o,this.currentMode,u);f?v.appendChild(f):v.innerHTML=Ce(ee(E))}else if(g){const f=this.createCodeText(o,this.currentMode,u),p=this.options.highlight===!1||(h=this.code[u])==null?void 0:h.highlighting;f!==null&&p?(Fo(u,p.colors),v.innerHTML=zo(f,p)):f!==null?v.textContent=f:v.innerHTML=Ce(ee(E))}else v.innerHTML=Ce(ee(E));s.appendChild(v)}return s.addEventListener("dragstart",u=>{var k;(k=u.dataTransfer)==null||k.setData(se,o.identifier)}),this.options.touch!==!1&&(Ro(),this.attachTouchDrag(s,o.identifier)),this.options.keyboard!==!1&&(s.tabIndex=0,s.setAttribute("role","button"),s.setAttribute("aria-label",this.tileName(o,c)),s.addEventListener("keydown",u=>{var k;u.key!=="Enter"&&u.key!==" "||(u.preventDefault(),(k=this.onChoose)==null||k.call(this,o.identifier))})),s}tileName(o,e){var n;const t=[];for(const s of e){const r=o.elements[s];if(r===void 0)continue;const c=j(this.elementTypes[s]);if(c==="code"){const l=this.createCodeText(o,this.currentMode,s);l!=null&&l.trim()&&t.push(l.trim());continue}const a=document.createElement("div");a.innerHTML=c==="image"?Ve(r,Re(this.elementTypes[s])):r;const d=c==="image"?Array.from(a.querySelectorAll("img"),l=>l.alt).join(" ").trim():(n=a.textContent)==null?void 0:n.trim();d&&t.push(d)}return t.join(", ")||o.identifier}dropTargetAt(o,e){const t=document.elementFromPoint(o,e);if(!t)return;const n={element:this.workspaceContainer,drop:(s,r,c)=>this.createBlockAtPosition(s,r,c)};return[...this.dropTargets(),n].find(s=>s.element.contains(t))}attachTouchDrag(o,e){o.addEventListener("pointerdown",t=>{var y;if(t.pointerType==="mouse"||!t.isPrimary)return;const n=o.getBoundingClientRect();let s,r,c={x:t.clientX,y:t.clientY};o.draggable=!1;let a={x:0,y:0},d=1,l=0;const h=()=>{if(s)return;s=o.cloneNode(!0),s.classList.add("morphic-drag-ghost"),s.removeAttribute("tabindex"),Object.assign(s.style,{position:"fixed",left:"0",top:"0",margin:"0",pointerEvents:"none",zIndex:"2147483647",transition:"none",animation:"none"}),this.container.appendChild(s);const C=s.getBoundingClientRect();s.style.left="100px",d=(s.getBoundingClientRect().left-C.left)/100||1,a={x:C.left,y:C.top},Object.assign(s.style,{left:`${(n.left-a.x)/d}px`,top:`${(n.top-a.y)/d}px`,width:`${n.width/d}px`}),k()},u=window.setTimeout(h,Wo),k=()=>{!s||l||(l=requestAnimationFrame(()=>{var E,f;if(l=0,!s)return;s.style.transform=`translate(${(c.x-t.clientX)/d}px, ${(c.y-t.clientY)/d}px)`;const C=this.dropTargetAt(c.x,c.y);C!==r&&((E=r==null?void 0:r.leave)==null||E.call(r)),r=C,(f=r==null?void 0:r.over)==null||f.call(r,c.x,c.y)}))},v=C=>{if(C.pointerId!==t.pointerId)return;c={x:C.clientX,y:C.clientY};const E=Math.abs(C.clientX-t.clientX),f=Math.abs(C.clientY-t.clientY);!s&&(E<_o||f>E)||(window.clearTimeout(u),h(),k())},w=C=>{s&&C.preventDefault()},b=C=>C.preventDefault(),g=C=>{var E,f;C.pointerId===t.pointerId&&(window.clearTimeout(u),o.removeEventListener("pointermove",v),o.removeEventListener("pointerup",g),o.removeEventListener("pointercancel",g),o.removeEventListener("touchmove",w),o.removeEventListener("contextmenu",b),o.draggable=!0,cancelAnimationFrame(l),(E=r==null?void 0:r.leave)==null||E.call(r),s&&(s.remove(),C.type==="pointerup"&&((f=this.dropTargetAt(C.clientX,C.clientY))==null||f.drop(e,C.clientX,C.clientY))))};(y=o.setPointerCapture)==null||y.call(o,t.pointerId),o.addEventListener("pointermove",v),o.addEventListener("pointerup",g),o.addEventListener("pointercancel",g),o.addEventListener("touchmove",w,{passive:!1}),o.addEventListener("contextmenu",b)})}ensurePreviewWorkspace(){var e;if(this.previewWorkspace)return this.previewWorkspace;this.previewContainer=document.createElement("div"),this.previewContainer.style.cssText="position:absolute;left:-9999px;top:-9999px;width:800px;height:600px;overflow:hidden;",document.body.appendChild(this.previewContainer);const o=this.workspace.options;return this.previewWorkspace=x.inject(this.previewContainer,{scrollbars:!1,media:o.pathToMedia,sounds:!1,renderer:o.renderer,rendererOverrides:o.rendererOverrides??void 0,theme:o.theme,rtl:o.RTL}),(e=this.onPreviewWorkspace)==null||e.call(this,this.previewWorkspace),this.previewWorkspace}syncPreviewFont(o){const e=this.ensurePreviewWorkspace();this.previewBase??(this.previewBase={theme:e.getTheme(),font:it(e)});const t=st(this.container,[["morphic-block",`morphic-mode-${V(this.currentMode)}`],[`morphic-element-${V(o)}`],[e.getRenderer().getClassName(),e.getTheme().getClassName()]],this.previewBase.font);rt(e,this.previewBase.theme,this.previewBase.font,t)}createPreviewBlock(o,e,t){var d;const n=this.ensurePreviewWorkspace(),s=n.newBlock(U(o.identifier,this.definitions)),r=this.blockColors.get(o.identifier);r&&s.setColour(r);const c={mode:e,template:o.elements[t]??"",elementName:t,inputSlots:o.inputSlots};We({block:s,definition:o,view:c,mode:"block",context:"toolbox",elementTypes:this.elementTypes,resolveBlocklyType:l=>U(l,this.definitions)});const a=ce(this.behaviors[o.identifier]);return(d=a==null?void 0:a.onViewApplied)==null||d.call(a,s,{Blockly:x,workspace:n,mode:e,context:"toolbox",definition:o}),s}createCodeText(o,e,t){try{const n=this.createPreviewBlock(o,e,t),{code:s}=ke(n.workspace,e,this.definitions,this.elementTypes,this.modes,t,{emptyStatements:!1});return n.dispose(!1),s}catch{return null}}createBlockPreviewSvg(o,e,t){try{const n=this.ensurePreviewWorkspace(),s=this.createPreviewBlock(o,e,t);for(const u of s.getDescendants(!1))u.initSvg(),u.queueRender();s.render();const r=s.getSvgRoot();if(!r)return s.dispose(!1),null;const c=r.getBBox(),a=r.cloneNode(!0),d=4,l=document.createElementNS("http://www.w3.org/2000/svg","svg"),h=Math.ceil(c.width+d*2);return this.widestBlock=Math.max(this.widestBlock,h),l.setAttribute("width",String(h)),l.setAttribute("height",String(Math.ceil(c.height+d*2))),l.setAttribute("viewBox",`${c.x-d} ${c.y-d} ${c.width+d*2} ${c.height+d*2}`),l.setAttribute("class",`${n.getRenderer().getClassName()} ${n.getTheme().getClassName()}`),l.style.direction="ltr",l.appendChild(a),s.dispose(!1),l}catch{return null}}createBlockAtPosition(o,e,t){const n=this.workspace,s=n.getInjectionDiv().getBoundingClientRect(),r=(e-s.left-n.scrollX)/n.scale,c=(t-s.top-n.scrollY)/n.scale,a=n.newBlock(U(o,this.definitions));a.moveTo(new x.utils.Coordinate(r,c)),a.initSvg(),a.render()}resolveBlockIds(){return this.options.blocks??[...this.definitions.keys()]}resolveCategoryBlockIds(o,e){return o.blocks&&o.blocks.length>0?o.blocks.filter(t=>e.includes(t)):e.filter(t=>{var n,s;return((s=(n=this.definitions.get(t))==null?void 0:n.category)==null?void 0:s.toLowerCase())===o.name.toLowerCase()})}}function $e(i,o){var t;if(i.blocks&&i.blocks.length>0)return i.blocks;const e=[];for(const n of o.values())((t=n.category)==null?void 0:t.toLowerCase())===i.name.toLowerCase()&&e.push(n.identifier);return e}function mt(i,o){var n,s,r;if((i.kind??((n=i.categories)!=null&&n.length?"categoryToolbox":"flyoutToolbox"))==="categoryToolbox")return{kind:"categoryToolbox",contents:(i.categories??[]).map(a=>({kind:"category",name:a.name,colour:a.color,contents:$e(a,o).map(d=>({kind:"block",type:U(d,o)}))}))};if((s=i.categories)!=null&&s.length){const c=i.categories,a=[];return c.forEach((l,h)=>{const u=V(l.name);a.push({kind:"label",id:`morphic-category-${u}`,text:l.name,"web-class":`morphic-flyout-category-label morphic-category-${u}`});for(const k of gt($e(l,o)))a.push({kind:"block",type:U(k,o)});h<c.length-1&&a.push({kind:"sep",gap:14})}),{kind:"flyoutToolbox",contents:a}}return{kind:"flyoutToolbox",contents:(i.blocks??gt(((r=i.categories)==null?void 0:r.flatMap(c=>$e(c,o)))??[...o.keys()])).map(c=>({kind:"block",type:U(c,o)}))}}function gt(i){return i.filter((o,e,t)=>t.indexOf(o)===e)}const jo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="4" y="4" width="9" height="10" rx="1.5"/><path d="M3 11V3a1 1 0 0 1 1-1h7"/></svg>',Uo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 3h6v2H5z"/><path d="M4 3H3a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V4a1 1 0 0 0-1-1h-1"/></svg>',Go='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8h7a3 3 0 0 1 0 6H6"/><polyline points="5 5 2 8 5 11"/></svg>',Xo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M13 8H6a3 3 0 0 0 0 6h4"/><polyline points="11 5 14 8 11 11"/></svg>',Yo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 4 13 4"/><path d="M5 4V3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v1"/><path d="M4 4l1 9a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1l1-9"/></svg>',Ko='<svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor"><polygon points="4,3 13,8 4,13"/></svg>',qo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="7" r="4"/><line x1="10" y1="10" x2="14" y2="14"/><line x1="5" y1="7" x2="9" y2="7"/><line x1="7" y1="5" x2="7" y2="9"/></svg>',Jo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="7" r="4"/><line x1="10" y1="10" x2="14" y2="14"/><line x1="5" y1="7" x2="9" y2="7"/></svg>',Zo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 3 3 6 3"/><polyline points="13 6 13 3 10 3"/><polyline points="3 10 3 13 6 13"/><polyline points="13 10 13 13 10 13"/></svg>',Qo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 2h8l2 2v10H3z"/><rect x="5" y="2" width="6" height="4"/><rect x="5" y="9" width="6" height="4"/></svg>',en='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8v5a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V8"/><polyline points="5 5 8 2 11 5"/><line x1="8" y1="2" x2="8" y2="10"/></svg>',tn='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8a5 5 0 1 0 1.5-3.5"/><polyline points="3 2 3 5 6 5"/></svg>',on='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2 8s2-4 6-4 6 4 6 4-2 4-6 4-6-4-6-4z"/><circle cx="8" cy="8" r="1.5"/></svg>',A={modeLabel(){return{id:"mode-label",render:i=>{const o=document.createElement("span");return o.className="morphic-toolbar-label",o.textContent=nn(i),o}}},copy(){return{id:"copy",label:"Copy",title:"Copy block",icon:jo,onClick:i=>{i.engine.copyActiveBlock(i.view)}}},paste(){return{id:"paste",label:"Paste",title:"Paste block",icon:Uo,disabled:i=>!i.engine.hasClipboardContents(),onClick:i=>{i.engine.pasteActiveBlock(i.view)}}},undo(){return{id:"undo",label:"Undo",title:"Undo (block model)",icon:Go,onClick:i=>{var o;(o=i.engine.getWorkspace())==null||o.undo(!1)},disabled:i=>{var o;return!((o=i.engine.getWorkspace())!=null&&o.getUndoStack().length)}}},redo(){return{id:"redo",label:"Redo",title:"Redo (block model)",icon:Xo,onClick:i=>{var o;(o=i.engine.getWorkspace())==null||o.undo(!0)},disabled:i=>{var o;return!((o=i.engine.getWorkspace())!=null&&o.getRedoStack().length)}}},zoomIn(){return{id:"zoom-in",label:"Zoom in",title:"Zoom in",icon:qo,onClick:i=>i.engine.zoomPane(i.view,"in")}},zoomOut(){return{id:"zoom-out",label:"Zoom out",title:"Zoom out",icon:Jo,onClick:i=>i.engine.zoomPane(i.view,"out")}},zoomFit(){return{id:"zoom-fit",label:"Fit",title:"Reset zoom",icon:Zo,onClick:i=>i.engine.zoomPane(i.view,"fit")}},clear(){return{id:"clear",label:"Clear",title:"Clear workspace",icon:Yo,onClick:i=>{var o;window.confirm("Clear workspace? This cannot be undone.")&&((o=i.engine.getWorkspace())==null||o.clear())}}},runCode(){return{id:"run",label:"Run",title:"Run generated code",icon:Ko,onClick:i=>{i.engine.runJavaScript()}}},save(){return{id:"save",label:"Save",title:"Save workspace as JSON",icon:Qo,onClick:i=>{if(!i.engine.getWorkspace())return;const e=i.engine.serializeWorkspace(),t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),n=URL.createObjectURL(t),s=document.createElement("a");s.href=n,s.download="workspace.json",s.click(),URL.revokeObjectURL(n)}}},load(){return{id:"load",label:"Load",title:"Load workspace JSON",icon:en,onClick:i=>{const o=document.createElement("input");o.type="file",o.accept="application/json",o.addEventListener("change",async()=>{var t;const e=(t=o.files)==null?void 0:t[0];if(e)try{const n=await e.text(),s=JSON.parse(n);i.engine.loadWorkspace(s)}catch(n){window.alert(`Load failed: ${n instanceof Error?n.message:String(n)}`)}}),o.click()}}},reset(){return{id:"reset",label:"Reset",title:"Reset workspace",icon:tn,onClick:i=>{var o;window.confirm("Reset workspace to empty? This cannot be undone.")&&((o=i.engine.getWorkspace())==null||o.clear())}}},togglePreview(){return{id:"toggle-preview",label:"Preview",title:"Toggle preview pane",icon:on,onClick:()=>{const i=document.querySelector("[data-morphic-preview-host]");i&&(i.hidden=!i.hidden)}}},readOnlyBadge(){return{id:"read-only",align:"right",render:()=>{const i=document.createElement("span");return i.className="morphic-toolbar-badge",i.textContent="read-only",i}}},spacer(){return{id:"spacer",render:()=>{const i=document.createElement("span");return i.className="morphic-toolbar-spacer",i}}},readOnlyDefaults(){return[A.modeLabel(),A.spacer(),A.copy(),A.zoomIn(),A.zoomOut(),A.zoomFit(),A.readOnlyBadge()]},defaultsFor(i){switch(i){case"workspace":case"codespace":return[A.modeLabel(),A.spacer(),A.undo(),A.redo(),A.copy(),A.paste(),A.zoomIn(),A.zoomOut(),A.zoomFit(),A.clear()];case"preview":return[A.modeLabel(),A.spacer(),A.copy(),A.zoomIn(),A.zoomOut(),A.zoomFit(),A.readOnlyBadge()]}}};function nn(i){const o=i.engine.getViewMode(i.view);return o?`Mode: ${o}`:""}function kt(i,o,e){const t=o.items??A.defaultsFor(e.pane),n=o.display??"icon";i.classList.add("morphic-toolbar"),i.setAttribute("data-morphic-pane",e.pane),i.setAttribute("data-morphic-view",e.view);const s=document.createElement("div");s.className="morphic-toolbar-left";const r=document.createElement("div");r.className="morphic-toolbar-right";const c=()=>{s.replaceChildren(),r.replaceChildren();let a=!1;for(const d of t){if(d.visible&&!d.visible(e))continue;if(d.id==="spacer"){a=!0;continue}(d.align==="right"||a&&d.align!=="left"?r:s).appendChild(sn(d,n,e))}};return i.replaceChildren(s,r),c(),{refresh:c,pane:e.pane,view:e.view,dispose:()=>i.replaceChildren()}}function sn(i,o,e){if(i.render){const n=i.render(e);if(typeof n=="string"){const s=document.createElement("span");return s.className="morphic-toolbar-item",s.dataset.toolbarId=i.id,s.textContent=n,s}return n.classList.add("morphic-toolbar-item"),n.dataset.toolbarId=i.id,n}const t=document.createElement("button");return t.className="morphic-toolbar-item",t.dataset.toolbarId=i.id,t.type="button",i.title&&(t.title=i.title),rn(t,i,o),i.disabled&&i.disabled(e)&&(t.disabled=!0),i.onClick&&t.addEventListener("click",()=>i.onClick(e)),t}function rn(i,o,e){const t=e!=="label"&&!!o.icon,n=e!=="icon"&&!!o.label,s=t||e==="icon"&&!o.label,r=n||e==="label"&&!o.icon;if(s&&o.icon){const c=document.createElement("span");c.className="morphic-toolbar-icon",c.innerHTML=o.icon,i.appendChild(c)}if(r&&o.label){const c=document.createElement("span");c.className="morphic-toolbar-text",c.textContent=o.label,i.appendChild(c)}!i.title&&o.label&&(i.title=o.label),!i.childNodes.length&&o.label&&(i.textContent=o.label)}function wt(i,o){return o.includes("{")?{mode:i,cssText:o}:{mode:i,href:o}}function cn(i){const o=[];for(const[e,t]of Object.entries(i)){const s=(e.split("/").pop()??e).replace(/\.css$/i,""),r=typeof t=="string"?t:typeof t=="object"&&t!==null&&"default"in t?String(t.default):void 0;r&&o.push(wt(s,r))}return o}function Ne(i){return typeof i=="string"?{mode:i}:{mode:i.mode,render:i.render}}const an="blockly-media/",vt=new Set;function ln(i,o){if(vt.has(i)||typeof Image>"u")return;vt.add(i);const e=new Image;e.onerror=()=>{o(`[MorphicBlocks] Blockly's media is missing at "${i}", so icons are not shown and sounds stay silent. Copy it there with "morphic-blocks copy-media <folder>", or point blockly.media to where it is.`)},e.src=`${i}sprites.png`}const He=i=>i.onWarning??(o=>console.warn(o)),re=new WeakMap,be=new Map;function dn(i){const o=i.setInsertionMarker;i.setInsertionMarker=function(e){var t;if(o.call(this,e),!!e)for(const n of this.inputList)(t=n.connection)==null||t.setShadowState(null)}}class hn extends EventTarget{constructor(e,t={}){super();m(this,"definitions");m(this,"behaviors");m(this,"elementTypes");m(this,"formatElementTypes");m(this,"styles",new Po);m(this,"registeredBlockTypes",new Set);m(this,"toolbars",new Set);m(this,"toolbarsBlocklyListener");m(this,"lastCopyData");m(this,"mountConfig");m(this,"workspace");m(this,"flyoutWorkspace");m(this,"toolboxCanvas");m(this,"tileDropTargets",new Set);m(this,"codeEditor");m(this,"codespace");m(this,"previewEditor");m(this,"views",new Set);m(this,"viewWorkspaceModes",new WeakMap);m(this,"viewCount",0);m(this,"selectionSync");m(this,"toolboxDefinition");m(this,"previewHost");m(this,"blockCategoryIndex",new Map);m(this,"appliedWorkspaceClasses",[]);m(this,"appliedToolboxFlyoutClasses",[]);m(this,"appliedToolboxShellClasses",[]);m(this,"headlessWorkspaceHost");m(this,"codespaceDropTeardown");m(this,"workspaceResizeObserver");m(this,"activePreset");m(this,"baseTheme");m(this,"baseFont");m(this,"mountGeneration",0);m(this,"selectionSyncOptions");m(this,"formatModes");m(this,"formatPresets");m(this,"formatCode");m(this,"formatHasHighlighting");m(this,"formatCategories");m(this,"onWorkspaceChange",e=>{if(!this.workspace||!this.mountConfig||e.workspaceId!==this.workspace.id||e.type!==x.Events.BLOCK_CREATE)return;const t=e;for(const n of t.ids??[]){const s=this.workspace.getBlockById(n);if(!s)continue;const r=this.definitions.get(W(s.type));if(!r)continue;const c=this.mountConfig.workspaceMode,a=s;if(a.__morphicMode===c&&a.__morphicContext==="workspace"&&s.getSvgRoot()){ze(s,c,"workspace"),this.styleBlock(s,r);continue}this.applyView(s,r,c,"workspace"),s.getSvgRoot()||this.deferApplyView(n,c,"workspace")}});m(this,"onFlyoutChange",e=>{if(!this.flyoutWorkspace||!this.mountConfig||e.workspaceId!==this.flyoutWorkspace.id||e.type!==x.Events.BLOCK_CREATE)return;const t=e;for(const n of t.ids??[]){const s=this.flyoutWorkspace.getBlockById(n);if(!s)continue;const r=this.definitions.get(W(s.type));r&&(this.applyView(s,r,this.mountConfig.toolboxMode,"toolbox"),s.getSvgRoot()||this.deferApplyView(n,this.mountConfig.toolboxMode,"toolbox"))}});m(this,"onStylesLoaded",()=>this.refresh());const n=e;this.definitions=Bo(Lo(Mo(n.blocks,n.elementTypes??{}))),this.behaviors=t,this.formatElementTypes=n.elementTypes??{},this.elementTypes=Fe(this.formatElementTypes,n.code),this.formatModes=n.modes,this.formatPresets=n.presets,this.formatCode=n.code,this.formatHasHighlighting="highlighting"in n,this.formatCategories=n.categories}mount(e){var y,C,E,f,p,S,T,M;this.dispose();const t={...e,modes:(y=e.modes??this.formatModes)==null?void 0:y.slice(),presets:e.presets??this.formatPresets,code:e.code??this.formatCode,toolbox:e.toolbox||this.formatCategories?{...e.toolbox,categories:((C=e.toolbox)==null?void 0:C.categories)??this.formatCategories}:void 0},n=t.modesFolder?cn(t.modesFolder):[],s=[...n,...Object.entries(t.modeStyles??{}).filter(([B])=>!n.some(D=>D.mode===B)).map(([B,D])=>wt(B,D))];this.elementTypes=Fe(this.formatElementTypes,t.code),this.validateDefinitions(t),this.validatePresets(t);const r=(E=t.presets)!=null&&E.length?t.presets.find(B=>B.name===t.preset)??t.presets[0]:void 0;if(t.preset&&!r)throw new Error(`MorphicBlocks.mount: unknown preset "${t.preset}".`);const c=(t.modes??[]).map(B=>B.name),a=c[0]??((f=s[0])==null?void 0:f.mode)??"default",d=r?Ne(r.toolbox):void 0,l=r?r.workspace??r.codespace??a:a,h=d?d.mode:a,u=d==null?void 0:d.render,k=r==null?void 0:r.codespace,v=r==null?void 0:r.preview;this.validateContainers(t);const w=t.workspaceContainer??this.createHeadlessHost(),b={...t,modeStyles:s,workspaceMode:l,toolboxMode:h,toolboxRender:u,codespaceMode:k,previewMode:v,workspaceHost:w,canvasToolbox:t.canvasToolbox??!!t.toolboxContainer};this.mountConfig=b,this.styles.validateModeCoverage(s,c,He(t)),(p=b.modes)!=null&&p.length&&this.styles.ensureModeVisibilityStyles(b.modes),this.styles.ensureStyles(b.baseStyle,s);for(const B of Array.from(document.head.querySelectorAll('link[data-morphic-source^="mode:"]')))B.sheet||B.addEventListener("load",this.onStylesLoaded,{once:!0});(S=document.fonts)==null||S.addEventListener("loadingdone",this.onStylesLoaded),this.blockCategoryIndex=this.createCategoryIndex(b.toolbox,b),this.styles.ensureCategoryStyles(((T=b.toolbox)==null?void 0:T.categories)??[]),this.styles.ensureWorkspaceStyles(),this.registerBlocks(),this.toolboxDefinition=this.resolveToolboxDefinition(b);const g=b.blockly??{};if(this.workspace=x.inject(b.workspaceHost,{...g,media:g.media??an,...b.canvasToolbox?{}:{toolbox:this.toolboxDefinition}}),this.workspace.addChangeListener(this.onWorkspaceChange),re.set(this.workspace,this),this.baseTheme=this.workspace.getTheme(),this.baseFont=it(this.workspace),t.workspaceContainer&&ln(this.workspace.options.pathToMedia,He(t)),t.workspaceContainer&&typeof ResizeObserver<"u"){const B=this.workspace;this.workspaceResizeObserver=new ResizeObserver(()=>x.svgResize(B)),this.workspaceResizeObserver.observe(t.workspaceContainer)}return this.applyWorkspaceContainerClass(),this.syncWorkspaceFont(),this.refreshToolbox(),this.bindFlyoutWorkspace(),this.renderWorkspaceBlocks(),this.renderFlyoutBlocks(),t.toolboxContainer&&this.mountToolbox(t.toolboxContainer),this.activePreset=r,r&&((M=b.onPresetApplied)==null||M.call(b,r)),this.mountViews(t,++this.mountGeneration)}async mountViews(e,t){const n=e.editorTheme?{theme:e.editorTheme}:void 0,s=e.previewTheme??e.editorTheme,r=[];if(e.codespaceContainer&&r.push(this.mountCodespace(n)),e.previewContainer&&r.push(this.mountPreview(e.previewContainer,s?{theme:s}:void 0)),e.codeEditorContainer&&r.push(this.mountCodeEditor(e.codeEditorContainer,n).then(()=>{t===this.mountGeneration&&this.hideCodeEditor()})),await Promise.all(r),t!==this.mountGeneration||!this.workspace)return;for(const[d,l]of Object.entries(e.toolbarContainers??{}))l&&this.mountToolbar(l,{pane:d});const c=(e.workspaceContainer?1:0)+r.length,a=e.selectionSync??c>1;a&&r.length>0&&this.enableSelectionSync(typeof a=="object"?a:void 0)}getPresets(){var e;return[...((e=this.mountConfig)==null?void 0:e.presets)??[]]}getActivePreset(){return this.activePreset}applyPreset(e){var r,c,a,d;if(!this.mountConfig||!this.workspace)throw new Error("MorphicBlocks must be mounted before applyPreset can be used.");const t=this.mountConfig.presets??[],n=typeof e=="number"?t[e]:t.find(l=>l.name===e);if(!n)throw new Error(`applyPreset: unknown preset "${e}".`);const s=Ne(n.toolbox);this.setModes({toolboxMode:s.mode,toolboxRender:s.render??null,workspaceMode:n.workspace??n.codespace,codespaceMode:n.codespace??null,previewMode:n.preview??null});for(const l of this.views){const h=(r=n.views)==null?void 0:r[l.name];h!==void 0&&h!==l.mode&&((c=l.setMode)==null||c.call(l,h))}return this.activePreset=n,(d=(a=this.mountConfig).onPresetApplied)==null||d.call(a,n),n}validateDefinitions(e){var s;const{errors:t,warnings:n}=ct({definitions:this.definitions,elementTypes:this.formatElementTypes,behaviors:this.behaviors,modes:e.modes,presets:e.presets,code:e.code,categories:(s=e.toolbox)==null?void 0:s.categories});if((this.formatHasHighlighting||"highlighting"in e)&&t.push('The top level "highlighting" map moved into the "code" section: "code": { "<element>": { "highlighting": { … } } }.'),n.length>0&&He(e)(`[MorphicBlocks] Definition warnings:
|
|
45
|
+
`)}class mn{constructor(o){y(this,"container");y(this,"workspaceContainer");y(this,"workspace");y(this,"definitions");y(this,"blockColors");y(this,"behaviors");y(this,"elementTypes");y(this,"options");y(this,"modes");y(this,"currentMode");y(this,"code");y(this,"previewWorkspace");y(this,"onPreviewWorkspace");y(this,"previewContainer");y(this,"previewBase");y(this,"onDragOver");y(this,"onDrop");y(this,"dropTargets");y(this,"collapsedCategories",new Set);y(this,"categoryParts",[]);y(this,"activeCategory");y(this,"grouped");y(this,"onScroll",()=>this.showScrollHints());y(this,"resizeObserver",typeof ResizeObserver<"u"?new ResizeObserver(()=>this.showScrollHints()):void 0);y(this,"onChoose");y(this,"widestBlock",0);var n;this.container=o.container,this.workspaceContainer=o.workspaceContainer,this.workspace=o.workspace,this.onPreviewWorkspace=o.onPreviewWorkspace,this.definitions=o.definitions,this.blockColors=o.blockColors,this.behaviors=o.behaviors,this.elementTypes=o.elementTypes??{},this.code=o.code??{},this.currentMode=o.mode,this.modes=o.modes??[],this.options=o.options??{},this.grouped=o.grouped??!0,this.dropTargets=o.dropTargets??(()=>[]);const e=this.options.collapsed,t=e===!0?(this.options.categories??[]).map(s=>s.name):e||[];for(const s of t)this.collapsedCategories.add(s);this.onChoose=o.onChoose,this.onDragOver=s=>{var r;(r=s.dataTransfer)!=null&&r.types.includes(Ne)&&s.preventDefault()},this.onDrop=s=>{var c;const r=(c=s.dataTransfer)==null?void 0:c.getData(Ne);r&&(s.preventDefault(),this.createBlockAtPosition(r,s.clientX,s.clientY))},this.workspaceContainer.addEventListener("dragover",this.onDragOver),this.workspaceContainer.addEventListener("drop",this.onDrop),this.container.classList.add("morphic-toolbox"),this.options.scrollbar!==!0&&(fs(),this.container.classList.add("morphic-toolbox-hide-scrollbar")),this.container.addEventListener("scroll",this.onScroll,{passive:!0}),(n=this.resizeObserver)==null||n.observe(this.container),this.render()}setGrouped(o){this.grouped=o}setBlocks(o){this.options={...this.options,blocks:o}}rerender(o){this.currentMode=o,this.render()}dispose(){var o,e;this.workspaceContainer.removeEventListener("dragover",this.onDragOver),this.workspaceContainer.removeEventListener("drop",this.onDrop),this.container.removeEventListener("scroll",this.onScroll),(o=this.resizeObserver)==null||o.disconnect(),this.container.classList.remove("morphic-toolbox","morphic-toolbox-hide-scrollbar","morphic-toolbox-more-above","morphic-toolbox-more-below","morphic-toolbox-stacked","morphic-toolbox-tabs"),this.container.innerHTML="",this.previewWorkspace&&(this.previewWorkspace.dispose(),this.previewWorkspace=void 0,this.previewBase=void 0),(e=this.previewContainer)!=null&&e.parentNode&&(this.previewContainer.parentNode.removeChild(this.previewContainer),this.previewContainer=void 0)}render(){this.widestBlock=0,this.renderTiles();for(const o of Array.from(this.container.querySelectorAll("[data-morphic-text-code]")))this.widestBlock=Math.max(this.widestBlock,o.scrollWidth);this.container.style.setProperty("--morphic-toolbox-block-width",`${Math.ceil(this.widestBlock)}px`),this.showCategories()}renderTiles(){this.container.innerHTML="";const o=this.options.modeLabel??!0,e=typeof o=="function"?o(this.currentMode):typeof o=="string"?o:o?`Mode: ${this.currentMode}`:"";if(e){const a=document.createElement("div");a.className="morphic-toolbox-header";const l=document.createElement("span");l.className="morphic-toolbar-label",l.textContent=e,a.appendChild(l),this.container.appendChild(a)}const t=this.resolveBlockIds(),n=this.grouped?this.options.categories??[]:[];this.categoryParts=[];const s=this.options.layout==="tabs";this.container.classList.toggle("morphic-toolbox-tabs",s),this.container.classList.toggle("morphic-toolbox-stacked",!s);const r=s&&n.length>0?document.createElement("div"):void 0;if(r&&(r.className="morphic-category-tabs",r.setAttribute("role","tablist"),this.container.appendChild(r)),n.length===0){for(const a of t){const l=this.definitions.get(a);l&&this.container.appendChild(this.createTile(l))}return}const c=new Set;for(const a of n){const l=this.resolveCategoryBlockIds(a,t);if(l.length===0)continue;const d=document.createElement("div");d.setAttribute("data-category",de(a.name)),a.color&&d.style.setProperty("--morphic-category-color",a.color);const h=document.createElement("div");h.className="morphic-category-tiles",h.id=`morphic-category-${++ms}`;let u,f;if(r)f=document.createElement("button"),f.className="morphic-category-tab",f.type="button",f.setAttribute("role","tab"),f.setAttribute("aria-controls",h.id),f.textContent=a.name,a.color&&f.style.setProperty("--morphic-category-color",a.color),f.addEventListener("click",()=>{this.activeCategory=a.name,this.showCategories()}),r.appendChild(f),h.setAttribute("role","tabpanel");else if(this.options.categoryHeadings!==!1){const p=this.options.collapsible!==!1;u=document.createElement(p?"button":"div"),u.className="morphic-category-heading",u.textContent=a.name,p?(u.type="button",u.setAttribute("aria-controls",h.id),u.addEventListener("click",()=>this.toggleCategory(a.name))):(u.setAttribute("role","heading"),u.setAttribute("aria-level","3")),d.appendChild(u)}this.categoryParts.push({name:a.name,group:d,heading:u,tiles:h,tab:f});for(const p of l){const g=this.definitions.get(p);g&&(h.appendChild(this.createTile(g)),c.add(p))}d.appendChild(h),this.container.appendChild(d)}for(const a of t)if(!c.has(a)){const l=this.definitions.get(a);l&&this.container.appendChild(this.createTile(l))}}toggleCategory(o){var t,n;const e=!this.collapsedCategories.delete(o);e&&this.collapsedCategories.add(o),this.showCategories(),(n=(t=this.options).onCategoryToggle)==null||n.call(t,o,e)}showScrollHints(){const{scrollTop:o,clientHeight:e,scrollHeight:t}=this.container;this.container.classList.toggle("morphic-toolbox-more-above",o>1),this.container.classList.toggle("morphic-toolbox-more-below",o+e<t-1)}showCategories(){this.showCategoryState(),this.showScrollHints()}showCategoryState(){var e;if(this.options.layout==="tabs"){const t=this.categoryParts.find(n=>n.name===this.activeCategory)??this.categoryParts[0];for(const n of this.categoryParts)n.group.hidden=n!==t,(e=n.tab)==null||e.setAttribute("aria-selected",String(n===t));return}const o=this.options.collapsible!==!1&&this.options.categoryHeadings!==!1;for(const{name:t,group:n,heading:s,tiles:r}of this.categoryParts){const c=o&&this.collapsedCategories.has(t);r.hidden=c,n.toggleAttribute("data-collapsed",c),(s==null?void 0:s.tagName)==="BUTTON"&&s.setAttribute("aria-expanded",String(!c))}}createTile(o){var h,u,f;const e=de(this.currentMode),t=de(o.identifier),n=this.blockColors.get(o.identifier),s=document.createElement("div");s.setAttribute("draggable","true"),s.setAttribute("data-block-type",o.identifier),s.className=`morphic-block morphic-mode-${e} morphic-block-${t}`,n&&s.style.setProperty("--morphic-block-color",n);const r=this.modes.find(p=>p.name===this.currentMode),c=(r==null?void 0:r.elements)??[],a=Object.entries(o.elements),l=[...c.map(p=>a.find(([g])=>g===p)).filter(p=>p!==void 0),...a.filter(([p])=>!c.includes(p))];for(const[p,g]of l){const v=document.createElement("div");v.className=`morphic-element-${de(p)}`;const w=this.elementTypes[p],C=pe(w),T=C==="code",F=C==="image",$=(h=this.modes.find(O=>O.name===this.currentMode))==null?void 0:h.render,E=T&&($==null?void 0:$[p])!=="text-based",M=F?Lt(g,St(w)):g;if(C==="custom"){v.dataset.morphicCustom="";const O=(u=this.options.custom)==null?void 0:u[p],A=(O==null?void 0:O(g,{block:o.identifier,element:p,mode:this.currentMode}))??g;typeof A=="string"?v.textContent=A:v.appendChild(A)}else if(E){this.syncPreviewFont(p);const O=this.createBlockPreviewSvg(o,this.currentMode,p);O?v.appendChild(O):v.innerHTML=Tt(we(M))}else if(T){v.dataset.morphicTextCode="";const O=this.createCodeText(o,this.currentMode,p),A=this.options.highlight===!1||(f=this.code[p])==null?void 0:f.highlighting;O!==null&&A?(hs(p,A.colors),v.innerHTML=vs(O,A)):O!==null?v.textContent=O:v.innerHTML=Tt(we(M))}else v.innerHTML=Tt(we(M));s.appendChild(v)}let d=!1;return s.addEventListener("pointerdown",p=>{d=gn(p.target)},!0),s.addEventListener("dragstart",p=>{var g;if(d){p.preventDefault();return}(g=p.dataTransfer)==null||g.setData(Ne,o.identifier)}),this.options.touch!==!1&&(us(),this.attachTouchDrag(s,o.identifier)),this.options.keyboard!==!1&&(s.tabIndex=0,s.setAttribute("role","button"),s.setAttribute("aria-label",this.tileName(o,c)),s.addEventListener("keydown",p=>{var g;p.key!=="Enter"&&p.key!==" "||p.target===s&&(p.preventDefault(),(g=this.onChoose)==null||g.call(this,o.identifier))})),s}tileName(o,e){var c,a;const{label:t}=this.options,n=typeof t=="function"?t(this.currentMode):t,s=n===void 0?void 0:o.elements[n];if(s!==void 0){const l=document.createElement("div");l.innerHTML=s;const d=(c=l.textContent)==null?void 0:c.trim();if(d)return d}const r=[];for(const l of e){const d=o.elements[l];if(d===void 0)continue;const h=pe(this.elementTypes[l]);if(h==="custom")continue;if(h==="code"){const p=this.createCodeText(o,this.currentMode,l);p!=null&&p.trim()&&r.push(p.trim());continue}const u=document.createElement("div");u.innerHTML=h==="image"?Lt(d,St(this.elementTypes[l])):d;const f=h==="image"?Array.from(u.querySelectorAll("img"),p=>p.alt).join(" ").trim():(a=u.textContent)==null?void 0:a.trim();f&&r.push(f)}return r.join(", ")||o.identifier}dropTargetAt(o,e){const t=document.elementFromPoint(o,e);if(!t)return;const n={element:this.workspaceContainer,drop:(s,r,c)=>this.createBlockAtPosition(s,r,c)};return[...this.dropTargets(),n].find(s=>s.element.contains(t))}attachTouchDrag(o,e){o.addEventListener("pointerdown",t=>{var C;if(t.pointerType==="mouse"||!t.isPrimary||gn(t.target))return;const n=o.getBoundingClientRect();let s,r,c={x:t.clientX,y:t.clientY};o.draggable=!1;let a={x:0,y:0},l=1,d=0;const h=()=>{if(s)return;s=o.cloneNode(!0),s.classList.add("morphic-drag-ghost"),s.removeAttribute("tabindex"),Object.assign(s.style,{position:"fixed",left:"0",top:"0",margin:"0",pointerEvents:"none",zIndex:"2147483647",transition:"none",animation:"none"}),this.container.appendChild(s);const T=s.getBoundingClientRect();s.style.left="100px",l=(s.getBoundingClientRect().left-T.left)/100||1,a={x:T.left,y:T.top},Object.assign(s.style,{left:`${(n.left-a.x)/l}px`,top:`${(n.top-a.y)/l}px`,width:`${n.width/l}px`}),f()},u=window.setTimeout(h,ks),f=()=>{!s||d||(d=requestAnimationFrame(()=>{var F,$;if(d=0,!s)return;s.style.transform=`translate(${(c.x-t.clientX)/l}px, ${(c.y-t.clientY)/l}px)`;const T=this.dropTargetAt(c.x,c.y);T!==r&&((F=r==null?void 0:r.leave)==null||F.call(r)),r=T,($=r==null?void 0:r.over)==null||$.call(r,c.x,c.y)}))},p=T=>{if(T.pointerId!==t.pointerId)return;c={x:T.clientX,y:T.clientY};const F=Math.abs(T.clientX-t.clientX),$=Math.abs(T.clientY-t.clientY);!s&&(F<gs||$>F)||(window.clearTimeout(u),h(),f())},g=T=>{s&&T.preventDefault()},v=T=>T.preventDefault(),w=T=>{var F,$;T.pointerId===t.pointerId&&(window.clearTimeout(u),o.removeEventListener("pointermove",p),o.removeEventListener("pointerup",w),o.removeEventListener("pointercancel",w),o.removeEventListener("touchmove",g),o.removeEventListener("contextmenu",v),o.draggable=!0,cancelAnimationFrame(d),(F=r==null?void 0:r.leave)==null||F.call(r),s&&(s.remove(),T.type==="pointerup"&&(($=this.dropTargetAt(T.clientX,T.clientY))==null||$.drop(e,T.clientX,T.clientY))))};(C=o.setPointerCapture)==null||C.call(o,t.pointerId),o.addEventListener("pointermove",p),o.addEventListener("pointerup",w),o.addEventListener("pointercancel",w),o.addEventListener("touchmove",g,{passive:!1}),o.addEventListener("contextmenu",v)})}ensurePreviewWorkspace(){var e;if(this.previewWorkspace)return this.previewWorkspace;this.previewContainer=document.createElement("div"),this.previewContainer.style.cssText="position:absolute;left:-9999px;top:-9999px;width:800px;height:600px;overflow:hidden;",document.body.appendChild(this.previewContainer);const o=this.workspace.options;return this.previewWorkspace=S.inject(this.previewContainer,{scrollbars:!1,media:o.pathToMedia,sounds:!1,renderer:o.renderer,rendererOverrides:o.rendererOverrides??void 0,theme:o.theme,rtl:o.RTL}),(e=this.onPreviewWorkspace)==null||e.call(this,this.previewWorkspace),this.previewWorkspace}syncPreviewFont(o){const e=this.ensurePreviewWorkspace();this.previewBase??(this.previewBase={theme:e.getTheme(),font:qo(e)});const t=Zo(this.container,[["morphic-block",`morphic-mode-${de(this.currentMode)}`],[`morphic-element-${de(o)}`],[e.getRenderer().getClassName(),e.getTheme().getClassName()]],this.previewBase.font);Qo(e,this.previewBase.theme,this.previewBase.font,t)}createPreviewBlock(o,e,t){var l;const n=this.ensurePreviewWorkspace(),s=n.newBlock(ke(o.identifier,this.definitions)),r=this.blockColors.get(o.identifier);r&&s.setColour(r);const c={mode:e,template:o.elements[t]??"",elementName:t,inputSlots:o.inputSlots};go({block:s,definition:o,view:c,mode:"block",context:"toolbox",elementTypes:this.elementTypes,resolveBlocklyType:d=>ke(d,this.definitions)});const a=Ge(this.behaviors[o.identifier]);return(l=a==null?void 0:a.onViewApplied)==null||l.call(a,s,{Blockly:S,workspace:n,element:t,mode:e,context:"toolbox",definition:o}),s}createCodeText(o,e,t){try{const n=this.createPreviewBlock(o,e,t),{code:s}=Vo(n.workspace,e,this.definitions,this.elementTypes,this.modes,t,{emptyStatements:!1});return n.dispose(!1),s}catch{return null}}createBlockPreviewSvg(o,e,t){try{const n=this.ensurePreviewWorkspace(),s=this.createPreviewBlock(o,e,t);for(const u of s.getDescendants(!1))u.initSvg(),u.queueRender();s.render();const r=s.getSvgRoot();if(!r)return s.dispose(!1),null;const c=r.getBBox(),a=r.cloneNode(!0),l=4,d=document.createElementNS("http://www.w3.org/2000/svg","svg"),h=Math.ceil(c.width+l*2);return this.widestBlock=Math.max(this.widestBlock,h),d.setAttribute("width",String(h)),d.setAttribute("height",String(Math.ceil(c.height+l*2))),d.setAttribute("viewBox",`${c.x-l} ${c.y-l} ${c.width+l*2} ${c.height+l*2}`),d.setAttribute("class",`${n.getRenderer().getClassName()} ${n.getTheme().getClassName()}`),d.style.direction="ltr",d.appendChild(a),s.dispose(!1),d}catch{return null}}createBlockAtPosition(o,e,t){const n=this.workspace,s=n.getInjectionDiv().getBoundingClientRect(),r=(e-s.left-n.scrollX)/n.scale,c=(t-s.top-n.scrollY)/n.scale,a=n.newBlock(ke(o,this.definitions));a.moveTo(new S.utils.Coordinate(r,c)),a.initSvg(),a.render()}resolveBlockIds(){return this.options.blocks??[...this.definitions.keys()]}resolveCategoryBlockIds(o,e){return o.blocks&&o.blocks.length>0?o.blocks.filter(t=>e.includes(t)):e.filter(t=>{var n,s;return((s=(n=this.definitions.get(t))==null?void 0:n.category)==null?void 0:s.toLowerCase())===o.name.toLowerCase()})}}function gn(i){if(!(i instanceof Element))return!1;const o=i.closest("button, a[href], input, select, textarea, [contenteditable]");return o!==null&&o.closest("[data-morphic-custom]")!==null}function et(i,o,e){var n;const t=[];if(i.blocks&&i.blocks.length>0)t.push(...i.blocks);else for(const s of o.values())((n=s.category)==null?void 0:n.toLowerCase())===i.name.toLowerCase()&&t.push(s.identifier);return e?t.filter(s=>e.includes(s)):t}function Xt(i,o){var n,s,r;if((i.kind??((n=i.categories)!=null&&n.length?"categoryToolbox":"flyoutToolbox"))==="categoryToolbox")return{kind:"categoryToolbox",contents:(i.categories??[]).filter(a=>et(a,o,i.blocks).length>0).map(a=>({kind:"category",name:a.name,colour:a.color,contents:et(a,o,i.blocks).map(l=>({kind:"block",type:ke(l,o)}))}))};if((s=i.categories)!=null&&s.length){const c=i.categories.filter(d=>et(d,o,i.blocks).length>0),a=[];return c.forEach((d,h)=>{const u=de(d.name);a.push({kind:"label",id:`morphic-category-${u}`,text:d.name,"web-class":`morphic-flyout-category-label morphic-category-${u}`});for(const f of kn(et(d,o,i.blocks)))a.push({kind:"block",type:ke(f,o)});h<c.length-1&&a.push({kind:"sep",gap:14})}),{kind:"flyoutToolbox",contents:a}}return{kind:"flyoutToolbox",contents:(i.blocks??kn(((r=i.categories)==null?void 0:r.flatMap(c=>et(c,o)))??[...o.keys()])).map(c=>({kind:"block",type:ke(c,o)}))}}function kn(i){return i.filter((o,e,t)=>t.indexOf(o)===e)}const ws=/(<img\b[^>]*?\bsrc\s*=\s*)(?:(["'])(.*?)\2|([^\s>"']+))/gi,ys=i=>i.replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,"&"),bs=i=>i.replace(/["'<>]/g,o=>`%${o.charCodeAt(0).toString(16).toUpperCase()}`);function Cs(i,o,e){let t=!1;const n=c=>{const a=e(c);if(!(a===void 0||a===c))return t=!0,a},s=Object.fromEntries(Object.entries(i.elements).map(([c,a])=>{const l=o[c],h=(typeof l=="string"?l:l==null?void 0:l.type)==="image"?Lt(a,St(l)):a;return h!==a&&(t=!0),[c,h.replace(ws,(u,f,p,g,v)=>{const w=n(ys(g??v??""));return w===void 0?u:`${f}"${bs(w)}"`})]})),r=i.fields?Object.fromEntries(Object.entries(i.fields).map(([c,a])=>{if(a.type!=="dropdown")return[c,a];const l=a.options.map(d=>typeof d=="object"&&!Array.isArray(d)&&typeof d.label=="object"&&d.label.src!==void 0?{...d,label:{...d.label,src:n(d.label.src)??d.label.src}}:d);return[c,{...a,options:l}]})):void 0;return t?{...i,elements:s,...r?{fields:r}:{}}:i}const Ss='<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>',Es='<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>',xs='<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>',Ts='<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>',Ls='<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>',Bs='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><line x1="4" y1="4" x2="12" y2="12"/><line x1="12" y1="4" x2="4" y2="12"/></svg>',$s='<svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor"><polygon points="4,3 13,8 4,13"/></svg>',Is='<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>',Ms='<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>',Os='<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>',As='<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>',Ds='<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>',Ns='<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>',re={viewLabel(){return{id:"view-label",render:i=>{const o=document.createElement("span");return o.className="morphic-toolbar-label",o.textContent=i.engine.getViewElement(i.view)??"",o}}},copy(){return{id:"copy",label:"Copy",title:"Copy block",icon:Ss,onClick:i=>{i.engine.copyActiveBlock(i.view)}}},paste(){return{id:"paste",label:"Paste",title:"Paste block",icon:Es,disabled:i=>!i.engine.hasClipboardContents(),onClick:i=>{i.engine.pasteActiveBlock(i.view)}}},undo(){return{id:"undo",label:"Undo",title:"Undo (block model)",icon:xs,onClick:i=>{var o;(o=i.engine.getWorkspace())==null||o.undo(!1)},disabled:i=>{var o;return!((o=i.engine.getWorkspace())!=null&&o.getUndoStack().length)}}},redo(){return{id:"redo",label:"Redo",title:"Redo (block model)",icon:Ts,onClick:i=>{var o;(o=i.engine.getWorkspace())==null||o.undo(!0)},disabled:i=>{var o;return!((o=i.engine.getWorkspace())!=null&&o.getRedoStack().length)}}},zoomIn(){return{id:"zoom-in",label:"Zoom in",title:"Zoom in",icon:Is,onClick:i=>i.engine.zoomPane(i.view,"in")}},zoomOut(){return{id:"zoom-out",label:"Zoom out",title:"Zoom out",icon:Ms,onClick:i=>i.engine.zoomPane(i.view,"out")}},zoomFit(){return{id:"zoom-fit",label:"Fit",title:"Reset zoom",icon:Os,onClick:i=>i.engine.zoomPane(i.view,"fit")}},deleteSelection(){return{id:"delete",label:"Delete",title:"Delete selected lines",icon:Bs,visible:i=>i.engine.getDeleteOptions(i.view).toolbarButton,disabled:i=>!i.engine.hasSelectedLines(i.view),onClick:i=>{i.engine.deleteSelectedLines(i.view)}}},clear(){return{id:"clear",label:"Clear",title:"Clear workspace",icon:Ls,onClick:i=>{var o;window.confirm("Clear workspace? This cannot be undone.")&&((o=i.engine.getWorkspace())==null||o.clear())}}},runCode(){return{id:"run",label:"Run",title:"Run generated code",icon:$s,onClick:i=>{i.engine.runJavaScript()}}},save(){return{id:"save",label:"Save",title:"Save workspace as JSON",icon:As,onClick:i=>{if(!i.engine.getWorkspace())return;const e=i.engine.serializeWorkspace(),t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),n=URL.createObjectURL(t),s=document.createElement("a");s.href=n,s.download="workspace.json",s.click(),URL.revokeObjectURL(n)}}},load(){return{id:"load",label:"Load",title:"Load workspace JSON",icon:Ds,onClick:i=>{const o=document.createElement("input");o.type="file",o.accept="application/json",o.addEventListener("change",async()=>{var t;const e=(t=o.files)==null?void 0:t[0];if(e)try{const n=await e.text(),s=JSON.parse(n);i.engine.loadWorkspace(s)}catch(n){window.alert(`Load failed: ${n instanceof Error?n.message:String(n)}`)}}),o.click()}}},reset(){return{id:"reset",label:"Reset",title:"Reset workspace",icon:Ns,onClick:i=>{var o;window.confirm("Reset workspace to empty? This cannot be undone.")&&((o=i.engine.getWorkspace())==null||o.clear())}}},readOnlyBadge(){return{id:"read-only",align:"right",render:()=>{const i=document.createElement("span");return i.className="morphic-toolbar-badge",i.textContent="read-only",i}}},spacer(){return{id:"spacer",render:()=>{const i=document.createElement("span");return i.className="morphic-toolbar-spacer",i}}},readOnlyDefaults(){return[re.viewLabel(),re.spacer(),re.copy(),re.zoomIn(),re.zoomOut(),re.zoomFit(),re.readOnlyBadge()]},defaultsFor(i,o=!1){if(o)return re.readOnlyDefaults();switch(i){case"workspace":return[re.viewLabel(),re.spacer(),re.undo(),re.redo(),re.copy(),re.paste(),re.zoomIn(),re.zoomOut(),re.zoomFit(),re.clear()];case"codespace":return[re.viewLabel(),re.spacer(),re.undo(),re.redo(),re.copy(),re.paste(),re.deleteSelection(),re.zoomIn(),re.zoomOut(),re.zoomFit(),re.clear()]}}};function vn(i,o,e){const t=o.items??re.defaultsFor(e.kind,e.readOnly),n=o.display??"icon";i.classList.add("morphic-toolbar"),i.setAttribute("data-morphic-kind",e.kind),i.setAttribute("data-morphic-view",e.view);const s=document.createElement("div");s.className="morphic-toolbar-left";const r=document.createElement("div");r.className="morphic-toolbar-right";const c=()=>{s.replaceChildren(),r.replaceChildren();let a=!1;for(const l of t){if(l.visible&&!l.visible(e))continue;if(l.id==="spacer"){a=!0;continue}(l.align==="right"||a&&l.align!=="left"?r:s).appendChild(Vs(l,n,e))}};return i.replaceChildren(s,r),c(),{refresh:c,kind:e.kind,view:e.view,dispose:()=>i.replaceChildren()}}function Vs(i,o,e){if(i.render){const n=i.render(e);if(typeof n=="string"){const s=document.createElement("span");return s.className="morphic-toolbar-item",s.dataset.toolbarId=i.id,s.textContent=n,s}return n.classList.add("morphic-toolbar-item"),n.dataset.toolbarId=i.id,n}const t=document.createElement("button");return t.className="morphic-toolbar-item",t.dataset.toolbarId=i.id,t.type="button",i.title&&(t.title=i.title),_s(t,i,o),i.disabled&&i.disabled(e)&&(t.disabled=!0),i.onClick&&t.addEventListener("click",()=>i.onClick(e)),t}function _s(i,o,e){const t=e!=="label"&&!!o.icon,n=e!=="icon"&&!!o.label,s=t||e==="icon"&&!o.label,r=n||e==="label"&&!o.icon;if(s&&o.icon){const c=document.createElement("span");c.className="morphic-toolbar-icon",c.innerHTML=o.icon,i.appendChild(c)}if(r&&o.label){const c=document.createElement("span");c.className="morphic-toolbar-text",c.textContent=o.label,i.appendChild(c)}!i.title&&o.label&&(i.title=o.label),!i.childNodes.length&&o.label&&(i.textContent=o.label)}function wn(i,o){return o.includes("{")?{mode:i,cssText:o}:{mode:i,href:o}}function Fs(i){const o=[];for(const[e,t]of Object.entries(i)){const s=(e.split("/").pop()??e).replace(/\.css$/i,""),r=typeof t=="string"?t:typeof t=="object"&&t!==null&&"default"in t?String(t.default):void 0;r&&o.push(wn(s,r))}return o}function yn(i){if(i.length===1)throw new Error(i[0]);if(i.length>1)throw new Error(`[MorphicBlocks] Invalid definitions:
|
|
46
|
+
- ${i.join(`
|
|
47
|
+
- `)}`)}const Ps="blockly-media/",bn=new Set;function Rs(i,o){if(bn.has(i)||typeof Image>"u")return;bn.add(i);const e=new Image;e.onerror=()=>{o(`[MorphicBlocks] Blockly's media is missing at "${i}", so icons are not shown and sounds stay silent. Copy it there with the bundler plugin (morphic-blocks/vite and others) or "morphic-blocks copy-media <folder>", or point blockly.media to where it is.`)},e.src=`${i}sprites.png`}const Oe=i=>i.onWarning??(o=>console.warn(o)),Ve=new WeakMap,ze=new Map;function Hs(i){const o=i.setInsertionMarker;i.setInsertionMarker=function(e){var t;if(o.call(this,e),!!e)for(const n of this.inputList)(t=n.connection)==null||t.setShadowState(null)}}class js extends EventTarget{constructor(e,t={}){super();y(this,"definitions");y(this,"loadedDefinitions");y(this,"behaviors");y(this,"elementTypes");y(this,"formatElementTypes");y(this,"styles",new ds);y(this,"registeredBlockTypes",new Set);y(this,"toolbars",new Set);y(this,"toolbarsBlocklyListener");y(this,"lastCopyData");y(this,"mountConfig");y(this,"workspace");y(this,"flyoutWorkspace");y(this,"toolboxCanvas");y(this,"tileDropTargets",new Set);y(this,"codeEditor");y(this,"views",new Set);y(this,"viewWorkspaceElements",new WeakMap);y(this,"viewCount",0);y(this,"selectionSync");y(this,"toolboxDefinition");y(this,"blockCategoryIndex",new Map);y(this,"appliedWorkspaceClasses",[]);y(this,"appliedToolboxFlyoutClasses",[]);y(this,"appliedToolboxShellClasses",[]);y(this,"headlessWorkspaceHost");y(this,"workspaceResizeObserver");y(this,"activePreset");y(this,"baseTheme");y(this,"baseFont");y(this,"mountGeneration",0);y(this,"selectionSyncOptions");y(this,"formatModes");y(this,"formatPresets");y(this,"formatViews");y(this,"formatCode");y(this,"formatHasHighlighting");y(this,"formatCategories");y(this,"formatBlockSets");y(this,"blockSetLists",new Map);y(this,"activeBlockSet");y(this,"categoriesShown",!0);y(this,"onWorkspaceChange",e=>{if(!this.workspace||!this.mountConfig||e.workspaceId!==this.workspace.id||e.type!==S.Events.BLOCK_CREATE)return;const t=e;for(const n of t.ids??[]){const s=this.workspace.getBlockById(n);if(!s)continue;const r=this.definitions.get(he(s.type));if(!r)continue;const c=this.mountConfig.workspaceElement,a=s;if(a.__morphicMode===c&&a.__morphicContext==="workspace"&&s.getSvgRoot()){wo(s,c,"workspace"),this.styleBlock(s,r);continue}this.applyView(s,r,c,"workspace"),s.getSvgRoot()||this.deferApplyView(n,c,"workspace")}});y(this,"onFlyoutChange",e=>{if(!this.flyoutWorkspace||!this.mountConfig||e.workspaceId!==this.flyoutWorkspace.id||e.type!==S.Events.BLOCK_CREATE)return;const t=e;for(const n of t.ids??[]){const s=this.flyoutWorkspace.getBlockById(n);if(!s)continue;const r=this.definitions.get(he(s.type));r&&(this.applyView(s,r,this.mountConfig.toolboxMode,"toolbox"),s.getSvgRoot()||this.deferApplyView(n,this.mountConfig.toolboxMode,"toolbox"))}});y(this,"onStylesLoaded",()=>this.refresh());const n=e;this.definitions=Yo(Xo(Ko(n.blocks,n.elementTypes??{}))),this.loadedDefinitions=new Map(this.definitions),this.behaviors=t,this.formatElementTypes=n.elementTypes??{},this.elementTypes=Ct(this.formatElementTypes,n.code),this.formatModes=n.modes,this.formatPresets=n.presets,this.formatViews=n.views,this.formatCode=n.code,this.formatHasHighlighting="highlighting"in n,this.formatCategories=n.categories,this.formatBlockSets=n.blockSets}mount(e){var E,M,O,A,N,V,m,x,B,Q;this.dispose(),this.resolveAssetUrls(e.assetUrl);const t={...e,modes:(E=e.modes??this.formatModes)==null?void 0:E.slice(),presets:e.presets??this.formatPresets,code:e.code??this.formatCode,toolbox:e.toolbox||this.formatCategories?{...e.toolbox,categories:((M=e.toolbox)==null?void 0:M.categories)??this.formatCategories}:void 0},n=t.modesFolder?Fs(t.modesFolder):[],s=[...n,...Object.entries(t.modeStyles??{}).filter(([P])=>!n.some(ie=>ie.mode===P)).map(([P,ie])=>wn(P,ie))];this.elementTypes=Ct(this.formatElementTypes,t.code),this.validateDefinitions(t),this.validatePresets(t);const r=(O=t.presets)!=null&&O.length?t.presets.find(P=>P.name===t.preset)??t.presets[0]:void 0;if(t.preset&&!r)throw new Error(`MorphicBlocks.mount: unknown preset "${t.preset}".`);this.blockSetLists=jt(this.formatBlockSets,P=>this.definitions.has(P)).lists,this.activeBlockSet=r==null?void 0:r.blockSet,this.categoriesShown=(r==null?void 0:r.categories)!==!1;const c=(t.modes??[]).map(P=>P.name),a=c[0]??((A=s[0])==null?void 0:A.mode)??"default",l=r?r.toolbox:a,d=Ut(t.views??this.formatViews),h={...t.containers};t.workspaceContainer&&(h.workspace??(h.workspace=t.workspaceContainer)),t.codespaceContainer&&(h.codespace??(h.codespace=t.codespaceContainer)),this.validateViews(d,h);const u=Object.keys(d).find(P=>d[P].kind==="workspace"&&h[P]),f=this.defaultElement(t.modes??[]),p=P=>(P?r==null?void 0:r.views[P]:void 0)??f,g=u?p(u):f,v=u&&h[u]||this.createHeadlessHost(),w={...t,modeStyles:s,workspaceElement:g,toolboxMode:l,viewDeclarations:d,viewContainers:h,programView:u,workspaceHost:v,canvasToolbox:t.canvasToolbox??!!t.toolboxContainer};this.mountConfig=w,this.styles.validateModeCoverage(s,c,Oe(t)),(N=w.modes)!=null&&N.length&&this.styles.ensureModeVisibilityStyles(w.modes),this.styles.ensureStyles(w.baseStyle,s);for(const P of Array.from(document.head.querySelectorAll('link[data-morphic-source^="mode:"]')))P.sheet||P.addEventListener("load",this.onStylesLoaded,{once:!0});(V=document.fonts)==null||V.addEventListener("loadingdone",this.onStylesLoaded),this.blockCategoryIndex=this.createCategoryIndex(w.toolbox,w),this.styles.ensureCategoryStyles(((m=w.toolbox)==null?void 0:m.categories)??[]),this.styles.ensureWorkspaceStyles(),this.registerBlocks(),this.toolboxDefinition=this.resolveToolboxDefinition(w);const C=typeof this.toolboxDefinition=="object"&&"kind"in this.toolboxDefinition?this.toolboxDefinition.kind:void 0;!w.canvasToolbox&&C==="categoryToolbox"&&((x=w.presets)!=null&&x.some(P=>P.categories===!1))&&Oe(w)(`[MorphicBlocks] Blockly's category toolbox keeps its categories; "categories": false in a preset works with the HTML toolbox (toolboxContainer) or toolboxLayout "flyout".`);const T=w.blockly??{},F=u?d[u].editable!==!1:!0;if(this.workspace=S.inject(w.workspaceHost,{...T,...F?{}:{readOnly:!0},...u&&d[u].rtl!==void 0?{rtl:d[u].rtl}:{},media:T.media??Ps,...w.canvasToolbox?{}:{toolbox:this.toolboxDefinition}}),co(this.workspace),In(this.workspace),this.workspace.addChangeListener(this.onWorkspaceChange),Ve.set(this.workspace,this),this.baseTheme=this.workspace.getTheme(),this.baseFont=qo(this.workspace),u&&Rs(this.workspace.options.pathToMedia,Oe(t)),u&&typeof ResizeObserver<"u"){const P=this.workspace;this.workspaceResizeObserver=new ResizeObserver(()=>S.svgResize(P)),this.workspaceResizeObserver.observe(v)}this.applyWorkspaceContainerClass(),this.syncWorkspaceFont(),this.refreshToolbox(),this.bindFlyoutWorkspace(),this.renderWorkspaceBlocks(),this.renderFlyoutBlocks(),t.toolboxContainer&&this.mountToolbox(t.toolboxContainer);const $=[];for(const[P,ie]of Object.entries(d)){const ce=h[P];if(!ce||P===u)continue;const oe=this.addView({kind:ie.kind,name:P,container:ce,element:p(P),editable:ie.editable,rtl:ie.rtl,delete:ie.delete,theme:((B=t.themes)==null?void 0:B[P])??t.editorTheme});$.push(oe.ready)}return this.activePreset=r,this.applyPresetClasses(),r&&((Q=w.onPresetApplied)==null||Q.call(w,r)),this.mountViews(t,$,++this.mountGeneration)}async mountViews(e,t,n){var a;const s=[...t];if(e.codeEditorContainer){const l=e.editorTheme?{theme:e.editorTheme}:void 0;s.push(this.mountCodeEditor(e.codeEditorContainer,l).then(()=>{n===this.mountGeneration&&this.hideCodeEditor()}))}if(await Promise.all(s),n!==this.mountGeneration||!this.workspace)return;for(const[l,d]of Object.entries(e.toolbars??{}))d&&this.resolveView(l)&&this.mountToolbar(d,{view:l});const r=Object.keys(((a=this.mountConfig)==null?void 0:a.viewContainers)??{}).filter(l=>this.resolveView(l)).length+(e.codeEditorContainer?1:0),c=e.selectionSync??r>1;c&&this.hasTextEditor()&&this.enableSelectionSync(typeof c=="object"?c:void 0)}applyPresetClasses(){var t,n;const e=(t=this.activePreset)==null?void 0:t.name;(n=this.mountConfig)!=null&&n.programView&&dt(this.mountConfig.workspaceHost,e);for(const s of this.views)dt(s.container,e)}hasTextEditor(){return!!this.codeEditor||[...this.views].some(e=>e.editor)}get codespace(){for(const e of this.views)if(e.kind==="codespace"&&e.editable!==!1)return e.editor}getPresets(){var e;return[...((e=this.mountConfig)==null?void 0:e.presets)??[]]}getActivePreset(){return this.activePreset}applyPreset(e){var r,c;if(!this.mountConfig||!this.workspace)throw new Error("MorphicBlocks must be mounted before applyPreset can be used.");const t=this.mountConfig.presets??[],n=typeof e=="number"?t[e]:t.find(a=>a.name===e);if(!n)throw new Error(`applyPreset: unknown preset "${e}".`);const s=Object.fromEntries(Object.entries(n.views).filter(([a])=>{var l;return((l=this.mountConfig)==null?void 0:l.viewDeclarations[a])||this.resolveView(a)}));return this.show({toolbox:n.toolbox,views:s,blockSet:n.blockSet??null,categories:n.categories!==!1}),this.activePreset=n,this.applyPresetClasses(),(c=(r=this.mountConfig).onPresetApplied)==null||c.call(r,n),n}validateDefinitions(e){var r;const{errors:t,warnings:n}=Wt({definitions:this.definitions,elementTypes:this.formatElementTypes,behaviors:this.behaviors,modes:e.modes,presets:e.presets,code:e.code,categories:(r=e.toolbox)==null?void 0:r.categories,views:Object.keys(e.views??this.formatViews??{}),blockSets:this.formatBlockSets}),s={previewContainer:'the preview is a codespace that cannot be edited: declare it in "views" ({ "preview": { "kind": "codespace", "editable": false } }) and pass containers: { preview: element }',previewTheme:"themes: { <view>: theme } sets a single text view's colours",toolbarContainers:"toolbars: { <view>: element }, by view name",codespace:'the codespace options sit on its view in "views": { "codespace": { "kind": "codespace", "delete": { … } } }'};for(const[c,a]of Object.entries(s))c in e&&t.push(`mount option "${c}" moved in 0.4.0: ${a}.`);if(t.push(...rn(e.presets,this.formatHasHighlighting||"highlighting"in e)),n.length>0&&Oe(e)(`[MorphicBlocks] Definition warnings:
|
|
31
48
|
- ${n.join(`
|
|
32
49
|
- `)}`),t.length>0)throw new Error(`[MorphicBlocks] Invalid definitions:
|
|
33
50
|
- ${t.join(`
|
|
34
|
-
- `)}`)}validatePresets(e){const t=e.presets??[];if(t.length===0)return;const n=e.modes??[],s=new Map(n.map(c=>[c.name,c])),r=new Set;for(const c of t){if(r.has(c.name))throw new Error(`Preset "${c.name}" is defined more than once.`);if(r.add(c.name),!c.workspace&&!c.codespace)throw new Error(`Preset "${c.name}": at least one of workspace or codespace must be set.`);if(c.codespace&&!e.codespaceContainer)throw new Error(`Preset "${c.name}" uses a codespace but no codespaceContainer was provided.`);const a=Ne(c.toolbox),d=[["toolbox",a.mode],["workspace",c.workspace],["codespace",c.codespace],["preview",c.preview]];for(const[l,h]of d){if(h===void 0)continue;const u=s.get(h);if(!u)throw new Error(`Preset "${c.name}": unknown mode "${h}" for ${l}.`);if((l==="codespace"||l==="preview")&&X(u,this.elementTypes)===void 0)throw new Error(`Preset "${c.name}": mode "${h}" has no code element to render in the ${l}.`)}for(const[l,h]of Object.entries(c.views??{}))if(!s.has(h))throw new Error(`Preset "${c.name}": unknown mode "${h}" for view "${l}".`);for(const l of Object.values(a.render??{}))if(l!=="block"&&l!=="text")throw new Error(`Preset "${c.name}": toolbox render values must be "block" or "text".`)}}dispose(){var e,t,n,s,r,c,a,d;for(const[l,h]of be)h===this&&be.delete(l);(e=this.workspaceResizeObserver)==null||e.disconnect(),this.workspaceResizeObserver=void 0,(t=document.fonts)==null||t.removeEventListener("loadingdone",this.onStylesLoaded),this.activePreset=void 0,(n=this.selectionSync)==null||n.disable(),this.selectionSync=void 0,(s=this.codeEditor)==null||s.dispose(),this.codeEditor=void 0,(r=this.codespaceDropTeardown)==null||r.call(this),this.codespaceDropTeardown=void 0,(c=this.codespace)==null||c.dispose(),this.codespace=void 0,(a=this.previewEditor)==null||a.dispose(),this.previewEditor=void 0,this.previewHost=void 0;for(const l of this.views)this.disposeView(l);this.views.clear(),(d=this.toolboxCanvas)==null||d.dispose(),this.toolboxCanvas=void 0;for(const l of[...this.toolbars])l.dispose();this.flyoutWorkspace&&(this.flyoutWorkspace.removeChangeListener(this.onFlyoutChange),this.flyoutWorkspace=void 0),this.workspace&&(this.workspace.removeChangeListener(this.onWorkspaceChange),this.workspace.dispose(),this.workspace=void 0),this.headlessWorkspaceHost&&(this.headlessWorkspaceHost.remove(),this.headlessWorkspaceHost=void 0),this.mountConfig=void 0,this.baseTheme=void 0,this.baseFont=void 0,this.toolboxDefinition=void 0,this.blockCategoryIndex.clear(),this.appliedWorkspaceClasses=[],this.appliedToolboxFlyoutClasses=[],this.appliedToolboxShellClasses=[]}mountToolbox(e,t){var r;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before mountToolbox can be used.");(r=this.toolboxCanvas)==null||r.dispose(),this.styles.ensureToolbarStyles(),this.mountConfig.canvasToolbox||this.workspace.updateToolbox({kind:"flyoutToolbox",contents:[]});const n=this.mountConfig.toolbox,s={...t,blocks:(t==null?void 0:t.blocks)??(n==null?void 0:n.blocks),categories:(t==null?void 0:t.categories)??(n==null?void 0:n.categories),modeLabel:(t==null?void 0:t.modeLabel)??(n==null?void 0:n.modeLabel),highlight:(t==null?void 0:t.highlight)??(n==null?void 0:n.highlight),touch:(t==null?void 0:t.touch)??(n==null?void 0:n.touch),keyboard:(t==null?void 0:t.keyboard)??(n==null?void 0:n.keyboard)};this.toolboxCanvas=new pt({container:e,workspaceContainer:this.mountConfig.workspaceHost,workspace:this.workspace,definitions:this.definitions,blockColors:this.buildBlockColorMap(),behaviors:this.behaviors,elementTypes:this.elementTypes,mode:this.mountConfig.toolboxMode,render:this.mountConfig.toolboxRender,modes:this.mountConfig.modes,code:this.mountConfig.code,options:s,onPreviewWorkspace:c=>re.set(c,this),dropTargets:()=>[...this.tileDropTargets],onChoose:c=>this.addBlockFromTile(c)})}refresh(){var e;if(!(!this.workspace||!this.mountConfig)){this.syncWorkspaceFont(),Oe(this.workspace);for(const t of this.views)t.workspace&&(this.syncFontOf(t.workspace,t.container),Oe(t.workspace));(e=this.toolboxCanvas)==null||e.rerender(this.mountConfig.toolboxMode,this.mountConfig.toolboxRender)}}getWorkspace(){return this.workspace}getAvailableModes(){var e;return(((e=this.mountConfig)==null?void 0:e.modes)??[]).map(t=>t.name)}getWorkspaceMode(){var e;return(e=this.mountConfig)==null?void 0:e.workspaceMode}getCodespaceMode(){var e,t;return((e=this.mountConfig)==null?void 0:e.codespaceMode)??((t=this.mountConfig)==null?void 0:t.workspaceMode)}getPreviewMode(){var e;return(e=this.mountConfig)==null?void 0:e.previewMode}setModeElements(e,t){var h,u,k,v,w,b,g;if(!this.mountConfig||!this.workspace)throw new Error("MorphicBlocks must be mounted before setModeElements can be used.");const n=this.mountConfig.modes??[],s=n.findIndex(y=>y.name===e);if(s===-1)throw new Error(`setModeElements: unknown mode "${e}".`);const r=t.filter(y=>!(y in this.elementTypes));if(r.length>0)throw new Error(`setModeElements: unknown elements ${r.map(y=>`"${y}"`).join(", ")}.`);const c={...n[s],elements:[...t]};if((!!this.mountConfig.codespaceContainer&&e===this.getCodespaceMode()||e===this.mountConfig.previewMode||[...this.views].some(y=>y.mode===e))&&X(c,this.elementTypes)===void 0)throw new Error(`setModeElements: mode "${e}" is shown in a codespace or preview and needs a code element.`);const d=n.map((y,C)=>C===s?c:y);this.validatePresets({...this.mountConfig,modes:d});const l=n.slice();n[s]=c,this.styles.ensureModeVisibilityStyles(n,l),e===this.mountConfig.toolboxMode&&((h=this.toolboxCanvas)==null||h.rerender(this.mountConfig.toolboxMode,this.mountConfig.toolboxRender),this.renderFlyoutBlocks()),e===this.mountConfig.workspaceMode&&(this.syncWorkspaceFont(),this.renderWorkspaceBlocks()),(u=this.codespace)==null||u.setHighlightRules(this.resolveHighlightRules("codespace")),(k=this.previewEditor)==null||k.setHighlightRules(this.resolveHighlightRules("preview")),(v=this.codespace)==null||v.refresh(),(w=this.previewEditor)==null||w.refresh();for(const y of this.views)y.mode===e&&(y.workspace&&(this.styleWorkspaceView(y),this.renderWorkspaceView(y)),(b=y.editor)==null||b.setHighlightRules(this.highlightRulesFor(y.mode)),(g=y.editor)==null||g.refresh())}modeDef(e){var t;if(e)return(((t=this.mountConfig)==null?void 0:t.modes)??[]).find(n=>n.name===e)}getActivePrimarySourceElement(){const e=this.modeDef(this.getCodespaceMode());if(e)return X(e,this.elementTypes)}getActivePreviewElement(){var t;const e=this.modeDef((t=this.mountConfig)==null?void 0:t.previewMode);if(e)return X(e,this.elementTypes)}mountToolbar(e,t){if(!this.workspace)throw new Error("MorphicBlocks must be mounted before mountToolbar can be used.");const n=t.view??t.pane;if(!n)throw new Error("mountToolbar: set `view` (or `pane`).");const s=["workspace","codespace","preview"],r=this.resolveView(n),c=(r==null?void 0:r.kind)??s.find(h=>h===n);if(!c)throw new Error(`mountToolbar: no view named "${n}".`);this.styles.ensureToolbarStyles();const a=t.items??(c==="workspace"&&(r!=null&&r.readOnly)?A.readOnlyDefaults():void 0),d=kt(e,{...t,items:a},{engine:this,pane:c,view:n,getText:()=>this.toolbarTextFor(n),refresh:()=>this.toolbarRefreshFor(n)});this.toolbars.add(d),this.ensureToolbarBlocklyListener();const l=d.dispose;return d.dispose=()=>{this.toolbars.delete(d),this.toolbars.size===0&&this.teardownToolbarBlocklyListener(),l()},d}toolbarTextFor(e){var n,s;const t=this.resolveView(e);if((t==null?void 0:t.kind)==="codespace")return((n=t.editor)==null?void 0:n.getValue())??this.generateCodespaceText().code;if((t==null?void 0:t.kind)==="preview")return((s=t.editor)==null?void 0:s.getValue())??"";if((t==null?void 0:t.kind)==="workspace"&&t.readOnly)return this.generateModeText(t.mode).code;if(this.codespace)return this.codespace.getValue();try{return this.generateJavaScript()}catch{return""}}toolbarRefreshFor(e){var t,n;(n=(t=this.resolveView(e))==null?void 0:t.editor)==null||n.refresh()}runJavaScript(e){var k,v,w;let t="",n,s=null;const r=[],c=(e==null?void 0:e.console)??(e!=null&&e.logToConsole?console:void 0),a=this.getActivePrimarySourceElement(),d=a?(w=(v=(k=this.mountConfig)==null?void 0:k.code)==null?void 0:v[a])==null?void 0:w.values:void 0,l=b=>(...g)=>{r.push({level:b,text:g.map(y=>ut(y,d)).join(" ")}),c&&(c[b]??c.log).apply(c,g)},h={log:l("log"),warn:l("warn"),error:l("error")};try{t=this.generateJavaScript(),n=new Function("console",t)(h)}catch(b){s=b instanceof Error?b:new Error(String(b))}const u={code:t,result:n,error:s,output:r};return this.dispatchEvent(new CustomEvent("morphic-run",{detail:u})),u}hasClipboardContents(){return!!this.lastCopyData}copyActiveBlock(e){var s;const t=this.resolveActiveBlock(e);if(!t)return!1;const n=t.toCopyData();if(!n)return!1;this.lastCopyData=n;try{const r=this.toolbarTextFor(e==="workspace"?"codespace":e);r&&((s=navigator.clipboard)==null||s.writeText(r))}catch{}for(const r of this.toolbars)r.refresh();return!0}pasteActiveBlock(e){return!this.lastCopyData||!this.workspace?!1:x.clipboard.paste(this.lastCopyData,this.workspace)!==null}resolveActiveBlock(e){var a,d,l;const t=x.common.getSelected();if(t&&"id"in t&&((a=this.workspace)!=null&&a.getBlockById(t.id)))return t;const n=(d=this.resolveView(e))==null?void 0:d.editor;if(!n)return null;const s=n.getCursorLine();let r=null;for(const[h,u]of n.metadata)if(u.startLine<=s&&u.endLine>=s){const k=u.endLine-u.startLine;(!r||k<r.size)&&(r={id:h,size:k})}return(r?(l=this.workspace)==null?void 0:l.getBlockById(r.id):null)??null}serializeWorkspace(){return this.workspace?x.serialization.workspaces.save(this.workspace):null}loadWorkspace(e){this.workspace&&(this.workspace.clear(),x.serialization.workspaces.load(e,this.workspace))}zoomPane(e,t){var r;const n=this.resolveView(e),s=n==null?void 0:n.workspace;if(s){t==="in"?s.zoomCenter(1):t==="out"?s.zoomCenter(-1):s.zoomToFit();return}(r=n==null?void 0:n.editor)==null||r.adjustZoom(t)}ensureToolbarBlocklyListener(){if(this.toolbarsBlocklyListener||!this.workspace)return;const e=t=>{for(const n of this.toolbars)n.refresh()};this.toolbarsBlocklyListener=e,this.workspace.addChangeListener(e)}teardownToolbarBlocklyListener(){!this.toolbarsBlocklyListener||!this.workspace||(this.workspace.removeChangeListener(this.toolbarsBlocklyListener),this.toolbarsBlocklyListener=void 0)}setModes(e){var t,n,s,r,c,a;if(!this.mountConfig||!this.workspace)throw new Error("MorphicBlocks must be mounted before setModes can be used.");for(const[d,l]of[["workspaceMode",e.workspaceMode],["toolboxMode",e.toolboxMode],["codespaceMode",e.codespaceMode],["previewMode",e.previewMode]])if(typeof l=="string"&&!this.modeDef(l))throw new Error(`setModes: unknown mode "${l}" for ${d}.`);if(typeof e.codespaceMode=="string"&&!this.mountConfig.codespaceContainer)throw new Error("setModes: codespaceMode requires a codespaceContainer at mount.");e.workspaceMode&&(this.mountConfig.workspaceMode=e.workspaceMode),e.codespaceMode!==void 0&&(this.mountConfig.codespaceMode=e.codespaceMode??void 0),e.previewMode!==void 0&&(this.mountConfig.previewMode=e.previewMode??void 0),e.toolboxRender!==void 0&&(this.mountConfig.toolboxRender=e.toolboxRender??void 0),(e.toolboxMode||e.toolboxRender!==void 0)&&(e.toolboxMode&&(this.mountConfig.toolboxMode=e.toolboxMode),(t=this.toolboxCanvas)==null||t.rerender(this.mountConfig.toolboxMode,this.mountConfig.toolboxRender)),e.workspaceMode&&(this.applyWorkspaceContainerClass(),this.syncWorkspaceFont(),this.renderWorkspaceBlocks()),this.applyTextViewClasses(),this.refreshToolbox(),this.bindFlyoutWorkspace(),this.renderFlyoutBlocks(),(n=this.codespace)==null||n.setHighlightRules(this.resolveHighlightRules("codespace")),(s=this.previewEditor)==null||s.setHighlightRules(this.resolveHighlightRules("preview")),(r=this.codespace)==null||r.refresh(),(c=this.previewEditor)==null||c.refresh();for(const d of this.toolbars)d.refresh();(a=this.selectionSync)==null||a.clearAll()}resolveHighlightRules(e){var n,s;if(!this.mountConfig)return;const t=e==="codespace"?this.getActivePrimarySourceElement():this.getActivePreviewElement();if(t)return(s=(n=this.mountConfig.code)==null?void 0:n[t])==null?void 0:s.highlighting}generateJavaScript(){if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before generateJavaScript can be used.");return ro(this.workspace,this.definitions,this.behaviors,this.mountConfig.javascript)}generateJavaScriptWithMetadata(){if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before generateJavaScriptWithMetadata can be used.");return co(this.workspace,this.definitions,this.behaviors,this.mountConfig.javascript)}async mountCodeEditor(e,t){var s;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before mountCodeEditor can be used.");(s=this.codeEditor)==null||s.dispose(),this.codeEditor=new ge(e,this.workspace,()=>this.generateJavaScriptWithMetadata(),t,!0);const n=this.codeEditor;await n.mount(),this.codeEditor===n&&this.refreshSelectionSync()}async mountCodespace(e){var s,r;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before mountCodespace can be used.");if(!this.mountConfig.codespaceContainer)throw new Error("mountCodespace requires a codespaceContainer to be passed to mount().");(s=this.codespace)==null||s.dispose(),(r=this.codespaceDropTeardown)==null||r.call(this);const t={...e,onDelete:(e==null?void 0:e.onDelete)??(c=>this.codespace&&this.deleteBlockAtCodespaceLine(this.codespace,c)),canDragBlock:(e==null?void 0:e.canDragBlock)??(c=>this.canMoveInCodespace(c)),highlightRules:(e==null?void 0:e.highlightRules)??this.resolveHighlightRules("codespace"),onPlaceholderApply:(e==null?void 0:e.onPlaceholderApply)??((c,a)=>this.applyPlaceholderEdit(c,a))};this.applyTextViewClasses(),this.codespace=new ge(this.mountConfig.codespaceContainer,this.workspace,()=>this.generateCodespaceText(),t);const n=this.codespace;await n.mount(),this.codespace===n&&(this.codespaceDropTeardown=this.attachCodespaceDropTarget(n,this.mountConfig.codespaceContainer,this.workspace),this.refreshSelectionSync())}attachCodespaceDropTarget(e,t,n){const s=p=>{var T;const S=(T=p.dataTransfer)==null?void 0:T.types;return S?S.includes(se)||S.includes(Se):!1},r=()=>{e.hideDropIndicator(),e.hideValueSlotHighlight()},c=(p,S)=>{const T=this.computeCodespaceDrop(e,p,S);if(!T){r();return}T.indicator.kind==="line"?(e.showDropIndicator(T.indicator.line,T.indicator.position),e.hideValueSlotHighlight()):(e.showValueSlotHighlight(T.indicator.from,T.indicator.to),e.hideDropIndicator())},a=p=>{s(p)&&(p.preventDefault(),c(p.clientX,p.clientY))},d=p=>{const S=p.relatedTarget;S&&t.contains(S)||r()},l=p=>{var S,T;s(p)&&(p.preventDefault(),h(p.clientX,p.clientY,(S=p.dataTransfer)==null?void 0:S.getData(se),(T=p.dataTransfer)==null?void 0:T.getData(Se)))},h=(p,S,T,M)=>{r();const B=this.computeCodespaceDrop(e,p,S);if(!B)return;let D=null;if(T)D=n.newBlock(U(T,this.definitions)),this.placeOrphanBelowTops(D),D.initSvg(),D.render();else if(M){if(D=n.getBlockById(M),!D)return}else return;const P=this.fitOrLoose(n,D,B);if(!P){T&&D.dispose(!1);return}let $=!1;x.Events.setGroup(!0);try{if(M&&D.getParent()&&D.unplug(!0),P.target.kind==="top")this.placeAtTopIndex(n,D,P.target.index),$=!0;else if(P.target.kind==="statement"){if(D.previousConnection){const O=n.getBlockById(P.target.targetBlockId);O&&O!==D&&(this.connectStatement(D,O,P.target.position),$=!0)}}else if(P.target.kind==="into-slot"){if(D.previousConnection){const O=n.getBlockById(P.target.parentBlockId);O&&O!==D&&(this.connectIntoSlot(D,O,P.target.inputName),$=!0)}}else if(P.target.kind==="value-slot"){if(D.outputConnection){const O=n.getBlockById(P.target.parentBlockId);O&&O!==D&&!this.isDescendantOf(O,D)&&($=this.connectIntoValueSlot(D,O,P.target.inputName))}!$&&T&&D.dispose(!1)}}finally{x.Events.setGroup(!1)}!$&&D.workspace&&!D.getParent()&&this.placeOrphanBelowTops(D),x.svgResize(n)};let u=null;const k=3,v=p=>p.button===2||p.button===0&&p.ctrlKey,w=p=>{if(!u)return;if(!u.dragging){const T=Math.abs(p.clientX-u.startX),M=Math.abs(p.clientY-u.startY);if(T+M<k)return;u.dragging=!0}const S=this.computeCodespaceDrop(e,p.clientX,p.clientY);if(!S){e.hideDropIndicator(),e.hideValueSlotHighlight();return}S.indicator.kind==="line"?(e.showDropIndicator(S.indicator.line,S.indicator.position),e.hideValueSlotHighlight()):(e.showValueSlotHighlight(S.indicator.from,S.indicator.to),e.hideDropIndicator())},b=p=>{window.removeEventListener("mousemove",w),window.removeEventListener("mouseup",b),e.hideDropIndicator(),e.hideValueSlotHighlight();const S=u;if(u=null,Ge(void 0),!(S!=null&&S.dragging))return;const T=this.computeCodespaceDrop(e,p.clientX,p.clientY);if(!T)return;const M=n.getBlockById(S.sourceId);M&&this.applyRightDragMove(n,M,T)},g=p=>{if(!v(p))return;const S=e.charAtCoords(p.clientX,p.clientY);if(S==null)return;const T=this.findInnermostBlockAtChar(e,S);T&&(p.preventDefault(),p.stopPropagation(),u={sourceId:T.id,startX:p.clientX,startY:p.clientY,dragging:!1},Ge(T.id),window.addEventListener("mousemove",w),window.addEventListener("mouseup",b))},y=p=>{p.preventDefault()},C=p=>{if(u)return;const S=e.charAtCoords(p.clientX,p.clientY);if(S==null){e.setHoverHighlight(null),e.setEditableHoverHighlight(null);return}const T=this.findInnermostEditablePlaceholderAtChar(e,S);e.setEditableHoverHighlight(T?{from:T.start,to:T.end}:null);const M=this.findHoverBlockAtChar(e,S);if(!M){e.setHoverHighlight(null);return}const B=e.metadata.get(M.id);if(!B||B.startChar===void 0||B.endChar===void 0){e.setHoverHighlight(null);return}e.setHoverHighlight({from:B.startChar,to:B.endChar})},E=()=>{e.setHoverHighlight(null),e.setEditableHoverHighlight(null)},f={element:t,over:c,leave:r,drop:(p,S,T)=>h(S,T,p)};return this.tileDropTargets.add(f),t.addEventListener("dragover",a),t.addEventListener("dragleave",d),t.addEventListener("drop",l),t.addEventListener("mousedown",g,!0),t.addEventListener("contextmenu",y),t.addEventListener("mousemove",C),t.addEventListener("mouseleave",E),()=>{this.tileDropTargets.delete(f),t.removeEventListener("dragover",a),t.removeEventListener("dragleave",d),t.removeEventListener("drop",l),t.removeEventListener("mousedown",g,!0),t.removeEventListener("contextmenu",y),t.removeEventListener("mousemove",C),t.removeEventListener("mouseleave",E),window.removeEventListener("mousemove",w),window.removeEventListener("mouseup",b)}}findInnermostBlockAtChar(e,t){if(!this.workspace)return null;let n=null;for(const[s,r]of e.metadata){if(r.startChar===void 0||r.endChar===void 0||t<r.startChar||t>=r.endChar)continue;const c=r.endChar-r.startChar;(n===null||c<n.size)&&(n={id:s,size:c})}return n?this.workspace.getBlockById(n.id):null}findHoverBlockAtChar(e,t){if(!this.workspace)return null;let n=null,s=null;for(const[c,a]of e.metadata){if(a.startChar===void 0||a.endChar===void 0||t<a.startChar||t>=a.endChar)continue;const d=a.endChar-a.startChar;(s===null||d<s.size)&&(s={id:c,size:d}),!a.atomic&&(n===null||d<n.size)&&(n={id:c,size:d})}const r=n??s;return r?this.workspace.getBlockById(r.id):null}findInnermostEditablePlaceholderAtChar(e,t){let n=null;for(const s of e.getPlaceholders()){if(!s.edit||t<s.start||t>=s.end)continue;const r=s.end-s.start;(n===null||r<n.size)&&(n={ph:s,size:r})}return n?{start:n.ph.start,end:n.ph.end}:null}applyRightDragMove(e,t,n){if(!n||(n=this.fitOrLoose(e,t,n),!n))return;let s=!1;x.Events.setGroup(!0);try{if(t.getParent()&&t.unplug(!0),n.target.kind==="top")this.placeAtTopIndex(e,t,n.target.index),s=!0;else if(n.target.kind==="statement"){if(t.previousConnection){const r=e.getBlockById(n.target.targetBlockId);r&&r!==t&&(this.connectStatement(t,r,n.target.position),s=!0)}}else if(n.target.kind==="into-slot"){if(t.previousConnection){const r=e.getBlockById(n.target.parentBlockId);r&&r!==t&&(this.connectIntoSlot(t,r,n.target.inputName),s=!0)}}else if(n.target.kind==="value-slot"&&t.outputConnection){const r=e.getBlockById(n.target.parentBlockId);r&&r!==t&&!this.isDescendantOf(r,t)&&(s=this.connectIntoValueSlot(t,r,n.target.inputName))}}finally{x.Events.setGroup(!1)}!s&&t.workspace&&!t.getParent()&&this.placeOrphanBelowTops(t),x.svgResize(e)}computeCodespaceDrop(e,t,n){var k,v;if(!this.workspace)return null;const s=this.workspace.getTopBlocks(!0),r=e.metadata,c=e.getLineCount();if(s.length===0)return{indicator:{kind:"line",line:1,position:"above"},target:{kind:"top",index:0}};if(e.isBelowLastLine(n)){const w=r.get(s[s.length-1].id);return{indicator:{kind:"line",line:(w==null?void 0:w.endLine)??c,position:"below"},target:{kind:"top",index:s.length}}}const a=e.getLineAtCoords(t,n);if(a===null){const w=r.get(s[0].id);return{indicator:{kind:"line",line:(w==null?void 0:w.startLine)??1,position:"above"},target:{kind:"top",index:0}}}const d=e.charAtCoords(t,n);if(d!==null){const w=this.findValueSlotDropAtChar(e,d);if(w)return{indicator:{kind:"value-slot",from:w.highlight.from,to:w.highlight.to},target:{kind:"value-slot",parentBlockId:w.parentBlockId,inputName:w.inputName}}}const l=this.findInnermostStatementSlotAtLine(a,r);if(l){const w=this.workspace.getBlockById(l.blockId);if(w){const b=xe(),g=[];let y=(v=(k=w.getInput(l.inputName))==null?void 0:k.connection)==null?void 0:v.targetBlock();for(;y;)y.id!==b&&g.push(y),y=y.getNextBlock();for(const C of g){const E=r.get(C.id);if(!E||a<E.startLine||a>E.endLine)continue;const f=a===E.endLine,p=e.isInLowerHalfOfLine(a,n);return f&&p?{indicator:{kind:"line",line:E.endLine,position:"below"},target:{kind:"statement",targetBlockId:C.id,position:"after"}}:{indicator:{kind:"line",line:E.startLine,position:"above"},target:{kind:"statement",targetBlockId:C.id,position:"before"}}}if(g.length>0){const C=g[g.length-1],E=r.get(C.id);return{indicator:{kind:"line",line:(E==null?void 0:E.endLine)??l.range.endLine,position:"below"},target:{kind:"into-slot",parentBlockId:l.blockId,inputName:l.inputName}}}return{indicator:{kind:"line",line:l.range.startLine,position:"above"},target:{kind:"into-slot",parentBlockId:l.blockId,inputName:l.inputName}}}}const h=xe();for(let w=0;w<s.length;w++)for(let b=s[w];b;b=b.getNextBlock()){if(b.id===h)continue;const g=r.get(b.id);if(!g||a<g.startLine||a>g.endLine)continue;const y=a===g.endLine,C=e.isInLowerHalfOfLine(a,n),E=y&&C,f=E&&!b.getNextBlock();return{indicator:E?{kind:"line",line:g.endLine,position:"below"}:{kind:"line",line:g.startLine,position:"above"},target:{kind:"statement",targetBlockId:b.id,position:E?"after":"before",topIndex:f?w+1:w}}}const u=r.get(s[s.length-1].id);return{indicator:{kind:"line",line:(u==null?void 0:u.endLine)??c,position:"below"},target:{kind:"top",index:s.length}}}findInnermostStatementSlotAtLine(e,t){let n=null;for(const[s,r]of t)if(r.statementSlots)for(const[c,a]of Object.entries(r.statementSlots)){if(e<a.startLine||e>a.endLine)continue;const d=a.endLine-a.startLine,l=this.computeBlockDepth(s);(n===null||d<n.size||d===n.size&&l>n.depth)&&(n={blockId:s,inputName:c,range:a,size:d,depth:l})}return n?{blockId:n.blockId,inputName:n.inputName,range:n.range}:null}fitOrLoose(e,t,n){return this.codespaceDropAllowed(e,t,n.target)?n:n.target.kind==="statement"&&n.target.topIndex!==void 0?{...n,target:{kind:"top",index:n.target.topIndex}}:null}codespaceDropAllowed(e,t,n){var a,d,l;const s=(h,u)=>!!h&&!!u&&e.connectionChecker.canConnect(h,u,!1);if(n.kind==="top")return!0;if(n.kind==="value-slot"){const h=e.getBlockById(n.parentBlockId);return s((a=h==null?void 0:h.getInput(n.inputName))==null?void 0:a.connection,t.outputConnection)}if(n.kind==="into-slot"){const h=e.getBlockById(n.parentBlockId),u=(d=h==null?void 0:h.getInput(n.inputName))==null?void 0:d.connection;let k=u==null?void 0:u.targetBlock();for(;k!=null&&k.getNextBlock()&&k.getNextBlock()!==t;)k=k.getNextBlock();return s(k&&k!==t?k.nextConnection:u,t.previousConnection)}const r=e.getBlockById(n.targetBlockId);if(!r||r===t)return!1;if(n.position==="before"){const h=(l=r.previousConnection)==null?void 0:l.targetConnection;return h&&h.getSourceBlock()!==t&&!s(h,t.previousConnection)?!1:s(t.nextConnection,r.previousConnection)}const c=r.getNextBlock();return s(r.nextConnection,t.previousConnection)?!c||c===t||s(t.nextConnection,c.previousConnection):!1}connectIntoSlot(e,t,n){if(!e.previousConnection)return;const s=t.getInput(n),r=s==null?void 0:s.connection;if(!r)return;const c=r.targetBlock();if(!c){r.connect(e.previousConnection);return}let a=c,d=a.getNextBlock();for(;d;)a=d,d=a.getNextBlock();a.nextConnection&&a.nextConnection.connect(e.previousConnection)}findValueSlotDropAtChar(e,t){var r,c;if(!this.workspace)return null;const n=xe();for(const a of e.getPlaceholders()){if(t<a.start||t>=a.end)continue;if(a.emptySlot){const{parentBlockId:u,inputName:k}=a.emptySlot;if(u===n)continue;const v=this.workspace.getBlockById(u);if(!((r=v==null?void 0:v.getInput(k))!=null&&r.connection))continue;return{parentBlockId:u,inputName:k,highlight:{from:a.start,to:a.end}}}const d=(c=a.edit)==null?void 0:c.blockId;if(!d||d===n)continue;const l=this.workspace.getBlockById(d);if(!l)continue;const h=this.resolveValueParent(l);if(h)return{parentBlockId:h.parentBlockId,inputName:h.inputName,highlight:{from:a.start,to:a.end}}}let s=null;for(const[a,d]of e.metadata){if(d.startChar===void 0||d.endChar===void 0||t<d.startChar||t>=d.endChar||a===n)continue;const l=this.workspace.getBlockById(a);if(!(l!=null&&l.outputConnection))continue;const h=d.endChar-d.startChar;(s===null||h<s.size)&&(s={id:a,size:h,from:d.startChar,to:d.endChar})}if(s){const a=this.workspace.getBlockById(s.id);if(a){const d=this.resolveValueParent(a);if(d)return{parentBlockId:d.parentBlockId,inputName:d.inputName,highlight:{from:s.from,to:s.to}}}}return null}resolveValueParent(e){var s;const t=(s=e.outputConnection)==null?void 0:s.targetConnection;if(!t)return null;const n=t.getSourceBlock();if(!n)return null;for(const r of n.inputList)if(r.connection===t)return{parentBlockId:n.id,inputName:r.name};return null}addBlockFromTile(e){const t=this.workspace;if(!t)return;const n=x.common.getSelected(),s=n instanceof x.BlockSvg&&n.workspace===t?n:null;x.Events.setGroup(!0);try{const r=t.newBlock(U(e,this.definitions)),c=s&&!s.isShadow()?{kind:"statement",targetBlockId:s.id,position:"after"}:null,a=c!==null&&this.codespaceDropAllowed(t,r,c);a||this.placeOrphanBelowTops(r),r.initSvg(),r.render(),a&&s&&this.connectStatement(r,s,"after"),x.common.setSelected(r);const d=t.getMetricsManager().getViewMetrics(!0),l=r.getBoundingRectangle();l.left>=d.left&&l.top>=d.top&&l.right<=d.left+d.width&&l.bottom<=d.top+d.height||t.centerOnBlock(r.id)}finally{x.Events.setGroup(!1)}}placeOrphanBelowTops(e){var s,r;if(!this.workspace)return;const t=this.workspace.getTopBlocks(!0).filter(c=>c.id!==e.id);if(t.length===0){e.moveTo(new x.utils.Coordinate(20,20));return}let n=0;for(const c of t){const a=c.getRelativeToSurfaceXY(),d=((r=(s=c.getHeightWidth)==null?void 0:s.call(c))==null?void 0:r.height)??50;n=Math.max(n,a.y+d)}e.moveTo(new x.utils.Coordinate(20,n+20))}isDescendantOf(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.getParent()}return!1}connectIntoValueSlot(e,t,n){if(!e.outputConnection)return!1;const s=t.getInput(n),r=s==null?void 0:s.connection;if(!r)return!1;const c=r.targetBlock(),a=!!c&&!c.isShadow();a&&(c.unplug(!1),this.placeOrphanBelowTops(c));try{return r.connect(e.outputConnection),!0}catch{if(a&&(c!=null&&c.outputConnection))try{r.connect(c.outputConnection)}catch{}return!1}}computeBlockDepth(e){var s,r;let t=0,n=((r=(s=this.workspace)==null?void 0:s.getBlockById(e))==null?void 0:r.getParent())??null;for(;n;)t++,n=n.getParent();return t}placeAtTopIndex(e,t,n){const s=e.getTopBlocks(!0).map(c=>c.id).filter(c=>c!==t.id),r=Math.max(0,Math.min(n,s.length));s.splice(r,0,t.id),this.applyTopBlockOrder(e,s)}connectStatement(e,t,n){var s,r,c;if(e.previousConnection)if(n==="before"){const a=((s=t.previousConnection)==null?void 0:s.targetConnection)??null;(r=t.previousConnection)==null||r.disconnect(),a?a.connect(e.previousConnection):e.moveTo(t.getRelativeToSurfaceXY()),e.nextConnection&&t.previousConnection&&e.nextConnection.connect(t.previousConnection)}else{const a=t.getNextBlock();(c=a==null?void 0:a.previousConnection)==null||c.disconnect(),t.nextConnection&&t.nextConnection.connect(e.previousConnection),a!=null&&a.previousConnection&&e.nextConnection&&e.nextConnection.connect(a.previousConnection)}}applyTopBlockOrder(e,t){const n=x.Events.disable!==void 0;n&&x.Events.disable();try{let s=20;for(const r of t){const c=e.getBlockById(r);c&&(c.moveTo(new x.utils.Coordinate(20,s)),s+=c.getHeightWidth().height+20)}}finally{n&&x.Events.enable()}x.svgResize(e),this.refreshTextViews()}refreshTextViews(){var e,t,n,s;(e=this.codespace)==null||e.refresh(),(t=this.previewEditor)==null||t.refresh(),(n=this.codeEditor)==null||n.refresh();for(const r of this.views)(s=r.editor)==null||s.refresh()}async mountPreview(e,t){var r;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before mountPreview can be used.");(r=this.previewEditor)==null||r.dispose();const n={...t,highlightRules:(t==null?void 0:t.highlightRules)??this.resolveHighlightRules("preview"),showPlaceholderMarkers:(t==null?void 0:t.showPlaceholderMarkers)??!1};this.previewHost=e,this.applyTextViewClasses(),this.previewEditor=new ge(e,this.workspace,()=>this.generatePreviewText(),n);const s=this.previewEditor;await s.mount(),this.previewEditor===s&&this.refreshSelectionSync()}generatePreviewText(){var e;return this.generateModeText((e=this.mountConfig)==null?void 0:e.previewMode)}generateModeText(e){const t=this.modeDef(e),n=t?X(t,this.elementTypes):void 0;return!this.workspace||!this.mountConfig||!e||!n?{code:"",metadata:new Map,placeholders:[]}:ke(this.workspace,e,this.definitions,this.elementTypes,this.mountConfig.modes??[],n)}highlightRulesFor(e){var s,r,c;const t=this.modeDef(e),n=t?X(t,this.elementTypes):void 0;return n?(c=(r=(s=this.mountConfig)==null?void 0:s.code)==null?void 0:r[n])==null?void 0:c.highlighting:void 0}addView(e){if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before addView can be used.");if(e.kind!=="preview"&&e.kind!=="codespace"&&e.kind!=="workspace")throw new Error(`addView: unknown view kind "${String(e.kind)}".`);if(e.kind==="workspace"&&e.editable===!0)throw new Error("addView: an added workspace is read only for now (editable: false).");if(e.name!==void 0&&this.resolveView(e.name))throw new Error(`addView: a view named "${e.name}" already exists.`);if(e.kind==="workspace")return this.addWorkspaceView(e);this.checkTextViewMode("addView",e.mode);const t=e.kind==="codespace",n=new ge(e.container,this.workspace,()=>this.generateModeText(c.mode),{theme:e.theme,highlightRules:this.highlightRulesFor(e.mode),...t?{onDelete:l=>this.deleteBlockAtCodespaceLine(n,l),canDragBlock:l=>this.canMoveInCodespace(l),onPlaceholderApply:(l,h)=>this.applyPlaceholderEdit(l,h)}:{showPlaceholderMarkers:!1}}),s=t?"morphic-codespace-root":"morphic-preview-root";let r=e.name;for(;r===void 0||this.resolveView(r);)r=`view-${++this.viewCount}`;const c={kind:e.kind,name:r,container:e.container,mode:e.mode,editor:n};this.views.add(c),fe(c.container,c.mode,s);const a=e.toolbar?this.mountToolbar(e.toolbar.container,{view:r,items:e.toolbar.items,display:e.toolbar.display}):void 0,d={kind:c.kind,name:c.name,ready:n.mount().then(()=>{this.views.has(c)&&(t&&this.workspace&&(c.teardown=this.attachCodespaceDropTarget(n,c.container,this.workspace)),this.linkAddedView())}),getMode:()=>c.mode,setMode:l=>{if(this.views.has(c)){this.checkTextViewMode("setMode",l),c.mode=l,fe(c.container,l,s),n.setHighlightRules(this.highlightRulesFor(l)),n.refresh();for(const h of this.toolbars)h.refresh()}},setTheme:l=>n.setTheme(l),dispose:()=>{var l;this.views.delete(c)&&(a==null||a.dispose(),(l=c.teardown)==null||l.call(c),n.dispose(),this.refreshSelectionSync())}};return c.setMode=d.setMode,d}addWorkspaceView(e){const t=this.workspace;if(!this.modeDef(e.mode))throw new Error(`addView: unknown mode "${e.mode}".`);let n=e.name;for(;n===void 0||this.resolveView(n);)n=`view-${++this.viewCount}`;const s=t.options,r=x.inject(e.container,{readOnly:!0,media:s.pathToMedia,sounds:!1,renderer:s.renderer,rendererOverrides:s.rendererOverrides??void 0,theme:this.baseTheme??s.theme,rtl:s.RTL,move:{scrollbars:!0,drag:!0,wheel:!0}});re.set(r,this),this.viewWorkspaceModes.set(r,e.mode);const c={kind:"workspace",name:n,container:e.container,mode:e.mode,workspace:r};this.views.add(c),this.styleWorkspaceView(c);const a=()=>{const{scrollX:g,scrollY:y,scale:C}=r;x.Events.disable();try{x.serialization.workspaces.load(x.serialization.workspaces.save(t),r)}finally{x.Events.enable()}this.renderWorkspaceView(c),r.scale!==C&&r.setScale(C),r.scroll(g,y)};a();let d=null,l=!1;const h=()=>{var g;for(const y of r.getAllBlocks(!1))y.unselect();(g=r.getBlockById(d??""))==null||g.select()},u=g=>{if(g.workspaceId===t.id){if(g.type===x.Events.SELECTED){d=g.newElementId??null,h();return}g.isUiEvent||l||(l=!0,setTimeout(()=>{l=!1,this.views.has(c)&&(a(),h())},0))}};t.addChangeListener(u);const k=g=>{var f;const y=g.target,C=(f=y==null?void 0:y.closest)==null?void 0:f.call(y,"[data-id]");let E=C?t.getBlockById(C.getAttribute("data-id")??""):null;for(;E!=null&&E.isShadow();)E=E.getParent();E?x.common.setSelected(E):y!=null&&y.classList.contains("blocklyMainBackground")&&x.common.setSelected(null)};e.container.addEventListener("click",k);const v=typeof ResizeObserver<"u"?new ResizeObserver(()=>x.svgResize(r)):void 0;v==null||v.observe(e.container);const w=e.toolbar?this.mountToolbar(e.toolbar.container,{view:n,items:e.toolbar.items,display:e.toolbar.display}):void 0;c.teardown=()=>{t.removeChangeListener(u),e.container.removeEventListener("click",k),v==null||v.disconnect(),w==null||w.dispose()};const b={kind:"workspace",name:n,ready:Promise.resolve(),getMode:()=>c.mode,setMode:g=>{if(this.views.has(c)){if(!this.modeDef(g))throw new Error(`setMode: unknown mode "${g}".`);c.mode=g,this.viewWorkspaceModes.set(r,g),this.styleWorkspaceView(c),this.renderWorkspaceView(c);for(const y of this.toolbars)y.refresh()}},setTheme:()=>{},dispose:()=>{this.views.delete(c)&&this.disposeView(c)}};return c.setMode=b.setMode,b}styleWorkspaceView(e){e.workspace&&(ue(e.container,e.mode,"workspace","morphic-workspace-root"),this.syncFontOf(e.workspace,e.container))}renderWorkspaceView(e){var t;for(const n of((t=e.workspace)==null?void 0:t.getAllBlocks(!1))??[]){const s=this.definitions.get(W(n.type));s&&this.applyView(n,s,e.mode,"workspace")}}disposeView(e){var t,n,s;(t=e.teardown)==null||t.call(e),(n=e.editor)==null||n.dispose(),(s=e.workspace)==null||s.dispose()}linkAddedView(){var t,n;if(this.selectionSync){this.refreshSelectionSync();return}const e=(t=this.mountConfig)==null?void 0:t.selectionSync;e===!1||!((n=this.mountConfig)!=null&&n.workspaceContainer)||this.enableSelectionSync(typeof e=="object"?e:void 0)}resolveView(e){var t,n,s;if(e==="workspace")return this.workspace?{name:e,kind:"workspace",mode:(t=this.mountConfig)==null?void 0:t.workspaceMode,workspace:this.workspace,readOnly:!1}:void 0;if(e==="codespace")return(n=this.mountConfig)!=null&&n.codespaceContainer?{name:e,kind:"codespace",mode:this.getCodespaceMode(),editor:this.codespace,readOnly:!1}:void 0;if(e==="preview")return this.previewHost?{name:e,kind:"preview",mode:(s=this.mountConfig)==null?void 0:s.previewMode,editor:this.previewEditor,readOnly:!0}:void 0;for(const r of this.views)if(r.name===e)return{name:e,kind:r.kind,mode:r.mode,editor:r.editor,workspace:r.workspace,readOnly:r.kind!=="codespace"}}getViewMode(e){var t;return(t=this.resolveView(e))==null?void 0:t.mode}checkTextViewMode(e,t){const n=this.modeDef(t);if(!n)throw new Error(`${e}: unknown mode "${t}".`);if(X(n,this.elementTypes)===void 0)throw new Error(`${e}: mode "${t}" has no code element to render.`)}applyPlaceholderEdit(e,t){var a;if(!this.workspace)return;let n=this.workspace.getBlockById(e.blockId);if(!n)return;if(n.isShadow()){const d=(a=n.outputConnection)==null?void 0:a.targetConnection;if(d){const l=this.workspace.newBlock(n.type);for(const h of n.inputList)for(const u of h.fieldRow){if(!u.name)continue;const k=l.getField(u.name);k&&k.setValue(u.getValue())}n.rendered&&(l.initSvg(),l.render()),d.connect(l.outputConnection),n=l}}const s=n.getField(e.fieldName);if(!s)return;s.setValue(t);const r=n;r.rendered&&typeof r.render=="function"&&r.render();const c=n.getParent();if(c){const d=c;d.rendered&&typeof d.render=="function"&&d.render()}}canMoveInCodespace(e){var n;const t=(n=this.workspace)==null?void 0:n.getBlockById(e);return!!(t!=null&&t.previousConnection||t!=null&&t.outputConnection)}deleteBlockAtCodespaceLine(e,t){var c;const n=e.metadata;if(!this.workspace||!n||n.size===0)return;let s=null,r=1/0;for(const[a,{startLine:d,endLine:l}]of n){if(t<d||t>l)continue;const h=l-d;h<r&&(r=h,s=a)}s&&((c=this.workspace.getBlockById(s))==null||c.dispose(!0))}generateCodespaceText(){if(!this.workspace||!this.mountConfig)return{code:"",metadata:new Map,placeholders:[]};const e=this.mountConfig.codespaceMode;if(e){const t=this.modeDef(e),n=t?X(t,this.elementTypes):void 0;return ke(this.workspace,e,this.definitions,this.elementTypes,this.mountConfig.modes??[],n)}return ke(this.workspace,this.mountConfig.workspaceMode,this.definitions,this.elementTypes,this.mountConfig.modes??[])}showCodeEditor(){var e;(e=this.codeEditor)==null||e.show()}hideCodeEditor(){var e;(e=this.codeEditor)==null||e.hide()}isCodeEditorVisible(){var e;return((e=this.codeEditor)==null?void 0:e.isVisible())??!1}setCodeEditorTheme(e){var t;(t=this.codeEditor)==null||t.setTheme(e)}setCodespaceTheme(e){var t;(t=this.codespace)==null||t.setTheme(e)}setPreviewTheme(e){var t;(t=this.previewEditor)==null||t.setTheme(e)}enableSelectionSync(e){var n;if(!this.workspace)throw new Error("MorphicBlocks must be mounted before enableSelectionSync can be used.");const t=[this.codeEditor,this.codespace,this.previewEditor,...[...this.views].map(s=>s.editor)].filter(s=>s!==void 0);if(t.length===0)throw new Error("enableSelectionSync requires at least one of mountCodeEditor, mountCodespace, or mountPreview to have been called first.");(n=this.selectionSync)==null||n.disable(),this.selectionSyncOptions=e,this.selectionSync=new To(this.workspace,t,e),this.selectionSync.enable()}refreshSelectionSync(){if(!this.selectionSync)return;this.codeEditor||this.codespace||this.previewEditor||[...this.views].some(t=>t.editor)?this.enableSelectionSync(this.selectionSyncOptions):this.disableSelectionSync()}disableSelectionSync(){var e;(e=this.selectionSync)==null||e.disable(),this.selectionSync=void 0,this.selectionSyncOptions=void 0}registerBlocks(){for(const e of this.definitions.values()){const t=Me(e.identifier);if(be.set(t,this),this.registeredBlockTypes.has(t))continue;const n=e.identifier;x.Blocks[t]={init(){const s=re.get(this.workspace)??be.get(t);s==null||s.initManagedBlock(this,n)}},this.registeredBlockTypes.add(t)}}initManagedBlock(e,t){var a;const n=this.definitions.get(t);if(!n)return;const s=e.workspace.isFlyout?"toolbox":"workspace",r=this.viewWorkspaceModes.get(e.workspace)??this.resolveMode(s);this.applyView(e,n,r,s),dn(e);const c=ce(this.behaviors[n.identifier]);(a=c==null?void 0:c.init)==null||a.call(c,e,this.createBehaviorContext(e,n,r,s))}validateContainers(e){if(!e.workspaceContainer&&!e.codespaceContainer)throw new Error("MorphicBlocks.mount requires at least one of workspaceContainer or codespaceContainer.")}createHeadlessHost(){const e=document.createElement("div");return e.style.cssText="position:absolute;left:-9999px;top:-9999px;width:800px;height:600px;overflow:hidden;",document.body.appendChild(e),this.headlessWorkspaceHost=e,e}resolveMode(e){return this.mountConfig?e==="toolbox"?this.mountConfig.toolboxMode:this.mountConfig.workspaceMode:"default"}applyView(e,t,n,s){var h,u;if(e.isDeadOrDying())return;const r=this.blockCategoryIndex.get(t.identifier);t.color===void 0&&(r==null?void 0:r.color)!==void 0&&e.setColour(r.color);const c=e.__morphicFieldMemory??(e.__morphicFieldMemory=new Map);for(const[k,v]of Yt(e))c.set(k,v);const a=Be(t,n,this.elementTypes,((h=this.mountConfig)==null?void 0:h.modes)??[]),d=e.workspace===this.workspace;We({block:e,definition:t,view:a,mode:n,context:s,elementTypes:d?this.elementTypes:void 0,resolveBlocklyType:k=>U(k,this.definitions)}),this.styleBlock(e,t);const l=ce(this.behaviors[t.identifier]);(u=l==null?void 0:l.onViewApplied)==null||u.call(l,e,this.createBehaviorContext(e,t,n,s)),Kt(e,c)}styleBlock(e,t){const n=this.blockCategoryIndex.get(t.identifier);$t(e,n==null?void 0:n.token),Nt(e,t.identifier),Ht(e),t.color!==void 0&&(e.setColour(t.color),Ee(e)&&e.render())}applyTextViewClasses(){this.mountConfig&&(this.mountConfig.codespaceContainer&&fe(this.mountConfig.codespaceContainer,this.getCodespaceMode(),"morphic-codespace-root"),this.previewHost&&fe(this.previewHost,this.mountConfig.previewMode,"morphic-preview-root"))}applyWorkspaceContainerClass(){var n;if(!this.mountConfig)return;const e=this.mountConfig.workspaceHost;ue(e,this.mountConfig.workspaceMode,"workspace","morphic-workspace-root");const t=this.resolveClassNames((n=this.mountConfig.ui)==null?void 0:n.workspaceClassName);this.replaceUserClasses(e,this.appliedWorkspaceClasses,t),this.appliedWorkspaceClasses=t}syncWorkspaceFont(){var e;this.workspace&&((e=this.mountConfig)!=null&&e.workspaceHost)&&this.syncFontOf(this.workspace,this.mountConfig.workspaceHost)}syncFontOf(e,t){if(!this.baseTheme||!this.baseFont)return;const n=st(t,[[e.getRenderer().getClassName(),this.baseTheme.getClassName()]],this.baseFont);rt(e,this.baseTheme,this.baseFont,n)&&Oe(e)}applyFlyoutClass(){var c,a,d;if(!this.workspace||!this.mountConfig)return;const e=this.resolveClassNames((c=this.mountConfig.ui)==null?void 0:c.toolboxClassName),t=this.workspace.getToolbox(),n=((a=t==null?void 0:t.getDiv)==null?void 0:a.call(t))??null;n&&(ue(n,this.mountConfig.toolboxMode,"toolbox","morphic-toolbox-shell"),this.replaceUserClasses(n,this.appliedToolboxShellClasses,e),this.appliedToolboxShellClasses=e);const s=(d=this.workspace.getFlyout())==null?void 0:d.getWorkspace(),r=s==null?void 0:s.getParentSvg();r&&(ue(r,this.mountConfig.toolboxMode,"toolbox","morphic-toolbox-root"),this.replaceUserClasses(r,this.appliedToolboxFlyoutClasses,e),this.appliedToolboxFlyoutClasses=e)}renderWorkspaceBlocks(){if(!(!this.workspace||!this.mountConfig))for(const e of this.workspace.getAllBlocks(!1)){const t=e,n=this.definitions.get(W(t.type));n&&this.applyView(t,n,this.mountConfig.workspaceMode,"workspace")}}renderFlyoutBlocks(){if(!(!this.flyoutWorkspace||!this.mountConfig)){for(const e of this.flyoutWorkspace.getAllBlocks(!1)){const t=e,n=this.definitions.get(W(t.type));n&&this.applyView(t,n,this.mountConfig.toolboxMode,"toolbox")}this.applyFlyoutClass()}}refreshToolbox(){var e;!this.workspace||!this.toolboxDefinition||(e=this.mountConfig)!=null&&e.canvasToolbox||this.workspace.options.readOnly||this.workspace.updateToolbox(this.toolboxDefinition)}bindFlyoutWorkspace(){var t;if(this.flyoutWorkspace&&(this.flyoutWorkspace.removeChangeListener(this.onFlyoutChange),this.flyoutWorkspace=void 0),!this.workspace)return;const e=(t=this.workspace.getFlyout())==null?void 0:t.getWorkspace();e&&(this.flyoutWorkspace=e,re.set(e,this),this.flyoutWorkspace.addChangeListener(this.onFlyoutChange),this.applyFlyoutClass())}resolveToolboxDefinition(e){if(e.toolbox){const s=this.resolveToolboxKind(e.toolboxLayout),r=s?{...e.toolbox,kind:s}:e.toolbox;return mt(r,this.definitions)}const t=e.blockly;if(t!=null&&t.toolbox)return t.toolbox;const n=this.resolveToolboxKind(e.toolboxLayout);return mt({...n!==void 0?{kind:n}:{},blocks:[...this.definitions.keys()]},this.definitions)}createBehaviorContext(e,t,n,s){return{Blockly:x,workspace:e.workspace,mode:n,context:s,definition:t}}resolveClassNames(e){return e?(Array.isArray(e)?e.join(" "):e).split(/\s+/).map(n=>n.trim()).filter((n,s,r)=>!!n&&r.indexOf(n)===s):[]}replaceUserClasses(e,t,n){for(const s of t)e.classList.remove(s);for(const s of n)e.classList.add(s)}buildBlockColorMap(){var t;const e=new Map;for(const[n,s]of this.definitions){const r=s.color??((t=this.blockCategoryIndex.get(n))==null?void 0:t.color);r!==void 0&&e.set(n,String(r))}return e}resolveToolboxKind(e){if(e)return e==="category"?"categoryToolbox":"flyoutToolbox"}createCategoryIndex(e,t){const n=new Map,s=(e==null?void 0:e.categories)??[],r=new Map;for(const a of s){const d=V(a.name);if(r.set(a.name.toLowerCase(),{token:d,color:a.color}),a.blocks)for(const l of a.blocks)n.has(l)||n.set(l,{token:d,color:a.color})}const c=t?this.definitions:new Map;for(const a of c.values()){if(!a.category||n.has(a.identifier))continue;const d=r.get(a.category.toLowerCase());d&&n.set(a.identifier,d)}return n}deferApplyView(e,t,n){const s=n==="toolbox"?this.flyoutWorkspace:this.workspace;s&&requestAnimationFrame(()=>{const r=s.getBlockById(e);if(!r)return;const c=this.definitions.get(W(r.type));c&&this.applyView(r,c,t,n)})}}function un(i,o,e){return Math.min(Math.max(i,o),e)}function fn(i,o){const{target:e,axis:t,invert:n=!1,onResize:s}=o,r=o.min??0,c=o.max??Number.POSITIVE_INFINITY,a=d=>{if(d.button!==0)return;d.preventDefault();const l=e.getBoundingClientRect(),h=t==="x"?l.width:l.height,u=t==="x"?d.clientX:d.clientY,k=document.body.style.userSelect,v=document.body.style.cursor;document.body.style.userSelect="none",document.body.style.cursor=t==="x"?"col-resize":"row-resize",i.setPointerCapture(d.pointerId);const w=g=>{const C=(t==="x"?g.clientX:g.clientY)-u,E=un(h+(n?-C:C),r,c);e.style.flexBasis=`${E}px`,s==null||s(E)},b=()=>{i.removeEventListener("pointermove",w),i.removeEventListener("pointerup",b),i.removeEventListener("lostpointercapture",b),document.body.style.userSelect=k,document.body.style.cursor=v};i.addEventListener("pointermove",w),i.addEventListener("pointerup",b),i.addEventListener("lostpointercapture",b)};return i.addEventListener("pointerdown",a),{dispose:()=>i.removeEventListener("pointerdown",a)}}const pn=Object.freeze(Object.defineProperty({__proto__:null,default:".morphic-placeholder-default,.morphic-placeholder-set{border-radius:2px;padding:0 .2em}.morphic-placeholder-default{font-style:italic;opacity:.55}"},Symbol.toStringTag,{value:"Module"})),mn=Object.freeze(Object.defineProperty({__proto__:null,default:".morphic-toolbar{display:flex;align-items:center;gap:var(--morphic-toolbar-gap, .5em);padding:var(--morphic-toolbar-padding, 4px 8px);background:var(--morphic-toolbar-bg, inherit);color:var(--morphic-toolbar-fg, inherit);font:var(--morphic-toolbar-font, inherit);border-bottom:var(--morphic-toolbar-border, 1px solid rgba(127, 127, 127, .2));box-sizing:border-box}.morphic-toolbar-left,.morphic-toolbar-right{display:flex;align-items:center;gap:var(--morphic-toolbar-gap, .5em)}.morphic-toolbar-right{margin-left:auto}.morphic-toolbar-item{display:inline-flex;align-items:center;gap:4px;background:var(--morphic-toolbar-item-bg, transparent);color:inherit;border:var(--morphic-toolbar-item-border, none);padding:var(--morphic-toolbar-item-padding, 2px 6px);border-radius:var(--morphic-toolbar-item-radius, 3px);cursor:pointer;font:inherit;line-height:1}.morphic-toolbar-item:hover:not(:disabled){background:var(--morphic-toolbar-item-hover-bg, rgba(127, 127, 127, .15))}.morphic-toolbar-item:disabled{opacity:.4;cursor:default}.morphic-toolbar-icon{display:inline-flex}.morphic-toolbar-label{opacity:.7;font-size:.9em}.morphic-toolbox-header{display:flex;align-items:center;padding:4px 6px 8px}.morphic-toolbar-badge{font-size:.85em;opacity:.6;padding:1px 6px;border:1px solid currentColor;border-radius:3px}.morphic-toolbar-spacer{flex:1}"},Symbol.toStringTag,{value:"Module"}));N.MorphicBlocks=hn,N.MorphicToolboxCanvas=pt,N.makeResizable=fn,N.renderToolbar=kt,N.toCleanId=W,N.toolbarItems=A,N.validateDefinitions=ct,Object.defineProperty(N,Symbol.toStringTag,{value:"Module"})}));
|
|
51
|
+
- `)}`)}validatePresets(e){const{errors:t,warnings:n}=sn({presets:e.presets,modes:e.modes,views:Ut(e.views??this.formatViews),elementTypes:this.elementTypes});for(const s of n)Oe(e)(`[MorphicBlocks] ${s}`);yn(t)}dispose(){var e,t,n,s,r;for(const[c,a]of ze)a===this&&ze.delete(c);(e=this.workspaceResizeObserver)==null||e.disconnect(),this.workspaceResizeObserver=void 0,(t=document.fonts)==null||t.removeEventListener("loadingdone",this.onStylesLoaded),this.activePreset=void 0,this.activeBlockSet=void 0,this.categoriesShown=!0,(n=this.selectionSync)==null||n.disable(),this.selectionSync=void 0,(s=this.codeEditor)==null||s.dispose(),this.codeEditor=void 0;for(const c of this.views)this.disposeView(c);this.views.clear(),(r=this.toolboxCanvas)==null||r.dispose(),this.toolboxCanvas=void 0;for(const c of[...this.toolbars])c.dispose();this.flyoutWorkspace&&(this.flyoutWorkspace.removeChangeListener(this.onFlyoutChange),this.flyoutWorkspace=void 0),this.workspace&&(this.workspace.removeChangeListener(this.onWorkspaceChange),this.workspace.dispose(),this.workspace=void 0),this.headlessWorkspaceHost&&(this.headlessWorkspaceHost.remove(),this.headlessWorkspaceHost=void 0),this.mountConfig=void 0,this.baseTheme=void 0,this.baseFont=void 0,this.toolboxDefinition=void 0,this.blockCategoryIndex.clear(),this.appliedWorkspaceClasses=[],this.appliedToolboxFlyoutClasses=[],this.appliedToolboxShellClasses=[]}mountToolbox(e,t){var c,a,l;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before mountToolbox can be used.");(c=this.toolboxCanvas)==null||c.dispose(),this.styles.ensureToolbarStyles(),this.mountConfig.canvasToolbox||this.workspace.updateToolbox({kind:"flyoutToolbox",contents:[]});const n=this.mountConfig.toolbox,s={...t,blocks:(t==null?void 0:t.blocks)??this.toolboxBlocks(),categories:(t==null?void 0:t.categories)??(n==null?void 0:n.categories),modeLabel:(t==null?void 0:t.modeLabel)??(n==null?void 0:n.modeLabel),highlight:(t==null?void 0:t.highlight)??(n==null?void 0:n.highlight),touch:(t==null?void 0:t.touch)??(n==null?void 0:n.touch),keyboard:(t==null?void 0:t.keyboard)??(n==null?void 0:n.keyboard),categoryHeadings:(t==null?void 0:t.categoryHeadings)??(n==null?void 0:n.categoryHeadings),collapsible:(t==null?void 0:t.collapsible)??(n==null?void 0:n.collapsible),collapsed:(t==null?void 0:t.collapsed)??(n==null?void 0:n.collapsed),onCategoryToggle:(t==null?void 0:t.onCategoryToggle)??(n==null?void 0:n.onCategoryToggle),layout:(t==null?void 0:t.layout)??(n==null?void 0:n.layout),scrollbar:(t==null?void 0:t.scrollbar)??(n==null?void 0:n.scrollbar),custom:(t==null?void 0:t.custom)??(n==null?void 0:n.custom),label:(t==null?void 0:t.label)??(n==null?void 0:n.label)};for(const[d,h]of Object.entries(this.elementTypes))pe(h)==="custom"&&!((a=s.custom)!=null&&a[d])&&Oe(this.mountConfig)(`[MorphicBlocks] The custom element "${d}" has no function in toolbox.custom; tiles show its content as text.`);s.layout==="tabs"&&!((l=s.categories)!=null&&l.length)&&Oe(this.mountConfig)('[MorphicBlocks] The toolbox layout "tabs" needs categories; the tiles show as a flat list.'),(s.collapsed===!0||Array.isArray(s.collapsed)&&s.collapsed.length>0)&&s.categoryHeadings===!1&&s.layout!=="tabs"&&Oe(this.mountConfig)("[MorphicBlocks] toolbox.collapsed needs category headings to open the categories again; all categories start open."),this.toolboxCanvas=new mn({container:e,workspaceContainer:this.mountConfig.workspaceHost,workspace:this.workspace,definitions:this.definitions,blockColors:this.buildBlockColorMap(),behaviors:this.behaviors,elementTypes:this.elementTypes,mode:this.mountConfig.toolboxMode,modes:this.mountConfig.modes,code:this.mountConfig.code,options:s,grouped:this.categoriesShown,onPreviewWorkspace:d=>Ve.set(d,this),dropTargets:()=>[...this.tileDropTargets],onChoose:d=>this.addBlockFromTile(d)})}refresh(){var e;if(!(!this.workspace||!this.mountConfig)){this.syncWorkspaceFont(),Ht(this.workspace);for(const t of this.views)t.workspace&&(this.syncFontOf(t.workspace,t.container),Ht(t.workspace));(e=this.toolboxCanvas)==null||e.rerender(this.mountConfig.toolboxMode)}}getWorkspace(){return this.workspace}getAvailableModes(){var e;return(((e=this.mountConfig)==null?void 0:e.modes)??[]).map(t=>t.name)}getToolboxMode(){var e;return(e=this.mountConfig)==null?void 0:e.toolboxMode}getViewNames(){var e;return[...(e=this.mountConfig)!=null&&e.programView?[this.mountConfig.programView]:[],...[...this.views].map(t=>t.name)]}setModeElements(e,t){var d;if(!this.mountConfig||!this.workspace)throw new Error("MorphicBlocks must be mounted before setModeElements can be used.");const n=this.mountConfig.modes??[],s=n.findIndex(h=>h.name===e);if(s===-1)throw new Error(`setModeElements: unknown mode "${e}".`);const r=t.filter(h=>!(h in this.elementTypes));if(r.length>0)throw new Error(`setModeElements: unknown elements ${r.map(h=>`"${h}"`).join(", ")}.`);const c={...n[s],elements:[...t]},a=n.map((h,u)=>u===s?c:h);this.validatePresets({...this.mountConfig,modes:a});const l=n.slice();n[s]=c,this.styles.ensureModeVisibilityStyles(n,l),e===this.mountConfig.toolboxMode&&((d=this.toolboxCanvas)==null||d.rerender(this.mountConfig.toolboxMode),this.renderFlyoutBlocks())}modeDef(e){var t;if(e)return(((t=this.mountConfig)==null?void 0:t.modes)??[]).find(n=>n.name===e)}codespaceElement(){var e,t;return((e=[...this.views].find(n=>n.kind==="codespace"))==null?void 0:e.element)??((t=this.mountConfig)==null?void 0:t.workspaceElement)}mountToolbar(e,t){if(!this.workspace)throw new Error("MorphicBlocks must be mounted before mountToolbar can be used.");const n=t.view,s=this.resolveView(n);if(!s)throw new Error(`mountToolbar: no view named "${n}".`);this.styles.ensureToolbarStyles();const r=vn(e,t,{engine:this,kind:s.kind,readOnly:s.readOnly,view:n,getText:()=>this.toolbarTextFor(n),refresh:()=>this.toolbarRefreshFor(n)});this.toolbars.add(r),this.ensureToolbarBlocklyListener();const c=r.dispose;return r.dispose=()=>{this.toolbars.delete(r),this.toolbars.size===0&&this.teardownToolbarBlocklyListener(),c()},r}toolbarTextFor(e){var n;const t=this.resolveView(e);if((t==null?void 0:t.kind)==="codespace")return((n=t.editor)==null?void 0:n.getValue())??this.generateElementText(t.element).code;if((t==null?void 0:t.kind)==="workspace"&&t.workspace!==this.workspace)return this.generateElementText(t.element).code;if(this.codespace)return this.codespace.getValue();try{return this.generateJavaScript()}catch{return""}}toolbarRefreshFor(e){var t,n;(n=(t=this.resolveView(e))==null?void 0:t.editor)==null||n.refresh()}runJavaScript(e){var p,g,v;let t="",n,s=null;const r=[],c=(e==null?void 0:e.console)??(e!=null&&e.logToConsole?console:void 0),a=this.codespaceElement(),l=a?(v=(g=(p=this.mountConfig)==null?void 0:p.code)==null?void 0:g[a])==null?void 0:v.values:void 0,d=w=>(...C)=>{r.push({level:w,text:C.map(T=>cn(T,l)).join(" ")}),c&&(c[w]??c.log).apply(c,C)},h={log:d("log"),warn:d("warn"),error:d("error")},u=Object.entries((e==null?void 0:e.globals)??{});try{t=this.generateJavaScript();for(const[w]of u){if(w==="console")throw new Error('globals: "console" is set with the console option of runJavaScript()');if(!/^[\p{L}_$][\p{L}\p{N}_$]*$/u.test(w))throw new Error(`globals: "${w}" is not a JavaScript name`)}n=new Function("console",...u.map(([w])=>w),t)(h,...u.map(([,w])=>w))}catch(w){s=w instanceof Error?w:new Error(String(w))}const f={code:t,result:n,error:s,output:r};return this.dispatchEvent(new CustomEvent("morphic-run",{detail:f})),f}hasClipboardContents(){return!!this.lastCopyData}getDeleteOptions(e){var n;const t=(n=[...this.views].find(s=>s.name===e))==null?void 0:n.delete;return{lineButtons:(t==null?void 0:t.lineButtons)!==!1,keys:(t==null?void 0:t.keys)!==!1,toolbarButton:(t==null?void 0:t.toolbarButton)!==!1}}hasSelectedLines(e){var n;const t=this.resolveView(e);return(t==null?void 0:t.kind)==="codespace"&&!!((n=t.editor)!=null&&n.getSelectedLines())}deleteSelectedLines(e){var s;const t=this.resolveView(e),n=(t==null?void 0:t.kind)==="codespace"?(s=t.editor)==null?void 0:s.getSelectedLines():null;return!(t!=null&&t.editor)||!n?!1:(t.editor.clearSelection(),this.deleteBlockAtCodespaceLine(t.editor,n.first,n.last),!0)}copyActiveBlock(e){var s;const t=this.resolveActiveBlock(e);if(!t)return!1;const n=t.toCopyData();if(!n)return!1;this.lastCopyData=n;try{const r=this.blockTextIn(e,t);r&&((s=navigator.clipboard)==null||s.writeText(r))}catch{}for(const r of this.toolbars)r.refresh();return!0}blockTextIn(e,t){var d,h;const n=this.resolveView(e),{code:s,metadata:r}=n!=null&&n.editor?{code:n.editor.getValue(),metadata:n.editor.metadata}:this.generateElementText((n==null?void 0:n.element)??((d=this.mountConfig)==null?void 0:d.workspaceElement)),c=r.get(t.id);if((c==null?void 0:c.startChar)===void 0||c.endChar===void 0)return"";const a=s.lastIndexOf(`
|
|
52
|
+
`,c.startChar-1)+1,l=((h=/^[ \t]*/.exec(s.slice(a)))==null?void 0:h[0])??"";return s.slice(c.startChar,c.endChar).split(`
|
|
53
|
+
`).map((u,f)=>f>0&&u.startsWith(l)?u.slice(l.length):u).join(`
|
|
54
|
+
`)}pasteActiveBlock(e){return!this.lastCopyData||!this.workspace?!1:S.clipboard.paste(this.lastCopyData,this.workspace)!==null}resolveActiveBlock(e){var a,l,d;const t=S.common.getSelected();if(t&&"id"in t&&((a=this.workspace)!=null&&a.getBlockById(t.id)))return t;const n=(l=this.resolveView(e))==null?void 0:l.editor;if(!n)return null;const s=n.getCursorLine();let r=null;for(const[h,u]of n.metadata)if(u.startLine<=s&&u.endLine>=s){const f=u.endLine-u.startLine;(!r||f<r.size)&&(r={id:h,size:f})}return(r?(d=this.workspace)==null?void 0:d.getBlockById(r.id):null)??null}serializeWorkspace(){return this.workspace?S.serialization.workspaces.save(this.workspace):null}loadWorkspace(e){this.workspace&&(this.workspace.clear(),S.serialization.workspaces.load(e,this.workspace))}zoomPane(e,t){var r;const n=this.resolveView(e),s=n==null?void 0:n.workspace;if(s){t==="in"?s.zoomCenter(1):t==="out"?s.zoomCenter(-1):s.zoomToFit();return}(r=n==null?void 0:n.editor)==null||r.adjustZoom(t)}refreshToolbars(e){for(const t of this.toolbars)t.view===e&&t.refresh()}ensureToolbarBlocklyListener(){if(this.toolbarsBlocklyListener||!this.workspace)return;const e=t=>{for(const n of this.toolbars)n.refresh()};this.toolbarsBlocklyListener=e,this.workspace.addChangeListener(e)}teardownToolbarBlocklyListener(){!this.toolbarsBlocklyListener||!this.workspace||(this.workspace.removeChangeListener(this.toolbarsBlocklyListener),this.toolbarsBlocklyListener=void 0)}show(e){var s,r,c,a,l;if(!this.mountConfig||!this.workspace)throw new Error("MorphicBlocks must be mounted before show can be used.");if(e.toolbox!==void 0&&!this.modeDef(e.toolbox))throw new Error(`show: unknown mode "${e.toolbox}" for the toolbox.`);if(e.blockSet&&!this.blockSetLists.has(e.blockSet))throw new Error(`show: unknown block set "${e.blockSet}".`);for(const[d,h]of Object.entries(e.views??{})){if(!this.mountConfig.viewDeclarations[d]&&!this.resolveView(d))throw new Error(`show: no view named "${d}".`);this.checkViewElement("show",h)}const t=e.blockSet!==void 0&&e.blockSet!==this.activeBlockSet;t&&(this.activeBlockSet=e.blockSet??void 0,(s=this.toolboxCanvas)==null||s.setBlocks(this.toolboxBlocks()));const n=e.categories!==void 0&&e.categories!==this.categoriesShown;n&&(this.categoriesShown=e.categories,(r=this.toolboxCanvas)==null||r.setGrouped(this.categoriesShown)),(t||n)&&(this.toolboxDefinition=this.resolveToolboxDefinition(this.mountConfig)),e.toolbox&&(this.mountConfig.toolboxMode=e.toolbox),(e.toolbox||t||n)&&((c=this.toolboxCanvas)==null||c.rerender(this.mountConfig.toolboxMode),this.refreshToolbox(),this.bindFlyoutWorkspace(),this.renderFlyoutBlocks());for(const[d,h]of Object.entries(e.views??{})){d===this.mountConfig.programView&&h!==this.mountConfig.workspaceElement&&(this.mountConfig.workspaceElement=h,this.applyWorkspaceContainerClass(),this.syncWorkspaceFont(),this.renderWorkspaceBlocks());const u=[...this.views].find(f=>f.name===d);u&&u.element!==h&&((a=u.show)==null||a.call(u,h))}this.refreshTextViews();for(const d of this.toolbars)d.refresh();(l=this.selectionSync)==null||l.clearAll()}setModes(e){throw new Error('setModes was replaced by show() in 0.4.0: show({ toolbox: "<mode>", views: { "<view>": "<element>" } }).')}generateJavaScript(){if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before generateJavaScript can be used.");return Ci(this.workspace,this.definitions,this.behaviors,this.mountConfig.javascript)}generateText(e){if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before generateText can be used.");return this.checkViewElement("generateText",e),this.generateElementText(e).code}loadText(e,t){var r;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before loadText can be used.");this.checkViewElement("loadText",t.element);const n=cs(e,t.element,this.definitions,(r=this.mountConfig.code)==null?void 0:r[t.element]);if(!n.ok)return n;const s=S.Events.getGroup();s||S.Events.setGroup(!0),$n(S.Events.getGroup());try{S.serialization.workspaces.load({blocks:{languageVersion:0,blocks:n.stacks}},this.workspace,{recordUndo:!0});let c=20;for(const a of this.workspace.getTopBlocks(!1)){const l=a.getRelativeToSurfaceXY();a.moveBy(20-l.x,c-l.y),c+=a.getHeightWidth().height+20}}finally{s||S.Events.setGroup(!1)}return{ok:!0,blocks:n.blocks}}generateJavaScriptWithMetadata(){if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before generateJavaScriptWithMetadata can be used.");return Si(this.workspace,this.definitions,this.behaviors,this.mountConfig.javascript)}async mountCodeEditor(e,t){var s;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before mountCodeEditor can be used.");(s=this.codeEditor)==null||s.dispose(),this.codeEditor=new Bo(e,this.workspace,()=>this.generateJavaScriptWithMetadata(),t,!0);const n=this.codeEditor;await n.mount(),this.codeEditor===n&&this.refreshSelectionSync()}attachCodespaceDropTarget(e,t,n){const s=E=>{var O;const M=(O=E.dataTransfer)==null?void 0:O.types;return M?M.includes(Ne)||M.includes(Ot):!1},r=()=>{e.hideDropIndicator(),e.hideValueSlotHighlight()},c=(E,M)=>{const O=this.computeCodespaceDrop(e,E,M);if(!O){r();return}O.indicator.kind==="line"?(e.showDropIndicator(O.indicator.line,O.indicator.position),e.hideValueSlotHighlight()):(e.showValueSlotHighlight(O.indicator.from,O.indicator.to),e.hideDropIndicator())},a=E=>{s(E)&&(E.preventDefault(),c(E.clientX,E.clientY))},l=E=>{const M=E.relatedTarget;M&&t.contains(M)||r()},d=E=>{var M,O;s(E)&&(E.preventDefault(),h(E.clientX,E.clientY,(M=E.dataTransfer)==null?void 0:M.getData(Ne),(O=E.dataTransfer)==null?void 0:O.getData(Ot)))},h=(E,M,O,A)=>{r();const N=this.computeCodespaceDrop(e,E,M);if(!N)return;let V=null;if(O)V=n.newBlock(ke(O,this.definitions)),this.placeOrphanBelowTops(V),V.initSvg(),V.render();else if(A){if(V=n.getBlockById(A),!V)return}else return;const m=this.fitOrLoose(n,V,N);if(!m){O&&V.dispose(!1);return}let x=!1;S.Events.setGroup(!0);try{if(A&&V.getParent()&&V.unplug(!0),m.target.kind==="top")this.placeAtTopIndex(n,V,m.target.index),x=!0;else if(m.target.kind==="statement"){if(V.previousConnection){const B=n.getBlockById(m.target.targetBlockId);B&&B!==V&&(this.connectStatement(V,B,m.target.position),x=!0)}}else if(m.target.kind==="into-slot"){if(V.previousConnection){const B=n.getBlockById(m.target.parentBlockId);B&&B!==V&&(this.connectIntoSlot(V,B,m.target.inputName),x=!0)}}else if(m.target.kind==="value-slot"){if(V.outputConnection){const B=n.getBlockById(m.target.parentBlockId);B&&B!==V&&!this.isDescendantOf(B,V)&&(x=this.connectIntoValueSlot(V,B,m.target.inputName))}!x&&O&&V.dispose(!1)}}finally{S.Events.setGroup(!1)}!x&&V.workspace&&!V.getParent()&&this.placeOrphanBelowTops(V),S.svgResize(n)};let u=null;const f=3,p=E=>E.button===2||E.button===0&&E.ctrlKey,g=E=>{if(!u)return;if(!u.dragging){const O=Math.abs(E.clientX-u.startX),A=Math.abs(E.clientY-u.startY);if(O+A<f)return;u.dragging=!0}const M=this.computeCodespaceDrop(e,E.clientX,E.clientY);if(!M){e.hideDropIndicator(),e.hideValueSlotHighlight();return}M.indicator.kind==="line"?(e.showDropIndicator(M.indicator.line,M.indicator.position),e.hideValueSlotHighlight()):(e.showValueSlotHighlight(M.indicator.from,M.indicator.to),e.hideDropIndicator())},v=E=>{window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",v),e.hideDropIndicator(),e.hideValueSlotHighlight();const M=u;if(u=null,xo(void 0),!(M!=null&&M.dragging))return;const O=this.computeCodespaceDrop(e,E.clientX,E.clientY);if(!O)return;const A=n.getBlockById(M.sourceId);A&&this.applyRightDragMove(n,A,O)},w=E=>{if(!p(E))return;const M=e.charAtCoords(E.clientX,E.clientY);if(M==null)return;const O=this.findInnermostBlockAtChar(e,M);O&&(E.preventDefault(),E.stopPropagation(),u={sourceId:O.id,startX:E.clientX,startY:E.clientY,dragging:!1},xo(O.id),window.addEventListener("mousemove",g),window.addEventListener("mouseup",v))},C=E=>{E.preventDefault()},T=E=>{if(u)return;const M=e.charAtCoords(E.clientX,E.clientY);if(M==null){e.setHoverHighlight(null),e.setEditableHoverHighlight(null);return}const O=this.findInnermostEditablePlaceholderAtChar(e,M);e.setEditableHoverHighlight(O?{from:O.start,to:O.end}:null);const A=this.findHoverBlockAtChar(e,M);if(!A){e.setHoverHighlight(null);return}const N=e.metadata.get(A.id);if(!N||N.startChar===void 0||N.endChar===void 0){e.setHoverHighlight(null);return}e.setHoverHighlight({from:N.startChar,to:N.endChar})},F=()=>{e.setHoverHighlight(null),e.setEditableHoverHighlight(null)},$={element:t,over:c,leave:r,drop:(E,M,O)=>h(M,O,E)};return this.tileDropTargets.add($),t.addEventListener("dragover",a),t.addEventListener("dragleave",l),t.addEventListener("drop",d),t.addEventListener("mousedown",w,!0),t.addEventListener("contextmenu",C),t.addEventListener("mousemove",T),t.addEventListener("mouseleave",F),()=>{this.tileDropTargets.delete($),t.removeEventListener("dragover",a),t.removeEventListener("dragleave",l),t.removeEventListener("drop",d),t.removeEventListener("mousedown",w,!0),t.removeEventListener("contextmenu",C),t.removeEventListener("mousemove",T),t.removeEventListener("mouseleave",F),window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",v)}}findInnermostBlockAtChar(e,t){if(!this.workspace)return null;let n=null;for(const[s,r]of e.metadata){if(r.startChar===void 0||r.endChar===void 0||t<r.startChar||t>=r.endChar)continue;const c=r.endChar-r.startChar;(n===null||c<n.size)&&(n={id:s,size:c})}return n?this.workspace.getBlockById(n.id):null}findHoverBlockAtChar(e,t){if(!this.workspace)return null;let n=null,s=null;for(const[c,a]of e.metadata){if(a.startChar===void 0||a.endChar===void 0||t<a.startChar||t>=a.endChar)continue;const l=a.endChar-a.startChar;(s===null||l<s.size)&&(s={id:c,size:l}),!a.atomic&&(n===null||l<n.size)&&(n={id:c,size:l})}const r=n??s;return r?this.workspace.getBlockById(r.id):null}findInnermostEditablePlaceholderAtChar(e,t){let n=null;for(const s of e.getPlaceholders()){if(!s.edit||t<s.start||t>=s.end)continue;const r=s.end-s.start;(n===null||r<n.size)&&(n={ph:s,size:r})}return n?{start:n.ph.start,end:n.ph.end}:null}applyRightDragMove(e,t,n){if(!n||(n=this.fitOrLoose(e,t,n),!n))return;let s=!1;S.Events.setGroup(!0);try{if(t.getParent()&&t.unplug(!0),n.target.kind==="top")this.placeAtTopIndex(e,t,n.target.index),s=!0;else if(n.target.kind==="statement"){if(t.previousConnection){const r=e.getBlockById(n.target.targetBlockId);r&&r!==t&&(this.connectStatement(t,r,n.target.position),s=!0)}}else if(n.target.kind==="into-slot"){if(t.previousConnection){const r=e.getBlockById(n.target.parentBlockId);r&&r!==t&&(this.connectIntoSlot(t,r,n.target.inputName),s=!0)}}else if(n.target.kind==="value-slot"&&t.outputConnection){const r=e.getBlockById(n.target.parentBlockId);r&&r!==t&&!this.isDescendantOf(r,t)&&(s=this.connectIntoValueSlot(t,r,n.target.inputName))}}finally{S.Events.setGroup(!1)}!s&&t.workspace&&!t.getParent()&&this.placeOrphanBelowTops(t),S.svgResize(e)}computeCodespaceDrop(e,t,n){var f,p;if(!this.workspace)return null;const s=this.workspace.getTopBlocks(!0),r=e.metadata,c=e.getLineCount();if(s.length===0)return{indicator:{kind:"line",line:1,position:"above"},target:{kind:"top",index:0}};if(e.isBelowLastLine(n)){const g=r.get(s[s.length-1].id);return{indicator:{kind:"line",line:(g==null?void 0:g.endLine)??c,position:"below"},target:{kind:"top",index:s.length}}}const a=e.getLineAtCoords(t,n);if(a===null){const g=r.get(s[0].id);return{indicator:{kind:"line",line:(g==null?void 0:g.startLine)??1,position:"above"},target:{kind:"top",index:0}}}const l=e.charAtCoords(t,n);if(l!==null){const g=this.findValueSlotDropAtChar(e,l);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 d=this.findInnermostStatementSlotAtLine(a,r);if(d){const g=this.workspace.getBlockById(d.blockId);if(g){const v=Dt(),w=[];let C=(p=(f=g.getInput(d.inputName))==null?void 0:f.connection)==null?void 0:p.targetBlock();for(;C;)C.id!==v&&w.push(C),C=C.getNextBlock();for(const T of w){const F=r.get(T.id);if(!F||a<F.startLine||a>F.endLine)continue;const $=a===F.endLine,E=e.isInLowerHalfOfLine(a,n);return $&&E?{indicator:{kind:"line",line:F.endLine,position:"below"},target:{kind:"statement",targetBlockId:T.id,position:"after"}}:{indicator:{kind:"line",line:F.startLine,position:"above"},target:{kind:"statement",targetBlockId:T.id,position:"before"}}}if(w.length>0){const T=w[w.length-1],F=r.get(T.id);return{indicator:{kind:"line",line:(F==null?void 0:F.endLine)??d.range.endLine,position:"below"},target:{kind:"into-slot",parentBlockId:d.blockId,inputName:d.inputName}}}return{indicator:{kind:"line",line:d.range.startLine,position:"above"},target:{kind:"into-slot",parentBlockId:d.blockId,inputName:d.inputName}}}}const h=Dt();for(let g=0;g<s.length;g++)for(let v=s[g];v;v=v.getNextBlock()){if(v.id===h)continue;const w=r.get(v.id);if(!w||a<w.startLine||a>w.endLine)continue;const C=a===w.endLine,T=e.isInLowerHalfOfLine(a,n),F=C&&T,$=F&&!v.getNextBlock();return{indicator:F?{kind:"line",line:w.endLine,position:"below"}:{kind:"line",line:w.startLine,position:"above"},target:{kind:"statement",targetBlockId:v.id,position:F?"after":"before",topIndex:$?g+1:g}}}const u=r.get(s[s.length-1].id);return{indicator:{kind:"line",line:(u==null?void 0:u.endLine)??c,position:"below"},target:{kind:"top",index:s.length}}}findInnermostStatementSlotAtLine(e,t){let n=null;for(const[s,r]of t)if(r.statementSlots)for(const[c,a]of Object.entries(r.statementSlots)){if(e<a.startLine||e>a.endLine)continue;const l=a.endLine-a.startLine,d=this.computeBlockDepth(s);(n===null||l<n.size||l===n.size&&d>n.depth)&&(n={blockId:s,inputName:c,range:a,size:l,depth:d})}return n?{blockId:n.blockId,inputName:n.inputName,range:n.range}:null}fitOrLoose(e,t,n){return this.codespaceDropAllowed(e,t,n.target)?n:n.target.kind==="statement"&&n.target.topIndex!==void 0?{...n,target:{kind:"top",index:n.target.topIndex}}:null}codespaceDropAllowed(e,t,n){var a,l,d;const s=(h,u)=>!!h&&!!u&&e.connectionChecker.canConnect(h,u,!1);if(n.kind==="top")return!0;if(n.kind==="value-slot"){const h=e.getBlockById(n.parentBlockId);return s((a=h==null?void 0:h.getInput(n.inputName))==null?void 0:a.connection,t.outputConnection)}if(n.kind==="into-slot"){const h=e.getBlockById(n.parentBlockId),u=(l=h==null?void 0:h.getInput(n.inputName))==null?void 0:l.connection;let f=u==null?void 0:u.targetBlock();for(;f!=null&&f.getNextBlock()&&f.getNextBlock()!==t;)f=f.getNextBlock();return s(f&&f!==t?f.nextConnection:u,t.previousConnection)}const r=e.getBlockById(n.targetBlockId);if(!r||r===t)return!1;if(n.position==="before"){const h=(d=r.previousConnection)==null?void 0:d.targetConnection;return h&&h.getSourceBlock()!==t&&!s(h,t.previousConnection)?!1:s(t.nextConnection,r.previousConnection)}const c=r.getNextBlock();return s(r.nextConnection,t.previousConnection)?!c||c===t||s(t.nextConnection,c.previousConnection):!1}connectIntoSlot(e,t,n){if(!e.previousConnection)return;const s=t.getInput(n),r=s==null?void 0:s.connection;if(!r)return;const c=r.targetBlock();if(!c){r.connect(e.previousConnection);return}let a=c,l=a.getNextBlock();for(;l;)a=l,l=a.getNextBlock();a.nextConnection&&a.nextConnection.connect(e.previousConnection)}findValueSlotDropAtChar(e,t){var r,c;if(!this.workspace)return null;const n=Dt();for(const a of e.getPlaceholders()){if(t<a.start||t>=a.end)continue;if(a.emptySlot){const{parentBlockId:u,inputName:f}=a.emptySlot;if(u===n)continue;const p=this.workspace.getBlockById(u);if(!((r=p==null?void 0:p.getInput(f))!=null&&r.connection))continue;return{parentBlockId:u,inputName:f,highlight:{from:a.start,to:a.end}}}const l=(c=a.edit)==null?void 0:c.blockId;if(!l||l===n)continue;const d=this.workspace.getBlockById(l);if(!d)continue;const h=this.resolveValueParent(d);if(h)return{parentBlockId:h.parentBlockId,inputName:h.inputName,highlight:{from:a.start,to:a.end}}}let s=null;for(const[a,l]of e.metadata){if(l.startChar===void 0||l.endChar===void 0||t<l.startChar||t>=l.endChar||a===n)continue;const d=this.workspace.getBlockById(a);if(!(d!=null&&d.outputConnection))continue;const h=l.endChar-l.startChar;(s===null||h<s.size)&&(s={id:a,size:h,from:l.startChar,to:l.endChar})}if(s){const a=this.workspace.getBlockById(s.id);if(a){const l=this.resolveValueParent(a);if(l)return{parentBlockId:l.parentBlockId,inputName:l.inputName,highlight:{from:s.from,to:s.to}}}}return null}resolveValueParent(e){var s;const t=(s=e.outputConnection)==null?void 0:s.targetConnection;if(!t)return null;const n=t.getSourceBlock();if(!n)return null;for(const r of n.inputList)if(r.connection===t)return{parentBlockId:n.id,inputName:r.name};return null}addBlockFromTile(e){const t=this.workspace;if(!t)return;const n=S.common.getSelected(),s=n instanceof S.BlockSvg&&n.workspace===t?n:null;S.Events.setGroup(!0);try{const r=t.newBlock(ke(e,this.definitions)),c=s&&!s.isShadow()?{kind:"statement",targetBlockId:s.id,position:"after"}:null,a=c!==null&&this.codespaceDropAllowed(t,r,c);a||this.placeOrphanBelowTops(r),r.initSvg(),r.render(),a&&s&&this.connectStatement(r,s,"after"),S.common.setSelected(r);const l=t.getMetricsManager().getViewMetrics(!0),d=r.getBoundingRectangle();d.left>=l.left&&d.top>=l.top&&d.right<=l.left+l.width&&d.bottom<=l.top+l.height||t.centerOnBlock(r.id)}finally{S.Events.setGroup(!1)}}placeOrphanBelowTops(e){var s,r;if(!this.workspace)return;const t=this.workspace.getTopBlocks(!0).filter(c=>c.id!==e.id);if(t.length===0){e.moveTo(new S.utils.Coordinate(20,20));return}let n=0;for(const c of t){const a=c.getRelativeToSurfaceXY(),l=((r=(s=c.getHeightWidth)==null?void 0:s.call(c))==null?void 0:r.height)??50;n=Math.max(n,a.y+l)}e.moveTo(new S.utils.Coordinate(20,n+20))}isDescendantOf(e,t){let n=e;for(;n;){if(n===t)return!0;n=n.getParent()}return!1}connectIntoValueSlot(e,t,n){if(!e.outputConnection)return!1;const s=t.getInput(n),r=s==null?void 0:s.connection;if(!r)return!1;const c=r.targetBlock(),a=!!c&&!c.isShadow();a&&c.unplug(!1);try{r.connect(e.outputConnection)}catch{if(a&&(c!=null&&c.outputConnection))try{r.connect(c.outputConnection)}catch{}return!1}if(a&&c.outputConnection){const l=S.Connection.getConnectionForOrphanedConnection(e,c.outputConnection);l?l.connect(c.outputConnection):this.placeOrphanBelowTops(c)}return!0}computeBlockDepth(e){var s,r;let t=0,n=((r=(s=this.workspace)==null?void 0:s.getBlockById(e))==null?void 0:r.getParent())??null;for(;n;)t++,n=n.getParent();return t}placeAtTopIndex(e,t,n){const s=e.getTopBlocks(!0).map(c=>c.id).filter(c=>c!==t.id),r=Math.max(0,Math.min(n,s.length));s.splice(r,0,t.id),this.applyTopBlockOrder(e,s)}connectStatement(e,t,n){var s,r,c;if(e.previousConnection)if(n==="before"){const a=((s=t.previousConnection)==null?void 0:s.targetConnection)??null;(r=t.previousConnection)==null||r.disconnect(),a?a.connect(e.previousConnection):e.moveTo(t.getRelativeToSurfaceXY()),e.nextConnection&&t.previousConnection&&e.nextConnection.connect(t.previousConnection)}else{const a=t.getNextBlock();(c=a==null?void 0:a.previousConnection)==null||c.disconnect(),t.nextConnection&&t.nextConnection.connect(e.previousConnection),a!=null&&a.previousConnection&&e.nextConnection&&e.nextConnection.connect(a.previousConnection)}}applyTopBlockOrder(e,t){const n=S.Events.disable!==void 0;n&&S.Events.disable();try{let s=20;for(const r of t){const c=e.getBlockById(r);c&&(c.moveTo(new S.utils.Coordinate(20,s)),s+=c.getHeightWidth().height+20)}}finally{n&&S.Events.enable()}S.svgResize(e),this.refreshTextViews()}refreshTextViews(){var e,t;(e=this.codeEditor)==null||e.refresh();for(const n of this.views)(t=n.editor)==null||t.refresh()}generateElementText(e){return!this.workspace||!this.mountConfig||!e?{code:"",metadata:new Map,placeholders:[]}:Vo(this.workspace,e,this.definitions,this.elementTypes,this.mountConfig.modes??[],e)}highlightRulesFor(e){var t,n,s;return(s=(n=(t=this.mountConfig)==null?void 0:t.code)==null?void 0:n[e])==null?void 0:s.highlighting}defaultElement(e){return(e[0]?Wi(e[0],this.elementTypes):void 0)??Object.keys(this.elementTypes).find(n=>pe(this.elementTypes[n])==="code")??"default"}addView(e){var d,h,u;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before addView can be used.");if(e.kind==="preview")throw new Error('addView: the preview is a codespace that cannot be edited since 0.4.0: { kind: "codespace", editable: false }.');if(e.kind!=="codespace"&&e.kind!=="workspace")throw new Error(`addView: unknown view kind "${String(e.kind)}".`);if(e.name!==void 0&&this.resolveView(e.name))throw new Error(`addView: a view named "${e.name}" already exists.`);if(e.kind==="workspace")return this.addWorkspaceView(e);this.checkViewElement("addView",e.element);const t=e.editable!==!1,n=new Bo(e.container,this.workspace,()=>this.generateElementText(c.element),{theme:e.theme,highlightRules:this.highlightRulesFor(e.element),...t?{onDelete:(f,p)=>this.deleteBlockAtCodespaceLine(n,f,p),onLineSelection:()=>this.refreshToolbars(c.name),deleteButtons:(d=e.delete)==null?void 0:d.lineButtons,deleteKeys:(h=e.delete)==null?void 0:h.keys,canDragBlock:f=>this.canMoveInCodespace(f),onPlaceholderApply:(f,p)=>this.applyPlaceholderEdit(f,p),onRepeat:(f,p,g)=>{var w;const v=(w=this.workspace)==null?void 0:w.getBlockById(f);v&&this.changeRepeat(v,p,g)}}:{showPlaceholderMarkers:!1}}),s=t?["morphic-codespace-root"]:["morphic-codespace-root","morphic-read-only"];let r=e.name;for(;r===void 0||this.resolveView(r);)r=`view-${++this.viewCount}`;const c={kind:e.kind,name:r,container:e.container,element:e.element,editor:n,editable:t,delete:e.delete};this.views.add(c),e.rtl!==void 0&&(e.container.dir=e.rtl?"rtl":"ltr"),lt(c.container,{name:r,element:c.element,classNames:s}),dt(c.container,(u=this.activePreset)==null?void 0:u.name);const a=e.toolbar?this.mountToolbar(e.toolbar.container,{view:r,items:e.toolbar.items,display:e.toolbar.display}):void 0,l={kind:c.kind,name:c.name,ready:n.mount().then(()=>{this.views.has(c)&&(t&&this.workspace&&(c.teardown=this.attachCodespaceDropTarget(n,c.container,this.workspace)),this.linkAddedView())}),getElement:()=>c.element,show:f=>{if(this.views.has(c)){this.checkViewElement("show",f),c.element=f,lt(c.container,{name:r,element:f,classNames:s}),n.setHighlightRules(this.highlightRulesFor(f)),n.refresh();for(const p of this.toolbars)p.refresh()}},setTheme:f=>n.setTheme(f),dispose:()=>{var f;this.views.delete(c)&&(a==null||a.dispose(),(f=c.teardown)==null||f.call(c),n.dispose(),this.refreshSelectionSync())}};return c.show=l.show,l}addWorkspaceView(e){var F;const t=this.workspace;this.checkViewElement("addView",e.element);let n=e.name;for(;n===void 0||this.resolveView(n);)n=`view-${++this.viewCount}`;const s=t.options,r=e.editable!==!1,c=S.inject(e.container,{readOnly:!r,media:s.pathToMedia,sounds:!1,renderer:s.renderer,rendererOverrides:s.rendererOverrides??void 0,theme:this.baseTheme??s.theme,rtl:e.rtl??s.RTL,move:{scrollbars:!0,drag:!0,wheel:!0}});co(c),Ve.set(c,this),this.viewWorkspaceElements.set(c,e.element);const a={kind:"workspace",name:n,container:e.container,element:e.element,workspace:c,editable:r};this.views.add(a),this.styleWorkspaceView(a),dt(a.container,(F=this.activePreset)==null?void 0:F.name);const l=()=>{const{scrollX:$,scrollY:E,scale:M}=c;S.Events.disable();try{S.serialization.workspaces.load(S.serialization.workspaces.save(t),c)}finally{S.Events.enable()}this.renderWorkspaceView(a),c.scale!==M&&c.setScale(M),c.scroll($,E)};l();let d=null,h=!1;const u=()=>{var $;for(const E of c.getAllBlocks(!1))E.unselect();($=c.getBlockById(d??""))==null||$.select()},f=$=>{if($.workspaceId!==t.id)return;if($.type===S.Events.SELECTED){d=$.newElementId??null,u();return}if($.isUiEvent||h)return;h=!0;const E=()=>{if(this.views.has(a)){if(r&&(c.isDragging()||S.WidgetDiv.isVisible()||S.DropDownDiv.isVisible())){setTimeout(E,100);return}h=!1,l(),u()}};setTimeout(E,0)};t.addChangeListener(f);const p=$=>{if($.isUiEvent||$.workspaceId!==c.id)return;const E=S.Events.getGroup();S.Events.setGroup($.group||E||!0);try{S.Events.fromJson($.toJson(),t).run(!0)}catch{}finally{S.Events.setGroup(E)}},g=r?this.attachWorkspaceTileDrop(c,e.container):void 0;r&&(c.addChangeListener(p),c.undo=$=>t.undo($));const v=$=>{var A;const E=$.target,M=(A=E==null?void 0:E.closest)==null?void 0:A.call(E,"[data-id]");let O=M?t.getBlockById(M.getAttribute("data-id")??""):null;for(;O!=null&&O.isShadow();)O=O.getParent();O?S.common.setSelected(O):E!=null&&E.classList.contains("blocklyMainBackground")&&S.common.setSelected(null)};e.container.addEventListener("click",v);const w=typeof ResizeObserver<"u"?new ResizeObserver(()=>S.svgResize(c)):void 0;w==null||w.observe(e.container);const C=e.toolbar?this.mountToolbar(e.toolbar.container,{view:n,items:e.toolbar.items,display:e.toolbar.display}):void 0;a.teardown=()=>{t.removeChangeListener(f),c.removeChangeListener(p),g==null||g(),e.container.removeEventListener("click",v),w==null||w.disconnect(),C==null||C.dispose()};const T={kind:"workspace",name:n,ready:Promise.resolve(),getElement:()=>a.element,show:$=>{if(this.views.has(a)){this.checkViewElement("show",$),a.element=$,this.viewWorkspaceElements.set(c,$),this.styleWorkspaceView(a),this.renderWorkspaceView(a);for(const E of this.toolbars)E.refresh()}},setTheme:()=>{},dispose:()=>{this.views.delete(a)&&this.disposeView(a)}};return a.show=T.show,T}styleWorkspaceView(e){e.workspace&&(lt(e.container,{name:e.name,element:e.element,classNames:["morphic-workspace-root","morphic-context-workspace",...e.editable===!1?["morphic-read-only"]:[]]}),this.syncFontOf(e.workspace,e.container))}renderWorkspaceView(e){var t;S.Events.disable();try{for(const n of((t=e.workspace)==null?void 0:t.getAllBlocks(!1))??[]){const s=this.definitions.get(he(n.type));s&&this.applyView(n,s,e.element,"workspace")}}finally{S.Events.enable()}}attachWorkspaceTileDrop(e,t){const n=(a,l,d)=>{const h=this.workspace;if(!h)return;const u=e.getInjectionDiv().getBoundingClientRect(),f=h.newBlock(ke(a,this.definitions));f.moveTo(new S.utils.Coordinate((l-u.left-e.scrollX)/e.scale,(d-u.top-e.scrollY)/e.scale)),f.initSvg(),f.render()},s=a=>{var l;(l=a.dataTransfer)!=null&&l.types.includes(Ne)&&a.preventDefault()},r=a=>{var d;const l=(d=a.dataTransfer)==null?void 0:d.getData(Ne);l&&(a.preventDefault(),n(l,a.clientX,a.clientY))},c={element:t,drop:n};return this.tileDropTargets.add(c),t.addEventListener("dragover",s),t.addEventListener("drop",r),()=>{this.tileDropTargets.delete(c),t.removeEventListener("dragover",s),t.removeEventListener("drop",r)}}disposeView(e){var t,n,s;(t=e.teardown)==null||t.call(e),(n=e.editor)==null||n.dispose(),(s=e.workspace)==null||s.dispose()}linkAddedView(){var t,n;if(this.selectionSync){this.refreshSelectionSync();return}const e=(t=this.mountConfig)==null?void 0:t.selectionSync;e===!1||!((n=this.mountConfig)!=null&&n.programView)||this.enableSelectionSync(typeof e=="object"?e:void 0)}resolveView(e){var t,n;if(this.workspace&&e===((t=this.mountConfig)==null?void 0:t.programView))return{name:e,kind:"workspace",element:this.mountConfig.workspaceElement,workspace:this.workspace,readOnly:((n=this.mountConfig.viewDeclarations[e])==null?void 0:n.editable)===!1};for(const s of this.views)if(s.name===e)return{name:e,kind:s.kind,element:s.element,editor:s.editor,workspace:s.workspace,readOnly:s.editable===!1}}getViewElement(e){var t;return(t=this.resolveView(e))==null?void 0:t.element}checkViewElement(e,t){if(pe(this.elementTypes[t])==="code")return;const n=!!this.modeDef(t);throw new Error(`${e}: "${t}" is no code element.`+(n?` Views show elements since 0.4.0, and "${t}" is a mode.`:""))}applyPlaceholderEdit(e,t){var a;if(!this.workspace)return;let n=this.workspace.getBlockById(e.blockId);if(!n)return;if(n.isShadow()){const l=(a=n.outputConnection)==null?void 0:a.targetConnection;if(l){const d=this.workspace.newBlock(n.type);for(const h of n.inputList)for(const u of h.fieldRow){if(!u.name)continue;const f=d.getField(u.name);f&&f.setValue(u.getValue())}n.rendered&&(d.initSvg(),d.render()),l.connect(d.outputConnection),n=d}}const s=n.getField(e.fieldName);if(!s)return;s.setValue(t);const r=n;r.rendered&&typeof r.render=="function"&&r.render();const c=n.getParent();if(c){const l=c;l.rendered&&typeof l.render=="function"&&l.render()}}canMoveInCodespace(e){var n;const t=(n=this.workspace)==null?void 0:n.getBlockById(e);return!!(t!=null&&t.previousConnection||t!=null&&t.outputConnection)}deleteBlockAtCodespaceLine(e,t,n=t){const s=new Set;for(let a=t;a<=n;a++){const l=this.blockOwningLine(e,a);l&&s.add(l)}const r=a=>{for(let l=a.getSurroundParent();l;l=l.getSurroundParent())if(s.has(l))return!0;return!1},c=[...s].filter(a=>!r(a));if(c.length!==0){S.Events.setGroup(!0);try{for(const a of c)a.dispose(!0)}finally{S.Events.setGroup(!1)}}}blockOwningLine(e,t){const n=e.metadata;if(!this.workspace||!n||n.size===0)return null;const s=a=>{let l=0;for(let d=a.getParent();d;d=d.getParent())l++;return l},r=[];for(const[a,{startLine:l,endLine:d}]of n){if(t<l||t>d)continue;const h=this.workspace.getBlockById(a);!h||h.isShadow()||!(h.previousConnection||h.nextConnection)&&h.getParent()||r.push({block:h,startLine:l,size:d-l,depth:s(h)})}const c=a=>{var l;return((l=a.sort((d,h)=>d.size-h.size||h.depth-d.depth)[0])==null?void 0:l.block)??null};return c(r.filter(a=>a.startLine===t))??c(r)}showCodeEditor(){var e;(e=this.codeEditor)==null||e.show()}hideCodeEditor(){var e;(e=this.codeEditor)==null||e.hide()}isCodeEditorVisible(){var e;return((e=this.codeEditor)==null?void 0:e.isVisible())??!1}setCodeEditorTheme(e){var t;(t=this.codeEditor)==null||t.setTheme(e)}setViewTheme(e,t){var n,s;(s=(n=this.resolveView(e))==null?void 0:n.editor)==null||s.setTheme(t)}enableSelectionSync(e){var n;if(!this.workspace)throw new Error("MorphicBlocks must be mounted before enableSelectionSync can be used.");const t=[this.codeEditor,...[...this.views].map(s=>s.editor)].filter(s=>s!==void 0);if(t.length===0)throw new Error("enableSelectionSync needs a text view or the code editor to be set up first.");(n=this.selectionSync)==null||n.disable(),this.selectionSyncOptions=e,this.selectionSync=new qi(this.workspace,t,e),this.selectionSync.enable()}refreshSelectionSync(){this.selectionSync&&(this.hasTextEditor()?this.enableSelectionSync(this.selectionSyncOptions):this.disableSelectionSync())}disableSelectionSync(){var e;(e=this.selectionSync)==null||e.disable(),this.selectionSync=void 0,this.selectionSyncOptions=void 0}registerBlocks(){for(const e of this.definitions.values()){const t=Ae(e.identifier);if(ze.set(t,this),this.registeredBlockTypes.has(t))continue;const n=e.identifier;S.Blocks[t]={init(){const s=Ve.get(this.workspace)??ze.get(t);s==null||s.initManagedBlock(this,n)},saveExtraState(){const s=Ve.get(this.workspace)??ze.get(t),r=s==null?void 0:s.definitions.get(n),c=r?Et(this,r):null,a=zn(this);return c||a?{...c,...a?{defaults:a}:{}}:null},loadExtraState(s){const r=Ve.get(this.workspace)??ze.get(t),c=r==null?void 0:r.definitions.get(n);r&&c&&r.loadBlockState(this,c,s)},mutationToDom(){const s=this.saveExtraState();if(!s)return null;const r=S.utils.xml.createElement("mutation");return r.setAttribute("state",JSON.stringify(s)),r},domToMutation(s){const r=s.getAttribute("state");r&&this.loadExtraState(JSON.parse(r))}},this.registeredBlockTypes.add(t)}}initManagedBlock(e,t){var d,h;const n=this.definitions.get(t);if(!n)return;const s=e.workspace.isFlyout?"toolbox":"workspace",r=this.viewWorkspaceElements.get(e.workspace)??this.resolveMode(s),c=e;c.__morphicFresh=!0,queueMicrotask(()=>{c.__morphicFresh=!1}),this.applyView(e,n,r,s),Hs(e);const a=Ge(this.behaviors[n.identifier]),l=s==="workspace"?No(n,r,this.elementTypes).elementName:Ze(n,r,this.elementTypes,((d=this.mountConfig)==null?void 0:d.modes)??[]).elementName;(h=a==null?void 0:a.init)==null||h.call(a,e,this.createBehaviorContext(e,n,l??r,s,r))}loadBlockState(e,t,n){var c,a;const s=Re(t);S.Events.disable();try{Un(e,n==null?void 0:n.defaults)}finally{S.Events.enable()}e.__morphicFresh=!1;const r=new Map([...s].map(([l,d])=>[l,Te(e,l,d)]));if(Mn(e,t,n)){S.Events.disable();try{for(const[l,d]of s)for(let h=Te(e,l,d);h<(r.get(l)??0);h++){const u=(a=(c=e.getInput(Se(l,h)))==null?void 0:c.connection)==null?void 0:a.targetBlock();u&&this.isSlotDefault(e,d,u)&&u.dispose(!1)}}finally{S.Events.enable()}this.rebuildBlock(e)}}isSlotDefault(e,t,n){const s=Qt(t,this.elementTypes[vo(e)??""]);return!n.isShadow()&&!!(s!=null&&s.placeholder)&&n.type===ke(s.placeholder,this.definitions)}rebuildBlock(e){const t=this.definitions.get(he(e.type));if(!t)return;const n=e.workspace.isFlyout?"toolbox":"workspace",s=this.viewWorkspaceElements.get(e.workspace)??this.resolveMode(n);S.Events.disable();try{this.applyView(e,t,s,n)}finally{S.Events.enable()}}changeRepeat(e,t,n){var d,h;const s=this.definitions.get(he(e.type)),r=s?Re(s).get(t):void 0;if(!s||!r)return;const c=Te(e,t,r),a=Math.max(0,c+n);if(a===c)return;const l=S.Events.getGroup();l||S.Events.setGroup(!0);try{const u=JSON.stringify(Et(e,s));for(let p=a;p<c;p++){const g=(h=(d=e.getInput(Se(t,p)))==null?void 0:d.connection)==null?void 0:h.targetBlock();if(!g||g.isShadow())continue;const v=this.isSlotDefault(e,r,g);g.unplug(),v&&g.dispose(!1)}for(let p=c;p<a;p++)Gn(e,Se(t,p));to(e,t,a),this.rebuildBlock(e);const f=S.Events.get(S.Events.BLOCK_CHANGE);S.Events.fire(new f(e,"mutation",null,u,JSON.stringify(Et(e,s))))}finally{l||S.Events.setGroup(!1)}}validateViews(e,t){yn(nn(e));for(const n of Object.keys(t))if(!e[n])throw new Error(`mount: a container for "${n}", but no view of that name. Declared views: ${Object.keys(e).join(", ")}.`);if(!Object.keys(e).some(n=>t[n]))throw new Error("MorphicBlocks.mount needs a container for at least one view.")}createHeadlessHost(){const e=document.createElement("div");return e.style.cssText="position:absolute;left:-9999px;top:-9999px;width:800px;height:600px;overflow:hidden;",document.body.appendChild(e),this.headlessWorkspaceHost=e,e}resolveMode(e){return this.mountConfig?e==="toolbox"?this.mountConfig.toolboxMode:this.mountConfig.workspaceElement:"default"}applyView(e,t,n,s){var h,u;if(e.isDeadOrDying())return;const r=this.blockCategoryIndex.get(t.identifier);t.color===void 0&&(r==null?void 0:r.color)!==void 0&&e.setColour(r.color);const c=e.__morphicFieldMemory??(e.__morphicFieldMemory=new Map);for(const[f,p]of li(e))c.set(f,p);const a=s==="workspace"?No(t,n,this.elementTypes):Ze(t,n,this.elementTypes,((h=this.mountConfig)==null?void 0:h.modes)??[]),l=e.workspace===this.workspace;go({block:e,definition:t,view:a,mode:n,context:s,elementTypes:l?this.elementTypes:void 0,codeSettings:this.elementTypes,resolveBlocklyType:f=>ke(f,this.definitions),onRepeat:s==="workspace"&&!e.workspace.options.readOnly?(f,p)=>this.changeRepeat(e,f,p):void 0}),this.styleBlock(e,t);const d=Ge(this.behaviors[t.identifier]);(u=d==null?void 0:d.onViewApplied)==null||u.call(d,e,this.createBehaviorContext(e,t,a.elementName??n,s,n)),s==="workspace"&&ai(e,t,a.elementName),di(e,c)}styleBlock(e,t){const n=this.blockCategoryIndex.get(t.identifier);Xn(e,n==null?void 0:n.token),Kn(e,t.identifier),Yn(e),t.color!==void 0&&(e.setColour(t.color),Bt(e)&&e.render())}applyWorkspaceContainerClass(){var s,r;if(!this.mountConfig)return;const e=this.mountConfig.workspaceHost,t=this.mountConfig.programView;lt(e,{name:t,element:this.mountConfig.workspaceElement,classNames:["morphic-workspace-root","morphic-context-workspace",...t&&((s=this.mountConfig.viewDeclarations[t])==null?void 0:s.editable)===!1?["morphic-read-only"]:[]]});const n=this.resolveClassNames((r=this.mountConfig.ui)==null?void 0:r.workspaceClassName);this.replaceUserClasses(e,this.appliedWorkspaceClasses,n),this.appliedWorkspaceClasses=n}syncWorkspaceFont(){var e;this.workspace&&((e=this.mountConfig)!=null&&e.workspaceHost)&&this.syncFontOf(this.workspace,this.mountConfig.workspaceHost)}syncFontOf(e,t){if(!this.baseTheme||!this.baseFont)return;const n=Zo(t,[[e.getRenderer().getClassName(),this.baseTheme.getClassName()]],this.baseFont);Qo(e,this.baseTheme,this.baseFont,n)&&Ht(e)}applyFlyoutClass(){var c,a,l;if(!this.workspace||!this.mountConfig)return;const e=this.resolveClassNames((c=this.mountConfig.ui)==null?void 0:c.toolboxClassName),t=this.workspace.getToolbox(),n=((a=t==null?void 0:t.getDiv)==null?void 0:a.call(t))??null;n&&(ko(n,this.mountConfig.toolboxMode,"toolbox","morphic-toolbox-shell"),this.replaceUserClasses(n,this.appliedToolboxShellClasses,e),this.appliedToolboxShellClasses=e);const s=(l=this.workspace.getFlyout())==null?void 0:l.getWorkspace(),r=s==null?void 0:s.getParentSvg();r&&(ko(r,this.mountConfig.toolboxMode,"toolbox","morphic-toolbox-root"),this.replaceUserClasses(r,this.appliedToolboxFlyoutClasses,e),this.appliedToolboxFlyoutClasses=e)}renderWorkspaceBlocks(){if(!(!this.workspace||!this.mountConfig))for(const e of this.workspace.getAllBlocks(!1)){const t=e,n=this.definitions.get(he(t.type));n&&this.applyView(t,n,this.mountConfig.workspaceElement,"workspace")}}renderFlyoutBlocks(){if(!(!this.flyoutWorkspace||!this.mountConfig)){for(const e of this.flyoutWorkspace.getAllBlocks(!1)){const t=e,n=this.definitions.get(he(t.type));n&&this.applyView(t,n,this.mountConfig.toolboxMode,"toolbox")}this.applyFlyoutClass()}}refreshToolbox(){var e;!this.workspace||!this.toolboxDefinition||(e=this.mountConfig)!=null&&e.canvasToolbox||this.workspace.options.readOnly||this.workspace.updateToolbox(this.toolboxDefinition)}bindFlyoutWorkspace(){var t;if(this.flyoutWorkspace&&(this.flyoutWorkspace.removeChangeListener(this.onFlyoutChange),this.flyoutWorkspace=void 0),!this.workspace)return;const e=(t=this.workspace.getFlyout())==null?void 0:t.getWorkspace();e&&(this.flyoutWorkspace=e,Ve.set(e,this),this.flyoutWorkspace.addChangeListener(this.onFlyoutChange),this.applyFlyoutClass())}resolveAssetUrls(e){for(const[t,n]of this.loadedDefinitions)this.definitions.set(t,e?Cs(n,this.formatElementTypes,e):n)}toolboxBlocks(){var e,t;return this.activeBlockSet?this.blockSetLists.get(this.activeBlockSet):(t=(e=this.mountConfig)==null?void 0:e.toolbox)==null?void 0:t.blocks}resolveToolboxDefinition(e){var r;const t=this.activeBlockSet?this.blockSetLists.get(this.activeBlockSet):void 0;if(e.toolbox||t){const c={...e.toolbox,...t?{blocks:t}:{}},a=this.resolveToolboxKind(e.toolboxLayout),l=a?{...c,kind:a}:c,d=l.kind??((r=l.categories)!=null&&r.length?"categoryToolbox":"flyoutToolbox");return!this.categoriesShown&&d==="flyoutToolbox"?Xt({...l,categories:void 0},this.definitions):Xt(l,this.definitions)}const n=e.blockly;if(n!=null&&n.toolbox)return n.toolbox;const s=this.resolveToolboxKind(e.toolboxLayout);return Xt({...s!==void 0?{kind:s}:{},blocks:[...this.definitions.keys()]},this.definitions)}createBehaviorContext(e,t,n,s,r){return{Blockly:S,workspace:e.workspace,element:n,...s==="toolbox"?{mode:r}:{},context:s,definition:t}}resolveClassNames(e){return e?(Array.isArray(e)?e.join(" "):e).split(/\s+/).map(n=>n.trim()).filter((n,s,r)=>!!n&&r.indexOf(n)===s):[]}replaceUserClasses(e,t,n){for(const s of t)e.classList.remove(s);for(const s of n)e.classList.add(s)}buildBlockColorMap(){var t;const e=new Map;for(const[n,s]of this.definitions){const r=s.color??((t=this.blockCategoryIndex.get(n))==null?void 0:t.color);r!==void 0&&e.set(n,String(r))}return e}resolveToolboxKind(e){if(e)return e==="category"?"categoryToolbox":"flyoutToolbox"}createCategoryIndex(e,t){const n=new Map,s=(e==null?void 0:e.categories)??[],r=new Map;for(const a of s){const l=de(a.name);if(r.set(a.name.toLowerCase(),{token:l,color:a.color}),a.blocks)for(const d of a.blocks)n.has(d)||n.set(d,{token:l,color:a.color})}const c=t?this.definitions:new Map;for(const a of c.values()){if(!a.category||n.has(a.identifier))continue;const l=r.get(a.category.toLowerCase());l&&n.set(a.identifier,l)}return n}deferApplyView(e,t,n){const s=n==="toolbox"?this.flyoutWorkspace:this.workspace;s&&requestAnimationFrame(()=>{const r=s.getBlockById(e);if(!r)return;const c=this.definitions.get(he(r.type));c&&this.applyView(r,c,t,n)})}}function Ws(i,o,e){return Math.min(Math.max(i,o),e)}function zs(i,o){const{target:e,axis:t,invert:n=!1,onResize:s}=o,r=o.min??0,c=o.max??Number.POSITIVE_INFINITY,a=o.step??10,l=()=>{const C=e.getBoundingClientRect();return t==="x"?C.width:C.height},d=C=>i.setAttribute("aria-valuenow",String(Math.round(C)));i.setAttribute("role","separator"),i.setAttribute("aria-orientation",t==="x"?"vertical":"horizontal"),i.setAttribute("aria-valuemin",String(r)),Number.isFinite(c)&&i.setAttribute("aria-valuemax",String(c)),e.id&&!i.hasAttribute("aria-controls")&&i.setAttribute("aria-controls",e.id),d(l());const h=C=>{const T=getComputedStyle(e);if(T.boxSizing==="border-box")return C;const $=(t==="x"?["Left","Right"]:["Top","Bottom"]).reduce((E,M)=>E+(Number.parseFloat(T[`padding${M}`])||0)+(Number.parseFloat(T[`border${M}Width`])||0),0);return Math.max(0,C-$)},u=C=>{const T=Ws(C,r,c);e.style.flexBasis=`${h(T)}px`,d(T),s==null||s(T)},f=C=>{if(C.button!==0)return;C.preventDefault();const T=l(),F=t==="x"?C.clientX:C.clientY,$=document.body.style.userSelect,E=document.body.style.cursor;document.body.style.userSelect="none",document.body.style.cursor=t==="x"?"col-resize":"row-resize",i.setPointerCapture(C.pointerId);const M=A=>{const V=(t==="x"?A.clientX:A.clientY)-F;u(T+(n?-V:V))},O=()=>{i.removeEventListener("pointermove",M),i.removeEventListener("pointerup",O),i.removeEventListener("lostpointercapture",O),document.body.style.userSelect=$,document.body.style.cursor=E};i.addEventListener("pointermove",M),i.addEventListener("pointerup",O),i.addEventListener("lostpointercapture",O)},[p,g]=t==="x"?["ArrowLeft","ArrowRight"]:["ArrowUp","ArrowDown"],v=C=>{const T=C.shiftKey?a*5:a;if(C.key===p||C.key===g){const F=C.key===g?T:-T;u(l()+(n?-F:F))}else if(C.key==="Home")u(r);else if(C.key==="End"&&Number.isFinite(c))u(c);else return;C.preventDefault()};i.hasAttribute("tabindex")||(i.tabIndex=0);const w=()=>d(l());return i.addEventListener("pointerdown",f),i.addEventListener("keydown",v),i.addEventListener("focus",w),{dispose:()=>{i.removeEventListener("pointerdown",f),i.removeEventListener("keydown",v),i.removeEventListener("focus",w)}}}const Us=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"})),Gs=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"}));le.MorphicBlocks=js,le.MorphicToolboxCanvas=mn,le.checkDefinitions=rs,le.makeResizable=zs,le.renderToolbar=vn,le.resolveBlockSets=jt,le.toClassToken=de,le.toCleanId=he,le.toolbarItems=re,le.validateDefinitions=Wt,Object.defineProperty(le,Symbol.toStringTag,{value:"Module"})}));
|