morphic-blocks 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -56,6 +56,37 @@ engine.mount({
56
56
  engine.applyPreset("python");
57
57
  ```
58
58
 
59
+ ## Serve Blockly's media yourself
60
+
61
+ By default Blockly loads its images and sounds from Google's server
62
+ (`blockly-demo.appspot.com`), so every visitor's browser contacts it. To keep
63
+ all requests on your own site, copy Blockly's `media` folder into your static
64
+ files before `dev` and `build`:
65
+
66
+ ```js
67
+ // scripts/copy-blockly-media.mjs
68
+ import { cpSync } from "node:fs";
69
+ import { createRequire } from "node:module";
70
+ import { dirname, join } from "node:path";
71
+
72
+ // Blockly comes with morphic-blocks, so look it up from there.
73
+ const require = createRequire(import.meta.url);
74
+ const blockly = dirname(require.resolve("blockly", { paths: [dirname(require.resolve("morphic-blocks"))] }));
75
+ cpSync(join(blockly, "media"), "public/blockly-media", { recursive: true });
76
+ ```
77
+
78
+ Then point Blockly at the copy:
79
+
80
+ ```ts
81
+ engine.mount({
82
+ workspaceContainer: document.getElementById("workspace")!,
83
+ blockly: { media: "blockly-media/" },
84
+ });
85
+ ```
86
+
87
+ This works with every package manager. `public/` is Vite's folder for static
88
+ files; use your bundler's equivalent.
89
+
59
90
  ## Features
60
91
 
61
92
  - **One definition, many representations** — define a block once; render it as
@@ -64,6 +95,9 @@ engine.applyPreset("python");
64
95
  mode. No per-representation duplication.
65
96
  - **Headless & embeddable** — bring your own UI; the framework stays unstyled.
66
97
  - **Built on Blockly** — the proven engine stays authoritative underneath.
98
+ - **No external requests.** The framework never contacts another server, so
99
+ your site decides every request its visitors make. Blockly's own media is
100
+ the one exception, and you can [serve it yourself](#serve-blocklys-media-yourself).
67
101
 
68
102
  ## Documentation
69
103
 
@@ -2214,10 +2214,22 @@ class Lo {
2214
2214
  }), s;
2215
2215
  }
2216
2216
  ensurePreviewWorkspace() {
2217
- var t;
2218
- return this.previewWorkspace ? this.previewWorkspace : (this.previewContainer = document.createElement("div"), this.previewContainer.style.cssText = "position:absolute;left:-9999px;top:-9999px;width:800px;height:600px;overflow:hidden;", document.body.appendChild(this.previewContainer), this.previewWorkspace = B.inject(this.previewContainer, {
2219
- scrollbars: !1
2220
- }), (t = this.onPreviewWorkspace) == null || t.call(this, this.previewWorkspace), this.previewWorkspace);
2217
+ var e;
2218
+ if (this.previewWorkspace) return this.previewWorkspace;
2219
+ 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);
2220
+ const t = this.workspace.options;
2221
+ return this.previewWorkspace = B.inject(this.previewContainer, {
2222
+ scrollbars: !1,
2223
+ // Load media from wherever the host's workspace does, never from
2224
+ // Blockly's default server. Nothing plays here, so no sounds at all.
2225
+ media: t.pathToMedia,
2226
+ sounds: !1,
2227
+ // Draw tiles the way the host's workspace draws its blocks.
2228
+ renderer: t.renderer,
2229
+ rendererOverrides: t.rendererOverrides ?? void 0,
2230
+ theme: t.theme,
2231
+ rtl: t.RTL
2232
+ }), (e = this.onPreviewWorkspace) == null || e.call(this, this.previewWorkspace), this.previewWorkspace;
2221
2233
  }
2222
2234
  /**
2223
2235
  * The tile shows a copy of the rendered block outside Blockly, so its text
@@ -23,7 +23,7 @@ ${u}${qt}${c.id}${He}
23
23
  ${t.family}
24
24
  ${t.size}
25
25
  ${t.weight}`;let o=xe.get(e);if(!o){const i=`${n.name}-morphic-font-${xe.size+1}`;o=L.Theme.defineTheme(i,{name:i,base:n,fontStyle:{family:t.family,size:t.size,weight:t.weight},...n.startHats!==void 0&&{startHats:n.startHats}}),xe.set(e,o)}return o}function Ye(n,t,e,o){const i=So(o,e)?t:xo(t,o);return n.getTheme()===i?!1:(n.setTheme(i),!0)}function Je(n){for(const t of n.getAllBlocks(!1)){t.markDirty();for(const e of t.inputList)for(const o of e.fieldRow)o.getConstants()}n.render()}function qe(n){var m,p,y,S;const{definitions:t,elementTypes:e,behaviors:o,modes:i,presets:s,highlighting:r,categories:c}=n,a=[],l=[],d=new Set(Object.keys(e)),u=new Set(Object.keys(e).filter(h=>U(e[h])==="code")),w=new Set((c??[]).map(h=>h.name));d.has(pe)&&a.push(`elementTypes declares "${pe}", which is reserved for a block's fallback template. Rename the element.`);const v=h=>t.has(h)||L.Blocks[h]!==void 0;for(const h of t.values()){const f=h.identifier;if(h.shape!==void 0)if(!Ue.includes(h.shape))a.push(`Block "${f}": unknown shape "${h.shape}". Use one of: ${Ue.join(", ")}.`);else{const T=N=>N!==void 0&&N!==!1,M=[];T(h.output)&&M.push("it also has an output, which makes it a value block"),(h.shape==="start"||h.shape==="standalone")&&T(h.previousStatement)&&M.push("it also connects above (previousStatement)"),(h.shape==="end"||h.shape==="standalone")&&T(h.nextStatement)&&M.push("it also connects below (nextStatement)"),h.shape==="statement"&&(h.previousStatement===!1||h.nextStatement===!1)&&M.push("a connection flag is set to false");for(const N of M)l.push(`Block "${f}": shape "${h.shape}" contradicts its flags: ${N}. The flags win.`)}const x=te(o[f]),B=!!(x!=null&&x.onViewApplied);for(const T of Object.keys(h.elements))d.has(T)||l.push(`Block "${f}": element "${T}" is not declared in elementTypes — it renders with no known type.`);const b=new Map,I=new Set,D=new Set;for(const[T,M]of Object.entries(h.elements)){if(!u.has(T))continue;const N=new Set;for(const F of q(M))F.kind==="placeholder"?(N.add(F.index),I.add(F.index)):F.kind==="field"&&D.add(F.name);b.set(T,N)}const j=[...b.entries()];if(j.length>1){const[T,M]=j[0];for(const[N,F]of j.slice(1))To(M,F)||a.push(`Block "${f}": code elements "${T}" and "${N}" use different placeholders (${tt(M)} vs ${tt(F)}). All code elements must share the same %N set, or an input disappears when switching to the differing mode.`)}const $=new Set(Object.keys(h.inputSlots??{}).map(T=>Number(T)).filter(T=>Number.isInteger(T)));for(const T of I)(m=h.inputSlots)!=null&&m[String(T)]||l.push(`Block "${f}": placeholder %${T} has no inputSlots["${T}"] entry — the input is auto-named ARG${T} and can't be read by name in behaviors.`);for(const T of $)I.has(T)||l.push(`Block "${f}": inputSlots["${T}"] has no matching %${T} placeholder in any code element — the config is ignored.`);const V=new Set(Object.keys(h.fields??{}));for(const T of D)!((p=h.fields)!=null&&p[T])&&!B&&a.push(`Block "${f}": field token %${T} has no fields["${T}"] entry and the block has no onViewApplied behavior to create it — the field will never appear.`);for(const T of V)D.has(T)||l.push(`Block "${f}": fields["${T}"] has no matching %${T} token in any code element — the config is ignored.`);for(const[T,M]of Object.entries(h.fields??{}))if((M==null?void 0:M.type)==="dropdown"){for(const N of M.options)if(!(typeof N!="object"||Array.isArray(N)||!N.display))for(const F of Object.keys(N.display))u.has(F)||l.push(`Block "${f}": fields["${T}"] option "${N.value}" has display for "${F}", which is not a code element — that entry never applies.`)}h.category!==void 0&&w.size>0&&!w.has(h.category)&&l.push(`Block "${f}": category "${h.category}" is not declared in categories — the block loses its colour and grouping.`);for(const[T,M]of Object.entries(h.inputSlots??{}))(M==null?void 0:M.kind)!==void 0&&!Qe.includes(M.kind)&&a.push(`Block "${f}": inputSlots["${T}"] has unknown kind "${M.kind}". Use one of: ${Qe.join(", ")}.`);for(const[T,M]of Object.entries(h.fields??{}))et.includes(M==null?void 0:M.type)||a.push(`Block "${f}": fields["${T}"] has unknown type "${M==null?void 0:M.type}". Use one of: ${et.join(", ")}.`);for(const[T,M]of Object.entries(h.inputSlots??{}))k((y=M==null?void 0:M.default)==null?void 0:y.shadow,`Block "${f}": inputSlots["${T}"].default.shadow`),k((S=M==null?void 0:M.default)==null?void 0:S.placeholder,`Block "${f}": inputSlots["${T}"].default.placeholder`)}for(const[h,f]of Object.entries(e)){const x=U(f);Ze.includes(x)||a.push(`elementTypes."${h}": unknown type "${x}". Use one of: ${Ze.join(", ")}.`)}for(const[h,f]of Object.entries(e)){if(typeof f=="string")continue;const x=f.empty;if(x)for(const[B,b]of Object.entries(x))k(b.shadow,`elementTypes.${h}.empty.${B}.shadow`),k(b.placeholder,`elementTypes.${h}.empty.${B}.placeholder`)}for(const[h,f]of Object.entries(e)){if(typeof f=="string")continue;const x=f.type;f.size!==void 0&&x!=="image"&&l.push(`elementTypes."${h}": "size" applies only to image elements — ignored for a ${x} element.`),f.stringQuote!==void 0&&x!=="code"&&l.push(`elementTypes."${h}": "stringQuote" applies only to code elements — ignored for a ${x} element.`),f.empty!==void 0&&x!=="code"&&l.push(`elementTypes."${h}": "empty" applies only to code elements — ignored for a ${x} element.`)}for(const h of i??[])for(const f of h.elements)d.has(f)||l.push(`Mode "${h.name}": element "${f}" is not declared in elementTypes — it renders nothing.`);for(const h of Object.keys(r??{}))u.has(h)||l.push(`highlighting["${h}"] is not a code element — its rules will never apply.`);const C=new Map,E=(h,f)=>{const x=C.get(h)??new Set;x.add(f),C.set(h,x)};for(const h of d)E(h,"element");for(const h of i??[])E(h.name,"mode");for(const h of s??[])E(h.name,"preset");for(const[h,f]of C)f.size>1&&l.push(`Name "${h}" is used as ${[...f].sort().join(" and ")} — reusing a name across element / mode / preset is allowed but confusing; consider distinct names.`);return{errors:a,warnings:l};function k(h,f){!h||v(h)||a.push(`${f}: "${h}" is neither a defined block nor a registered Blockly block type.`)}}const Ze=["text","code","image"],Qe=["value","statement"],et=["dropdown","text","number","checkbox"];function To(n,t){if(n.size!==t.size)return!1;for(const e of n)if(!t.has(e))return!1;return!0}function tt(n){const t=[...n].sort((e,o)=>e-o);return t.length?t.map(e=>`%${e}`).join(" "):"(none)"}class Lo{ensureModeVisibilityStyles(t){const e=['[class^="morphic-element-"] { display: none; }'];for(const o of t){const i=H(o.name);for(const s of o.elements){const r=H(s);e.push(`.morphic-mode-${i} > .morphic-element-${r} { display: block; }`)}}fe("mode-visibility",e.join(`
26
- `))}ensureStyles(t,e){this.ensureStyleBundle(t,"base");for(const o of e)this.ensureStyleBundle(o,`mode:${o.mode}`)}async ensureToolbarStyles(){const t=await Promise.resolve().then(()=>Jo);fe("toolbar",t.default)}ensureCategoryStyles(t){for(const e of t){if(!e.color)continue;const o=H(e.name);fe(`category:${o}`,`.morphic-category-${o} { --morphic-category-color: ${e.color}; }`)}}validateModeCoverage(t,e){const o=new Set(t.map(s=>s.mode)),i=e.filter(s=>!o.has(s));i.length>0&&console.warn(`[MorphicBlocks] Modes without explicit CSS definition: ${i.join(", ")}.`)}ensureStyleBundle(t,e){t&&(t.href&&Bo(e,t.href),t.cssText&&fe(e,t.cssText))}}function fe(n,t){for(const o of Array.from(document.head.querySelectorAll("style[data-morphic-source]")))if(o.dataset.morphicSource===n&&o.textContent===t)return;const e=document.createElement("style");e.dataset.morphicSource=n,e.textContent=t,document.head.appendChild(e)}function Bo(n,t){for(const o of Array.from(document.head.querySelectorAll("link[data-morphic-source]")))if(o.getAttribute("href")===t)return;const e=document.createElement("link");e.rel="stylesheet",e.href=t,e.dataset.morphicSource=n,document.head.appendChild(e)}const ee="morphic/block-type";class ot{constructor(t){g(this,"container");g(this,"workspaceContainer");g(this,"workspace");g(this,"definitions");g(this,"blockColors");g(this,"behaviors");g(this,"elementTypes");g(this,"options");g(this,"modes");g(this,"currentMode");g(this,"renderOverride");g(this,"previewWorkspace");g(this,"onPreviewWorkspace");g(this,"previewContainer");g(this,"previewBase");g(this,"onDragOver");g(this,"onDrop");this.container=t.container,this.workspaceContainer=t.workspaceContainer,this.workspace=t.workspace,this.onPreviewWorkspace=t.onPreviewWorkspace,this.definitions=t.definitions,this.blockColors=t.blockColors,this.behaviors=t.behaviors,this.elementTypes=t.elementTypes??{},this.currentMode=t.mode,this.renderOverride=t.render,this.modes=t.modes??[],this.options=t.options??{},this.onDragOver=e=>{var o;(o=e.dataTransfer)!=null&&o.types.includes(ee)&&e.preventDefault()},this.onDrop=e=>{var i;const o=(i=e.dataTransfer)==null?void 0:i.getData(ee);o&&(e.preventDefault(),this.createBlockAtPosition(o,e.clientX,e.clientY))},this.workspaceContainer.addEventListener("dragover",this.onDragOver),this.workspaceContainer.addEventListener("drop",this.onDrop),this.render()}rerender(t,e){this.currentMode=t,this.renderOverride=e,this.render()}dispose(){var t;this.workspaceContainer.removeEventListener("dragover",this.onDragOver),this.workspaceContainer.removeEventListener("drop",this.onDrop),this.container.innerHTML="",this.previewWorkspace&&(this.previewWorkspace.dispose(),this.previewWorkspace=void 0,this.previewBase=void 0),(t=this.previewContainer)!=null&&t.parentNode&&(this.previewContainer.parentNode.removeChild(this.previewContainer),this.previewContainer=void 0)}render(){if(this.container.innerHTML="",this.options.modeLabel!==!1){const i=document.createElement("div");i.className="morphic-toolbox-header";const s=document.createElement("span");s.className="morphic-toolbar-label",s.textContent=`Mode: ${this.currentMode}`,i.appendChild(s),this.container.appendChild(i)}const t=this.resolveBlockIds(),e=this.options.categories??[];if(e.length===0){for(const i of t){const s=this.definitions.get(i);s&&this.container.appendChild(this.createTile(s))}return}const o=new Set;for(const i of e){const s=this.resolveCategoryBlockIds(i,t);if(s.length===0)continue;const r=document.createElement("div");r.setAttribute("data-category",H(i.name)),i.color&&r.style.setProperty("--morphic-category-color",i.color);for(const c of s){const a=this.definitions.get(c);a&&(r.appendChild(this.createTile(a)),o.add(c))}this.container.appendChild(r)}for(const i of t)if(!o.has(i)){const s=this.definitions.get(i);s&&this.container.appendChild(this.createTile(s))}}createTile(t){var d;const e=H(this.currentMode),o=H(t.identifier),i=this.blockColors.get(t.identifier),s=document.createElement("div");s.setAttribute("draggable","true"),s.setAttribute("data-block-type",t.identifier),s.className=`morphic-block morphic-mode-${e} morphic-block-${o}`,i&&s.style.setProperty("--morphic-block-color",i);const r=this.modes.find(u=>u.name===this.currentMode),c=(r==null?void 0:r.elements)??[],a=Object.entries(t.elements),l=[...c.map(u=>a.find(([w])=>w===u)).filter(u=>u!==void 0),...a.filter(([u])=>!c.includes(u))];for(const[u,w]of l){const v=document.createElement("div");v.className=`morphic-element-${H(u)}`;const C=this.elementTypes[u],E=U(C),k=E==="code",m=E==="image",p=((d=this.renderOverride)==null?void 0:d[u])??(k?"block":"text"),y=m?wt(w,ft(C)):w;if(k&&p==="block"){this.syncPreviewFont(u);const S=this.createBlockPreviewSvg(t,this.currentMode);S?v.appendChild(S):v.innerHTML=Me(q(y))}else v.innerHTML=Me(q(y));s.appendChild(v)}return s.addEventListener("dragstart",u=>{var w;(w=u.dataTransfer)==null||w.setData(ee,t.identifier)}),s}ensurePreviewWorkspace(){var t;return this.previewWorkspace?this.previewWorkspace:(this.previewContainer=document.createElement("div"),this.previewContainer.style.cssText="position:absolute;left:-9999px;top:-9999px;width:800px;height:600px;overflow:hidden;",document.body.appendChild(this.previewContainer),this.previewWorkspace=L.inject(this.previewContainer,{scrollbars:!1}),(t=this.onPreviewWorkspace)==null||t.call(this,this.previewWorkspace),this.previewWorkspace)}syncPreviewFont(t){const e=this.ensurePreviewWorkspace();this.previewBase??(this.previewBase={theme:e.getTheme(),font:Xe(e)});const o=Ke(this.container,[["morphic-block",`morphic-mode-${H(this.currentMode)}`],[`morphic-element-${H(t)}`]],this.previewBase.font);Ye(e,this.previewBase.theme,this.previewBase.font,o)}createBlockPreviewSvg(t,e){var o;try{const i=this.ensurePreviewWorkspace(),s=i.newBlock(G(t.identifier,this.definitions)),r=this.blockColors.get(t.identifier);r&&s.setColour(r);const c=Ee(t,e,this.elementTypes,this.modes);De({block:s,definition:t,view:c,mode:"block",context:"toolbox"});const a=te(this.behaviors[t.identifier]);(o=a==null?void 0:a.onViewApplied)==null||o.call(a,s,{Blockly:L,workspace:i,mode:e,context:"toolbox",definition:t}),s.initSvg(),s.render();const l=s.getSvgRoot();if(!l)return s.dispose(!1),null;const d=l.getBBox(),u=l.cloneNode(!0),w=4,v=document.createElementNS("http://www.w3.org/2000/svg","svg");return v.setAttribute("width",String(Math.ceil(d.width+w*2))),v.setAttribute("height",String(Math.ceil(d.height+w*2))),v.setAttribute("viewBox",`${d.x-w} ${d.y-w} ${d.width+w*2} ${d.height+w*2}`),v.appendChild(u),s.dispose(!1),v}catch{return null}}createBlockAtPosition(t,e,o){const i=this.workspace,s=i.getInjectionDiv().getBoundingClientRect(),r=(e-s.left-i.scrollX)/i.scale,c=(o-s.top-i.scrollY)/i.scale,a=i.newBlock(G(t,this.definitions));a.initSvg(),a.render(),a.moveTo(new L.utils.Coordinate(r,c))}resolveBlockIds(){return this.options.blocks??[...this.definitions.keys()]}resolveCategoryBlockIds(t,e){return t.blocks&&t.blocks.length>0?t.blocks.filter(o=>e.includes(o)):e.filter(o=>{var i,s;return((s=(i=this.definitions.get(o))==null?void 0:i.category)==null?void 0:s.toLowerCase())===t.name.toLowerCase()})}}function Te(n,t){var o;if(n.blocks&&n.blocks.length>0)return n.blocks;const e=[];for(const i of t.values())((o=i.category)==null?void 0:o.toLowerCase())===n.name.toLowerCase()&&e.push(i.identifier);return e}function nt(n,t){var i,s,r;if((n.kind??((i=n.categories)!=null&&i.length?"categoryToolbox":"flyoutToolbox"))==="categoryToolbox")return{kind:"categoryToolbox",contents:(n.categories??[]).map(a=>({kind:"category",name:a.name,colour:a.color,contents:Te(a,t).map(l=>({kind:"block",type:G(l,t)}))}))};if((s=n.categories)!=null&&s.length){const c=n.categories,a=[];return c.forEach((d,u)=>{const w=H(d.name);a.push({kind:"label",id:`morphic-category-${w}`,text:d.name,"web-class":`morphic-flyout-category-label morphic-category-${w}`});for(const v of it(Te(d,t)))a.push({kind:"block",type:G(v,t)});u<c.length-1&&a.push({kind:"sep",gap:14})}),{kind:"flyoutToolbox",contents:a}}return{kind:"flyoutToolbox",contents:(n.blocks??it(((r=n.categories)==null?void 0:r.flatMap(c=>Te(c,t)))??[...t.keys()])).map(c=>({kind:"block",type:G(c,t)}))}}function it(n){return n.filter((t,e,o)=>o.indexOf(t)===e)}const Mo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="4" y="4" width="9" height="10" rx="1.5"/><path d="M3 11V3a1 1 0 0 1 1-1h7"/></svg>',Io='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 3h6v2H5z"/><path d="M4 3H3a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V4a1 1 0 0 0-1-1h-1"/></svg>',Do='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8h7a3 3 0 0 1 0 6H6"/><polyline points="5 5 2 8 5 11"/></svg>',Ao='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M13 8H6a3 3 0 0 0 0 6h4"/><polyline points="11 5 14 8 11 11"/></svg>',Oo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 4 13 4"/><path d="M5 4V3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v1"/><path d="M4 4l1 9a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1l1-9"/></svg>',No='<svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor"><polygon points="4,3 13,8 4,13"/></svg>',$o='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="7" r="4"/><line x1="10" y1="10" x2="14" y2="14"/><line x1="5" y1="7" x2="9" y2="7"/><line x1="7" y1="5" x2="7" y2="9"/></svg>',Po='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="7" r="4"/><line x1="10" y1="10" x2="14" y2="14"/><line x1="5" y1="7" x2="9" y2="7"/></svg>',Ho='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 3 3 6 3"/><polyline points="13 6 13 3 10 3"/><polyline points="3 10 3 13 6 13"/><polyline points="13 10 13 13 10 13"/></svg>',Fo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 2h8l2 2v10H3z"/><rect x="5" y="2" width="6" height="4"/><rect x="5" y="9" width="6" height="4"/></svg>',Ro='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8v5a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V8"/><polyline points="5 5 8 2 11 5"/><line x1="8" y1="2" x2="8" y2="10"/></svg>',_o='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8a5 5 0 1 0 1.5-3.5"/><polyline points="3 2 3 5 6 5"/></svg>',Vo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2 8s2-4 6-4 6 4 6 4-2 4-6 4-6-4-6-4z"/><circle cx="8" cy="8" r="1.5"/></svg>',O={modeLabel(){return{id:"mode-label",render:n=>{const t=document.createElement("span");return t.className="morphic-toolbar-label",t.textContent=zo(n),t}}},copy(){return{id:"copy",label:"Copy",title:"Copy block",icon:Mo,onClick:n=>{n.engine.copyActiveBlock(n.pane)}}},paste(){return{id:"paste",label:"Paste",title:"Paste block",icon:Io,disabled:n=>!n.engine.hasClipboardContents(),onClick:n=>{n.engine.pasteActiveBlock(n.pane)}}},undo(){return{id:"undo",label:"Undo",title:"Undo (block model)",icon:Do,onClick:n=>{var t;(t=n.engine.getWorkspace())==null||t.undo(!1)},disabled:n=>{var t;return!((t=n.engine.getWorkspace())!=null&&t.getUndoStack().length)}}},redo(){return{id:"redo",label:"Redo",title:"Redo (block model)",icon:Ao,onClick:n=>{var t;(t=n.engine.getWorkspace())==null||t.undo(!0)},disabled:n=>{var t;return!((t=n.engine.getWorkspace())!=null&&t.getRedoStack().length)}}},zoomIn(){return{id:"zoom-in",label:"Zoom in",title:"Zoom in",icon:$o,onClick:n=>n.engine.zoomPane(n.pane,"in")}},zoomOut(){return{id:"zoom-out",label:"Zoom out",title:"Zoom out",icon:Po,onClick:n=>n.engine.zoomPane(n.pane,"out")}},zoomFit(){return{id:"zoom-fit",label:"Fit",title:"Reset zoom",icon:Ho,onClick:n=>n.engine.zoomPane(n.pane,"fit")}},clear(){return{id:"clear",label:"Clear",title:"Clear workspace",icon:Oo,onClick:n=>{var t;window.confirm("Clear workspace? This cannot be undone.")&&((t=n.engine.getWorkspace())==null||t.clear())}}},runCode(){return{id:"run",label:"Run",title:"Run generated code",icon:No,onClick:n=>{n.engine.runJavaScript()}}},save(){return{id:"save",label:"Save",title:"Save workspace as JSON",icon:Fo,onClick:n=>{if(!n.engine.getWorkspace())return;const e=n.engine.serializeWorkspace(),o=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),i=URL.createObjectURL(o),s=document.createElement("a");s.href=i,s.download="workspace.json",s.click(),URL.revokeObjectURL(i)}}},load(){return{id:"load",label:"Load",title:"Load workspace JSON",icon:Ro,onClick:n=>{const t=document.createElement("input");t.type="file",t.accept="application/json",t.addEventListener("change",async()=>{var o;const e=(o=t.files)==null?void 0:o[0];if(e)try{const i=await e.text(),s=JSON.parse(i);n.engine.loadWorkspace(s)}catch(i){window.alert(`Load failed: ${i instanceof Error?i.message:String(i)}`)}}),t.click()}}},reset(){return{id:"reset",label:"Reset",title:"Reset workspace",icon:_o,onClick:n=>{var t;window.confirm("Reset workspace to empty? This cannot be undone.")&&((t=n.engine.getWorkspace())==null||t.clear())}}},togglePreview(){return{id:"toggle-preview",label:"Preview",title:"Toggle preview pane",icon:Vo,onClick:()=>{const n=document.querySelector("[data-morphic-preview-host]");n&&(n.hidden=!n.hidden)}}},readOnlyBadge(){return{id:"read-only",align:"right",render:()=>{const n=document.createElement("span");return n.className="morphic-toolbar-badge",n.textContent="read-only",n}}},spacer(){return{id:"spacer",render:()=>{const n=document.createElement("span");return n.className="morphic-toolbar-spacer",n}}},defaultsFor(n){switch(n){case"workspace":case"codespace":return[O.modeLabel(),O.spacer(),O.undo(),O.redo(),O.copy(),O.paste(),O.zoomIn(),O.zoomOut(),O.zoomFit(),O.clear()];case"preview":return[O.modeLabel(),O.spacer(),O.copy(),O.zoomIn(),O.zoomOut(),O.zoomFit(),O.readOnlyBadge()]}}};function zo(n){const t=n.engine,e=n.pane==="workspace"?t.getWorkspaceMode():n.pane==="codespace"?t.getCodespaceMode():t.getPreviewMode();return e?`Mode: ${e}`:""}function st(n,t,e){const o=t.items??O.defaultsFor(t.pane),i=t.display??"icon";n.classList.add("morphic-toolbar"),n.setAttribute("data-morphic-pane",t.pane);const s=document.createElement("div");s.className="morphic-toolbar-left";const r=document.createElement("div");r.className="morphic-toolbar-right";const c=()=>{s.replaceChildren(),r.replaceChildren();let a=!1;for(const l of o){if(l.visible&&!l.visible(e))continue;if(l.id==="spacer"){a=!0;continue}(l.align==="right"||a&&l.align!=="left"?r:s).appendChild(Wo(l,i,e))}};return n.replaceChildren(s,r),c(),{refresh:c,pane:t.pane,dispose:()=>n.replaceChildren()}}function Wo(n,t,e){if(n.render){const i=n.render(e);if(typeof i=="string"){const s=document.createElement("span");return s.className="morphic-toolbar-item",s.dataset.toolbarId=n.id,s.textContent=i,s}return i.classList.add("morphic-toolbar-item"),i.dataset.toolbarId=n.id,i}const o=document.createElement("button");return o.className="morphic-toolbar-item",o.dataset.toolbarId=n.id,o.type="button",n.title&&(o.title=n.title),jo(o,n,t),n.disabled&&n.disabled(e)&&(o.disabled=!0),n.onClick&&o.addEventListener("click",()=>n.onClick(e)),o}function jo(n,t,e){const o=e!=="label"&&!!t.icon,i=e!=="icon"&&!!t.label,s=o||e==="icon"&&!t.label,r=i||e==="label"&&!t.icon;if(s&&t.icon){const c=document.createElement("span");c.className="morphic-toolbar-icon",c.innerHTML=t.icon,n.appendChild(c)}if(r&&t.label){const c=document.createElement("span");c.className="morphic-toolbar-text",c.textContent=t.label,n.appendChild(c)}!n.title&&t.label&&(n.title=t.label),!n.childNodes.length&&t.label&&(n.textContent=t.label)}function rt(n,t){return t.includes("{")?{mode:n,cssText:t}:{mode:n,href:t}}function Uo(n){const t=[];for(const[e,o]of Object.entries(n)){const s=(e.split("/").pop()??e).replace(/\.css$/i,""),r=typeof o=="string"?o:typeof o=="object"&&o!==null&&"default"in o?String(o.default):void 0;r&&t.push(rt(s,r))}return t}function Le(n){return typeof n=="string"?{mode:n}:{mode:n.mode,render:n.render}}const me=new WeakMap,ge=new Map;class Go extends EventTarget{constructor(e,o={}){super();g(this,"definitions");g(this,"behaviors");g(this,"elementTypes");g(this,"styles",new Lo);g(this,"registeredBlockTypes",new Set);g(this,"toolbars",new Set);g(this,"toolbarsBlocklyListener");g(this,"lastCopyData");g(this,"mountConfig");g(this,"workspace");g(this,"flyoutWorkspace");g(this,"toolboxCanvas");g(this,"codeEditor");g(this,"codespace");g(this,"previewEditor");g(this,"selectionSync");g(this,"toolboxDefinition");g(this,"blockCategoryIndex",new Map);g(this,"appliedWorkspaceClasses",[]);g(this,"appliedToolboxFlyoutClasses",[]);g(this,"appliedToolboxShellClasses",[]);g(this,"headlessWorkspaceHost");g(this,"codespaceDropTeardown");g(this,"workspaceResizeObserver");g(this,"activePreset");g(this,"baseTheme");g(this,"baseFont");g(this,"mountGeneration",0);g(this,"selectionSyncOptions");g(this,"formatModes");g(this,"formatPresets");g(this,"formatHighlighting");g(this,"formatCategories");g(this,"onWorkspaceChange",e=>{if(!this.workspace||!this.mountConfig||e.workspaceId!==this.workspace.id||e.type!==L.Events.BLOCK_CREATE)return;const o=e;for(const i of o.ids??[]){const s=this.workspace.getBlockById(i);if(!s)continue;const r=this.definitions.get(W(s.type));r&&(this.applyView(s,r,this.mountConfig.workspaceMode,"workspace"),s.getSvgRoot()||this.deferApplyView(i,this.mountConfig.workspaceMode,"workspace"))}});g(this,"onFlyoutChange",e=>{if(!this.flyoutWorkspace||!this.mountConfig||e.workspaceId!==this.flyoutWorkspace.id||e.type!==L.Events.BLOCK_CREATE)return;const o=e;for(const i of o.ids??[]){const s=this.flyoutWorkspace.getBlockById(i);if(!s)continue;const r=this.definitions.get(W(s.type));r&&(this.applyView(s,r,this.mountConfig.toolboxMode,"toolbox"),s.getSvgRoot()||this.deferApplyView(i,this.mountConfig.toolboxMode,"toolbox"))}});g(this,"onStylesLoaded",()=>{var e;!this.workspace||!this.mountConfig||(this.syncWorkspaceFont(),Je(this.workspace),(e=this.toolboxCanvas)==null||e.rerender(this.mountConfig.toolboxMode,this.mountConfig.toolboxRender))});const i=e;this.definitions=wo(ko(vo(i.blocks,i.elementTypes??{}))),this.behaviors=o,this.elementTypes=i.elementTypes??{},this.formatModes=i.modes,this.formatPresets=i.presets,this.formatHighlighting=i.highlighting,this.formatCategories=i.categories}mount(e){var p,y,S,h,f,x,B;this.dispose();const o={...e,modes:e.modes??this.formatModes,presets:e.presets??this.formatPresets,highlighting:e.highlighting??this.formatHighlighting,toolbox:e.toolbox||this.formatCategories?{...e.toolbox,categories:((p=e.toolbox)==null?void 0:p.categories)??this.formatCategories}:void 0},i=o.modesFolder?Uo(o.modesFolder):[],s=[...i,...Object.entries(o.modeStyles??{}).filter(([b])=>!i.some(I=>I.mode===b)).map(([b,I])=>rt(b,I))];this.validateDefinitions(o),this.validatePresets(o);const r=(y=o.presets)!=null&&y.length?o.presets.find(b=>b.name===o.preset)??o.presets[0]:void 0;if(o.preset&&!r)throw new Error(`MorphicBlocks.mount: unknown preset "${o.preset}".`);const c=(o.modes??[]).map(b=>b.name),a=c[0]??((S=s[0])==null?void 0:S.mode)??"default",l=r?Le(r.toolbox):void 0,d=r?r.workspace??r.codespace??a:a,u=l?l.mode:a,w=l==null?void 0:l.render,v=r==null?void 0:r.codespace,C=r==null?void 0:r.preview;this.validateContainers(o);const E=o.workspaceContainer??this.createHeadlessHost(),k={...o,modeStyles:s,workspaceMode:d,toolboxMode:u,toolboxRender:w,codespaceMode:v,previewMode:C,workspaceHost:E,canvasToolbox:o.canvasToolbox??!!o.toolboxContainer};this.mountConfig=k,this.styles.validateModeCoverage(s,c),(h=k.modes)!=null&&h.length&&this.styles.ensureModeVisibilityStyles(k.modes),this.styles.ensureStyles(k.baseStyle,s);for(const b of Array.from(document.head.querySelectorAll('link[data-morphic-source^="mode:"]')))b.sheet||b.addEventListener("load",this.onStylesLoaded,{once:!0});(f=document.fonts)==null||f.addEventListener("loadingdone",this.onStylesLoaded),this.blockCategoryIndex=this.createCategoryIndex(k.toolbox,k),this.styles.ensureCategoryStyles(((x=k.toolbox)==null?void 0:x.categories)??[]),this.registerBlocks(),this.toolboxDefinition=this.resolveToolboxDefinition(k);const m=k.blockly??{};if(this.workspace=L.inject(k.workspaceHost,{...m,...k.canvasToolbox?{}:{toolbox:this.toolboxDefinition}}),this.workspace.addChangeListener(this.onWorkspaceChange),me.set(this.workspace,this),this.baseTheme=this.workspace.getTheme(),this.baseFont=Xe(this.workspace),o.workspaceContainer&&typeof ResizeObserver<"u"){const b=this.workspace;this.workspaceResizeObserver=new ResizeObserver(()=>L.svgResize(b)),this.workspaceResizeObserver.observe(o.workspaceContainer)}return this.applyWorkspaceContainerClass(),this.syncWorkspaceFont(),this.refreshToolbox(),this.bindFlyoutWorkspace(),this.renderWorkspaceBlocks(),this.renderFlyoutBlocks(),o.toolboxContainer&&this.mountToolbox(o.toolboxContainer),this.activePreset=r,r&&((B=k.onPresetApplied)==null||B.call(k,r)),this.mountViews(o,++this.mountGeneration)}async mountViews(e,o){const i=e.editorTheme?{theme:e.editorTheme}:void 0,s=e.previewTheme??e.editorTheme,r=[];if(e.codespaceContainer&&r.push(this.mountCodespace(i)),e.previewContainer&&r.push(this.mountPreview(e.previewContainer,s?{theme:s}:void 0)),e.codeEditorContainer&&r.push(this.mountCodeEditor(e.codeEditorContainer,i).then(()=>{o===this.mountGeneration&&this.hideCodeEditor()})),await Promise.all(r),o!==this.mountGeneration||!this.workspace)return;for(const[l,d]of Object.entries(e.toolbarContainers??{}))d&&this.mountToolbar(d,{pane:l});const c=(e.workspaceContainer?1:0)+r.length,a=e.selectionSync??c>1;a&&r.length>0&&this.enableSelectionSync(typeof a=="object"?a:void 0)}getPresets(){var e;return[...((e=this.mountConfig)==null?void 0:e.presets)??[]]}getActivePreset(){return this.activePreset}applyPreset(e){var r,c;if(!this.mountConfig||!this.workspace)throw new Error("MorphicBlocks must be mounted before applyPreset can be used.");const o=this.mountConfig.presets??[],i=typeof e=="number"?o[e]:o.find(a=>a.name===e);if(!i)throw new Error(`applyPreset: unknown preset "${e}".`);const s=Le(i.toolbox);return this.setModes({toolboxMode:s.mode,toolboxRender:s.render??null,workspaceMode:i.workspace??i.codespace,codespaceMode:i.codespace??null,previewMode:i.preview??null}),this.activePreset=i,(c=(r=this.mountConfig).onPresetApplied)==null||c.call(r,i),i}validateDefinitions(e){var s;const{errors:o,warnings:i}=qe({definitions:this.definitions,elementTypes:this.elementTypes,behaviors:this.behaviors,modes:e.modes,presets:e.presets,highlighting:e.highlighting,categories:(s=e.toolbox)==null?void 0:s.categories});if(i.length>0&&console.warn(`[MorphicBlocks] Definition warnings:
26
+ `))}ensureStyles(t,e){this.ensureStyleBundle(t,"base");for(const o of e)this.ensureStyleBundle(o,`mode:${o.mode}`)}async ensureToolbarStyles(){const t=await Promise.resolve().then(()=>Jo);fe("toolbar",t.default)}ensureCategoryStyles(t){for(const e of t){if(!e.color)continue;const o=H(e.name);fe(`category:${o}`,`.morphic-category-${o} { --morphic-category-color: ${e.color}; }`)}}validateModeCoverage(t,e){const o=new Set(t.map(s=>s.mode)),i=e.filter(s=>!o.has(s));i.length>0&&console.warn(`[MorphicBlocks] Modes without explicit CSS definition: ${i.join(", ")}.`)}ensureStyleBundle(t,e){t&&(t.href&&Bo(e,t.href),t.cssText&&fe(e,t.cssText))}}function fe(n,t){for(const o of Array.from(document.head.querySelectorAll("style[data-morphic-source]")))if(o.dataset.morphicSource===n&&o.textContent===t)return;const e=document.createElement("style");e.dataset.morphicSource=n,e.textContent=t,document.head.appendChild(e)}function Bo(n,t){for(const o of Array.from(document.head.querySelectorAll("link[data-morphic-source]")))if(o.getAttribute("href")===t)return;const e=document.createElement("link");e.rel="stylesheet",e.href=t,e.dataset.morphicSource=n,document.head.appendChild(e)}const ee="morphic/block-type";class ot{constructor(t){g(this,"container");g(this,"workspaceContainer");g(this,"workspace");g(this,"definitions");g(this,"blockColors");g(this,"behaviors");g(this,"elementTypes");g(this,"options");g(this,"modes");g(this,"currentMode");g(this,"renderOverride");g(this,"previewWorkspace");g(this,"onPreviewWorkspace");g(this,"previewContainer");g(this,"previewBase");g(this,"onDragOver");g(this,"onDrop");this.container=t.container,this.workspaceContainer=t.workspaceContainer,this.workspace=t.workspace,this.onPreviewWorkspace=t.onPreviewWorkspace,this.definitions=t.definitions,this.blockColors=t.blockColors,this.behaviors=t.behaviors,this.elementTypes=t.elementTypes??{},this.currentMode=t.mode,this.renderOverride=t.render,this.modes=t.modes??[],this.options=t.options??{},this.onDragOver=e=>{var o;(o=e.dataTransfer)!=null&&o.types.includes(ee)&&e.preventDefault()},this.onDrop=e=>{var i;const o=(i=e.dataTransfer)==null?void 0:i.getData(ee);o&&(e.preventDefault(),this.createBlockAtPosition(o,e.clientX,e.clientY))},this.workspaceContainer.addEventListener("dragover",this.onDragOver),this.workspaceContainer.addEventListener("drop",this.onDrop),this.render()}rerender(t,e){this.currentMode=t,this.renderOverride=e,this.render()}dispose(){var t;this.workspaceContainer.removeEventListener("dragover",this.onDragOver),this.workspaceContainer.removeEventListener("drop",this.onDrop),this.container.innerHTML="",this.previewWorkspace&&(this.previewWorkspace.dispose(),this.previewWorkspace=void 0,this.previewBase=void 0),(t=this.previewContainer)!=null&&t.parentNode&&(this.previewContainer.parentNode.removeChild(this.previewContainer),this.previewContainer=void 0)}render(){if(this.container.innerHTML="",this.options.modeLabel!==!1){const i=document.createElement("div");i.className="morphic-toolbox-header";const s=document.createElement("span");s.className="morphic-toolbar-label",s.textContent=`Mode: ${this.currentMode}`,i.appendChild(s),this.container.appendChild(i)}const t=this.resolveBlockIds(),e=this.options.categories??[];if(e.length===0){for(const i of t){const s=this.definitions.get(i);s&&this.container.appendChild(this.createTile(s))}return}const o=new Set;for(const i of e){const s=this.resolveCategoryBlockIds(i,t);if(s.length===0)continue;const r=document.createElement("div");r.setAttribute("data-category",H(i.name)),i.color&&r.style.setProperty("--morphic-category-color",i.color);for(const c of s){const a=this.definitions.get(c);a&&(r.appendChild(this.createTile(a)),o.add(c))}this.container.appendChild(r)}for(const i of t)if(!o.has(i)){const s=this.definitions.get(i);s&&this.container.appendChild(this.createTile(s))}}createTile(t){var d;const e=H(this.currentMode),o=H(t.identifier),i=this.blockColors.get(t.identifier),s=document.createElement("div");s.setAttribute("draggable","true"),s.setAttribute("data-block-type",t.identifier),s.className=`morphic-block morphic-mode-${e} morphic-block-${o}`,i&&s.style.setProperty("--morphic-block-color",i);const r=this.modes.find(u=>u.name===this.currentMode),c=(r==null?void 0:r.elements)??[],a=Object.entries(t.elements),l=[...c.map(u=>a.find(([w])=>w===u)).filter(u=>u!==void 0),...a.filter(([u])=>!c.includes(u))];for(const[u,w]of l){const v=document.createElement("div");v.className=`morphic-element-${H(u)}`;const C=this.elementTypes[u],E=U(C),k=E==="code",m=E==="image",p=((d=this.renderOverride)==null?void 0:d[u])??(k?"block":"text"),y=m?wt(w,ft(C)):w;if(k&&p==="block"){this.syncPreviewFont(u);const S=this.createBlockPreviewSvg(t,this.currentMode);S?v.appendChild(S):v.innerHTML=Me(q(y))}else v.innerHTML=Me(q(y));s.appendChild(v)}return s.addEventListener("dragstart",u=>{var w;(w=u.dataTransfer)==null||w.setData(ee,t.identifier)}),s}ensurePreviewWorkspace(){var e;if(this.previewWorkspace)return this.previewWorkspace;this.previewContainer=document.createElement("div"),this.previewContainer.style.cssText="position:absolute;left:-9999px;top:-9999px;width:800px;height:600px;overflow:hidden;",document.body.appendChild(this.previewContainer);const t=this.workspace.options;return this.previewWorkspace=L.inject(this.previewContainer,{scrollbars:!1,media:t.pathToMedia,sounds:!1,renderer:t.renderer,rendererOverrides:t.rendererOverrides??void 0,theme:t.theme,rtl:t.RTL}),(e=this.onPreviewWorkspace)==null||e.call(this,this.previewWorkspace),this.previewWorkspace}syncPreviewFont(t){const e=this.ensurePreviewWorkspace();this.previewBase??(this.previewBase={theme:e.getTheme(),font:Xe(e)});const o=Ke(this.container,[["morphic-block",`morphic-mode-${H(this.currentMode)}`],[`morphic-element-${H(t)}`]],this.previewBase.font);Ye(e,this.previewBase.theme,this.previewBase.font,o)}createBlockPreviewSvg(t,e){var o;try{const i=this.ensurePreviewWorkspace(),s=i.newBlock(G(t.identifier,this.definitions)),r=this.blockColors.get(t.identifier);r&&s.setColour(r);const c=Ee(t,e,this.elementTypes,this.modes);De({block:s,definition:t,view:c,mode:"block",context:"toolbox"});const a=te(this.behaviors[t.identifier]);(o=a==null?void 0:a.onViewApplied)==null||o.call(a,s,{Blockly:L,workspace:i,mode:e,context:"toolbox",definition:t}),s.initSvg(),s.render();const l=s.getSvgRoot();if(!l)return s.dispose(!1),null;const d=l.getBBox(),u=l.cloneNode(!0),w=4,v=document.createElementNS("http://www.w3.org/2000/svg","svg");return v.setAttribute("width",String(Math.ceil(d.width+w*2))),v.setAttribute("height",String(Math.ceil(d.height+w*2))),v.setAttribute("viewBox",`${d.x-w} ${d.y-w} ${d.width+w*2} ${d.height+w*2}`),v.appendChild(u),s.dispose(!1),v}catch{return null}}createBlockAtPosition(t,e,o){const i=this.workspace,s=i.getInjectionDiv().getBoundingClientRect(),r=(e-s.left-i.scrollX)/i.scale,c=(o-s.top-i.scrollY)/i.scale,a=i.newBlock(G(t,this.definitions));a.initSvg(),a.render(),a.moveTo(new L.utils.Coordinate(r,c))}resolveBlockIds(){return this.options.blocks??[...this.definitions.keys()]}resolveCategoryBlockIds(t,e){return t.blocks&&t.blocks.length>0?t.blocks.filter(o=>e.includes(o)):e.filter(o=>{var i,s;return((s=(i=this.definitions.get(o))==null?void 0:i.category)==null?void 0:s.toLowerCase())===t.name.toLowerCase()})}}function Te(n,t){var o;if(n.blocks&&n.blocks.length>0)return n.blocks;const e=[];for(const i of t.values())((o=i.category)==null?void 0:o.toLowerCase())===n.name.toLowerCase()&&e.push(i.identifier);return e}function nt(n,t){var i,s,r;if((n.kind??((i=n.categories)!=null&&i.length?"categoryToolbox":"flyoutToolbox"))==="categoryToolbox")return{kind:"categoryToolbox",contents:(n.categories??[]).map(a=>({kind:"category",name:a.name,colour:a.color,contents:Te(a,t).map(l=>({kind:"block",type:G(l,t)}))}))};if((s=n.categories)!=null&&s.length){const c=n.categories,a=[];return c.forEach((d,u)=>{const w=H(d.name);a.push({kind:"label",id:`morphic-category-${w}`,text:d.name,"web-class":`morphic-flyout-category-label morphic-category-${w}`});for(const v of it(Te(d,t)))a.push({kind:"block",type:G(v,t)});u<c.length-1&&a.push({kind:"sep",gap:14})}),{kind:"flyoutToolbox",contents:a}}return{kind:"flyoutToolbox",contents:(n.blocks??it(((r=n.categories)==null?void 0:r.flatMap(c=>Te(c,t)))??[...t.keys()])).map(c=>({kind:"block",type:G(c,t)}))}}function it(n){return n.filter((t,e,o)=>o.indexOf(t)===e)}const Mo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="4" y="4" width="9" height="10" rx="1.5"/><path d="M3 11V3a1 1 0 0 1 1-1h7"/></svg>',Io='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 3h6v2H5z"/><path d="M4 3H3a1 1 0 0 0-1 1v9a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V4a1 1 0 0 0-1-1h-1"/></svg>',Do='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8h7a3 3 0 0 1 0 6H6"/><polyline points="5 5 2 8 5 11"/></svg>',Ao='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M13 8H6a3 3 0 0 0 0 6h4"/><polyline points="11 5 14 8 11 11"/></svg>',Oo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 4 13 4"/><path d="M5 4V3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v1"/><path d="M4 4l1 9a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1l1-9"/></svg>',No='<svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor"><polygon points="4,3 13,8 4,13"/></svg>',$o='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="7" r="4"/><line x1="10" y1="10" x2="14" y2="14"/><line x1="5" y1="7" x2="9" y2="7"/><line x1="7" y1="5" x2="7" y2="9"/></svg>',Po='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="7" r="4"/><line x1="10" y1="10" x2="14" y2="14"/><line x1="5" y1="7" x2="9" y2="7"/></svg>',Ho='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 3 3 6 3"/><polyline points="13 6 13 3 10 3"/><polyline points="3 10 3 13 6 13"/><polyline points="13 10 13 13 10 13"/></svg>',Fo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 2h8l2 2v10H3z"/><rect x="5" y="2" width="6" height="4"/><rect x="5" y="9" width="6" height="4"/></svg>',Ro='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8v5a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V8"/><polyline points="5 5 8 2 11 5"/><line x1="8" y1="2" x2="8" y2="10"/></svg>',_o='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8a5 5 0 1 0 1.5-3.5"/><polyline points="3 2 3 5 6 5"/></svg>',Vo='<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2 8s2-4 6-4 6 4 6 4-2 4-6 4-6-4-6-4z"/><circle cx="8" cy="8" r="1.5"/></svg>',O={modeLabel(){return{id:"mode-label",render:n=>{const t=document.createElement("span");return t.className="morphic-toolbar-label",t.textContent=zo(n),t}}},copy(){return{id:"copy",label:"Copy",title:"Copy block",icon:Mo,onClick:n=>{n.engine.copyActiveBlock(n.pane)}}},paste(){return{id:"paste",label:"Paste",title:"Paste block",icon:Io,disabled:n=>!n.engine.hasClipboardContents(),onClick:n=>{n.engine.pasteActiveBlock(n.pane)}}},undo(){return{id:"undo",label:"Undo",title:"Undo (block model)",icon:Do,onClick:n=>{var t;(t=n.engine.getWorkspace())==null||t.undo(!1)},disabled:n=>{var t;return!((t=n.engine.getWorkspace())!=null&&t.getUndoStack().length)}}},redo(){return{id:"redo",label:"Redo",title:"Redo (block model)",icon:Ao,onClick:n=>{var t;(t=n.engine.getWorkspace())==null||t.undo(!0)},disabled:n=>{var t;return!((t=n.engine.getWorkspace())!=null&&t.getRedoStack().length)}}},zoomIn(){return{id:"zoom-in",label:"Zoom in",title:"Zoom in",icon:$o,onClick:n=>n.engine.zoomPane(n.pane,"in")}},zoomOut(){return{id:"zoom-out",label:"Zoom out",title:"Zoom out",icon:Po,onClick:n=>n.engine.zoomPane(n.pane,"out")}},zoomFit(){return{id:"zoom-fit",label:"Fit",title:"Reset zoom",icon:Ho,onClick:n=>n.engine.zoomPane(n.pane,"fit")}},clear(){return{id:"clear",label:"Clear",title:"Clear workspace",icon:Oo,onClick:n=>{var t;window.confirm("Clear workspace? This cannot be undone.")&&((t=n.engine.getWorkspace())==null||t.clear())}}},runCode(){return{id:"run",label:"Run",title:"Run generated code",icon:No,onClick:n=>{n.engine.runJavaScript()}}},save(){return{id:"save",label:"Save",title:"Save workspace as JSON",icon:Fo,onClick:n=>{if(!n.engine.getWorkspace())return;const e=n.engine.serializeWorkspace(),o=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),i=URL.createObjectURL(o),s=document.createElement("a");s.href=i,s.download="workspace.json",s.click(),URL.revokeObjectURL(i)}}},load(){return{id:"load",label:"Load",title:"Load workspace JSON",icon:Ro,onClick:n=>{const t=document.createElement("input");t.type="file",t.accept="application/json",t.addEventListener("change",async()=>{var o;const e=(o=t.files)==null?void 0:o[0];if(e)try{const i=await e.text(),s=JSON.parse(i);n.engine.loadWorkspace(s)}catch(i){window.alert(`Load failed: ${i instanceof Error?i.message:String(i)}`)}}),t.click()}}},reset(){return{id:"reset",label:"Reset",title:"Reset workspace",icon:_o,onClick:n=>{var t;window.confirm("Reset workspace to empty? This cannot be undone.")&&((t=n.engine.getWorkspace())==null||t.clear())}}},togglePreview(){return{id:"toggle-preview",label:"Preview",title:"Toggle preview pane",icon:Vo,onClick:()=>{const n=document.querySelector("[data-morphic-preview-host]");n&&(n.hidden=!n.hidden)}}},readOnlyBadge(){return{id:"read-only",align:"right",render:()=>{const n=document.createElement("span");return n.className="morphic-toolbar-badge",n.textContent="read-only",n}}},spacer(){return{id:"spacer",render:()=>{const n=document.createElement("span");return n.className="morphic-toolbar-spacer",n}}},defaultsFor(n){switch(n){case"workspace":case"codespace":return[O.modeLabel(),O.spacer(),O.undo(),O.redo(),O.copy(),O.paste(),O.zoomIn(),O.zoomOut(),O.zoomFit(),O.clear()];case"preview":return[O.modeLabel(),O.spacer(),O.copy(),O.zoomIn(),O.zoomOut(),O.zoomFit(),O.readOnlyBadge()]}}};function zo(n){const t=n.engine,e=n.pane==="workspace"?t.getWorkspaceMode():n.pane==="codespace"?t.getCodespaceMode():t.getPreviewMode();return e?`Mode: ${e}`:""}function st(n,t,e){const o=t.items??O.defaultsFor(t.pane),i=t.display??"icon";n.classList.add("morphic-toolbar"),n.setAttribute("data-morphic-pane",t.pane);const s=document.createElement("div");s.className="morphic-toolbar-left";const r=document.createElement("div");r.className="morphic-toolbar-right";const c=()=>{s.replaceChildren(),r.replaceChildren();let a=!1;for(const l of o){if(l.visible&&!l.visible(e))continue;if(l.id==="spacer"){a=!0;continue}(l.align==="right"||a&&l.align!=="left"?r:s).appendChild(Wo(l,i,e))}};return n.replaceChildren(s,r),c(),{refresh:c,pane:t.pane,dispose:()=>n.replaceChildren()}}function Wo(n,t,e){if(n.render){const i=n.render(e);if(typeof i=="string"){const s=document.createElement("span");return s.className="morphic-toolbar-item",s.dataset.toolbarId=n.id,s.textContent=i,s}return i.classList.add("morphic-toolbar-item"),i.dataset.toolbarId=n.id,i}const o=document.createElement("button");return o.className="morphic-toolbar-item",o.dataset.toolbarId=n.id,o.type="button",n.title&&(o.title=n.title),jo(o,n,t),n.disabled&&n.disabled(e)&&(o.disabled=!0),n.onClick&&o.addEventListener("click",()=>n.onClick(e)),o}function jo(n,t,e){const o=e!=="label"&&!!t.icon,i=e!=="icon"&&!!t.label,s=o||e==="icon"&&!t.label,r=i||e==="label"&&!t.icon;if(s&&t.icon){const c=document.createElement("span");c.className="morphic-toolbar-icon",c.innerHTML=t.icon,n.appendChild(c)}if(r&&t.label){const c=document.createElement("span");c.className="morphic-toolbar-text",c.textContent=t.label,n.appendChild(c)}!n.title&&t.label&&(n.title=t.label),!n.childNodes.length&&t.label&&(n.textContent=t.label)}function rt(n,t){return t.includes("{")?{mode:n,cssText:t}:{mode:n,href:t}}function Uo(n){const t=[];for(const[e,o]of Object.entries(n)){const s=(e.split("/").pop()??e).replace(/\.css$/i,""),r=typeof o=="string"?o:typeof o=="object"&&o!==null&&"default"in o?String(o.default):void 0;r&&t.push(rt(s,r))}return t}function Le(n){return typeof n=="string"?{mode:n}:{mode:n.mode,render:n.render}}const me=new WeakMap,ge=new Map;class Go extends EventTarget{constructor(e,o={}){super();g(this,"definitions");g(this,"behaviors");g(this,"elementTypes");g(this,"styles",new Lo);g(this,"registeredBlockTypes",new Set);g(this,"toolbars",new Set);g(this,"toolbarsBlocklyListener");g(this,"lastCopyData");g(this,"mountConfig");g(this,"workspace");g(this,"flyoutWorkspace");g(this,"toolboxCanvas");g(this,"codeEditor");g(this,"codespace");g(this,"previewEditor");g(this,"selectionSync");g(this,"toolboxDefinition");g(this,"blockCategoryIndex",new Map);g(this,"appliedWorkspaceClasses",[]);g(this,"appliedToolboxFlyoutClasses",[]);g(this,"appliedToolboxShellClasses",[]);g(this,"headlessWorkspaceHost");g(this,"codespaceDropTeardown");g(this,"workspaceResizeObserver");g(this,"activePreset");g(this,"baseTheme");g(this,"baseFont");g(this,"mountGeneration",0);g(this,"selectionSyncOptions");g(this,"formatModes");g(this,"formatPresets");g(this,"formatHighlighting");g(this,"formatCategories");g(this,"onWorkspaceChange",e=>{if(!this.workspace||!this.mountConfig||e.workspaceId!==this.workspace.id||e.type!==L.Events.BLOCK_CREATE)return;const o=e;for(const i of o.ids??[]){const s=this.workspace.getBlockById(i);if(!s)continue;const r=this.definitions.get(W(s.type));r&&(this.applyView(s,r,this.mountConfig.workspaceMode,"workspace"),s.getSvgRoot()||this.deferApplyView(i,this.mountConfig.workspaceMode,"workspace"))}});g(this,"onFlyoutChange",e=>{if(!this.flyoutWorkspace||!this.mountConfig||e.workspaceId!==this.flyoutWorkspace.id||e.type!==L.Events.BLOCK_CREATE)return;const o=e;for(const i of o.ids??[]){const s=this.flyoutWorkspace.getBlockById(i);if(!s)continue;const r=this.definitions.get(W(s.type));r&&(this.applyView(s,r,this.mountConfig.toolboxMode,"toolbox"),s.getSvgRoot()||this.deferApplyView(i,this.mountConfig.toolboxMode,"toolbox"))}});g(this,"onStylesLoaded",()=>{var e;!this.workspace||!this.mountConfig||(this.syncWorkspaceFont(),Je(this.workspace),(e=this.toolboxCanvas)==null||e.rerender(this.mountConfig.toolboxMode,this.mountConfig.toolboxRender))});const i=e;this.definitions=wo(ko(vo(i.blocks,i.elementTypes??{}))),this.behaviors=o,this.elementTypes=i.elementTypes??{},this.formatModes=i.modes,this.formatPresets=i.presets,this.formatHighlighting=i.highlighting,this.formatCategories=i.categories}mount(e){var p,y,S,h,f,x,B;this.dispose();const o={...e,modes:e.modes??this.formatModes,presets:e.presets??this.formatPresets,highlighting:e.highlighting??this.formatHighlighting,toolbox:e.toolbox||this.formatCategories?{...e.toolbox,categories:((p=e.toolbox)==null?void 0:p.categories)??this.formatCategories}:void 0},i=o.modesFolder?Uo(o.modesFolder):[],s=[...i,...Object.entries(o.modeStyles??{}).filter(([b])=>!i.some(I=>I.mode===b)).map(([b,I])=>rt(b,I))];this.validateDefinitions(o),this.validatePresets(o);const r=(y=o.presets)!=null&&y.length?o.presets.find(b=>b.name===o.preset)??o.presets[0]:void 0;if(o.preset&&!r)throw new Error(`MorphicBlocks.mount: unknown preset "${o.preset}".`);const c=(o.modes??[]).map(b=>b.name),a=c[0]??((S=s[0])==null?void 0:S.mode)??"default",l=r?Le(r.toolbox):void 0,d=r?r.workspace??r.codespace??a:a,u=l?l.mode:a,w=l==null?void 0:l.render,v=r==null?void 0:r.codespace,C=r==null?void 0:r.preview;this.validateContainers(o);const E=o.workspaceContainer??this.createHeadlessHost(),k={...o,modeStyles:s,workspaceMode:d,toolboxMode:u,toolboxRender:w,codespaceMode:v,previewMode:C,workspaceHost:E,canvasToolbox:o.canvasToolbox??!!o.toolboxContainer};this.mountConfig=k,this.styles.validateModeCoverage(s,c),(h=k.modes)!=null&&h.length&&this.styles.ensureModeVisibilityStyles(k.modes),this.styles.ensureStyles(k.baseStyle,s);for(const b of Array.from(document.head.querySelectorAll('link[data-morphic-source^="mode:"]')))b.sheet||b.addEventListener("load",this.onStylesLoaded,{once:!0});(f=document.fonts)==null||f.addEventListener("loadingdone",this.onStylesLoaded),this.blockCategoryIndex=this.createCategoryIndex(k.toolbox,k),this.styles.ensureCategoryStyles(((x=k.toolbox)==null?void 0:x.categories)??[]),this.registerBlocks(),this.toolboxDefinition=this.resolveToolboxDefinition(k);const m=k.blockly??{};if(this.workspace=L.inject(k.workspaceHost,{...m,...k.canvasToolbox?{}:{toolbox:this.toolboxDefinition}}),this.workspace.addChangeListener(this.onWorkspaceChange),me.set(this.workspace,this),this.baseTheme=this.workspace.getTheme(),this.baseFont=Xe(this.workspace),o.workspaceContainer&&typeof ResizeObserver<"u"){const b=this.workspace;this.workspaceResizeObserver=new ResizeObserver(()=>L.svgResize(b)),this.workspaceResizeObserver.observe(o.workspaceContainer)}return this.applyWorkspaceContainerClass(),this.syncWorkspaceFont(),this.refreshToolbox(),this.bindFlyoutWorkspace(),this.renderWorkspaceBlocks(),this.renderFlyoutBlocks(),o.toolboxContainer&&this.mountToolbox(o.toolboxContainer),this.activePreset=r,r&&((B=k.onPresetApplied)==null||B.call(k,r)),this.mountViews(o,++this.mountGeneration)}async mountViews(e,o){const i=e.editorTheme?{theme:e.editorTheme}:void 0,s=e.previewTheme??e.editorTheme,r=[];if(e.codespaceContainer&&r.push(this.mountCodespace(i)),e.previewContainer&&r.push(this.mountPreview(e.previewContainer,s?{theme:s}:void 0)),e.codeEditorContainer&&r.push(this.mountCodeEditor(e.codeEditorContainer,i).then(()=>{o===this.mountGeneration&&this.hideCodeEditor()})),await Promise.all(r),o!==this.mountGeneration||!this.workspace)return;for(const[l,d]of Object.entries(e.toolbarContainers??{}))d&&this.mountToolbar(d,{pane:l});const c=(e.workspaceContainer?1:0)+r.length,a=e.selectionSync??c>1;a&&r.length>0&&this.enableSelectionSync(typeof a=="object"?a:void 0)}getPresets(){var e;return[...((e=this.mountConfig)==null?void 0:e.presets)??[]]}getActivePreset(){return this.activePreset}applyPreset(e){var r,c;if(!this.mountConfig||!this.workspace)throw new Error("MorphicBlocks must be mounted before applyPreset can be used.");const o=this.mountConfig.presets??[],i=typeof e=="number"?o[e]:o.find(a=>a.name===e);if(!i)throw new Error(`applyPreset: unknown preset "${e}".`);const s=Le(i.toolbox);return this.setModes({toolboxMode:s.mode,toolboxRender:s.render??null,workspaceMode:i.workspace??i.codespace,codespaceMode:i.codespace??null,previewMode:i.preview??null}),this.activePreset=i,(c=(r=this.mountConfig).onPresetApplied)==null||c.call(r,i),i}validateDefinitions(e){var s;const{errors:o,warnings:i}=qe({definitions:this.definitions,elementTypes:this.elementTypes,behaviors:this.behaviors,modes:e.modes,presets:e.presets,highlighting:e.highlighting,categories:(s=e.toolbox)==null?void 0:s.categories});if(i.length>0&&console.warn(`[MorphicBlocks] Definition warnings:
27
27
  - ${i.join(`
28
28
  - `)}`),o.length>0)throw new Error(`[MorphicBlocks] Invalid definitions:
29
29
  - ${o.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "morphic-blocks",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Mode-driven wrapper framework around Google Blockly",
5
5
  "repository": {
6
6
  "type": "git",