@tvolden/block-code-editor 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/block-editor.cjs +4 -4
- package/dist/block-editor.js +1428 -1299
- package/dist/commands/build.d.ts +5 -0
- package/dist/components/BlockRenderer.d.ts +4 -0
- package/dist/components/Canvas.d.ts +4 -0
- package/dist/components/MouthDecorations.d.ts +9 -1
- package/dist/utils/blockLayout.d.ts +58 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -25,7 +25,8 @@ dotnet add package BlockCodeEditor.Commands
|
|
|
25
25
|
The editor's blocks come from definitions (`BlockDefinition`, loaded from `blocksUrl` / `blocksUrls` as JSON, see `public/blocks.json`). A block's `params` are its parameters in order, each `{ "name", "type" }`:
|
|
26
26
|
|
|
27
27
|
- A parameter is filled by typing a value into its socket, or by dropping a query whose `returnType` (or `usableAs`) is its `type`. `number`, `string` and `boolean` sockets have their own shapes. On a command block, `command` is a mouth that holds a chain of commands.
|
|
28
|
-
- `"optional": true` marks a parameter that may be left out. It isn't drawn as an empty socket but as a small `+ name` chip. Like an empty socket, the chip takes a dropped query or a click to type a value, which adds the parameter; its `×` (or clearing its text, or dragging its query out) leaves it out again. A parameter left out has no value in the canvas, the program tree (`empty`) or the commands: the host uses its default. Older definitions without the flag work as before, with every parameter required.
|
|
28
|
+
- `"optional": true` marks a parameter that may be left out. It isn't drawn as an empty socket but as a small `+ name` chip. Like an empty socket, the chip takes a dropped query or a click to type a value, which adds the parameter; its `×` (or clearing its text, or dragging its query out) leaves it out again. A parameter left out has no value in the canvas, the program tree (`empty`) or the commands: the host uses its default. Older definitions without the flag work as before, with every parameter required.
|
|
29
|
+
- An optional command parameter (a mouth) that holds no chain is drawn as a `+ name` chip on the block's bottom bar instead of an empty mouth, e.g. `If(Condition, Then, Else?)` shows its `Then` mouth and a `+ Else` chip. Clicking the chip opens the mouth, empty, under a divider bar with its name; dropping commands on the chip puts them in the mouth. The `×` on an open optional mouth's divider bar closes it, and a chain it holds is put down beside the block as one undoable action. Opening a mouth is only the editor's view: an empty mouth is "not given" anyway, so it isn't in the canvas, the program tree or the commands. A mouth holding a chain is always open, also on another user's canvas or after a reload. Taking its chain out leaves it open until its `×` is clicked.
|
|
29
30
|
|
|
30
31
|
## Developing
|
|
31
32
|
|
package/dist/block-editor.cjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("react/jsx-runtime"),u=require("react");function mo(e,t,n){"dependencies"in e?n(e.dependencies(t)):e.onClick()}function F(e){return`${e.publisher}/${e.name}`}function ze(e){return`${dt}${F(e)}@${e.version}`}const dt="dep:";function pn(e,t){const n=e.split(/[.-]/),r=t.split(/[.-]/);for(let o=0;o<Math.max(n.length,r.length);o++){const s=n[o]??"0",c=r[o]??"0",l=Number(s),x=Number(c),y=!isNaN(l)&&!isNaN(x)?l-x:s.localeCompare(c);if(y!==0)return y}return 0}const ko=1;class A extends Error{code;constructor(t,n){super(n),this.name="CommandRejected",this.code=t}}function _e(e,t){switch(t.type){case"InsertBlocks":return vo(e,t);case"RemoveBlocks":return So(e,t);case"MoveBlock":return $o(e,t);case"Attach":return Bo(e,t);case"Detach":return jo(e,t);case"SetText":return Co(e,t);case"SetDependencies":return To(e,t);case"Batch":return Eo(e,t);default:throw new A("INVALID_COMMAND",`Unknown command type '${t.type}'.`)}}function Ye(e){return{textValue:e?.textValue??null,queryBlockId:e?.queryBlockId??null,commandBlockId:e?.commandBlockId??null}}function ye(e){const t=Rt(e)?{x:e.x,y:e.y}:{x:0,y:0};return{...e,...t,paramSlots:e.paramSlots.map(Ye)}}function $e(e){return e==null||e===""?null:e}function De(e,t){const n=e.blocks.get(t);if(!n)throw new A("BLOCK_NOT_FOUND",`Block '${t}' doesn't exist.`);return n}function Rt(e){return!e.parentBlockId&&!e.embeddedInBlockId}function xn(e){const t=[];e.nextBlockId&&t.push(e.nextBlockId);for(const n of e.paramSlots)n.queryBlockId&&t.push(n.queryBlockId),n.commandBlockId&&t.push(n.commandBlockId);return t}function Xe(e,t){const n=[],r=new Set,o=[t];for(;o.length>0;){const s=o.shift();if(r.has(s))continue;const c=e.get(s);c&&(r.add(s),n.push(s),o.push(...xn(c)))}return n}function gn(e){const t=o=>new A("NOT_A_FRAGMENT",`The blocks aren't one fragment: ${o}.`);if(e.length===0)throw new A("INVALID_COMMAND","The command has no blocks.");const n=new Map;for(const o of e){if(n.has(o.instanceId))throw t(`'${o.instanceId}' is given twice`);n.set(o.instanceId,o)}const r=e.filter(Rt);if(r.length!==1)throw t(`it has ${r.length} roots`);for(const o of e){if(o.nextBlockId){const s=n.get(o.nextBlockId);if(!s||s.parentBlockId!==o.instanceId||s.embeddedInBlockId)throw t(`the block under '${o.instanceId}' doesn't match`)}if(o.paramSlots.forEach((s,c)=>{for(const l of[s.queryBlockId,s.commandBlockId]){if(!l)continue;const x=n.get(l);if(!x||x.embeddedInBlockId!==o.instanceId||x.embeddedSlotIndex!==c||x.parentBlockId)throw t(`slot ${c} of '${o.instanceId}' doesn't match`)}}),o.parentBlockId){const s=n.get(o.parentBlockId);if(!s||s.nextBlockId!==o.instanceId)throw t(`the block above '${o.instanceId}' doesn't match`)}if(o.embeddedInBlockId){const s=n.get(o.embeddedInBlockId)?.paramSlots[o.embeddedSlotIndex];if(!s||s.queryBlockId!==o.instanceId&&s.commandBlockId!==o.instanceId)throw t(`the block holding '${o.instanceId}' doesn't match`)}}if(Xe(n,r[0].instanceId).length!==e.length)throw t("not every block hangs off the root");return r[0]}function bo(e,t){return JSON.stringify(ye(e))===JSON.stringify(ye(t))}function rt(e,t,n){const r=e.paramSlots.map(Ye);return r[t]={...r[t],...n},{...e,paramSlots:r}}function yn(e,t){if(!Number.isInteger(t)||t<0||t>=e.paramSlots.length)throw new A("NO_SUCH_SLOT",`Block '${e.instanceId}' has no slot ${t}.`);return Ye(e.paramSlots[t])}function mn(e,t){if(e.x!==t.x||e.y!==t.y)throw new A("POSITION_CHANGED",`Block '${e.instanceId}' isn't at (${t.x}, ${t.y}).`)}function kn(e){if(!Rt(e))throw new A("NOT_A_ROOT",`Block '${e.instanceId}' is linked, not a root.`)}const $t=e=>`${e.publisher}/${e.name}@${e.version}`;function Io(e,t){const n=new Set(e.map($t));return e.length===t.length&&n.size===new Set(t.map($t)).size&&t.every(r=>n.has($t(r)))}function vo(e,t){gn(t.blocks);for(const r of t.blocks)if(e.blocks.has(r.instanceId))throw new A("ID_EXISTS",`Block '${r.instanceId}' already exists.`);const n=new Map(e.blocks);for(const r of t.blocks)n.set(r.instanceId,ye(r));return{...e,blocks:n}}function So(e,t){gn(t.blocks);const n=new Set;for(const o of t.blocks){const s=De(e,o.instanceId);if(!bo(s,o))throw new A("BLOCK_CHANGED",`Block '${o.instanceId}' has changed.`);n.add(o.instanceId)}for(const o of e.blocks.values())if(!n.has(o.instanceId)&&xn(o).some(s=>n.has(s)))throw new A("LINKED_FROM_OUTSIDE",`Block '${o.instanceId}' links into the blocks to remove.`);const r=new Map(e.blocks);return n.forEach(o=>r.delete(o)),{...e,blocks:r}}function $o(e,t){const n=De(e,t.id);kn(n),mn(n,t.from);const r=new Map(e.blocks);return r.set(n.instanceId,{...n,x:t.to.x,y:t.to.y}),{...e,blocks:r}}function Bo(e,t){const n=De(e,t.id);kn(n),mn(n,t.from);const r=t.to,o="next"in r?r.next:"mouth"in r?r.mouth:r.socket,s=De(e,o);if(Xe(e.blocks,n.instanceId).includes(o))throw new A("CYCLE",`Block '${o}' is inside the fragment of '${n.instanceId}'.`);const c=new Map(e.blocks);if("next"in r){if(s.nextBlockId)throw new A("PLACE_OCCUPIED",`Block '${o}' already has a block under it.`);return c.set(o,{...s,nextBlockId:n.instanceId}),c.set(n.instanceId,{...n,x:0,y:0,parentBlockId:o}),{...e,blocks:c}}const l=yn(s,r.slot);if("mouth"in r){if(l.commandBlockId||l.queryBlockId)throw new A("PLACE_OCCUPIED",`Mouth ${r.slot} of '${o}' isn't empty.`);c.set(o,rt(s,r.slot,{commandBlockId:n.instanceId}))}else{if(l.queryBlockId||l.commandBlockId||l.textValue!==null)throw new A("PLACE_OCCUPIED",`Socket ${r.slot} of '${o}' isn't empty.`);c.set(o,rt(s,r.slot,{queryBlockId:n.instanceId}))}return c.set(n.instanceId,{...n,x:0,y:0,embeddedInBlockId:o,embeddedSlotIndex:r.slot}),{...e,blocks:c}}function wo(e,t,n){if("next"in n)return t.parentBlockId===n.next&&e.blocks.get(n.next)?.nextBlockId===t.instanceId;const r="mouth"in n?n.mouth:n.socket;if(t.embeddedInBlockId!==r||t.embeddedSlotIndex!==n.slot)return!1;const o=Ye(e.blocks.get(r)?.paramSlots[n.slot]);return("mouth"in n?o.commandBlockId:o.queryBlockId)===t.instanceId}function jo(e,t){const n=De(e,t.id);if(!wo(e,n,t.from))throw new A("NOT_AT_PLACE",`Block '${n.instanceId}' isn't linked at the given place.`);const r=new Map(e.blocks),o=t.from;if("next"in o){const s=r.get(o.next);r.set(o.next,{...s,nextBlockId:null})}else{const s="mouth"in o?o.mouth:o.socket,c="mouth"in o?{commandBlockId:null}:{queryBlockId:null};r.set(s,rt(r.get(s),o.slot,c))}return r.set(n.instanceId,{...n,x:t.to.x,y:t.to.y,parentBlockId:null,embeddedInBlockId:null,embeddedSlotIndex:-1}),{...e,blocks:r}}function Co(e,t){const n=De(e,t.blockId),r=yn(n,t.slot);if(r.queryBlockId)throw new A("SLOT_HAS_QUERY",`Slot ${t.slot} of '${n.instanceId}' holds a query.`);if($e(r.textValue)!==$e(t.from))throw new A("TEXT_CHANGED",`Slot ${t.slot} of '${n.instanceId}' has changed.`);const o=new Map(e.blocks);return o.set(n.instanceId,rt(n,t.slot,{textValue:$e(t.to)})),{...e,blocks:o}}function To(e,t){if(!Io(e.dependencies,t.from))throw new A("DEPENDENCIES_CHANGED","The dependencies have changed.");return{...e,dependencies:t.to.map(n=>({publisher:n.publisher,name:n.name,version:n.version}))}}function Eo(e,t){return t.commands.reduce(_e,e)}const Pe={x:0,y:0};class ut{state;commands=[];constructor(t){this.state=t}get current(){return this.state}add(t){this.state=_e(this.state,t),this.commands.push(t)}build(){return this.commands.length===0?null:this.commands.length===1?this.commands[0]:{type:"Batch",commands:this.commands}}}function Nt(e){return{x:Math.round(e.x),y:Math.round(e.y)}}function ft(e,t){return t.parentBlockId?{next:t.parentBlockId}:t.embeddedInBlockId?e.blocks.get(t.embeddedInBlockId)?.paramSlots[t.embeddedSlotIndex]?.commandBlockId===t.instanceId?{mouth:t.embeddedInBlockId,slot:t.embeddedSlotIndex}:{socket:t.embeddedInBlockId,slot:t.embeddedSlotIndex}:null}function bn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function In(e,t){return Xe(e.blocks,t).map(n=>ye(e.blocks.get(n)))}function Po(e,t){let n=t;for(;;){const r=e.blocks.get(n)?.nextBlockId;if(!r)return n;n=r}}function vn(e,t,n){const r=e.current.blocks.get(t),o={x:r.x,y:r.y};if("socket"in n){const s=$e(e.current.blocks.get(n.socket)?.paramSlots[n.slot]?.textValue);s!==null&&e.add({type:"SetText",blockId:n.socket,slot:n.slot,from:s,to:null}),e.add({type:"Attach",id:t,to:n,from:o});return}if("mouth"in n){const s=e.current.blocks.get(n.mouth)?.paramSlots[n.slot]?.commandBlockId??null;if(s){e.add({type:"Detach",id:s,from:n,to:Pe}),e.add({type:"Attach",id:t,to:n,from:o}),e.add({type:"Attach",id:s,to:{next:Po(e.current,t)},from:Pe});return}}e.add({type:"Attach",id:t,to:n,from:o})}function Sn(e,t,n,r){const o=new ut(e),s=Nt(n);return o.add({type:"InsertBlocks",blocks:[ye({...t,...s})]}),r&&vn(o,t.instanceId,r),o.build()}function wt(e,t,n,r){const o=e.blocks.get(t);if(!o)return null;const s=new ut(e),c=Nt(n),l=ft(e,o);return r&&l&&bn(r,l)?null:(l?s.add({type:"Detach",id:t,from:l,to:c}):!r&&(o.x!==c.x||o.y!==c.y)&&s.add({type:"MoveBlock",id:t,from:{x:o.x,y:o.y},to:c}),r&&vn(s,t,r),s.build())}function $n(e,t){const n=e.blocks.get(t);if(!n)return null;const r=new ut(e),o=ft(e,n);return o&&r.add({type:"Detach",id:t,from:o,to:Pe}),r.add({type:"RemoveBlocks",blocks:In(r.current,t)}),r.build()}function jt(e,t,n,r){const o=$e(n),s=$e(r);return o===s?null:{type:"SetText",blockId:e,slot:t,from:o,to:s}}function Bn(e,t,n){const r=new ut(e);for(const o of n){const s=r.current.blocks.get(o);if(!s)continue;const c=ft(r.current,s),l=s.nextBlockId;if(l){const x=c?Pe:{x:s.x,y:s.y};r.add({type:"Detach",id:l,from:{next:o},to:x})}c&&r.add({type:"Detach",id:o,from:c,to:Pe}),r.add({type:"RemoveBlocks",blocks:In(r.current,o)}),l&&c&&r.add({type:"Attach",id:l,to:c,from:Pe})}return r.add({type:"SetDependencies",from:r.current.dependencies,to:t}),r.build()}function Ot(e){switch(e.type){case"InsertBlocks":return{type:"RemoveBlocks",blocks:e.blocks};case"RemoveBlocks":return{type:"InsertBlocks",blocks:e.blocks};case"MoveBlock":return{type:"MoveBlock",id:e.id,from:e.to,to:e.from};case"Attach":return{type:"Detach",id:e.id,from:e.to,to:e.from};case"Detach":return{type:"Attach",id:e.id,to:e.from,from:e.to};case"SetText":return{type:"SetText",blockId:e.blockId,slot:e.slot,from:e.to,to:e.from};case"SetDependencies":return{type:"SetDependencies",from:e.to,to:e.from};case"Batch":return{type:"Batch",commands:e.commands.map(Ot).reverse()};default:throw new A("INVALID_COMMAND",`Unknown command type '${e.type}'.`)}}function wn(e,t=0){return{confirmed:e,version:t,pending:[],undo:[],redo:[]}}function Mo(e,t,n){return{...e,pending:[...e.pending,{id:t,command:n,kind:"do",original:n}]}}function Do(e,t){const n=e.undo[e.undo.length-1];if(!n||!st(e))return null;const r=Ot(n);return{sync:{...e,pending:[...e.pending,{id:t,command:r,kind:"undo",original:n}]},command:r}}function Ao(e,t){const n=e.redo[e.redo.length-1];return!n||!st(e)?null:{sync:{...e,pending:[...e.pending,{id:t,command:n,kind:"redo",original:n}]},command:n}}function st(e){return e.pending.length===0}function _o(e,t,n){return{sync:wn(e,t),dropped:n.pending.length}}function an(e,t,n){let r;try{r=_e(e.confirmed,t.command)}catch{return{sync:e,outOfSync:!0}}const o=e.pending.find(c=>c.id===t.id),s={...e,confirmed:r,version:n,pending:e.pending.filter(c=>c.id!==t.id)};if(!o)return{sync:s,outOfSync:!1};switch(o.kind){case"do":return{sync:{...s,undo:[...s.undo,o.original],redo:[]},outOfSync:!1};case"undo":return{sync:{...s,undo:s.undo.slice(0,-1),redo:[...s.redo,o.original]},outOfSync:!1};case"redo":return{sync:{...s,undo:[...s.undo,o.original],redo:s.redo.slice(0,-1)},outOfSync:!1}}}function dn(e,t){const n=e.pending.find(o=>o.id===t)??null;if(!n)return{sync:e,action:null};const r={...e,pending:e.pending.filter(o=>o.id!==t)};return n.kind==="undo"?{sync:{...r,undo:r.undo.slice(0,-1)},action:n}:n.kind==="redo"?{sync:{...r,redo:r.redo.slice(0,-1)},action:n}:{sync:r,action:n}}function un(e){let t=e.confirmed;for(const r of e.pending)try{t=_e(t,r.command)}catch{break}const n=new Set;return t!==e.confirmed&&t.blocks.forEach((r,o)=>{e.confirmed.blocks.get(o)!==r&&n.add(o)}),{state:t,provisionalIds:n}}const jn=66,Ro={cursor:null,drag:null,typing:null};class No{presence=Ro;lastSent=Number.NEGATIVE_INFINITY;timer=null;send;intervalMs;now;constructor(t,n=jn,r=Date.now){this.send=t,this.intervalMs=n,this.now=r}get current(){return this.presence}update(t){if(this.presence={...this.presence,...t},this.timer)return;const n=this.lastSent+this.intervalMs-this.now();n<=0?this.flush():this.timer=setTimeout(()=>this.flush(),n)}updateNow(t){this.presence={...this.presence,...t},this.flush()}dispose(){this.timer&&clearTimeout(this.timer),this.timer=null}flush(){this.dispose(),this.lastSent=this.now(),this.send(this.presence)}}const it="command",ue=new Map,Fe=new Map,me=new Map;async function Lt(e){const t=me.get(e.id);if(t&&t.info.url===e.url)return t;t&&Ht(e.id);const n=await fetch(e.url);if(!n.ok)throw new Error(`HTTP ${n.status} fetching ${e.url}`);const r=await n.json(),o=[],s=[];for(const l of r)ue.has(l.id)?s.push(l.id):(ue.set(l.id,l),Fe.set(l.id,e.id),o.push(l.id));const c={info:e,blockIds:o,conflictIds:s};return me.set(e.id,c),c}function Ht(e){const t=me.get(e);if(t){for(const n of t.blockIds)ue.delete(n),Fe.delete(n);me.delete(e)}}function We(){return Array.from(me.values())}function Cn(e){return Fe.get(e)}function ct(e){const t=ue.get(e);if(!t)throw new Error(`Block definition not found: "${e}"`);return t}function N(e){return ue.get(e)}function Tn(){return[...ue.values()]}function Oo(){return[...new Set(Tn().map(e=>e.category))]}function Lo(e,t){const n=[],r=[];for(const s of t)ue.has(s.id)?r.push(s.id):(ue.set(s.id,s),Fe.set(s.id,e.id),n.push(s.id));const o={info:e,blockIds:n,conflictIds:r};return me.set(e.id,o),o}async function Ho(e){me.get(fn)?.info.url!==e&&(ue.clear(),Fe.clear(),me.clear(),await Lt({id:fn,name:"Core",description:"Built-in blocks",url:e,builtIn:!0}))}const fn="__core__",En=36,Be=50,ge=24,Ue=24,zt=16,zo=24,Ct=24,Wo=16,Pn=20,qo=26,Vo=8,Uo=6,Tt=12,Bt=12,Mn=8,Et=6;function Dn(e){return e.blockType==="query"&&e.returnType?`${e.name} [${e.returnType}]`:e.name}const Yo={number:{w:44,h:ge},string:{w:60,h:ge},boolean:{w:52,h:ge}},Xo={w:75,h:ge};function lt(e){return Yo[e]??Xo}function Ae(e,t){return e.blockType==="command"&&t.type===it}const Fo=18;function An(e,t){return!!e.optional&&!t?.queryBlockId&&!t?.textValue}function _n(e){return`+ ${e}`}function Ko(e){return _n(e).length*Nn+12}function Rn(e,t,n){if(An(e,t))return Ko(e.name);if(t?.queryBlockId&&n){const r=n.get(t.queryBlockId);if(r){const o=N(r.definitionId);if(o)return ce(o,r.paramSlots,n)}}return lt(e.type).w}const Nn=5;function Qo(e,t,n){const o=t==="number"||t==="boolean"?n-ge:n-10,s=Math.floor(o/Nn);return e.length<=s?e:s<=1?"…":`${e.slice(0,s-1)}…`}function Pt(e,t){return`${e}: ${t}`}function On(e){const t=Pt(e.name,e.type);return e.optional?`${t} (optional)`:t}function Go(e){return Math.max(72,e.length*6+22)}function Wt(e){let t=Vo;return(e.blockType==="start"?e.provides??[]:[]).map(n=>{const r={id:n.id,name:n.name,x:t,y:Be+6,w:Go(n.name)};return t+=r.w+Uo,r})}function ce(e,t,n){let r=Tt+Bt+Dn(e).length*Et;for(let c=0;c<e.params.length;c++)Ae(e,e.params[c])||(r+=Mn+Rn(e.params[c],t?.[c],n));const o=Wt(e);if(o.length>0){const c=o[o.length-1];r=Math.max(r,c.x+c.w+Bt)}e.params.forEach(c=>{Ae(e,c)&&(r=Math.max(r,zt+Tt+c.name.length*Et+Bt))});const s=e.blockType==="start"?140:110;return Math.max(s,r)}function Ke(e){return e.blockType==="start"?Be:e.blockType==="command"?En:ge}function ke(e,t,n){if(e.blockType==="start")return Be+(e.provides&&e.provides.length>0?8+qo:0);if(e.blockType==="command"){const r=je(e,t,n);if(r.length===0)return En;const o=r[r.length-1];return o.y+o.h+Wo}return ge}function qt(e,t){const n=N(e.definitionId);return n?ke(n,e.paramSlots,t):Ue}function Ln(e,t){let n=0;const r=new Set;let o=e;for(;o&&!r.has(o);){r.add(o);const s=t.get(o);if(!s)break;n+=qt(s,t),o=s.nextBlockId}return n}function je(e,t,n){const r=[];let o=Ke(e);return e.params.forEach((s,c)=>{if(!Ae(e,s))return;let l=null;r.length>0&&(l=o,o+=Ct);const x=t?.[c]?.commandBlockId,y=x&&n?Ln(x,n):0,g=Math.max(zo,y);r.push({index:c,name:s.name,x:zt,y:o,h:g,dividerY:l}),o+=g}),r}function Qe(e,t,n){const r=Ke(e),o=[];let s=Tt+Dn(e).length*Et;for(let c=0;c<e.params.length;c++){const l=e.params[c];if(Ae(e,l))continue;const x=An(l,t?.[c]),y=Rn(l,t?.[c],n),g=x?Fo:lt(l.type).h;s+=Mn,o.push({x:s,y:(r-g)/2,w:y,h:g,type:l.type,index:c,collapsed:x}),s+=y}return o}function Zo(e){const t=new Map;function n(r,o,s){const c=e.get(r);if(!c||t.has(r))return;t.set(r,{x:o,y:s});const l=N(c.definitionId);if(l){for(const x of Qe(l,c.paramSlots,e)){const y=c.paramSlots[x.index]?.queryBlockId;y&&n(y,o+x.x,s+x.y)}for(const x of je(l,c.paramSlots,e)){const y=c.paramSlots[x.index]?.commandBlockId;y&&n(y,o+x.x,s+x.y)}}c.nextBlockId&&n(c.nextBlockId,o,s+qt(c,e))}return e.forEach(r=>{!r.parentBlockId&&!r.embeddedInBlockId&&n(r.instanceId,r.x,r.y)}),t}function Hn(e,t){const n=new Set;function r(c){const l=[];let x=c??null;for(;x&&!n.has(x);){const y=e.blocks.get(x);if(!y)break;l.push(o(y)),x=y.nextBlockId}return l}function o(c){n.add(c.instanceId);const l=t(c.definitionId),x=c.paramSlots.map((y,g)=>{const B=l?.params[g]??{name:`param${g}`,type:"string"},O=y.queryBlockId?e.blocks.get(y.queryBlockId):void 0;let w;return l&&Ae(l,B)?w={kind:"body",body:r(y.commandBlockId)}:O?w={kind:"query",node:o(O)}:y.textValue!==null&&y.textValue!==void 0&&y.textValue!==""?w={kind:"text",text:y.textValue}:w={kind:"empty"},{name:B.name,type:B.type,value:w}});return{definitionId:c.definitionId,name:l?.name??c.definitionId,blockType:l?.blockType??"missing",args:x}}return{roots:[...e.blocks.values()].filter(c=>!c.parentBlockId&&!c.embeddedInBlockId).sort((c,l)=>c.y-l.y||c.x-l.x||(c.instanceId<l.instanceId?-1:c.instanceId>l.instanceId?1:0)).map(c=>({position:{x:c.x,y:c.y},body:r(c.instanceId)}))}}const Me={id:"dark",label:"Dark",appBg:"#0e1118",paletteBg:"#141820",paletteHeaderBg:"#0e1118",canvasBg:"#111420",consoleBg:"#0e1118",consoleHeaderBg:"#141820",border:"#252d42",accent:"#c9a43a",textPrimary:"#dde8f8",textSecondary:"#7a90b8",textMuted:"#5a6888",inputBg:"#0e1118",inputBorder:"#303858",gridDot:"#252d42",blockBody:"#1a2236",blockBorder:"#303858",blockText:"#e8f0fc",socketBody:"#141e30",consoleOutput:"#b8d4ec",consoleSeparator:"#4a6090",deleteBorder:"#252d42",deleteText:"#5a6888",deleteActiveBg:"#3a0c0c",deleteActiveBorder:"#8a2020",deleteActiveText:"#e06060",titleBg:"#0e1118",titlePrimaryText:"#c9a43a",titleSecondaryText:"#5a6888",pkgBg:"#141820",pkgBorder:"#252d42",pkgActiveBg:"#1a2236",pkgActiveBorder:"#3a4d70",pkgText:"#7a8aaa",pkgActiveText:"#c9a43a",pkgSubText:"#5a6888",switcherBg:"transparent",switcherActiveBg:"#1a2236",switcherText:"#5a6888",switcherActiveText:"#c9a43a",switcherBorder:"#252d42"},Jo={id:"light",label:"Light",appBg:"#f0f2f6",paletteBg:"#ffffff",paletteHeaderBg:"#f8f9fc",canvasBg:"#e8ebf2",consoleBg:"#ffffff",consoleHeaderBg:"#f8f9fc",border:"#dde2ec",accent:"#2a50a0",textPrimary:"#1a2030",textSecondary:"#5060a0",textMuted:"#a0aac0",inputBg:"#f0f2f6",inputBorder:"#d0d8e8",gridDot:"#c0c8d8",blockBody:"#ffffff",blockBorder:"#c8d0e0",blockText:"#1a2030",socketBody:"#eaecf4",consoleOutput:"#2a50a0",consoleSeparator:"#dde2ec",deleteBorder:"#dde2ec",deleteText:"#b0b8d0",deleteActiveBg:"#fff0f0",deleteActiveBorder:"#e08080",deleteActiveText:"#c04040",titleBg:"#ffffff",titlePrimaryText:"#1a2030",titleSecondaryText:"#8090b0",pkgBg:"#f8f9fc",pkgBorder:"#dde2ec",pkgActiveBg:"#eef2fc",pkgActiveBorder:"#a0b8e0",pkgText:"#7080a0",pkgActiveText:"#2a50a0",pkgSubText:"#9090a0",switcherBg:"transparent",switcherActiveBg:"#eaedf4",switcherText:"#9090a0",switcherActiveText:"#1a2030",switcherBorder:"#dde2ec"},qe=[Me,Jo],Ve=u.createContext(Me);function U(){return u.useContext(Ve)}const X=16,xe=14,ve=X+xe/2,Se=5,P=4;function er(e,t){return[`M ${P} 0`,`H ${X} L ${ve} ${Se} L ${X+xe} 0`,`H ${e-P} Q ${e} 0 ${e} ${P}`,`V ${t-P} Q ${e} ${t} ${e-P} ${t}`,`H ${X+xe} L ${ve} ${t+Se} L ${X} ${t}`,`H ${P} Q 0 ${t} 0 ${t-P}`,`V ${P} Q 0 0 ${P} 0 Z`].join(" ")}function tr(e,t,n,r){const o=[`M ${P} 0`,`H ${X} L ${ve} ${Se} L ${X+xe} 0`,`H ${e-P} Q ${e} 0 ${e} ${P}`];for(const s of r){const c=s.y,l=s.y+s.h;o.push(`V ${c}`,`H ${n+X+xe} L ${n+ve} ${c+Se} L ${n+X} ${c}`,`H ${n}`,`V ${l}`,`H ${n+X} L ${n+ve} ${l+Se} L ${n+X+xe} ${l}`,`H ${e}`)}return o.push(`V ${t-P} Q ${e} ${t} ${e-P} ${t}`,`H ${X+xe} L ${ve} ${t+Se} L ${X} ${t}`,`H ${P} Q 0 ${t} 0 ${t-P}`,`V ${P} Q 0 0 ${P} 0 Z`),o.join(" ")}function nr(e,t){return["M 0 10 Q 0 0 10 0",`H ${e-10} Q ${e} 0 ${e} 10`,`V ${t-P} Q ${e} ${t} ${e-P} ${t}`,`H ${X+xe} L ${ve} ${t+Se} L ${X} ${t}`,`H ${P} Q 0 ${t} 0 ${t-P}`,"V 10 Z"].join(" ")}function or(e,t){const n=t/2;return[`M ${n} 0 H ${e-n}`,`A ${n} ${n} 0 0 1 ${e-n} ${t}`,`H ${n} A ${n} ${n} 0 0 1 ${n} 0 Z`].join(" ")}function rr(e,t){const n=t/2;return[`M ${n} 0 H ${e-n}`,`L ${e} ${t/2} L ${e-n} ${t}`,`H ${n} L 0 ${t/2} Z`].join(" ")}function zn(e,t,n){return[`M ${n} 0 H ${e-n} Q ${e} 0 ${e} ${n}`,`V ${t-n} Q ${e} ${t} ${e-n} ${t}`,`H ${n} Q 0 ${t} 0 ${t-n}`,`V ${n} Q 0 0 ${n} 0 Z`].join(" ")}function sr(e,t){return zn(e,t,5)}function ir(e,t){return zn(e,t,9)}function Vt(e,t,n){switch(e){case"number":return or(t,n);case"boolean":return rr(t,n);case"string":return sr(t,n);default:return ir(t,n)}}function Ut(e,t,n){return Vt(e,t,n)}function Yt(e,t,n){const r=ce(e,t,n),o=ke(e,t,n);if(e.blockType==="start")return nr(r,o);if(e.blockType==="query")return Vt(e.returnType,r,o);const s=je(e,t,n);return s.length>0?tr(r,o,zt,s):er(r,o)}function cr({available:e,dependencies:t,onChange:n,actions:r,blockCounts:o,conflictCounts:s}){const c=U(),[l,x]=u.useState(""),[y,g]=u.useState(""),[B,O]=u.useState(!1),[w,L]=u.useState(null),H=new Map(e.map(k=>[F(k),k])),S=new Set(t.map(F)),v=e.filter(k=>!S.has(F(k)));function Q(){const k=H.get(l);if(!k)return;const _=B&&y.trim()?y.trim():k.version;n([...t,{publisher:k.publisher,name:k.name,version:_}]),x(""),g("")}function m(k){n(t.filter(_=>F(_)!==k)),L(null)}function K(k,_){n(t.map(V=>F(V)===k?{...V,version:_}:V))}const G={background:c.inputBg,color:c.textPrimary,border:`1px solid ${c.inputBorder}`,borderRadius:4,fontSize:11,padding:"4px 6px",outline:"none",minWidth:0},se={background:"none",color:c.textSecondary,border:`1px solid ${c.border}`,borderRadius:4,fontSize:11,padding:"4px 8px",cursor:"pointer"},Z=w?o.get(w)??0:0;return i.jsxs("div",{style:{flex:1,overflowY:"auto",padding:10,display:"flex",flexDirection:"column",gap:6},children:[t.length===0&&i.jsx("div",{style:{color:c.textMuted,fontSize:11,fontStyle:"italic"},children:"No packages yet — add one to get blocks."}),w&&i.jsxs("div",{style:{border:`1px solid ${c.deleteActiveBorder}`,background:c.deleteActiveBg,borderRadius:4,padding:"6px 8px",fontSize:11,color:c.textPrimary},children:["Remove ",i.jsx("b",{children:w}),"?"," ",Z>0?`Its ${Z} block${Z===1?"":"s"} on the canvas ${Z===1?"is":"are"} deleted.`:"None of its blocks are on the canvas.",i.jsxs("div",{style:{display:"flex",gap:6,marginTop:6},children:[i.jsx("button",{type:"button",onClick:()=>m(w),style:{...se,background:c.deleteActiveBorder,color:"white",borderColor:c.deleteActiveBorder},children:"Remove"}),i.jsx("button",{type:"button",onClick:()=>L(null),style:se,children:"Cancel"})]})]}),t.map(k=>{const _=F(k),V=H.get(_),z=V&&pn(V.version,k.version)>0?V.version:null,te=s.get(_)??0;return i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11},children:[i.jsx("span",{"aria-hidden":!0,style:{width:9,height:9,flexShrink:0,background:V?.color??c.border}}),i.jsx("span",{title:V?.description,style:{color:c.textPrimary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:_}),i.jsx("span",{style:{color:c.textMuted,fontVariantNumeric:"tabular-nums"},children:k.version}),te>0&&i.jsxs("span",{title:`${te} block ID(s) skipped: another package already defines them`,style:{fontSize:9,color:c.accent,border:`1px solid ${c.accent}`,borderRadius:3,padding:"0 3px"},children:["⚠ ",te]}),z&&i.jsxs("button",{type:"button",onClick:()=>K(_,z),title:`Version ${z} is available. Click to update.`,style:{...se,padding:"0 5px",fontSize:10,color:c.accent,borderColor:c.accent},children:[z," available"]}),i.jsx("button",{type:"button",onClick:()=>L(_),title:"Remove package",style:{marginLeft:"auto",background:"none",border:"none",color:c.textMuted,fontSize:15,lineHeight:1,cursor:"pointer"},children:"×"})]},_)}),i.jsxs("div",{style:{display:"flex",gap:6,marginTop:4},children:[i.jsxs("select",{value:l,onChange:k=>x(k.target.value),style:{...G,flex:1},children:[i.jsx("option",{value:"",children:v.length?"Add package…":"No more packages"}),v.map(k=>i.jsxs("option",{value:F(k),children:[F(k)," ",k.version]},F(k)))]}),B&&i.jsx("input",{value:y,onChange:k=>g(k.target.value),placeholder:H.get(l)?.version??"version",style:{...G,width:64}}),i.jsx("button",{type:"button",onClick:Q,disabled:!l,style:{...se,opacity:l?1:.4,cursor:l?"pointer":"default"},children:"Add"})]}),r&&r.length>0&&i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:r.map(k=>i.jsx("button",{type:"button",onClick:()=>mo(k,t,n),title:k.title,style:se,children:k.label},k.label))}),i.jsx("button",{type:"button",onClick:()=>O(k=>!k),style:{alignSelf:"flex-start",background:"none",border:"none",padding:0,color:c.textMuted,fontSize:10,cursor:"pointer"},children:B?"Hide version choice":"Choose a specific version…"})]})}const lr="#c08820";function Xt({mouths:e,w:t,isEmpty:n}){const r=U();return i.jsx("g",{style:{pointerEvents:"none"},children:e.map(o=>i.jsxs("g",{children:[o.dividerY!==null&&i.jsxs("g",{style:{pointerEvents:"all"},children:[i.jsx("title",{children:Pt(o.name,it)}),i.jsx("rect",{x:0,y:o.dividerY,width:t,height:Ct,fill:"transparent"}),i.jsx("text",{x:11,y:o.dividerY+Ct/2+4,fill:r.blockText,fontSize:10,fontWeight:"bold",fontFamily:"sans-serif",style:{userSelect:"none"},children:o.name})]}),n(o.index)&&i.jsxs("g",{style:{pointerEvents:"all"},children:[i.jsx("title",{children:Pt(o.name,it)}),i.jsx("rect",{x:o.x+3,y:o.y+3,width:Math.max(60,o.name.length*6+20),height:o.h-6,rx:3,fill:"transparent",stroke:lr,strokeWidth:1,strokeDasharray:"4,3"}),i.jsx("text",{x:o.x+10,y:o.y+o.h/2+3,fill:r.textMuted,fontSize:9,fontFamily:"sans-serif",fontStyle:"italic",style:{userSelect:"none"},children:o.name})]})]},o.index))})}function Wn({name:e,type:t,w:n,h:r}){const o=U();return i.jsx("text",{x:n/2,y:r/2+3,textAnchor:"middle",fill:o.textMuted,fontSize:9,fontFamily:"sans-serif",fontStyle:"italic",style:{userSelect:"none",pointerEvents:"none"},children:Qo(e,t,n)})}function qn({name:e,w:t,h:n}){const r=U();return i.jsxs(i.Fragment,{children:[i.jsx("rect",{x:.5,y:.5,width:t-1,height:n-1,rx:(n-1)/2,fill:"transparent",stroke:r.textMuted,strokeWidth:1,strokeDasharray:"3,2"}),i.jsx("text",{x:t/2,y:n/2+3,textAnchor:"middle",fill:r.textMuted,fontSize:9,fontFamily:"sans-serif",style:{userSelect:"none",pointerEvents:"none"},children:_n(e)})]})}const ar=5;function dr({w:e,title:t,onRemove:n}){const r=U();return i.jsxs("g",{transform:`translate(${e-2},-1)`,onPointerDown:o=>o.stopPropagation(),onClick:o=>{o.stopPropagation(),n()},style:{cursor:"pointer"},children:[i.jsx("title",{children:t}),i.jsx("circle",{r:ar,fill:r.blockBody,stroke:r.textMuted,strokeWidth:1}),i.jsx("path",{d:"M -2 -2 L 2 2 M 2 -2 L -2 2",stroke:r.blockText,strokeWidth:1.2,strokeLinecap:"round"})]})}function Vn({def:e,onPointerDown:t,isPlaced:n}){const r=U(),o=ce(e),s=ke(e),c=Qe(e),l=je(e),x=`pal-${e.id}`,y=Yt(e);return i.jsx("div",{style:{marginBottom:6,userSelect:"none",position:"relative",opacity:n?.4:1},onPointerDown:n?void 0:g=>t(g,e.id),title:n?"Already on canvas — only one instance allowed":void 0,children:i.jsxs("svg",{width:o+2,height:s+8,style:{display:"block",cursor:n?"not-allowed":"grab",overflow:"visible"},children:[i.jsx("defs",{children:i.jsx("clipPath",{id:x,children:i.jsx("path",{d:y})})}),i.jsxs("g",{transform:"translate(1, 1)",children:[i.jsx("path",{d:y,fill:r.blockBody,stroke:r.blockBorder,strokeWidth:1.5}),i.jsx("rect",{x:0,y:0,width:4,height:s+20,fill:e.color,clipPath:`url(#${x})`}),l.length>0&&i.jsx(Xt,{mouths:l,w:o,isEmpty:()=>!0}),i.jsxs("text",{x:11,y:Ke(e)/2+4,fill:r.blockText,fontSize:11,fontWeight:"bold",fontFamily:"sans-serif",style:{userSelect:"none",pointerEvents:"none"},children:[e.name,e.blockType==="query"&&e.returnType&&i.jsx("tspan",{fill:r.textMuted,fontSize:9,fontWeight:"normal",children:` [${e.returnType}]`})]}),n&&i.jsx("text",{x:o/2,y:s/2+4,textAnchor:"middle",fill:r.textMuted,fontSize:9,fontFamily:"sans-serif",style:{userSelect:"none",pointerEvents:"none"},children:"✓ on canvas"}),c.map(g=>{const B=e.params[g.index];return i.jsxs("g",{transform:`translate(${g.x},${g.y})`,children:[i.jsx("title",{children:On(B)}),g.collapsed?i.jsx(qn,{name:B.name,w:g.w,h:g.h}):i.jsxs(i.Fragment,{children:[i.jsx("path",{d:Ut(g.type,g.w,g.h),fill:r.socketBody,stroke:r.blockBorder,strokeWidth:1}),i.jsx(Wn,{name:B.name,type:g.type,w:g.w,h:g.h})]})]},g.index)}),e.blockType==="start"&&e.provides&&e.provides.length>0&&i.jsxs("g",{children:[i.jsx("line",{x1:8,y1:Be,x2:o-8,y2:Be,stroke:"rgba(255,255,255,0.15)",strokeWidth:1}),Wt(e).map(g=>{const O=N(g.id)?.color??e.color,w=g.w,L=Pn;return i.jsxs("g",{transform:`translate(${g.x}, ${g.y})`,children:[i.jsx("rect",{x:0,y:0,width:w,height:L,rx:10,fill:O,opacity:.82,stroke:"rgba(255,255,255,0.25)",strokeWidth:1}),i.jsx("text",{x:w/2,y:L/2+3.5,textAnchor:"middle",fill:"white",fontSize:9.5,fontFamily:"sans-serif",fontWeight:"bold",style:{userSelect:"none",pointerEvents:"none"},children:g.name})]},g.id)})]})]})]})})}function ur({cat:e,defs:t,collapsed:n,onToggle:r,onPointerDown:o,placedStartIds:s}){const c=U();return i.jsxs("div",{style:{marginBottom:2},children:[i.jsxs("button",{onClick:()=>r(e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",background:"none",border:"none",padding:"5px 0 4px",borderBottom:`1px solid ${c.border}`,cursor:"pointer",textAlign:"left",marginBottom:n?0:6},children:[i.jsx("span",{style:{color:c.accent,fontSize:8,lineHeight:1,opacity:.6},children:n?"▶":"▼"}),i.jsx("span",{style:{color:c.accent,fontSize:10,fontWeight:"bold",textTransform:"uppercase",letterSpacing:1,opacity:.85},children:e}),n&&i.jsx("span",{style:{color:c.textMuted,fontSize:9,marginLeft:"auto"},children:t.length})]}),!n&&i.jsx("div",{style:{paddingBottom:4},children:t.map(l=>i.jsx(Vn,{def:l,onPointerDown:o,isPlaced:l.blockType==="start"&&s.has(l.id)},l.id))})]})}function fr({onPointerDown:e,isDropTarget:t,registryVersion:n,packages:r,placedStartIds:o}){const s=U(),[c,l]=u.useState("blocks"),[x,y]=u.useState(""),[g,B]=u.useState(new Set),O=u.useMemo(()=>Tn().filter(m=>!m.category.startsWith("$")),[n]),w=u.useMemo(()=>Oo().filter(m=>!m.startsWith("$")),[n]),L=x.trim().toLowerCase(),H=L?O.filter(m=>m.name.toLowerCase().includes(L)):null;function S(m){B(K=>{const G=new Set(K);return G.has(m)?G.delete(m):G.add(m),G})}const v=r?.dependencies.length??0,Q=m=>({flex:1,background:"none",border:"none",borderBottom:`2px solid ${c===m?s.accent:"transparent"}`,color:c===m?s.accent:s.textMuted,fontSize:10,fontWeight:"bold",textTransform:"uppercase",letterSpacing:1,padding:"8px 0",cursor:"pointer",transition:"color 0.15s, border-color 0.15s"});return i.jsxs("div",{style:{width:260,minWidth:260,backgroundColor:s.paletteBg,borderRight:`1px solid ${s.border}`,display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[r&&i.jsxs("div",{style:{display:"flex",borderBottom:`1px solid ${s.border}`,flexShrink:0,background:s.paletteHeaderBg},children:[i.jsx("button",{style:Q("blocks"),onClick:()=>l("blocks"),children:"Blocks"}),i.jsxs("button",{style:Q("packages"),onClick:()=>l("packages"),children:["Packages",v>0?` · ${v}`:""]})]}),c==="blocks"&&i.jsxs(i.Fragment,{children:[i.jsx("div",{style:{padding:"8px 10px 6px",flexShrink:0},children:i.jsx("input",{type:"search",placeholder:"Search blocks…",value:x,onChange:m=>y(m.target.value),style:{width:"100%",boxSizing:"border-box",background:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:4,color:s.textPrimary,fontSize:11,padding:"5px 9px",outline:"none"}})}),i.jsx("div",{style:{flex:1,overflowY:"auto",padding:"4px 10px 0"},children:H?H.length>0?H.map(m=>i.jsx(Vn,{def:m,onPointerDown:e,isPlaced:m.blockType==="start"&&o.has(m.id)},m.id)):i.jsx("div",{style:{color:s.textMuted,fontSize:11,padding:"12px 0",textAlign:"center"},children:"No blocks match"}):w.map(m=>i.jsx(ur,{cat:m,defs:O.filter(K=>K.category===m),collapsed:g.has(m),onToggle:S,onPointerDown:e,placedStartIds:o},m))}),i.jsx("div",{style:{flexShrink:0,margin:"8px 10px 10px",padding:"7px 10px",borderRadius:4,background:t?s.deleteActiveBg:"transparent",border:`1px dashed ${t?s.deleteActiveBorder:s.deleteBorder}`,color:t?s.deleteActiveText:s.deleteText,textAlign:"center",fontSize:10,fontWeight:"bold",letterSpacing:.5,textTransform:"uppercase",transition:"background 0.12s, color 0.12s, border-color 0.12s",pointerEvents:"none",userSelect:"none"},children:t?"Release to delete":"Drag here to delete"})]}),c==="packages"&&r&&i.jsx(cr,{...r})]})}function hr(e,t,n){let r=e;for(;;)if(r.embeddedInBlockId){const o=n.get(r.embeddedInBlockId);if(!o)return!1;r=o}else if(r.parentBlockId){const o=n.get(r.parentBlockId);if(!o)return!1;r=o}else return N(r.definitionId)?.provides?.some(s=>s.id===t)??!1}function ht(e){const{block:t,allBlocks:n,onPointerDown:r,onBlockClick:o,onSocketClick:s,editingSocket:c,onSocketCommit:l,onSocketCancelEdit:x,onOutputDrag:y,isGhost:g,draggingIds:B,provisionalIds:O,onSocketInput:w,onParamRemove:L,embedded:H}=e,S=U(),v=N(t.definitionId),Q=B?.has(t.instanceId)??!1,m=O?.has(t.instanceId)??!1,K=(h,ee,b,E)=>{const W=h?n.get(h):void 0;return W?i.jsx("g",{transform:`translate(${ee},${b})`,children:i.jsx(ht,{block:W,allBlocks:n,onPointerDown:r,onBlockClick:o,onSocketClick:s,editingSocket:c,onSocketCommit:l,onSocketCancelEdit:x,onOutputDrag:y,isGhost:g,draggingIds:B,provisionalIds:O,onSocketInput:w,onParamRemove:L,embedded:!0})},E):null};if(!v){const h=r?E=>{E.stopPropagation(),r(E,t.instanceId)}:void 0,ee=o?E=>{E.stopPropagation(),o(t.instanceId)}:void 0,b=t.definitionId.replace(/^__coll__/,"").slice(0,16);return i.jsxs("g",{transform:g||H?void 0:`translate(${t.x},${t.y})`,opacity:Q?.35:.85,children:[i.jsxs("g",{onPointerDown:h,onClick:ee,style:{cursor:"grab"},children:[i.jsx("rect",{x:0,y:0,width:160,height:Ue,rx:3,fill:"rgba(160,40,40,0.18)",stroke:"#c05050",strokeWidth:1.5,strokeDasharray:"5,3"}),i.jsxs("text",{x:8,y:16,fill:"#c05050",fontSize:10,fontFamily:"sans-serif",fontStyle:"italic",style:{userSelect:"none",pointerEvents:"none"},children:["⚠ ",b," (missing)"]})]}),K(t.nextBlockId,0,Ue,"next")]})}const G=ce(v,t.paramSlots,n),se=ke(v,t.paramSlots,n),Z=Ke(v),k=Qe(v,t.paramSlots,n),_=je(v,t.paramSlots,n),V=Q?.35:m?.6:g&&!H?.75:1,z=`clip-${g?"g":"c"}-${t.instanceId}`,te=Yt(v,t.paramSlots,n),J=r?h=>{h.stopPropagation(),r(h,t.instanceId)}:void 0,Re=o?h=>{h.stopPropagation(),o(t.instanceId)}:void 0;if(v.category.startsWith("$")&&!g&&!hr(t,v.id,n)){const h=ce(v),ee=ge,b=Vt(v.returnType??"string",h,ee);return i.jsxs("g",{transform:g||H?void 0:`translate(${t.x},${t.y})`,opacity:Q?.35:.85,onPointerDown:J,onClick:Re,style:{cursor:"grab"},children:[i.jsx("path",{d:b,fill:"rgba(180,100,0,0.15)",stroke:"#c08820",strokeWidth:1.5,strokeDasharray:"5,3"}),i.jsxs("text",{x:h/2,y:ee/2+3.5,textAnchor:"middle",fill:"#c08820",fontSize:9,fontFamily:"sans-serif",fontStyle:"italic",style:{userSelect:"none",pointerEvents:"none"},children:["⚠ ",v.name]})]})}return i.jsxs("g",{transform:g||H?void 0:`translate(${t.x},${t.y})`,opacity:V,onPointerDown:J,onClick:Re,style:{cursor:g?"grabbing":"grab"},children:[i.jsx("defs",{children:i.jsx("clipPath",{id:z,children:i.jsx("path",{d:te})})}),i.jsx("path",{d:te,fill:S.blockBody,stroke:m?S.accent:S.blockBorder,strokeWidth:1.5,strokeDasharray:m?"4,3":void 0}),i.jsx("rect",{x:0,y:0,width:4,height:se+20,fill:v.color,clipPath:`url(#${z})`}),i.jsxs("text",{x:11,y:Z/2+4,fill:S.blockText,fontSize:11,fontWeight:"bold",fontFamily:"sans-serif",style:{userSelect:"none",pointerEvents:"none"},children:[v.name,v.blockType==="query"&&v.returnType&&i.jsx("tspan",{fill:S.textMuted,fontSize:9,fontWeight:"normal",children:` [${v.returnType}]`})]}),v.blockType==="start"&&v.provides&&v.provides.length>0&&i.jsxs("g",{children:[i.jsx("line",{x1:8,y1:Be,x2:G-8,y2:Be,stroke:"rgba(255,255,255,0.15)",strokeWidth:1}),Wt(v).map(h=>{const b=N(h.id)?.color??v.color,E=h.w,W=Pn,ne=!g&&!H;return i.jsxs("g",{transform:`translate(${h.x}, ${h.y})`,onPointerDown:ne?fe=>{fe.stopPropagation(),y?.(fe,h.id)}:void 0,style:{cursor:ne?"grab":"default"},children:[i.jsx("rect",{x:0,y:0,width:E,height:W,rx:10,fill:b,opacity:.82,stroke:"rgba(255,255,255,0.25)",strokeWidth:1}),i.jsx("text",{x:E/2,y:W/2+3.5,textAnchor:"middle",fill:"white",fontSize:9.5,fontFamily:"sans-serif",fontWeight:"bold",style:{userSelect:"none",pointerEvents:"none"},children:h.name})]},h.id)})]}),k.map(h=>{const ee=t.paramSlots[h.index],b=ee?.queryBlockId,E=b?n.get(b):null,W=v.params[h.index],ne=W.name,fe=On(W),Ne=W.optional&&L&&!g?i.jsx(dr,{w:h.w,title:`Leave out ${ne}`,onRemove:()=>L(t.instanceId,h.index)}):null;if(E)return i.jsxs("g",{children:[i.jsx("title",{children:fe}),K(b,h.x,h.y,"query"),Ne&&i.jsx("g",{transform:`translate(${h.x},${h.y})`,children:Ne})]},h.index);const Ce=ee?.textValue,be=c?.blockId===t.instanceId&&c?.slotIndex===h.index;if(h.collapsed&&!be)return i.jsxs("g",{transform:`translate(${h.x},${h.y})`,onPointerDown:j=>j.stopPropagation(),onClick:j=>{j.stopPropagation(),s?.(t.instanceId,h.index)},style:{cursor:"pointer"},children:[i.jsx("title",{children:`${fe}: click to type a value, or drop a ${h.type} query here`}),i.jsx(qn,{name:ne,w:h.w,h:h.h})]},h.index);const Oe=h.collapsed?Math.max(h.w,lt(h.type).w):h.w,le=h.collapsed?lt(h.type).h:h.h;return i.jsxs("g",{transform:`translate(${h.x},${h.y+(h.h-le)/2})`,onPointerDown:j=>j.stopPropagation(),onClick:j=>{j.stopPropagation(),s?.(t.instanceId,h.index)},style:{cursor:"text"},children:[i.jsx("title",{children:fe}),i.jsx("path",{d:Ut(h.type,Oe,le),fill:be?S.blockBorder:S.socketBody,stroke:S.blockBorder,strokeWidth:be?1.5:1}),be?i.jsx("foreignObject",{x:0,y:0,width:Oe,height:le,children:i.jsx("input",{autoFocus:!0,defaultValue:Ce??"",onChange:j=>w?.(t.instanceId,h.index,j.target.value),onKeyDown:j=>{j.stopPropagation(),j.key==="Enter"&&l?.(t.instanceId,h.index,j.target.value),j.key==="Escape"&&x?.()},onBlur:j=>l?.(t.instanceId,h.index,j.target.value),onPointerDown:j=>j.stopPropagation(),style:{width:"100%",height:"100%",background:"transparent",border:"none",outline:"none",color:S.blockText,fontSize:10,fontFamily:"sans-serif",textAlign:"center",padding:"0 4px",boxSizing:"border-box",caretColor:S.blockText}})}):Ce?i.jsx("text",{x:h.w/2,y:h.h/2+4,textAnchor:"middle",fill:S.blockText,fontSize:10,fontFamily:"sans-serif",fontStyle:m?"italic":void 0,style:{userSelect:"none",pointerEvents:"none"},children:Ce}):i.jsx(Wn,{name:ne,type:h.type,w:h.w,h:h.h}),!be&&Ne]},h.index)}),_.length>0&&i.jsx(Xt,{mouths:_,w:G,isEmpty:h=>!t.paramSlots[h]?.commandBlockId}),_.map(h=>K(t.paramSlots[h.index]?.commandBlockId,h.x,h.y,`mouth-${h.index}`)),K(t.nextBlockId,0,se,"next")]})}const Un=u.forwardRef(({blocks:e,draggingIds:t,provisionalIds:n,onBlockPointerDown:r,onBlockClick:o,onSocketClick:s,editingSocket:c,onSocketInput:l,onSocketCommit:x,onSocketCancelEdit:y,onParamRemove:g,onOutputDrag:B,overlay:O},w)=>{const L=U(),H=[...e.values()].filter(S=>!S.embeddedInBlockId&&!S.parentBlockId);return i.jsxs("svg",{ref:w,style:{flex:1,background:L.canvasBg,display:"block"},onPointerDown:S=>{S.target===S.currentTarget&&S.preventDefault()},children:[i.jsx("defs",{children:i.jsx("pattern",{id:"grid",width:"28",height:"28",patternUnits:"userSpaceOnUse",children:i.jsx("circle",{cx:"14",cy:"14",r:"0.7",fill:L.gridDot})})}),i.jsx("rect",{width:"100%",height:"100%",fill:"url(#grid)"}),H.map(S=>i.jsx(ht,{block:S,allBlocks:e,onPointerDown:r,onBlockClick:o,onSocketClick:s,draggingIds:t,provisionalIds:n,editingSocket:c,onSocketInput:l,onSocketCommit:x,onSocketCancelEdit:y,onParamRemove:g,onOutputDrag:B},S.instanceId)),O]})});Un.displayName="Canvas";function Yn({onSelect:e}){const t=U();return i.jsx("div",{style:{display:"flex",gap:4},children:qe.map(n=>i.jsx("button",{onClick:()=>e(n),style:{background:t.id===n.id?t.switcherActiveBg:t.switcherBg,border:`1px solid ${t.switcherBorder}`,borderRadius:4,padding:"2px 9px",color:t.id===n.id?t.switcherActiveText:t.switcherText,fontSize:10,fontWeight:t.id===n.id?"bold":"normal",letterSpacing:.5,cursor:"pointer",transition:"color 0.1s, background 0.1s"},children:n.label},n.id))})}function pr({canUndo:e,canRedo:t,onUndo:n,onRedo:r,notice:o,extra:s}){const c=U(),l=x=>({width:28,height:24,padding:0,background:c.paletteBg,color:x?c.textPrimary:c.textMuted,border:`1px solid ${c.border}`,borderRadius:4,fontSize:14,lineHeight:1,cursor:x?"pointer":"default",opacity:x?1:.5});return i.jsxs("div",{style:{position:"absolute",top:8,right:8,display:"flex",alignItems:"center",gap:6,pointerEvents:"none"},children:[o&&i.jsx("span",{style:{fontSize:11,color:c.textPrimary,background:c.paletteBg,border:`1px solid ${c.accent}`,borderRadius:4,padding:"3px 8px"},children:o}),s&&i.jsx("div",{style:{pointerEvents:"auto"},children:s}),i.jsx("button",{type:"button",title:"Undo (Ctrl+Z)","aria-label":"Undo",disabled:!e,onClick:n,style:{...l(e),pointerEvents:"auto"},children:"↶"}),i.jsx("button",{type:"button",title:"Redo (Ctrl+Shift+Z)","aria-label":"Redo",disabled:!t,onClick:r,style:{...l(t),pointerEvents:"auto"},children:"↷"})]})}function xr(e){try{return localStorage.getItem(e)}catch{return null}}function gr(e,t){try{localStorage.setItem(e,t)}catch{}}let we=null;function yr(e){we===null&&(we=e)}function mr(e){we===e&&(we=null)}function kr(e){we=e}function br(e){return we===null||we===e}function Ir({writers:e,onExport:t}){const n=U(),[r,o]=u.useState(!1);return i.jsxs("div",{style:{position:"relative"},children:[i.jsx("button",{type:"button",onClick:()=>o(s=>!s),"aria-expanded":r,style:{height:24,padding:"0 8px",fontSize:11,background:n.paletteBg,color:n.textPrimary,border:`1px solid ${n.border}`,borderRadius:4,cursor:"pointer"},children:"Export ▾"}),r&&i.jsx("div",{role:"menu",style:{position:"absolute",top:28,right:0,minWidth:120,zIndex:10,background:n.paletteBg,border:`1px solid ${n.border}`,borderRadius:4,padding:3},children:e.map(s=>i.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{o(!1),t(s)},style:{display:"block",width:"100%",textAlign:"left",padding:"4px 8px",fontSize:11,background:"none",border:"none",color:n.textPrimary,cursor:"pointer"},children:[s.label," ",i.jsxs("span",{style:{color:n.textMuted},children:[".",s.fileExtension]})]},s.id))})]})}function vr(e,t){const n=N(e.definitionId);if(!n)return{w:160,h:Ue};const r=n.blockType==="query"?qt(e,t):Ln(e.instanceId,t);return{w:ce(n,e.paramSlots,t),h:r}}function Sr({peers:e,blocks:t,layout:n}){const r=U();return i.jsx("g",{style:{pointerEvents:"none"},children:e.map(o=>{const{color:s}=o,c=[];if(o.typing){const l=t.get(o.typing.blockId),x=n.get(o.typing.blockId),y=l&&N(l.definitionId),g=y&&l&&Qe(y,l.paramSlots,t).find(B=>B.index===o.typing.slot);x&&g&&c.push(i.jsxs("g",{transform:`translate(${x.x+g.x},${x.y+g.y})`,children:[i.jsx("path",{d:Ut(g.type,g.w,g.h),fill:r.socketBody,stroke:s,strokeWidth:2}),i.jsxs("text",{x:g.w/2,y:g.h/2+4,textAnchor:"middle",fill:s,fontSize:10,fontFamily:"sans-serif",children:[o.typing.text,"|"]})]},"typing"))}if(o.drag&&"leadId"in o.drag){const l=t.get(o.drag.leadId),x=n.get(o.drag.leadId);if(l&&x){const{w:y,h:g}=vr(l,t);c.push(i.jsx("rect",{x:x.x-3,y:x.y-3,width:y+6,height:g+6,rx:5,fill:"none",stroke:s,strokeWidth:1.5,strokeDasharray:"5,3"},"origin"),i.jsxs("g",{transform:`translate(${o.drag.at.x},${o.drag.at.y})`,opacity:.5,children:[i.jsx(ht,{block:l,allBlocks:t,isGhost:!0}),i.jsx("rect",{x:-3,y:-3,width:y+6,height:g+6,rx:5,fill:"none",stroke:s,strokeWidth:1.5})]},"ghost"))}}if(o.drag&&"definitionId"in o.drag){const l=N(o.drag.definitionId),x=l?ce(l):120,y=l?ke(l):Ue;c.push(i.jsxs("g",{transform:`translate(${o.drag.at.x},${o.drag.at.y})`,children:[i.jsx("rect",{width:x,height:y,rx:4,fill:s,fillOpacity:.12,stroke:s,strokeWidth:1.5,strokeDasharray:"5,3"}),i.jsx("text",{x:8,y:y/2+4,fill:s,fontSize:11,fontWeight:"bold",fontFamily:"sans-serif",children:l?.name??o.drag.definitionId})]},"new"))}if(o.cursor){const l=o.name.length*6.5+10;c.push(i.jsxs("g",{transform:`translate(${o.cursor.x},${o.cursor.y})`,children:[i.jsx("path",{d:"M 0 0 L 0 14 L 4 10.5 L 7 17 L 9.5 16 L 6.5 9.5 L 11 9.5 Z",fill:s,stroke:"white",strokeWidth:1}),i.jsx("rect",{x:12,y:14,width:l,height:16,rx:3,fill:s}),i.jsx("text",{x:17,y:26,fill:"white",fontSize:10,fontFamily:"sans-serif",children:o.name})]},"cursor"))}return i.jsx("g",{children:c},o.clientId)})})}const $r="local";function Br(e,t,n){const r=e==="undo"?"Couldn't undo":e==="redo"?"Couldn't redo":"Your change was undone";return t==="HOST_REJECTED"?`${r}: ${n}`:`${r}: ${{TEXT_CHANGED:"someone else changed that parameter",PLACE_OCCUPIED:"someone else put a block there first",BLOCK_NOT_FOUND:"a block it needs was deleted",BLOCK_CHANGED:"someone else changed those blocks",NOT_AT_PLACE:"someone else moved that block",NOT_A_ROOT:"someone else moved that block",POSITION_CHANGED:"someone else moved that block",DEPENDENCIES_CHANGED:"someone else changed the packages"}[t]??"the canvas has changed"}.`}function nt(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function wr(e,t){return e.embeddedInBlockId?t.get(e.embeddedInBlockId)?.paramSlots[e.embeddedSlotIndex]?.commandBlockId===e.instanceId:!1}function jr(e){return e.kind==="next"?{next:e.blockId}:{mouth:e.blockId,slot:e.slotIndex}}async function hn(e,t){if(!e||!t)return!1;const n=new Map(e.map(c=>[ze(c),c])),r=new Set(We().map(c=>c.info.id).filter(c=>c.startsWith(dt))),o=[...r].filter(c=>!n.has(c)),s=[...n].filter(([c])=>!r.has(c));o.forEach(Ht);for(const[c,l]of s)await Lt({id:c,name:F(l),description:"",url:t(l),builtIn:!1});return o.length>0||s.length>0}function Cr(e){const t=new Map(We().map(r=>[r.info.id,r.info.name])),n=new Map;return e.forEach(r=>{const o=Cn(r.definitionId);if(!o?.startsWith(dt))return;const s=t.get(o);n.set(s,(n.get(s)??0)+1)}),n}function Tr(e,t,n){const r=ct(e);return{instanceId:nt(),definitionId:e,x:t,y:n,nextBlockId:null,parentBlockId:null,embeddedInBlockId:null,embeddedSlotIndex:-1,paramSlots:r.params.map(()=>({textValue:null,queryBlockId:null,commandBlockId:null}))}}function Mt(e,t){const n=[];let r=e;for(;r;)n.push(r),r=t.get(r)?.nextBlockId??null;return n}function Dt(e,t){const n=t.get(e);return n?.parentBlockId?Dt(n.parentBlockId,t):n&&wr(n,t)?Dt(n.embeddedInBlockId,t):e}function At(e,t){const n=N(e.definitionId);if(!n)return`[missing:${e.definitionId}]`;const r=e.paramSlots.map((o,s)=>{const c=n.params[s];if(c&&Ae(n,c)){const x=(o.commandBlockId?Mt(o.commandBlockId,t):[]).map(y=>t.get(y)).filter(Boolean).map(y=>At(y,t));return x.length>0?`{ ${x.join("; ")} }`:"{ }"}if(o.queryBlockId){const l=t.get(o.queryBlockId);if(l)return At(l,t)}return o.textValue!==null&&o.textValue!==void 0?n.params[s]?.type==="string"?`"${o.textValue}"`:o.textValue:"_"});return`${n.id}(${r.join(", ")})`}function Er({ghostPos:e,blocks:t}){const n=U();if(!e)return null;if(e.instanceId){const x=t.get(e.instanceId);if(x)return i.jsx("svg",{style:{position:"fixed",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:9999},children:i.jsx("g",{transform:`translate(${e.x},${e.y})`,opacity:.8,children:i.jsx(ht,{block:x,allBlocks:t,isGhost:!0})})})}const r=ct(e.defId),o=ke(r),s=r.blockType==="command",c=Yt(r),l=je(r);return i.jsxs("svg",{style:{position:"fixed",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:9999},children:[s&&i.jsx("defs",{children:i.jsx("clipPath",{id:"ghost-pal-clip",children:i.jsx("path",{d:c})})}),i.jsxs("g",{transform:`translate(${e.x},${e.y})`,opacity:.8,children:[i.jsx("path",{d:c,fill:s?n.blockBody:r.color,stroke:s?n.blockBorder:"rgba(0,0,0,0.4)",strokeWidth:1.5}),s&&i.jsx("rect",{x:0,y:0,width:4,height:o+20,fill:r.color,clipPath:"url(#ghost-pal-clip)"}),l.length>0&&i.jsx(Xt,{mouths:l,w:ce(r),isEmpty:()=>!0}),i.jsx("text",{x:11,y:Ke(r)/2+4,fill:s?n.blockText:"white",fontSize:11,fontWeight:"bold",fontFamily:"sans-serif",style:{userSelect:"none"},children:r.name})]})]})}function Pr(e,t){return e.returnType===t||(e.usableAs?.includes(t)??!1)}function Xn({blocksUrl:e="/blocks.json",blocksUrls:t,onRun:n,onThemeChange:r,navTabs:o,initialState:s,onSave:c,themeId:l,hideTitleBar:x,getStateRef:y,additionalBlocks:g,dependencies:B,onDependenciesChange:O,packageBlocksUrl:w,availablePackages:L,packageActions:H,collaboration:S,scriptWriters:v,onExport:Q}){const[m,K]=u.useState(()=>{if(l)return qe.find(d=>d.id===l)??Me;const a=xr("cardcq-theme");return qe.find(d=>d.id===a)??Me}),[G,se]=u.useState(l);l!==G&&(se(l),l&&K(qe.find(a=>a.id===l)??Me));const[Z,k]=u.useState(!1),[_,V]=u.useState(null),z=S?.commands,te=S?.clientId??$r,[J,Re]=u.useState(()=>wn({blocks:new Map((s?.blocks??[]).map(([a,d])=>[a,ye(d)])),dependencies:B??[]})),{state:h,provisionalIds:ee}=u.useMemo(()=>un(J),[J]),b=h.blocks,E=u.useRef(J),W=u.useRef(h);u.useEffect(()=>{E.current=J,W.current=h});const ne=(B??[]).map(ze).join("|"),[fe,Ne]=u.useState(ne);ne!==fe&&(Ne(ne),!z&&ne!==J.confirmed.dependencies.map(ze).join("|")&&Re(a=>({...a,confirmed:{...a.confirmed,dependencies:B??[]}})));const Ce=u.useRef(O);u.useEffect(()=>{Ce.current=O});const[be,Oe]=u.useState(null),le=u.useRef(null),j=u.useCallback(a=>{Oe(a),le.current&&clearTimeout(le.current),le.current=setTimeout(()=>Oe(null),5e3)},[]);u.useEffect(()=>()=>{le.current&&clearTimeout(le.current)},[]);const he=u.useCallback(a=>{const d=E.current;E.current=a,W.current=un(a).state,Re(a),a.confirmed.dependencies!==d.confirmed.dependencies&&Ce.current?.(a.confirmed.dependencies)},[]),Te=u.useCallback((a,d,f)=>{const p={id:d,clientId:te,baseVersion:E.current.version,command:f};if(z){he(a),z.submit(p);return}const I=an(a,p,a.version+1);I.outOfSync?(he(dn(a,d).sync),j("That change couldn't be made: the canvas has changed.")):he(I.sync)},[te,z,he,j]),oe=u.useCallback(a=>{if(!a)return;const d=nt();Te(Mo(E.current,d,a),d,a)},[Te]),pt=u.useCallback(()=>{const a=nt(),d=Do(E.current,a);d&&Te(d.sync,a,d.command)},[Te]),xt=u.useCallback(()=>{const a=nt(),d=Ao(E.current,a);d&&Te(d.sync,a,d.command)},[Te]),Ge=S?.presence,Kt=S?.presenceIntervalMs??jn,re=u.useRef(null),[Qt,Gt]=u.useState([]);u.useEffect(()=>{if(!Ge)return;const a=new No(f=>Ge.publish(f),Kt);re.current=a;const d=Ge.subscribe(f=>Gt(f.filter(p=>p.clientId!==te)));return()=>{a.updateNow({cursor:null,drag:null,typing:null}),a.dispose(),re.current=null,d(),Gt([])}},[Ge,Kt,te]),u.useEffect(()=>{if(z)return z.subscribe(a=>{if(a.type==="snapshot"){const d={blocks:new Map(a.state.blocks.map(([p,I])=>[p,ye(I)])),dependencies:a.state.dependencies},f=_o(d,a.version,E.current);he(f.sync),f.dropped>0&&j("Reloaded from the server: your unconfirmed changes were discarded.")}else if(a.type==="applied"){const d=an(E.current,a.envelope,a.version);d.outOfSync?(j("Out of sync with the server: reloading…"),z.resync?.()):he(d.sync)}else{const d=dn(E.current,a.id);he(d.sync),d.action&&j(Br(d.action.kind,a.code,a.message))}})},[z,he,j]);const[Ie]=u.useState(()=>Symbol("BlockEditor"));u.useEffect(()=>(yr(Ie),()=>mr(Ie)),[Ie]);const Zt=u.useCallback(()=>kr(Ie),[Ie]);u.useEffect(()=>{function a(d){if(!br(Ie))return;const f=d.target;if(f&&(f.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(f.tagName))||!(d.ctrlKey||d.metaKey))return;const p=d.key.toLowerCase();p==="z"&&!d.shiftKey?(d.preventDefault(),pt()):(p==="z"&&d.shiftKey||p==="y"&&!d.metaKey)&&(d.preventDefault(),xt())}return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[pt,xt,Ie]);const Kn=u.useMemo(()=>{const a=new Set;for(const d of b.values())N(d.definitionId)?.blockType==="start"&&a.add(d.definitionId);return a},[b]),[Qn,Ze]=u.useState(null),[Gn,Jt]=u.useState(new Set),[Zn,en]=u.useState(!1),[tn,gt]=u.useState(0),[Jn,yt]=u.useState([]),ae=u.useMemo(()=>Zo(b),[b,tn]);u.useEffect(()=>{y&&(y.current=()=>({blocks:[...b.entries()]}))},[b,y]);const de=u.useRef(null),mt=u.useRef(!1),Je=u.useRef(null),Le=(t??[e]).join("|"),kt=B!==void 0||S?.commands!==void 0&&w!==void 0,bt=u.useRef(kt?h.dependencies:void 0),It=u.useRef(w);u.useEffect(()=>{bt.current=kt?h.dependencies:void 0,It.current=w});const eo=h.dependencies.map(ze).join("|"),Ee=u.useRef(Promise.resolve()),[to,no]=u.useState(Le);Le!==to&&(no(Le),k(!1),V(null)),u.useEffect(()=>{let a=!1;const d=Le.split("|");return Ee.current=Ee.current.then(async()=>{if(!a)try{await Ho(d[0]);for(let f=1;f<d.length&&!a;f++)await Lt({id:`__extra_${f}__`,name:`Extra ${f}`,description:"",url:d[f],builtIn:!0});if(a||(await hn(bt.current,It.current),a))return;yt(We()),gt(f=>f+1),k(!0)}catch(f){a||V(String(f))}}),()=>{a=!0}},[Le]),u.useEffect(()=>{if(!Z)return;let a=!1;return Ee.current=Ee.current.then(async()=>{if(!a)try{if(!await hn(bt.current,It.current))return;yt(We()),gt(f=>f+1)}catch(d){V(String(d))}}),()=>{a=!0}},[Z,eo]),u.useEffect(()=>{if(!Z)return;let a=!1;return Ee.current=Ee.current.then(()=>{if(!a)try{Ht("__inline__"),g&&g.length>0&&Lo({id:"__inline__",name:"Inline",description:"",url:"",builtIn:!0},g),yt(We()),gt(d=>d+1)}catch(d){V(String(d))}}),()=>{a=!0}},[g,Z]);const pe=u.useCallback((a,d)=>{const f=Je.current?.getBoundingClientRect()??{left:0,top:0};return{x:a-f.left,y:d-f.top}},[]),nn=u.useCallback((a,d,f,p,I)=>{if(N(f)?.blockType!=="command")return null;let M=null;const D=T=>{(!M||T.dist<M.dist)&&(M=T)},R=(T,q)=>{const Y=Math.abs(a-T),$=Math.abs(d-q);return Y<40&&$<24?Math.hypot(Y,$):null};return b.forEach(T=>{if(I.has(T.instanceId))return;const q=N(T.definitionId),Y=ae.get(T.instanceId);if(!(!q||q.blockType==="query"||!Y)){if(!T.nextBlockId||T.nextBlockId===p){const $=Y.y+ke(q,T.paramSlots,b),ie=R(Y.x,$);ie!==null&&D({kind:"next",blockId:T.instanceId,snapX:Y.x,snapY:$,dist:ie})}for(const $ of je(q,T.paramSlots,b)){const ie=Y.x+$.x,et=Y.y+$.y,tt=R(ie,et);tt!==null&&D({kind:"mouth",blockId:T.instanceId,slotIndex:$.index,snapX:ie,snapY:et,dist:tt})}}}),M},[b,ae]),on=u.useCallback((a,d,f,p,I)=>{const C=N(f);if(!C||C.blockType!=="query")return null;const M=20;let D=null;return b.forEach(R=>{if(I.has(R.instanceId))return;const T=N(R.definitionId),q=ae.get(R.instanceId);if(!T||!q)return;Qe(T,R.paramSlots,b).forEach($=>{if(!Pr(C,$.type))return;const ie=R.paramSlots[$.index]?.queryBlockId;if(ie&&ie!==p)return;const et=q.x+$.x+$.w/2,tt=q.y+$.y+$.h/2,sn=Math.abs(a+$.w/2-et),cn=Math.abs(d+$.h/2-tt);if(sn<$.w/2+M&&cn<$.h/2+M){const ln=Math.hypot(sn,cn);(!D||ln<D.dist)&&(D={blockId:R.instanceId,slotIndex:$.index,snapX:q.x+$.x,snapY:q.y+$.y,dist:ln})}})}),D},[b,ae]),oo=u.useCallback(a=>{if(de.current?.moved)return;const d=Dt(a,b),p=Mt(d,b).map(I=>b.get(I)).filter(Boolean).map(I=>At(I,b));n?.(p)},[b,n]),[ro,vt]=u.useState(null),He=u.useRef(null),so=u.useCallback((a,d)=>{if(de.current?.moved)return;const f=W.current.blocks.get(a)?.paramSlots[d]?.textValue??null;He.current={blockId:a,slotIndex:d,startText:f},vt(He.current),re.current?.updateNow({typing:{blockId:a,slot:d,text:f??""}})},[]),io=u.useCallback((a,d,f)=>{re.current?.update({typing:{blockId:a,slot:d,text:f}})},[]),co=u.useCallback((a,d,f)=>{const p=He.current;He.current=null,vt(null),!(!p||p.blockId!==a||p.slotIndex!==d)&&(re.current?.updateNow({typing:null}),oe(jt(a,d,p.startText,f)))},[oe]),lo=u.useCallback(()=>{He.current=null,vt(null),re.current?.updateNow({typing:null})},[]),ao=u.useCallback((a,d)=>{const f=W.current,p=f.blocks.get(a),I=p?.paramSlots[d];if(!p||!I)return;if(!I.queryBlockId){oe(jt(a,d,I.textValue,null));return}const C=N(p.definitionId),M=ae.get(a)??p,D=M.x+(C?ce(C,p.paramSlots,f.blocks):0)+24;oe(wt(f,I.queryBlockId,{x:D,y:M.y},null))},[ae,oe]),uo=u.useCallback(a=>{const d=W.current,f=new Set(a.map(F)),p=new Set(d.dependencies.filter(C=>!f.has(F(C))).map(ze)),I=[...d.blocks.values()].filter(C=>p.has(Cn(C.definitionId)??"")).map(C=>C.instanceId);oe(Bn(d,a,I))},[oe]),fo=u.useCallback(a=>{K(a),l||gr("cardcq-theme",a.id),r?.(a)},[r,l]),rn=u.useCallback((a,d)=>{a.preventDefault();const f=ct(d),p=ce(f),I=ke(f);de.current={type:"palette",defId:d,offsetX:p/2,offsetY:I/2,startClientX:a.clientX,startClientY:a.clientY,moved:!1},Ze({x:a.clientX-p/2,y:a.clientY-I/2,defId:d}),a.target.setPointerCapture(a.pointerId)},[]),ho=u.useCallback((a,d)=>{a.preventDefault();const f=b.get(d);if(!f)return;const{x:p,y:I}=pe(a.clientX,a.clientY),{x:C,y:M}=ae.get(d)??f,D=p-C,R=I-M,q=N(f.definitionId)?.blockType==="query"?[d]:Mt(d,b);de.current={type:"canvas",defId:f.definitionId,instanceId:d,carriedIds:q,offsetX:D,offsetY:R,startClientX:a.clientX,startClientY:a.clientY,moved:!1},Jt(new Set([d])),Ze({x:a.clientX-D,y:a.clientY-R,defId:f.definitionId,instanceId:d}),a.target.setPointerCapture(a.pointerId)},[b,ae,pe]);u.useEffect(()=>{function a(f){const p=de.current;if(!p)return;let I=!1;if(!p.moved&&(Math.abs(f.clientX-p.startClientX)>4||Math.abs(f.clientY-p.startClientY)>4)&&(p.moved=!0,I=!0),!p.moved)return;Ze({x:f.clientX-p.offsetX,y:f.clientY-p.offsetY,defId:p.defId,instanceId:p.instanceId});const C=pe(f.clientX-p.offsetX,f.clientY-p.offsetY),M=p.type==="canvas"?{drag:{leadId:p.instanceId,at:C},cursor:pe(f.clientX,f.clientY)}:{drag:{definitionId:p.defId,at:C},cursor:pe(f.clientX,f.clientY)};if(I?re.current?.updateNow(M):re.current?.update(M),p.type==="canvas"){const D=Je.current?.getBoundingClientRect(),R=!!D&&f.clientX<D.left;R!==mt.current&&(mt.current=R,en(R))}}function d(f){const p=de.current;if(!p||(de.current=null,Ze(null),Jt(new Set),mt.current=!1,en(!1),!p.moved))return;re.current?.updateNow({drag:null});const I=Je.current?.getBoundingClientRect();if(!I)return;const C=W.current;if(p.type==="canvas"&&f.clientX<I.left){oe($n(C,p.instanceId));return}const M=f.clientX-p.offsetX-I.left,D=f.clientY-p.offsetY-I.top,R=ct(p.defId),T=p.type==="canvas"?p.instanceId:null,q=new Set(T?Xe(C.blocks,T):[]);let Y=null;if(R.blockType==="query"){const $=on(M,D,p.defId,T,q);$&&(Y={socket:$.blockId,slot:$.slotIndex})}else{const $=nn(M,D,p.defId,T,q);$&&(Y=jr($))}if(p.type==="palette"){if(f.clientX<I.left||f.clientX>I.right||f.clientY<I.top||f.clientY>I.bottom||R.blockType==="start"&&[...C.blocks.values()].some(ie=>ie.definitionId===p.defId))return;oe(Sn(C,Tr(p.defId,M,D),{x:M,y:D},Y))}else oe(wt(C,T,{x:M,y:D},Y))}return document.addEventListener("pointermove",a),document.addEventListener("pointerup",d),()=>{document.removeEventListener("pointermove",a),document.removeEventListener("pointerup",d)}},[nn,on,oe,pe]);const po=u.useCallback(a=>{de.current?.moved||re.current?.update({cursor:pe(a.clientX,a.clientY)})},[pe]),xo=u.useCallback(()=>{de.current?.moved||re.current?.updateNow({cursor:null})},[]),go=u.useCallback(a=>{const d=a.write(Hn(W.current,N));if(Q){Q(d,a);return}const f=URL.createObjectURL(new Blob([d],{type:"text/plain"})),p=document.createElement("a");p.href=f,p.download=`behavior.${a.fileExtension}`,p.click(),URL.revokeObjectURL(f)},[Q]),St={display:"flex",flexDirection:"column",flex:1,minHeight:0,width:"100%",height:"100%",overflow:"hidden",background:m.appBg,color:m.textPrimary,fontFamily:"system-ui, sans-serif",boxSizing:"border-box"},yo={display:"flex",flex:1,minHeight:0,overflow:"hidden"};return _?i.jsx(Ve.Provider,{value:m,children:i.jsxs("div",{style:{...St,alignItems:"center",justifyContent:"center",color:"#c06060",fontFamily:"monospace"},children:["Failed to load blocks: ",_]})}):Z?i.jsx(Ve.Provider,{value:m,children:i.jsxs("div",{style:St,onPointerDownCapture:Zt,onFocusCapture:Zt,children:[!x&&i.jsxs("div",{style:{flexShrink:0,display:"flex",alignItems:"center",gap:10,padding:"0 14px",height:38,background:m.titleBg,borderBottom:`1px solid ${m.border}`},children:[i.jsx("span",{style:{color:m.titlePrimaryText,fontWeight:"bold",fontSize:13,letterSpacing:1,textTransform:"uppercase"},children:"CardCQ"}),i.jsx("span",{style:{color:m.titleSecondaryText,fontSize:11,letterSpacing:.5},children:"Behavior Editor"}),o,i.jsxs("div",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:8},children:[c&&i.jsx("button",{onClick:()=>c({blocks:[...b.entries()]}),style:{padding:"3px 10px",fontSize:11,fontWeight:"bold",background:m.titleBg,color:m.titlePrimaryText,border:`1px solid ${m.border}`,borderRadius:4,cursor:"pointer",letterSpacing:.5},children:"Save"}),!l&&i.jsx(Yn,{onSelect:fo})]})]}),i.jsxs("div",{style:yo,children:[i.jsx(fr,{onPointerDown:rn,isDropTarget:Zn,registryVersion:tn,packages:kt&&(O||z)?{available:L??[],dependencies:h.dependencies,onChange:uo,actions:H,blockCounts:Cr(b),conflictCounts:new Map(Jn.filter(a=>a.info.id.startsWith(dt)).map(a=>[a.info.name,a.conflictIds.length]))}:void 0,placedStartIds:Kn}),i.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",position:"relative"},onPointerMove:po,onPointerLeave:xo,children:[i.jsx(Un,{ref:Je,blocks:b,draggingIds:Gn,provisionalIds:ee,onBlockPointerDown:ho,onBlockClick:oo,onSocketClick:so,editingSocket:ro,onSocketInput:io,onSocketCommit:co,onSocketCancelEdit:lo,onParamRemove:ao,onOutputDrag:rn,overlay:Qt.length>0?i.jsx(Sr,{peers:Qt,blocks:b,layout:ae}):null}),i.jsx(pr,{canUndo:st(J)&&J.undo.length>0,canRedo:st(J)&&J.redo.length>0,onUndo:pt,onRedo:xt,notice:be,extra:v&&v.length>0?i.jsx(Ir,{writers:v,onExport:go}):null})]})]}),i.jsx(Er,{ghostPos:Qn,blocks:b})]})}):i.jsx(Ve.Provider,{value:m,children:i.jsx("div",{style:{...St,alignItems:"center",justifyContent:"center",color:m.textMuted},children:"Loading…"})})}function Ft(e){const t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[^A-Za-z0-9]+/g,"_").replace(/^_+|_+$/g,"").toLowerCase();return/^[0-9]/.test(t)?`_${t}`:t||"_"}function _t(e){return JSON.stringify(e)}function Fn(e,t){switch(e.kind){case"text":return t==="string"?_t(e.text):t==="boolean"?e.text.toLowerCase()==="true"?"True":"False":/^-?\d+(\.\d+)?$/.test(e.text)?e.text:_t(e.text);case"query":return ot(e.node);case"body":return"None";case"empty":return"None"}}function ot(e){const t=e.args.filter(n=>n.value.kind!=="body").map(n=>Fn(n.value,n.type));return`${Ft(e.name)}(${t.join(", ")})`}function at(e,t){return e.length===0?[`${t}pass`]:e.flatMap(n=>{const r=n.args.filter(s=>s.value.kind==="body");if(r.length===0)return[`${t}${ot(n)}`];const o=`${t} `;if(r.length===1){const s=r[0].value;return[`${t}with ${ot(n)}:`,...at(s.body,o)]}return[`${t}with ${ot(n)}:`,...r.flatMap(s=>[`${o}with ${Ft(s.name)}:`,...at(s.value.body,`${o} `)])]})}const Mr={id:"python",label:"Python",fileExtension:"py",write(e){return`# Generated by the block editor
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("react/jsx-runtime"),f=require("react");function Ao(e,t,n){"dependencies"in e?n(e.dependencies(t)):e.onClick()}function G(e){return`${e.publisher}/${e.name}`}function We(e){return`${yt}${G(e)}@${e.version}`}const yt="dep:";function wn(e,t){const n=e.split(/[.-]/),o=t.split(/[.-]/);for(let r=0;r<Math.max(n.length,o.length);r++){const s=n[r]??"0",c=o[r]??"0",l=Number(s),x=Number(c),m=!isNaN(l)&&!isNaN(x)?l-x:s.localeCompare(c);if(m!==0)return m}return 0}const Oo=1;class O extends Error{code;constructor(t,n){super(n),this.name="CommandRejected",this.code=t}}function Re(e,t){switch(t.type){case"InsertBlocks":return Lo(e,t);case"RemoveBlocks":return Ho(e,t);case"MoveBlock":return zo(e,t);case"Attach":return Wo(e,t);case"Detach":return Uo(e,t);case"SetText":return Vo(e,t);case"SetDependencies":return Yo(e,t);case"Batch":return Fo(e,t);default:throw new O("INVALID_COMMAND",`Unknown command type '${t.type}'.`)}}function Ke(e){return{textValue:e?.textValue??null,queryBlockId:e?.queryBlockId??null,commandBlockId:e?.commandBlockId??null}}function ve(e){const t=qt(e)?{x:e.x,y:e.y}:{x:0,y:0};return{...e,...t,paramSlots:e.paramSlots.map(Ke)}}function Ce(e){return e==null||e===""?null:e}function Oe(e,t){const n=e.blocks.get(t);if(!n)throw new O("BLOCK_NOT_FOUND",`Block '${t}' doesn't exist.`);return n}function qt(e){return!e.parentBlockId&&!e.embeddedInBlockId}function Bn(e){const t=[];e.nextBlockId&&t.push(e.nextBlockId);for(const n of e.paramSlots)n.queryBlockId&&t.push(n.queryBlockId),n.commandBlockId&&t.push(n.commandBlockId);return t}function Qe(e,t){const n=[],o=new Set,r=[t];for(;r.length>0;){const s=r.shift();if(o.has(s))continue;const c=e.get(s);c&&(o.add(s),n.push(s),r.push(...Bn(c)))}return n}function jn(e){const t=r=>new O("NOT_A_FRAGMENT",`The blocks aren't one fragment: ${r}.`);if(e.length===0)throw new O("INVALID_COMMAND","The command has no blocks.");const n=new Map;for(const r of e){if(n.has(r.instanceId))throw t(`'${r.instanceId}' is given twice`);n.set(r.instanceId,r)}const o=e.filter(qt);if(o.length!==1)throw t(`it has ${o.length} roots`);for(const r of e){if(r.nextBlockId){const s=n.get(r.nextBlockId);if(!s||s.parentBlockId!==r.instanceId||s.embeddedInBlockId)throw t(`the block under '${r.instanceId}' doesn't match`)}if(r.paramSlots.forEach((s,c)=>{for(const l of[s.queryBlockId,s.commandBlockId]){if(!l)continue;const x=n.get(l);if(!x||x.embeddedInBlockId!==r.instanceId||x.embeddedSlotIndex!==c||x.parentBlockId)throw t(`slot ${c} of '${r.instanceId}' doesn't match`)}}),r.parentBlockId){const s=n.get(r.parentBlockId);if(!s||s.nextBlockId!==r.instanceId)throw t(`the block above '${r.instanceId}' doesn't match`)}if(r.embeddedInBlockId){const s=n.get(r.embeddedInBlockId)?.paramSlots[r.embeddedSlotIndex];if(!s||s.queryBlockId!==r.instanceId&&s.commandBlockId!==r.instanceId)throw t(`the block holding '${r.instanceId}' doesn't match`)}}if(Qe(n,o[0].instanceId).length!==e.length)throw t("not every block hangs off the root");return o[0]}function Ro(e,t){return JSON.stringify(ve(e))===JSON.stringify(ve(t))}function ut(e,t,n){const o=e.paramSlots.map(Ke);return o[t]={...o[t],...n},{...e,paramSlots:o}}function Cn(e,t){if(!Number.isInteger(t)||t<0||t>=e.paramSlots.length)throw new O("NO_SUCH_SLOT",`Block '${e.instanceId}' has no slot ${t}.`);return Ke(e.paramSlots[t])}function Tn(e,t){if(e.x!==t.x||e.y!==t.y)throw new O("POSITION_CHANGED",`Block '${e.instanceId}' isn't at (${t.x}, ${t.y}).`)}function Pn(e){if(!qt(e))throw new O("NOT_A_ROOT",`Block '${e.instanceId}' is linked, not a root.`)}const Dt=e=>`${e.publisher}/${e.name}@${e.version}`;function No(e,t){const n=new Set(e.map(Dt));return e.length===t.length&&n.size===new Set(t.map(Dt)).size&&t.every(o=>n.has(Dt(o)))}function Lo(e,t){jn(t.blocks);for(const o of t.blocks)if(e.blocks.has(o.instanceId))throw new O("ID_EXISTS",`Block '${o.instanceId}' already exists.`);const n=new Map(e.blocks);for(const o of t.blocks)n.set(o.instanceId,ve(o));return{...e,blocks:n}}function Ho(e,t){jn(t.blocks);const n=new Set;for(const r of t.blocks){const s=Oe(e,r.instanceId);if(!Ro(s,r))throw new O("BLOCK_CHANGED",`Block '${r.instanceId}' has changed.`);n.add(r.instanceId)}for(const r of e.blocks.values())if(!n.has(r.instanceId)&&Bn(r).some(s=>n.has(s)))throw new O("LINKED_FROM_OUTSIDE",`Block '${r.instanceId}' links into the blocks to remove.`);const o=new Map(e.blocks);return n.forEach(r=>o.delete(r)),{...e,blocks:o}}function zo(e,t){const n=Oe(e,t.id);Pn(n),Tn(n,t.from);const o=new Map(e.blocks);return o.set(n.instanceId,{...n,x:t.to.x,y:t.to.y}),{...e,blocks:o}}function Wo(e,t){const n=Oe(e,t.id);Pn(n),Tn(n,t.from);const o=t.to,r="next"in o?o.next:"mouth"in o?o.mouth:o.socket,s=Oe(e,r);if(Qe(e.blocks,n.instanceId).includes(r))throw new O("CYCLE",`Block '${r}' is inside the fragment of '${n.instanceId}'.`);const c=new Map(e.blocks);if("next"in o){if(s.nextBlockId)throw new O("PLACE_OCCUPIED",`Block '${r}' already has a block under it.`);return c.set(r,{...s,nextBlockId:n.instanceId}),c.set(n.instanceId,{...n,x:0,y:0,parentBlockId:r}),{...e,blocks:c}}const l=Cn(s,o.slot);if("mouth"in o){if(l.commandBlockId||l.queryBlockId)throw new O("PLACE_OCCUPIED",`Mouth ${o.slot} of '${r}' isn't empty.`);c.set(r,ut(s,o.slot,{commandBlockId:n.instanceId}))}else{if(l.queryBlockId||l.commandBlockId||l.textValue!==null)throw new O("PLACE_OCCUPIED",`Socket ${o.slot} of '${r}' isn't empty.`);c.set(r,ut(s,o.slot,{queryBlockId:n.instanceId}))}return c.set(n.instanceId,{...n,x:0,y:0,embeddedInBlockId:r,embeddedSlotIndex:o.slot}),{...e,blocks:c}}function qo(e,t,n){if("next"in n)return t.parentBlockId===n.next&&e.blocks.get(n.next)?.nextBlockId===t.instanceId;const o="mouth"in n?n.mouth:n.socket;if(t.embeddedInBlockId!==o||t.embeddedSlotIndex!==n.slot)return!1;const r=Ke(e.blocks.get(o)?.paramSlots[n.slot]);return("mouth"in n?r.commandBlockId:r.queryBlockId)===t.instanceId}function Uo(e,t){const n=Oe(e,t.id);if(!qo(e,n,t.from))throw new O("NOT_AT_PLACE",`Block '${n.instanceId}' isn't linked at the given place.`);const o=new Map(e.blocks),r=t.from;if("next"in r){const s=o.get(r.next);o.set(r.next,{...s,nextBlockId:null})}else{const s="mouth"in r?r.mouth:r.socket,c="mouth"in r?{commandBlockId:null}:{queryBlockId:null};o.set(s,ut(o.get(s),r.slot,c))}return o.set(n.instanceId,{...n,x:t.to.x,y:t.to.y,parentBlockId:null,embeddedInBlockId:null,embeddedSlotIndex:-1}),{...e,blocks:o}}function Vo(e,t){const n=Oe(e,t.blockId),o=Cn(n,t.slot);if(o.queryBlockId)throw new O("SLOT_HAS_QUERY",`Slot ${t.slot} of '${n.instanceId}' holds a query.`);if(Ce(o.textValue)!==Ce(t.from))throw new O("TEXT_CHANGED",`Slot ${t.slot} of '${n.instanceId}' has changed.`);const r=new Map(e.blocks);return r.set(n.instanceId,ut(n,t.slot,{textValue:Ce(t.to)})),{...e,blocks:r}}function Yo(e,t){if(!No(e.dependencies,t.from))throw new O("DEPENDENCIES_CHANGED","The dependencies have changed.");return{...e,dependencies:t.to.map(n=>({publisher:n.publisher,name:n.name,version:n.version}))}}function Fo(e,t){return t.commands.reduce(Re,e)}const _e={x:0,y:0};class kt{state;commands=[];constructor(t){this.state=t}get current(){return this.state}add(t){this.state=Re(this.state,t),this.commands.push(t)}build(){return this.commands.length===0?null:this.commands.length===1?this.commands[0]:{type:"Batch",commands:this.commands}}}function Ut(e){return{x:Math.round(e.x),y:Math.round(e.y)}}function bt(e,t){return t.parentBlockId?{next:t.parentBlockId}:t.embeddedInBlockId?e.blocks.get(t.embeddedInBlockId)?.paramSlots[t.embeddedSlotIndex]?.commandBlockId===t.instanceId?{mouth:t.embeddedInBlockId,slot:t.embeddedSlotIndex}:{socket:t.embeddedInBlockId,slot:t.embeddedSlotIndex}:null}function En(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Mn(e,t){return Qe(e.blocks,t).map(n=>ve(e.blocks.get(n)))}function Xo(e,t){let n=t;for(;;){const o=e.blocks.get(n)?.nextBlockId;if(!o)return n;n=o}}function Dn(e,t,n){const o=e.current.blocks.get(t),r={x:o.x,y:o.y};if("socket"in n){const s=Ce(e.current.blocks.get(n.socket)?.paramSlots[n.slot]?.textValue);s!==null&&e.add({type:"SetText",blockId:n.socket,slot:n.slot,from:s,to:null}),e.add({type:"Attach",id:t,to:n,from:r});return}if("mouth"in n){const s=e.current.blocks.get(n.mouth)?.paramSlots[n.slot]?.commandBlockId??null;if(s){e.add({type:"Detach",id:s,from:n,to:_e}),e.add({type:"Attach",id:t,to:n,from:r}),e.add({type:"Attach",id:s,to:{next:Xo(e.current,t)},from:_e});return}}e.add({type:"Attach",id:t,to:n,from:r})}function _n(e,t,n,o){const r=new kt(e),s=Ut(n);return r.add({type:"InsertBlocks",blocks:[ve({...t,...s})]}),o&&Dn(r,t.instanceId,o),r.build()}function ft(e,t,n,o){const r=e.blocks.get(t);if(!r)return null;const s=new kt(e),c=Ut(n),l=bt(e,r);return o&&l&&En(o,l)?null:(l?s.add({type:"Detach",id:t,from:l,to:c}):!o&&(r.x!==c.x||r.y!==c.y)&&s.add({type:"MoveBlock",id:t,from:{x:r.x,y:r.y},to:c}),o&&Dn(s,t,o),s.build())}function Ko(e,t,n,o){const r=e.blocks.get(t)?.paramSlots[n]?.commandBlockId;return r?ft(e,r,o,null):null}function An(e,t){const n=e.blocks.get(t);if(!n)return null;const o=new kt(e),r=bt(e,n);return r&&o.add({type:"Detach",id:t,from:r,to:_e}),o.add({type:"RemoveBlocks",blocks:Mn(o.current,t)}),o.build()}function _t(e,t,n,o){const r=Ce(n),s=Ce(o);return r===s?null:{type:"SetText",blockId:e,slot:t,from:r,to:s}}function On(e,t,n){const o=new kt(e);for(const r of n){const s=o.current.blocks.get(r);if(!s)continue;const c=bt(o.current,s),l=s.nextBlockId;if(l){const x=c?_e:{x:s.x,y:s.y};o.add({type:"Detach",id:l,from:{next:r},to:x})}c&&o.add({type:"Detach",id:r,from:c,to:_e}),o.add({type:"RemoveBlocks",blocks:Mn(o.current,r)}),l&&c&&o.add({type:"Attach",id:l,to:c,from:_e})}return o.add({type:"SetDependencies",from:o.current.dependencies,to:t}),o.build()}function Vt(e){switch(e.type){case"InsertBlocks":return{type:"RemoveBlocks",blocks:e.blocks};case"RemoveBlocks":return{type:"InsertBlocks",blocks:e.blocks};case"MoveBlock":return{type:"MoveBlock",id:e.id,from:e.to,to:e.from};case"Attach":return{type:"Detach",id:e.id,from:e.to,to:e.from};case"Detach":return{type:"Attach",id:e.id,to:e.from,from:e.to};case"SetText":return{type:"SetText",blockId:e.blockId,slot:e.slot,from:e.to,to:e.from};case"SetDependencies":return{type:"SetDependencies",from:e.to,to:e.from};case"Batch":return{type:"Batch",commands:e.commands.map(Vt).reverse()};default:throw new O("INVALID_COMMAND",`Unknown command type '${e.type}'.`)}}function Rn(e,t=0){return{confirmed:e,version:t,pending:[],undo:[],redo:[]}}function Qo(e,t,n){return{...e,pending:[...e.pending,{id:t,command:n,kind:"do",original:n}]}}function Go(e,t){const n=e.undo[e.undo.length-1];if(!n||!ht(e))return null;const o=Vt(n);return{sync:{...e,pending:[...e.pending,{id:t,command:o,kind:"undo",original:n}]},command:o}}function Zo(e,t){const n=e.redo[e.redo.length-1];return!n||!ht(e)?null:{sync:{...e,pending:[...e.pending,{id:t,command:n,kind:"redo",original:n}]},command:n}}function ht(e){return e.pending.length===0}function Jo(e,t,n){return{sync:Rn(e,t),dropped:n.pending.length}}function kn(e,t,n){let o;try{o=Re(e.confirmed,t.command)}catch{return{sync:e,outOfSync:!0}}const r=e.pending.find(c=>c.id===t.id),s={...e,confirmed:o,version:n,pending:e.pending.filter(c=>c.id!==t.id)};if(!r)return{sync:s,outOfSync:!1};switch(r.kind){case"do":return{sync:{...s,undo:[...s.undo,r.original],redo:[]},outOfSync:!1};case"undo":return{sync:{...s,undo:s.undo.slice(0,-1),redo:[...s.redo,r.original]},outOfSync:!1};case"redo":return{sync:{...s,undo:[...s.undo,r.original],redo:s.redo.slice(0,-1)},outOfSync:!1}}}function bn(e,t){const n=e.pending.find(r=>r.id===t)??null;if(!n)return{sync:e,action:null};const o={...e,pending:e.pending.filter(r=>r.id!==t)};return n.kind==="undo"?{sync:{...o,undo:o.undo.slice(0,-1)},action:n}:n.kind==="redo"?{sync:{...o,redo:o.redo.slice(0,-1)},action:n}:{sync:o,action:n}}function In(e){let t=e.confirmed;for(const o of e.pending)try{t=Re(t,o.command)}catch{break}const n=new Set;return t!==e.confirmed&&t.blocks.forEach((o,r)=>{e.confirmed.blocks.get(r)!==o&&n.add(r)}),{state:t,provisionalIds:n}}const Nn=66,er={cursor:null,drag:null,typing:null};class tr{presence=er;lastSent=Number.NEGATIVE_INFINITY;timer=null;send;intervalMs;now;constructor(t,n=Nn,o=Date.now){this.send=t,this.intervalMs=n,this.now=o}get current(){return this.presence}update(t){if(this.presence={...this.presence,...t},this.timer)return;const n=this.lastSent+this.intervalMs-this.now();n<=0?this.flush():this.timer=setTimeout(()=>this.flush(),n)}updateNow(t){this.presence={...this.presence,...t},this.flush()}dispose(){this.timer&&clearTimeout(this.timer),this.timer=null}flush(){this.dispose(),this.lastSent=this.now(),this.send(this.presence)}}const Ye="command",me=new Map,Ge=new Map,Se=new Map;async function Yt(e){const t=Se.get(e.id);if(t&&t.info.url===e.url)return t;t&&Ft(e.id);const n=await fetch(e.url);if(!n.ok)throw new Error(`HTTP ${n.status} fetching ${e.url}`);const o=await n.json(),r=[],s=[];for(const l of o)me.has(l.id)?s.push(l.id):(me.set(l.id,l),Ge.set(l.id,e.id),r.push(l.id));const c={info:e,blockIds:r,conflictIds:s};return Se.set(e.id,c),c}function Ft(e){const t=Se.get(e);if(t){for(const n of t.blockIds)me.delete(n),Ge.delete(n);Se.delete(e)}}function qe(){return Array.from(Se.values())}function Ln(e){return Ge.get(e)}function pt(e){const t=me.get(e);if(!t)throw new Error(`Block definition not found: "${e}"`);return t}function A(e){return me.get(e)}function Hn(){return[...me.values()]}function nr(){return[...new Set(Hn().map(e=>e.category))]}function or(e,t){const n=[],o=[];for(const s of t)me.has(s.id)?o.push(s.id):(me.set(s.id,s),Ge.set(s.id,e.id),n.push(s.id));const r={info:e,blockIds:n,conflictIds:o};return Se.set(e.id,r),r}async function rr(e){Se.get(vn)?.info.url!==e&&(me.clear(),Ge.clear(),Se.clear(),await Yt({id:vn,name:"Core",description:"Built-in blocks",url:e,builtIn:!0}))}const vn="__core__",zn=36,Te=50,Ie=24,Fe=24,Xt=16,sr=24,Xe=24,ir=16,Wn=26,cr=11,lr=6,qn=16,Un=20,ar=26,dr=8,ur=6,At=12,lt=12,Vn=8,Ot=6;function Yn(e){return e.blockType==="query"&&e.returnType?`${e.name} [${e.returnType}]`:e.name}const fr={number:{w:44,h:Ie},string:{w:60,h:Ie},boolean:{w:52,h:Ie}},hr={w:75,h:Ie};function xt(e){return fr[e]??hr}function pe(e,t){return e.blockType==="command"&&t.type===Ye}function pr(e){return e.params.some(t=>pe(e,t))}const Rt=18;function Fn(e,t){return!!e.optional&&!t?.queryBlockId&&!t?.textValue}function Xn(e){return`+ ${e}`}function Kn(e){return Xn(e).length*Gn+12}function Kt(e,t,n){return pe(e,t)&&!!t.optional&&!n?.commandBlockId&&!n?.opened}function xr(e,t){if(t.size===0)return e;let n=null;for(const o of t){const[r,s]=gr(o),c=(n??e).get(r),l=c?.paramSlots[s];if(!c||!l||l.commandBlockId)continue;n??=new Map(e);const x=c.paramSlots.map((m,y)=>y===s?{...m,opened:!0}:m);n.set(r,{...c,paramSlots:x})}return n??e}function Nt(e,t){return`${e}#${t}`}function gr(e){const t=e.lastIndexOf("#");return[e.slice(0,t),Number(e.slice(t+1))]}function mr(e){const t=[];return e.forEach(n=>{const o=A(n.definitionId);o&&o.params.forEach((r,s)=>{pe(o,r)&&r.optional&&n.paramSlots[s]?.commandBlockId&&t.push(Nt(n.instanceId,s))})}),t}function Qn(e,t,n){if(Fn(e,t))return Kn(e.name);if(t?.queryBlockId&&n){const o=n.get(t.queryBlockId);if(o){const r=A(o.definitionId);if(r)return le(r,o.paramSlots,n)}}return xt(e.type).w}const Gn=5;function yr(e,t,n){const r=t==="number"||t==="boolean"?n-Ie:n-10,s=Math.floor(r/Gn);return e.length<=s?e:s<=1?"…":`${e.slice(0,s-1)}…`}function gt(e,t){return`${e}: ${t}`}function Zn(e){const t=gt(e.name,e.type);return e.optional?`${t} (optional)`:t}function kr(e){return Math.max(72,e.length*6+22)}function Qt(e){let t=dr;return(e.blockType==="start"?e.provides??[]:[]).map(n=>{const o={id:n.id,name:n.name,x:t,y:Te+6,w:kr(n.name)};return t+=o.w+ur,o})}function le(e,t,n){let o=At+lt+Yn(e).length*Ot;for(let l=0;l<e.params.length;l++)pe(e,e.params[l])||(o+=Vn+Qn(e.params[l],t?.[l],n));const r=Qt(e);if(r.length>0){const l=r[r.length-1];o=Math.max(o,l.x+l.w+lt)}e.params.forEach(l=>{pe(e,l)&&(o=Math.max(o,Xt+At+l.name.length*Ot+lt+(l.optional?qn:0)))});const s=Ze(e,t,n);if(s.length>0){const l=s[s.length-1];o=Math.max(o,l.x+l.w+lt)}const c=e.blockType==="start"?140:110;return Math.max(c,o)}function Ne(e){return e.blockType==="start"?Te:e.blockType==="command"?zn:Ie}function $e(e,t,n){return e.blockType==="start"?Te+(e.provides&&e.provides.length>0?8+ar:0):e.blockType==="command"?pr(e)?Jn(e,t,n)+br(e,t):zn:Ie}function Jn(e,t,n){const o=Ee(e,t,n);if(o.length===0)return Ne(e);const r=o[o.length-1];return r.y+r.h}function br(e,t){return e.params.some((n,o)=>Kt(e,n,t?.[o]))?Wn:ir}function Ze(e,t,n){const o=e.params.map((c,l)=>({param:c,index:l})).filter(({param:c,index:l})=>Kt(e,c,t?.[l]));if(o.length===0)return[];const r=Jn(e,t,n)+(Wn-Rt)/2;let s=cr;return o.map(({param:c,index:l})=>{const x={index:l,name:c.name,x:s,y:r,w:Kn(c.name),h:Rt};return s+=x.w+lr,x})}function Gt(e,t){const n=A(e.definitionId);return n?$e(n,e.paramSlots,t):Fe}function eo(e,t){let n=0;const o=new Set;let r=e;for(;r&&!o.has(r);){o.add(r);const s=t.get(r);if(!s)break;n+=Gt(s,t),r=s.nextBlockId}return n}function Ee(e,t,n){const o=[],r=e.params.findIndex(c=>pe(e,c));let s=Ne(e);return e.params.forEach((c,l)=>{if(!pe(e,c)||Kt(e,c,t?.[l]))return;let x=null;l!==r&&(x=s,s+=Xe);const m=t?.[l]?.commandBlockId,y=m&&n?eo(m,n):0,k=Math.max(sr,y);o.push({index:l,name:c.name,x:Xt,y:s,h:k,dividerY:x,optional:!!c.optional}),s+=k}),o}function Ir(e,t,n){return[...Ee(e,t,n).map(o=>({slot:o.index,x:o.x,y:o.y})),...Ze(e,t,n).map(o=>({slot:o.index,x:o.x,y:o.y}))]}function vr(e,t){const n=e.dividerY??e.y-Xe;return{x:t-qn/2-4,y:n+Xe/2}}function Je(e,t,n){const o=Ne(e),r=[];let s=At+Yn(e).length*Ot;for(let c=0;c<e.params.length;c++){const l=e.params[c];if(pe(e,l))continue;const x=Fn(l,t?.[c]),m=Qn(l,t?.[c],n),y=x?Rt:xt(l.type).h;s+=Vn,r.push({x:s,y:(o-y)/2,w:m,h:y,type:l.type,index:c,collapsed:x}),s+=m}return r}function Sr(e){const t=new Map;function n(o,r,s){const c=e.get(o);if(!c||t.has(o))return;t.set(o,{x:r,y:s});const l=A(c.definitionId);if(l){for(const x of Je(l,c.paramSlots,e)){const m=c.paramSlots[x.index]?.queryBlockId;m&&n(m,r+x.x,s+x.y)}for(const x of Ee(l,c.paramSlots,e)){const m=c.paramSlots[x.index]?.commandBlockId;m&&n(m,r+x.x,s+x.y)}}c.nextBlockId&&n(c.nextBlockId,r,s+Gt(c,e))}return e.forEach(o=>{!o.parentBlockId&&!o.embeddedInBlockId&&n(o.instanceId,o.x,o.y)}),t}function to(e,t){const n=new Set;function o(c){const l=[];let x=c??null;for(;x&&!n.has(x);){const m=e.blocks.get(x);if(!m)break;l.push(r(m)),x=m.nextBlockId}return l}function r(c){n.add(c.instanceId);const l=t(c.definitionId),x=c.paramSlots.map((m,y)=>{const k=l?.params[y]??{name:`param${y}`,type:"string"},_=m.queryBlockId?e.blocks.get(m.queryBlockId):void 0;let B;return l&&pe(l,k)?B={kind:"body",body:o(m.commandBlockId)}:_?B={kind:"query",node:r(_)}:m.textValue!==null&&m.textValue!==void 0&&m.textValue!==""?B={kind:"text",text:m.textValue}:B={kind:"empty"},{name:k.name,type:k.type,value:B}});return{definitionId:c.definitionId,name:l?.name??c.definitionId,blockType:l?.blockType??"missing",args:x}}return{roots:[...e.blocks.values()].filter(c=>!c.parentBlockId&&!c.embeddedInBlockId).sort((c,l)=>c.y-l.y||c.x-l.x||(c.instanceId<l.instanceId?-1:c.instanceId>l.instanceId?1:0)).map(c=>({position:{x:c.x,y:c.y},body:o(c.instanceId)}))}}const Ae={id:"dark",label:"Dark",appBg:"#0e1118",paletteBg:"#141820",paletteHeaderBg:"#0e1118",canvasBg:"#111420",consoleBg:"#0e1118",consoleHeaderBg:"#141820",border:"#252d42",accent:"#c9a43a",textPrimary:"#dde8f8",textSecondary:"#7a90b8",textMuted:"#5a6888",inputBg:"#0e1118",inputBorder:"#303858",gridDot:"#252d42",blockBody:"#1a2236",blockBorder:"#303858",blockText:"#e8f0fc",socketBody:"#141e30",consoleOutput:"#b8d4ec",consoleSeparator:"#4a6090",deleteBorder:"#252d42",deleteText:"#5a6888",deleteActiveBg:"#3a0c0c",deleteActiveBorder:"#8a2020",deleteActiveText:"#e06060",titleBg:"#0e1118",titlePrimaryText:"#c9a43a",titleSecondaryText:"#5a6888",pkgBg:"#141820",pkgBorder:"#252d42",pkgActiveBg:"#1a2236",pkgActiveBorder:"#3a4d70",pkgText:"#7a8aaa",pkgActiveText:"#c9a43a",pkgSubText:"#5a6888",switcherBg:"transparent",switcherActiveBg:"#1a2236",switcherText:"#5a6888",switcherActiveText:"#c9a43a",switcherBorder:"#252d42"},$r={id:"light",label:"Light",appBg:"#f0f2f6",paletteBg:"#ffffff",paletteHeaderBg:"#f8f9fc",canvasBg:"#e8ebf2",consoleBg:"#ffffff",consoleHeaderBg:"#f8f9fc",border:"#dde2ec",accent:"#2a50a0",textPrimary:"#1a2030",textSecondary:"#5060a0",textMuted:"#a0aac0",inputBg:"#f0f2f6",inputBorder:"#d0d8e8",gridDot:"#c0c8d8",blockBody:"#ffffff",blockBorder:"#c8d0e0",blockText:"#1a2030",socketBody:"#eaecf4",consoleOutput:"#2a50a0",consoleSeparator:"#dde2ec",deleteBorder:"#dde2ec",deleteText:"#b0b8d0",deleteActiveBg:"#fff0f0",deleteActiveBorder:"#e08080",deleteActiveText:"#c04040",titleBg:"#ffffff",titlePrimaryText:"#1a2030",titleSecondaryText:"#8090b0",pkgBg:"#f8f9fc",pkgBorder:"#dde2ec",pkgActiveBg:"#eef2fc",pkgActiveBorder:"#a0b8e0",pkgText:"#7080a0",pkgActiveText:"#2a50a0",pkgSubText:"#9090a0",switcherBg:"transparent",switcherActiveBg:"#eaedf4",switcherText:"#9090a0",switcherActiveText:"#1a2030",switcherBorder:"#dde2ec"},Ue=[Ae,$r],Ve=f.createContext(Ae);function Y(){return f.useContext(Ve)}const X=16,be=14,Be=X+be/2,je=5,D=4;function wr(e,t){return[`M ${D} 0`,`H ${X} L ${Be} ${je} L ${X+be} 0`,`H ${e-D} Q ${e} 0 ${e} ${D}`,`V ${t-D} Q ${e} ${t} ${e-D} ${t}`,`H ${X+be} L ${Be} ${t+je} L ${X} ${t}`,`H ${D} Q 0 ${t} 0 ${t-D}`,`V ${D} Q 0 0 ${D} 0 Z`].join(" ")}function Br(e,t,n,o){const r=[`M ${D} 0`,`H ${X} L ${Be} ${je} L ${X+be} 0`,`H ${e-D} Q ${e} 0 ${e} ${D}`];for(const s of o){const c=s.y,l=s.y+s.h;r.push(`V ${c}`,`H ${n+X+be} L ${n+Be} ${c+je} L ${n+X} ${c}`,`H ${n}`,`V ${l}`,`H ${n+X} L ${n+Be} ${l+je} L ${n+X+be} ${l}`,`H ${e}`)}return r.push(`V ${t-D} Q ${e} ${t} ${e-D} ${t}`,`H ${X+be} L ${Be} ${t+je} L ${X} ${t}`,`H ${D} Q 0 ${t} 0 ${t-D}`,`V ${D} Q 0 0 ${D} 0 Z`),r.join(" ")}function jr(e,t){return["M 0 10 Q 0 0 10 0",`H ${e-10} Q ${e} 0 ${e} 10`,`V ${t-D} Q ${e} ${t} ${e-D} ${t}`,`H ${X+be} L ${Be} ${t+je} L ${X} ${t}`,`H ${D} Q 0 ${t} 0 ${t-D}`,"V 10 Z"].join(" ")}function Cr(e,t){const n=t/2;return[`M ${n} 0 H ${e-n}`,`A ${n} ${n} 0 0 1 ${e-n} ${t}`,`H ${n} A ${n} ${n} 0 0 1 ${n} 0 Z`].join(" ")}function Tr(e,t){const n=t/2;return[`M ${n} 0 H ${e-n}`,`L ${e} ${t/2} L ${e-n} ${t}`,`H ${n} L 0 ${t/2} Z`].join(" ")}function no(e,t,n){return[`M ${n} 0 H ${e-n} Q ${e} 0 ${e} ${n}`,`V ${t-n} Q ${e} ${t} ${e-n} ${t}`,`H ${n} Q 0 ${t} 0 ${t-n}`,`V ${n} Q 0 0 ${n} 0 Z`].join(" ")}function Pr(e,t){return no(e,t,5)}function Er(e,t){return no(e,t,9)}function Zt(e,t,n){switch(e){case"number":return Cr(t,n);case"boolean":return Tr(t,n);case"string":return Pr(t,n);default:return Er(t,n)}}function Jt(e,t,n){return Zt(e,t,n)}function en(e,t,n){const o=le(e,t,n),r=$e(e,t,n);if(e.blockType==="start")return jr(o,r);if(e.blockType==="query")return Zt(e.returnType,o,r);const s=Ee(e,t,n);return s.length>0?Br(o,r,Xt,s):wr(o,r)}function Mr({available:e,dependencies:t,onChange:n,actions:o,blockCounts:r,conflictCounts:s}){const c=Y(),[l,x]=f.useState(""),[m,y]=f.useState(""),[k,_]=f.useState(!1),[B,L]=f.useState(null),N=new Map(e.map(b=>[G(b),b])),q=new Set(t.map(G)),H=e.filter(b=>!q.has(G(b)));function $(){const b=N.get(l);if(!b)return;const z=k&&m.trim()?m.trim():b.version;n([...t,{publisher:b.publisher,name:b.name,version:z}]),x(""),y("")}function g(b){n(t.filter(z=>G(z)!==b)),L(null)}function J(b,z){n(t.map(U=>G(U)===b?{...U,version:z}:U))}const K={background:c.inputBg,color:c.textPrimary,border:`1px solid ${c.inputBorder}`,borderRadius:4,fontSize:11,padding:"4px 6px",outline:"none",minWidth:0},ee={background:"none",color:c.textSecondary,border:`1px solid ${c.border}`,borderRadius:4,fontSize:11,padding:"4px 8px",cursor:"pointer"},Q=B?r.get(B)??0:0;return i.jsxs("div",{style:{flex:1,overflowY:"auto",padding:10,display:"flex",flexDirection:"column",gap:6},children:[t.length===0&&i.jsx("div",{style:{color:c.textMuted,fontSize:11,fontStyle:"italic"},children:"No packages yet — add one to get blocks."}),B&&i.jsxs("div",{style:{border:`1px solid ${c.deleteActiveBorder}`,background:c.deleteActiveBg,borderRadius:4,padding:"6px 8px",fontSize:11,color:c.textPrimary},children:["Remove ",i.jsx("b",{children:B}),"?"," ",Q>0?`Its ${Q} block${Q===1?"":"s"} on the canvas ${Q===1?"is":"are"} deleted.`:"None of its blocks are on the canvas.",i.jsxs("div",{style:{display:"flex",gap:6,marginTop:6},children:[i.jsx("button",{type:"button",onClick:()=>g(B),style:{...ee,background:c.deleteActiveBorder,color:"white",borderColor:c.deleteActiveBorder},children:"Remove"}),i.jsx("button",{type:"button",onClick:()=>L(null),style:ee,children:"Cancel"})]})]}),t.map(b=>{const z=G(b),U=N.get(z),R=U&&wn(U.version,b.version)>0?U.version:null,ae=s.get(z)??0;return i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11},children:[i.jsx("span",{"aria-hidden":!0,style:{width:9,height:9,flexShrink:0,background:U?.color??c.border}}),i.jsx("span",{title:U?.description,style:{color:c.textPrimary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:z}),i.jsx("span",{style:{color:c.textMuted,fontVariantNumeric:"tabular-nums"},children:b.version}),ae>0&&i.jsxs("span",{title:`${ae} block ID(s) skipped: another package already defines them`,style:{fontSize:9,color:c.accent,border:`1px solid ${c.accent}`,borderRadius:3,padding:"0 3px"},children:["⚠ ",ae]}),R&&i.jsxs("button",{type:"button",onClick:()=>J(z,R),title:`Version ${R} is available. Click to update.`,style:{...ee,padding:"0 5px",fontSize:10,color:c.accent,borderColor:c.accent},children:[R," available"]}),i.jsx("button",{type:"button",onClick:()=>L(z),title:"Remove package",style:{marginLeft:"auto",background:"none",border:"none",color:c.textMuted,fontSize:15,lineHeight:1,cursor:"pointer"},children:"×"})]},z)}),i.jsxs("div",{style:{display:"flex",gap:6,marginTop:4},children:[i.jsxs("select",{value:l,onChange:b=>x(b.target.value),style:{...K,flex:1},children:[i.jsx("option",{value:"",children:H.length?"Add package…":"No more packages"}),H.map(b=>i.jsxs("option",{value:G(b),children:[G(b)," ",b.version]},G(b)))]}),k&&i.jsx("input",{value:m,onChange:b=>y(b.target.value),placeholder:N.get(l)?.version??"version",style:{...K,width:64}}),i.jsx("button",{type:"button",onClick:$,disabled:!l,style:{...ee,opacity:l?1:.4,cursor:l?"pointer":"default"},children:"Add"})]}),o&&o.length>0&&i.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:o.map(b=>i.jsx("button",{type:"button",onClick:()=>Ao(b,t,n),title:b.title,style:ee,children:b.label},b.label))}),i.jsx("button",{type:"button",onClick:()=>_(b=>!b),style:{alignSelf:"flex-start",background:"none",border:"none",padding:0,color:c.textMuted,fontSize:10,cursor:"pointer"},children:k?"Hide version choice":"Choose a specific version…"})]})}function tn({name:e,w:t,h:n}){const o=Y();return i.jsxs(i.Fragment,{children:[i.jsx("rect",{x:.5,y:.5,width:t-1,height:n-1,rx:(n-1)/2,fill:"transparent",stroke:o.textMuted,strokeWidth:1,strokeDasharray:"3,2"}),i.jsx("text",{x:t/2,y:n/2+3,textAnchor:"middle",fill:o.textMuted,fontSize:9,fontFamily:"sans-serif",style:{userSelect:"none",pointerEvents:"none"},children:Xn(e)})]})}const Dr=5;function Sn({w:e,title:t,onRemove:n}){const o=Y();return i.jsxs("g",{transform:`translate(${e-2},-1)`,onPointerDown:r=>r.stopPropagation(),onClick:r=>{r.stopPropagation(),n()},style:{cursor:"pointer"},children:[i.jsx("title",{children:t}),i.jsx("circle",{r:Dr,fill:o.blockBody,stroke:o.textMuted,strokeWidth:1}),i.jsx("path",{d:"M -2 -2 L 2 2 M 2 -2 L -2 2",stroke:o.blockText,strokeWidth:1.2,strokeLinecap:"round"})]})}function nn({chips:e,onOpen:t}){return i.jsx(i.Fragment,{children:e.map(n=>i.jsxs("g",{transform:`translate(${n.x},${n.y})`,onPointerDown:t?o=>o.stopPropagation():void 0,onClick:t?o=>{o.stopPropagation(),t(n.index)}:void 0,style:{cursor:t?"pointer":void 0},children:[i.jsx("title",{children:`${gt(n.name,Ye)} (optional)${t?": click to add it, or drop commands here":""}`}),i.jsx(tn,{name:n.name,w:n.w,h:n.h})]},n.index))})}const _r="#c08820";function on({mouths:e,w:t,isEmpty:n}){const o=Y();return i.jsx("g",{style:{pointerEvents:"none"},children:e.map(r=>i.jsxs("g",{children:[r.dividerY!==null&&i.jsxs("g",{style:{pointerEvents:"all"},children:[i.jsx("title",{children:gt(r.name,Ye)}),i.jsx("rect",{x:0,y:r.dividerY,width:t,height:Xe,fill:"transparent"}),i.jsx("text",{x:11,y:r.dividerY+Xe/2+4,fill:o.blockText,fontSize:10,fontWeight:"bold",fontFamily:"sans-serif",style:{userSelect:"none"},children:r.name})]}),n(r.index)&&i.jsxs("g",{style:{pointerEvents:"all"},children:[i.jsx("title",{children:gt(r.name,Ye)}),i.jsx("rect",{x:r.x+3,y:r.y+3,width:Math.max(60,r.name.length*6+20),height:r.h-6,rx:3,fill:"transparent",stroke:_r,strokeWidth:1,strokeDasharray:"4,3"}),i.jsx("text",{x:r.x+10,y:r.y+r.h/2+3,fill:o.textMuted,fontSize:9,fontFamily:"sans-serif",fontStyle:"italic",style:{userSelect:"none"},children:r.name})]})]},r.index))})}function oo({name:e,type:t,w:n,h:o}){const r=Y();return i.jsx("text",{x:n/2,y:o/2+3,textAnchor:"middle",fill:r.textMuted,fontSize:9,fontFamily:"sans-serif",fontStyle:"italic",style:{userSelect:"none",pointerEvents:"none"},children:yr(e,t,n)})}function ro({def:e,onPointerDown:t,isPlaced:n}){const o=Y(),r=le(e),s=$e(e),c=Je(e),l=Ee(e),x=Ze(e),m=`pal-${e.id}`,y=en(e);return i.jsx("div",{style:{marginBottom:6,userSelect:"none",position:"relative",opacity:n?.4:1},onPointerDown:n?void 0:k=>t(k,e.id),title:n?"Already on canvas — only one instance allowed":void 0,children:i.jsxs("svg",{width:r+2,height:s+8,style:{display:"block",cursor:n?"not-allowed":"grab",overflow:"visible"},children:[i.jsx("defs",{children:i.jsx("clipPath",{id:m,children:i.jsx("path",{d:y})})}),i.jsxs("g",{transform:"translate(1, 1)",children:[i.jsx("path",{d:y,fill:o.blockBody,stroke:o.blockBorder,strokeWidth:1.5}),i.jsx("rect",{x:0,y:0,width:4,height:s+20,fill:e.color,clipPath:`url(#${m})`}),l.length>0&&i.jsx(on,{mouths:l,w:r,isEmpty:()=>!0}),i.jsx(nn,{chips:x}),i.jsxs("text",{x:11,y:Ne(e)/2+4,fill:o.blockText,fontSize:11,fontWeight:"bold",fontFamily:"sans-serif",style:{userSelect:"none",pointerEvents:"none"},children:[e.name,e.blockType==="query"&&e.returnType&&i.jsx("tspan",{fill:o.textMuted,fontSize:9,fontWeight:"normal",children:` [${e.returnType}]`})]}),n&&i.jsx("text",{x:r/2,y:s/2+4,textAnchor:"middle",fill:o.textMuted,fontSize:9,fontFamily:"sans-serif",style:{userSelect:"none",pointerEvents:"none"},children:"✓ on canvas"}),c.map(k=>{const _=e.params[k.index];return i.jsxs("g",{transform:`translate(${k.x},${k.y})`,children:[i.jsx("title",{children:Zn(_)}),k.collapsed?i.jsx(tn,{name:_.name,w:k.w,h:k.h}):i.jsxs(i.Fragment,{children:[i.jsx("path",{d:Jt(k.type,k.w,k.h),fill:o.socketBody,stroke:o.blockBorder,strokeWidth:1}),i.jsx(oo,{name:_.name,type:k.type,w:k.w,h:k.h})]})]},k.index)}),e.blockType==="start"&&e.provides&&e.provides.length>0&&i.jsxs("g",{children:[i.jsx("line",{x1:8,y1:Te,x2:r-8,y2:Te,stroke:"rgba(255,255,255,0.15)",strokeWidth:1}),Qt(e).map(k=>{const B=A(k.id)?.color??e.color,L=k.w,N=Un;return i.jsxs("g",{transform:`translate(${k.x}, ${k.y})`,children:[i.jsx("rect",{x:0,y:0,width:L,height:N,rx:10,fill:B,opacity:.82,stroke:"rgba(255,255,255,0.25)",strokeWidth:1}),i.jsx("text",{x:L/2,y:N/2+3.5,textAnchor:"middle",fill:"white",fontSize:9.5,fontFamily:"sans-serif",fontWeight:"bold",style:{userSelect:"none",pointerEvents:"none"},children:k.name})]},k.id)})]})]})]})})}function Ar({cat:e,defs:t,collapsed:n,onToggle:o,onPointerDown:r,placedStartIds:s}){const c=Y();return i.jsxs("div",{style:{marginBottom:2},children:[i.jsxs("button",{onClick:()=>o(e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",background:"none",border:"none",padding:"5px 0 4px",borderBottom:`1px solid ${c.border}`,cursor:"pointer",textAlign:"left",marginBottom:n?0:6},children:[i.jsx("span",{style:{color:c.accent,fontSize:8,lineHeight:1,opacity:.6},children:n?"▶":"▼"}),i.jsx("span",{style:{color:c.accent,fontSize:10,fontWeight:"bold",textTransform:"uppercase",letterSpacing:1,opacity:.85},children:e}),n&&i.jsx("span",{style:{color:c.textMuted,fontSize:9,marginLeft:"auto"},children:t.length})]}),!n&&i.jsx("div",{style:{paddingBottom:4},children:t.map(l=>i.jsx(ro,{def:l,onPointerDown:r,isPlaced:l.blockType==="start"&&s.has(l.id)},l.id))})]})}function Or({onPointerDown:e,isDropTarget:t,registryVersion:n,packages:o,placedStartIds:r}){const s=Y(),[c,l]=f.useState("blocks"),[x,m]=f.useState(""),[y,k]=f.useState(new Set),_=f.useMemo(()=>Hn().filter(g=>!g.category.startsWith("$")),[n]),B=f.useMemo(()=>nr().filter(g=>!g.startsWith("$")),[n]),L=x.trim().toLowerCase(),N=L?_.filter(g=>g.name.toLowerCase().includes(L)):null;function q(g){k(J=>{const K=new Set(J);return K.has(g)?K.delete(g):K.add(g),K})}const H=o?.dependencies.length??0,$=g=>({flex:1,background:"none",border:"none",borderBottom:`2px solid ${c===g?s.accent:"transparent"}`,color:c===g?s.accent:s.textMuted,fontSize:10,fontWeight:"bold",textTransform:"uppercase",letterSpacing:1,padding:"8px 0",cursor:"pointer",transition:"color 0.15s, border-color 0.15s"});return i.jsxs("div",{style:{width:260,minWidth:260,backgroundColor:s.paletteBg,borderRight:`1px solid ${s.border}`,display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[o&&i.jsxs("div",{style:{display:"flex",borderBottom:`1px solid ${s.border}`,flexShrink:0,background:s.paletteHeaderBg},children:[i.jsx("button",{style:$("blocks"),onClick:()=>l("blocks"),children:"Blocks"}),i.jsxs("button",{style:$("packages"),onClick:()=>l("packages"),children:["Packages",H>0?` · ${H}`:""]})]}),c==="blocks"&&i.jsxs(i.Fragment,{children:[i.jsx("div",{style:{padding:"8px 10px 6px",flexShrink:0},children:i.jsx("input",{type:"search",placeholder:"Search blocks…",value:x,onChange:g=>m(g.target.value),style:{width:"100%",boxSizing:"border-box",background:s.inputBg,border:`1px solid ${s.inputBorder}`,borderRadius:4,color:s.textPrimary,fontSize:11,padding:"5px 9px",outline:"none"}})}),i.jsx("div",{style:{flex:1,overflowY:"auto",padding:"4px 10px 0"},children:N?N.length>0?N.map(g=>i.jsx(ro,{def:g,onPointerDown:e,isPlaced:g.blockType==="start"&&r.has(g.id)},g.id)):i.jsx("div",{style:{color:s.textMuted,fontSize:11,padding:"12px 0",textAlign:"center"},children:"No blocks match"}):B.map(g=>i.jsx(Ar,{cat:g,defs:_.filter(J=>J.category===g),collapsed:y.has(g),onToggle:q,onPointerDown:e,placedStartIds:r},g))}),i.jsx("div",{style:{flexShrink:0,margin:"8px 10px 10px",padding:"7px 10px",borderRadius:4,background:t?s.deleteActiveBg:"transparent",border:`1px dashed ${t?s.deleteActiveBorder:s.deleteBorder}`,color:t?s.deleteActiveText:s.deleteText,textAlign:"center",fontSize:10,fontWeight:"bold",letterSpacing:.5,textTransform:"uppercase",transition:"background 0.12s, color 0.12s, border-color 0.12s",pointerEvents:"none",userSelect:"none"},children:t?"Release to delete":"Drag here to delete"})]}),c==="packages"&&o&&i.jsx(Mr,{...o})]})}function Rr(e,t,n){let o=e;for(;;)if(o.embeddedInBlockId){const r=n.get(o.embeddedInBlockId);if(!r)return!1;o=r}else if(o.parentBlockId){const r=n.get(o.parentBlockId);if(!r)return!1;o=r}else return A(o.definitionId)?.provides?.some(s=>s.id===t)??!1}function It(e){const{block:t,allBlocks:n,onPointerDown:o,onBlockClick:r,onSocketClick:s,editingSocket:c,onSocketCommit:l,onSocketCancelEdit:x,onOutputDrag:m,isGhost:y,draggingIds:k,provisionalIds:_,onSocketInput:B,onParamRemove:L,onMouthOpen:N,onMouthClose:q,embedded:H}=e,$=Y(),g=A(t.definitionId),J=k?.has(t.instanceId)??!1,K=_?.has(t.instanceId)??!1,ee=(u,E,V,Z)=>{const re=u?n.get(u):void 0;return re?i.jsx("g",{transform:`translate(${E},${V})`,children:i.jsx(It,{block:re,allBlocks:n,onPointerDown:o,onBlockClick:r,onSocketClick:s,editingSocket:c,onSocketCommit:l,onSocketCancelEdit:x,onOutputDrag:m,isGhost:y,draggingIds:k,provisionalIds:_,onSocketInput:B,onParamRemove:L,onMouthOpen:N,onMouthClose:q,embedded:!0})},Z):null};if(!g){const u=o?Z=>{Z.stopPropagation(),o(Z,t.instanceId)}:void 0,E=r?Z=>{Z.stopPropagation(),r(t.instanceId)}:void 0,V=t.definitionId.replace(/^__coll__/,"").slice(0,16);return i.jsxs("g",{transform:y||H?void 0:`translate(${t.x},${t.y})`,opacity:J?.35:.85,children:[i.jsxs("g",{onPointerDown:u,onClick:E,style:{cursor:"grab"},children:[i.jsx("rect",{x:0,y:0,width:160,height:Fe,rx:3,fill:"rgba(160,40,40,0.18)",stroke:"#c05050",strokeWidth:1.5,strokeDasharray:"5,3"}),i.jsxs("text",{x:8,y:16,fill:"#c05050",fontSize:10,fontFamily:"sans-serif",fontStyle:"italic",style:{userSelect:"none",pointerEvents:"none"},children:["⚠ ",V," (missing)"]})]}),ee(t.nextBlockId,0,Fe,"next")]})}const Q=le(g,t.paramSlots,n),b=$e(g,t.paramSlots,n),z=Ne(g),U=Je(g,t.paramSlots,n),R=Ee(g,t.paramSlots,n),ae=Ze(g,t.paramSlots,n),oe=J?.35:K?.6:y&&!H?.75:1,Le=`clip-${y?"g":"c"}-${t.instanceId}`,de=en(g,t.paramSlots,n),et=o?u=>{u.stopPropagation(),o(u,t.instanceId)}:void 0,P=r?u=>{u.stopPropagation(),r(t.instanceId)}:void 0;if(g.category.startsWith("$")&&!y&&!Rr(t,g.id,n)){const u=le(g),E=Ie,V=Zt(g.returnType??"string",u,E);return i.jsxs("g",{transform:y||H?void 0:`translate(${t.x},${t.y})`,opacity:J?.35:.85,onPointerDown:et,onClick:P,style:{cursor:"grab"},children:[i.jsx("path",{d:V,fill:"rgba(180,100,0,0.15)",stroke:"#c08820",strokeWidth:1.5,strokeDasharray:"5,3"}),i.jsxs("text",{x:u/2,y:E/2+3.5,textAnchor:"middle",fill:"#c08820",fontSize:9,fontFamily:"sans-serif",fontStyle:"italic",style:{userSelect:"none",pointerEvents:"none"},children:["⚠ ",g.name]})]})}return i.jsxs("g",{transform:y||H?void 0:`translate(${t.x},${t.y})`,opacity:oe,onPointerDown:et,onClick:P,style:{cursor:y?"grabbing":"grab"},children:[i.jsx("defs",{children:i.jsx("clipPath",{id:Le,children:i.jsx("path",{d:de})})}),i.jsx("path",{d:de,fill:$.blockBody,stroke:K?$.accent:$.blockBorder,strokeWidth:1.5,strokeDasharray:K?"4,3":void 0}),i.jsx("rect",{x:0,y:0,width:4,height:b+20,fill:g.color,clipPath:`url(#${Le})`}),i.jsxs("text",{x:11,y:z/2+4,fill:$.blockText,fontSize:11,fontWeight:"bold",fontFamily:"sans-serif",style:{userSelect:"none",pointerEvents:"none"},children:[g.name,g.blockType==="query"&&g.returnType&&i.jsx("tspan",{fill:$.textMuted,fontSize:9,fontWeight:"normal",children:` [${g.returnType}]`})]}),g.blockType==="start"&&g.provides&&g.provides.length>0&&i.jsxs("g",{children:[i.jsx("line",{x1:8,y1:Te,x2:Q-8,y2:Te,stroke:"rgba(255,255,255,0.15)",strokeWidth:1}),Qt(g).map(u=>{const V=A(u.id)?.color??g.color,Z=u.w,re=Un,xe=!y&&!H;return i.jsxs("g",{transform:`translate(${u.x}, ${u.y})`,onPointerDown:xe?ye=>{ye.stopPropagation(),m?.(ye,u.id)}:void 0,style:{cursor:xe?"grab":"default"},children:[i.jsx("rect",{x:0,y:0,width:Z,height:re,rx:10,fill:V,opacity:.82,stroke:"rgba(255,255,255,0.25)",strokeWidth:1}),i.jsx("text",{x:Z/2,y:re/2+3.5,textAnchor:"middle",fill:"white",fontSize:9.5,fontFamily:"sans-serif",fontWeight:"bold",style:{userSelect:"none",pointerEvents:"none"},children:u.name})]},u.id)})]}),U.map(u=>{const E=t.paramSlots[u.index],V=E?.queryBlockId,Z=V?n.get(V):null,re=g.params[u.index],xe=re.name,ye=Zn(re),Me=re.optional&&L&&!y?i.jsx(Sn,{w:u.w,title:`Leave out ${xe}`,onRemove:()=>L(t.instanceId,u.index)}):null;if(Z)return i.jsxs("g",{children:[i.jsx("title",{children:ye}),ee(V,u.x,u.y,"query"),Me&&i.jsx("g",{transform:`translate(${u.x},${u.y})`,children:Me})]},u.index);const ge=E?.textValue,te=c?.blockId===t.instanceId&&c?.slotIndex===u.index;if(u.collapsed&&!te)return i.jsxs("g",{transform:`translate(${u.x},${u.y})`,onPointerDown:v=>v.stopPropagation(),onClick:v=>{v.stopPropagation(),s?.(t.instanceId,u.index)},style:{cursor:"pointer"},children:[i.jsx("title",{children:`${ye}: click to type a value, or drop a ${u.type} query here`}),i.jsx(tn,{name:xe,w:u.w,h:u.h})]},u.index);const se=u.collapsed?Math.max(u.w,xt(u.type).w):u.w,ue=u.collapsed?xt(u.type).h:u.h;return i.jsxs("g",{transform:`translate(${u.x},${u.y+(u.h-ue)/2})`,onPointerDown:v=>v.stopPropagation(),onClick:v=>{v.stopPropagation(),s?.(t.instanceId,u.index)},style:{cursor:"text"},children:[i.jsx("title",{children:ye}),i.jsx("path",{d:Jt(u.type,se,ue),fill:te?$.blockBorder:$.socketBody,stroke:$.blockBorder,strokeWidth:te?1.5:1}),te?i.jsx("foreignObject",{x:0,y:0,width:se,height:ue,children:i.jsx("input",{autoFocus:!0,defaultValue:ge??"",onChange:v=>B?.(t.instanceId,u.index,v.target.value),onKeyDown:v=>{v.stopPropagation(),v.key==="Enter"&&l?.(t.instanceId,u.index,v.target.value),v.key==="Escape"&&x?.()},onBlur:v=>l?.(t.instanceId,u.index,v.target.value),onPointerDown:v=>v.stopPropagation(),style:{width:"100%",height:"100%",background:"transparent",border:"none",outline:"none",color:$.blockText,fontSize:10,fontFamily:"sans-serif",textAlign:"center",padding:"0 4px",boxSizing:"border-box",caretColor:$.blockText}})}):ge?i.jsx("text",{x:u.w/2,y:u.h/2+4,textAnchor:"middle",fill:$.blockText,fontSize:10,fontFamily:"sans-serif",fontStyle:K?"italic":void 0,style:{userSelect:"none",pointerEvents:"none"},children:ge}):i.jsx(oo,{name:xe,type:u.type,w:u.w,h:u.h}),!te&&Me]},u.index)}),R.length>0&&i.jsx(on,{mouths:R,w:Q,isEmpty:u=>!t.paramSlots[u]?.commandBlockId}),R.map(u=>ee(t.paramSlots[u.index]?.commandBlockId,u.x,u.y,`mouth-${u.index}`)),!y&&q&&R.filter(u=>u.optional).map(u=>{const E=vr(u,Q);return i.jsx("g",{transform:`translate(${E.x},${E.y})`,children:i.jsx(Sn,{w:2,title:`Leave out ${u.name}`,onRemove:()=>q(t.instanceId,u.index)})},`close-${u.index}`)}),i.jsx(nn,{chips:ae,onOpen:!y&&N?u=>N(t.instanceId,u):void 0}),ee(t.nextBlockId,0,b,"next")]})}const so=f.forwardRef(({blocks:e,draggingIds:t,provisionalIds:n,onBlockPointerDown:o,onBlockClick:r,onSocketClick:s,editingSocket:c,onSocketInput:l,onSocketCommit:x,onSocketCancelEdit:m,onParamRemove:y,onMouthOpen:k,onMouthClose:_,onOutputDrag:B,overlay:L},N)=>{const q=Y(),H=[...e.values()].filter($=>!$.embeddedInBlockId&&!$.parentBlockId);return i.jsxs("svg",{ref:N,style:{flex:1,background:q.canvasBg,display:"block"},onPointerDown:$=>{$.target===$.currentTarget&&$.preventDefault()},children:[i.jsx("defs",{children:i.jsx("pattern",{id:"grid",width:"28",height:"28",patternUnits:"userSpaceOnUse",children:i.jsx("circle",{cx:"14",cy:"14",r:"0.7",fill:q.gridDot})})}),i.jsx("rect",{width:"100%",height:"100%",fill:"url(#grid)"}),H.map($=>i.jsx(It,{block:$,allBlocks:e,onPointerDown:o,onBlockClick:r,onSocketClick:s,draggingIds:t,provisionalIds:n,editingSocket:c,onSocketInput:l,onSocketCommit:x,onSocketCancelEdit:m,onParamRemove:y,onMouthOpen:k,onMouthClose:_,onOutputDrag:B},$.instanceId)),L]})});so.displayName="Canvas";function io({onSelect:e}){const t=Y();return i.jsx("div",{style:{display:"flex",gap:4},children:Ue.map(n=>i.jsx("button",{onClick:()=>e(n),style:{background:t.id===n.id?t.switcherActiveBg:t.switcherBg,border:`1px solid ${t.switcherBorder}`,borderRadius:4,padding:"2px 9px",color:t.id===n.id?t.switcherActiveText:t.switcherText,fontSize:10,fontWeight:t.id===n.id?"bold":"normal",letterSpacing:.5,cursor:"pointer",transition:"color 0.1s, background 0.1s"},children:n.label},n.id))})}function Nr({canUndo:e,canRedo:t,onUndo:n,onRedo:o,notice:r,extra:s}){const c=Y(),l=x=>({width:28,height:24,padding:0,background:c.paletteBg,color:x?c.textPrimary:c.textMuted,border:`1px solid ${c.border}`,borderRadius:4,fontSize:14,lineHeight:1,cursor:x?"pointer":"default",opacity:x?1:.5});return i.jsxs("div",{style:{position:"absolute",top:8,right:8,display:"flex",alignItems:"center",gap:6,pointerEvents:"none"},children:[r&&i.jsx("span",{style:{fontSize:11,color:c.textPrimary,background:c.paletteBg,border:`1px solid ${c.accent}`,borderRadius:4,padding:"3px 8px"},children:r}),s&&i.jsx("div",{style:{pointerEvents:"auto"},children:s}),i.jsx("button",{type:"button",title:"Undo (Ctrl+Z)","aria-label":"Undo",disabled:!e,onClick:n,style:{...l(e),pointerEvents:"auto"},children:"↶"}),i.jsx("button",{type:"button",title:"Redo (Ctrl+Shift+Z)","aria-label":"Redo",disabled:!t,onClick:o,style:{...l(t),pointerEvents:"auto"},children:"↷"})]})}function Lr(e){try{return localStorage.getItem(e)}catch{return null}}function Hr(e,t){try{localStorage.setItem(e,t)}catch{}}let Pe=null;function zr(e){Pe===null&&(Pe=e)}function Wr(e){Pe===e&&(Pe=null)}function qr(e){Pe=e}function Ur(e){return Pe===null||Pe===e}function Vr({writers:e,onExport:t}){const n=Y(),[o,r]=f.useState(!1);return i.jsxs("div",{style:{position:"relative"},children:[i.jsx("button",{type:"button",onClick:()=>r(s=>!s),"aria-expanded":o,style:{height:24,padding:"0 8px",fontSize:11,background:n.paletteBg,color:n.textPrimary,border:`1px solid ${n.border}`,borderRadius:4,cursor:"pointer"},children:"Export ▾"}),o&&i.jsx("div",{role:"menu",style:{position:"absolute",top:28,right:0,minWidth:120,zIndex:10,background:n.paletteBg,border:`1px solid ${n.border}`,borderRadius:4,padding:3},children:e.map(s=>i.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{r(!1),t(s)},style:{display:"block",width:"100%",textAlign:"left",padding:"4px 8px",fontSize:11,background:"none",border:"none",color:n.textPrimary,cursor:"pointer"},children:[s.label," ",i.jsxs("span",{style:{color:n.textMuted},children:[".",s.fileExtension]})]},s.id))})]})}function Yr(e,t){const n=A(e.definitionId);if(!n)return{w:160,h:Fe};const o=n.blockType==="query"?Gt(e,t):eo(e.instanceId,t);return{w:le(n,e.paramSlots,t),h:o}}function Fr({peers:e,blocks:t,layout:n}){const o=Y();return i.jsx("g",{style:{pointerEvents:"none"},children:e.map(r=>{const{color:s}=r,c=[];if(r.typing){const l=t.get(r.typing.blockId),x=n.get(r.typing.blockId),m=l&&A(l.definitionId),y=m&&l&&Je(m,l.paramSlots,t).find(k=>k.index===r.typing.slot);x&&y&&c.push(i.jsxs("g",{transform:`translate(${x.x+y.x},${x.y+y.y})`,children:[i.jsx("path",{d:Jt(y.type,y.w,y.h),fill:o.socketBody,stroke:s,strokeWidth:2}),i.jsxs("text",{x:y.w/2,y:y.h/2+4,textAnchor:"middle",fill:s,fontSize:10,fontFamily:"sans-serif",children:[r.typing.text,"|"]})]},"typing"))}if(r.drag&&"leadId"in r.drag){const l=t.get(r.drag.leadId),x=n.get(r.drag.leadId);if(l&&x){const{w:m,h:y}=Yr(l,t);c.push(i.jsx("rect",{x:x.x-3,y:x.y-3,width:m+6,height:y+6,rx:5,fill:"none",stroke:s,strokeWidth:1.5,strokeDasharray:"5,3"},"origin"),i.jsxs("g",{transform:`translate(${r.drag.at.x},${r.drag.at.y})`,opacity:.5,children:[i.jsx(It,{block:l,allBlocks:t,isGhost:!0}),i.jsx("rect",{x:-3,y:-3,width:m+6,height:y+6,rx:5,fill:"none",stroke:s,strokeWidth:1.5})]},"ghost"))}}if(r.drag&&"definitionId"in r.drag){const l=A(r.drag.definitionId),x=l?le(l):120,m=l?$e(l):Fe;c.push(i.jsxs("g",{transform:`translate(${r.drag.at.x},${r.drag.at.y})`,children:[i.jsx("rect",{width:x,height:m,rx:4,fill:s,fillOpacity:.12,stroke:s,strokeWidth:1.5,strokeDasharray:"5,3"}),i.jsx("text",{x:8,y:m/2+4,fill:s,fontSize:11,fontWeight:"bold",fontFamily:"sans-serif",children:l?.name??r.drag.definitionId})]},"new"))}if(r.cursor){const l=r.name.length*6.5+10;c.push(i.jsxs("g",{transform:`translate(${r.cursor.x},${r.cursor.y})`,children:[i.jsx("path",{d:"M 0 0 L 0 14 L 4 10.5 L 7 17 L 9.5 16 L 6.5 9.5 L 11 9.5 Z",fill:s,stroke:"white",strokeWidth:1}),i.jsx("rect",{x:12,y:14,width:l,height:16,rx:3,fill:s}),i.jsx("text",{x:17,y:26,fill:"white",fontSize:10,fontFamily:"sans-serif",children:r.name})]},"cursor"))}return i.jsx("g",{children:c},r.clientId)})})}const Xr="local";function Kr(e,t,n){const o=e==="undo"?"Couldn't undo":e==="redo"?"Couldn't redo":"Your change was undone";return t==="HOST_REJECTED"?`${o}: ${n}`:`${o}: ${{TEXT_CHANGED:"someone else changed that parameter",PLACE_OCCUPIED:"someone else put a block there first",BLOCK_NOT_FOUND:"a block it needs was deleted",BLOCK_CHANGED:"someone else changed those blocks",NOT_AT_PLACE:"someone else moved that block",NOT_A_ROOT:"someone else moved that block",POSITION_CHANGED:"someone else moved that block",DEPENDENCIES_CHANGED:"someone else changed the packages"}[t]??"the canvas has changed"}.`}function at(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Qr(e,t){return e.embeddedInBlockId?t.get(e.embeddedInBlockId)?.paramSlots[e.embeddedSlotIndex]?.commandBlockId===e.instanceId:!1}function Gr(e){return e.kind==="next"?{next:e.blockId}:{mouth:e.blockId,slot:e.slotIndex}}async function $n(e,t){if(!e||!t)return!1;const n=new Map(e.map(c=>[We(c),c])),o=new Set(qe().map(c=>c.info.id).filter(c=>c.startsWith(yt))),r=[...o].filter(c=>!n.has(c)),s=[...n].filter(([c])=>!o.has(c));r.forEach(Ft);for(const[c,l]of s)await Yt({id:c,name:G(l),description:"",url:t(l),builtIn:!1});return r.length>0||s.length>0}function Zr(e){const t=new Map(qe().map(o=>[o.info.id,o.info.name])),n=new Map;return e.forEach(o=>{const r=Ln(o.definitionId);if(!r?.startsWith(yt))return;const s=t.get(r);n.set(s,(n.get(s)??0)+1)}),n}function Jr(e,t,n){const o=pt(e);return{instanceId:at(),definitionId:e,x:t,y:n,nextBlockId:null,parentBlockId:null,embeddedInBlockId:null,embeddedSlotIndex:-1,paramSlots:o.params.map(()=>({textValue:null,queryBlockId:null,commandBlockId:null}))}}function Lt(e,t){const n=[];let o=e;for(;o;)n.push(o),o=t.get(o)?.nextBlockId??null;return n}function Ht(e,t){const n=t.get(e);return n?.parentBlockId?Ht(n.parentBlockId,t):n&&Qr(n,t)?Ht(n.embeddedInBlockId,t):e}function zt(e,t){const n=A(e.definitionId);if(!n)return`[missing:${e.definitionId}]`;const o=e.paramSlots.map((r,s)=>{const c=n.params[s];if(c&&pe(n,c)){const x=(r.commandBlockId?Lt(r.commandBlockId,t):[]).map(m=>t.get(m)).filter(Boolean).map(m=>zt(m,t));return x.length>0?`{ ${x.join("; ")} }`:"{ }"}if(r.queryBlockId){const l=t.get(r.queryBlockId);if(l)return zt(l,t)}return r.textValue!==null&&r.textValue!==void 0?n.params[s]?.type==="string"?`"${r.textValue}"`:r.textValue:"_"});return`${n.id}(${o.join(", ")})`}function es({ghostPos:e,blocks:t}){const n=Y();if(!e)return null;if(e.instanceId){const x=t.get(e.instanceId);if(x)return i.jsx("svg",{style:{position:"fixed",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:9999},children:i.jsx("g",{transform:`translate(${e.x},${e.y})`,opacity:.8,children:i.jsx(It,{block:x,allBlocks:t,isGhost:!0})})})}const o=pt(e.defId),r=$e(o),s=o.blockType==="command",c=en(o),l=Ee(o);return i.jsxs("svg",{style:{position:"fixed",top:0,left:0,width:"100%",height:"100%",pointerEvents:"none",zIndex:9999},children:[s&&i.jsx("defs",{children:i.jsx("clipPath",{id:"ghost-pal-clip",children:i.jsx("path",{d:c})})}),i.jsxs("g",{transform:`translate(${e.x},${e.y})`,opacity:.8,children:[i.jsx("path",{d:c,fill:s?n.blockBody:o.color,stroke:s?n.blockBorder:"rgba(0,0,0,0.4)",strokeWidth:1.5}),s&&i.jsx("rect",{x:0,y:0,width:4,height:r+20,fill:o.color,clipPath:"url(#ghost-pal-clip)"}),l.length>0&&i.jsx(on,{mouths:l,w:le(o),isEmpty:()=>!0}),i.jsx(nn,{chips:Ze(o)}),i.jsx("text",{x:11,y:Ne(o)/2+4,fill:s?n.blockText:"white",fontSize:11,fontWeight:"bold",fontFamily:"sans-serif",style:{userSelect:"none"},children:o.name})]})]})}function ts(e,t){return e.returnType===t||(e.usableAs?.includes(t)??!1)}function co({blocksUrl:e="/blocks.json",blocksUrls:t,onRun:n,onThemeChange:o,navTabs:r,initialState:s,onSave:c,themeId:l,hideTitleBar:x,getStateRef:m,additionalBlocks:y,dependencies:k,onDependenciesChange:_,packageBlocksUrl:B,availablePackages:L,packageActions:N,collaboration:q,scriptWriters:H,onExport:$}){const[g,J]=f.useState(()=>{if(l)return Ue.find(d=>d.id===l)??Ae;const a=Lr("cardcq-theme");return Ue.find(d=>d.id===a)??Ae}),[K,ee]=f.useState(l);l!==K&&(ee(l),l&&J(Ue.find(a=>a.id===l)??Ae));const[Q,b]=f.useState(!1),[z,U]=f.useState(null),R=q?.commands,ae=q?.clientId??Xr,[oe,Le]=f.useState(()=>Rn({blocks:new Map((s?.blocks??[]).map(([a,d])=>[a,ve(d)])),dependencies:k??[]})),{state:de,provisionalIds:et}=f.useMemo(()=>In(oe),[oe]),P=de.blocks,u=f.useRef(oe),E=f.useRef(de);f.useEffect(()=>{u.current=oe,E.current=de});const V=(k??[]).map(We).join("|"),[Z,re]=f.useState(V);V!==Z&&(re(V),!R&&V!==oe.confirmed.dependencies.map(We).join("|")&&Le(a=>({...a,confirmed:{...a.confirmed,dependencies:k??[]}})));const xe=f.useRef(_);f.useEffect(()=>{xe.current=_});const[ye,Me]=f.useState(null),ge=f.useRef(null),te=f.useCallback(a=>{Me(a),ge.current&&clearTimeout(ge.current),ge.current=setTimeout(()=>Me(null),5e3)},[]);f.useEffect(()=>()=>{ge.current&&clearTimeout(ge.current)},[]);const se=f.useCallback(a=>{const d=u.current;u.current=a,E.current=In(a).state,Le(a),a.confirmed.dependencies!==d.confirmed.dependencies&&xe.current?.(a.confirmed.dependencies)},[]),ue=f.useCallback((a,d,h)=>{const p={id:d,clientId:ae,baseVersion:u.current.version,command:h};if(R){se(a),R.submit(p);return}const I=kn(a,p,a.version+1);I.outOfSync?(se(bn(a,d).sync),te("That change couldn't be made: the canvas has changed.")):se(I.sync)},[ae,R,se,te]),v=f.useCallback(a=>{if(!a)return;const d=at();ue(Qo(u.current,d,a),d,a)},[ue]),vt=f.useCallback(()=>{const a=at(),d=Go(u.current,a);d&&ue(d.sync,a,d.command)},[ue]),St=f.useCallback(()=>{const a=at(),d=Zo(u.current,a);d&&ue(d.sync,a,d.command)},[ue]),tt=q?.presence,sn=q?.presenceIntervalMs??Nn,ie=f.useRef(null),[cn,ln]=f.useState([]);f.useEffect(()=>{if(!tt)return;const a=new tr(h=>tt.publish(h),sn);ie.current=a;const d=tt.subscribe(h=>ln(h.filter(p=>p.clientId!==ae)));return()=>{a.updateNow({cursor:null,drag:null,typing:null}),a.dispose(),ie.current=null,d(),ln([])}},[tt,sn,ae]),f.useEffect(()=>{if(R)return R.subscribe(a=>{if(a.type==="snapshot"){const d={blocks:new Map(a.state.blocks.map(([p,I])=>[p,ve(I)])),dependencies:a.state.dependencies},h=Jo(d,a.version,u.current);se(h.sync),h.dropped>0&&te("Reloaded from the server: your unconfirmed changes were discarded.")}else if(a.type==="applied"){const d=kn(u.current,a.envelope,a.version);d.outOfSync?(te("Out of sync with the server: reloading…"),R.resync?.()):se(d.sync)}else{const d=bn(u.current,a.id);se(d.sync),d.action&&te(Kr(d.action.kind,a.code,a.message))}})},[R,se,te]);const[we]=f.useState(()=>Symbol("BlockEditor"));f.useEffect(()=>(zr(we),()=>Wr(we)),[we]);const an=f.useCallback(()=>qr(we),[we]);f.useEffect(()=>{function a(d){if(!Ur(we))return;const h=d.target;if(h&&(h.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(h.tagName))||!(d.ctrlKey||d.metaKey))return;const p=d.key.toLowerCase();p==="z"&&!d.shiftKey?(d.preventDefault(),vt()):(p==="z"&&d.shiftKey||p==="y"&&!d.metaKey)&&(d.preventDefault(),St())}return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[vt,St,we]);const ao=f.useMemo(()=>{const a=new Set;for(const d of P.values())A(d.definitionId)?.blockType==="start"&&a.add(d.definitionId);return a},[P]),[uo,nt]=f.useState(null),[fo,dn]=f.useState(new Set),[ho,un]=f.useState(!1),[ot,$t]=f.useState(0),[po,wt]=f.useState([]),[rt,Bt]=f.useState(()=>new Set),[fn,xo]=f.useState(null);if(fn?.blocks!==P||fn.registryVersion!==ot){xo({blocks:P,registryVersion:ot});const a=mr(P);a.some(d=>!rt.has(d))&&Bt(new Set([...rt,...a]))}const ne=f.useMemo(()=>xr(P,rt),[P,rt]),ce=f.useMemo(()=>Sr(ne),[ne,ot]);f.useEffect(()=>{m&&(m.current=()=>({blocks:[...P.entries()]}))},[P,m]);const fe=f.useRef(null),jt=f.useRef(!1),st=f.useRef(null),He=(t??[e]).join("|"),Ct=k!==void 0||q?.commands!==void 0&&B!==void 0,Tt=f.useRef(Ct?de.dependencies:void 0),Pt=f.useRef(B);f.useEffect(()=>{Tt.current=Ct?de.dependencies:void 0,Pt.current=B});const go=de.dependencies.map(We).join("|"),De=f.useRef(Promise.resolve()),[mo,yo]=f.useState(He);He!==mo&&(yo(He),b(!1),U(null)),f.useEffect(()=>{let a=!1;const d=He.split("|");return De.current=De.current.then(async()=>{if(!a)try{await rr(d[0]);for(let h=1;h<d.length&&!a;h++)await Yt({id:`__extra_${h}__`,name:`Extra ${h}`,description:"",url:d[h],builtIn:!0});if(a||(await $n(Tt.current,Pt.current),a))return;wt(qe()),$t(h=>h+1),b(!0)}catch(h){a||U(String(h))}}),()=>{a=!0}},[He]),f.useEffect(()=>{if(!Q)return;let a=!1;return De.current=De.current.then(async()=>{if(!a)try{if(!await $n(Tt.current,Pt.current))return;wt(qe()),$t(h=>h+1)}catch(d){U(String(d))}}),()=>{a=!0}},[Q,go]),f.useEffect(()=>{if(!Q)return;let a=!1;return De.current=De.current.then(()=>{if(!a)try{Ft("__inline__"),y&&y.length>0&&or({id:"__inline__",name:"Inline",description:"",url:"",builtIn:!0},y),wt(qe()),$t(d=>d+1)}catch(d){U(String(d))}}),()=>{a=!0}},[y,Q]);const ke=f.useCallback((a,d)=>{const h=st.current?.getBoundingClientRect()??{left:0,top:0};return{x:a-h.left,y:d-h.top}},[]),hn=f.useCallback((a,d,h,p,I)=>{if(A(h)?.blockType!=="command")return null;let C=null;const T=j=>{(!C||j.dist<C.dist)&&(C=j)},M=(j,W)=>{const F=Math.abs(a-j),S=Math.abs(d-W);return F<40&&S<24?Math.hypot(F,S):null};return ne.forEach(j=>{if(I.has(j.instanceId))return;const W=A(j.definitionId),F=ce.get(j.instanceId);if(!(!W||W.blockType==="query"||!F)){if(!j.nextBlockId||j.nextBlockId===p){const S=F.y+$e(W,j.paramSlots,ne),he=M(F.x,S);he!==null&&T({kind:"next",blockId:j.instanceId,snapX:F.x,snapY:S,dist:he})}for(const S of Ir(W,j.paramSlots,ne)){const he=F.x+S.x,it=F.y+S.y,ct=M(he,it);ct!==null&&T({kind:"mouth",blockId:j.instanceId,slotIndex:S.slot,snapX:he,snapY:it,dist:ct})}}}),C},[ne,ce]),pn=f.useCallback((a,d,h,p,I)=>{const w=A(h);if(!w||w.blockType!=="query")return null;const C=20;let T=null;return ne.forEach(M=>{if(I.has(M.instanceId))return;const j=A(M.definitionId),W=ce.get(M.instanceId);if(!j||!W)return;Je(j,M.paramSlots,ne).forEach(S=>{if(!ts(w,S.type))return;const he=M.paramSlots[S.index]?.queryBlockId;if(he&&he!==p)return;const it=W.x+S.x+S.w/2,ct=W.y+S.y+S.h/2,gn=Math.abs(a+S.w/2-it),mn=Math.abs(d+S.h/2-ct);if(gn<S.w/2+C&&mn<S.h/2+C){const yn=Math.hypot(gn,mn);(!T||yn<T.dist)&&(T={blockId:M.instanceId,slotIndex:S.index,snapX:W.x+S.x,snapY:W.y+S.y,dist:yn})}})}),T},[ne,ce]),ko=f.useCallback(a=>{if(fe.current?.moved)return;const d=Ht(a,P),p=Lt(d,P).map(I=>P.get(I)).filter(Boolean).map(I=>zt(I,P));n?.(p)},[P,n]),[bo,Et]=f.useState(null),ze=f.useRef(null),Io=f.useCallback((a,d)=>{if(fe.current?.moved)return;const h=E.current.blocks.get(a)?.paramSlots[d]?.textValue??null;ze.current={blockId:a,slotIndex:d,startText:h},Et(ze.current),ie.current?.updateNow({typing:{blockId:a,slot:d,text:h??""}})},[]),vo=f.useCallback((a,d,h)=>{ie.current?.update({typing:{blockId:a,slot:d,text:h}})},[]),So=f.useCallback((a,d,h)=>{const p=ze.current;ze.current=null,Et(null),!(!p||p.blockId!==a||p.slotIndex!==d)&&(ie.current?.updateNow({typing:null}),v(_t(a,d,p.startText,h)))},[v]),$o=f.useCallback(()=>{ze.current=null,Et(null),ie.current?.updateNow({typing:null})},[]),wo=f.useCallback((a,d)=>{const h=E.current,p=h.blocks.get(a),I=p?.paramSlots[d];if(!p||!I)return;if(!I.queryBlockId){v(_t(a,d,I.textValue,null));return}const w=A(p.definitionId),C=ce.get(a)??p,T=C.x+(w?le(w,p.paramSlots,h.blocks):0)+24;v(ft(h,I.queryBlockId,{x:T,y:C.y},null))},[ce,v]),Bo=f.useCallback((a,d)=>{fe.current?.moved||Bt(h=>new Set(h).add(Nt(a,d)))},[]),jo=f.useCallback((a,d)=>{Bt(T=>{const M=new Set(T);return M.delete(Nt(a,d)),M});const h=E.current,p=h.blocks.get(a);if(!p)return;const I=A(p.definitionId),w=ce.get(a)??p,C=w.x+(I?le(I,p.paramSlots,h.blocks):0)+24;v(Ko(h,a,d,{x:C,y:w.y}))},[ce,v]),Co=f.useCallback(a=>{const d=E.current,h=new Set(a.map(G)),p=new Set(d.dependencies.filter(w=>!h.has(G(w))).map(We)),I=[...d.blocks.values()].filter(w=>p.has(Ln(w.definitionId)??"")).map(w=>w.instanceId);v(On(d,a,I))},[v]),To=f.useCallback(a=>{J(a),l||Hr("cardcq-theme",a.id),o?.(a)},[o,l]),xn=f.useCallback((a,d)=>{a.preventDefault();const h=pt(d),p=le(h),I=$e(h);fe.current={type:"palette",defId:d,offsetX:p/2,offsetY:I/2,startClientX:a.clientX,startClientY:a.clientY,moved:!1},nt({x:a.clientX-p/2,y:a.clientY-I/2,defId:d}),a.target.setPointerCapture(a.pointerId)},[]),Po=f.useCallback((a,d)=>{a.preventDefault();const h=P.get(d);if(!h)return;const{x:p,y:I}=ke(a.clientX,a.clientY),{x:w,y:C}=ce.get(d)??h,T=p-w,M=I-C,W=A(h.definitionId)?.blockType==="query"?[d]:Lt(d,P);fe.current={type:"canvas",defId:h.definitionId,instanceId:d,carriedIds:W,offsetX:T,offsetY:M,startClientX:a.clientX,startClientY:a.clientY,moved:!1},dn(new Set([d])),nt({x:a.clientX-T,y:a.clientY-M,defId:h.definitionId,instanceId:d}),a.target.setPointerCapture(a.pointerId)},[P,ce,ke]);f.useEffect(()=>{function a(h){const p=fe.current;if(!p)return;let I=!1;if(!p.moved&&(Math.abs(h.clientX-p.startClientX)>4||Math.abs(h.clientY-p.startClientY)>4)&&(p.moved=!0,I=!0),!p.moved)return;nt({x:h.clientX-p.offsetX,y:h.clientY-p.offsetY,defId:p.defId,instanceId:p.instanceId});const w=ke(h.clientX-p.offsetX,h.clientY-p.offsetY),C=p.type==="canvas"?{drag:{leadId:p.instanceId,at:w},cursor:ke(h.clientX,h.clientY)}:{drag:{definitionId:p.defId,at:w},cursor:ke(h.clientX,h.clientY)};if(I?ie.current?.updateNow(C):ie.current?.update(C),p.type==="canvas"){const T=st.current?.getBoundingClientRect(),M=!!T&&h.clientX<T.left;M!==jt.current&&(jt.current=M,un(M))}}function d(h){const p=fe.current;if(!p||(fe.current=null,nt(null),dn(new Set),jt.current=!1,un(!1),!p.moved))return;ie.current?.updateNow({drag:null});const I=st.current?.getBoundingClientRect();if(!I)return;const w=E.current;if(p.type==="canvas"&&h.clientX<I.left){v(An(w,p.instanceId));return}const C=h.clientX-p.offsetX-I.left,T=h.clientY-p.offsetY-I.top,M=pt(p.defId),j=p.type==="canvas"?p.instanceId:null,W=new Set(j?Qe(w.blocks,j):[]);let F=null;if(M.blockType==="query"){const S=pn(C,T,p.defId,j,W);S&&(F={socket:S.blockId,slot:S.slotIndex})}else{const S=hn(C,T,p.defId,j,W);S&&(F=Gr(S))}if(p.type==="palette"){if(h.clientX<I.left||h.clientX>I.right||h.clientY<I.top||h.clientY>I.bottom||M.blockType==="start"&&[...w.blocks.values()].some(he=>he.definitionId===p.defId))return;v(_n(w,Jr(p.defId,C,T),{x:C,y:T},F))}else v(ft(w,j,{x:C,y:T},F))}return document.addEventListener("pointermove",a),document.addEventListener("pointerup",d),()=>{document.removeEventListener("pointermove",a),document.removeEventListener("pointerup",d)}},[hn,pn,v,ke]);const Eo=f.useCallback(a=>{fe.current?.moved||ie.current?.update({cursor:ke(a.clientX,a.clientY)})},[ke]),Mo=f.useCallback(()=>{fe.current?.moved||ie.current?.updateNow({cursor:null})},[]),Do=f.useCallback(a=>{const d=a.write(to(E.current,A));if($){$(d,a);return}const h=URL.createObjectURL(new Blob([d],{type:"text/plain"})),p=document.createElement("a");p.href=h,p.download=`behavior.${a.fileExtension}`,p.click(),URL.revokeObjectURL(h)},[$]),Mt={display:"flex",flexDirection:"column",flex:1,minHeight:0,width:"100%",height:"100%",overflow:"hidden",background:g.appBg,color:g.textPrimary,fontFamily:"system-ui, sans-serif",boxSizing:"border-box"},_o={display:"flex",flex:1,minHeight:0,overflow:"hidden"};return z?i.jsx(Ve.Provider,{value:g,children:i.jsxs("div",{style:{...Mt,alignItems:"center",justifyContent:"center",color:"#c06060",fontFamily:"monospace"},children:["Failed to load blocks: ",z]})}):Q?i.jsx(Ve.Provider,{value:g,children:i.jsxs("div",{style:Mt,onPointerDownCapture:an,onFocusCapture:an,children:[!x&&i.jsxs("div",{style:{flexShrink:0,display:"flex",alignItems:"center",gap:10,padding:"0 14px",height:38,background:g.titleBg,borderBottom:`1px solid ${g.border}`},children:[i.jsx("span",{style:{color:g.titlePrimaryText,fontWeight:"bold",fontSize:13,letterSpacing:1,textTransform:"uppercase"},children:"CardCQ"}),i.jsx("span",{style:{color:g.titleSecondaryText,fontSize:11,letterSpacing:.5},children:"Behavior Editor"}),r,i.jsxs("div",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:8},children:[c&&i.jsx("button",{onClick:()=>c({blocks:[...P.entries()]}),style:{padding:"3px 10px",fontSize:11,fontWeight:"bold",background:g.titleBg,color:g.titlePrimaryText,border:`1px solid ${g.border}`,borderRadius:4,cursor:"pointer",letterSpacing:.5},children:"Save"}),!l&&i.jsx(io,{onSelect:To})]})]}),i.jsxs("div",{style:_o,children:[i.jsx(Or,{onPointerDown:xn,isDropTarget:ho,registryVersion:ot,packages:Ct&&(_||R)?{available:L??[],dependencies:de.dependencies,onChange:Co,actions:N,blockCounts:Zr(P),conflictCounts:new Map(po.filter(a=>a.info.id.startsWith(yt)).map(a=>[a.info.name,a.conflictIds.length]))}:void 0,placedStartIds:ao}),i.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",position:"relative"},onPointerMove:Eo,onPointerLeave:Mo,children:[i.jsx(so,{ref:st,blocks:ne,draggingIds:fo,provisionalIds:et,onBlockPointerDown:Po,onBlockClick:ko,onSocketClick:Io,editingSocket:bo,onSocketInput:vo,onSocketCommit:So,onSocketCancelEdit:$o,onParamRemove:wo,onMouthOpen:Bo,onMouthClose:jo,onOutputDrag:xn,overlay:cn.length>0?i.jsx(Fr,{peers:cn,blocks:ne,layout:ce}):null}),i.jsx(Nr,{canUndo:ht(oe)&&oe.undo.length>0,canRedo:ht(oe)&&oe.redo.length>0,onUndo:vt,onRedo:St,notice:ye,extra:H&&H.length>0?i.jsx(Vr,{writers:H,onExport:Do}):null})]})]}),i.jsx(es,{ghostPos:uo,blocks:ne})]})}):i.jsx(Ve.Provider,{value:g,children:i.jsx("div",{style:{...Mt,alignItems:"center",justifyContent:"center",color:g.textMuted},children:"Loading…"})})}function rn(e){const t=e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/[^A-Za-z0-9]+/g,"_").replace(/^_+|_+$/g,"").toLowerCase();return/^[0-9]/.test(t)?`_${t}`:t||"_"}function Wt(e){return JSON.stringify(e)}function lo(e,t){switch(e.kind){case"text":return t==="string"?Wt(e.text):t==="boolean"?e.text.toLowerCase()==="true"?"True":"False":/^-?\d+(\.\d+)?$/.test(e.text)?e.text:Wt(e.text);case"query":return dt(e.node);case"body":return"None";case"empty":return"None"}}function dt(e){const t=e.args.filter(n=>n.value.kind!=="body").map(n=>lo(n.value,n.type));return`${rn(e.name)}(${t.join(", ")})`}function mt(e,t){return e.length===0?[`${t}pass`]:e.flatMap(n=>{const o=n.args.filter(s=>s.value.kind==="body");if(o.length===0)return[`${t}${dt(n)}`];const r=`${t} `;if(o.length===1){const s=o[0].value;return[`${t}with ${dt(n)}:`,...mt(s.body,r)]}return[`${t}with ${dt(n)}:`,...o.flatMap(s=>[`${r}with ${rn(s.name)}:`,...mt(s.value.body,`${r} `)])]})}const ns={id:"python",label:"Python",fileExtension:"py",write(e){return`# Generated by the block editor
|
|
2
2
|
|
|
3
|
-
${e.roots.map((n,
|
|
4
|
-
`)}return[`def chain_${
|
|
3
|
+
${e.roots.map((n,o)=>{const[r,...s]=n.body;if(r?.blockType==="start"){const c=r.args.filter(l=>l.value.kind!=="body").map(l=>lo(l.value,l.type));return[`@on(${[Wt(r.name),...c].join(", ")})`,`def ${rn(r.name)}():`,...mt(s," ")].join(`
|
|
4
|
+
`)}return[`def chain_${o+1}():`,...mt(n.body," ")].join(`
|
|
5
5
|
`)}).join(`
|
|
6
6
|
|
|
7
7
|
|
|
8
8
|
`)}
|
|
9
|
-
`}};class
|
|
9
|
+
`}};class os{state;version=0;clients=new Map;delayMs;constructor(t,n=0){this.state=t,this.delayMs=n}get delay(){return this.delayMs}setDelay(t){this.delayMs=t}get current(){return{state:this.state,version:this.version}}connect(t,n,o){const r=this.clients.get(t)??{id:t,name:n,color:o,commandListeners:new Set,presenceListeners:new Set,presence:{cursor:null,drag:null,typing:null}};return r.name=n,r.color=o,this.clients.set(t,r),{commands:{submit:l=>this.later(()=>this.receive(l)),subscribe:l=>(r.commandListeners.add(l),this.later(()=>l(this.snapshot())),()=>r.commandListeners.delete(l)),resync:()=>this.later(()=>r.commandListeners.forEach(l=>l(this.snapshot())))},presence:{publish:l=>{r.presence=l,this.broadcastPresence()},subscribe:l=>(r.presenceListeners.add(l),l(this.peersOf(t)),()=>r.presenceListeners.delete(l))}}}disconnect(t){this.clients.delete(t)&&this.broadcastPresence()}later(t){this.delayMs>0?setTimeout(t,this.delayMs):queueMicrotask(t)}snapshot(){return{type:"snapshot",state:{blocks:[...this.state.blocks.entries()],dependencies:this.state.dependencies},version:this.version}}receive(t){try{this.state=Re(this.state,t.command)}catch(o){if(!(o instanceof O))throw o;const r={type:"rejected",id:t.id,code:o.code,message:o.message};this.clients.get(t.clientId)?.commandListeners.forEach(s=>s(r));return}this.version+=1;const n={type:"applied",envelope:t,version:this.version};this.clients.forEach(o=>o.commandListeners.forEach(r=>r(n)))}peersOf(t){return[...this.clients.values()].filter(n=>n.id!==t).map(n=>({...n.presence,clientId:n.id,name:n.name,color:n.color}))}broadcastPresence(){this.clients.forEach(t=>t.presenceListeners.forEach(n=>n(this.peersOf(t.id))))}}exports.BlockEditor=co;exports.COMMANDS_VERSION=Oo;exports.COMMAND_PARAM_TYPE=Ye;exports.CommandRejected=O;exports.LocalServer=os;exports.THEMES=Ue;exports.ThemeContext=Ve;exports.ThemeSwitcher=io;exports.applyCommand=Re;exports.changeDependencies=On;exports.compareVersions=wn;exports.darkTheme=Ae;exports.default=co;exports.deleteChain=An;exports.fragmentOf=Qe;exports.invertCommand=Vt;exports.moveChain=ft;exports.normalizeBlock=ve;exports.normalizeSlot=Ke;exports.normalizeText=Ce;exports.packageKey=G;exports.placeNewBlock=_n;exports.placeOf=bt;exports.pythonWriter=ns;exports.roundPosition=Ut;exports.samePlace=En;exports.setSocketText=_t;exports.toProgram=to;exports.useTheme=Y;
|