morphic-blocks 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,54 +1,59 @@
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(`
1
+ (function(fe,ye){typeof exports=="object"&&typeof module<"u"?ye(exports,require("blockly/blocks"),require("blockly"),require("blockly/javascript")):typeof define=="function"&&define.amd?define(["exports","blockly/blocks","blockly","blockly/javascript"],ye):(fe=typeof globalThis<"u"?globalThis:fe||self,ye(fe.MorphicBlocks={},fe.Blockly,fe.Blockly,fe.javascript))})(this,(function(fe,ye,Re,je){"use strict";var yr=Object.defineProperty;var br=(fe,ye,Re)=>ye in fe?yr(fe,ye,{enumerable:!0,configurable:!0,writable:!0,value:Re}):fe[ye]=Re;var b=(fe,ye,Re)=>br(fe,typeof ye!="symbol"?ye+"":ye,Re);function jn(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 v=jn(Re);function Xe(i){if(!(!i||typeof i=="function"))return i}function Hn(i){if(i)return typeof i=="function"?i:i.generate}const Ke="morphic-mode-",st="morphic-context-",rt="morphic-shows-",Wn="morphic-view-",oo="morphic-preset-",no="morphic-category-",zn="morphic-block-",Gn=-1,Un=0,Xn=1,Et="morphic:";function xe(i){return Et+i}function me(i){return i.startsWith(Et)?i.slice(Et.length):i}function be(i,o){return o.has(i)?xe(i):i}class io extends v.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 ct(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 St extends io{constructor(e,t="",n=[]){super(function(){return this.nameOptions(t)});b(this,"targets");b(this,"scopes");this.initial=t,this.targets=(Array.isArray(e)?e:[e]).map(ct).filter(s=>s!==null),this.scopes=(Array.isArray(n)?n:[n]).map(xe)}refersTo(e,t){const n=me(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 d;const t=(d=this.getSourceBlock())==null?void 0:d.workspace;if(!t)return[];const n=this.scopeBlock(),s=`${n===void 0?"":(n==null?void 0:n.id)??"-"}|${(this.targets??[]).map(l=>`${l.block}.${l.field}`).join(",")}`,r=e==null?void 0:e.get(s);if(r)return r;const c=new Set;for(const l of this.targets??[])for(const u of t.getBlocksByType(xe(l.block),!1)){if(u.isInsertionMarker()||!this.sees(u,n))continue;const h=u.getFieldValue(l.field);typeof h=="string"&&h!==""&&c.add(h)}const a=[...c].sort((l,u)=>l.localeCompare(u));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()}}function Kn(i,o,e,t){const n=[e??[]].flat().map(xe);let s;if(n.length>0)for(s=t;s&&!n.includes(s.type);)s=s.getSurroundParent();const r=a=>{if(s===void 0)return!0;for(let d=a.getSurroundParent();d;d=d.getSurroundParent())if(d===s)return!0;return!1},c=new Set;for(const a of[o].flat().map(ct))if(a)for(const d of i.getBlocksByType(xe(a.block),!1)){if(d.isInsertionMarker()||!r(d))continue;const l=d.getFieldValue(a.field);typeof l=="string"&&l!==""&&c.add(l)}return[...c]}const Ye=new Set;function so(i){i&&(Ye.add(i),Ye.size>50&&Ye.delete(Ye.values().next().value))}function xt(i,o=i.getAllBlocks(!1)){return o.flatMap(e=>e.inputList.flatMap(t=>t.fieldRow.filter(n=>n instanceof St)))}function Yn(i){i.addChangeListener(o=>{const e=r=>{const c=v.Events.getGroup();v.Events.setGroup(o.group||c);try{r()}finally{v.Events.setGroup(c)}},t=[v.Events.BLOCK_CREATE,v.Events.BLOCK_DELETE,v.Events.BLOCK_CHANGE,v.Events.BLOCK_MOVE];if(o.isUiEvent||!t.includes(o.type))return;const n=xt(i);if(n.length===0)return;const s=()=>{const r=new Map;for(const c of n)c.showMissing(r)};if(!o.recordUndo||Ye.has(o.group)){s();return}if(o.type===v.Events.BLOCK_CREATE){const r=(o.ids??[]).map(c=>i.getBlockById(c)).filter(c=>c!==null);e(()=>xt(i,r).forEach(c=>c.pickDeclared()))}if(o.type===v.Events.BLOCK_MOVE){const r=o,c=r.newParentId!==r.oldParentId?i.getBlockById(r.blockId??""):null;c&&e(()=>{for(const a of xt(i,c.getDescendants(!1)))a.isScoped()&&a.pickDeclared()})}if(o.type===v.Events.BLOCK_CHANGE){const r=o,c=r.blockId?i.getBlockById(r.blockId):null,a=String(r.oldValue??""),d=String(r.newValue??"");r.element==="field"&&r.name&&c&&a!==d&&e(()=>{for(const l of n)!l.refersTo(c,r.name)||l.getValue()!==a||l.declaredNames().includes(a)||l.setValue(d)})}s()})}function ge(i){if(i!==void 0)return typeof i=="string"?i:i.type}function Tt(i,o){const e={...i};for(const[t,n]of Object.entries(o??{})){const s=i[t];if(ge(s)!=="code")continue;const{empty:r,stringQuote:c,emptyStatement:a,types:d,operators:l}=n;if(r===void 0&&c===void 0&&a===void 0&&d===void 0&&l===void 0)continue;const h={...typeof s=="string"?{type:s}:s,empty:r,stringQuote:c,emptyStatement:a,types:d,operators:l};e[t]=h}return e}const He=16;function Lt(i){if(!i||typeof i=="string")return{width:He,height:He};const o=i.size;if(o===void 0)return{width:He,height:He};if(typeof o=="number")return{width:o,height:o};const e=/^(\d+)(?:x(\d+))?$/i.exec(o.trim());if(!e)return{width:He,height:He};const t=Number.parseInt(e[1],10),n=e[2]?Number.parseInt(e[2],10):t;return{width:t,height:n}}function ro(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 co(i,o){for(let e=i.getSurroundParent();e;e=e.getSurroundParent()){const t=e.getField(o);if(t)return t}return null}function Ee(i){return!!(i!=null&&i.repeat)&&(i.kind??"value")==="value"}function Le(i,o){return(i==null?void 0:i.name)??`ARG${o}`}function Be(i,o){return`${i}_${o}`}function We(i){const o=new Map;for(const[e,t]of Object.entries(i.inputSlots??{}))t&&Ee(t)&&o.set(Le(t,e),t);return o}function Me(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 ao(i,o,e){(i.__morphicRepeat??(i.__morphicRepeat=new Map)).set(o,Math.max(0,Math.floor(e)))}function lo(i,o,e){return Array.from({length:Me(i,o,e)},(t,n)=>Be(o,n))}function at(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 uo(i){return/[^\s,;]/.test(i)}function Bt(i,o){for(const[e,t]of Object.entries(i.inputSlots??{})){const n=Le(t,e);if(n===o||t&&Ee(t)&&o.startsWith(`${n}_`)&&/^\d+$/.test(o.slice(n.length+1)))return t}}function It(i,o){const e=We(o);if(e.size===0)return null;const t={};for(const[n,s]of e)t[n]=Me(i,n,s);return{repeat:t}}function qn(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 We(o)){const c=t[s];typeof c!="number"||c===Me(i,s,r)||(ao(i,s,c),n=!0)}return n}const ho=new WeakSet,fo=new WeakSet;function Jn(i){ho.add(i)}function Zn(i){for(const o of[i.previousConnection,i.outputConnection])o&&fo.add(o)}function po(i){const o=i.connectionChecker,e=o.doTypeChecks.bind(o);o.doTypeChecks=(t,n)=>e(t,n)&&Qn(t,n)}function Qn(i,o){const[e,t]=i.isSuperior()?[i,o]:[o,i];if(fo.has(t)&&!e.getCheck())return!1;const n=ei(e);if(!n||!ho.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(d=>s.includes(d))};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 ei(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 $t="MORPHIC_TYPE_",qe=i=>{var o;return!!((o=i.name)!=null&&o.startsWith($t))};function mo(i,o,e){var c,a,d;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?((d=n.outputConnection)==null?void 0:d.getCheck())??[]:s.length===1?s:[];for(const l of r){const u=t[l];if(u!==void 0)return u}return t.default??""}const lt=18,go=":type",dt="%parent.";function vo(i,o){return i.startsWith(dt,o)&&/[A-Z_]/.test(i[o+dt.length]??"")}function Te(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){bo(o,i.slice(e));break}const r=i.slice(e,s+1),c=ri(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(go,s)){o.push({kind:"valueType",index:r}),e=s+go.length;continue}Number.isNaN(r)||o.push({kind:"placeholder",index:r}),e=s;continue}if(vo(i,e)){let s=e+dt.length;for(;s<i.length&&/[A-Z0-9_]/.test(i[s]??"");)s+=1;o.push({kind:"parentField",name:i.slice(e+dt.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||vo(i,n))break;n+=1}bo(o,i.slice(e,n)),e=n}return ci(o)}function ti(i,o,e){const t=i.filter(d=>d.kind!=="image"),n=t.indexOf(i[o]),s=d=>{for(let l=n+d;l>=0&&l<t.length;l+=d){const u=t[l];if(u.kind!=="text")return null;const h=d===-1?u.value.trimEnd():u.value.trimStart();if(h)return d===-1?h.at(-1):h[0];if(u.value.includes(`
2
2
  `))return`
3
3
  `}return""},r=/[\p{L}\p{N}_$]/u,c=s(-1),a=s(1);return{before:c===""||c!==null&&(`([{,
4
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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function ct(i){return i.replace(/"/g,"&quot;").replace(/'/g,"&#39;")}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:
5
+ `.includes(a)||e&&r.test(a))}}const oi="\"'`";function ko(i,o){const e=i==null?void 0:i.at(-1);return e&&oi.includes(e)&&(o==null?void 0:o[0])===e?e:null}function wo(i,o){return i.replaceAll("\\","\\\\").replaceAll(o,`\\${o}`)}function ni(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 yo(i){return i.replace(/\s+/g," ").trim()}function pe(i){return i.trim().replace(/[^A-Za-z0-9_-]+/g,"-")}function Mt(i){return i.map(o=>o.kind==="text"?ii(o.value):o.kind==="image"?`<img src="${ut(o.src)}" alt="${ut(o.alt)}" width="${o.width}" height="${o.height}">`:o.kind==="field"?`<span class="morphic-field-placeholder" data-field-name="${ut(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 ii(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function ut(i){return i.replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const si=/\.(svg|png|jpe?g|gif|webp)(?:[#?].*)?$/i;function Ot(i,o){if(!i)return i;const e=i.trim();return/^<img\b/i.test(e)?i:si.test(e)?`<img src="${ut(e)}" width="${o.width}" height="${o.height}">`:i}function ri(i){if(!/^<img\b/i.test(i))return null;const o=ht(i,"src");if(!o)return null;const e=ht(i,"alt")??"",t=Number.parseInt(ht(i,"width")??`${lt}`,10),n=Number.parseInt(ht(i,"height")??`${lt}`,10);return{kind:"image",src:o,alt:e,width:Number.isNaN(t)?lt:t,height:Number.isNaN(n)?lt:n}}function ht(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 bo(i,o){o&&i.push({kind:"text",value:o})}function ci(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 ai="MORPHIC_OMITTED_FIELDS";function li(i){const o=i.__morphicPlaceholderSlots;return o!=null&&o.size?[...o]:void 0}function di(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 ui(i,o){var t,n;const e=i;(t=e.__morphicPlaceholderSlots)==null||t.delete(o),(n=e.__morphicShadowMemory)==null||n.delete(o)}function Co(i){const{block:o,definition:e,view:t,mode:n,context:s,elementTypes:r,resolveBlocklyType:c}=i,a=Ci(o),d=o.__morphicShadowMemory??(o.__morphicShadowMemory=new Map);for(const[h,f]of Ei(o))d.set(h,f);$i(o),mi(o,e,t,i.onRepeat);const l=gi(o,e);Mi(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),Ti(o,a),Si(o,d),r&&xi(o,e,t,r,c);for(const h of l)h.setVisible(!1);vi(o,e,t,i.codeSettings??r),xo(o,n,s);const u=o;u.__morphicMode=n,u.__morphicContext=s,Dt(o)&&o.render()}function Dt(i){var o;return i.rendered&&!!((o=i.getSvgRoot())!=null&&o.parentNode)}function Eo(i,o,e,t){Ie(i.classList,Ke),Ie(i.classList,st),i.classList.add(t),i.classList.add(`${Ke}${pe(o)}`),i.classList.add(`${st}${e}`)}function So(i){return i.__morphicMode}function hi(i,o){const e=i.getSvgRoot();e&&(Ie(e.classList,no),o&&e.classList.add(`${no}${o}`))}function fi(i,o){const e=i.getSvgRoot();if(!e)return;const t=`${zn}${pe(o)}`;e.classList.contains(t)||e.classList.add(t)}function pi(i){const o=i.getSvgRoot();if(!o)return;const e=getComputedStyle(o).getPropertyValue("--morphic-block-color").trim();e&&(i.setColour(e),Dt(i)&&i.render())}function ft(i,o){Ie(i.classList,Ke),Ie(i.classList,rt),i.classList.add("morphic-view",...o.classNames),o.name&&i.classList.add(`${Wn}${pe(o.name)}`),o.element&&i.classList.add(`${rt}${pe(o.element)}`)}function pt(i,o){Ie(i.classList,oo),o&&i.classList.add(`${oo}${pe(o)}`)}function xo(i,o,e){const t=i.getSvgRoot();if(!t)return;Ie(t.classList,Ke),Ie(t.classList,rt),Ie(t.classList,st);const n=e==="workspace"?rt:Ke;t.classList.add(`${n}${pe(o)}`),t.classList.add(`${st}${e}`)}function mi(i,o,e,t){var d;const n=Te(e.template),s=[],r=new Set,c=new Set,a=l=>Lo(l,s);for(const l of n){if(l.kind==="text"){const f=yo(l.value);f&&s.push(f);continue}if(l.kind==="image"){s.push(new v.FieldImage(l.src,l.width,l.height,l.alt));continue}if(l.kind==="valueType"){s.push({field:new v.FieldLabel(""),name:`${$t}${l.index}`});continue}if(l.kind==="parentField"){s.push(new Je(l.name,"parent"));continue}if(l.kind==="field"){const f=(d=o.fields)==null?void 0:d[l.name];f&&c.has(l.name)?s.push(new Je(l.name)):f&&(c.add(l.name),s.push({field:Bo(f,e.elementName),name:l.name}));continue}if(r.has(l.index)){const f=At(o,e,l.index);if(((f==null?void 0:f.kind)??"value")==="value"&&!(f&&Ee(f))){s.push(new Je(Le(f,l.index),"slot"));continue}const p=i.appendDummyInput(`DUPLICATE_${l.index}_${i.inputList.length}`);a(p),p.appendField(`%${l.index}`);continue}r.add(l.index);const u=At(o,e,l.index);if(u&&Ee(u)){const f=Le(u,l.index),p=Me(i,f,u),m=yo(at(u,e.elementName));for(let E=0;E<p;E++)E>0&&m&&s.push(m),Lo(Nt(i,u,l.index,Be(f,E)),s);t&&(p>0&&s.push(new To("remove",()=>t(f,-1))),s.push(new To("add",()=>t(f,1))));continue}if((u==null?void 0:u.kind)==="statement"&&s.length>0){const f=i.appendDummyInput(`PRE_STMT_${i.inputList.length}`);a(f)}const h=Nt(i,u,l.index);a(h),u!=null&&u.label&&h.appendField(u.label)}if(s.length>0){const l=i.appendDummyInput(`TRAILING_${i.inputList.length}`);a(l)}i.inputList.length===0&&i.appendDummyInput("LABEL").appendField(o.identifier)}function gi(i,o){const e=[];for(const[t,n]of Object.entries(o.inputSlots??{})){if(!n)continue;const s=Le(n,t),r=Ee(n)?Array.from({length:Me(i,s,n)},(c,a)=>Be(s,a)):[s];for(const c of r)i.getInput(c)||e.push(Nt(i,n,Number(t),c))}return e}function vi(i,o,e,t){const n=i.inputList.flatMap(d=>d.fieldRow),s=n.filter(qe),r=n.some(d=>d 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 d of s){const l=d.name.slice($t.length),u=mo(i,At(o,e,Number(l)),c);d.getValue()!==u&&d.setValue(u,!1)}};a(),Vt(i),i.setOnChange(d=>{(d.type===v.Events.BLOCK_MOVE||d.type===v.Events.BLOCK_CREATE)&&a(),r&&Vt(i)})}function At(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 Nt(i,o,e,t=Le(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(ki(o.align)),o!=null&&o.strict&&s.connection&&Jn(s.connection),s}function ki(i){return i==="right"?Xn:i==="centre"?Un:Gn}class To extends v.Field{constructor(e,t){super(e==="add"?"+":"−");b(this,"EDITABLE",!0);b(this,"SERIALIZABLE",!1);b(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 v.FieldLabel{constructor(o,e="field"){super(""),this.fieldName=o,this.source=e}}function wi(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&&!qe(s));return n.length===1&&!t.some(s=>s.connection)?n[0].getText():"…"}function Vt(i){for(const o of i.inputList)for(const e of o.fieldRow){if(!(e instanceof Je))continue;const t=e.source==="parent"?co(i,e.fieldName):i.getField(e.fieldName),n=e.source==="slot"?wi(i,e.fieldName):(t==null?void 0:t.getText())??"";e.getValue()!==n&&e.setValue(n,!1)}}function Lo(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 Bo(i,o){switch(i.type){case"dropdown":{const e=i.options.map(n=>yi(n,o)),t=new io(e);return i.default!==void 0&&t.setValue(i.default),t}case"reference":return new St(i.to,i.default,i.scope);case"number":return new v.FieldNumber(i.default??0,i.min,i.max,i.precision);case"checkbox":return new v.FieldCheckbox(i.default?"TRUE":"FALSE");case"text":default:return new v.FieldTextInput(i.default??"")}}function yi(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?bi(t.color,s,r):t.src,alt:t.alt??i.value,width:s,height:r},i.value]}return[t??i.value,i.value]}function bi(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 Ci(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 Ei(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 xi(i,o,e,t,n=s=>s){var c,a;const s=e.elementName?t[e.elementName]:void 0,r=i.workspace;for(const d of i.inputList){const l=d.connection;if(!l||l.type!==v.INPUT_VALUE)continue;const u=Bt(o,d.name);if(!(u!=null&&u.name)||(u.kind??"value")!=="value")continue;const h=ro(u,s);if(h){if(h.shadow&&!(((c=l.getShadowState)==null?void 0:c.call(l,!0))??((a=l.getShadowDom)==null?void 0:a.call(l))))try{l.setShadowState({type:n(h.shadow),fields:h.fieldValues??{}})}catch{}if(h.placeholder){const f=i,p=f.__morphicPlaceholderSlots??(f.__morphicPlaceholderSlots=new Set),m=l.targetBlock(),E=!m||m.isShadow(),g=p.has(d.name);if(p.add(d.name),E&&!g)try{const w=r.newBlock(n(h.placeholder));if(h.fieldValues)for(const[$,H]of Object.entries(h.fieldValues)){const x=w.getField($);x&&x.setValue(H)}w.outputConnection&&l.connect(w.outputConnection),i.rendered&&(w.initSvg(),w.queueRender())}catch{}}}}}function Ti(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 Li(i,o,e){const t=Object.entries(o.fields??{}).filter(([s])=>!i.getField(s));if(t.length===0)return;const n=i.appendDummyInput(ai);for(const[s,r]of t)n.appendField(Bo(r,e),s);n.setVisible(!1)}function Bi(i){const o=new Map;for(const e of i.inputList)for(const t of e.fieldRow)t.name&&!qe(t)&&o.set(t.name,t.getValue());return o}function Ii(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{}}Vt(i)}function $i(i){for(;i.inputList.length>0;){const o=i.inputList[0];if(!o)break;i.removeInput(o.name,!0)}}function Mi(i,o){o.output!==void 0&&Oi(i,o.output),o.previousStatement!==void 0&&Di(i,o.previousStatement),o.nextStatement!==void 0&&Ai(i,o.nextStatement),o.strict&&Zn(i)}function Oi(i,o){if(o===!1){i.setOutput(!1);return}if(o===!0){i.setOutput(!0);return}i.setOutput(!0,o)}function Di(i,o){if(o===!1){i.setPreviousStatement(!1);return}if(o===!0){i.setPreviousStatement(!0);return}i.setPreviousStatement(!0,o)}function Ai(i,o){if(o===!1){i.setNextStatement(!1);return}if(o===!0){i.setNextStatement(!0);return}i.setNextStatement(!0,o)}function Ie(i,o){const e=Array.from(i).filter(t=>t.startsWith(o));for(const t of e)i.remove(t)}class Ni{ensureModeVisibilityStyles(o,e){const t=Mo(o);if(e){const n=Mo(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}}Ce("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(()=>kr);Ce("toolbar",o.default)}ensureWorkspaceStyles(){Ce("workspace",[".morphic-workspace-root .blocklyMainBackground {"," stroke: var(--morphic-workspace-border-color, transparent);"," stroke-width: var(--morphic-workspace-border-width, 1px);","}"].join(`
7
+ `))}ensureCategoryStyles(o){for(const e of o){if(!e.color)continue;const t=pe(e.name);Ce(`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&&Ri(e,o.href),o.cssText&&Ce(e,o.cssText))}}function Vi(i,o={}){const e=`.morphic-block .morphic-element-${pe(i)}`;Ce(`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(`
8
+ `))}function Io(i,o={}){Ce("drag-text",":where(.morphic-drag-text) { white-space: pre; font: var(--morphic-drag-text-font, 1em ui-monospace, monospace); }");const e=`.morphic-drag-text-${pe(i)}`;Ce(`drag-text:${i}`,[`:where(${e} .morphic-tok-keyword) { color: ${o.keyword??"#cc7832"}; }`,`:where(${e} .morphic-tok-string) { color: ${o.string??"#6a8759"}; }`,`:where(${e} .morphic-tok-number) { color: ${o.number??"#6897bb"}; }`,`:where(${e} .morphic-tok-comment) { color: ${o.comment??"#808080"}; font-style: italic; }`].join(`
9
+ `))}function $o(){Ce("value-rejected",":where(.morphic-value-rejected) { outline: 2px solid #d32f2f; outline-offset: 1px; }")}function Pi(){const i="var(--morphic-drop-indicator, #5a86bc)";Ce("code-drag",[`:where(.morphic-drop-indicator-above) { box-shadow: inset 0 2px 0 0 ${i}; }`,`:where(.morphic-drop-indicator-below) { box-shadow: inset 0 -2px 0 0 ${i}; }`,":where(.cm-line.morphic-drag-source) { height: 0; overflow: hidden; }",":where(.cm-gutterElement.morphic-drag-source) { overflow: hidden; visibility: hidden; }",":where(.morphic-drag-source-value) { opacity: 0.35; }",":where(.morphic-grip-marker) { cursor: grab; }",":where(.morphic-grip-marker:active) { cursor: grabbing; }",":where(.morphic-drag-refused) { cursor: not-allowed; }",":where(.morphic-drag-no-place) { cursor: not-allowed; }"].join(`
10
+ `))}function _i(){Ce("tile-touch",".morphic-block[data-block-type] { touch-action: pan-y; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; }")}function Fi(){const i=":where(.morphic-toolbox-hide-scrollbar",o=e=>`mask-image: ${e}; -webkit-mask-image: ${e};`;Ce("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)")} }`,`:where(.morphic-toolbox-dragging) { ${o("none")} }`,":where(.morphic-drag-refused) { cursor: not-allowed; }",":where(.morphic-drag-no-place) { cursor: not-allowed; }"].join(`
11
+ `))}function Mo(i){const o=['[class^="morphic-element-"] { display: none; }'];for(const e of i){const t=pe(e.name);for(const n of e.elements){const s=pe(n);o.push(`.morphic-mode-${t} > .morphic-element-${s} { display: block; }`)}}return o.join(`
12
+ `)}function Ce(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 Ri(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)}function Oo(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=Do(e),s=(h,f,p)=>{for(const m of n(h))p.add(f+m.from,f+m.to,t[m.kind])},r=h=>{const f=new o.RangeSetBuilder,p=h.state.doc;for(const{from:m,to:E}of h.visibleRanges){let g=m;for(;g<=E;){const w=p.lineAt(g);if(s(w.text,w.from,f),w.to>=E)break;g=w.to+1}}return f.finish()},c=i.ViewPlugin.fromClass(class{constructor(h){b(this,"decorations");this.decorations=r(h)}update(h){(h.docChanged||h.viewportChanged)&&(this.decorations=r(h.view))}},{decorations:h=>h.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 u=[c,a];return Object.keys(l).length>0&&u.push(i.EditorView.theme(l)),u}function Do(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 u of e)if(s.startsWith(u.open,a)){const h=a;for(a+=u.open.length;a<c;){if(s[a]==="\\"&&a+1<c){a+=2;continue}if(s.startsWith(u.close,a)){a+=u.close.length;break}a+=1}r.push({from:h,to:a,kind:"string"}),d=!0;break}if(d)continue;if(n){const u=/^\d+(?:\.\d+)?/.exec(s.slice(a));if(u){r.push({from:a,to:a+u[0].length,kind:"number"}),a+=u[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}}let Ao,ji=0;function Pt(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 No(){return Ao}function Vo(i){Ao=i}const Po={fontSize:"14px",fontFamily:"monospace",lineHeight:1.5},Ze={...Po,background:"#1e1e1e",foreground:"#d4d4d4",gutterBackground:"#1e1e1e",gutterForeground:"#858585",selectionBackground:"#264f78",dropIndicator:"#5a86bc"};function Hi(i){return typeof ResizeObserver>"u"?[]:[i.ViewPlugin.fromClass(class{constructor(o){b(this,"observer");b(this,"watched",new Set);b(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 Oe=(i,o)=>`color-mix(in srgb, ${i} ${o}%, transparent)`;let _o=!1;async function Wi(){if(_o)return;_o=!0;const o=(await Promise.resolve().then(()=>wr)).default,e=document.createElement("style");e.dataset.morphicSource="code-editor",e.textContent=o,document.head.appendChild(e)}const zi=150,Gi=new Set(["create","delete","move","change"]);function Ui(i){return Gi.has(i.type)}async function Xi(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:
7
13
  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:
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(`
14
+ npm install @codemirror/lang-javascript`)}}function _t(i,o){const e={...o.codemirror?Po:Ze,...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,"--morphic-drop-indicator":e.dropIndicator??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:Oe(t,70),backgroundColor:Oe(t,12)},".morphic-delete-marker:hover":{color:t,backgroundColor:Oe(t,22)},".morphic-grip-marker":{color:Oe(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:Oe(t,70),backgroundColor:Oe(t,12)},".morphic-repeat-button:hover":{color:t,backgroundColor:Oe(t,22)}});return o.codemirror?[n,o.codemirror]:n}class Fo{constructor(o,e,t,n={},s=!1){b(this,"editorView");b(this,"container");b(this,"options");b(this,"workspace");b(this,"generateWithMetadata");b(this,"visible",!0);b(this,"syncTimer");b(this,"changeListener");b(this,"lastCode","");b(this,"metadata",new Map);b(this,"placeholders",[]);b(this,"placeholderEditorEl");b(this,"placeholderEditorList");b(this,"placeholderEditorScrollHandler");b(this,"placeholderEditorOutsideHandler");b(this,"onCursorLine");b(this,"onEmptyClick");b(this,"cm");b(this,"themeCompartment");b(this,"syntaxHighlightCompartment");b(this,"highlightEffect");b(this,"themeSelection",Ze.selectionBackground);b(this,"activeHighlight");b(this,"metadataEffect");b(this,"placeholderEffect");b(this,"repeatEffect");b(this,"dropIndicatorEffect");b(this,"dropPreviewEffect");b(this,"dragSourceEffect");b(this,"valueSlotHighlightEffect");b(this,"hoverHighlightEffect");b(this,"groupsEffect");b(this,"editableHoverHighlightEffect");b(this,"emptyClickListener");b(this,"disposed",!1);b(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(){var e;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),(e=this.placeholderEditorList)==null||e.remove(),this.placeholderEditorList=void 0,o.parentNode&&o.parentNode.removeChild(o))}openPlaceholderEditor(o){var H,x,M;if(!this.editorView)return;const e=o.edit,t=e?void 0:o.emptySlot,n=this.options.onPlaceholderApply,s=this.options.onValueApply;if(e?!n:!t||!s)return;const r=!e||e.value===!0&&e.fieldType!=="text";this.closePlaceholderEditor();const c=this.editorView,a=c.coordsAtPos(o.start),d=c.coordsAtPos(o.end);if(!a||!d)return;const l=c.scrollDOM.getBoundingClientRect(),u=c.state.doc.sliceString(o.start,o.end);let h;if(r){const L=document.createElement("input");if(L.type="text",L.spellcheck=!1,L.autocapitalize="off",e?L.value=u:L.placeholder=u,(H=e==null?void 0:e.options)!=null&&H.length){const V=document.createElement("datalist");V.id=`morphic-value-choices-${++ji}`;for(const[A]of e.options)V.appendChild(document.createElement("option")).value=A;L.setAttribute("list",V.id),this.placeholderEditorList=V}h=L}else if(e.fieldType==="dropdown"){const L=document.createElement("select");for(const[V,A]of e.options??[]){const _=document.createElement("option");_.value=A,_.textContent=V,L.appendChild(_)}h=L}else{const L=document.createElement("input");L.type=e.fieldType==="number"?"number":"text";const V=(M=(x=this.workspace.getBlockById(e.blockId))==null?void 0:x.getField(e.fieldName))==null?void 0:M.getValue();L.value=e.fieldType==="text"&&typeof V=="string"?V:u,h=L}const f=getComputedStyle(c.contentDOM),p=(()=>{let L=c.dom;for(;L;){const V=getComputedStyle(L).backgroundColor;if(V&&V!=="rgba(0, 0, 0, 0)"&&V!=="transparent")return V;L=L.parentElement}return"#fff"})();if(Object.assign(h.style,{position:"absolute",left:`${a.left-l.left+c.scrollDOM.scrollLeft}px`,top:`${a.top-l.top+c.scrollDOM.scrollTop}px`,minWidth:`${Math.max(40,d.right-a.left+8)}px`,height:`${a.bottom-a.top}px`,font:f.font,lineHeight:f.lineHeight,padding:"0 2px",margin:"0",border:`1px solid ${f.color}`,borderRadius:"2px",background:p,color:f.color,boxSizing:"border-box",zIndex:"20"}),h instanceof HTMLInputElement){const L=h,V=L.hasAttribute("list")?20:0,A=()=>{const _=Math.max(L.value.length,L.placeholder.length,1)+1;L.style.width=`calc(${_}ch + ${6+V}px)`};A(),L.addEventListener("input",A)}c.scrollDOM.appendChild(h),this.placeholderEditorList&&c.scrollDOM.appendChild(this.placeholderEditorList),this.placeholderEditorEl=h;let m,E=!1,g=!1;const w=()=>{if(g)return;const L=h.value;if(!r){this.closePlaceholderEditor(),n(e,L);return}if(E||L===m)return;if(L.trim()===""||e&&L===u){this.closePlaceholderEditor(),(e==null?void 0:e.fieldType)==="number"&&L.trim()===""&&n(e,"0");return}E=!0;const V=e?n(e,L):s(t,L);if(E=!1,V===!1){m=L,$o(),h.classList.add("morphic-value-rejected"),h.setAttribute("aria-invalid","true");return}this.closePlaceholderEditor()};h.addEventListener("input",()=>{m=void 0,h.classList.remove("morphic-value-rejected"),h.removeAttribute("aria-invalid")});const $=()=>{this.closePlaceholderEditor()};if(h.addEventListener("keydown",L=>{const V=L.key;if(V==="Enter")L.preventDefault(),w();else if(V==="Escape")L.preventDefault(),$();else if(V==="Backspace"&&h.value===""&&(e!=null&&e.value)&&this.options.onValueRemove){L.preventDefault(),g=!0;const A=this.options.onValueRemove(e);g=!1,A!==!1&&this.closePlaceholderEditor()}}),h.addEventListener("mousedown",L=>L.stopPropagation()),h.addEventListener("click",L=>L.stopPropagation()),h instanceof HTMLSelectElement){h.addEventListener("change",()=>w());const L=this.workspace.getBlockById(e.blockId),V=L==null?void 0:L.getField(e.fieldName),A=V==null?void 0:V.getValue();A!=null&&(h.value=String(A)),requestAnimationFrame(()=>{this.placeholderEditorOutsideHandler=_=>{_.target instanceof Node&&!h.contains(_.target)&&$()},document.addEventListener("mousedown",this.placeholderEditorOutsideHandler)})}else h.addEventListener("blur",()=>w());this.placeholderEditorScrollHandler=()=>this.closePlaceholderEditor(),c.scrollDOM.addEventListener("scroll",this.placeholderEditorScrollHandler),requestAnimationFrame(()=>{h.focus({preventScroll:!0}),h instanceof HTMLInputElement&&h.select()})}async mount(){var M,L,V;if(Wi(),Pi(),this.cm=await Xi(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=_t(o,this.options.theme??{});this.themeSelection=((M=this.options.theme)==null?void 0:M.selectionBackground)??Ze.selectionBackground;const s=Oo(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 d=this.options.onRepeat;class l extends o.WidgetType{constructor(_){super(),this.range=_}eq(_){return _.range.blockId===this.range.blockId&&_.range.slotName===this.range.slotName&&_.range.count===this.range.count}toDOM(){const _=document.createElement("span");_.className="morphic-repeat-buttons";const{blockId:J,slotName:k,count:C}=this.range,I=(Z,R,Q)=>{const T=document.createElement("button");T.type="button",T.className=`morphic-repeat-button morphic-repeat-${Z}`,T.textContent=R,T.addEventListener("mousedown",D=>D.preventDefault()),T.addEventListener("click",D=>{D.stopPropagation(),d==null||d(J,k,Q)}),_.appendChild(T)};return C>0&&I("remove","−",-1),I("add","+",1),_}ignoreEvent(){return!0}}const u=e.StateField.define({create(){return o.Decoration.none},update(A,_){for(const J of _.effects)if(J.is(a)){const k=_.state.doc.length;return o.Decoration.set(J.value.filter(C=>C.at<=k).sort((C,I)=>C.at-I.at).map(C=>o.Decoration.widget({widget:new l(C),side:1}).range(C.at)))}return _.changes.empty?A:o.Decoration.none},provide(A){return o.EditorView.decorations.from(A)}}),h=e.StateField.define({create(){return o.Decoration.none},update(A,_){for(const J of _.effects)if(J.is(c)){const k=J.value;if(!k||k.length===0)return o.Decoration.none;const C=_.state.doc.length,I=[...k].filter(D=>D.start<D.end&&D.end<=C).sort((D,F)=>D.start-F.start||D.end-F.end),Z=new e.RangeSetBuilder,R=o.Decoration.mark({class:"morphic-placeholder-default"}),Q=o.Decoration.mark({class:"morphic-placeholder-set"}),T=o.Decoration.mark({class:"morphic-placeholder-set morphic-reference-missing"});for(const D of I)Z.add(D.start,D.end,D.missing?T:D.kind==="default"?R:Q);return Z.finish()}return _.changes.empty?A:o.Decoration.none},provide(A){return o.EditorView.decorations.from(A)}}),f=e.StateEffect.define();this.highlightEffect=f;const p=this,m=e.StateField.define({create(){return o.Decoration.none},update(A,_){for(const J of _.effects)if(J.is(f)){const k=J.value;if(!k)return o.Decoration.none;const C=Array.isArray(k)?k:[k];if(C.length===0)return o.Decoration.none;const I=_.state.doc,Z=o.Decoration.mark({class:"morphic-highlight",attributes:{style:`background: var(--morphic-highlight-color, ${Oe(p.themeSelection,60)})`}}),R=C.map(Q=>{const T=I.line(Math.min(Q.fromLine,I.lines)).from,D=I.line(Math.min(Q.toLine,I.lines)).to;return Z.range(T,D)}).sort((Q,T)=>Q.from-T.from);return o.Decoration.set(R)}return _.changes.empty?A:o.Decoration.none},provide(A){return o.EditorView.decorations.from(A)}}),E=o.EditorView.updateListener.of(A=>{var C;if(A.docChanged||A.transactions.some(I=>I.isUserEvent("select.pointer")))return;const _=A.state.selection.main.head,J=A.startState.selection.main.head;if(_===J)return;if(p.findPlaceholderAtPos(_)){(C=p.onEmptyClick)==null||C.call(p);return}if(!p.onCursorLine)return;const k=A.state.doc.lineAt(_).number;p.onCursorLine(k)});let g="";const w=o.EditorView.updateListener.of(A=>{var k,C;if(!A.selectionSet&&!A.docChanged)return;const _=Pt(A.state),J=_?`${_.first}-${_.last}`:"";J!==g&&(g=J,(C=(k=p.options).onLineSelection)==null||C.call(k))}),$=this.options.showPlaceholderMarkers!==!1,H=[o.lineNumbers(),o.highlightSpecialChars(),e.EditorState.readOnly.of(!0),...t?[t.javascript()]:[],m,...$?[h]:[],...d?[u]:[],E,w,this.themeCompartment.of(n),this.syntaxHighlightCompartment.of(s),...this.buildDeleteExtensions(o,e,r),...this.buildGripExtensions(o,e,r),...this.buildDropIndicatorExtensions(o,e),...this.buildDropPreviewExtensions(o,e),...this.buildDragSourceExtensions(o,e),...this.buildValueSlotHighlightExtensions(o,e),...this.buildHoverHighlightExtensions(o,e),...this.buildGroupExtensions(o,e),...Hi(o),...this.buildEditableHoverHighlightExtensions(o,e),...this.options.extensions??[]],x=this.generateWithMetadata();this.lastCode=x.code,this.metadata=x.metadata,this.placeholders=[...x.placeholders].sort((A,_)=>A.start-_.start),this.editorView=new o.EditorView({parent:this.container,state:e.EditorState.create({doc:this.lastCode,extensions:H})}),this.groupsEffect&&((L=x.groups)!=null&&L.length)&&this.editorView.dispatch({effects:this.groupsEffect.of(x.groups)}),this.metadataEffect&&this.metadata.size>0&&this.editorView.dispatch({effects:this.metadataEffect.of(this.metadata)}),(V=x.repeats)!=null&&V.length&&this.editorView.dispatch({effects:a.of(x.repeats)}),this.placeholderEffect&&x.placeholders.length>0&&this.editorView.dispatch({effects:this.placeholderEffect.of(x.placeholders)}),this.emptyClickListener=A=>{var J,k,C;if(this.isBelowLastLine(A.clientY)){(J=this.onEmptyClick)==null||J.call(this);return}const _=(k=this.editorView)==null?void 0:k.posAtCoords({x:A.clientX,y:A.clientY});if(typeof _=="number"){const I=this.findPlaceholderAtPos(_);if(I){(C=this.onEmptyClick)==null||C.call(this),(I.edit?this.options.onPlaceholderApply:I.emptySlot&&this.options.onValueApply)&&requestAnimationFrame(()=>this.openPlaceholderEditor(I));return}}if(this.onCursorLine){const I=this.getLineAtCoords(A.clientX,A.clientY);I!==null&&this.onCursorLine(I)}},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(u,h){for(const f of h.effects)if(f.is(t)){const p=f.value,m=h.state.doc,E=new Set;for(const{startLine:w}of p.values())w>=1&&w<=m.lines&&E.add(w);const g=Array.from(E).sort((w,$)=>w-$).map(w=>r.range(m.line(w).from));return e.RangeSet.of(g,!0)}return u.map(h.changes)}}),a=o.gutter({class:"morphic-delete-gutter",markers(u){return u.state.field(c)},initialSpacer:()=>r,domEventHandlers:{click(u,h){const f=u.state.doc.lineAt(h.from).number;return n(f),!0}}}),d=u=>{const h=Pt(u.state);return h?n(h.first,h.last):n(u.state.doc.lineAt(u.state.selection.main.head).number),!0},l=o.keymap.of([{key:"Delete",run:d},{key:"Backspace",run:d}]);return[...this.options.deleteButtons!==!1?[c,a]:[],...this.options.deleteKeys!==!1?[e.Prec.highest(l)]:[]]}buildGripExtensions(o,e,t){const n=this.options.canDragBlock;if(!n)return[];const s=this.options.onBlockGrab;class r extends o.GutterMarker{constructor(l){super(),this.blockId=l}eq(l){return l instanceof r&&l.blockId===this.blockId}toDOM(){const l=document.createElement("span");l.textContent="⠿",l.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","user-select: none","touch-action: none","transition: color 0.15s"].join(";");const u=this.blockId;return l.addEventListener("pointerdown",h=>{!h.isPrimary||h.pointerType==="mouse"&&h.button!==0||(h.preventDefault(),s==null||s(u,h,l))}),l}}const c=e.StateField.define({create(){return e.RangeSet.empty},update(d,l){for(const u of l.effects)if(u.is(t)){const h=u.value,f=l.state.doc,p=new Map;for(const[E,{startLine:g,startChar:w,endChar:$}]of h){if(g<1||g>f.lines||!n(E))continue;const H=($??0)-(w??0),x=p.get(g);(!x||H>x.width)&&p.set(g,{id:E,width:H})}const m=Array.from(p.entries()).sort((E,g)=>E[0]-g[0]).map(([E,{id:g}])=>new r(g).range(f.line(E).from));return e.RangeSet.of(m,!0)}return d.map(l.changes)}}),a=o.gutter({class:"morphic-grip-gutter",markers(d){return d.state.field(c)},initialSpacer:()=>new r("")});return[c,a]}buildDropIndicatorExtensions(o,e){const t=e.StateEffect.define();return this.dropIndicatorEffect=t,[e.StateField.define({create(){return o.Decoration.none},update(s,r){for(const c of r.effects)if(c.is(t)){const a=c.value;if(!a)return o.Decoration.none;const d=r.state.doc,l=Math.max(1,Math.min(a.line,d.lines)),u=d.line(l),h=a.position==="above"?"morphic-drop-indicator-above":"morphic-drop-indicator-below",f=o.Decoration.line({class:h});return o.Decoration.set([f.range(u.from)])}return r.changes.empty?s:o.Decoration.none},provide(s){return o.EditorView.decorations.from(s)}})]}buildDropPreviewExtensions(o,e){const t=e.StateEffect.define();this.dropPreviewEffect=t;class n extends o.WidgetType{constructor(l,u){super(),this.text=l,this.kind=u}eq(l){return l.text===this.text&&l.kind===this.kind}toDOM(l){const u=document.createElement(this.kind==="line"?"div":"span");if(u.className=`morphic-drop-preview morphic-drop-preview-${this.kind}`,u.textContent=this.text,this.kind==="line"){u.classList.add("morphic-drop-indicator-above");const h=l.contentDOM.querySelector(".cm-line");h&&(u.style.paddingLeft=getComputedStyle(h).paddingLeft)}return u}ignoreEvent(){return!0}}const s=d=>/^[ \t]*/.exec(d)[0],r=(d,l,u=l)=>d.split(`
15
+ `).map((h,f)=>(f===0?u:l)+h).join(`
16
+ `),c=e.StateField.define({create(){return o.Decoration.none},update(d,l){for(const u of l.effects){if(!u.is(t))continue;const h=u.value;if(!h)return o.Decoration.none;const f=l.state.doc,p=x=>f.line(Math.max(1,Math.min(x,f.lines))),{text:m,place:E}=h;if(E.kind==="value"){const x=Math.max(0,Math.min(E.from,f.length)),M=Math.max(x,Math.min(E.to,f.length)),L=new n(m,"value");return o.Decoration.set([x===M?o.Decoration.widget({widget:L,side:1}).range(x):o.Decoration.replace({widget:L}).range(x,M)])}if(E.kind==="fill"){const x=p(E.line),M=s(x.text),L=new n(r(m,M,""),"fill"),V=x.from+M.length;return o.Decoration.set([o.Decoration.line({class:"morphic-drop-indicator-above"}).range(x.from),V<x.to?o.Decoration.replace({widget:L}).range(V,x.to):o.Decoration.widget({widget:L,side:1}).range(x.to)],!0)}const g=p(E.line),w=E.indentLine?s(p(E.indentLine).text):"",$=E.position==="above",H=new n(r(m,w),"line");return o.Decoration.set([o.Decoration.widget({widget:H,block:!0,side:$?-1:1}).range($?g.from:g.to)])}return l.changes.empty?d:o.Decoration.none},provide(d){return o.EditorView.decorations.from(d)}}),a=o.EditorView.baseTheme({".morphic-drop-preview":{whiteSpace:"pre",opacity:"0.55",backgroundColor:"rgba(90, 134, 188, 0.18)",borderRadius:"2px"},".morphic-drop-preview-line":{boxSizing:"border-box"}});return[c,a]}buildDragSourceExtensions(o,e){const t=e.StateEffect.define();this.dragSourceEffect=t;const n=new class extends o.GutterMarker{constructor(){super(...arguments);b(this,"elementClass","morphic-drag-source")}},s={text:o.Decoration.none,gutter:e.RangeSet.empty};return[e.StateField.define({create(){return s},update(c,a){for(const d of a.effects){if(!d.is(t))continue;const l=d.value;if(!l)return s;const u=a.state.doc;if("range"in l){const E=Math.max(0,Math.min(l.range.from,u.length)),g=Math.max(E,Math.min(l.range.to,u.length));return E===g?s:{text:o.Decoration.set([o.Decoration.mark({class:"morphic-drag-source-value"}).range(E,g)]),gutter:e.RangeSet.empty}}const h=Math.max(1,Math.min(l.lines.from,u.lines)),f=Math.max(h,Math.min(l.lines.to,u.lines)),p=[];for(let E=h;E<=f;E++)p.push(u.line(E).from);const m=o.Decoration.line({class:"morphic-drag-source"});return{text:o.Decoration.set(p.map(E=>m.range(E))),gutter:e.RangeSet.of(p.map(E=>n.range(E)))}}return a.changes.empty?c:s},provide(c){return[o.EditorView.decorations.from(c,a=>a.text),o.gutterLineClass.from(c,a=>a.gutter)]}})]}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 u=a.state.doc.length,h=Math.max(0,Math.min(l.from,u)),f=Math.max(h,Math.min(l.to,u));return h===f?o.Decoration.none:o.Decoration.set([n.range(h,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(h,f){let p=h;for(const m of f.effects)m.is(t)&&(p={groups:m.value,hover:null}),m.is(n)&&(p={...p,hover:m.value});return p}}),c=h=>{const{groups:f,hover:p}=h.field(r),m=new Map;return f.forEach(({startLine:E,endLine:g},w)=>{for(let $=E;$<=Math.min(g,h.doc.lines);$++){const H=[w%2===0?"morphic-group-odd":"morphic-group-even"];$===E&&H.push("morphic-group-start"),$===g&&H.push("morphic-group-end"),g>E&&H.push("morphic-group-line"),w===p&&H.push("morphic-group-hover"),m.set($,H.join(" "))}}),m},a=o.EditorView.decorations.compute([r,"doc"],h=>{const f=[...c(h)].map(([p,m])=>o.Decoration.line({class:m}).range(h.doc.line(p).from));return o.Decoration.set(f)}),d=o.gutterLineClass.compute([r,"doc"],h=>e.RangeSet.of([...c(h)].map(([f,p])=>new s(p).range(h.doc.line(f).from)))),l=(h,f)=>{const p=h.posAtCoords({x:f.clientX,y:f.clientY},!1),m=h.state.doc.lineAt(p).number,E=h.state.field(r).groups.findIndex(g=>m>=g.startLine&&m<=g.endLine);return E===-1?null:E},u=o.EditorView.domEventHandlers({mousemove(h,f){const p=l(f,h);p!==f.state.field(r).hover&&f.dispatch({effects:n.of(p)})},mouseleave(h,f){f.state.field(r).hover!==null&&f.dispatch({effects:n.of(null)})}});return[r,a,d,u]}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 u=a.state.doc.length,h=Math.max(0,Math.min(l.from,u)),f=Math.max(h,Math.min(l.to,u));return h===f?o.Decoration.none:o.Decoration.set([n.range(h,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 d of a.effects)if(d.is(t)){const l=d.value;if(!l)return o.Decoration.none;const u=a.state.doc.length,h=Math.max(0,Math.min(l.from,u)),f=Math.max(h,Math.min(l.to,u));return h===f?o.Decoration.none:o.Decoration.set([n.range(h,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)})}showDropPreview(o,e){!this.editorView||!this.dropPreviewEffect||this.editorView.dispatch({effects:this.dropPreviewEffect.of({text:o,place:e})})}isOnDropPreview(o,e){var r;const t=(r=this.editorView)==null?void 0:r.dom.querySelector(".morphic-drop-preview");if(!t)return!1;const n=t.getBoundingClientRect(),s=this.editorView.dom.getBoundingClientRect();return n.height>0&&e>=n.top&&e<n.bottom&&o>=s.left&&o<s.right}hideDropPreview(){!this.editorView||!this.dropPreviewEffect||this.editorView.dispatch({effects:this.dropPreviewEffect.of(null)})}setDragSource(o){!this.editorView||!this.dragSourceEffect||this.editorView.dispatch({effects:this.dragSourceEffect.of(o)})}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??Ze.selectionBackground,this.activeHighlight&&this.highlightLines(this.activeHighlight);const e=_t(this.cm.view,o);this.editorView.dispatch({effects:this.themeCompartment.reconfigure(e)})}setHighlightRules(o){if(!this.editorView||!this.cm||!this.syntaxHighlightCompartment)return;const e=Oo(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?Pt(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??Ze.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=_t(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()},zi)}attachSyncListener(){this.changeListener||(this.changeListener=o=>{Ui(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 Ki(i,o,e,t){const n={behaviors:e,definitions:o};return jo(je.javascriptGenerator,n,t,!1),je.javascriptGenerator.workspaceToCode(i)}function Yi(i,o,e,t){const n={behaviors:e,definitions:o};jo(je.javascriptGenerator,n,t,!0);const s=je.javascriptGenerator.workspaceToCode(i);return ls(s)}const qi="// __MORPHIC_BLOCK_START:",Ji="// __MORPHIC_BLOCK_END:",Ro="__";function jo(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=Hn(o.behaviors[n]);i.forBlock[xe(n)]=(c,a)=>{const d=Zi(c,a,s),l=r?r(d):rs(n,s);if(ns(c,s))return[ss(l),je.Order.NONE];const u=is(l);return t?`${qi}${c.id}${Ro}
17
+ ${u}${Ji}${c.id}${Ro}
18
+ `:u}}}function Zi(i,o,e){var f;const t={},n={},s={},r=i.workspace.isFlyout?"toolbox":"workspace",c=We(e),a=p=>!c.has(p)&&Ee(Bt(e,p)),l=i.inputList.filter(p=>{var m;return((m=p.connection)==null?void 0:m.type)===v.INPUT_VALUE&&!a(p.name)}).length+c.size>=2,u=p=>l&&!a(p);for(const p of i.inputList){const m=(f=p.connection)==null?void 0:f.targetBlock();if(m)if(m.outputConnection){const E=o.valueToCode(i,p.name,je.Order.NONE)||"undefined";t[p.name]=u(p.name)?Qi(E,m):E}else t[p.name]=o.statementToCode(i,p.name).trimEnd();for(const E of p.fieldRow){if(!E.name||qe(E))continue;const g=String(E.getValue()??"");n[E.name]=g,s[E.name]=JSON.stringify(g)}}const h={};for(const[p,m]of We(e))h[p]=lo(i,p,m).map(E=>t[E]).filter(E=>E!==void 0),t[p]=h[p].join(", ");return{blockId:i.id,blockType:me(i.type),element:So(i)??"default",context:r,inputs:t,fields:n,quoted:s,lists:h}}function Qi(i,o){return!es(o)||os(i)?i:`(${i})`}function es(i){return ts(i)>0}function ts(i){return i.inputList.filter(o=>{var e;return((e=o.connection)==null?void 0:e.type)===v.INPUT_VALUE}).length}function os(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 ns(i,o){return i.outputConnection?!0:o.output===!1?!1:o.output!==void 0}function is(i){const o=i.trim();return o?o.endsWith(";")||o.endsWith("}")||o.endsWith(`
11
19
  `)?`${o}
12
20
  `:`${o};
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(`
21
+ `:""}function ss(i){const o=i.trim();return o?o.endsWith(";")?o.slice(0,-1):o:"undefined"}function rs(i,o){return o.output!==void 0&&o.output!==!1?"undefined":`// No generator behavior defined for "${i}"`}const cs=/^\s*\/\/ __MORPHIC_BLOCK_START:(.+)__$/,as=/^\s*\/\/ __MORPHIC_BLOCK_END:(.+)__$/;function ls(i){const o=i.split(`
22
+ `),e=[],t=new Map,n=new Map;let s=0;for(const r of o){const c=r.match(cs);if(c){n.set(c[1],s+1);continue}const a=r.match(as);if(a){const d=a[1],l=n.get(d);l!==void 0&&(t.set(d,{startLine:l,endLine:s}),n.delete(d));continue}e.push(r),s++}return{code:e.join(`
23
+ `),metadata:t,placeholders:[]}}const De={rank:40,direction:"none"},Ho={"||":10,or:10,"&&":20,and:20,not:{prefix:30},"==":De,"!=":De,"===":De,"!==":De,"<":De,"<=":De,">":De,">=":De,"+":{rank:50,prefix:70},"-":{rank:50,prefix:70},"*":60,"/":60,"%":60,"//":60,"!":{prefix:70},"**":{rank:80,direction:"right"}};function Ft(i,o){if(o===!1)return null;const e=o==null?void 0:o[i];if(e===null)return null;const t=Object.hasOwn(Ho,i)?Ho[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 Ae={rank:-1/0,above:!1},mt={rank:1/0,above:!1};function ze(i,o,e){return e!==void 0&&e===i.sign?!0:i.above?o>i.rank:o>=i.rank}function Wo(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 zo(i,o,e){if(o.output===void 0||o.output===!1)return null;const t=i.filter(h=>h.kind!=="image"),n=h=>{var f;return(h==null?void 0:h.kind)==="placeholder"?((f=o.inputSlots)==null?void 0:f[String(h.index)])??{}:void 0},s=h=>{const f=n(h);return(h==null?void 0:h.kind)==="placeholder"&&f&&(f.kind??"value")==="value"&&!Ee(f)?h.index:null},r=t[0],c=t.at(-1);if(t.length===1){const h=n(r);if((r==null?void 0:r.kind)!=="placeholder"||!h||!Ee(h))return null;const f=at(h,e).trim();return f?{kind:"chain",slot:r.index,sign:f}:null}const a=s(c);if(a===null)return null;const d=s(r),l=t.slice(d===null?0:1,-1);if(l.length===0)return null;const u=[];for(const h of l)if(h.kind==="text")u.push({text:h.value});else if(h.kind==="field")u.push({field:h.name});else return null;return d===null?{kind:"prefix",slot:a,sign:u}:d===a?null:{kind:"infix",left:d,right:a,sign:u}}function Rt(i,o,e){let t;if(i.kind==="chain")t=i.sign;else{const a=i.sign.map(d=>"text"in d?d.text:o(d.field));if(a.some(d=>d===void 0))return null;t=a.join("").trim().replace(/\s+/g," ")}const n=Ft(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 ds=/[\p{L}\p{N}_$]$/u,us=/(?:[\p{L}\p{N}_$]+|[^\s\p{L}\p{N}_$()[\]{},;"'`]+)$/u,hs=/^(?:[\p{L}\p{N}_$]+|[^\s\p{L}\p{N}_$()[\]{},;"'`]+)/u;function Go(i,o,e,t){const n=i.filter(d=>d.kind!=="image"),s=n.indexOf(i[o]),r=ti(i,o,e),c=fs(n,s,t)??(r.before?Ae:mt),a=ps(n,s,t)??(r.after?Ae:mt);return Wo(c,a)}function fs(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=us.exec(n))==null?void 0:f[0],r=s?Ft(s,e):null;if(!s||!r)return null;const c=n.slice(0,n.length-s.length).trimEnd(),a=c===""?o>=2:/[)\]}"'`]$/.test(c),d=ds.test(c),l=r.direction??"left",u=typeof r.rank=="number"&&(a||d)?{rank:r.rank,above:l!=="right",...l==="any"?{sign:s}:{}}:null,h=typeof r.prefix=="number"&&(!a||d)?{rank:r.prefix,above:!1}:null;return u&&h?Wo(u,h):u??h}function ps(i,o,e){var r;const t=i[o+1];if((t==null?void 0:t.kind)!=="text")return null;const n=(r=hs.exec(t.value.replace(/^[ \t]+/,"")))==null?void 0:r[0],s=n?Ft(n,e):null;return typeof(s==null?void 0:s.rank)!="number"?null:{rank:s.rank,above:s.direction==="right"||s.direction==="none"}}function ms(i,o={}){for(const e of i.elements)if(ge(o[e])==="code")return e}function Qe(i,o,e={},t=[]){const n=i.elements,s=t.find(c=>c.name===o);if(s){for(const c of s.elements)if(ge(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(ge(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 Uo(i,o,e={}){const t=i.elements[o];return t!==void 0&&ge(e[o])==="code"?{mode:o,template:t,elementName:o,inputSlots:i.inputSlots}:Qe(i,o,e,[])}function ve(i,o){if(o.length===0)return;if(i.indent===""||!o.includes(`
16
24
  `)){i.output+=o;return}const e=o.split(`
17
25
  `);i.output+=e[0];for(let t=1;t<e.length;t++)i.output+=`
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}
26
+ `+i.indent+e[t]}function Xo(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},d=[],l=()=>c.output.split(`
27
+ `).length;let u=!0;for(const h of i.getTopBlocks(!0)){const f=c.output.length;u||(c.output+=`
28
+ `);const p=l();Ko(h,a,c),c.output.length===f+(u?0:1)?c.output=c.output.slice(0,f):(u=!1,d.push({startLine:p,endLine:l()}))}return{code:c.output,metadata:c.metadata,placeholders:c.placeholders,repeats:c.repeats,groups:d}}function Ko(i,o,e){const t=1+e.indent.length;let n=i,s=!0;for(;n;){const r=e.output.length;s||ve(e,`
29
+ `),jt(n,o,e),e.output.length===r+(s?0:t)?e.output=e.output.slice(0,r):s=!1,n=n.getNextBlock()}}function gs(i){return i.inputList.some(o=>{var e;return((e=o.connection)==null?void 0:e.type)===v.INPUT_VALUE})}function Yo(i,o){if(o.elementOverride){const e=i.elements[o.elementOverride];return e===void 0?null:{template:e,elementName:o.elementOverride}}try{const e=Qe(i,o.mode,o.elementTypes,o.modeDefs);return{template:e.template,elementName:e.elementName}}catch{return null}}function qo(i,o,e,t,n){const s=zo(e,o,t);if(!s)return null;const r=Jo(t?n.elementTypes[t]:void 0);return Rt(s,a=>{const d=i.getField(a);return d?vt(o,t,a,d):void 0},r)}function Jo(i){return typeof i=="object"?i.operators:void 0}function Zo(i,o,e){if(ze(e,-1/0)||!gs(i))return!1;const t=o.definitions.get(me(i.type));if(!t)return!0;const n=Yo(t,o);if(!n)return!0;if(vs(n.template)||ks(n.template))return!1;const s=qo(i,t,Te(n.template),n.elementName,o);return!s||!ze(e,s.rank,s.sign)}function vs(i){const o=Te(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 ks(i){var s;const o=Te(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 jt(i,o,e,t=!1){var H,x,M,L,V;const n=o.definitions.get(me(i.type));if(!n){const A=e.output.length,_=Ge(e.output);if(ws(i,e),e.output.length===A)return;const J=Ge(e.output),k=e.output.endsWith(`
30
+ `)?Math.max(_,J-1):J;let C=e.output.length;for(;C>A&&e.output[C-1]===`
31
+ `;)C--;const I=et(i);e.metadata.set(i.id,{startLine:_,endLine:k,startChar:A,endChar:C,atomic:!!I}),_e(e,A,"set",i.outputConnection?gt(I):I??void 0);return}const s=Yo(n,o);if(!s)return;const{template:r,elementName:c}=s,a=c?o.elementTypes[c]:void 0,d=e.output.length;t&&ve(e,"(");const l=e.output.length,u=Ge(e.output),h={},f=Te(r),p=qo(i,n,f,c,o),m=n.output===void 0||n.output===!1;for(const[A,_]of f.entries()){if(_.kind==="text"){ve(e,_.value);continue}if(_.kind==="field"){const I=i.getField(_.name);if(!I)continue;const Z=e.output.length,R=vt(n,c,_.name,I),Q=Cs(I)?ko(en(f[A-1]),en(f[A+1])):null;ve(e,Q?wo(R,Q):R);const T=!!i.outputConnection&&et(i)!==null,D=Wt(Ht(i,I,_.name),i,o),F=T?gt(D):D;if(F){_e(e,Z,"set",F);const W=e.placeholders[e.placeholders.length-1];W&&W.start===Z&&I instanceof St&&I.isMissing()&&(W.missing=!0)}continue}if(_.kind==="image")continue;if(_.kind==="parentField"){const I=co(i,_.name),Z=I==null?void 0:I.getSourceBlock(),R=Z?o.definitions.get(me(Z.type)):void 0;I&&ve(e,R?vt(R,c,_.name,I):tt(I));continue}if(_.kind==="valueType"){ve(e,mo(i,(H=n.inputSlots)==null?void 0:H[String(_.index)],a));continue}const J=(x=n.inputSlots)==null?void 0:x[String(_.index)],k=J==null?void 0:J.name;if(!k)continue;if((J==null?void 0:J.kind)==="statement"){const I=((L=(M=i.getInput(k))==null?void 0:M.connection)==null?void 0:L.targetBlock())??null,Z=Ge(e.output),R=e.indent,Q=e.output.lastIndexOf(`
32
+ `)+1;if(e.indent=((V=/^[ \t]*/.exec(e.output.slice(Q)))==null?void 0:V[0])??"",I)Ko(I,o,e);else{const F=o.emptyStatements&&typeof a=="object"?a.emptyStatement:void 0;if(F){const W=e.output.length;ve(e,F),_e(e,W,"default")}}e.indent=R;const T=Ge(e.output),D=e.output.endsWith(`
33
+ `)?Math.max(Z,T-1):T;h[k]={startLine:Z,endLine:D};continue}if(J&&Ee(J)){const I=at(J,c),Z=p?p.bound(_.index):uo(I)?mt:Ae,R=lo(i,k,J);R.forEach((Q,T)=>{T>0&&ve(e,I),Qo(i,n,J,Q,o,e,c,a,Z)}),e.repeats.push({blockId:i.id,slotName:k,count:R.length,at:e.output.length});continue}const C=p?p.bound(_.index):Go(f,A,m,Jo(a));Qo(i,n,J,k,o,e,c,a,C)}if(e.output.length===l){e.output=e.output.slice(0,d);return}t&&ve(e,")");const E=Ge(e.output),g=e.output.endsWith(`
34
+ `)?Math.max(u,E-1):E;let w=e.output.length;for(;w>d&&e.output[w-1]===`
35
+ `;)w--;const $={startLine:u,endLine:g,startChar:d,endChar:w};Object.keys(h).length>0&&($.statementSlots=h),et(i)&&($.atomic=!0),e.metadata.set(i.id,$)}function Qo(i,o,e,t,n,s,r,c,a){var p;const d=i.getInput(t),l=((p=d==null?void 0:d.connection)==null?void 0:p.targetBlock())??null,u=l!=null&&l.isShadow()?null:l;let h=!1;if(!u&&l&&n.definitions.has(me(l.type))){const m=s.output.length,E=s.placeholders.length;jt(l,n,s,Zo(l,n,a));for(const g of l.getDescendants(!1))s.metadata.delete(g.id);if(s.output.length>m){const g=s.placeholders.splice(E);for(const w of g)s.placeholders.push({...w,kind:"default"});g.length===0&&_e(s,m,"default");return}}if(!u){const m=l!=null&&l.isShadow()?l.inputList.flatMap(x=>x.fieldRow).filter(x=>!!x.name):[],E=!(l!=null&&l.isShadow())&&d?d.fieldRow.filter(x=>{var M;return!!x.name&&!((M=o.fields)!=null&&M[x.name])&&!qe(x)}):[],g=m.length>0||E.length>0,w=g?bs(e,c):void 0;w&&ve(s,w);const $=s.output.length;if(m.length>0){const x=l?n.definitions.get(me(l.type)):void 0;for(const M of m){const L=x&&M.name?vt(x,r,M.name,M):tt(M);ve(s,w?wo(L,w):L)}}else if(E.length>0)for(const x of E){const M=s.output.length;ve(s,tt(x));const L=Ht(i,x,x.name);L&&(_e(s,M,"set",L),h=!0)}let H;if(g||(ve(s,ys(e==null?void 0:e.check)),H={parentBlockId:i.id,inputName:t}),!h){const x=l!=null&&l.isShadow()?gt(Wt(et(l),l,n)):void 0;_e(s,$,"default",x,H)}w&&ve(s,w);return}const f=s.output.length;jt(u,n,s,Zo(u,n,a)),_e(s,f,"set",gt(Wt(et(u),u,n)))}function ws(i,o){for(const e of i.inputList)for(const t of e.fieldRow)t.name&&ve(o,tt(t))}function _e(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 ys(i){const o=Array.isArray(i)?i[0]:i;return o?`[${{Number:"NUMBER",String:"TEXT",Boolean:"BOOL"}[o]??o.toUpperCase()}]`:"[VALUE]"}function bs(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 gt(i){return i?{...i,value:!0}:void 0}function Ht(i,o,e){let t,n;if(o instanceof v.FieldNumber)t="number";else if(o instanceof v.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 v.FieldTextInput)t="text";else return null;return{blockId:i.id,fieldName:e,fieldType:t,options:n}}function Wt(i,o,e){var c;if(!(i!=null&&i.options))return i;const t=e.definitions.get(me(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=Qe(t,e.mode,e.elementTypes,e.modeDefs).elementName}catch{return i}const r=a=>{var d;for(const l of n.options)if(typeof l=="object"&&!Array.isArray(l)&&l.value===a)return(s&&((d=l.display)==null?void 0:d[s]))??a;return a};return{...i,options:i.options.map(([,a])=>[r(a),a])}}function et(i){let o=null,e=null,t=0;for(const n of i.inputList){if(n.connection&&n.connection.type===v.INPUT_VALUE)return null;for(const s of n.fieldRow)s.name&&(t++,o=s.name,e=s)}return t!==1||!o||!e?null:Ht(i,e,o)}function vt(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 tt(t)}function Cs(i){return i instanceof v.FieldTextInput&&!(i instanceof v.FieldNumber)}function en(i){return(i==null?void 0:i.kind)==="text"?i.value:void 0}function tt(i){if(!i)return"";if(i instanceof v.FieldDropdown)return String(i.getValue());const o=i.getText;return typeof o=="function"?o.call(i):String(i.getValue())}function Ge(i){let o=1;for(let e=0;e<i.length;e++)i[e]===`
36
+ `&&o++;return o}class Es{constructor(o,e,t={}){b(this,"workspace");b(this,"editors");b(this,"blockToCode");b(this,"codeToBlock");b(this,"blockListener");b(this,"cursorCallbacks",new Map);b(this,"emptyClickCallbacks",new Map);b(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&&v.common.getSelected()!==s&&(this.guard=!0,v.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,v.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 tn={statement:{above:!0,below:!0},start:{above:!1,below:!0},end:{above:!0,below:!1},standalone:{above:!1,below:!1}},on=Object.keys(tn);function nn(i){return i.map(o=>{const e=o.shape?tn[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 kt="default";function sn(i,o){const e=Object.keys(o).filter(t=>ge(o[t])==="code");return i.map(t=>{var a;const n=(a=t.elements)==null?void 0:a[kt];if(n===void 0||e.length===0)return t;const{[kt]:s,...r}=t.elements,c={...r};for(const d of e)c[d]===void 0&&(c[d]=n);return{...t,elements:c}})}function rn(i){const o=new Map,e=Array.isArray(i)?i:[i];for(const t of e)Ss(t,o),o.set(t.identifier,t);return o}function Ss(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 xs=4/3,Ts={normal:"400",bold:"700"},cn=i=>Ts[i]??i;function Ls(i){const o=parseFloat(i);if(!Number.isFinite(o)||o<=0)return;const e=i.trim().endsWith("pt")?o:o/xs;return Math.round(e*100)/100}function an(i){const o=i.getRenderer().getConstants();return{family:o.FIELD_TEXT_FONTFAMILY,size:o.FIELD_TEXT_FONTSIZE,weight:cn(o.FIELD_TEXT_FONTWEIGHT)}}function ln(i,o,e){const t=document.createElement("div");t.setAttribute("aria-hidden","true"),t.style.cssText="position:absolute;visibility:hidden;width:0;height:0;overflow:hidden;";let n=t;for(const d of o){const l=document.createElement("div");l.className=d.join(" "),n.appendChild(l),n=l}const s=document.createElementNS("http://www.w3.org/2000/svg","svg"),r=document.createElementNS("http://www.w3.org/2000/svg","text");r.setAttribute("class","blocklyText"),s.appendChild(r),n.appendChild(s),i.appendChild(t);const c=getComputedStyle(r),a={family:c.fontFamily||e.family,size:Ls(c.fontSize)??e.size,weight:c.fontWeight?cn(c.fontWeight):e.weight};return t.remove(),a}const Bs=(i,o)=>i.family===o.family&&i.size===o.size&&i.weight===o.weight,zt=new Map;function Is(i,o){const e=`${i.name}
29
37
  ${o.family}
30
38
  ${o.size}
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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return i.split(`
39
+ ${o.weight}`;let t=zt.get(e);if(!t){const n=`${i.name}-morphic-font-${zt.size+1}`;t=v.Theme.defineTheme(n,{name:n,base:i,fontStyle:{family:o.family,size:o.size,weight:o.weight},...i.startHats!==void 0&&{startHats:i.startHats}}),zt.set(e,t)}return t}function dn(i,o,e,t){const n=Bs(t,e)?o:Is(o,t);return i.getTheme()===n?!1:(i.setTheme(n),!0)}function Gt(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 Ut(i={},o){const e=new Map,t=[],n=[],s=(c,a)=>{for(const d of a)o(d)||t.push(`Block set "${c}": "${d}" is no block in the definitions.`)},r=(c,a)=>{const d=e.get(c);if(d)return d;const l=i[c];if(Array.isArray(l))return s(c,l),e.set(c,l),l;let u=[];l.extends===c||a.includes(l.extends)?t.push(`Block set "${c}": extends "${l.extends}", which extends it again (${[...a,c,l.extends].join(" → ")}).`):i[l.extends]?u=r(l.extends,[...a,c]):t.push(`Block set "${c}": extends "${l.extends}", which is no block set.`);const h=l.add??[],f=l.remove??[];s(c,[...h,...f]);for(const m of f)u.includes(m)||n.push(`Block set "${c}": removes "${m}", which "${l.extends}" does not have.`);const p=[...u.filter(m=>!f.includes(m)),...h.filter(m=>!u.includes(m))];return e.set(c,p),p};for(const c of Object.keys(i))r(c,[]);return{lists:e,errors:t,warnings:n}}function Xt(i){var H,x,M,L,V,A,_,J;const{definitions:o,elementTypes:e,behaviors:t,modes:n,presets:s,code:r,categories:c,views:a,blockSets:d}=i,l=[],u=[],h=new Set(Object.keys(e)),f=new Set(Object.keys(e).filter(k=>ge(e[k])==="code")),p=new Set((c??[]).map(k=>k.name));h.has(kt)&&l.push(`elementTypes declares "${kt}", which is reserved for a block's fallback template. Rename the element.`);const m=k=>o.has(k)||v.Blocks[k]!==void 0;for(const k of o.values()){const C=k.identifier;if(k.shape!==void 0)if(!on.includes(k.shape))l.push(`Block "${C}": unknown shape "${k.shape}". Use one of: ${on.join(", ")}.`);else{const O=Y=>Y!==void 0&&Y!==!1,N=[];O(k.output)&&N.push("it also has an output, which makes it a value block"),(k.shape==="start"||k.shape==="standalone")&&O(k.previousStatement)&&N.push("it also connects above (previousStatement)"),(k.shape==="end"||k.shape==="standalone")&&O(k.nextStatement)&&N.push("it also connects below (nextStatement)"),k.shape==="statement"&&(k.previousStatement===!1||k.nextStatement===!1)&&N.push("a connection flag is set to false");for(const Y of N)u.push(`Block "${C}": shape "${k.shape}" contradicts its flags: ${Y}. The flags win.`)}const I=O=>typeof O=="string"||Array.isArray(O)&&O.length>0;k.strict&&!I(k.previousStatement)&&!I(k.output)&&l.push(`Block "${C}" is strict but has no check. Name its kind in "previousStatement" (or "output"), e.g. "previousStatement": "ClassField".`);const Z=Xe(t[C]),R=!!(Z!=null&&Z.onViewApplied);for(const O of Object.keys(k.elements))h.has(O)||u.push(`Block "${C}": element "${O}" is not declared in elementTypes — it renders with no known type.`);const Q=new Map,T=new Set,D=new Set,F=new Map;for(const[O,N]of Object.entries(k.elements)){if(!f.has(O))continue;const Y=new Set,re=new Set;for(const de of Te(N))de.kind==="placeholder"?(Y.add(de.index),T.add(de.index)):de.kind==="field"?D.add(de.name):de.kind==="valueType"&&(re.add(de.index),T.add(de.index));Q.set(O,Y),F.set(O,re)}for(const[O,N]of F)for(const Y of N){const re=(H=k.inputSlots)==null?void 0:H[String(Y)];re!=null&&re.repeat?l.push(`Block "${C}": element "${O}" uses %${Y}:type, but %${Y} repeats. A slot with several values has no one type.`):(!((x=Q.get(O))!=null&&x.has(Y))&&!re||(re==null?void 0:re.kind)==="statement")&&l.push(`Block "${C}": element "${O}" uses %${Y}:type, but %${Y} is not a value slot in it — the type comes from the value in that slot.`)}const W=[...Q.entries()];if(W.length>1){const[O,N]=W[0];for(const[Y,re]of W.slice(1)){const de=[...N,...re].filter(we=>{var Se;return N.has(we)!==re.has(we)&&!((Se=k.inputSlots)!=null&&Se[String(we)])});de.length>0&&l.push(`Block "${C}": code elements "${O}" and "${Y}" use different placeholders (${fn(N)} vs ${fn(re)}). Declare inputSlots["${de[0]}"], so the block keeps the slot where a template leaves it out, or write %${de[0]} in every code element.`)}}const se=new Set(Object.keys(k.inputSlots??{}).map(O=>Number(O)).filter(O=>Number.isInteger(O)));for(const O of T)(M=k.inputSlots)!=null&&M[String(O)]||u.push(`Block "${C}": placeholder %${O} has no inputSlots["${O}"] entry — the input is auto-named ARG${O} and can't be read by name in behaviors.`);for(const O of se)T.has(O)||u.push(`Block "${C}": inputSlots["${O}"] has no matching %${O} placeholder in any code element — the config is ignored.`);const ie=new Set(Object.keys(k.fields??{}));for(const O of D)!((L=k.fields)!=null&&L[O])&&!R&&l.push(`Block "${C}": field token %${O} has no fields["${O}"] entry and the block has no onViewApplied behavior to create it — the field will never appear.`);for(const O of ie)D.has(O)||u.push(`Block "${C}": fields["${O}"] has no matching %${O} token in any code element — it is never shown.`);for(const[O,N]of Object.entries(k.fields??{}))if((N==null?void 0:N.type)==="dropdown")for(const Y of N.options){if(typeof Y!="object"||Array.isArray(Y))continue;const re=Y.label;if(re&&typeof re=="object"&&typeof re.src!="string"&&typeof re.color!="string"&&l.push(`Block "${C}": fields["${O}"] option "${Y.value}" has an image label without "src" or "color".`),!!Y.display)for(const de of Object.keys(Y.display))f.has(de)||u.push(`Block "${C}": fields["${O}"] option "${Y.value}" has display for "${de}", which is not a code element — that entry never applies.`)}k.category!==void 0&&p.size>0&&!p.has(k.category)&&u.push(`Block "${C}": category "${k.category}" is not declared in categories — the block loses its colour and grouping.`);for(const[O,N]of Object.entries(k.inputSlots??{})){(N==null?void 0:N.kind)!==void 0&&!un.includes(N.kind)&&l.push(`Block "${C}": inputSlots["${O}"] has unknown kind "${N.kind}". Use one of: ${un.join(", ")}.`),N!=null&&N.repeat&&(N.kind??"value")!=="value"&&l.push(`Block "${C}": inputSlots["${O}"] repeats, but it is a statement slot. Only value slots repeat; a statement slot already holds any number of blocks.`),N!=null&&N.repeat&&!N.name&&l.push(`Block "${C}": inputSlots["${O}"] repeats but has no name. Give it a "name"; its entries are named after it.`);const Y=Object.values(k.inputSlots??{}).find(re=>{var de;return(re==null?void 0:re.repeat)&&re.name&&((de=N==null?void 0:N.name)==null?void 0:de.startsWith(`${re.name}_`))&&/^\d+$/.test(N.name.slice(re.name.length+1))});Y&&l.push(`Block "${C}": inputSlots["${O}"] is named "${N.name}", which is the name of an entry of the repeating slot "${Y.name}". Give it another name.`),N!=null&&N.strict&&(N.check===void 0||N.check.length===0)&&l.push(`Block "${C}": inputSlots["${O}"] is strict but has no check. A strict slot takes only blocks whose check matches its own, so nothing would fit.`)}for(const[O,N]of Object.entries(k.fields??{}))hn.includes(N==null?void 0:N.type)||l.push(`Block "${C}": fields["${O}"] has unknown type "${N==null?void 0:N.type}". Use one of: ${hn.join(", ")}.`);for(const[O,N]of Object.entries(k.fields??{})){if((N==null?void 0:N.type)!=="reference")continue;for(const re of N.scope===void 0?[]:[N.scope].flat())o.has(re)||l.push(`Block "${C}": fields["${O}"] has the scope "${re}", but there is no block "${re}".`);const Y=Array.isArray(N.to)?N.to:[N.to];Y.length===0&&l.push(`Block "${C}": fields["${O}"] is a reference without "to". Name the field it lists, e.g. "class_define.NAME".`);for(const re of Y){const de=ct(re),we=`Block "${C}": fields["${O}"] refers to "${re}"`;if(!de){l.push(`${we}, which is not a block and a field. Write it as "block.FIELD", e.g. "class_define.NAME".`);continue}const Se=o.get(de.block);Se?!((V=Se.fields)!=null&&V[de.field])&&!((A=Xe(t[de.block]))!=null&&A.onViewApplied)&&l.push(`${we}, but block "${de.block}" has no field "${de.field}".`):l.push(`${we}, but there is no block "${de.block}".`)}}for(const[O,N]of Object.entries(k.inputSlots??{}))$((_=N==null?void 0:N.default)==null?void 0:_.shadow,`Block "${C}": inputSlots["${O}"].default.shadow`),$((J=N==null?void 0:N.default)==null?void 0:J.placeholder,`Block "${C}": inputSlots["${O}"].default.placeholder`)}for(const[k,C]of Object.entries(e)){const I=ge(C);Kt.includes(I)||l.push(`elementTypes."${k}": unknown type "${I}". Use one of: ${Kt.join(", ")}.`)}for(const[k,C]of Object.entries(r??{}))for(const[I,Z]of Object.entries(C.empty??{}))$(Z.shadow,`code.${k}.empty.${I}.shadow`),$(Z.placeholder,`code.${k}.empty.${I}.placeholder`);for(const[k,C]of Object.entries(e)){if(typeof C=="string")continue;const I=C.type;C.size!==void 0&&I!=="image"&&u.push(`elementTypes."${k}": "size" applies only to image elements — ignored for a ${I} element.`);for(const Z of["empty","stringQuote"])Z in C&&l.push(`elementTypes."${k}": "${Z}" moved into the "code" section: "code": { "${k}": { "${Z}": … } }.`)}for(const k of n??[])for(const C of k.elements)h.has(C)||u.push(`Mode "${k.name}": element "${C}" is not declared in elementTypes — it renders nothing.`);for(const k of n??[])for(const[C,I]of Object.entries(k.render??{}))I==="block"||I==="text"?l.push(`Mode "${k.name}": render "${I}" is now "${I}-based" (render.${C}).`):I!=="block-based"&&I!=="text-based"?l.push(`Mode "${k.name}": render.${C} must be "block-based" or "text-based".`):f.has(C)||u.push(`Mode "${k.name}": render.${C} names no code element — it changes nothing.`);for(const k of s??[]){const C=k.toolbox;if(typeof C=="object"&&C!==null){const{mode:I,render:Z}=C,R=Object.keys(Z??{})[0]??"python";l.push(`Preset "${k.name}": the toolbox entry is a mode name since 0.4.0, and its "render" moved into the mode: "toolbox": "${I??"<mode>"}", and on that mode "render": { "${R}": "text-based" }.`)}}const E=Ut(d,k=>o.has(k));l.push(...E.errors),u.push(...E.warnings);for(const k of s??[])k.blockSet!==void 0&&!(d!=null&&d[k.blockSet])&&l.push(`Preset "${k.name}": blockSet "${k.blockSet}" is no block set.`);for(const k of Object.keys(r??{}))f.has(k)||u.push(`code["${k}"] is not a code element — its settings will never apply.`);const g=new Map,w=(k,C)=>{const I=g.get(k)??new Set;I.add(C),g.set(k,I)};for(const k of h)w(k,"element");for(const k of n??[])w(k.name,"mode");for(const k of s??[])w(k.name,"preset");for(const k of a??[])w(k,"view");for(const k of c??[])w(k.name,"category");for(const k of Object.keys(d??{}))w(k,"block set");for(const[k,C]of g){C.size>1&&u.push(`Name "${k}" is used as ${[...C].sort().join(" and ")} — reusing a name across element / mode / preset / view / category / block set is allowed but confusing; consider distinct names.`);const I=[...C].filter(R=>R!=="category"&&R!=="block set");I.length>0&&/[^A-Za-z0-9_-]/.test(k)&&u.push(`Name "${k}" (${I.sort().join(", ")}) has characters a CSS class cannot hold; its classes use "${pe(k)}".`);const Z=k.toLowerCase();$s.includes(Z)&&!(C.size===1&&C.has("category"))&&u.push(`Name "${k}" (${[...C].sort().join(", ")}) is a Morphic Blocks word — name it after what it is in your app (e.g. "python", "icon-tiles", "editor-pane").`)}return{errors:l,warnings:u};function $(k,C){!k||m(k)||l.push(`${C}: "${k}" is neither a defined block nor a registered Blockly block type.`)}}const Kt=["text","code","image","custom"],$s=["workspace","codespace","preview","toolbox","mode","preset","view","element","block","blocks","blockset","block-set","tile","tiles","category",...Kt],un=["value","statement"],hn=["dropdown","reference","text","number","checkbox"];function fn(i){const o=[...i].sort((e,t)=>e-t);return o.length?o.map(e=>`%${e}`).join(" "):"(none)"}const Ms={workspace:"workspace",codespace:"codespace"};function Yt(i){return Object.fromEntries(Object.entries(i??Ms).map(([o,e])=>[o,typeof e=="string"?{kind:e}:e]))}function pn(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 mn(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(", ")}).`),ge(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 gn(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 Os(i,o={},e={}){const t=i,n=t.elementTypes??{};let s;try{s=rn(nn(sn(t.blocks,n)))}catch(u){return{errors:[u.message],warnings:[]}}const r=Yt(t.views),c=Xt({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=mn({presets:t.presets,modes:t.modes,views:r,elementTypes:Tt(n,t.code)}),d=[...c.errors,...gn(t.presets,"highlighting"in t),...pn(r),...a.errors],l=[...c.warnings,...a.warnings];if(e.modeStyles){const u=new Set(e.modeStyles),h=(t.modes??[]).map(f=>f.name).filter(f=>!u.has(f));h.length>0&&l.push(`Modes without explicit CSS definition: ${h.join(", ")}.`)}return{errors:d,warnings:l}}function vn(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=>vn(c,o,!0)).join(r)}${s}`}return String(i)}const kn="Put brackets around the parts of this line: these operators have no order.",Ne=/[\p{L}\p{M}\p{N}_$]/u,wt=/[\p{L}_$][\p{L}\p{M}\p{N}_$]*/uy,wn=/-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][-+]?\d+)?/y;function Ds(i,o,e,t={}){return yn(i,o,e,t)}function As(i,o,e,t={},n){return yn(i,o,e,t,n)}function yn(i,o,e,t,n){var we,Se,it;const s=i.replace(/\r\n?/g,`
40
+ `),r=n?s.trim():s,c=new Set(((we=t.highlighting)==null?void 0:we.keywords)??[]),a=(Se=t.highlighting)==null?void 0:Se.comment,d=Object.values(t.types??{}).sort((y,S)=>S.length-y.length),l=new Set;for(const y of e.values())for(const S of Object.values(y.fields??{}))if(S.type==="reference")for(const B of[S.to].flat())l.add(B);const u=[];for(const y of e.values()){const S=de(y,o);S&&u.push(S)}u.sort((y,S)=>S.weight-y.weight);const h=u.filter(y=>!y.isValue),f=u.filter(y=>y.isValue&&!y.continues),p=u.filter(y=>y.isValue&&y.continues),m=new Set;let E=new Set;const g=[],w=new Map,$=new Map;let H={pos:-1},x={pos:-1,message:""};const M=(y,S)=>{y>H.pos&&(H={pos:y,message:S}),S&&y>=x.pos&&(x={pos:y,message:S})},L=y=>r.slice(0,Math.max(0,y)).split(`
41
+ `).length,V=y=>{for(;r[y]===" "||r[y]===" ";)y++;return y},A=y=>{const S=r.indexOf(`
42
+ `,y);return S===-1?r.length:S},_=y=>{for(;;){const S=A(y);if(S>=r.length||r.slice(y,S).trim()!=="")return r.slice(y,S).trim()===""?r.length:y;y=S+1}},J=y=>{const S=V(y);return S>=r.length||r[S]===`
43
+ `||!!a&&S>y&&r.startsWith(a,S)},k=(y,S)=>{var B;return!y||y.kind==="text"||y.kind==="body"?!1:y.kind!=="field"||((B=y.field)==null?void 0:B.type)!=="dropdown"?!0:Cn(y.field.options,o).some(({shown:ee})=>Ne.test(S==="start"?ee[0]??"":ee.at(-1)??""))};function C(y,S,B,ee,z,U){const K=y.split(`
44
+ `);for(let j=0;j<K.length;j++){const oe=K[j];if(j>0){if(!B){if(S=V(S),S<r.length&&r[S]!==`
45
+ `)return null;S=_(Math.min(S+1,r.length)),B=!0}if(oe.trim()==="")continue;const ue=/^[ \t]*/.exec(oe)[0];if(!r.startsWith(ee+ue,S))return null;S+=ee.length+ue.length,B=!1;const te=I(oe.slice(ue.length),S,void 0,j===K.length-1?U:void 0);if(te===null)return null;S=te;continue}if(oe==="")continue;if(B)return null;const X=I(oe,S,z,K.length===1?U:void 0);if(X===null)return null;S=X}return{pos:S,lineStart:B}}function I(y,S,B,ee){((B==null?void 0:B.kind)==="value"||(B==null?void 0:B.kind)==="repeat")&&/^[^\s\p{L}\p{N}_$]/u.test(y)&&(S=V(S));for(let z=0;z<y.length;){if(y[z]===" "||y[z]===" "){let U=z;for(;y[U]===" "||y[U]===" ";)U++;const K=z===0?k(B,"end"):Ne.test(y[z-1]),j=U===y.length?k(ee,"start"):Ne.test(y[U]),oe=S;if(S=V(S),K&&j&&S===oe)return null;z=U;continue}if(r[S]!==y[z])return null;S++,z++}return S}function Z(y,S,B){var K;const z=y.tokens[S].field;if((z==null?void 0:z.type)==="dropdown")return Cn(z.options,o).filter(({shown:j})=>r.startsWith(j,B)&&!(Ne.test(j.at(-1)??"")&&Ne.test(r[B+j.length]??""))).map(({value:j,shown:oe})=>({value:j,shown:oe,end:B+oe.length}));if((z==null?void 0:z.type)==="number"){wn.lastIndex=B;const j=wn.exec(r);return j?[{value:j[0],shown:j[0],end:B+j[0].length}]:[]}if((z==null?void 0:z.type)==="text"){const j=y.tokens[S+1],oe=y.tokens[S-1],X=(j==null?void 0:j.kind)==="text"?j.value[0]:void 0,ue=(oe==null?void 0:oe.kind)==="text"?oe.value.at(-1):void 0,te=ko((oe==null?void 0:oe.kind)==="text"?oe.value:void 0,(j==null?void 0:j.kind)==="text"?j.value:void 0);if(te){const P=ni(r,B,te);return P?[{value:P.value,shown:r.slice(B,P.end),end:P.end}]:[]}if(X&&!Ne.test(X)&&X!==" "&&X!==`
46
+ `&&ue&&!Ne.test(ue)&&ue!==" "&&X!=="("){const P=r.indexOf(X,B);return P===-1||P>A(B)?[]:[{value:r.slice(B,P),shown:r.slice(B,P),end:P}]}const q=y.tokens[0];if(!j&&!y.isValue&&a&&(q==null?void 0:q.kind)==="text"&&q.value.trim()===a){const P=r.slice(B,A(B)).trimEnd();return[{value:P,shown:P,end:B+P.length}]}}wt.lastIndex=B;const U=(K=wt.exec(r))==null?void 0:K[0];return U&&!c.has(U)?[{value:U,shown:U,end:B+U.length}]:[]}const R=(y,S)=>y.form?Rt(y.form,B=>S.shown[B],t.operators):null,Q=(y,S,B)=>{var z;const ee=(z=R(y,B))==null?void 0:z.bound(S.number);return ee?{rank:ee.rank,above:ee.above}:S.bound};function*T(y,S,B,ee,z,U,K){var te,q;const{tokens:j,def:oe}=y;if(S===j.length){yield{pos:B,lineStart:ee,taken:K};return}const X=j[S],ue=()=>yt(U,[...Object.values(K.inputs).flatMap(P=>P.declares),...se(oe,K.fields)]);if(X.kind==="text"){const P=C(X.value,B,ee,z,j[S-1],j[S+1]);P?yield*T(y,S+1,P.pos,P.lineStart,z,U,K):M(B,"");return}if(!ee){if(X.kind==="skip"&&!X.types){const P=((te=[...g].reverse().find(G=>X.field in G))==null?void 0:te[X.field])??"";r.startsWith(P,B)&&!(P&&Ne.test(r[B+P.length]??""))&&(yield*T(y,S+1,B+P.length,!1,z,U,K));return}if(X.kind==="skip"){const P=d.find(ce=>r.startsWith(ce,B));wt.lastIndex=B;const G=P?B+P.length:B+(((q=wt.exec(r))==null?void 0:q[0].length)??0),ne=P&&X.slotName?{...K,types:{...K.types,[X.slotName]:P}}:K;G>B&&(yield*T(y,S+1,G,!1,z,U,ne));return}if(X.kind==="field"){for(const P of Z(y,S,B)){if(X.name in K.fields&&K.shown[X.name]!==P.shown)continue;const G={...K,fields:{...K.fields,[X.name]:P.value},shown:{...K.shown,[X.name]:P.shown}};yield*T(y,S+1,P.end,!1,z,U,G)}return}if(X.kind==="value"){const P=V(B),G=K.written[X.name];if(G!==void 0){r.startsWith(G,P)&&(yield*T(y,S+1,P+G.length,!1,z,U,K));return}const ne=En(X.slot.check);if(r.startsWith(ne,P)){const ce={...K,written:{...K.written,[X.name]:ne}};yield*T(y,S+1,P+ne.length,!1,z,U,ce)}for(const ce of O(P,Q(y,X,K),ue(),X.slot)){const ae={...K,inputs:{...K.inputs,[X.name]:ce},written:{...K.written,[X.name]:r.slice(P,ce.end)}};yield*T(y,S+1,ce.end,!1,z,U,ae)}return}if(X.kind==="repeat"){yield*D(y,S,X,B,0,z,U,K);return}}}function*D(y,S,B,ee,z,U,K,j){let oe=ee;if(z>0&&(oe=I(B.separator,ee,void 0,void 0)),oe!==null){oe=V(oe);const ue=Be(B.name,z),te=En(B.slot.check),q=G=>({...j,inputs:G?{...j.inputs,[ue]:G}:j.inputs,repeat:{...j.repeat,[B.name]:z+1}}),P=yt(K,[...Object.values(j.inputs).flatMap(G=>G.declares),...se(y.def,j.fields)]);for(const G of O(oe,Q(y,B,j),P,B.slot))yield*D(y,S,B,G.end,z+1,U,K,q(G));r.startsWith(te,oe)&&(yield*D(y,S,B,oe+te.length,z+1,U,K,q(void 0)))}const X={...j,repeat:{...j.repeat,[B.name]:z}};yield*T(y,S+1,ee,!1,U,K,X)}function*F(y,S,B,ee,z,U,K){const j=y.tokens.findIndex((ue,te)=>te>=S&&ue.kind==="body");if(j===-1){yield*T(y,S,B,ee,z,U,K);return}const oe={...y,tokens:y.tokens.slice(0,j)},X=y.tokens[j];for(const ue of T(oe,S,B,ee,z,U,K)){if(!ue.lineStart)continue;const te=yt(U,[...Object.values(ue.taken.inputs).flatMap(G=>G.declares),...se(y.def,ue.taken.fields)]);g.push(ue.taken.shown);const q=N(ue.pos,z+X.indent,X.slot,te);g.pop();const P=q.stacks[0]?{...ue.taken.inputs,[X.name]:q.stacks[0]}:ue.taken.inputs;yield*F(y,j+1,q.pos,!0,z,U,{...ue.taken,inputs:P})}}function W(y,S,B){var ue,te,q;const{def:ee}=y,z=Object.values(S.inputs);let U=z.reduce((P,G)=>P+G.penalty,0);const K={};for(const[P,G]of Object.entries(S.fields)){const ne=(ue=ee.fields)==null?void 0:ue[P];if(K[P]=(ne==null?void 0:ne.type)==="number"?Number(G):G,(ne==null?void 0:ne.type)==="reference"){const ae=[ne.to].flat().map(le=>`${le}=${G}`);ae.some(le=>B.has(le))?U-=ne.scope?.1:0:U+=ae.some(le=>E.has(le))?.5:1}const ce=`${ee.identifier}.${P}=${G}`;l.has(`${ee.identifier}.${P}`)&&(B.has(ce)&&U++,m.add(ce))}const j=[];for(const[P,G]of Object.entries(ee.inputSlots??{})){if((G.kind??"value")!=="value")continue;const ne=Le(G,P);if(!Ee(G))j.push(ne);else for(let ce=0;ce<(S.repeat[ne]??0);ce++)j.push(Be(ne,ce))}const oe={type:xe(ee.identifier)};Object.keys(K).length>0&&(oe.fields=K);const X=Object.entries(S.inputs).map(([P,G])=>[P,{block:G.state}]);for(const[P,G]of Object.entries(S.types)){const ne=(te=Object.entries(t.types??{}).find(([le,ke])=>ke===G&&le!=="default"))==null?void 0:te[0],ce=ne?(q=t.empty)==null?void 0:q[ne]:void 0,ae=(ce==null?void 0:ce.shadow)??(ce==null?void 0:ce.placeholder);ae&&e.has(ae)&&!(P in S.inputs)&&X.push([P,{block:{type:xe(ae),fields:ce.fieldValues??{}}}])}return X.length>0&&(oe.inputs=Object.fromEntries(X)),oe.extraState={...Object.keys(S.repeat).length>0?{repeat:S.repeat}:{},defaults:j},{state:oe,def:ee,penalty:U,declares:se(ee,S.fields),count:1+z.reduce((P,G)=>P+G.count,0)}}function se(y,S){return Object.entries(S).filter(([B])=>l.has(`${y.identifier}.${B}`)).map(([B,ee])=>`${y.identifier}.${B}=${ee}`)}const ie={fields:{},shown:{},inputs:{},repeat:{},types:{},written:{}};function O(y,S,B,ee){var ue;const z=V(y),U=`${z}|${S.rank}${S.above?">":""}${S.sign??""}|${bn(ee)}|${g.length}:${JSON.stringify(g.at(-1)??{})}|${B.key}`,K=w.get(U);if(K)return K;const j=[];if(r[z]==="(")for(const te of O(z+1,Ae,B)){const q=V(te.end);r[q]===")"&&j.push({...te,end:q+1,rank:1/0,open:void 0})}for(const te of f)for(const q of T(te,0,z,!1,"",B,ie)){if(q.lineStart)continue;const P=((ue=R(te,q.taken))==null?void 0:ue.rank)??1/0;ze(S,P)&&j.push({...W(te,q.taken,B),end:q.pos,rank:P})}for(let te=0;te<j.length;te++){const q=j[te];for(const P of p){if(P.tight?q.rank!==1/0:S.rank===1/0)continue;const G=P.tokens[0];if(!Sn(G.slot,q.def))continue;const ne=G.kind==="repeat"?{...ie,inputs:{[Be(G.name,0)]:q},repeat:{[G.name]:1}}:{...ie,inputs:{[G.name]:q}},ce=G.kind==="repeat"?D(P,0,G,q.end,1,"",B,ne):T(P,1,q.end,!1,"",B,ne);for(const ae of ce){if(ae.lineStart||ae.pos===q.end)continue;let le;const ke=P.tight?null:R(P,ae.taken);if(P.tight)le={...W(P,ae.taken,B),end:ae.pos,rank:1/0};else if(ke){if(!ze(S,ke.rank,ke.sign))continue;if(!ze(ke.bound(G.number),q.rank)){(q.rank===ke.rank||q.rank===-1/0)&&M(q.end,kn);continue}le={...W(P,ae.taken,B),end:ae.pos,rank:ke.rank}}else{if(!ze(S,-1/0))continue;const $e=`${P.def.identifier}|${JSON.stringify(ae.taken.fields)}`;if(q.rank!==1/0&&q.open!==$e){M(q.end,kn);continue}le={...W(P,ae.taken,B),end:ae.pos,rank:-1/0,open:$e}}j.some($e=>$e.end===le.end&&$e.def===le.def&&$e.penalty<=le.penalty)||j.push(le)}}}const oe=new Map;for(const te of j){if(ee&&!Sn(ee,te.def))continue;const q=oe.get(te.end);(!q||te.penalty<q.penalty)&&oe.set(te.end,te)}const X=[...oe.values()].sort((te,q)=>q.end-te.end);return w.set(U,X),X}function N(y,S,B,ee){const z=`${y}|${S}|${bn(B)}|${g.length}:${JSON.stringify(g.at(-1)??{})}|${ee.key}`,U=$.get(z);if(U)return U;const K=[];let j;const oe=[];for(;y=_(y),!(y>=r.length);){const ue=/^[ \t]*/.exec(r.slice(y,A(y)))[0];if(ue!==S){(ue.length>S.length||!S.startsWith(ue))&&M(y,"The line is indented differently from the lines around it.");break}const te=y+S.length;if(B&&K.length===0&&t.emptyStatement&&r.slice(te,A(te)).trim()===t.emptyStatement){const ae=_(Math.min(A(te)+1,r.length));if(ae>=r.length||/^[ \t]*/.exec(r.slice(ae,A(ae)))[0]!==S){y=ae;break}}const q=yt(ee,oe),P=j==null?void 0:j.read.def;let G;const ne=(ae,le,ke)=>{if(!ke&&!J(le))return;const to=P?Vs(P,ae.def,B):B?Ns(B,ae.def):!1;if(B&&!to)return;const $e=ae.penalty+(!B&&ae.def.strict?100:0);(!G||$e<G.score)&&(G={read:ae,pos:ke?le:Math.min(A(le)+1,r.length),joins:to,score:$e})};for(const ae of h)for(const le of F(ae,0,te,!1,S,q,ie))ne(W(ae,le.taken,q),le.pos,le.lineStart);if(!G&&!B)for(const ae of O(te,Ae,q))ne(ae,ae.end,!1);if(!G){M(te,`No block writes "${r.slice(te,A(te)).trim()}".`);break}const ce=G;if(ce.joins&&j){j.state.next={block:ce.read.state};const ae=K[K.length-1];ae.penalty+=ce.read.penalty,ae.count+=ce.read.count,ae.declares.push(...ce.read.declares)}else K.push({...ce.read,declares:[...ce.read.declares]});j={read:ce.read,state:ce.read.state},oe.push(...ce.read.declares),y=ce.pos}const X={stacks:K,pos:y};return $.set(z,X),X}if(n){const y={has:ee=>n.names.has(ee),key:""},S=ee=>ee.find(z=>z.end===r.length),B=S(O(0,Ae,y,n.slot));return B?{ok:!0,block:B.state,blocks:B.count}:n.slot&&S(O(0,Ae,y))?{ok:!1,reason:"wrong-slot",message:`This slot does not take ${r}.`}:{ok:!1,reason:"no-block",message:x.message||`No block writes "${r}".`}}const Y={has:()=>!1,key:""};N(0,"",null,Y),E=new Set(m),w.clear(),$.clear(),H={pos:-1,message:""},x={pos:-1,message:""};const re=N(0,"",null,Y);if(_(re.pos)<r.length){const y=L(Math.max(H.pos,re.pos)),S=((it=r.split(`
47
+ `)[y-1])==null?void 0:it.trim())??"";return{ok:!1,line:y,message:L(x.pos)===y?x.message:`No block writes "${S}".`}}return{ok:!0,stacks:re.stacks.map(y=>y.state),blocks:re.stacks.reduce((y,S)=>y+S.count,0)};function de(y,S){var te,q,P;const B=y.elements[S];if(B===void 0)return null;const ee=Te(B).filter(G=>G.kind!=="image"),z=y.output!==void 0&&y.output!==!1,U=[];for(let G=0;G<ee.length;G++){const ne=ee[G];if(ne.kind==="text")U.push({kind:"text",value:ne.value});else if(ne.kind==="field")U.push({kind:"field",name:ne.name,field:(te=y.fields)==null?void 0:te[ne.name]});else if(ne.kind==="valueType")U.push({kind:"skip",types:!0,slotName:Le((q=y.inputSlots)==null?void 0:q[String(ne.index)],ne.index)});else if(ne.kind==="parentField")U.push({kind:"skip",types:!1,field:ne.name});else if(ne.kind==="placeholder"){const ce=((P=y.inputSlots)==null?void 0:P[String(ne.index)])??{},ae=Le(ce,ne.index);if(ce.kind==="statement"){const le=U[U.length-1],ke=(le==null?void 0:le.kind)==="text"?/\n([ \t]*)$/.exec(le.value):null;if(!ke||(le==null?void 0:le.kind)!=="text")return null;le.value=le.value.slice(0,le.value.length-ke[1].length),U.push({kind:"body",name:ae,slot:ce,indent:ke[1]});continue}if(Ee(ce)){const le=at(ce,S);U.push({kind:"repeat",name:ae,number:ne.index,slot:ce,separator:le,bound:uo(le)?mt:Ae})}else U.push({kind:"value",name:ae,number:ne.index,slot:ce,bound:Go(ee,G,!z,t.operators)})}}if(U.length===0)return null;const K=U[0],j=U[1],oe=z&&(K.kind==="value"||K.kind==="repeat"),X=zo(ee,y,S),ue=(X==null?void 0:X.kind)==="infix"&&X.sign.every(G=>"text"in G)&&Rt(X,()=>{},t.operators);return{def:y,tokens:U,isValue:z,continues:oe,form:X,tight:oe&&!ue&&(j==null?void 0:j.kind)==="text"&&j.value[0]!==" "&&j.value[0]!==" ",weight:U.reduce((G,ne)=>G+(ne.kind==="text"?ne.value.replace(/\s/g,"").length:0),0)}}}function yt(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 bn(i){return i?`${JSON.stringify(i.check??null)}${i.strict?"!":""}`:"-"}function Cn(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 En(i){const o=Array.isArray(i)?i[0]:i;return o?`[${{Number:"NUMBER",String:"TEXT",Boolean:"BOOL"}[o]??o.toUpperCase()}]`:"[VALUE]"}const Ve=i=>typeof i=="string"?[i]:Array.isArray(i)?i:null,qt=(i,o)=>!i||!o||i.some(e=>o.includes(e)),bt=(i,o)=>!!i&&!!o&&i.some(e=>o.includes(e));function Sn(i,o){if(o.output===void 0||o.output===!1)return!1;const e=Ve(i.check),t=Ve(o.output);return i.strict||o.strict?bt(e,t):qt(e,t)}function Ns(i,o){if(!o.previousStatement)return!1;const e=Ve(i.check),t=Ve(o.previousStatement);return i.strict||o.strict?bt(e,t):qt(e,t)}function Vs(i,o,e){if(!i.nextStatement||!o.previousStatement||e!=null&&e.strict&&!bt(Ve(e.check),Ve(o.previousStatement)))return!1;const t=Ve(i.nextStatement),n=Ve(o.previousStatement);return o.strict?bt(t,n):qt(t,n)}function xn(i){const o=i.workspace.connectionChecker,e=new Set(i.getDescendants(!1));let t=v.config.snapRadius,n=null;for(const s of i.getConnections_(!1))for(const r of s.neighbours(t)){if(e.has(r.getSourceBlock())||!o.canConnect(s,r,!0,t))continue;const c=s.distanceFrom(r);c>t||n&&c===t||(n={local:s,neighbour:r},t=c)}return n}function Ps(i,o){var n;const e=i.getConnections_(!0)[o.local],t=(n=i.workspace.getBlockById(o.blockId))==null?void 0:n.getConnections_(!0)[o.index];return!e||!t||!i.workspace.connectionChecker.canConnect(e,t,!1)?null:{local:e,neighbour:t}}function _s(i,o,e,t){const n=v.Events.getGroup();n||v.Events.setGroup(!0);try{v.renderManagement.triggerQueuedRenders(i);const s=i.newBlock(o);s.moveTo(e),s.bumpNeighbours=()=>{};try{s.initSvg(),s.render()}finally{Reflect.deleteProperty(s,"bumpNeighbours")}const r=(t&&Ps(s,t))??xn(s);return r?r.local.connect(r.neighbour):s.bumpNeighbours(),s}finally{n||v.Events.setGroup(!1)}}function Tn(i,o,e){const t=i.getInjectionDiv().getBoundingClientRect();return new v.utils.Coordinate((o-t.left-i.scrollX)/i.scale,(e-t.top-i.scrollY)/i.scale)}function Jt(i){const o=document.createElement("div");o.className="morphic-drag-layer",Object.assign(o.style,{position:"fixed",inset:"0 auto auto 0",width:"0",height:"0",margin:"0",border:"0",padding:"0",overflow:"visible",background:"transparent",color:"inherit",pointerEvents:"none"}),i.appendChild(o);try{return o.setAttribute("popover","manual"),o.showPopover(),{layer:o,onTop:!0}}catch{return o.removeAttribute("popover"),{layer:o,onTop:!1}}}const Ln=new WeakSet;function Bn(i){var t;const o=v.serialization.workspaces.save(i),e=(t=o.blocks)==null?void 0:t.blocks;return e&&(o.blocks.blocks=e.filter(({id:n})=>{const s=n===void 0?null:i.getBlockById(n);return!s||!Ln.has(s)})),o}class Fs{constructor(o,e=()=>o){b(this,"block");b(this,"type","");b(this,"previewer");b(this,"shown");b(this,"replaced");b(this,"raised");this.view=o,this.program=e}show(o,e,t=!0){var n,s;v.Events.disable();try{if(((n=this.block)!=null&&n.isDisposed()||this.type!==o)&&this.hide(),this.block)this.block.moveDuringDrag(e);else{const r=this.make(o,e);r.bumpNeighbours=()=>{},r.render(),r.setConnectionTracking(!1);for(const c of r.getDescendants(!1))Ln.add(c),c.setConnectionTracking=()=>{};r.getSvgRoot().classList.add("morphic-drag-preview"),r.getSvgRoot().style.pointerEvents="none",(s=this.view.getLayerManager())==null||s.moveToDragLayer(r),this.raise(r),this.block=r,this.type=o,this.previewer=new v.InsertionMarkerPreviewer(r)}this.alignLayer(),this.showPlace(t?this.placeFor(this.block):void 0)}finally{v.Events.enable()}}place(){const o=this.shown;if(!o||!this.block||this.block.isDisposed())return;const e=o.neighbour.getSourceBlock();if(e.isDisposed())return;const t=this.block.getConnections_(!0).indexOf(o.local),n=e.getConnections_(!0).indexOf(o.neighbour);return t<0||n<0?void 0:{blockId:e.id,index:n,local:t}}hide(){var t,n;const{block:o,previewer:e}=this;this.block=void 0,this.previewer=void 0,this.shown=void 0,this.replaced=void 0,v.Events.disable();try{try{e==null||e.dispose()}catch{}o&&!o.isDisposed()&&o.dispose(!1)}finally{v.Events.enable()}(t=this.raised)==null||t.watch.disconnect(),(n=this.raised)==null||n.holder.remove(),this.raised=void 0}make(o,e){const t=this.program();if(t&&t!==this.view){const s=t.newBlock(o);let r;try{r=v.serialization.blocks.save(s,{addCoordinates:!1,saveIds:!1})}finally{s.dispose(!1)}if(r){this.view.isDragging=()=>!0;try{const c=v.serialization.blocks.append(r,this.view);return c.moveTo(e),c}finally{Reflect.deleteProperty(this.view,"isDragging")}}}const n=this.view.newBlock(o);return n.moveTo(e),n.initSvg(),n}raise(o){const{layer:e,onTop:t}=Jt(this.view.getInjectionDiv());if(!t){e.remove();return}const n=v.utils.dom.createSvgElement(v.utils.Svg.SVG,{},e);Object.assign(n.style,{position:"absolute",left:"0",top:"0",width:"1px",height:"1px",overflow:"visible"});const s=v.utils.dom.createSvgElement(v.utils.Svg.G,{},n),r=o.getSvgRoot(),c=()=>{const d=r.cloneNode(!0);d.style.visibility="",d.removeAttribute("data-id"),d.querySelectorAll("[data-id]").forEach(l=>l.removeAttribute("data-id")),s.replaceChildren(d)};r.style.visibility="hidden",c();const a=new MutationObserver(d=>{var l;d.some(u=>u.target!==r||u.attributeName!=="transform")?c():(l=s.firstElementChild)==null||l.setAttribute("transform",r.getAttribute("transform")??"")});a.observe(r,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),this.raised={holder:e,canvas:s,watch:a}}alignLayer(){const o=this.raised;if(!o)return;const e=this.view.getInjectionDiv().getBoundingClientRect();o.holder.style.left=`${e.left}px`,o.holder.style.top=`${e.top}px`,o.canvas.setAttribute("transform",`translate(${this.view.scrollX},${this.view.scrollY}) scale(${this.view.scale})`)}placeFor(o){const e=xn(o)??void 0,t=this.shown;if(!e||!t||t.neighbour.getSourceBlock().isDisposed())return e;if(t.local===e.local&&t.neighbour===e.neighbour)return t;const n=t.local.distanceFrom(t.neighbour);return n>v.config.snapRadius?e:e.local.distanceFrom(e.neighbour)>n-v.config.currentConnectionPreference?t:e}showPlace(o){const e=this.previewer;if(!e)return;const t=(o==null?void 0:o.neighbour.targetBlock())??void 0,n=this.shown;if(this.shown=o,!o){this.replaced=void 0,e.hidePreview();return}const{local:s,neighbour:r}=o,c=s.type===v.ConnectionType.OUTPUT_VALUE||s.type===v.ConnectionType.PREVIOUS_STATEMENT,a=t&&(s.type===v.ConnectionType.OUTPUT_VALUE?t.outputConnection:t.previousConnection);if(c&&t&&!t.isInsertionMarker()&&!(a&&v.Connection.getConnectionForOrphanedConnection(s.getSourceBlock(),a))){if(this.replaced===t&&(n==null?void 0:n.neighbour)===r)return;this.replaced=t,e.previewReplacement(s,r,t)}else this.replaced=void 0,e.previewConnection(s,r)}}function In(i,o,e,t){const n=new Fs(o,e),s=()=>!o.options.readOnly;return{element:i,preview:()=>"block",takes:s,over:(r,c,a)=>n.show(t(a),Tn(o,r,c),s()),leave:()=>n.hide(),drop:(r,c,a)=>{const d=n.place();n.hide();const l=e();l&&s()&&_s(l,t(r),Tn(o,c,a),d)}}}let Rs=0;const js=8,Hs=4,$n=12,Ws=350,Ct=12,ot="morphic-drag-refused",Mn="morphic-drag-no-place";function Zt(i,o){const e=Do(o),t=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");return i.split(`
44
48
  `).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(`
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(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&amp;/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:
49
+ `)}class On{constructor(o){b(this,"container");b(this,"workspaceContainer");b(this,"workspace");b(this,"definitions");b(this,"blockColors");b(this,"behaviors");b(this,"elementTypes");b(this,"options");b(this,"modes");b(this,"currentMode");b(this,"code");b(this,"previewWorkspace");b(this,"onPreviewWorkspace");b(this,"previewContainer");b(this,"previewBase");b(this,"dropTargets");b(this,"workspaceTarget");b(this,"endDrag");b(this,"collapsedCategories",new Set);b(this,"categoryParts",[]);b(this,"activeCategory");b(this,"grouped");b(this,"onScroll",()=>this.showScrollHints());b(this,"resizeObserver",typeof ResizeObserver<"u"?new ResizeObserver(()=>this.showScrollHints()):void 0);b(this,"onChoose");b(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??(()=>[]),this.workspaceTarget=In(this.workspaceContainer,this.workspace,()=>this.workspace,s=>be(s,this.definitions));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.container.classList.add("morphic-toolbox"),this.options.scrollbar!==!0&&(Fi(),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,t,n,s;(o=this.endDrag)==null||o.call(this),(t=(e=this.workspaceTarget).leave)==null||t.call(e),this.container.removeEventListener("scroll",this.onScroll),(n=this.resizeObserver)==null||n.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),(s=this.previewContainer)!=null&&s.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 d=document.createElement("span");d.className="morphic-toolbar-label",d.textContent=e,a.appendChild(d),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 d=this.definitions.get(a);d&&this.container.appendChild(this.createTile(d))}return}const c=new Set;for(const a of n){const d=this.resolveCategoryBlockIds(a,t);if(d.length===0)continue;const l=document.createElement("div");l.setAttribute("data-category",pe(a.name)),a.color&&l.style.setProperty("--morphic-category-color",a.color);const u=document.createElement("div");u.className="morphic-category-tiles",u.id=`morphic-category-${++Rs}`;let h,f;if(r)f=document.createElement("button"),f.className="morphic-category-tab",f.type="button",f.setAttribute("role","tab"),f.setAttribute("aria-controls",u.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),u.setAttribute("role","tabpanel");else if(this.options.categoryHeadings!==!1){const p=this.options.collapsible!==!1;h=document.createElement(p?"button":"div"),h.className="morphic-category-heading",h.textContent=a.name,p?(h.type="button",h.setAttribute("aria-controls",u.id),h.addEventListener("click",()=>this.toggleCategory(a.name))):(h.setAttribute("role","heading"),h.setAttribute("aria-level","3")),l.appendChild(h)}this.categoryParts.push({name:a.name,group:l,heading:h,tiles:u,tab:f});for(const p of d){const m=this.definitions.get(p);m&&(u.appendChild(this.createTile(m)),c.add(p))}l.appendChild(u),this.container.appendChild(l)}for(const a of t)if(!c.has(a)){const d=this.definitions.get(a);d&&this.container.appendChild(this.createTile(d))}}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 l,u,h;const e=pe(this.currentMode),t=pe(o.identifier),n=this.blockColors.get(o.identifier),s=document.createElement("div");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(f=>f.name===this.currentMode),c=(r==null?void 0:r.elements)??[],a=Object.entries(o.elements),d=[...c.map(f=>a.find(([p])=>p===f)).filter(f=>f!==void 0),...a.filter(([f])=>!c.includes(f))];for(const[f,p]of d){const m=document.createElement("div");m.className=`morphic-element-${pe(f)}`;const E=this.elementTypes[f],g=ge(E),w=g==="code",$=g==="image",H=(l=this.modes.find(L=>L.name===this.currentMode))==null?void 0:l.render,x=w&&(H==null?void 0:H[f])!=="text-based",M=$?Ot(p,Lt(E)):p;if(g==="custom"){m.dataset.morphicCustom="";const L=(u=this.options.custom)==null?void 0:u[f],V=(L==null?void 0:L(p,{block:o.identifier,element:f,mode:this.currentMode}))??p;typeof V=="string"?m.textContent=V:m.appendChild(V)}else if(x){this.syncPreviewFont(f);const L=this.createBlockPreviewSvg(o,this.currentMode,f);L?m.appendChild(L):m.innerHTML=Mt(Te(M))}else if(w){m.dataset.morphicTextCode="";const L=this.createCodeText(o,this.currentMode,f),V=this.options.highlight===!1||(h=this.code[f])==null?void 0:h.highlighting;L!==null&&V?(Vi(f,V.colors),m.innerHTML=Zt(L,V)):L!==null?m.textContent=L:m.innerHTML=Mt(Te(M))}else m.innerHTML=Mt(Te(M));s.appendChild(m)}return s.addEventListener("dragstart",f=>f.preventDefault()),this.options.touch!==!1&&_i(),this.attachDrag(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",f=>{var p;f.key!=="Enter"&&f.key!==" "||f.target===s&&(f.preventDefault(),(p=this.onChoose)==null||p.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 d=document.createElement("div");d.innerHTML=s;const l=(c=d.textContent)==null?void 0:c.trim();if(l)return l}const r=[];for(const d of e){const l=o.elements[d];if(l===void 0)continue;const u=ge(this.elementTypes[d]);if(u==="custom")continue;if(u==="code"){const p=this.createCodeText(o,this.currentMode,d);p!=null&&p.trim()&&r.push(p.trim());continue}const h=document.createElement("div");h.innerHTML=u==="image"?Ot(l,Lt(this.elementTypes[d])):l;const f=u==="image"?Array.from(h.querySelectorAll("img"),p=>p.alt).join(" ").trim():(a=h.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[...this.dropTargets(),this.workspaceTarget].find(n=>n.element.contains(t))}heldTargetAt(o,e,t){const n=this.dropTargetAt(o,e);if(n||!t)return{target:n,x:o,y:e};const s=document.elementFromPoint(o,e);if(s&&this.container.contains(s))return{target:n,x:o,y:e};const r=t.element.getBoundingClientRect();return r.width<=0||r.height<=0?{target:n,x:o,y:e}:o<r.left-Ct||o>=r.right+Ct||e<r.top-Ct||e>=r.bottom+Ct?{target:n,x:o,y:e}:{target:t,x:Math.min(Math.max(o,r.left),r.right-1),y:Math.min(Math.max(e,r.top),r.bottom-1)}}attachDrag(o,e){o.addEventListener("pointerdown",t=>{var J,k;const n=t.pointerType==="mouse";if(!t.isPrimary||(n?t.button!==0:this.options.touch===!1)||zs(t.target))return;(J=this.endDrag)==null||J.call(this);const s=o.getBoundingClientRect();let r,c,a,d={x:t.clientX,y:t.clientY},l={x:0,y:0},u=1,h=1,f=0,p;const m=()=>{if(r)return;p=this.createDragLayer(),r=o.cloneNode(!0),r.classList.add("morphic-drag-ghost"),r.removeAttribute("tabindex"),Object.assign(r.style,{position:"fixed",left:"0",top:"0",margin:"0",pointerEvents:"none",zIndex:"2147483647",transition:"none",animation:"none",transformOrigin:"0 0"}),p.appendChild(r);const C=r.getBoundingClientRect();r.style.left="100px",u=(r.getBoundingClientRect().left-C.left)/100||1,l={x:C.left,y:C.top},Object.assign(r.style,{left:`${(s.left-l.x)/u}px`,top:`${(s.top-l.y)/u}px`,width:`${s.width/u}px`});const I=(Z,R)=>Z.offsetWidth>0&&R>0?R/Z.offsetWidth:1;h=I(o,s.width)/I(r,r.getBoundingClientRect().width),Math.abs(h-1)<.01?h=1:r.style.width=`${s.width/u/h}px`,w()},E=n?0:window.setTimeout(m,Ws),g=C=>{if(a&&a.element!==(C==null?void 0:C.element)&&(a.holder.remove(),a=void 0),!!C){if(!a){const I=this.createDragText(e,C.element);if(!I)return;(p??this.container).appendChild(I),a={element:C.element,holder:I}}C.font&&a.holder.style.setProperty("--morphic-drag-text-font",C.font),a.holder.style.transform=`translate(${(d.x-l.x)/u+$n}px, ${(d.y-l.y)/u+$n}px)`}},w=()=>{!r||f||(f=requestAnimationFrame(()=>{var D,F,W,se;if(f=0,!r)return;const C=`translate(${(d.x-t.clientX)/u}px, ${(d.y-t.clientY)/u}px)`;r.style.transform=h===1?C:`${C} scale(${h})`;const I=this.heldTargetAt(d.x,d.y,c),Z=I.target;Z!==c&&(c==null||c.element.classList.remove(ot),(D=c==null?void 0:c.leave)==null||D.call(c)),c=Z;const R=((F=c==null?void 0:c.takes)==null?void 0:F.call(c))===!1;o.classList.toggle(ot,R),c==null||c.element.classList.toggle(ot,R);const Q=(W=c==null?void 0:c.preview)==null?void 0:W.call(c);g(typeof Q=="object"?Q:void 0),r.style.visibility=Q==="block"||a?"hidden":"";const T=(se=c==null?void 0:c.over)==null?void 0:se.call(c,I.x,I.y,e,(a==null?void 0:a.holder.textContent)??void 0);a&&(a.holder.style.visibility=T===!0?"hidden":""),o.classList.toggle(Mn,T===!1)}))},$=C=>{if(C.pointerId!==t.pointerId)return;if(C.buttons===0){V(!1);return}d={x:C.clientX,y:C.clientY};const I=Math.abs(C.clientX-t.clientX),Z=Math.abs(C.clientY-t.clientY);!r&&(n?Math.max(I,Z)<Hs:I<js||Z>I)||(window.clearTimeout(E),m(),w())},H=C=>{r&&C.preventDefault()},x=C=>C.preventDefault(),M=C=>{C.key==="Escape"&&V(!1)};let L=!1;const V=(C,I=d.x,Z=d.y)=>{var F,W,se,ie;if(L)return;L=!0,this.endDrag===_&&(this.endDrag=void 0),window.clearTimeout(E),window.removeEventListener("pointermove",$,!0),window.removeEventListener("pointerup",A,!0),window.removeEventListener("pointercancel",A,!0),o.removeEventListener("touchmove",H),o.removeEventListener("contextmenu",x),document.removeEventListener("selectstart",x),window.removeEventListener("keydown",M,!0),(F=o.hasPointerCapture)!=null&&F.call(o,t.pointerId)&&o.releasePointerCapture(t.pointerId),cancelAnimationFrame(f);const R=C&&r?this.heldTargetAt(I,Z,c):void 0,Q=R==null?void 0:R.target,T=((W=Q==null?void 0:Q.takes)==null?void 0:W.call(Q))===!1?void 0:Q,D=r!==void 0;try{c!==T&&((se=c==null?void 0:c.leave)==null||se.call(c))}finally{o.classList.remove(ot,Mn),c==null||c.element.classList.remove(ot),g(void 0),r==null||r.remove(),r=void 0,p==null||p.remove(),p=void 0,this.container.classList.remove("morphic-toolbox-dragging")}if(D){if(n){const O=N=>N.stopPropagation();o.addEventListener("click",O,{capture:!0,once:!0}),window.setTimeout(()=>o.removeEventListener("click",O,!0),0)}try{T==null||T.drop(e,R.x,R.y)}finally{(ie=T==null?void 0:T.leave)==null||ie.call(T)}}},A=C=>{C.pointerId===t.pointerId&&V(C.type==="pointerup",C.clientX,C.clientY)},_=()=>V(!1);this.endDrag=_,(k=o.setPointerCapture)==null||k.call(o,t.pointerId),window.addEventListener("pointermove",$,!0),window.addEventListener("pointerup",A,!0),window.addEventListener("pointercancel",A,!0),o.addEventListener("touchmove",H,{passive:!1}),o.addEventListener("contextmenu",x),document.addEventListener("selectstart",x),window.addEventListener("keydown",M,!0)})}createDragLayer(){const{layer:o,onTop:e}=Jt(this.container);return e||this.container.classList.add("morphic-toolbox-dragging"),o}createDragText(o,e){var c,a;const t=this.definitions.get(o),n=t?(c=this.createCodeText(t,this.currentMode,e,!0))==null?void 0:c.trimEnd():void 0;if(!n)return null;const s=document.createElement("div");s.className=`morphic-drag-text morphic-drag-text-${pe(e)}`,Object.assign(s.style,{position:"fixed",left:"0",top:"0",margin:"0",pointerEvents:"none",zIndex:"2147483647"});const r=this.options.highlight===!1||(a=this.code[e])==null?void 0:a.highlighting;return Io(e,r==null?void 0:r.colors),r?s.innerHTML=Zt(n,r):s.textContent=n,s}ensurePreviewWorkspace(){var e;if(this.previewWorkspace)return this.previewWorkspace;this.previewContainer=document.createElement("div"),this.previewContainer.style.cssText="position:absolute;left:-9999px;top:-9999px;width:800px;height:600px;overflow:hidden;",document.body.appendChild(this.previewContainer);const o=this.workspace.options;return this.previewWorkspace=v.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:an(e)});const t=ln(this.container,[["morphic-block",`morphic-mode-${pe(this.currentMode)}`],[`morphic-element-${pe(o)}`],[e.getRenderer().getClassName(),e.getTheme().getClassName()]],this.previewBase.font);dn(e,this.previewBase.theme,this.previewBase.font,t)}createPreviewBlock(o,e,t){var d;const n=this.ensurePreviewWorkspace(),s=n.newBlock(be(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};Co({block:s,definition:o,view:c,mode:"block",context:"toolbox",elementTypes:this.elementTypes,resolveBlocklyType:l=>be(l,this.definitions)});const a=Xe(this.behaviors[o.identifier]);return(d=a==null?void 0:a.onViewApplied)==null||d.call(a,s,{Blockly:v,workspace:n,element:t,mode:e,context:"toolbox",definition:o}),s}createCodeText(o,e,t,n=!1){try{const s=this.createPreviewBlock(o,e,t),{code:r}=Xo(s.workspace,e,this.definitions,this.elementTypes,this.modes,t,{emptyStatements:n});return s.dispose(!1),r}catch{return null}}createBlockPreviewSvg(o,e,t){try{const n=this.ensurePreviewWorkspace(),s=this.createPreviewBlock(o,e,t);for(const h of s.getDescendants(!1))h.initSvg(),h.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"),u=Math.ceil(c.width+d*2);return this.widestBlock=Math.max(this.widestBlock,u),l.setAttribute("width",String(u)),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}}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 zs(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}const Dn=/^-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][-+]?\d+)?$/,An=new WeakSet;function Nn(i,o){const e=()=>{for(const n of i.getAllBlocks(!1))for(const s of n.inputList)for(const r of s.fieldRow)r instanceof v.FieldNumber&&!An.has(r)&&Gs(r,o)},t=i.getInjectionDiv();return t.addEventListener("pointerdown",e,!0),()=>t.removeEventListener("pointerdown",e,!0)}function Gs(i,o){An.add(i);const e=i,t=e.getValueFromEditorText_.bind(i),n=e.onHtmlInputKeyDown_.bind(i),s=e.onFinishEditing_.bind(i),r=e.render_.bind(i);let c,a;const d=l=>{const u=e.htmlInput_;u&&(u.classList.toggle("morphic-value-rejected",l),l&&u.setAttribute("aria-invalid","true"))};e.getValueFromEditorText_=l=>(c=Dn.test(l.trim())||l.trim()===""||!o(i)?void 0:l,a=void 0,d(!1),c!==void 0&&e.htmlInput_&&(e.htmlInput_.style.minWidth=`${l.length+2}ch`),t(l)),e.render_=()=>{r(),!(c===void 0||!e.htmlInput_)&&(e.htmlInput_.classList.remove("blocklyInvalidInput"),c!==a&&e.htmlInput_.removeAttribute("aria-invalid"))},e.onHtmlInputKeyDown_=l=>{l.key==="Escape"&&(c=void 0);const u=l.key==="Enter"&&c!==void 0?o(i):void 0;if(!u||c===void 0){n(l);return}const h=c;if(l.preventDefault(),h!==a){if(!u(h,!0)){a=h,$o(),d(!0);return}c=void 0,v.WidgetDiv.hide(),u(h,!1)}},e.onFinishEditing_=l=>{s(l);const u=c,h=u!==void 0&&u!==a?o(i):void 0;c=void 0,a=void 0,h&&setTimeout(()=>h(u,!1),0)}}function nt(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 Qt(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=>nt(a,o,i.blocks).length>0).map(a=>({kind:"category",name:a.name,colour:a.color,contents:nt(a,o,i.blocks).map(d=>({kind:"block",type:be(d,o)}))}))};if((s=i.categories)!=null&&s.length){const c=i.categories.filter(l=>nt(l,o,i.blocks).length>0),a=[];return c.forEach((l,u)=>{const h=pe(l.name);a.push({kind:"label",id:`morphic-category-${h}`,text:l.name,"web-class":`morphic-flyout-category-label morphic-category-${h}`});for(const f of Vn(nt(l,o,i.blocks)))a.push({kind:"block",type:be(f,o)});u<c.length-1&&a.push({kind:"sep",gap:14})}),{kind:"flyoutToolbox",contents:a}}return{kind:"flyoutToolbox",contents:(i.blocks??Vn(((r=i.categories)==null?void 0:r.flatMap(c=>nt(c,o)))??[...o.keys()])).map(c=>({kind:"block",type:be(c,o)}))}}function Vn(i){return i.filter((o,e,t)=>t.indexOf(o)===e)}const Us=/(<img\b[^>]*?\bsrc\s*=\s*)(?:(["'])(.*?)\2|([^\s>"']+))/gi,Xs=i=>i.replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&amp;/g,"&"),Ks=i=>i.replace(/["'<>]/g,o=>`%${o.charCodeAt(0).toString(16).toUpperCase()}`);function Ys(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 d=o[c],u=(typeof d=="string"?d:d==null?void 0:d.type)==="image"?Ot(a,Lt(d)):a;return u!==a&&(t=!0),[c,u.replace(Us,(h,f,p,m,E)=>{const g=n(Xs(m??E??""));return g===void 0?h:`${f}"${Ks(g)}"`})]})),r=i.fields?Object.fromEntries(Object.entries(i.fields).map(([c,a])=>{if(a.type!=="dropdown")return[c,a];const d=a.options.map(l=>typeof l=="object"&&!Array.isArray(l)&&typeof l.label=="object"&&l.label.src!==void 0?{...l,label:{...l.label,src:n(l.label.src)??l.label.src}}:l);return[c,{...a,options:d}]})):void 0;return t?{...i,elements:s,...r?{fields:r}:{}}:i}const qs='<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>',Js='<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>',Zs='<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>',Qs='<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>',er='<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>',tr='<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>',or='<svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor"><polygon points="4,3 13,8 4,13"/></svg>',nr='<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>',ir='<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>',sr='<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>',rr='<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>',cr='<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>',ar='<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>',he={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:qs,onClick:i=>{i.engine.copyActiveBlock(i.view)}}},paste(){return{id:"paste",label:"Paste",title:"Paste block",icon:Js,disabled:i=>!i.engine.hasClipboardContents(),onClick:i=>{i.engine.pasteActiveBlock(i.view)}}},undo(){return{id:"undo",label:"Undo",title:"Undo (block model)",icon:Zs,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:Qs,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:nr,onClick:i=>i.engine.zoomPane(i.view,"in")}},zoomOut(){return{id:"zoom-out",label:"Zoom out",title:"Zoom out",icon:ir,onClick:i=>i.engine.zoomPane(i.view,"out")}},zoomFit(){return{id:"zoom-fit",label:"Fit",title:"Reset zoom",icon:sr,onClick:i=>i.engine.zoomPane(i.view,"fit")}},deleteSelection(){return{id:"delete",label:"Delete",title:"Delete selected lines",icon:tr,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:er,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:or,onClick:i=>{i.engine.runJavaScript()}}},save(){return{id:"save",label:"Save",title:"Save workspace as JSON",icon:rr,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:cr,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:ar,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[he.viewLabel(),he.spacer(),he.copy(),he.zoomIn(),he.zoomOut(),he.zoomFit(),he.readOnlyBadge()]},defaultsFor(i,o=!1){if(o)return he.readOnlyDefaults();switch(i){case"workspace":return[he.viewLabel(),he.spacer(),he.undo(),he.redo(),he.copy(),he.paste(),he.zoomIn(),he.zoomOut(),he.zoomFit(),he.clear()];case"codespace":return[he.viewLabel(),he.spacer(),he.undo(),he.redo(),he.copy(),he.paste(),he.deleteSelection(),he.zoomIn(),he.zoomOut(),he.zoomFit(),he.clear()]}}};function Pn(i,o,e){const t=o.items??he.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 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(lr(d,n,e))}};return i.replaceChildren(s,r),c(),{refresh:c,kind:e.kind,view:e.view,dispose:()=>i.replaceChildren()}}function lr(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),dr(t,i,o),i.disabled&&i.disabled(e)&&(t.disabled=!0),i.onClick&&t.addEventListener("click",()=>i.onClick(e)),t}function dr(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 _n(i,o){return o.includes("{")?{mode:i,cssText:o}:{mode:i,href:o}}function ur(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(_n(s,r))}return o}function Fn(i){if(i.length===1)throw new Error(i[0]);if(i.length>1)throw new Error(`[MorphicBlocks] Invalid definitions:
46
50
  - ${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:
51
+ - `)}`)}const hr="blockly-media/",Rn=new Set;function fr(i,o){if(Rn.has(i)||typeof Image>"u")return;Rn.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 Pe=i=>i.onWarning??(o=>console.warn(o)),Fe=new WeakMap,Ue=new Map;function eo(i,o,e){var r;const t=o.get(e);if((t==null?void 0:t.startChar)===void 0||t.endChar===void 0)return"";const n=i.lastIndexOf(`
52
+ `,t.startChar-1)+1,s=((r=/^[ \t]*/.exec(i.slice(n)))==null?void 0:r[0])??"";return i.slice(t.startChar,t.endChar).split(`
53
+ `).map((c,a)=>a>0&&c.startsWith(s)?c.slice(s.length):c).join(`
54
+ `)}function pr(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 mr extends EventTarget{constructor(e,t={}){super();b(this,"definitions");b(this,"loadedDefinitions");b(this,"behaviors");b(this,"elementTypes");b(this,"formatElementTypes");b(this,"styles",new Ni);b(this,"registeredBlockTypes",new Set);b(this,"toolbars",new Set);b(this,"toolbarsBlocklyListener");b(this,"lastCopyData");b(this,"mountConfig");b(this,"workspace");b(this,"flyoutWorkspace");b(this,"toolboxCanvas");b(this,"tileDropTargets",new Set);b(this,"codeEditor");b(this,"views",new Set);b(this,"codeGrabbers",new WeakMap);b(this,"viewWorkspaceElements",new WeakMap);b(this,"viewCount",0);b(this,"selectionSync");b(this,"toolboxDefinition");b(this,"blockCategoryIndex",new Map);b(this,"appliedWorkspaceClasses",[]);b(this,"appliedToolboxFlyoutClasses",[]);b(this,"appliedToolboxShellClasses",[]);b(this,"headlessWorkspaceHost");b(this,"workspaceResizeObserver");b(this,"activePreset");b(this,"baseTheme");b(this,"baseFont");b(this,"mountGeneration",0);b(this,"selectionSyncOptions");b(this,"formatModes");b(this,"formatPresets");b(this,"formatViews");b(this,"formatCode");b(this,"formatHasHighlighting");b(this,"formatCategories");b(this,"formatBlockSets");b(this,"blockSetLists",new Map);b(this,"activeBlockSet");b(this,"categoriesShown",!0);b(this,"onWorkspaceChange",e=>{if(!this.workspace||!this.mountConfig||e.workspaceId!==this.workspace.id||e.type!==v.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(me(s.type));if(!r)continue;const c=this.mountConfig.workspaceElement,a=s;if(a.__morphicMode===c&&a.__morphicContext==="workspace"&&s.getSvgRoot()){xo(s,c,"workspace"),this.styleBlock(s,r);continue}this.applyView(s,r,c,"workspace"),s.getSvgRoot()||this.deferApplyView(n,c,"workspace")}});b(this,"onFlyoutChange",e=>{if(!this.flyoutWorkspace||!this.mountConfig||e.workspaceId!==this.flyoutWorkspace.id||e.type!==v.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(me(s.type));r&&(this.applyView(s,r,this.mountConfig.toolboxMode,"toolbox"),s.getSvgRoot()||this.deferApplyView(n,this.mountConfig.toolboxMode,"toolbox"))}});b(this,"onStylesLoaded",()=>this.refresh());const n=e;this.definitions=rn(nn(sn(n.blocks,n.elementTypes??{}))),this.loadedDefinitions=new Map(this.definitions),this.behaviors=t,this.formatElementTypes=n.elementTypes??{},this.elementTypes=Tt(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 M,L,V,A,_,J,k,C,I,Z;this.dispose(),this.resolveAssetUrls(e.assetUrl);const t={...e,modes:(M=e.modes??this.formatModes)==null?void 0:M.slice(),presets:e.presets??this.formatPresets,code:e.code??this.formatCode,toolbox:e.toolbox||this.formatCategories?{...e.toolbox,categories:((L=e.toolbox)==null?void 0:L.categories)??this.formatCategories}:void 0},n=t.modesFolder?ur(t.modesFolder):[],s=[...n,...Object.entries(t.modeStyles??{}).filter(([R])=>!n.some(Q=>Q.mode===R)).map(([R,Q])=>_n(R,Q))];this.elementTypes=Tt(this.formatElementTypes,t.code),this.validateDefinitions(t),this.validatePresets(t);const r=(V=t.presets)!=null&&V.length?t.presets.find(R=>R.name===t.preset)??t.presets[0]:void 0;if(t.preset&&!r)throw new Error(`MorphicBlocks.mount: unknown preset "${t.preset}".`);this.blockSetLists=Ut(this.formatBlockSets,R=>this.definitions.has(R)).lists,this.activeBlockSet=r==null?void 0:r.blockSet,this.categoriesShown=(r==null?void 0:r.categories)!==!1;const c=(t.modes??[]).map(R=>R.name),a=c[0]??((A=s[0])==null?void 0:A.mode)??"default",d=r?r.toolbox:a,l=Yt(t.views??this.formatViews),u={...t.containers};t.workspaceContainer&&(u.workspace??(u.workspace=t.workspaceContainer)),t.codespaceContainer&&(u.codespace??(u.codespace=t.codespaceContainer)),this.validateViews(l,u);const h=Object.keys(l).find(R=>l[R].kind==="workspace"&&u[R]),f=this.defaultElement(t.modes??[]),p=R=>(R?r==null?void 0:r.views[R]:void 0)??f,m=h?p(h):f,E=h&&u[h]||this.createHeadlessHost(),g={...t,modeStyles:s,workspaceElement:m,toolboxMode:d,viewDeclarations:l,viewContainers:u,programView:h,workspaceHost:E,canvasToolbox:t.canvasToolbox??!!t.toolboxContainer};this.mountConfig=g,this.styles.validateModeCoverage(s,c,Pe(t)),(_=g.modes)!=null&&_.length&&this.styles.ensureModeVisibilityStyles(g.modes),this.styles.ensureStyles(g.baseStyle,s);for(const R of Array.from(document.head.querySelectorAll('link[data-morphic-source^="mode:"]')))R.sheet||R.addEventListener("load",this.onStylesLoaded,{once:!0});(J=document.fonts)==null||J.addEventListener("loadingdone",this.onStylesLoaded),this.blockCategoryIndex=this.createCategoryIndex(g.toolbox,g),this.styles.ensureCategoryStyles(((k=g.toolbox)==null?void 0:k.categories)??[]),this.styles.ensureWorkspaceStyles(),this.registerBlocks(),this.toolboxDefinition=this.resolveToolboxDefinition(g);const w=typeof this.toolboxDefinition=="object"&&"kind"in this.toolboxDefinition?this.toolboxDefinition.kind:void 0;!g.canvasToolbox&&w==="categoryToolbox"&&((C=g.presets)!=null&&C.some(R=>R.categories===!1))&&Pe(g)(`[MorphicBlocks] Blockly's category toolbox keeps its categories; "categories": false in a preset works with the HTML toolbox (toolboxContainer) or toolboxLayout "flyout".`);const $=g.blockly??{},H=h?l[h].editable!==!1:!0;if(this.workspace=v.inject(g.workspaceHost,{...$,...H?{}:{readOnly:!0},...h&&l[h].rtl!==void 0?{rtl:l[h].rtl}:{},media:$.media??hr,...g.canvasToolbox?{}:{toolbox:this.toolboxDefinition}}),po(this.workspace),h&&H&&Nn(this.workspace,R=>this.typedValueTaker(R,()=>{const Q=this.mountConfig;return Q!=null&&Q.programView?{name:Q.programView,element:Q.workspaceElement}:void 0})),Yn(this.workspace),this.workspace.addChangeListener(this.onWorkspaceChange),Fe.set(this.workspace,this),this.baseTheme=this.workspace.getTheme(),this.baseFont=an(this.workspace),h&&fr(this.workspace.options.pathToMedia,Pe(t)),h&&typeof ResizeObserver<"u"){const R=this.workspace;this.workspaceResizeObserver=new ResizeObserver(()=>v.svgResize(R)),this.workspaceResizeObserver.observe(E)}this.applyWorkspaceContainerClass(),this.syncWorkspaceFont(),this.refreshToolbox(),this.bindFlyoutWorkspace(),this.renderWorkspaceBlocks(),this.renderFlyoutBlocks(),t.toolboxContainer&&this.mountToolbox(t.toolboxContainer);const x=[];for(const[R,Q]of Object.entries(l)){const T=u[R];if(!T||R===h)continue;const D=this.addView({kind:Q.kind,name:R,container:T,element:p(R),editable:Q.editable,rtl:Q.rtl,delete:Q.delete,theme:((I=t.themes)==null?void 0:I[R])??t.editorTheme});x.push(D.ready)}return this.activePreset=r,this.applyPresetClasses(),r&&((Z=g.onPresetApplied)==null||Z.call(g,r)),this.mountViews(t,x,++this.mountGeneration)}async mountViews(e,t,n){var a;const s=[...t];if(e.codeEditorContainer){const d=e.editorTheme?{theme:e.editorTheme}:void 0;s.push(this.mountCodeEditor(e.codeEditorContainer,d).then(()=>{n===this.mountGeneration&&this.hideCodeEditor()}))}if(await Promise.all(s),n!==this.mountGeneration||!this.workspace)return;for(const[d,l]of Object.entries(e.toolbars??{}))l&&this.resolveView(d)&&this.mountToolbar(l,{view:d});const r=Object.keys(((a=this.mountConfig)==null?void 0:a.viewContainers)??{}).filter(d=>this.resolveView(d)).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&&pt(this.mountConfig.workspaceHost,e);for(const s of this.views)pt(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 d;return((d=this.mountConfig)==null?void 0:d.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}=Xt({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(...gn(e.presets,this.formatHasHighlighting||"highlighting"in e)),n.length>0&&Pe(e)(`[MorphicBlocks] Definition warnings:
48
55
  - ${n.join(`
49
56
  - `)}`),t.length>0)throw new Error(`[MorphicBlocks] Invalid definitions:
50
57
  - ${t.join(`
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"})}));
58
+ - `)}`)}validatePresets(e){const{errors:t,warnings:n}=mn({presets:e.presets,modes:e.modes,views:Yt(e.views??this.formatViews),elementTypes:this.elementTypes});for(const s of n)Pe(e)(`[MorphicBlocks] ${s}`);Fn(t)}dispose(){var e,t,n,s,r;for(const[c,a]of Ue)a===this&&Ue.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,d;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[l,u]of Object.entries(this.elementTypes))ge(u)==="custom"&&!((a=s.custom)!=null&&a[l])&&Pe(this.mountConfig)(`[MorphicBlocks] The custom element "${l}" has no function in toolbox.custom; tiles show its content as text.`);s.layout==="tabs"&&!((d=s.categories)!=null&&d.length)&&Pe(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"&&Pe(this.mountConfig)("[MorphicBlocks] toolbox.collapsed needs category headings to open the categories again; all categories start open."),this.toolboxCanvas=new On({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:l=>Fe.set(l,this),dropTargets:()=>[...this.tileDropTargets],onChoose:l=>this.addBlockFromTile(l)})}refresh(){var e;if(!(!this.workspace||!this.mountConfig)){this.syncWorkspaceFont(),Gt(this.workspace);for(const t of this.views)t.workspace&&(this.syncFontOf(t.workspace,t.container),Gt(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 l;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(u=>u.name===e);if(s===-1)throw new Error(`setModeElements: unknown mode "${e}".`);const r=t.filter(u=>!(u in this.elementTypes));if(r.length>0)throw new Error(`setModeElements: unknown elements ${r.map(u=>`"${u}"`).join(", ")}.`);const c={...n[s],elements:[...t]},a=n.map((u,h)=>h===s?c:u);this.validatePresets({...this.mountConfig,modes:a});const d=n.slice();n[s]=c,this.styles.ensureModeVisibilityStyles(n,d),e===this.mountConfig.toolboxMode&&((l=this.toolboxCanvas)==null||l.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=Pn(e,t,{engine:this,kind:s.kind,readOnly:s.readOnly,view:n,getText:()=>this.toolbarTextFor(n),refresh:()=>this.toolbarRefreshFor(n)});this.toolbars.add(r),this.ensureToolbarBlocklyListener();const c=r.dispose;return r.dispose=()=>{this.toolbars.delete(r),this.toolbars.size===0&&this.teardownToolbarBlocklyListener(),c()},r}toolbarTextFor(e){var n;const t=this.resolveView(e);if((t==null?void 0:t.kind)==="codespace")return((n=t.editor)==null?void 0:n.getValue())??this.generateElementText(t.element).code;if((t==null?void 0:t.kind)==="workspace"&&t.workspace!==this.workspace)return this.generateElementText(t.element).code;if(this.codespace)return this.codespace.getValue();try{return this.generateJavaScript()}catch{return""}}toolbarRefreshFor(e){var t,n;(n=(t=this.resolveView(e))==null?void 0:t.editor)==null||n.refresh()}runJavaScript(e){var p,m,E;let t="",n,s=null;const r=[],c=(e==null?void 0:e.console)??(e!=null&&e.logToConsole?console:void 0),a=this.codespaceElement(),d=a?(E=(m=(p=this.mountConfig)==null?void 0:p.code)==null?void 0:m[a])==null?void 0:E.values:void 0,l=g=>(...w)=>{r.push({level:g,text:w.map($=>vn($,d)).join(" ")}),c&&(c[g]??c.log).apply(c,w)},u={log:l("log"),warn:l("warn"),error:l("error")},h=Object.entries((e==null?void 0:e.globals)??{});try{t=this.generateJavaScript();for(const[g]of h){if(g==="console")throw new Error('globals: "console" is set with the console option of runJavaScript()');if(!/^[\p{L}_$][\p{L}\p{N}_$]*$/u.test(g))throw new Error(`globals: "${g}" is not a JavaScript name`)}n=new Function("console",...h.map(([g])=>g),t)(u,...h.map(([,g])=>g))}catch(g){s=g instanceof Error?g:new Error(String(g))}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,values:(t==null?void 0:t.values)!==!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 c;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)??((c=this.mountConfig)==null?void 0:c.workspaceElement));return eo(s,r,t.id)}pasteActiveBlock(e){return!this.lastCopyData||!this.workspace?!1:v.clipboard.paste(this.lastCopyData,this.workspace)!==null}resolveActiveBlock(e){var a,d,l;const t=v.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[u,h]of n.metadata)if(h.startLine<=s&&h.endLine>=s){const f=h.endLine-h.startLine;(!r||f<r.size)&&(r={id:u,size:f})}return(r?(l=this.workspace)==null?void 0:l.getBlockById(r.id):null)??null}serializeWorkspace(){return this.workspace?Bn(this.workspace):null}loadWorkspace(e){this.workspace&&(this.workspace.clear(),v.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,d;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[l,u]of Object.entries(e.views??{})){if(!this.mountConfig.viewDeclarations[l]&&!this.resolveView(l))throw new Error(`show: no view named "${l}".`);this.checkViewElement("show",u)}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[l,u]of Object.entries(e.views??{})){l===this.mountConfig.programView&&u!==this.mountConfig.workspaceElement&&(this.mountConfig.workspaceElement=u,this.applyWorkspaceContainerClass(),this.syncWorkspaceFont(),this.renderWorkspaceBlocks());const h=[...this.views].find(f=>f.name===l);h&&h.element!==u&&((a=h.show)==null||a.call(h,u))}this.refreshTextViews();for(const l of this.toolbars)l.refresh();(d=this.selectionSync)==null||d.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 Ki(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=Ds(e,t.element,this.definitions,(r=this.mountConfig.code)==null?void 0:r[t.element]);if(!n.ok)return n;const s=v.Events.getGroup();s||v.Events.setGroup(!0),so(v.Events.getGroup());try{v.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 d=a.getRelativeToSurfaceXY();a.moveBy(20-d.x,c-d.y),c+=a.getHeightWidth().height+20}}finally{s||v.Events.setGroup(!1)}return{ok:!0,blocks:n.blocks}}loadValueText(e,t){return this.readValueText(e,t,!1)}readValueText(e,t,n){var E,g,w;if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before loadValueText can be used.");this.checkViewElement("loadValueText",t.element);const s=this.workspace,r=s.getBlockById(typeof t.block=="string"?t.block:t.block.id);let c;if(t.slot===void 0){if(!(r!=null&&r.outputConnection))throw new Error("loadValueText: without a slot, the block must be a value.");c=r.outputConnection.targetConnection}else if(c=((E=r==null?void 0:r.getInput(t.slot))==null?void 0:E.connection)??null,!c||c.type!==v.ConnectionType.INPUT_VALUE)throw new Error(`loadValueText: the block has no value slot "${t.slot}".`);const a=c?void 0:r,d=c==null?void 0:c.getSourceBlock(),l=(g=c==null?void 0:c.getParentInput())==null?void 0:g.name,u=d&&this.definitions.get(me(d.type)),h=As(e,t.element,this.definitions,(w=this.mountConfig.code)==null?void 0:w[t.element],{slot:u&&l?Bt(u,l):void 0,names:this.declaredNameKeys()});if(!h.ok)return h;const f=this.unknownNameIn(h.block,d??a);if(f!==void 0)return{ok:!1,reason:"unknown-name",name:f,message:`"${f}" is not declared here.`};let p;v.Events.disable();try{if(p=v.serialization.blocks.append(h.block,s),!p.outputConnection||c&&!s.connectionChecker.canConnect(c,p.outputConnection,!1))return p.dispose(!1),{ok:!1,reason:"wrong-slot",message:`This slot does not take ${e.trim()}.`};if(n)return p.dispose(!1),{ok:!0,blocks:h.blocks};if(a){const $=a.getRelativeToSurfaceXY(),H=p.getRelativeToSurfaceXY();p.moveBy($.x-H.x,$.y-H.y)}}finally{v.Events.enable()}const m=v.Events.getGroup();m||v.Events.setGroup(!0),so(v.Events.getGroup());try{if(v.Events.fire(new(v.Events.get(v.Events.BLOCK_CREATE))(p)),c){const $=c.targetBlock();$&&!$.isShadow()&&$.dispose(!1),c.connect(p.outputConnection)}else a.dispose(!1)}finally{m||v.Events.setGroup(!1)}return{ok:!0,blocks:h.blocks}}declaredNameKeys(){const e=new Set;if(!this.workspace)return e;const t=new Set;for(const n of this.definitions.values())for(const s of Object.values(n.fields??{}))if(s.type==="reference")for(const r of[s.to].flat())t.add(r);for(const n of t){const s=ct(n);if(s)for(const r of this.workspace.getBlocksByType(xe(s.block),!1)){const c=r.getFieldValue(s.field);typeof c=="string"&&c!==""&&e.add(`${n}=${c}`)}}return e}unknownNameIn(e,t){var s;const n=this.definitions.get(me(e.type));for(const[r,c]of Object.entries((n==null?void 0:n.fields)??{})){if(c.type!=="reference")continue;const a=String(((s=e.fields)==null?void 0:s[r])??"");if(!Kn(t.workspace,c.to,c.scope,t).includes(a))return a}for(const r of Object.values(e.inputs??{})){const c=r.block?this.unknownNameIn(r.block,t):void 0;if(c!==void 0)return c}}generateJavaScriptWithMetadata(){if(!this.workspace||!this.mountConfig)throw new Error("MorphicBlocks must be mounted before generateJavaScriptWithMetadata can be used.");return Yi(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 Fo(e,this.workspace,()=>this.generateJavaScriptWithMetadata(),t,!0);const n=this.codeEditor;await n.mount(),this.codeEditor===n&&this.refreshSelectionSync()}attachCodespaceDropTarget(e,t,n,s){let r=null,c=null,a;const d=()=>{r=null,c=null,a=void 0,e.hideDropIndicator(),e.hideValueSlotHighlight(),e.hideDropPreview()},l=(T,D)=>{const F=`${T} ${JSON.stringify(D.target)}`;if((a==null?void 0:a.key)===F)return a.fit&&{...D,target:a.fit.target};let W=null;v.Events.disable();try{const se=n.newBlock(be(T,this.definitions));try{W=this.fitOrLoose(n,se,D)}finally{se.dispose(!1)}}finally{v.Events.enable()}return a={key:F,fit:W},W},u=(T,D)=>({text:D,fit:F=>l(T,F)}),h=T=>{const D=T?n.getBlockById(T):null,F=D?eo(e.getValue(),e.metadata,D.id):"";return D&&F?{text:F,fit:W=>this.fitOrLoose(n,D,W)}:void 0},f=(T,D,F)=>{if(r&&c){if(c.inLine)e.hideDropPreview();else if(e.isOnDropPreview(T,D))return}const W=this.computeCodespaceDrop(e,T,D),se=W&&F?F.fit(W):W;if(!se){const ie=a;d(),a=ie;return}if(F){const ie=this.dropPreviewPlace(e,se),O=`${F.text}
59
+ ${JSON.stringify(ie)}`,N=ie.kind==="value";if(r=se,(c==null?void 0:c.key)===O&&!N)return;c={key:O,inLine:N},e.hideDropIndicator(),e.hideValueSlotHighlight(),e.showDropPreview(F.text,ie);return}se.indicator.kind==="line"?(e.showDropIndicator(se.indicator.line,se.indicator.position),e.hideValueSlotHighlight()):(e.showValueSlotHighlight(se.indicator.from,se.indicator.to),e.hideDropIndicator())},p=(T,D,F)=>{const W=r;d();const se=W??this.computeCodespaceDrop(e,T,D);if(!se)return;const ie=n.newBlock(be(F,this.definitions));this.placeOrphanBelowTops(ie),ie.initSvg(),ie.render();const O=this.fitOrLoose(n,ie,se);if(!O){ie.dispose(!1);return}let N=!1;v.Events.setGroup(!0);try{if(O.target.kind==="top")this.placeAtTopIndex(n,ie,O.target.index),N=!0;else if(O.target.kind==="statement"){if(ie.previousConnection){const Y=n.getBlockById(O.target.targetBlockId);Y&&Y!==ie&&(this.connectStatement(ie,Y,O.target.position),N=!0)}}else if(O.target.kind==="into-slot"){if(ie.previousConnection){const Y=n.getBlockById(O.target.parentBlockId);Y&&Y!==ie&&(this.connectIntoSlot(ie,Y,O.target.inputName),N=!0)}}else if(O.target.kind==="value-slot"){if(ie.outputConnection){const Y=n.getBlockById(O.target.parentBlockId);Y&&Y!==ie&&!this.isDescendantOf(Y,ie)&&(N=this.connectIntoValueSlot(ie,Y,O.target.inputName))}N||ie.dispose(!1)}}finally{v.Events.setGroup(!1)}!N&&ie.workspace&&!ie.getParent()&&this.placeOrphanBelowTops(ie),v.svgResize(n)};let m=null;const E=3,g=12,w="morphic-drag-refused",$="morphic-drag-no-place",H=T=>T.button===2||T.button===0&&T.ctrlKey,x=T=>{const D=n.getBlockById(T),F=e.metadata.get(T);!D||!F||(!D.outputConnection||!D.getParent()?e.setDragSource({lines:{from:F.startLine,to:F.endLine}}):F.startChar!==void 0&&F.endChar!==void 0&&e.setDragSource({range:{from:F.startChar,to:F.endChar}}))},M=()=>{if(!m)return;const T=eo(e.getValue(),e.metadata,m.sourceId);if(!T)return;const D=s(),F=document.createElement("div");F.className=`morphic-drag-text morphic-drag-text-${pe(D)}`,Object.assign(F.style,{position:"fixed",left:"0",top:"0",margin:"0",pointerEvents:"none",zIndex:"2147483647"});const W=this.highlightRulesFor(D);Io(D,W==null?void 0:W.colors),W?F.innerHTML=Zt(T,W):F.textContent=T;const se=this.tileTextLook(t,D).font;se&&F.style.setProperty("--morphic-drag-text-font",se),m.layer=Jt(t).layer,m.layer.appendChild(F);const ie=F.getBoundingClientRect();m.origin={x:ie.left,y:ie.top},m.text=F},L=(T,D)=>{var se,ie,O,N,Y,re;if(!m)return;m.text&&(m.text.style.transform=`translate(${T-m.origin.x+g}px, ${D-m.origin.y+g}px)`);const F=document.elementFromPoint(T,D);if(F&&t.contains(F)){(se=m.refused)==null||se.classList.remove(w),m.refused=void 0,(ie=m.grip)==null||ie.classList.remove(w),f(T,D,h(m.sourceId));const de=r!==null;m.text&&(m.text.style.visibility=de?"hidden":""),(O=m.grip)==null||O.classList.toggle($,!de);return}m.text&&(m.text.style.visibility=""),(N=m.grip)==null||N.classList.remove($);const W=(F==null?void 0:F.closest(".morphic-view"))??void 0;W!==m.refused&&((Y=m.refused)==null||Y.classList.remove(w),W==null||W.classList.add(w),m.refused=W),(re=m.grip)==null||re.classList.toggle(w,!!W),r&&d()},V=T=>{if(!(!m||m.pointerId!==void 0&&T.pointerId!==m.pointerId)){if(T.buttons===0){A(!1);return}if(!m.dragging){const D=Math.abs(T.clientX-m.startX),F=Math.abs(T.clientY-m.startY);if(D+F<E)return;m.dragging=!0,M(),x(m.sourceId)}L(T.clientX,T.clientY)}},A=(T,D=0,F=0)=>{var Y,re,de,we,Se,it;const W=m;if(!W)return;m=null,window.removeEventListener("pointermove",V,!0),window.removeEventListener("pointerup",_,!0),window.removeEventListener("pointercancel",_,!0),window.removeEventListener("keydown",J,!0);const se=r;if(d(),(Y=W.text)==null||Y.remove(),(re=W.layer)==null||re.remove(),(de=W.refused)==null||de.classList.remove(w),(we=W.grip)==null||we.classList.remove(w,$),W.grip&&W.pointerId!==void 0&&((it=(Se=W.grip).hasPointerCapture)!=null&&it.call(Se,W.pointerId))&&W.grip.releasePointerCapture(W.pointerId),Vo(void 0),!W.dragging||(e.setDragSource(null),!T))return;const ie=document.elementFromPoint(D,F),O=se??(ie&&t.contains(ie)?this.computeCodespaceDrop(e,D,F):null);if(!O)return;const N=n.getBlockById(W.sourceId);N&&this.applyRightDragMove(n,N,O)},_=T=>{!m||m.pointerId!==void 0&&T.pointerId!==m.pointerId||A(T.type==="pointerup",T.clientX,T.clientY)},J=T=>{T.key==="Escape"&&A(!1)},k=(T,D,F)=>{var se;A(!1);const W=F?D.pointerId:void 0;m={sourceId:T,pointerId:W,startX:D.clientX,startY:D.clientY,dragging:!1,grip:F,origin:{x:0,y:0}},Vo(T),F&&W!==void 0&&((se=F.setPointerCapture)==null||se.call(F,W)),window.addEventListener("pointermove",V,!0),window.addEventListener("pointerup",_,!0),window.addEventListener("pointercancel",_,!0),window.addEventListener("keydown",J,!0)};this.codeGrabbers.set(e,k);const C=T=>{if(!H(T))return;const D=e.charAtCoords(T.clientX,T.clientY);if(D==null)return;const F=this.findInnermostBlockAtChar(e,D);F&&(T.preventDefault(),T.stopPropagation(),k(F.id,T))},I=T=>{T.preventDefault()},Z=T=>{if(m)return;const D=e.charAtCoords(T.clientX,T.clientY);if(D==null){e.setHoverHighlight(null),e.setEditableHoverHighlight(null);return}const F=this.findInnermostEditablePlaceholderAtChar(e,D);e.setEditableHoverHighlight(F?{from:F.start,to:F.end}:null);const W=this.findHoverBlockAtChar(e,D);if(!W){e.setHoverHighlight(null);return}const se=e.metadata.get(W.id);if(!se||se.startChar===void 0||se.endChar===void 0){e.setHoverHighlight(null);return}e.setHoverHighlight({from:se.startChar,to:se.endChar})},R=()=>{e.setHoverHighlight(null),e.setEditableHoverHighlight(null)},Q={element:t,preview:()=>this.tileTextLook(t,s()),over:(T,D,F,W)=>(f(T,D,W===void 0?void 0:u(F,W)),W===void 0?void 0:r!==null),leave:d,drop:(T,D,F)=>p(D,F,T)};return this.tileDropTargets.add(Q),t.addEventListener("mousedown",C,!0),t.addEventListener("contextmenu",I),t.addEventListener("mousemove",Z),t.addEventListener("mouseleave",R),()=>{this.tileDropTargets.delete(Q),A(!1),this.codeGrabbers.delete(e),t.removeEventListener("mousedown",C,!0),t.removeEventListener("contextmenu",I),t.removeEventListener("mousemove",Z),t.removeEventListener("mouseleave",R)}}tileTextLook(e,t){return{element:t,font:getComputedStyle(e.querySelector(".cm-content")??e).font||void 0}}dropPreviewPlace(e,t){var r,c,a;const{indicator:n,target:s}=t;if(n.kind==="value-slot")return{kind:"value",from:n.from,to:n.to};if(s.kind==="into-slot"){const d=(r=this.workspace)==null?void 0:r.getBlockById(s.parentBlockId);let l=(d==null?void 0:d.getInputTargetBlock(s.inputName))??null;if(!l)return{kind:"fill",line:n.line};for(;l.getNextBlock();)l=l.getNextBlock();return{...n,indentLine:(c=e.metadata.get(l.id))==null?void 0:c.startLine}}return s.kind==="statement"?{...n,indentLine:(a=e.metadata.get(s.targetBlockId))==null?void 0:a.startLine}:n}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;v.Events.setGroup(!0);try{if(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{v.Events.setGroup(!1)}!s&&t.workspace&&!t.getParent()&&this.placeOrphanBelowTops(t),v.svgResize(e)}computeCodespaceDrop(e,t,n){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)){let g=s[s.length-1];for(;g.getNextBlock();)g=g.getNextBlock();const w=r.get(g.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 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 d=e.charAtCoords(t,n);if(d!==null){const g=this.findValueSlotDropAtChar(e,d);if(g)return{indicator:{kind:"value-slot",from:g.highlight.from,to:g.highlight.to},target:{kind:"value-slot",parentBlockId:g.parentBlockId,inputName:g.inputName}}}const l=No(),u=e.isInLowerHalfOfLine(a,n),h=(g,w)=>{var H,x;const $=[];for(let M=((x=(H=g.getInput(w))==null?void 0:H.connection)==null?void 0:x.targetBlock())??null;M;M=M.getNextBlock())M.id!==l&&$.push(M);return $},f=(g,w,$,H)=>{const x=h(g,w),M=x[0],L=M&&r.get(M.id);if(H==="start"&&M&&L)return{indicator:{kind:"line",line:L.startLine,position:"above"},target:{kind:"statement",targetBlockId:M.id,position:"before"}};const V=x[x.length-1],A=V&&r.get(V.id);return{indicator:V?{kind:"line",line:(A==null?void 0:A.endLine)??$.endLine,position:"below"}:{kind:"line",line:$.startLine,position:"above"},target:{kind:"into-slot",parentBlockId:g.id,inputName:w}}},p=(g,w)=>{const $=Object.entries(w.statementSlots??{}).filter(([M])=>{var L;return(L=g.getInput(M))==null?void 0:L.connection}),H=$.filter(([,M])=>M.endLine<a).sort((M,L)=>L[1].endLine-M[1].endLine)[0],x=$.filter(([,M])=>M.startLine>a).sort((M,L)=>M[1].startLine-L[1].startLine)[0];return!u&&H?f(g,H[0],H[1],"end"):u&&x?f(g,x[0],x[1],"start"):$.length===0?u&&a===w.endLine?"after":"before":u?"after":"before"},m=this.findInnermostStatementSlotAtLine(a,r);if(m){const g=this.workspace.getBlockById(m.blockId);if(g){for(const w of h(g,m.inputName)){const $=r.get(w.id);if(!$||a<$.startLine||a>$.endLine)continue;const H=p(w,$);return typeof H=="object"?H:H==="after"?{indicator:{kind:"line",line:$.endLine,position:"below"},target:{kind:"statement",targetBlockId:w.id,position:"after"}}:{indicator:{kind:"line",line:$.startLine,position:"above"},target:{kind:"statement",targetBlockId:w.id,position:"before"}}}return f(g,m.inputName,m.range,"end")}}for(let g=0;g<s.length;g++)for(let w=s[g];w;w=w.getNextBlock()){if(w.id===l)continue;const $=r.get(w.id);if(!$||a<$.startLine||a>$.endLine)continue;const H=p(w,$);if(typeof H=="object")return H;const x=H==="after",M=x&&!w.getNextBlock();return{indicator:x?{kind:"line",line:$.endLine,position:"below"}:{kind:"line",line:$.startLine,position:"above"},target:{kind:"statement",targetBlockId:w.id,position:x?"after":"before",topIndex:M?g+1:g}}}const E=r.get(s[s.length-1].id);return{indicator:{kind:"line",line:(E==null?void 0:E.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=(u,h)=>!!u&&!!h&&e.connectionChecker.canConnect(u,h,!1);if(n.kind==="top")return!0;if(n.kind==="value-slot"){const u=e.getBlockById(n.parentBlockId);return s((a=u==null?void 0:u.getInput(n.inputName))==null?void 0:a.connection,t.outputConnection)}if(n.kind==="into-slot"){const u=e.getBlockById(n.parentBlockId),h=(d=u==null?void 0:u.getInput(n.inputName))==null?void 0:d.connection;let f=h==null?void 0:h.targetBlock();for(;f!=null&&f.getNextBlock()&&f.getNextBlock()!==t;)f=f.getNextBlock();return s(f&&f!==t?f.nextConnection:h,t.previousConnection)}const r=e.getBlockById(n.targetBlockId);if(!r||r===t)return!1;if(n.position==="before"){const u=(l=r.previousConnection)==null?void 0:l.targetConnection;return u&&u.getSourceBlock()!==t&&!s(u,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=No();for(const a of e.getPlaceholders()){if(t<a.start||t>=a.end)continue;if(a.emptySlot){const{parentBlockId:h,inputName:f}=a.emptySlot;if(h===n)continue;const p=this.workspace.getBlockById(h);if(!((r=p==null?void 0:p.getInput(f))!=null&&r.connection))continue;return{parentBlockId:h,inputName:f,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 u=this.resolveValueParent(l);if(u)return{parentBlockId:u.parentBlockId,inputName:u.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 u=d.endChar-d.startChar;(s===null||u<s.size)&&(s={id:a,size:u,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=v.common.getSelected(),s=n instanceof v.BlockSvg&&n.workspace===t?n:null;v.Events.setGroup(!0);try{const r=t.newBlock(be(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"),v.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{v.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 v.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 v.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 d=v.Connection.getConnectionForOrphanedConnection(e,c.outputConnection);d?d.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=v.Events.disable!==void 0;n&&v.Events.disable();try{let s=20;for(const r of t){const c=e.getBlockById(r);c&&(c.moveTo(new v.utils.Coordinate(20,s)),s+=c.getHeightWidth().height+20)}}finally{n&&v.Events.enable()}v.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:[]}:Xo(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]?ms(e[0],this.elementTypes):void 0)??Object.keys(this.elementTypes).find(n=>ge(this.elementTypes[n])==="code")??"default"}addView(e){var l,u,h,f;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 Fo(e.container,this.workspace,()=>this.generateElementText(c.element),{theme:e.theme,highlightRules:this.highlightRulesFor(e.element),...t?{onDelete:(p,m)=>this.deleteBlockAtCodespaceLine(n,p,m),onLineSelection:()=>this.refreshToolbars(c.name),deleteButtons:(l=e.delete)==null?void 0:l.lineButtons,deleteKeys:(u=e.delete)==null?void 0:u.keys,canDragBlock:p=>this.canMoveInCodespace(p),onBlockGrab:(p,m,E)=>{var g;return(g=this.codeGrabbers.get(n))==null?void 0:g(p,m,E)},onPlaceholderApply:(p,m)=>this.applyPlaceholderEdit(p,m,c),onValueApply:(p,m)=>this.typeValue(c,{block:p.parentBlockId,slot:p.inputName},m),...((h=e.delete)==null?void 0:h.values)!==!1?{onValueRemove:p=>this.removeValue(p)}:{},onRepeat:(p,m,E)=>{var w;const g=(w=this.workspace)==null?void 0:w.getBlockById(p);g&&this.changeRepeat(g,m,E)}}:{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"),ft(c.container,{name:r,element:c.element,classNames:s}),pt(c.container,(f=this.activePreset)==null?void 0:f.name);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(()=>{if(this.views.has(c)){if(t&&this.workspace)c.teardown=this.attachCodespaceDropTarget(n,c.container,this.workspace,()=>c.element);else{const p={element:c.container,preview:()=>this.tileTextLook(c.container,c.element),takes:()=>!1,drop:()=>{}};this.tileDropTargets.add(p),c.teardown=()=>this.tileDropTargets.delete(p)}this.linkAddedView()}}),getElement:()=>c.element,show:p=>{if(this.views.has(c)){this.checkViewElement("show",p),c.element=p,ft(c.container,{name:r,element:p,classNames:s}),n.setHighlightRules(this.highlightRulesFor(p)),n.refresh();for(const m of this.toolbars)m.refresh()}},setTheme:p=>n.setTheme(p),dispose:()=>{var p;this.views.delete(c)&&(a==null||a.dispose(),(p=c.teardown)==null||p.call(c),n.dispose(),this.refreshSelectionSync())}};return c.show=d.show,d}addWorkspaceView(e){var H;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=v.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}});po(c),r&&Nn(c,x=>this.typedValueTaker(x,()=>a)),Fe.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),pt(a.container,(H=this.activePreset)==null?void 0:H.name);const d=()=>{const{scrollX:x,scrollY:M,scale:L}=c;v.Events.disable();try{v.serialization.workspaces.load(Bn(t),c)}finally{v.Events.enable()}this.renderWorkspaceView(a),c.scale!==L&&c.setScale(L),c.scroll(x,M)};d();let l=null,u=!1;const h=()=>{var x;for(const M of c.getAllBlocks(!1))M.unselect();(x=c.getBlockById(l??""))==null||x.select()},f=x=>{if(x.workspaceId!==t.id)return;if(x.type===v.Events.SELECTED){l=x.newElementId??null,h();return}if(x.isUiEvent||u)return;u=!0;const M=()=>{if(this.views.has(a)){if(r&&(c.isDragging()||v.WidgetDiv.isVisible()||v.DropDownDiv.isVisible())){setTimeout(M,100);return}u=!1,d(),h()}};setTimeout(M,0)};t.addChangeListener(f);const p=x=>{if(x.isUiEvent||x.workspaceId!==c.id)return;const M=v.Events.getGroup();v.Events.setGroup(x.group||M||!0);try{v.Events.fromJson(x.toJson(),t).run(!0)}catch{}finally{v.Events.setGroup(M)}},m=this.attachWorkspaceTileDrop(c,e.container);r&&(c.addChangeListener(p),c.undo=x=>t.undo(x));const E=x=>{var A;const M=x.target,L=(A=M==null?void 0:M.closest)==null?void 0:A.call(M,"[data-id]");let V=L?t.getBlockById(L.getAttribute("data-id")??""):null;for(;V!=null&&V.isShadow();)V=V.getParent();V?v.common.setSelected(V):M!=null&&M.classList.contains("blocklyMainBackground")&&v.common.setSelected(null)};e.container.addEventListener("click",E);const g=typeof ResizeObserver<"u"?new ResizeObserver(()=>v.svgResize(c)):void 0;g==null||g.observe(e.container);const w=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),m(),e.container.removeEventListener("click",E),g==null||g.disconnect(),w==null||w.dispose()};const $={kind:"workspace",name:n,ready:Promise.resolve(),getElement:()=>a.element,show:x=>{if(this.views.has(a)){this.checkViewElement("show",x),a.element=x,this.viewWorkspaceElements.set(c,x),this.styleWorkspaceView(a),this.renderWorkspaceView(a);for(const M of this.toolbars)M.refresh()}},setTheme:()=>{},dispose:()=>{this.views.delete(a)&&this.disposeView(a)}};return a.show=$.show,$}styleWorkspaceView(e){e.workspace&&(ft(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;v.Events.disable();try{for(const n of((t=e.workspace)==null?void 0:t.getAllBlocks(!1))??[]){const s=this.definitions.get(me(n.type));s&&this.applyView(n,s,e.element,"workspace")}}finally{v.Events.enable()}}attachWorkspaceTileDrop(e,t){const n=In(t,e,()=>this.workspace,s=>be(s,this.definitions));return this.tileDropTargets.add(n),()=>{var s;(s=n.leave)==null||s.call(n),this.tileDropTargets.delete(n)}}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(ge(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,n){var d,l,u;if(!this.workspace)return!0;let s=this.workspace.getBlockById(e.blockId);if(!s)return!0;if(e.value&&n&&e.fieldType!=="text"){const h=t.trim(),f=((d=e.options)==null?void 0:d.find(([E])=>E===h))??((l=e.options)==null?void 0:l.find(([,E])=>E===h)),m=(e.fieldType==="number"?Dn.test(h):f!==void 0)?void 0:this.valuePlaceOf(s);if(m)return this.typeValue(n,m,t);t=f?f[1]:h}if(s.isShadow()){const h=(u=s.outputConnection)==null?void 0:u.targetConnection;if(h){const f=this.workspace.newBlock(s.type);for(const p of s.inputList)for(const m of p.fieldRow){if(!m.name)continue;const E=f.getField(m.name);E&&E.setValue(m.getValue())}s.rendered&&(f.initSvg(),f.render()),h.connect(f.outputConnection),s=f}}const r=s.getField(e.fieldName);if(!r)return!0;r.setValue(t);const c=s;c.rendered&&typeof c.render=="function"&&c.render();const a=s.getParent();if(a){const h=a;h.rendered&&typeof h.render=="function"&&h.render()}return!0}valuePlaceOf(e){var s;const t=(s=e.outputConnection)==null?void 0:s.targetConnection,n=t==null?void 0:t.getParentInput();return t&&n?{block:t.getSourceBlock().id,slot:n.name}:e.outputConnection?{block:e.id}:void 0}removeValue(e){var s;const t=(s=this.workspace)==null?void 0:s.getBlockById(e.blockId);if(!(t!=null&&t.outputConnection)||t.isShadow()||!t.isDeletable())return!1;const n=v.Events.getGroup();n||v.Events.setGroup(!0);try{t.dispose(!1)}finally{n||v.Events.setGroup(!1)}return!0}typeValue(e,t,n,s=!1,r=!1){var d,l,u;const c=(d=this.workspace)==null?void 0:d.getBlockById(t.block);if(!c||(t.slot===void 0?!c.outputConnection:!c.getInput(t.slot)))return!0;let a=this.readValueText(n,{element:e.element,...t},s);if(!a.ok&&a.reason!=="wrong-slot"&&r)for(const h of Object.keys(this.elementTypes)){if(h===e.element||ge(this.elementTypes[h])!=="code")continue;const f=this.readValueText(n,{element:h,...t},s);if(f.ok){a=f;break}a.reason==="no-block"&&f.reason!=="no-block"&&(a=f)}return a.ok?!0:((u=(l=this.mountConfig)==null?void 0:l.onValueRejected)==null||u.call(l,{view:e.name,text:n,reason:a.reason,...a.name!==void 0?{name:a.name}:{},message:a.message}),!1)}typedValueTaker(e,t){const n=e.getSourceBlock(),s=t();if(!n||!s||n.inputList.flatMap(a=>a.fieldRow).filter(a=>a.name).length!==1||n.inputList.some(a=>a.connection))return;const c=this.valuePlaceOf(n);return c&&((a,d)=>this.typeValue(s,c,a,d,!0))}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 d=this.blockOwningLine(e,a);d&&s.add(d)}const r=a=>{for(let d=a.getSurroundParent();d;d=d.getSurroundParent())if(s.has(d))return!0;return!1},c=[...s].filter(a=>!r(a));if(c.length!==0){v.Events.setGroup(!0);try{for(const a of c)a.dispose(!0)}finally{v.Events.setGroup(!1)}}}blockOwningLine(e,t){const n=e.metadata;if(!this.workspace||!n||n.size===0)return null;const s=a=>{let d=0;for(let l=a.getParent();l;l=l.getParent())d++;return d},r=[];for(const[a,{startLine:d,endLine:l}]of n){if(t<d||t>l)continue;const u=this.workspace.getBlockById(a);!u||u.isShadow()||!(u.previousConnection||u.nextConnection)&&u.getParent()||r.push({block:u,startLine:d,size:l-d,depth:s(u)})}const c=a=>{var d;return((d=a.sort((l,u)=>l.size-u.size||u.depth-l.depth)[0])==null?void 0:d.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 Es(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=xe(e.identifier);if(Ue.set(t,this),this.registeredBlockTypes.has(t))continue;const n=e.identifier;v.Blocks[t]={init(){const s=Fe.get(this.workspace)??Ue.get(t);s==null||s.initManagedBlock(this,n)},saveExtraState(){const s=Fe.get(this.workspace)??Ue.get(t),r=s==null?void 0:s.definitions.get(n),c=r?It(this,r):null,a=li(this);return c||a?{...c,...a?{defaults:a}:{}}:null},loadExtraState(s){const r=Fe.get(this.workspace)??Ue.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=v.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 l,u;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),pr(e);const a=Xe(this.behaviors[n.identifier]),d=s==="workspace"?Uo(n,r,this.elementTypes).elementName:Qe(n,r,this.elementTypes,((l=this.mountConfig)==null?void 0:l.modes)??[]).elementName;(u=a==null?void 0:a.init)==null||u.call(a,e,this.createBehaviorContext(e,n,d??r,s,r))}loadBlockState(e,t,n){var c,a;const s=We(t);v.Events.disable();try{di(e,n==null?void 0:n.defaults)}finally{v.Events.enable()}e.__morphicFresh=!1;const r=new Map([...s].map(([d,l])=>[d,Me(e,d,l)]));if(qn(e,t,n)){v.Events.disable();try{for(const[d,l]of s)for(let u=Me(e,d,l);u<(r.get(d)??0);u++){const h=(a=(c=e.getInput(Be(d,u)))==null?void 0:c.connection)==null?void 0:a.targetBlock();h&&this.isSlotDefault(e,l,h)&&h.dispose(!1)}}finally{v.Events.enable()}this.rebuildBlock(e)}}isSlotDefault(e,t,n){const s=ro(t,this.elementTypes[So(e)??""]);return!n.isShadow()&&!!(s!=null&&s.placeholder)&&n.type===be(s.placeholder,this.definitions)}rebuildBlock(e){const t=this.definitions.get(me(e.type));if(!t)return;const n=e.workspace.isFlyout?"toolbox":"workspace",s=this.viewWorkspaceElements.get(e.workspace)??this.resolveMode(n);v.Events.disable();try{this.applyView(e,t,s,n)}finally{v.Events.enable()}}changeRepeat(e,t,n){var l,u;const s=this.definitions.get(me(e.type)),r=s?We(s).get(t):void 0;if(!s||!r)return;const c=Me(e,t,r),a=Math.max(0,c+n);if(a===c)return;const d=v.Events.getGroup();d||v.Events.setGroup(!0);try{const h=JSON.stringify(It(e,s));for(let p=a;p<c;p++){const m=(u=(l=e.getInput(Be(t,p)))==null?void 0:l.connection)==null?void 0:u.targetBlock();if(!m||m.isShadow())continue;const E=this.isSlotDefault(e,r,m);m.unplug(),E&&m.dispose(!1)}for(let p=c;p<a;p++)ui(e,Be(t,p));ao(e,t,a),this.rebuildBlock(e);const f=v.Events.get(v.Events.BLOCK_CHANGE);v.Events.fire(new f(e,"mutation",null,h,JSON.stringify(It(e,s))))}finally{d||v.Events.setGroup(!1)}}validateViews(e,t){Fn(pn(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 u,h;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 Bi(e))c.set(f,p);const a=s==="workspace"?Uo(t,n,this.elementTypes):Qe(t,n,this.elementTypes,((u=this.mountConfig)==null?void 0:u.modes)??[]),d=e.workspace===this.workspace;Co({block:e,definition:t,view:a,mode:n,context:s,elementTypes:d?this.elementTypes:void 0,codeSettings:this.elementTypes,resolveBlocklyType:f=>be(f,this.definitions),onRepeat:s==="workspace"&&!e.workspace.options.readOnly?(f,p)=>this.changeRepeat(e,f,p):void 0}),this.styleBlock(e,t);const l=Xe(this.behaviors[t.identifier]);(h=l==null?void 0:l.onViewApplied)==null||h.call(l,e,this.createBehaviorContext(e,t,a.elementName??n,s,n)),s==="workspace"&&Li(e,t,a.elementName),Ii(e,c)}styleBlock(e,t){const n=this.blockCategoryIndex.get(t.identifier);hi(e,n==null?void 0:n.token),fi(e,t.identifier),pi(e),t.color!==void 0&&(e.setColour(t.color),Dt(e)&&e.render())}applyWorkspaceContainerClass(){var s,r;if(!this.mountConfig)return;const e=this.mountConfig.workspaceHost,t=this.mountConfig.programView;ft(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=ln(t,[[e.getRenderer().getClassName(),this.baseTheme.getClassName()]],this.baseFont);dn(e,this.baseTheme,this.baseFont,n)&&Gt(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&&(Eo(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&&(Eo(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(me(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(me(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,Fe.set(e,this),this.flyoutWorkspace.addChangeListener(this.onFlyoutChange),this.applyFlyoutClass())}resolveAssetUrls(e){for(const[t,n]of this.loadedDefinitions)this.definitions.set(t,e?Ys(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),d=a?{...c,kind:a}:c,l=d.kind??((r=d.categories)!=null&&r.length?"categoryToolbox":"flyoutToolbox");return!this.categoriesShown&&l==="flyoutToolbox"?Qt({...d,categories:void 0},this.definitions):Qt(d,this.definitions)}const n=e.blockly;if(n!=null&&n.toolbox)return n.toolbox;const s=this.resolveToolboxKind(e.toolboxLayout);return Qt({...s!==void 0?{kind:s}:{},blocks:[...this.definitions.keys()]},this.definitions)}createBehaviorContext(e,t,n,s,r){return{Blockly:v,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 d=pe(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(me(r.type));c&&this.applyView(r,c,t,n)})}}function gr(i,o,e){return Math.min(Math.max(i,o),e)}function vr(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,d=()=>{const w=e.getBoundingClientRect();return t==="x"?w.width:w.height},l=w=>i.setAttribute("aria-valuenow",String(Math.round(w)));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),l(d());const u=w=>{const $=getComputedStyle(e);if($.boxSizing==="border-box")return w;const x=(t==="x"?["Left","Right"]:["Top","Bottom"]).reduce((M,L)=>M+(Number.parseFloat($[`padding${L}`])||0)+(Number.parseFloat($[`border${L}Width`])||0),0);return Math.max(0,w-x)},h=w=>{const $=gr(w,r,c);e.style.flexBasis=`${u($)}px`,l($),s==null||s($)},f=w=>{if(w.button!==0)return;w.preventDefault();const $=d(),H=t==="x"?w.clientX:w.clientY,x=document.body.style.userSelect,M=document.body.style.cursor;document.body.style.userSelect="none",document.body.style.cursor=t==="x"?"col-resize":"row-resize",i.setPointerCapture(w.pointerId);const L=A=>{const J=(t==="x"?A.clientX:A.clientY)-H;h($+(n?-J:J))},V=()=>{i.removeEventListener("pointermove",L),i.removeEventListener("pointerup",V),i.removeEventListener("lostpointercapture",V),document.body.style.userSelect=x,document.body.style.cursor=M};i.addEventListener("pointermove",L),i.addEventListener("pointerup",V),i.addEventListener("lostpointercapture",V)},[p,m]=t==="x"?["ArrowLeft","ArrowRight"]:["ArrowUp","ArrowDown"],E=w=>{const $=w.shiftKey?a*5:a;if(w.key===p||w.key===m){const H=w.key===m?$:-$;h(d()+(n?-H:H))}else if(w.key==="Home")h(r);else if(w.key==="End"&&Number.isFinite(c))h(c);else return;w.preventDefault()};i.hasAttribute("tabindex")||(i.tabIndex=0);const g=()=>l(d());return i.addEventListener("pointerdown",f),i.addEventListener("keydown",E),i.addEventListener("focus",g),{dispose:()=>{i.removeEventListener("pointerdown",f),i.removeEventListener("keydown",E),i.removeEventListener("focus",g)}}}const kr=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"})),wr=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"}));fe.MorphicBlocks=mr,fe.MorphicToolboxCanvas=On,fe.checkDefinitions=Os,fe.makeResizable=vr,fe.renderToolbar=Pn,fe.resolveBlockSets=Ut,fe.toClassToken=pe,fe.toCleanId=me,fe.toolbarItems=he,fe.validateDefinitions=Xt,Object.defineProperty(fe,Symbol.toStringTag,{value:"Module"})}));