@yuzhouu/canvas-kit 0.1.19 → 0.1.20

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.
@@ -19,7 +19,7 @@ Pr("circle",{cx:"3",cy:"7",r:"1"}),
19
19
  Pr("circle",{cx:"7",cy:"7",r:"1"}),
20
20
  Pr("circle",{cx:"3",cy:"11",r:"1"}),
21
21
  Pr("circle",{cx:"7",cy:"11",r:"1"})]})}):null,u?Pr("span",{"aria-hidden":"true",style:{alignItems:"center",display:"flex",flex:"0 0 auto",marginRight:4,pointerEvents:"none"},children:u}):null,
22
- br("div",{"data-ui":h.name,"data-shape-id":t.id,role:m&&!n?"button":void 0,"aria-label":m&&!n?`${c}: ${k}`:void 0,onClick:m?D:void 0,onPointerDown:m?F:void 0,style:{background:m&&n?"var(--land-surface-bg, white)":void 0,borderRadius:4,boxShadow:m&&n?"inset 0 0 0 1.5px var(--land-selection, #2563eb)":void 0,color:m&&n?"transparent":"inherit",cursor:m?"text":"grab",height:m&&n?"100%":void 0,minWidth:m&&n?32:void 0,overflow:m&&n?"visible":"hidden",padding:S?`0 6px 0 ${y?0:6}px`:0,pointerEvents:"auto",position:"relative",textOverflow:"ellipsis",whiteSpace:"pre",width:m&&n?"auto":void 0},children:[m?Pr("input",{ref:I,"data-ui":h.input,"data-shape-id":t.id,"aria-label":l,value:i,autoComplete:"off",disabled:!n,readOnly:!n,spellCheck:!1,onBlur:R,onChange:A,onCompositionStart:K,onCompositionEnd:Y,onKeyDown:X,onPointerDown:F,style:{background:"none",border:0,borderRadius:4,boxSizing:"border-box",color:"var(--land-text-primary, #0f172a)",cursor:"text",display:n?void 0:"none",font:"inherit",height:"100%",inset:0,lineHeight:"24px",minWidth:0,outline:0,padding:"0 6px",position:"absolute",userSelect:"text",width:"100%"}}):null,k+String.fromCharCode(8203)]})]})})})}import{createContext as cr,memo as lr,useCallback as hr,useContext as pr,useEffect as ur,useId as gr,useLayoutEffect as fr,useMemo as mr,useRef as Sr,useState as yr,useSyncExternalStore as Ir}from"react";import{Fragment as wr,jsx as Pr,jsxs as br}from"react/jsx-runtime";var vr=class{graph;name;current;isEqual;lastChangedEpoch;consumers=new Set;constructor(e,t,n,i){this.graph=e,this.name=t,this.current=n,this.isEqual=i,this.lastChangedEpoch=e.getEpoch()}get(){return this.graph.trackDependency(this),this.current}peek(){return this.current}__unsafe__isEqual(e,t){return this.isEqual?this.isEqual(e,t):Object.is(e,t)}__unsafe__restore(e,t){this.current=e,this.lastChangedEpoch=t}set(e){const t=this.current;return this.__unsafe__isEqual(t,e)?t:(this.graph.noteInitialValue(this,t,this.lastChangedEpoch),this.graph.advanceEpoch(),this.lastChangedEpoch=this.graph.getEpoch(),this.current=e,this.graph.atomDidChange(this),e)}update(e){return this.set(e(this.current))}},xr=Symbol("UNINITIALIZED"),Cr=class{graph;name;derive;isEqual;isComputed=!0;lastChangedEpoch;lastCheckedEpoch=-1;consumers=new Set;state=xr;dependencies=[];dependencyEpochs=[];consumerNodeValue=null;constructor(e,t,n,i){this.graph=e,this.name=t,this.derive=n,this.isEqual=i,this.lastChangedEpoch=e.getEpoch()}get(){return this.graph.trackDependency(this),this.peek()}peek(){if(this.lastCheckedEpoch===this.graph.getEpoch())return this.state;if(this.state!==xr&&!this.haveDependenciesChanged())return this.lastCheckedEpoch=this.graph.getEpoch(),this.state;let e,t;this.graph.startCapture(this.consumerNode);try{e=this.derive(this.state)}finally{t=this.graph.stopCapture()}for(const n of this.dependencies)t.has(n)||n.consumers.delete(this.consumerNode);this.dependencies=[...t],this.dependencyEpochs=this.dependencies.map(e=>e.lastChangedEpoch);for(const n of this.dependencies)n.consumers.add(this.consumerNode);return this.state!==xr&&(this.isEqual?this.isEqual(this.state,e):Object.is(this.state,e))||(this.state=e,this.graph.advanceEpoch(),this.lastChangedEpoch=this.graph.getEpoch()),this.lastCheckedEpoch=this.graph.getEpoch(),this.state}get consumerNode(){return this.consumerNodeValue||(this.consumerNodeValue={type:"computed",signal:this}),this.consumerNodeValue}haveDependenciesChanged(){for(let e=0;e<this.dependencies.length;e++){const t=this.dependencies[e];if(t.peek(),t.lastChangedEpoch!==this.dependencyEpochs[e])return!0}return!1}},Mr=class{graph;name;fn;options;dependencies=[];dependencyEpochs=[];lastReactedEpoch=-1;isActive=!1;consumerNode={type:"effect",notify:()=>this.maybeSchedule()};constructor(e,t,n,i){this.graph=e,this.name=t,this.fn=n,this.options=i}attach(){this.isActive=!0,this.execute()}detach(){this.isActive=!1;for(const e of this.dependencies)e.consumers.delete(this.consumerNode);this.dependencies=[],this.dependencyEpochs=[]}maybeSchedule(){this.isActive&&this.lastReactedEpoch!==this.graph.getEpoch()&&(this.haveDependenciesChanged()?this.options?.scheduleEffect?this.options.scheduleEffect(()=>this.execute()):this.execute():this.lastReactedEpoch=this.graph.getEpoch())}execute(){if(this.isActive){for(const e of this.dependencies)e.consumers.delete(this.consumerNode);this.graph.startCapture(this.consumerNode);try{this.fn()}finally{const e=this.graph.stopCapture();this.dependencies=[...e],this.dependencyEpochs=this.dependencies.map(e=>e.lastChangedEpoch);for(const t of this.dependencies)t.consumers.add(this.consumerNode);this.lastReactedEpoch=this.graph.getEpoch()}}}haveDependenciesChanged(){for(let e=0;e<this.dependencies.length;e++){const t=this.dependencies[e];if(t.peek(),t.lastChangedEpoch!==this.dependencyEpochs[e])return!0}return!1}},Tr=null,Br=class{epoch=0;currentTransaction=null;captureStack=null;atom=(e,t,n)=>((e,t,n,i)=>new vr(e,t,n,i?.isEqual))(this,e,t,n);computed=(e,t,n)=>((e,t,n,i)=>new Cr(e,t,n,i?.isEqual))(this,e,t,n);effect=(e,t,n)=>((e,t,n,i)=>{const s=new Mr(e,t,n,i);return s.attach(),()=>s.detach()})(this,e,t,n);transact=e=>{if(this.currentTransaction)return void e();const t={initialAtomSnapshots:new Map};this.currentTransaction=t;try{e()}catch(s){throw this.restoreInitialAtomSnapshots(t),this.currentTransaction=null,s}const n=[];let i=!1;for(const[o,r]of t.initialAtomSnapshots){const e=o.peek();o.__unsafe__isEqual(r.value,e)?(o.__unsafe__restore(r.value,r.lastChangedEpoch),i=!0):n.push(o)}i&&this.advanceEpoch(),this.currentTransaction=null,this.flushChanges(n)};getEpoch(){return this.epoch}isComputingSignal(){return"computed"===this.captureStack?.consumer.type}advanceEpoch(){return++this.epoch}noteInitialValue(e,t,n){this.currentTransaction&&!this.currentTransaction.initialAtomSnapshots.has(e)&&this.currentTransaction.initialAtomSnapshots.set(e,{value:t,lastChangedEpoch:n})}startCapture(e){this.captureStack={consumer:e,dependencies:new Set,previous:this.captureStack},Tr={graph:this,previous:Tr}}stopCapture(){if(!this.captureStack)throw new Error("Cannot stop dependency capture because no capture is active.");if(Tr?.graph!==this)throw new Error("SignalGraph dependency capture stack is out of order.");const e=this.captureStack;return this.captureStack=e.previous,Tr=Tr.previous,e.dependencies}trackDependency(e){if(Tr&&Tr.graph!==this)throw new Error("Cannot read signals across different SignalGraph instances while capturing dependencies.");this.captureStack&&(this.captureStack.dependencies.add(e),e.consumers.add(this.captureStack.consumer))}atomDidChange(e){this.currentTransaction||this.flushChanges([e])}restoreInitialAtomSnapshots(e){if(0!==e.initialAtomSnapshots.size){for(const[t,n]of e.initialAtomSnapshots)t.__unsafe__restore(n.value,n.lastChangedEpoch);this.advanceEpoch()}}flushChanges(e){const t=new Set,n=new Set,i=e=>{for(const s of e)n.has(s)||(n.add(s),"effect"===s.type?t.add(s):i(s.signal.consumers))};for(const a of e)i(a.consumers);let s,o=!1;for(const a of t)try{a.notify()}catch(r){o||(s=r,o=!0)}if(o)throw s}},kr=class{undoStack=[];redoStack=[];get canUndo(){return this.undoStack.length>0}get canRedo(){return this.redoStack.length>0}clear(){this.undoStack.length=0,this.redoStack.length=0}append(e,n="change"){t(e)||(this.undoStack.push(((e,t)=>({forward:t,inverse:i(t),label:e}))(n,e)),this.redoStack.length=0)}undo(){const e=this.undoStack.pop()??null;return e?(this.redoStack.push(e),e):null}redo(){const e=this.redoStack.pop()??null;return e?(this.undoStack.push(e),e):null}rollbackUndo(e){if(this.redoStack.at(-1)!==e)throw new Error("Cannot roll back an outdated history undo.");this.redoStack.pop(),this.undoStack.push(e)}rollbackRedo(e){if(this.undoStack.at(-1)!==e)throw new Error("Cannot roll back an outdated history redo.");this.undoStack.pop(),this.redoStack.push(e)}getEntries(){return this.undoStack}},Er=class{signals;records;activeTransaction=null;recordAtoms=new Map;revisionAtom;draftRevisionAtom;listeners=new Set;writeGuard;constructor(t,n={}){this.signals=n.signals??e(),this.revisionAtom=this.signals.atom("store.revision",0),this.draftRevisionAtom=this.signals.atom("store.draftRevision",0),this.records=new Map(t.map(e=>[e.id,e])),this.writeGuard=n.writeGuard}get(e){const t=this.activeTransaction?.journal.get(e);return t?t.after:this.records.get(e)}getRevision(){return this.revisionAtom.get()}getActiveTransactionRevision(){const e=this.activeTransaction;return e?(this.draftRevisionAtom.get(),e.revision):null}getActiveTransactionDiff(){const e=this.activeTransaction;if(!e)throw new Error("Store.getActiveTransactionDiff() requires an active transaction.");return o(e.journal)}getRecordSignal(e){let t=this.recordAtoms.get(e);if(t)return t;const n=this.records.get(e);t=this.signals.atom(`store.record.${e}`,n),this.recordAtoms.set(e,t);const i=this.get(e);return i!==n&&t.set(i),t}getAll(){if(this.signals.isComputingSignal())throw new Error("Store.getAll() cannot run while deriving a computed signal. Read a keyed record or indexed query signal instead.");return Array.from(this.getReadableRecords().values())}getByScope(e){return this.getAll().filter(t=>"scope"in t&&t.scope===e)}listen(e){return this.listeners.add(e),()=>this.listeners.delete(e)}atomic(e,n="system"){if(this.activeTransaction)return void e();let i,s=[],a=!1;try{this.signals.transact(()=>{const i=this.draftRevisionAtom.peek(),a={revision:i,initialDraftRevision:i,journal:new Map};this.activeTransaction=a,this.bumpDraftRevision(a);let d=!1;try{e();const i=o(a.journal);if(t(i))return;const c={source:n,diff:i};this.writeGuard?.(c),r(this.records,a.journal),d=!0,this.revisionAtom.set(this.revisionAtom.peek()+1),this.activeTransaction=null,s=this.notifyListeners(c)}catch(c){throw d||this.restoreTransactionSignals(a),c}finally{this.activeTransaction=null}})}catch(d){i=d,a=!0}if(s.length>0)throw s[0];if(a)throw i}put(e,t="system"){this.atomic(()=>{for(const t of e)this.stageRecord(t.id,t)},t)}remove(e,t="system"){this.atomic(()=>{for(const t of e)this.stageRecord(t,void 0)},t)}applyDiff(e,t="system"){this.atomic(()=>{for(const t of e.added)this.stageRecord(t.id,t);for(const t of e.updated)this.stageRecord(t.after.id,t.after);for(const t of e.removed)this.stageRecord(t.id,void 0)},t)}stageRecord(e,t){const n=this.requireActiveTransaction(),i=this.get(e);if(i===t)return;const s=n.journal.get(e)??{before:this.records.get(e),after:t,moveToEnd:!1};s.after=t,void 0===i&&void 0!==t&&(s.moveToEnd=!0,n.journal.delete(e)),n.journal.set(e,s),this.bumpDraftRevision(n),this.recordAtoms.get(e)?.set(t)}getReadableRecords(){const e=this.activeTransaction;if(!e)return this.records;const t=new Map(this.records);return r(t,e.journal),t}requireActiveTransaction(){if(!this.activeTransaction)throw new Error("Store mutations must run inside store.atomic");return this.activeTransaction}bumpDraftRevision(e){const t=this.draftRevisionAtom.peek()+1;e.revision=t,this.draftRevisionAtom.set(t)}restoreTransactionSignals(e){for(const[t]of e.journal)this.recordAtoms.get(t)?.set(this.records.get(t));this.draftRevisionAtom.set(e.initialDraftRevision)}notifyListeners(e){const t=[];for(const i of this.listeners)try{i(e)}catch(n){t.push(n)}return t}},Ar="document:main",Rr="page:default",Kr="session:main",Yr={x:0,y:0,z:1},Xr=Symbol("editorStore"),Fr=new Set,Dr=class{editor;suppressedReactionIds=Fr;constructor(e){this.editor=e}getSuppressedReactionIds(){return this.suppressedReactionIds}runWithSuppressedReactions(e,t,...n){const i=this.suppressedReactionIds,s=new Set(i);for(const o of e)s.add(o);if(s.size===i.size)return v(t);this.suppressedReactionIds=s;try{return v(t)}finally{this.suppressedReactionIds=i}}getConflictingBindings(e){const t=this.getExclusiveBindingKey(e);return t?this.getAllBindings().filter(n=>n.id!==e.id&&n.type===e.type&&this.getExclusiveBindingKey(n)===t):[]}canBind(e){const t=this.getEndpointContext(e);return!(!t||0===e.endpoints.length)&&(this.editor.bindings.getUtil(e).canBind?.(this.editor,e,t)??!0)}syncCreatedBinding(e,t){const n=this.editor.bindings.getUtil(e).onBindingCreate?.(this.editor,e);this.applyEffect(n,t,e.id),this.syncShapeCompanionState(P(e),t,e.id)}syncUpdatedBinding(e,t,n){const i=this.editor.bindings.getUtil(t).onBindingUpdate?.(this.editor,e,t);this.applyEffect(i,n,t.id),this.syncShapeCompanionState([...P(e),...P(t)],n,t.id)}repairLoadedBindings(e){S(this.editor).atomic(()=>{const t=new Set,n=new Set;for(const s of this.getAllBindings()){if(!this.getEndpointContext(s)){this.applyEffect(this.editor.bindings.getUtil(s).onInvalidBindingLoad?.(this.editor,s),e,s.id),S(this.editor).remove([s.id],e);continue}if(!this.canBind(s)){this.applyEffect(this.editor.bindings.getUtil(s).onInvalidBindingLoad?.(this.editor,s),e,s.id),S(this.editor).remove([s.id],e);continue}const i=this.getExclusiveBindingKey(s);if(i){if(t.has(i)){S(this.editor).remove([s.id],e);continue}t.add(i)}const o=this.editor.bindings.getUtil(s).onBindingLoad?.(this.editor,s);this.applyEffect(o,e,s.id);for(const e of P(s))n.add(e)}const i=S(this.editor).getAll().filter(p).filter(e=>!this.editor.shapes.getUtil(e).isValidAfterBindingLoad(e,{editor:this.editor})).map(e=>e.id);i.length>0&&this.editor.commands.deleteShapes(i,{source:e}),this.syncShapeCompanionState(Array.from(n),e)},e)}handleShapeChanges(e,t){if(0===e.length)return;const n=this.suppressedReactionIds,i=new Set(e.map(e=>e.after.id)),s=new Set,o=new Set,r=(e,i,r,a)=>{for(const d of this.editor.bindings.getForShape(e.id)){if(n.has(d.id))continue;if("ancestry"===a&&o.has(d.id))continue;const c=`${d.id}:${e.id}:${a}`;if(s.has(c))continue;s.add(c),"self"===a&&o.add(d.id);const l=b(d,e.id),h=this.editor.bindings.getUtil(d).onAfterShapeChange?.(this.editor,d,{before:i,after:r,...l,reason:a});this.applyEffect(h,t,d.id)}};for(const a of e)r(a.after,a.before,a.after,"self");for(const a of e)if(w(a))for(const e of this.editor.layers.getDescendantIds(a.after.id)){if(i.has(e))continue;const t=this.editor.shapes.get(e);t&&r(t,t,t,"ancestry")}this.syncShapeCompanionState(e.filter(({before:e,after:t})=>e.isHidden!==t.isHidden||e.isLocked!==t.isLocked).map(({after:e})=>e.id),t)}getShapeCompanionRootId(e){return this.getShapeCompanionRootIds([e]).get(e)??e}getShapeCompanionRootIds(e,t=this.getAllBindings()){const n=I(e,t,e=>this.editor.bindings.getUtil(e)),i=new Map;for(const s of e){const e=n.get(s)??s;i.set(s,this.editor.shapes.get(e)?e:s)}return i}getShapeCompanionMemberIds(e){const t=this.getShapeCompanionContext(),n=[],i=new Set;for(const s of e){const e=t.rootIdByShapeId.get(s)??s;if(t.shapeById.has(e))for(const s of[e,...t.memberIdsByRootId.get(e)??[]])i.has(s)||(i.add(s),n.push(s))}return n}cleanupBindingsForDeletedShapes(e,t){if(0===e.length)return;const n=new Set(e),i=new Map;for(const s of e)for(const e of this.editor.bindings.getForShape(s))i.set(e.id,e);for(const s of i.values()){const e=P(s).filter(e=>n.has(e));for(const n of e){const e=this.editor.shapes.get(n);if(!e)continue;const i=this.editor.bindings.getUtil(s).onBeforeDeleteShape?.(this.editor,s,{shape:e,...b(s,n)});this.applyEffect(i,t,s.id)}if(n.has(s.ownerId)){S(this.editor).remove([s.id],t);continue}const i=this.editor.bindings.get(s.id);if(!i)continue;const o=i.endpoints.filter(({targetId:e})=>!n.has(e));o.length!==i.endpoints.length&&(0===o.length?S(this.editor).remove([i.id],t):S(this.editor).put([{...i,endpoints:o}],t))}}cleanupBindings(e,t){for(const n of e){const e=this.editor.bindings.get(n);if(!e)continue;const i=this.editor.bindings.getUtil(e).onBeforeDeleteBinding?.(this.editor,e);this.applyEffect(i,t,e.id)}}applyEffect(e,t,n){if(!e)return;const i=new Set(e.suppressBindingIds??[]);n&&i.add(n),this.runWithSuppressedReactions(i,()=>{e.deleteBindingIds&&e.deleteBindingIds.length>0&&S(this.editor).remove(Array.from(new Set(e.deleteBindingIds)),t),e.bindings&&e.bindings.length>0&&S(this.editor).put(e.bindings,t),e.shapes&&e.shapes.length>0&&this.editor.commands.updateShapes(e.shapes.map(e=>({id:e.id,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,parentId:e.parentId,index:e.index,props:e.props,meta:e.meta})),{source:t}),e.deleteShapeIds&&e.deleteShapeIds.length>0&&this.editor.commands.deleteShapes(Array.from(new Set(e.deleteShapeIds)),{source:t})})}syncShapeCompanionState(e,t,n){if(0===e.length)return;const i=this.getShapeCompanionContext(),s=new Set,o=[];for(const r of e){const e=i.rootIdByShapeId.get(r)??r;if(s.has(e))continue;s.add(e);const t=i.shapeById.get(e);if(t)for(const n of i.memberIdsByRootId.get(e)??[]){const e=i.shapeById.get(n);!e||e.isHidden===t.isHidden&&e.isLocked===t.isLocked||o.push({...e,isHidden:t.isHidden,isLocked:t.isLocked})}}o.length>0&&this.applyEffect({shapes:o},t,n)}getShapeCompanionContext(){const e=S(this.editor).getAll(),t=e.filter(p).sort((e,t)=>e.parentId===t.parentId?e.index.localeCompare(t.index)||e.id.localeCompare(t.id):e.parentId.localeCompare(t.parentId)),n=new Map(t.map(e=>[e.id,e])),i=new Map(I(t.map(e=>e.id),e.filter(g),e=>this.editor.bindings.getUtil(e))),s=new Map;for(const o of t){const e=i.get(o.id)??o.id,t=n.has(e)?e:o.id;if(i.set(o.id,t),t===o.id)continue;const r=s.get(t);r?r.push(o.id):s.set(t,[o.id])}return{memberIdsByRootId:s,rootIdByShapeId:i,shapeById:n}}getAllBindings(){return S(this.editor).getAll().filter(g).sort((e,t)=>e.id.localeCompare(t.id))}getEndpointContext(e){const t=this.editor.shapes.get(e.ownerId);if(!t)return null;const n=e.endpoints.map(e=>{const t=this.editor.shapes.get(e.targetId);return t?{endpoint:e,targetShape:t}:null});return n.some(e=>!e)?null:{ownerShape:t,endpoints:n.filter(e=>!!e)}}getExclusiveBindingKey(e){const t=this.editor.bindings.getUtil(e).getExclusiveBindingKey?.(e);return t?`${e.type}:${t}`:null}},Or=class{registry=new Map;register(e){this.registry.set(e.type,e)}values(){return this.registry.values()}get(e){const t=this.registry.get(e);if(!t)throw new Error(`Missing binding util for type "${e}"`);return t}},Lr=class e{x;y;constructor(e,t){this.x=e,this.y=t}add(t){return new e(this.x+t.x,this.y+t.y)}sub(t){return new e(this.x-t.x,this.y-t.y)}mul(t){return new e(this.x*t,this.y*t)}div(t){return new e(this.x/t,this.y/t)}len2(){return this.x*this.x+this.y*this.y}len(){return Math.sqrt(this.len2())}dist2(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}dist(e){return Math.sqrt(this.dist2(e))}rot(t){const n=Math.cos(t),i=Math.sin(t);return new e(this.x*n-this.y*i,this.x*i+this.y*n)}per(){return new e(-this.y,this.x)}normalize(){const t=this.len();return 0===t?new e(0,0):this.div(t)}equals(e){return this.x===e.x&&this.y===e.y}clone(){return new e(this.x,this.y)}static From(t,n){return new e(t,n)}static Zero(){return new e(0,0)}static Med(t,n){return new e((t.x+n.x)/2,(t.y+n.y)/2)}static Lrp(t,n,i){return new e(t.x+(n.x-t.x)*i,t.y+(n.y-t.y)*i)}static Dist(e,t){return e.dist(t)}static Dist2(e,t){return e.dist2(t)}static Angle(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}static Nudge(e,t,n){const i=t.sub(e),s=i.len();return 0===s?e.clone():e.add(i.mul(n/s))}static RotWith(t,n,i){const s=t.x-n.x,o=t.y-n.y,r=Math.cos(i),a=Math.sin(i);return new e(n.x+s*r-o*a,n.y+s*a+o*r)}static IsNaN(e){return isNaN(e.x)||isNaN(e.y)}},zr=class e{x;y;w;h;constructor(e,t,n,i){this.x=e,this.y=t,this.w=n,this.h=i}get minX(){return this.x}get minY(){return this.y}get maxX(){return this.x+this.w}get maxY(){return this.y+this.h}get center(){return new Lr(this.x+this.w/2,this.y+this.h/2)}containsPoint(e){return e.x>=this.minX&&e.x<=this.maxX&&e.y>=this.minY&&e.y<=this.maxY}containsBox(e){return e.minX>=this.minX&&e.maxX<=this.maxX&&e.minY>=this.minY&&e.maxY<=this.maxY}intersects(e){return this.minX<e.maxX&&this.maxX>e.minX&&this.minY<e.maxY&&this.maxY>e.minY}expand(t){return new e(this.x-t,this.y-t,this.w+2*t,this.h+2*t)}clone(){return new e(this.x,this.y,this.w,this.h)}static FromPoints(t){let n=1/0,i=1/0,s=-1/0,o=-1/0;for(const e of t)n=Math.min(n,e.x),i=Math.min(i,e.y),s=Math.max(s,e.x),o=Math.max(o,e.y);return new e(n,i,s-n,o-i)}},_r=["fill-blue","fill-green","fill-red","fill-amber","fill-white","fill-slate","stroke-blue","stroke-green","stroke-red","stroke-orange","stroke-slate","stroke-muted","text-slate","text-blue","text-green","text-red"],$r=Object.fromEntries(_r.map(e=>[e,`--land-shape-${e}`])),Nr={"fill-blue":"#dbeafe","fill-green":"#dcfce7","fill-red":"#fee2e2","fill-amber":"#fff7ed","fill-white":"#f8fafc","fill-slate":"#e2e8f0","stroke-blue":"#1d4ed8","stroke-green":"#15803d","stroke-red":"#dc2626","stroke-orange":"#ea580c","stroke-slate":"#334155","stroke-muted":"#94a3b8","text-slate":"#0f172a","text-blue":"#1d4ed8","text-green":"#15803d","text-red":"#dc2626"},Ur=class{registry=new Map;register(e){this.registry.set(e.type,e)}get(e){return this.registry.get(e)??null}has(e){return this.registry.has(e)}unregister(e){return this.registry.delete(e)}values(){return this.registry.values()}},Hr=class{ids=new Set;registry=new Map;register(e){if(this.ids.has(e.id))throw new Error(`Duplicate shape SVG decoration id: ${e.id}.`);this.ids.add(e.id);const t=this.registry.get(e.subType)??[];t.push(e),this.registry.set(e.subType,t)}get(e){return null===e?[]:this.registry.get(e)??[]}},Wr=class e{a;b;c;d;e;f;constructor(e,t,n,i,s,o){this.a=e,this.b=t,this.c=n,this.d=i,this.e=s,this.f=o}static Identity(){return new e(1,0,0,1,0,0)}static Translate(t,n){return new e(1,0,0,1,t,n)}static Rotate(t){const n=Math.cos(t),i=Math.sin(t);return new e(n,i,-i,n,0,0)}static Scale(t,n){return new e(t,0,0,n,0,0)}compose(t){return new e(this.a*t.a+this.c*t.b,this.b*t.a+this.d*t.b,this.a*t.c+this.c*t.d,this.b*t.c+this.d*t.d,this.a*t.e+this.c*t.f+this.e,this.b*t.e+this.d*t.f+this.f)}applyToPoint(e){return new Lr(this.a*e.x+this.c*e.y+this.e,this.b*e.x+this.d*e.y+this.f)}determinant(){return this.a*this.d-this.b*this.c}getMaximumLinearScale(){const e=this.a*this.a+this.b*this.b+this.c*this.c+this.d*this.d,t=this.determinant(),n=Math.max(0,e*e-4*t*t);return Math.sqrt((e+Math.sqrt(n))/2)}tryInvert(t=0){const n=this.determinant(),i=Number.isFinite(t)?Math.max(0,t):0;if(!Number.isFinite(n)||Math.abs(n)<=i)return null;const s=1/n;return new e(this.d*s,-this.b*s,-this.c*s,this.a*s,(this.c*this.f-this.d*this.e)*s,(this.b*this.e-this.a*this.f)*s)}invert(){return this.tryInvert()??e.Identity()}toCssString(){return`matrix(${this.a},${this.b},${this.c},${this.d},${this.e},${this.f})`}toSvgString(){return`matrix(${this.a} ${this.b} ${this.c} ${this.d} ${this.e} ${this.f})`}static ForShape(t,n,i,s=1,o=1){const r=e.Translate(t,n),a=0===i?e.Identity():e.Rotate(i),d=1===s&&1===o?e.Identity():e.Scale(s,o);return r.compose(a).compose(d)}},qr=class{values=new Map;disposers=[];isDisposed=!1;provide(e,t,n){if(this.isDisposed)throw new Error("Cannot provide an editor runtime after disposal.");if(this.values.has(e.id))throw new Error(`Editor runtime already provided: ${e.id}`);return this.values.set(e.id,t),n&&this.disposers.push(()=>n(t)),t}get(e){return this.values.get(e.id)??null}require(e){const t=this.get(e);if(null===t)throw new Error(`Missing editor runtime: ${e.id}`);return t}onDispose(e){this.isDisposed?e():this.disposers.push(e)}dispose(){if(this.isDisposed)return;this.isDisposed=!0;let e=null;try{for(const n of this.disposers.splice(0).reverse())try{n()}catch(t){e??=t}}finally{this.values.clear()}if(null!==e)throw e}},Gr=class{ids=new Set;registry=new Map;register(e){if(this.ids.has(e.id))throw new Error(`Duplicate shape hit-test decoration id: ${e.id}.`);this.ids.add(e.id);const t=this.registry.get(e.subType)??[];t.push(e),this.registry.set(e.subType,t)}get(e){return null===e?[]:this.registry.get(e)??[]}},Vr=class{registry=new Map;register(e){this.registry.set(e.type,e)}has(e){return this.registry.has(e)}values(){return this.registry.values()}get(e){const t=this.registry.get(e);if(!t)throw new Error(`Missing shape util for type "${e}"`);return t}},jr=class{editor;activeToolId;isToolLocked;registry=new Map;activeTool=null;constructor(e){this.editor=e,this.activeToolId=e.signals.atom("tools.activeToolId","select"),this.isToolLocked=e.signals.atom("tools.isToolLocked",!1)}register(e,t){this.registry.set(e,t)}hasTool(e){return this.registry.has(e)}select(e,t="system"){this.editor.commands.setActiveTool(e,{source:t})}setLocked(e,t="system"){this.editor.commands.setToolLocked(e,{source:t})}toggleLocked(e="system"){this.setLocked(!this.editor.state.tool.get().isToolLocked,e)}syncActiveTool(e,t="tool_switch"){const n=this.registry.get(e);if(!n)throw new Error(`Unknown tool "${e}"`);this.activeTool&&this.activeToolId.get()===e||(this.activeTool&&(this.editor.interaction.cancel(t),this.activeTool.exit({reason:t})),this.activeToolId.set(e),this.activeTool=n(this.editor),this.activeTool.enter())}dispatch(e,t){return this.activeTool?.dispatch(e,t)}syncLockedState(e){this.isToolLocked.set(e)}isInInitialState(){return this.activeTool?.isInInitialState()??!0}},Qr=new WeakMap,Zr=class{editor;nextShapeNumber=1;nextPageNumber=1;nextBindingNumber=1;nextAssetNumber=1;constructor(e){this.editor=e,this.syncCounters()}createPage(e){const t=this.nextPageNumber;return this.nextPageNumber+=1,{id:`page:${t}`,typeName:"page",scope:"document",name:e?.name??`Page ${t}`,index:e?.index??String(t).padStart(4,"0"),meta:e?.meta??{}}}createShape(e){const t=e.parentId??this.editor.state.session.get().currentPageId;if(!this.editor.layers.canReceiveChildren(t))throw new Error("Invalid parent id for shape");const n=this.nextShapeNumber;this.nextShapeNumber+=1;const i=this.editor.shapeUtils.get(e.type).validateProps({...this.editor.shapes.getDefaultProps(e.type),...e.props});return{id:`shape:${n}`,typeName:"shape",scope:"document",type:e.type,subType:e.subType??null,parentId:t,index:e.index??this.createShapeIndex(n),x:e.x,y:e.y,rotation:e.rotation??0,scaleX:e.scaleX??1,scaleY:e.scaleY??1,opacity:e.opacity??1,isHidden:e.isHidden??!1,isLocked:e.isLocked??!1,props:i,meta:e.meta??{}}}createBinding(e){const t=e.id??`binding:${this.nextBindingNumber}`;e.id||(this.nextBindingNumber+=1);const n=this.editor.bindingUtils.get(e.type),i=new Set,s=e.endpoints.map(e=>{if(i.has(e.slot))throw new Error(`Duplicate binding endpoint slot: ${e.slot}`);return i.add(e.slot),{slot:e.slot,targetId:e.targetId,props:n.validateEndpointProps(e.slot,{...n.getDefaultEndpointProps(e.slot),...e.props}),meta:e.meta??{}}}).sort((e,t)=>e.slot.localeCompare(t.slot));if(0===s.length)throw new Error("A binding must have at least one endpoint");return{id:t,typeName:"binding",scope:"document",type:e.type,ownerId:e.ownerId,endpoints:s,meta:e.meta??{}}}createAsset(e){const t=e.id??`asset:${this.nextAssetNumber}`;return e.id||(this.nextAssetNumber+=1),{id:t,typeName:"asset",scope:"document",type:e.type,props:e.props??{},meta:e.meta??{}}}createShapeIndex(e){return String(e).padStart(6,"0")}syncCounters(){let e=0,t=0,n=0,i=0;for(const s of S(this.editor).getAll())if(p(s))e=Math.max(e,ae(s.id));else if(l(s)){const e=s.id.split(":")[1]??"",n=Number("default"===e?1:e);Number.isFinite(n)&&(t=Math.max(t,n))}else g(s)?n=Math.max(n,ae(s.id)):f(s)&&(i=Math.max(i,ae(s.id)));this.nextShapeNumber=e+1,this.nextPageNumber=t+1,this.nextBindingNumber=n+1,this.nextAssetNumber=i+1}},Jr=new Lr(24,24),ea={propagation:"stop"},ta={propagation:"stop",clickSequence:"break"},na=class{lastPointerDown=null;lastPointerUp=null;currentClickCount=1;createContext(e,t){return"pointer"!==e.type?{origin:t,pointer:null}:("pointer_down"===e.name&&(this.currentClickCount=this.isContinuation(e)?2:1,this.lastPointerDown=ct(e)),{origin:t,pointer:{clickCount:this.matchesCurrentPointer(e)?this.currentClickCount:1}})}complete(e,t,n){return"break"===n?.clickSequence?(this.reset(),null):"pointer"!==e.type||"pointer_up"!==e.name?null:this.matchesCurrentPointer(e)?(this.lastPointerUp=ct(e),(t.pointer?.clickCount??1)<2||"stop"===n?.propagation?null:{type:"double_click",timestamp:e.timestamp,pointerId:e.pointerId,button:e.button,buttons:e.buttons,pointerType:e.pointerType,screenPoint:e.screenPoint.clone(),pagePoint:e.pagePoint.clone(),pressure:e.pressure,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}):(this.reset(),null)}isContinuation(e){const t=this.lastPointerDown,n=this.lastPointerUp;return!!(t&&n&&n.timestamp>=t.timestamp&&e.timestamp-n.timestamp<=250&&n.screenPoint.dist2(e.screenPoint)<=1600&&lt(t,e)&&lt(n,e))}matchesCurrentPointer(e){return!this.lastPointerDown||lt(this.lastPointerDown,e)}reset(){this.lastPointerDown=null,this.lastPointerUp=null,this.currentClickCount=1}},ia={propagation:"stop",clickSequence:"break"},sa=class{editor;clickRecognizer=new na;activeRoutes=new WeakMap;constructor(e){this.editor=e}handle(e){const t=this.activeRoutes.get(e);return t?(t.effect=dt(t.effect,this.routeAfterInputs(e,t.context)),ht(t.effect)):ht(this.routeNewEvent(e,"external"))}cancelInteraction(e,t={}){this.routeNewEvent({type:"cancel",reason:e},"derived",t)}routeNewEvent(e,t,n){const i=this.clickRecognizer.createContext(e,t),s={context:i};this.activeRoutes.set(e,s);try{this.editor.inputs.handleEvent(e),s.effect=dt(s.effect,"cancel"===e.type?this.routeCancellation(e,i,n):this.routeAfterInputs(e,i));const t=this.clickRecognizer.complete(e,i,s.effect);return t&&(s.effect=dt(s.effect,this.routeNewEvent(t,"derived"))),s.effect}finally{this.activeRoutes.delete(e)}}routeAfterInputs(e,t){if("cancel"===e.type)return this.routeCancellation(e,t);if("pointer"===e.type&&"pointer_cancel"===e.name){const n=this.editor.interactions.broadcastEvent(this.editor,e,t),i=this.editor.tools.dispatch(e,t);return this.editor.interaction.clearSelection(),dt(dt(n,i),ia)}if((e=>"keyboard"===e.type&&"key_down"===e.name&&"Escape"===e.key&&!e.shiftKey&&!e.altKey&&!e.accelKey)(e))return this.routeEscape();const n=!!this.editor.state.shapeEditingSession.get(),i=this.editor.interactions.handleEvent(this.editor,e,t);return"stop"===i?.propagation||"double_click"===e.type||n&&"keyboard"===e.type?i:dt(i,this.editor.tools.dispatch(e,t))}routeCancellation(e,t,n={}){const i=!1===n.notifyInteractionHandlers?void 0:this.editor.interactions.broadcastEvent(this.editor,e,t),s=this.editor.tools.dispatch(e,t);return this.editor.interaction.clearSelection(),dt(dt(i,s),ia)}routeEscape(){const e=!this.editor.tools.isInInitialState(),t=!!this.editor.state.shapeEditingSession.get(),n=this.routeNewEvent({type:"cancel",reason:"escape"},"derived");return t&&this.editor.state.shapeEditingSession.get()&&this.editor.editing.cancel("user"),e||"select"===this.editor.state.tool.get().activeToolId||this.editor.commands.setActiveTool("select",{source:"system"}),dt(n,ia)}},oa=class{pressedKeyCodes;isSpacePressed;state;constructor(e){this.pressedKeyCodes=e.atom("inputs.pressedKeyCodes",new Set),this.isSpacePressed=e.computed("inputs.isSpacePressed",()=>this.pressedKeyCodes.get().has("Space")),this.state=e.atom("inputs.state",{originPagePoint:null,currentPagePoint:null,previousPagePoint:null,originScreenPoint:null,currentScreenPoint:null,previousScreenPoint:null,currentTimestamp:null,previousTimestamp:null,pageVelocity:pt(),screenVelocity:pt(),pointerId:null,pointerType:null,buttons:0,isPointing:!1,isDragging:!1,dragPhase:"idle",shiftKey:!1,altKey:!1,ctrlKey:!1,metaKey:!1,accelKey:!1})}setCurrentPointerPoint(e){this.state.update(t=>{if(t.currentPagePoint?.equals(e.pagePoint)&&t.currentScreenPoint?.equals(e.screenPoint)&&t.currentTimestamp===e.timestamp&&t.shiftKey===e.shiftKey&&t.altKey===e.altKey&&t.ctrlKey===e.ctrlKey&&t.metaKey===e.metaKey&&t.accelKey===e.accelKey)return t;const n=t.currentPagePoint??e.pagePoint,i=t.currentScreenPoint??e.screenPoint,s=t.currentTimestamp??e.timestamp,o=e.timestamp-s;return{...t,previousPagePoint:n,previousScreenPoint:i,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:s,currentTimestamp:e.timestamp,pageVelocity:ut(n,e.pagePoint,o),screenVelocity:ut(i,e.screenPoint,o),shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}})}handleEvent(e){switch(e.type){case"pointer":return void this.handlePointerEvent(e);case"keyboard":return void this.handleKeyboardEvent(e);case"wheel":return void this.handleWheelEvent(e);case"cancel":return this.resetPointer(),void("blur"!==e.reason&&"dispose"!==e.reason||this.resetKeyboard())}}resetPointer(){this.state.update(e=>({...e,originPagePoint:null,currentPagePoint:null,previousPagePoint:null,originScreenPoint:null,currentScreenPoint:null,previousScreenPoint:null,currentTimestamp:null,previousTimestamp:null,pageVelocity:pt(),screenVelocity:pt(),pointerId:null,pointerType:null,buttons:0,isPointing:!1,isDragging:!1,dragPhase:"idle"}))}handlePointerEvent(e){this.state.update(t=>{switch(e.name){case"pointer_down":return{...t,originPagePoint:e.pagePoint,currentPagePoint:e.pagePoint,previousPagePoint:e.pagePoint,originScreenPoint:e.screenPoint,currentScreenPoint:e.screenPoint,previousScreenPoint:e.screenPoint,currentTimestamp:e.timestamp,previousTimestamp:e.timestamp,pageVelocity:pt(),screenVelocity:pt(),pointerId:e.pointerId,pointerType:e.pointerType,buttons:e.buttons,isPointing:!0,isDragging:!1,dragPhase:"pointing",shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey};case"pointer_move":{if(t.currentPagePoint?.equals(e.pagePoint)&&t.currentScreenPoint?.equals(e.screenPoint)&&t.currentTimestamp===e.timestamp&&t.buttons===e.buttons&&gt(t,e))return t;const n=t.currentPagePoint??e.pagePoint,i=t.currentScreenPoint??e.screenPoint,s=t.isPointing&&(t.isDragging||(t.originScreenPoint??e.screenPoint).dist2(e.screenPoint)>=9),o=t.currentTimestamp??e.timestamp,r=e.timestamp-o;return{...t,previousPagePoint:n,previousScreenPoint:i,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:o,currentTimestamp:e.timestamp,pageVelocity:ut(n,e.pagePoint,r),screenVelocity:ut(i,e.screenPoint,r),buttons:e.buttons,isDragging:s,dragPhase:t.isPointing?s?"dragging":"pointing":"idle",shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}}case"pointer_up":case"pointer_cancel":return{...t,previousPagePoint:t.currentPagePoint,previousScreenPoint:t.currentScreenPoint,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:t.currentTimestamp,currentTimestamp:e.timestamp,pageVelocity:pt(),screenVelocity:pt(),buttons:e.buttons,isPointing:!1,isDragging:!1,dragPhase:"idle",shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}}})}handleKeyboardEvent(e){this.pressedKeyCodes.update(t=>{const n="key_down"===e.name;if(t.has(e.code)===n)return t;const i=new Set(t);return n?i.add(e.code):i.delete(e.code),i}),this.state.update(t=>gt(t,e)?t:{...t,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey})}resetKeyboard(){this.pressedKeyCodes.get().size>0&&this.pressedKeyCodes.set(new Set),this.state.update(e=>e.shiftKey||e.altKey||e.ctrlKey||e.metaKey||e.accelKey?{...e,shiftKey:!1,altKey:!1,ctrlKey:!1,metaKey:!1,accelKey:!1}:e)}handleWheelEvent(e){this.state.update(t=>gt(t,e)?t:{...t,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey})}},ra=class{handlers=[];registeredIds=new Set;register(e){this.registeredIds.has(e.id)||(this.handlers.push(e),this.handlers.sort((e,t)=>(t.priority??0)-(e.priority??0)),this.registeredIds.add(e.id))}getHandlers(){return this.handlers}handleEvent(e,t,n){let i;for(const s of this.handlers)if((!e.state.readonly.get()||!0===s.enabledInReadonly)&&(i=dt(i,s.editorEvent?.handleEvent(e,t,n)),"stop"===i?.propagation))return i;return i}broadcastEvent(e,t,n){let i;for(const s of this.handlers)i=dt(i,s.editorEvent?.handleEvent(e,t,n));return i}createSelectionHandleSession(e,t){if(e.state.readonly.get())return null;for(const n of this.handlers){const i=n.selectionHandle?.createSession(e,t);if(i)return i}return null}createShapePointerSession(e,t){if(e.state.readonly.get())return null;for(const n of this.handlers){const i=n.shapePointer?.createSession(e,t);if(i)return i}return null}},aa=class{editor;buffer;activeScopes=[];stateAtom;unsubscribeOperations;isDisposed=!1;state;constructor(e){this.editor=e,this.buffer=new kr,this.stateAtom=e.signals.atom("editor.history.state",{canUndo:!1,canRedo:!1},{isEqual:ft}),this.state=this.stateAtom,this.unsubscribeOperations=this.editor.operations.subscribe(e=>{this.handleCommit(e)})}clear(){this.buffer.clear(),this.publishEffectiveState()}activateScope(e){if(this.isDisposed)throw new Error("Cannot activate a history scope after disposal.");const t={scope:e,unsubscribe:()=>{}};return t.unsubscribe=e.subscribe(()=>{this.activeScopes.includes(t)&&this.publishEffectiveState()}),this.activeScopes.push(t),this.publishEffectiveState(),()=>{this.deactivateScope(t)}}dispose(){if(this.isDisposed)return;this.isDisposed=!0,this.unsubscribeOperations();let e=null;for(const n of this.activeScopes.splice(0).reverse())try{n.unsubscribe()}catch(t){e??=t}if(null!==e)throw e}undo(){return this.step("undo")}redo(){return this.step("redo")}getEntries(){return this.buffer.getEntries()}handleCommit(e){"record"===e.history&&"user"===e.source&&(this.buffer.append(e.diff,e.label),this.publishEffectiveState())}deactivateScope(e){const t=this.activeScopes.indexOf(e);if(!(t<0)){this.activeScopes.splice(t,1);try{e.unsubscribe()}finally{this.isDisposed||this.publishEffectiveState()}}}step(e){this.editor.assertDocumentWriteAllowed();const t=this.activeScopes.at(-1)?.scope;if(t){const n="undo"===e?t.undo():t.redo();return this.publishEffectiveState(),n}this.editor.interaction.cancelForCommand();const n="undo"===e?this.buffer.undo():this.buffer.redo();return!!n&&(this.replay(e,n),this.publishEffectiveState(),!0)}replay(e,t){try{this.editor.operations.run({kind:`history.${e}`,label:t.label,source:"history",history:"ignore"},()=>{const n="undo"===e?t.inverse:t.forward;S(this.editor).applyDiff(n,"history"),this.editor.snapshots.syncAfterDocumentRestore()})}catch(n){throw"undo"===e?this.buffer.rollbackUndo(t):this.buffer.rollbackRedo(t),this.publishEffectiveState(),n}}publishEffectiveState(){const e=this.activeScopes.at(-1)?.scope;var t;this.stateAtom.set({canUndo:(t=e?.getState()??{canUndo:this.buffer.canUndo,canRedo:this.buffer.canRedo}).canUndo,canRedo:t.canRedo})}},da=class{manager;state;constructor(e,t){this.manager=e,this.state=t}get id(){return this.state.id}get kind(){return this.state.kind}get source(){return this.state.source}get isActive(){return"active"===this.state.status}commit(){return this.manager.commit(this.state)}cancel(){this.manager.cancel(this.state)}},ca=class{editor;onUnhandledError;stack=[];commitListeners=new Set;commitQueue=[];nextOperationId=1;revision=0;isDrainingCommitQueue=!1;constructor(e,t=()=>{}){this.editor=e,this.onUnhandledError=t,S(e).listen(e=>this.handleStoreChange(e))}begin(e){const t=e.source??"user",n=this.getActiveState(),i={id:"operation:"+this.nextOperationId++,kind:e.kind,label:e.label??e.kind,source:t,history:e.history??("user"===t?"record":"ignore"),parent:n,diff:{added:[],updated:[],removed:[]},status:"active"};return this.stack.push(i),new da(this,i)}run(e,t){const n=this.begin(e);try{const e=t();return n.commit(),e}catch(i){throw n.isActive&&n.cancel(),i}}getActive(){const e=this.getActiveState();return e?new da(this,e):null}subscribe(e){return this.commitListeners.add(e),()=>{this.commitListeners.delete(e)}}commit(e){this.assertTopActive(e);const n=mt(e.diff);if(this.stack.pop(),e.status="committed",e.parent)return e.parent.diff=s(e.parent.diff,n),null;if(t(n))return null;const i={id:e.id,revision:++this.revision,kind:e.kind,label:e.label,source:e.source,history:e.history,diff:n,snapshot:yt(this.editor.snapshots.getDocument()),sessionSnapshot:It(this.editor.snapshots.getSession())};return this.enqueueCommit(i),i}cancel(e){this.assertTopActive(e);const n=mt(e.diff);if(!t(n))try{S(this.editor).applyDiff(i(n),e.source),this.editor.snapshots.syncAfterDocumentRestore()}catch(s){if(!t(mt(e.diff)))throw s;return this.stack.pop(),e.status="cancelled",void this.reportUnhandledError(s)}this.stack.pop(),e.status="cancelled"}handleStoreChange(e){const n=((e,t)=>({added:e.added.filter(t),updated:e.updated.filter(e=>t(e.before)&&t(e.after)),removed:e.removed.filter(t)}))(e.diff,m);if(t(n))return;const i=this.getActiveState();if(i)return void(i.diff=s(i.diff,n));const o=mt(n);t(o)||this.enqueueCommit({id:"operation:"+this.nextOperationId++,revision:++this.revision,kind:"editor.change",label:"change",source:e.source,history:"user"===e.source?"record":"ignore",diff:o,snapshot:yt(this.editor.snapshots.getDocument()),sessionSnapshot:It(this.editor.snapshots.getSession())})}getActiveState(){return this.stack.at(-1)??null}assertTopActive(e){if("active"!==e.status)throw new Error(`Editor operation "${e.kind}" is no longer active.`);if(this.getActiveState()!==e)throw new Error(`Editor operation "${e.kind}" must be completed in LIFO order.`)}enqueueCommit(e){if(this.commitQueue.push(e),!this.isDrainingCommitQueue){this.isDrainingCommitQueue=!0;try{for(;this.commitQueue.length>0;){const e=this.commitQueue.shift();for(const n of this.commitListeners)try{n(e)}catch(t){this.reportUnhandledError(t)}}}finally{this.isDrainingCommitQueue=!1}}}reportUnhandledError(e){try{this.onUnhandledError(e)}catch{}}},la=["owner","target","related"],ha=class{editor;state;bindingsOwnedByShapeSignals=new Map;bindingsTargetingShapeSignals=new Map;bindingsForShapeSignals=new Map;draftBindingIndex=null;unsubscribeFromStore;constructor(e){this.editor=e;const t=S(e);this.state=(e=>{const t=e.filter(g).sort(bt),n={bindingById:new Map,bindingIdsByOwnerShape:new Map,bindingIdsByTargetShape:new Map,relatedBindingIdsByShape:new Map};for(const i of t){n.bindingById.set(i.id,i),wt(n.bindingIdsByOwnerShape,i.ownerId,i.id),wt(n.relatedBindingIdsByShape,i.ownerId,i.id);for(const e of Bt(i))wt(n.bindingIdsByTargetShape,e,i.id),e!==i.ownerId&&wt(n.relatedBindingIdsByShape,e,i.id)}return n})(t.getAll()),this.unsubscribeFromStore=t.listen(e=>{this.handleStoreChange(e)})}dispose(){this.unsubscribeFromStore(),this.bindingsOwnedByShapeSignals.clear(),this.bindingsTargetingShapeSignals.clear(),this.bindingsForShapeSignals.clear(),this.draftBindingIndex=null}getBindingsOwnedByShape(e){const t=this.getDraftBindingIndex();return t?[...this.getDraftBindingsForRelation("owner",e,t)]:[...this.getBindingsOwnedByShapeSignal(e).get()]}getBindingsOwnedByShapeSignal(e){let t=this.bindingsOwnedByShapeSignals.get(e);return t||(t=this.editor.signals.atom(`editor.query.bindingsOwnedByShape.${e}`,this.getBindingsOwnedByState(this.state,e),{isEqual:J}),this.bindingsOwnedByShapeSignals.set(e,t)),t}getBindingsTargetingShape(e){const t=this.getDraftBindingIndex();return t?[...this.getDraftBindingsForRelation("target",e,t)]:[...this.getBindingsTargetingShapeSignal(e).get()]}getBindingsTargetingShapeSignal(e){let t=this.bindingsTargetingShapeSignals.get(e);return t||(t=this.editor.signals.atom(`editor.query.bindingsTargetingShape.${e}`,this.getBindingsTargetingState(this.state,e),{isEqual:J}),this.bindingsTargetingShapeSignals.set(e,t)),t}getBindingsForShape(e){const t=this.getDraftBindingIndex();return t?[...this.getDraftBindingsForRelation("related",e,t)]:[...this.getBindingsForShapeSignal(e).get()]}getBindingsForShapeSignal(e){let t=this.bindingsForShapeSignals.get(e);return t||(t=this.editor.signals.atom(`editor.query.bindingsForShape.${e}`,this.getBindingsForState(this.state,e),{isEqual:J}),this.bindingsForShapeSignals.set(e,t)),t}handleStoreChange(e){const t=this.state,n=((e,t)=>{const n=t.diff.added.filter(g),i=t.diff.updated.filter(Ct),s=t.diff.removed.filter(g);if(0===n.length&&0===i.length&&0===s.length)return e;const o={bindingById:new Map(e.bindingById),bindingIdsByOwnerShape:new Map(e.bindingIdsByOwnerShape),bindingIdsByTargetShape:new Map(e.bindingIdsByTargetShape),relatedBindingIdsByShape:new Map(e.relatedBindingIdsByShape)};for(const r of s)o.bindingById.delete(r.id),Mt(o,r);for(const{before:r,after:a}of i)kt(r,a)&&Mt(o,r);for(const r of n)o.bindingById.set(r.id,r);for(const{after:r}of i)o.bindingById.set(r.id,r);for(const r of n)Tt(o,r);for(const{before:r,after:a}of i)kt(r,a)&&Tt(o,a);return o})(t,e);n!==t&&(this.state=n,this.updateCachedSignals(e,n))}updateCachedSignals(e,t){const n=new Set,i=new Set,s=new Set,o=e=>{if(g(e)){n.add(e.ownerId),s.add(e.ownerId);for(const{targetId:t}of e.endpoints)i.add(t),s.add(t)}};for(const r of e.diff.added)o(r);for(const r of e.diff.removed)o(r);for(const r of e.diff.updated)o(r.before),o(r.after);for(const r of n)this.bindingsOwnedByShapeSignals.get(r)?.set(this.getBindingsOwnedByState(t,r));for(const r of i)this.bindingsTargetingShapeSignals.get(r)?.set(this.getBindingsTargetingState(t,r));for(const r of s)this.bindingsForShapeSignals.get(r)?.set(this.getBindingsForState(t,r))}getBindingsOwnedByState(e,t){return this.getBindingsForIds(e,e.bindingIdsByOwnerShape.get(t))}getBindingsTargetingState(e,t){return this.getBindingsForIds(e,e.bindingIdsByTargetShape.get(t))}getBindingsForState(e,t){return this.getBindingsForIds(e,e.relatedBindingIdsByShape.get(t))}getBindingsForIds(e,t){return t&&0!==t.length?t.map(t=>e.bindingById.get(t)).filter(e=>!!e):[]}getDraftBindingIndex(){const e=S(this.editor),t=e.getActiveTransactionRevision();return null===t?null:(this.draftBindingIndex?.revision===t||(this.draftBindingIndex=((e,t)=>{const n={revision:e,relations:{owner:Et(),target:Et(),related:Et()}};for(const i of t.removed)g(i)&&At(n,i,void 0);for(const i of t.updated)g(i.before)&&At(n,i.before,void 0),g(i.after)&&At(n,i.after,i.after);for(const i of t.added)g(i)&&At(n,i,i);return n})(t,e.getActiveTransactionDiff())),this.draftBindingIndex)}getDraftBindingsForRelation(e,t,n){return(({committed:e,draftIndex:t,relation:n,shapeId:i})=>{const s=t.relations[n],o=s.cacheByShape.get(i);if(o)return o;const r=s.changesByShape.get(i);if(!r)return s.cacheByShape.set(i,e),e;const a=new Map(e.map(e=>[e.id,e]));for(const[c,l]of r)l?a.set(c,l):a.delete(c);const d=Array.from(a.values()).sort(bt);return s.cacheByShape.set(i,d),d})({committed:"owner"===e?this.getBindingsOwnedByState(this.state,t):"target"===e?this.getBindingsTargetingState(this.state,t):this.getBindingsForState(this.state,t),draftIndex:n,relation:e,shapeId:t})}},pa=class{editor;signalsByShapeId=new Map;unsubscribeFromStore;constructor(e){this.editor=e,this.unsubscribeFromStore=e.listen(({diff:e})=>{for(const t of e.removed)p(t)&&this.signalsByShapeId.delete(t.id)})}dispose(){this.unsubscribeFromStore(),this.signalsByShapeId.clear()}getCachedShapeGeometry(e){return this.getOrCreateSignals(e).pageGeometry.get()}getShapePageBoundsSignal(e){return this.getOrCreateSignals(e).pageBounds}getShapeLocalToPageTransformSignal(e){return this.getOrCreateSignals(e).localToPageTransform}getShapeGeometry(e){return(e=>{if(e)return{bounds:e.bounds.clone(),center:e.center.clone(),corners:e.corners.map(e=>e.clone()),outlineVertices:e.outlineVertices.map(e=>e.clone())}})(this.getCachedShapeGeometry(e))}getShapeLocalToPageTransform(e){return Dt(this.getShapeLocalToPageTransformSignal(e).get())}getShapeParentToPageTransform(e){return e.startsWith("page:")?this.editor.pages.get(e)?Wr.Identity():void 0:Dt(this.getOrCreateSignals(e).localToPageTransform.get())}getShapePositionedToPageTransform(e){return Dt(this.getOrCreateSignals(e).positionedToPageTransform.get())}getShapePageBounds(e){return Xt(this.getShapePageBoundsSignal(e).get())??void 0}getShapePositionedBounds(e){return Xt(this.getOrCreateSignals(e).positionedBounds.get())??void 0}getShapePageCenter(e){return t=this.getCachedShapeGeometry(e)?.center,(t?t.clone():t)??void 0;var t}getShapePageCorners(e){return Ft(this.getCachedShapeGeometry(e)?.corners)}getShapePageOutlineVertices(e){return Ft(this.getCachedShapeGeometry(e)?.outlineVertices)}getShapeClipAncestorIds(e){return[...this.getShapeClipAncestorIdsSignal(e).get()]}getShapeClipAncestorIdsSignal(e){return this.getOrCreateSignals(e).clipAncestorIds}isPagePointInShapeClip(e,t){const n=this.editor.shapes.get(e);if(!n)return!1;for(const i of zt(this.editor,n,e=>this.editor.shapes.get(e))){const e=this.editor.shapes.getUtil(i).getChildClipLocalPolygons(i);if(!e||!E(e))continue;const n=this.getOrCreateSignals(i.id).localToPageTransform.get()?.tryInvert();if(!n||!R(n.applyToPoint(t),e))return!1}return!0}getShapeClippedPageBounds(e){const t=this.editor.shapes.get(e);let n=this.getShapePageBounds(e);if(!t||!n)return null;for(const i of zt(this.editor,t,e=>this.editor.shapes.get(e))){const e=this.editor.shapes.getUtil(i).getChildClipLocalPolygons(i),t=e?E(e):null,s=this.getOrCreateSignals(i.id).localToPageTransform.get();if(!t||!s)continue;const o=$t(n,_t(t,s));if(!o)return null;n=o}return n}getOrCreateSignals(e){let t=this.signalsByShapeId.get(e);if(!t){const n=e=>this.editor.shapes.getSignal(e).get(),i=this.editor.signals.computed(`editor.query.shapePositionedBounds.${e}`,()=>{const t=n(e);return t?this.editor.shapes.getUtil(t).getPositionedBounds(t):void 0},{isEqual:se}),s=this.editor.signals.computed(`editor.query.shapeLocalToPageTransform.${e}`,()=>{const t=n(e);return t?Ot(this.editor,t,n):void 0},{isEqual:Kt}),o=this.editor.signals.computed(`editor.query.shapeGeometry.${e}`,()=>{const t=n(e);if(!t)return;const i=Lt(this.editor,t.parentId,n);return i?ke(t,this.editor.shapes.getUtil(t),i):void 0},{isEqual:Yt});t={positionedBounds:i,pageGeometry:o,localToPageTransform:s,positionedToPageTransform:this.editor.signals.computed(`editor.query.shapePositionedToPageTransform.${e}`,()=>{const t=n(e);if(!t)return;const i=Lt(this.editor,t.parentId,n);return i?ve(t,this.editor.shapes.getUtil(t),i):void 0},{isEqual:Kt}),pageBounds:this.editor.signals.computed(`editor.query.shapePageBounds.${e}`,()=>o.get()?.bounds,{isEqual:se}),clipAncestorIds:this.editor.signals.computed(`editor.query.shapeClipAncestorIds.${e}`,()=>{const t=n(e);return t?zt(this.editor,t,n).map(e=>e.id):[]},{isEqual:J})},this.signalsByShapeId.set(e,t)}return t}},ua=class{editor;pagesSignal;currentPageShapeIdsSignal;currentPageShapesSignal;currentPageShapeTreeSignal;stateAtom;pagesAtom;pageShapeIdsSignals=new Map;unsubscribeFromStore;constructor(e,t){this.editor=e;const{atom:n,computed:i}=e.signals,s=S(e),o=s.getAll();this.stateAtom=n("editor.query.shapeTree",(e=>{const t=e.filter(l).sort((e,t)=>e.index.localeCompare(t.index)),n=e.filter(p).sort((e,t)=>e.parentId===t.parentId?((e,t)=>e.index.localeCompare(t.index))(e,t):e.parentId.localeCompare(t.parentId)),i=new Map,s=new Map,o=new Map,r=new Map(n.map(e=>[e.id,e]));for(const d of n)Nt(s,d.parentId,d.id);const a=(e,t)=>{for(const n of s.get(t)??[]){const t=r.get(n);t&&(Nt(i,e,t.id),o.set(t.id,e),a(e,t.id))}};for(const d of t)a(d.id,d.id);return{pageShapeIdsByPage:i,childShapeIdsByParent:s,pageIdByShape:o}})(o)),this.pagesAtom=n("editor.query.pages",o.filter(l).sort((e,t)=>e.index.localeCompare(t.index)),{isEqual:J}),this.pagesSignal=this.pagesAtom,this.unsubscribeFromStore=s.listen(e=>{this.handleStoreChange(e)}),this.currentPageShapeIdsSignal=i("editor.query.currentPageShapeIds",()=>this.getShapeIdsForPageSnapshot(t.get()),{isEqual:J}),this.currentPageShapesSignal=i("editor.query.currentPageShapes",()=>this.currentPageShapeIdsSignal.get().map(e=>this.editor.shapes.getSignal(e).get()).filter(e=>!!e)),this.currentPageShapeTreeSignal=i("editor.query.currentPageShapeTree",()=>this.currentPageShapeIdsSignal.get().map(e=>this.editor.shapes.getSignal(e).get()).filter(e=>!!e).map(e=>({id:e.id,parentId:e.parentId,type:e.type,subType:e.subType})),{isEqual:qt})}dispose(){this.unsubscribeFromStore(),this.pageShapeIdsSignals.clear()}getShapeIdsForPageSignal(e){let t=this.pageShapeIdsSignals.get(e);return t||(t=this.editor.signals.computed(`editor.query.pageShapeIds.${e}`,()=>this.getShapeIdsForPageSnapshot(e),{isEqual:J}),this.pageShapeIdsSignals.set(e,t)),t}getShapeIdsForPage(e){return[...this.getShapeIdsForPageSnapshot(e)]}getShapesForPage(e){return this.getShapeIdsForPageSnapshot(e).map(e=>this.editor.shapes.get(e)).filter(e=>!!e)}getChildShapeIds(e){return[...this.getChildShapeIdsSnapshot(e)]}getChildShapes(e){return this.getChildShapeIdsSnapshot(e).map(e=>this.editor.shapes.get(e)).filter(e=>!!e)}getDescendantShapeIds(e){const t=[],n=new Set,i=e=>{for(const s of this.getChildShapeIdsSnapshot(e))n.has(s)||(n.add(s),t.push(s),i(s))};return i(e),t}getPageIdForShape(e){return this.stateAtom.get().pageIdByShape.get(e)??null}getShapeIdsForPageSnapshot(e){return this.stateAtom.get().pageShapeIdsByPage.get(e)??[]}getChildShapeIdsSnapshot(e){return this.stateAtom.get().childShapeIdsByParent.get(e)??[]}handleStoreChange(e){const t=S(this.editor),n=this.stateAtom.peek(),i=((e,t,n)=>{const i=t.diff.added.filter(p),s=t.diff.updated.filter(Wt),o=t.diff.removed.filter(p);if(!(i.length>0||o.length>0||s.some(({before:e,after:t})=>e.parentId!==t.parentId||e.index!==t.index)))return e;const r={pageShapeIdsByPage:new Map(e.pageShapeIdsByPage),childShapeIdsByParent:new Map(e.childShapeIdsByParent),pageIdByShape:new Map(e.pageIdByShape)},a=e=>{const t=n(e);return p(t)?t.index:void 0},d=new Set,c=e=>{let t=e;const i=new Set;for(;t&&!i.has(t);){i.add(t);const e=n(t);if(!e)return null;if(l(e))return e.id;if(!p(e))return null;t=e.parentId}return null};for(const l of o){Ut(r.childShapeIdsByParent,l.parentId,l.id);const t=e.pageIdByShape.get(l.id);t&&d.add(t)}for(const{before:l,after:h}of s){if(l.parentId===h.parentId&&l.index===h.index)continue;Ut(r.childShapeIdsByParent,l.parentId,l.id),Ht(r.childShapeIdsByParent,h.parentId,h,a);const t=e.pageIdByShape.get(l.id);t&&d.add(t);const n=c(h.parentId);n&&d.add(n)}for(const l of i)Ht(r.childShapeIdsByParent,l.parentId,l,a);for(const l of i){const e=c(l.parentId);e&&d.add(e)}if(d.size>0){const t=new Map(e.pageShapeIdsByPage),i=new Map(e.pageIdByShape);for(const[n,o]of e.pageIdByShape)d.has(o)&&i.delete(n);const s=(e,t)=>{const o=[];for(const a of r.childShapeIdsByParent.get(t)??[])n(a)&&(o.push(a),i.set(a,e),o.push(...s(e,a)));return o};for(const e of d){const n=s(e,e);n.length>0?t.set(e,n):t.delete(e)}r.pageShapeIdsByPage=t,r.pageIdByShape=i}return r})(n,e,e=>t.get(e));i!==n&&this.stateAtom.set(i);const s=this.pagesAtom.peek(),o=((e,t)=>{if(!(t.diff.added.some(l)||t.diff.removed.some(l)||t.diff.updated.some(({before:e,after:t})=>l(e)||l(t))))return e;const n=new Map(e.map(e=>[e.id,e]));for(const i of t.diff.removed)l(i)&&n.delete(i.id);for(const i of t.diff.updated)l(i.before)&&n.delete(i.before.id),l(i.after)&&n.set(i.after.id,i.after);for(const i of t.diff.added)l(i)&&n.set(i.id,i);return Array.from(n.values()).sort((e,t)=>e.index.localeCompare(t.index))})(s,e);o!==s&&this.pagesAtom.set([...o])}},ga=class{entries;cellSize;cells=new Map;order=new Map;constructor(e){this.entries=e,this.cellSize=(e=>{if(0===e.length)return 256;let t=0;for(const n of e)t+=Math.max(n.queryBounds.w,n.queryBounds.h);return Math.max(16,Math.round(t/e.length)||256)})(e);for(let t=0;t<e.length;t+=1){const n=e[t];n&&(this.order.set(n,t),this.insert(n))}}cellKey(e,t){return`${e}:${t}`}insert(e){const t=Math.floor(e.queryBounds.minX/this.cellSize),n=Math.floor(e.queryBounds.minY/this.cellSize),i=Math.floor(e.queryBounds.maxX/this.cellSize),s=Math.floor(e.queryBounds.maxY/this.cellSize);for(let o=n;o<=s;o+=1)for(let n=t;n<=i;n+=1){const t=this.cellKey(n,o),i=this.cells.get(t);i?i.push(e):this.cells.set(t,[e])}}search(e){const t=Math.floor(e.minX/this.cellSize),n=Math.floor(e.minY/this.cellSize),i=Math.floor(e.maxX/this.cellSize),s=Math.floor(e.maxY/this.cellSize);if((i-t+1)*(s-n+1)>this.entries.length)return this.entries.filter(t=>t.queryBounds.intersects(e));const o=new Set,r=[];for(let a=n;a<=s;a+=1)for(let n=t;n<=i;n+=1){const t=this.cells.get(this.cellKey(n,a));if(t)for(const n of t)o.has(n)||(o.add(n),n.queryBounds.intersects(e)&&r.push(n))}return r.length>1&&r.sort((e,t)=>(this.order.get(e)??0)-(this.order.get(t)??0)),r}},fa=class{editor;shapeTree;geometry;pageIndexSignals=new Map;constructor(e,t,n){this.editor=e,this.shapeTree=t,this.geometry=n}getShapesInBounds(e,t){return this.getShapeIdsInBounds(e,t).map(e=>this.editor.shapes.get(e)).filter(e=>!!e)}getShapeIdsInBounds(e,t){return this.getPageIndex(t?.pageId).search(e).filter(t=>t.shapeBounds.intersects(e)).map(e=>e.shapeId)}getShapesInViewport(e,t){return this.getShapesInBounds(e,t)}getShapeIdsInViewport(e,t){return this.getShapeIdsInBounds(e,t)}getShapeAtPoint(e,t){return this.getShapesAtPoint(e,t)[0]??null}getShapesAtPoint(e,t){const n=this.getPageIndex(t?.pageId).search((e=>new zr(e.x-.5,e.y-.5,1,1))(e)),i=[];for(let s=n.length-1;s>=0;s-=1){const o=n[s];if(!o?.pointHitTestBounds.containsPoint(e))continue;const r=this.editor.shapes.get(o.shapeId);if(!r)continue;if(t?.filter&&!t.filter(r))continue;const a=this.editor.shapes.getUtil(r),d=this.geometry.getShapeParentToPageTransform(r.parentId);if(!d)continue;const c=Me(r,e,a,d),l={editor:this.editor,pagePoint:e,positionedPoint:c};("bindingTarget"===t?.hitTest?a.hitTestBindingTarget(r,c,l):a.hitTest(r,c,l)||this.editor.shapeHitTestDecorations.get(r.subType).some(e=>e.hitTest(r,c,l)))&&i.push(r)}return i}getShapesHitByLineSegment(e,t,n){const i=n?.margin??0,s=((e,t,n)=>zr.FromPoints([e,t]).expand(Math.max(.5,n)))(e,t,i),o=this.getPageIndex(n?.pageId).search(s),r=[];for(let a=o.length-1;a>=0;a-=1){const s=o[a];if(!s)continue;const d=this.geometry.getShapeClippedPageBounds(s.shapeId);if(!d||!Vt(e,t,d.expand(i)))continue;if(!this.doesLineSegmentIntersectShapeClip(s.shapeId,e,t,i))continue;const c=this.editor.shapes.get(s.shapeId);if(!c)continue;if(n?.filter&&!n.filter(c))continue;const l=this.editor.shapes.getUtil(c),h=this.geometry.getShapeParentToPageTransform(c.parentId);if(!h)continue;const p=Me(c,e,l,h),u=Me(c,t,l,h),g=this.geometry.getShapePositionedToPageTransform(c.id)?.tryInvert(),f=g?i*g.getMaximumLinearScale():i;l.hitTestLineSegment(c,{editor:this.editor,pageStart:e,pageEnd:t,pageMargin:i,positionedStart:p,positionedEnd:u,positionedMargin:f})&&r.push(c)}return r}doesLineSegmentIntersectShapeClip(e,t,n,i){for(const s of this.geometry.getShapeClipAncestorIds(e)){const e=this.editor.shapes.get(s);if(!e)return!1;const o=this.editor.shapes.getUtil(e).getChildClipLocalPolygons(e);if(!o)continue;const r=this.editor.shapes.computeLocalToPageTransform(e).tryInvert();if(!r)return!1;const a=i*Math.sqrt(r.a*r.a+r.b*r.b+r.c*r.c+r.d*r.d),d=r.applyToPoint(t),c=r.applyToPoint(n);if(!o.some(e=>K(d,c,e,a)))return!1}return!0}getPageIndexSignal(e){let t=this.pageIndexSignals.get(e);return t||(t=this.editor.signals.computed(`editor.spatialIndex.page.${e}`,()=>{const t=this.shapeTree.getShapeIdsForPageSignal(e).get(),n=[];for(const e of t){const t=this.editor.shapes.getSignal(e).get();if(!t)continue;this.editor.shapes.getUtil(t);const i=this.geometry.getShapePageBoundsSignal(e).get();if(!i)continue;const s=this.geometry.getShapePositionedToPageTransform(e);if(!s)continue;const o=jt(Qt(this.editor,t),s),r=zr.FromPoints([new Lr(i.minX,i.minY),new Lr(i.maxX,i.maxY),new Lr(o.minX,o.minY),new Lr(o.maxX,o.maxY)]);n.push({shapeId:e,shapeBounds:i,queryBounds:r,pointHitTestBounds:o})}return new ga(n)}),this.pageIndexSignals.set(e,t)),t}getPageIndex(e=this.editor.pages.getCurrentId()){return this.getPageIndexSignal(e).get()}},ma=class extends Error{constructor(e){super(e),this.name="SnapshotParseError"}},Sa=.001,ya=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"],Ia=["free","aspect_ratio_locked"],wa=class{editor;signals;selectedShapeItemsSignal;frameGeometrySignal;companionFrameGeometriesSignal;pathSignal;pageClipPathSignal;bindingSegmentsSignal;frameStyleSignal;handleAnchorsSignal;handlesSignal;constructor(e,t){this.editor=e,this.signals=t;const{computed:n}=e.signals;this.selectedShapeItemsSignal=n("editor.selectedShapeOverlayItems",()=>"select"!==t.tool.get().activeToolId?[]:t.selectedShapeIds.get().map(t=>e.shapes.getSignal(t).get()).filter(e=>!!e).map(t=>{const n=e.shapes.getUtil(t).getSelectionOverlayInfo(t,{editor:e});return{id:t.id,usesSelectionPathOverlay:n.usesSelectionPathOverlay,startPagePoint:n.startPagePoint,endPagePoint:n.endPagePoint,middlePagePoint:n.middlePagePoint,path:n.path,pathStyle:n.pathStyle,pageClipPath:n.pageClipPath??null,bindingSegments:n.bindingSegments??[]}}),{isEqual:Qn}),this.frameGeometrySignal=n("editor.selectionOverlayFrameGeometry",()=>{const t=this.selectedShapeItemsSignal.get();if(0===t.length)return null;if(gi(t))return null;const n=e.selection.getFrame();return n?{bounds:n.bounds,rotation:n.rotation,rotationCenter:n.rotationCenter}:null},{isEqual:Zn}),this.companionFrameGeometriesSignal=n("editor.selectionOverlayCompanionFrameGeometries",()=>{if("select"!==t.tool.get().activeToolId)return[];const n=[];for(const i of t.selectedShapes.get())for(const t of e.bindings.getForShape(i.id))n.push(...e.bindings.getUtil(t).getSelectionCompanionFrameGeometries?.(e,t,{selectedShape:i})??[]);return n},{isEqual:Jn}),this.pathSignal=n("editor.selectionOverlayPath",()=>{const e=this.selectedShapeItemsSignal.get();return gi(e)?e[0]?.path??null:null}),this.pageClipPathSignal=n("editor.selectionOverlayPageClipPath",()=>{const e=this.selectedShapeItemsSignal.get();return gi(e)?e[0]?.pageClipPath??null:null}),this.bindingSegmentsSignal=n("editor.selectionOverlayBindingSegments",()=>{const e=this.selectedShapeItemsSignal.get();return gi(e)?[...e[0]?.bindingSegments??[]]:[]},{isEqual:Ln}),this.frameStyleSignal=n("editor.selectionOverlayFrameStyle",()=>{const e=t.cameraZoom.get();return{strokeWidth:2/e,cornerRadius:3/e}},{isEqual:ei}),this.handleAnchorsSignal=n("editor.selectionOverlayHandleAnchors",()=>{if("select"!==t.tool.get().activeToolId)return null;const n=t.selectedShapes.get();if(0===n.length)return null;const i=e.selection.getFrame(),s=t.cameraZoom.get(),o=1===n.length,r=e.selection.canResize(),a=e.selection.canRotate();return((t,n,i,s,d,c,l)=>{const h=t.map(t=>(t=>e.shapes.getUtil(t).getSelectionHandleAnchors(t,{isOnlySelected:o,editor:e}))(t)),p=t.every(t=>(t=>r&&e.shapes.getUtil(t).canUseSelectionResizeHandles(t,{editor:e}))(t)),u=t.every(t=>(t=>a&&e.shapes.getUtil(t).canUseSelectionRotateHandle(t,{editor:e}))(t)),g=new Set(l),f=h.flatMap(e=>e.terminalHandleAnchors),m=h.flatMap(e=>e.middleHandleAnchors),S=h.flatMap(e=>e.customHandleAnchors??[]),y=f.length>0||m.length>0||S.length>0;if(!n)return{resizeHandleAnchors:[],rotateHandleAnchors:[],terminalHandleAnchors:f,middleHandleAnchors:m,customHandleAnchors:S};const{bounds:I,rotation:w,rotationCenter:P,hasCompatibleRotation:b}=n,v=t[0]?.rotation??w,x=8/i,C=14/i,M=I.w<2*x,T=I.h<2*x,B=e=>0===w?e:Lr.RotWith(e,P,w),k=new Lr(I.minX,I.minY),E=new Lr(I.center.x,I.minY),A=new Lr(I.maxX,I.minY),R=new Lr(I.maxX,I.center.y),K=new Lr(I.maxX,I.maxY),Y=new Lr(I.center.x,I.maxY),X=new Lr(I.minX,I.maxY),F=new Lr(I.minX,I.center.y);return{resizeHandleAnchors:!p||y?[]:[{kind:"resize",id:"top_left",point:B(k)},...M?[]:[{kind:"resize",id:"top",point:B(E)}],...M&&T?[]:[{kind:"resize",id:"top_right",point:B(A)}],...T?[]:[{kind:"resize",id:"right",point:B(R)}],...M||T?[]:[{kind:"resize",id:"bottom_right",point:B(K)}],...M?[]:[{kind:"resize",id:"bottom",point:B(Y)}],...M||T?[]:[{kind:"resize",id:"bottom_left",point:B(X)}],...T?[]:[{kind:"resize",id:"left",point:B(F)}]].filter(e=>g.has(e.id)),rotateHandleAnchors:!u||y||!b||M||T?[]:[{kind:"rotate",id:"bottom_left_rotate",point:B(ui({bounds:I,rotateOffset:C,referenceRotation:v,frameRotation:w}))}],terminalHandleAnchors:f,middleHandleAnchors:m,customHandleAnchors:S}})(n,i,s,0,0,0,((e,t,n)=>{if(0===t.length)return[];const i=1===t.length,s=t.map(t=>e.shapes.getUtil(t).getSelectionResizeHandleIds(t,{editor:e,isOnlyResizeTarget:i})),o=Gn(e,t,n);return ya.filter(n=>s.every(e=>e.includes(n))&&Vn(e,t,n,o).length>0)})(e,e.selection.getResizeTargets(),i?.rotation??0))},{isEqual:pi}),this.handlesSignal=n("editor.selectionOverlayHandles",()=>{const e=this.handleAnchorsSignal.get();if(!e)return null;const n=t.cameraZoom.get(),{resizeHandles:i,rotateHandles:s,terminalHandles:o,middleHandles:r,customHandles:a}=((e,t)=>{const n=8/t,i=n/2,s=e=>new zr(e.x-i,e.y-i,n,n);return{resizeHandles:e.resizeHandleAnchors.map(e=>({...e,bounds:s(e.point)})),rotateHandles:e.rotateHandleAnchors.map(e=>({...e,bounds:s(e.point)})),terminalHandles:e.terminalHandleAnchors.map(e=>({...e,bounds:s(e.point)})),middleHandles:e.middleHandleAnchors.map(e=>({...e,bounds:s(e.point)})),customHandles:e.customHandleAnchors.map(e=>({...e,bounds:s(e.point)}))}})(e,n);return{resizeHandles:i,rotateHandles:s,terminalHandles:o,middleHandles:r,customHandles:a,strokeWidth:2/n}},{isEqual:hi})}hitTestHandle(e){const t=this.handlesSignal.get();return t?function({point:e,selectionFrame:t,handles:n,hitDistance:i}){const{middleHandles:s,terminalHandles:o,customHandles:r,resizeHandles:a,rotateHandles:d}=n;for(const c of s)if(c.bounds.expand(i).containsPoint(e))return c;for(const c of o)if(c.bounds.expand(i).containsPoint(e))return c;for(const c of r)if(c.bounds.expand(i).containsPoint(e))return c;for(const c of a)if(c.bounds.containsPoint(e))return c;if(t){const n=((e,t,n,i)=>{const s=new Set(n.map(e=>e.id)),o=_n(e,t),{bounds:r}=t,a=[];o.x>=r.minX&&o.x<=r.maxX&&(s.has("top")&&a.push({id:"top",distance:Math.abs(o.y-r.minY)}),s.has("bottom")&&a.push({id:"bottom",distance:Math.abs(o.y-r.maxY)})),o.y>=r.minY&&o.y<=r.maxY&&(s.has("right")&&a.push({id:"right",distance:Math.abs(o.x-r.maxX)}),s.has("left")&&a.push({id:"left",distance:Math.abs(o.x-r.minX)}));const d=a.filter(e=>e.distance<=i).sort((e,t)=>e.distance-t.distance)[0];return d?{kind:"resize",id:d.id,point:e.clone(),bounds:new zr(e.x-i,e.y-i,2*i,2*i)}:null})(e,t,a,i);if(n)return n}for(const c of d)if(c.bounds.expand(i).containsPoint(e))return c;return null}({point:e,selectionFrame:this.editor.selection.getFrame(),handles:t,hitDistance:6/this.signals.cameraZoom.get()}):null}},Pa=class{editor;entryRequestAtom;entryRequestSignal;nextEntryRequestId=1;operation=null;constructor(e){this.editor=e,this.entryRequestAtom=e.signals.atom("editor.shapeEditingEntryRequest",null),this.entryRequestSignal=this.entryRequestAtom}canEditShape(e){const t="string"==typeof e?this.editor.shapes.get(e):e;return!!t&&!t.isLocked&&this.editor.shapes.getUtil(t).canEdit(t)}start(e,t="user"){let n=this.editor.shapes.get(e.shapeId);if(!n||!this.canEditShape(n))return null;const i=this.editor.state.shapeEditingSession.get();if(i?.shapeId===n.id){const s={...i,entryMode:e.entryMode??i.entryMode,caretPagePoint:e.caretPagePoint?{...e.caretPagePoint}:i.caretPagePoint};return this.editor.session.update({editingShapeId:n.id,shapeEditingSession:s},t),this.publishEntryRequest({shapeId:n.id,entryMode:s.entryMode,caretPagePoint:s.caretPagePoint}),s}if(e.preserveInteraction||this.editor.interaction.cancelForCommand(),this.editor.state.shapeEditingSession.get()&&!this.complete(t))return null;if(n=this.editor.shapes.get(e.shapeId),!n||!this.canEditShape(n))return null;const s=e.operationKind??`editing:${n.id}`;if(e.reuseActiveOperation){const e=this.editor.operations.getActive();if(!e||e.source!==t)throw new Error("Shape editing can only reuse an active operation with the same source.");this.operation=e}else this.operation=this.editor.operations.begin({kind:s,label:"shape.edit",source:"user",history:"record"});const o={shapeId:n.id,operationKind:s,entryMode:e.entryMode??"focusEnd",caretPagePoint:e.caretPagePoint?{...e.caretPagePoint}:void 0,isComposing:!1};return this.editor.commands.setSelectedShapeIds([n.id],{source:t}),this.editor.session.update({editingShapeId:n.id,shapeEditingSession:o},t),this.publishEntryRequest({shapeId:n.id,entryMode:o.entryMode,caretPagePoint:o.caretPagePoint}),o}complete(e="user"){const t=this.editor.state.shapeEditingSession.get();return!!t&&!t.isComposing&&(this.end({runEditEnd:!0,source:e}),this.commitOperation(),!0)}cancel(e="user"){const t=this.editor.state.shapeEditingSession.get();return!!t&&!t.isComposing&&(this.editor.session.update({editingShapeId:null,shapeEditingSession:null},e),this.cancelOperation(),!0)}setComposition(e,t="system"){const n=this.editor.state.shapeEditingSession.get();n&&n.isComposing!==e&&this.editor.session.update({shapeEditingSession:{...n,isComposing:e}},t)}consumeEntryRequest(e){const t=this.entryRequestAtom.get();t&&t.id===e&&this.entryRequestAtom.set(null)}removeShapeIds(e,t="system"){const n=this.editor.state.shapeEditingSession.get();n&&e.includes(n.shapeId)&&(this.end({runEditEnd:!1,source:t}),this.commitOperation())}prepareForShapeRemoval(e,t="system"){const n=this.editor.state.shapeEditingSession.get();if(!n||!e.includes(n.shapeId))return;this.editor.tools.isInInitialState()||this.editor.interaction.cancelForCommand();const i=this.editor.state.shapeEditingSession.get();i&&e.includes(i.shapeId)&&(this.end({runEditEnd:!1,source:t}),this.commitOperation())}end(e){const t=this.editor.state.shapeEditingSession.get();if(!t)return;this.entryRequestAtom.set(null);const n=this.editor.shapes.get(t.shapeId);if(this.editor.session.update({editingShapeId:null,shapeEditingSession:null},e.source),!e.runEditEnd||!n)return;const i=this.editor.shapes.getUtil(n).onEditEnd(n,{editor:this.editor});i?.deleteShapeIds&&i.deleteShapeIds.length>0&&this.editor.commands.deleteShapes(i.deleteShapeIds,{source:e.source})}cancelOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.cancel()}commitOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.commit()}publishEntryRequest(e){this.entryRequestAtom.set({id:this.nextEntryRequestId++,shapeId:e.shapeId,entryMode:e.entryMode,caretPagePoint:e.caretPagePoint?{...e.caretPagePoint}:void 0})}},ba=class extends Error{},va=class{editor;unsubscribeFromStore;shapeSignals=new Map;contentCutoutLocalPolygonSignals=new Map;selectedSignals=new Map;renderOrderSignals=new Map;renderVisibleSignals=new Map;documentVisibleSignals=new Map;effectiveOpacitySignals=new Map;editingSessionSignals=new Map;dropTargetSignals=new Map;hoveredSignals=new Map;constructor(e){this.editor=e,this.unsubscribeFromStore=e.listen(({diff:e})=>{for(const t of e.removed)p(t)&&this.evict(t.id)})}dispose(){this.unsubscribeFromStore(),this.shapeSignals.clear(),this.contentCutoutLocalPolygonSignals.clear(),this.selectedSignals.clear(),this.renderOrderSignals.clear(),this.renderVisibleSignals.clear(),this.documentVisibleSignals.clear(),this.effectiveOpacitySignals.clear(),this.editingSessionSignals.clear(),this.dropTargetSignals.clear(),this.hoveredSignals.clear()}isDocumentHidden(e){return!1===Di(this.editor,e,e=>this.editor.shapes.get(e))}getShapeSignal(e){let t=this.shapeSignals.get(e);return t||(t=this.editor.signals.computed(`editor.shape.${e}`,()=>{const t=this.editor.store.getRecordSignal(e).get();return p(t)?t:void 0}),this.shapeSignals.set(e,t)),t}getContentCutoutLocalPolygonsSignal(e){let t=this.contentCutoutLocalPolygonSignals.get(e);return t||(t=this.editor.signals.computed(`editor.shapeContentCutouts.${e}`,()=>{const t=this.getShapeSignal(e).get();return t?this.editor.bindings.getTargetingShapeSignal(e).get().flatMap(n=>{const i=this.getShapeSignal(n.ownerId).get();return i?n.endpoints.filter(({targetId:t})=>t===e).flatMap(e=>this.editor.bindings.getUtil(n).getTargetShapeContentCutoutLocalPolygons?.(this.editor,n,{ownerShape:i,endpoint:e,targetShape:t})??[]):[]}):[]},{isEqual:ie}),this.contentCutoutLocalPolygonSignals.set(e,t)),t}getSelectedSignal(e){let t=this.selectedSignals.get(e);return t||(t=this.editor.signals.computed(`editor.shapeSelected.${e}`,()=>this.editor.state.selectedShapeIdSet.get().has(e)),this.selectedSignals.set(e,t)),t}getRenderOrderSignal(e){let t=this.renderOrderSignals.get(e);return t||(t=this.editor.signals.computed(`editor.shapeRenderOrder.${e}`,()=>this.editor.render.viewport.shapeOrderById.get().get(e)??-1),this.renderOrderSignals.set(e,t)),t}getRenderVisibleSignal(e){let t=this.renderVisibleSignals.get(e);return t||(t=this.editor.signals.computed(`editor.shapeRenderVisible.${e}`,()=>{const t=this.editor.shapes.getClipAncestorIdsSignal(e).get().length>0;return this.editor.render.viewport.visibleShapeIdSet.get().has(e)&&this.getDocumentVisibleSignal(e).get()&&(!t||null!==this.editor.shapes.getClippedPageBounds(e))}),this.renderVisibleSignals.set(e,t)),t}getDocumentVisibleSignal(e){let t=this.documentVisibleSignals.get(e);return t||(t=this.editor.signals.computed(`editor.shapeDocumentVisible.${e}`,()=>Di(this.editor,e,e=>this.getShapeSignal(e).get())??!1),this.documentVisibleSignals.set(e,t)),t}getEffectiveOpacitySignal(e){let t=this.effectiveOpacitySignals.get(e);return t||(t=this.editor.signals.computed(`editor.shapeEffectiveOpacity.${e}`,()=>{const t=new Set([e]);let n=1,i=this.getShapeSignal(e).get();for(;i&&(n*=i.opacity,i.parentId.startsWith("shape:"));){const e=i.parentId;if(t.has(e))break;t.add(e),i=this.getShapeSignal(e).get()}return n}),this.effectiveOpacitySignals.set(e,t)),t}getEditingSessionSignal(e){let t=this.editingSessionSignals.get(e);return t||(t=this.editor.signals.computed(`editor.shapeEditingSessionForShape.${e}`,()=>{const t=this.editor.state.shapeEditingSession.get();return t?.shapeId===e?t:null}),this.editingSessionSignals.set(e,t)),t}getDropTargetSignal(e){let t=this.dropTargetSignals.get(e);return t||(t=this.editor.signals.computed(`editor.shapeDropTarget.${e}`,()=>this.editor.render.interaction.dropTargetShapeId.get()===e),this.dropTargetSignals.set(e,t)),t}getHoveredSignal(e){let t=this.hoveredSignals.get(e);return t||(t=this.editor.signals.computed(`editor.shapeHovered.${e}`,()=>{const t=this.editor.render.interaction.hoveredShapeId.get();if(!t)return!1;const n=this.getShapeSignal(e).get();return!!n&&this.editor.shapes.getUtil(n).getHoverDecorationTargetId(n,{editor:this.editor})===t}),this.hoveredSignals.set(e,t)),t}evict(e){this.shapeSignals.delete(e),this.contentCutoutLocalPolygonSignals.delete(e),this.selectedSignals.delete(e),this.renderOrderSignals.delete(e),this.renderVisibleSignals.delete(e),this.documentVisibleSignals.delete(e),this.effectiveOpacitySignals.delete(e),this.editingSessionSignals.delete(e),this.dropTargetSignals.delete(e),this.hoveredSignals.delete(e)}},xa=["corner","edge_midpoint","corner","edge_midpoint","center","edge_midpoint","corner","edge_midpoint","corner"],Ca={corner:0,edge_midpoint:1,center:2,custom:3},Ma=class{editor;constructor(e){this.editor=e}createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t}){return this.createBoundsSnapSnapshot({movingShapeIds:e,coordinateSpace:t})}createResizeSnapshot({resizingShapeIds:e,coordinateSpace:t}){return this.createBoundsSnapSnapshot({movingShapeIds:e,coordinateSpace:t})}createHandleSnapshot({context:e,currentPagePoint:t,allowSelfSnap:n=!1,excludedShapeIds:i=[]}){const s=this.editor.shapes.get(e.shapeId),o=new Set(this.editor.layers.includeDescendants([e.shapeId]));this.collectBindingDrivenExcludedShapeIds([e.shapeId],o);for(const l of i)o.add(l);const r=[],a=[],d=this.getSnapScopeParentId([e.shapeId]),c=this.getCandidateShapeIds({excludedShapeIds:o,scopeParentId:d});s&&n&&this.collectSelfHandleSnapGeometry({shape:s,context:e,currentPagePoint:t,points:r,outlines:a});for(const l of c){const e=this.editor.shapes.get(l);e&&this.collectHandleSnapGeometry({shape:e,points:r,outlines:a})}return{points:r,outlines:a,scopeParentId:d,candidateShapeIds:c}}collectHandleSnapGeometry({shape:e,points:t,outlines:n}){const i=this.editor.shapes.getUtil(e);if(!i.canSnap(e,{editor:this.editor}))return;const s=this.editor.shapes.getClippedPageBounds(e.id);if(!s)return;const o=this.editor.shapes.computeLocalToPageTransform(e),r=i.getHandleSnapGeometry(e);for(const l of r.points??[]){const n=Es(l),i=o.applyToPoint(n.point);this.editor.shapes.isPagePointInClip(e.id,i)&&t.push({id:`${e.id}:point:${t.length}`,nodeId:e.id,point:i,kind:n.kind,weight:n.weight})}const a=r.outline;if(null===a)return;const d=this.editor.shapes.getClipAncestorIds(e.id).length>0?es(s):(a??(c=i.getLocalBounds(e),[new Lr(c.minX,c.minY),new Lr(c.maxX,c.minY),new Lr(c.maxX,c.maxY),new Lr(c.minX,c.maxY)])).map(e=>o.applyToPoint(e));var c;d.length>0&&n.push({id:e.id,points:d})}collectSelfHandleSnapGeometry({shape:e,context:t,currentPagePoint:n,points:i,outlines:s}){const o=this.editor.shapes.getUtil(e);if(!o.canSnap(e,{editor:this.editor}))return;const r=this.editor.shapes.getClippedPageBounds(e.id);if(!r)return;const a=o.getHandleSnapGeometry(e),d=this.editor.shapes.computeLocalToPageTransform(e),c={...t,currentPagePoint:n.clone()};for(const p of a.getSelfSnapPoints?.(c)??[]){const t=Es(p),n=d.applyToPoint(t.point);this.editor.shapes.isPagePointInClip(e.id,n)&&i.push({id:`${e.id}:self-point:${i.length}`,nodeId:e.id,point:n,kind:t.kind,weight:t.weight})}const l=a.getSelfSnapOutline?.(c)??null;if(!l)return;const h=this.editor.shapes.getClipAncestorIds(e.id).length>0?es(r):l.map(e=>d.applyToPoint(e));h.length>0&&s.push({id:e.id,points:h})}createBoundsSnapSnapshot({movingShapeIds:e,coordinateSpace:t}){const n=Array.from(e),i=new Set(this.editor.layers.includeDescendants(n));this.collectBindingDrivenExcludedShapeIds(n,i);const s=[],o=[],r={rotation:t.rotation,rotationCenter:t.rotationCenter},a=this.getSnapScopeParentId(n),d=this.getCandidateShapeIds({excludedShapeIds:i,scopeParentId:a});for(const c of d){const e=this.editor.shapes.get(c);if(!e)continue;const n=this.editor.shapes.getUtil(e);if(!n.canSnap(e,{editor:this.editor}))continue;const i=this.editor.shapes.getClippedPageBounds(e.id);if(!i)continue;const a=(this.editor.shapes.getClipAncestorIds(e.id).length>0?es(i):this.editor.shapes.getPageOutlineVertices(e.id)).map(e=>0===t.rotation?e.clone():_n(e,r));if(0===a.length)continue;const d=zr.FromPoints(a);o.push({id:e.id,bounds:d});const l=n.getBoundsSnapGeometry(e).points,h=[];if(void 0===l)Hi(d).forEach((e,t)=>{h.push({point:e,kind:xa[t]??"custom"})});else{const n=this.editor.shapes.computeLocalToPageTransform(e);for(const i of l){const s=Es(i),o=n.applyToPoint(s.point);this.editor.shapes.isPagePointInClip(e.id,o)&&h.push({point:0===t.rotation?o:_n(o,r),kind:s.kind,weight:s.weight})}}h.forEach((t,n)=>{s.push({id:`${e.id}:${n}`,nodeId:e.id,point:t.point,kind:t.kind,weight:t.weight})})}return{points:s,pointIndex:cs(s),nodes:o,coordinateSpace:{rotation:t.rotation,rotationCenter:t.rotationCenter.clone()},scopeParentId:a,candidateShapeIds:d}}collectBindingDrivenExcludedShapeIds(e,t){const n=new Set,i=[...e];for(;i.length>0;){const e=i.pop();if(!e||n.has(e))continue;n.add(e);const s=this.editor.shapes.get(e);if(s)for(const n of this.editor.bindings.getForShape(e)){const o=n.ownerId===e,r=n.endpoints.filter(({targetId:t})=>t===e).map(({slot:e})=>e);if(!o&&0===r.length)continue;const a=this.editor.bindings.getUtil(n).getGeometryDependentShapeIds?.(this.editor,n,{shape:s,owner:o,endpointSlots:r})??[];for(const e of a)for(const n of this.editor.layers.includeDescendants([e]))t.has(n)||(t.add(n),i.push(n))}}}getSnapScopeParentId(e){let t=null;for(const n of e){const e=this.editor.shapes.get(n);if(e)if(t){if(e.parentId!==t)return this.editor.pages.getCurrentId()}else t=e.parentId}return t??this.editor.pages.getCurrentId()}getCandidateShapeIds({excludedShapeIds:e,scopeParentId:t}){const n=this.editor.pages.getCurrentId(),i=this.editor.render.viewport.pageBounds.get(),s=new Set;if(t?.startsWith("shape:")){const e=this.editor.shapes.get(t);e&&this.editor.shapes.getUtil(e).canSnapChildrenToSelf(e)&&s.add(e.id)}const o=t??n;for(const r of this.editor.layers.getChildIds(o))s.add(r);return(null===i?Array.from(s):this.editor.shapes.getIdsInBounds(i,{pageId:n}).filter(e=>s.has(e))).filter(n=>{if(e.has(n))return!1;const s=this.editor.shapes.get(n);if(!s||s.parentId!==o)return n===t;const r=this.editor.shapes.getClippedPageBounds(n);return!!r&&(!i||r.intersects(i))})}},Ta=class{diagnostics;gapCache=new WeakMap;_indicatorsSignal;indicatorsSignal;activeSignal;snapshots;axisSnapMemory={x:null,y:null};constructor(e,t={}){this.diagnostics=t,this._indicatorsSignal=e.signals.atom("editor.snapIndicators",[]),this.indicatorsSignal=this._indicatorsSignal,this.activeSignal=e.signals.computed("editor.snapIndicatorsActive",()=>this._indicatorsSignal.get().length>0),this.snapshots=new Ma(e)}setIndicators(e){const t=e.map(ks);ys(this._indicatorsSignal.get(),t)||this._indicatorsSignal.set(t)}clearIndicators(){this._indicatorsSignal.get().length>0&&this._indicatorsSignal.set([]),this.clearAxisSnapMemory()}clearAxisSnapMemory(){this.axisSnapMemory.x=null,this.axisSnapMemory.y=null}getSwitchDistance(e){return Math.min(.25*e,2)}getReleaseThreshold(e){return 1.5*e}updateAxisSnapMemory(e,t){this.axisSnapMemory[e]=t?{type:t.type,id:t.id,candidatePointIds:"points"===t.type?t.candidatePointIds:void 0}:null}reportDiagnostics(e){this.diagnostics.onEvaluation?.(e)}getNow(){return this.diagnostics.now?.()??Date.now()}createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t}){const n=this.snapshots.createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t});return this.gapCache.set(n,{x:os(n.nodes,"x"),y:os(n.nodes,"y")}),n}createResizeSnapshot({resizingShapeIds:e,coordinateSpace:t}){return this.snapshots.createResizeSnapshot({resizingShapeIds:e,coordinateSpace:t})}createHandleSnapshot(e){return this.snapshots.createHandleSnapshot(e)}snapTranslate(e){const t=this.getNow(),n=Zi(e.initialSelectionBounds,e.dragDelta),i=(s=Hi(e.initialSelectionBounds),o=e.dragDelta,s.map(e=>e.add(o)));var s,o;const r=this.gapCache.get(e.snapshot)??{x:os(e.snapshot.nodes,"x"),y:os(e.snapshot.nodes,"y")},a=this.getReleaseThreshold(e.threshold),d=this.getSwitchDistance(e.threshold),c=this.axisSnapMemory.x,l=this.axisSnapMemory.y,h={candidatePointCount:0,matchedPointCount:0},p="y"===e.lockedAxis?null:Ss(fs("x",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===c?.type?new Set(c.candidatePointIds??[]):void 0,releaseThreshold:a,selectionPointKinds:xa,switchDistance:d,stats:h}),ds("x",n,r.x,e.threshold,{previousSnapId:"gaps"===c?.type?c.id:null,releaseThreshold:a,switchDistance:d}),{previousSnap:c,switchDistance:d}),u="x"===e.lockedAxis?null:Ss(fs("y",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===l?.type?new Set(l.candidatePointIds??[]):void 0,releaseThreshold:a,selectionPointKinds:xa,switchDistance:d,stats:h}),ds("y",n,r.y,e.threshold,{previousSnapId:"gaps"===l?.type?l.id:null,releaseThreshold:a,switchDistance:d}),{previousSnap:l,switchDistance:d}),g=new Lr(p?.nudge??0,u?.nudge??0),f=[];return"points"===p?.type?f.push(...Ps("x",p,g,e.snapshot.coordinateSpace)):"gaps"===p?.type&&f.push(Bs(p,e.snapshot.coordinateSpace,g)),"points"===u?.type?f.push(...Ps("y",u,g,e.snapshot.coordinateSpace)):"gaps"===u?.type&&f.push(Bs(u,e.snapshot.coordinateSpace,g)),this.setIndicators(f),this.updateAxisSnapMemory("x",p),this.updateAxisSnapMemory("y",u),this.reportDiagnostics({operation:"translate",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:e.snapshot.nodes.length,candidatePointCount:h.candidatePointCount,candidateGapCount:("y"===e.lockedAxis?0:r.x.length)+("x"===e.lockedAxis?0:r.y.length),matchedPointCount:h.matchedPointCount,xSnapId:p?.id??null,ySnapId:u?.id??null,indicatorCount:f.length}),{nudge:g,indicators:f}}snapResize(e){const t=this.getNow(),n=$i({handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY}),i=ms(n,e.resizedSelectionBounds),s="top"===n||"bottom"===n,o="left"===n||"right"===n,r=this.getReleaseThreshold(e.threshold),a=this.getSwitchDistance(e.threshold),d=this.axisSnapMemory.x,c=this.axisSnapMemory.y,l={candidatePointCount:0,matchedPointCount:0},h=s?null:fs("x",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===d?.type?new Set(d.candidatePointIds??[]):void 0,releaseThreshold:r,switchDistance:a,stats:l}),p=o?null:fs("y",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===c?.type?new Set(c.candidatePointIds??[]):void 0,releaseThreshold:r,switchDistance:a,stats:l}),u={x:null!==h,y:null!==p},g=new Lr(h?.nudge??0,p?.nudge??0);if(e.isAspectRatioLocked&&Oi(f=n)!==Li(f)&&zi(f)!==_i(f)&&(0!==g.x||0!==g.y)){const t=h&&p?Math.abs(g.x)<Math.abs(g.y)?"x":"y":h?"x":"y",i=0===e.initialSelectionBounds.h?1:e.initialSelectionBounds.w/e.initialSelectionBounds.h;"x"===t?(u.y=!1,g.y=g.x/i,"bottom_left"!==n&&"top_right"!==n||(g.y=-g.y)):(u.x=!1,g.x=g.y*i,"bottom_left"!==n&&"top_right"!==n||(g.x=-g.x))}var f;const m=function(e,t){const n=$i({handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY});let i=e.resizedSelectionBounds.minX,s=e.resizedSelectionBounds.maxX,o=e.resizedSelectionBounds.minY,r=e.resizedSelectionBounds.maxY;e.isResizingFromCenter?(Oi(n)?(i+=t.x,s-=t.x):Li(n)&&(i-=t.x,s+=t.x),zi(n)?(o+=t.y,r-=t.y):_i(n)&&(o-=t.y,r+=t.y)):(Oi(n)?i+=t.x:Li(n)&&(s+=t.x),zi(n)?o+=t.y:_i(n)&&(r+=t.y));const a=(({minX:e,minY:t,maxX:n,maxY:i})=>{const s=Math.min(e,n),o=Math.min(t,i),r=Math.max(e,n),a=Math.max(t,i);return new zr(s,o,Math.max(1,r-s),Math.max(1,a-o))})({minX:i,minY:o,maxX:s,maxY:r});if(!e.isAspectRatioLocked){const t=(({startBounds:e,bounds:t,handleId:n,scaleX:i,scaleY:s,isResizingFromCenter:o=!1})=>{const r=Ni({axis:"x",startBounds:e,bounds:t,handleId:n,scale:i,isResizingFromCenter:o}),a=Ni({axis:"y",startBounds:e,bounds:t,handleId:n,scale:s,isResizingFromCenter:o});return{scaleX:Oi(n)||Li(n)?r*(t.w/Math.max(1,e.w)):i??1,scaleY:zi(n)||_i(n)?a*(t.h/Math.max(1,e.h)):s??1}})({startBounds:e.initialSelectionBounds,bounds:a,handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY,isResizingFromCenter:e.isResizingFromCenter});return{bounds:a,scaleX:t.scaleX,scaleY:t.scaleY}}return Ui({startBounds:e.initialSelectionBounds,bounds:a,handleId:e.handleId,aspectRatio:0===e.initialSelectionBounds.h?1:e.initialSelectionBounds.w/e.initialSelectionBounds.h,isResizingFromCenter:e.isResizingFromCenter,scaleX:e.scaleX,scaleY:e.scaleY})}(e,g),{bounds:S}=m,y=ms("any",S),I=[];if(u.x){const t=fs("x",y,e.snapshot.pointIndex,1e-8,{stats:l});t&&I.push(...Ms("x",t,Lr.Zero(),e.snapshot.coordinateSpace,S,e.snapshot.nodes))}if(u.y){const t=fs("y",y,e.snapshot.pointIndex,1e-8,{stats:l});t&&I.push(...Ms("y",t,Lr.Zero(),e.snapshot.coordinateSpace,S,e.snapshot.nodes))}return this.setIndicators(I),this.updateAxisSnapMemory("x",u.x?h:null),this.updateAxisSnapMemory("y",u.y?p:null),this.reportDiagnostics({operation:"resize",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:e.snapshot.nodes.length,candidatePointCount:l.candidatePointCount,candidateGapCount:0,matchedPointCount:l.matchedPointCount,xSnapId:u.x?h?.id??null:null,ySnapId:u.y?p?.id??null:null,indicatorCount:I.length}),{nudge:g,bounds:S,scaleX:m.scaleX,scaleY:m.scaleY,indicators:I}}snapHandle(e){const t=this.getNow();if("none"===e.mode)return this.clearIndicators(),this.reportDiagnostics({operation:"handle",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:0,outlineCount:e.snapshot.outlines.length,candidatePointCount:e.snapshot.points.length,candidateGapCount:0,matchedPointCount:0,indicatorCount:0}),null;const n="point"===e.mode?this.snapHandlePoint(e):this.snapHandleAlign(e);return n?(this.setIndicators(n.indicators),this.reportDiagnostics({operation:"handle",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:0,outlineCount:e.snapshot.outlines.length,candidatePointCount:e.snapshot.points.length,candidateGapCount:0,matchedPointCount:n.indicators.length,indicatorCount:n.indicators.length}),n):(this.clearIndicators(),this.reportDiagnostics({operation:"handle",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:0,outlineCount:e.snapshot.outlines.length,candidatePointCount:e.snapshot.points.length,candidateGapCount:0,matchedPointCount:0,indicatorCount:0}),null)}snapHandlePoint(e){const t=As(e);let n=null,i=null,s=e.threshold*e.threshold;for(const a of t)for(const t of e.snapshot.points){const e=a.dist2(t.point);e>s||(s=e,n=t.point,i=a)}if(!n)for(const a of t)for(const t of e.snapshot.outlines){const e=is(a,t.points);!e||e.distanceSquared>s||(s=e.distanceSquared,n=e.point,i=a)}if(!n||!i)return null;const o=n.sub(i);return{snappedPagePoint:e.pagePoint.add(o),nudge:o,indicators:[(r=n,{id:Cs("x",[r,r],[r]),type:"points",axis:"x",line:[r.clone(),r.clone()],points:[r.clone()],rotation:0,rotationCenter:r.clone()})]};var r}snapHandleAlign(e){const t=As(e);let n=null,i=null,s=null,o=null,r=e.threshold,a=e.threshold;for(const h of t)for(const t of e.snapshot.points){const e=Math.abs(t.point.x-h.x);e<=r&&(r=e,n=t.point,s=h);const d=Math.abs(t.point.y-h.y);d<=a&&(a=d,i=t.point,o=h)}if(!n&&!i)return null;const d=new Lr(n&&s?n.x-s.x:0,i&&o?i.y-o.y:0),c=e.pagePoint.add(d),l=[];return n&&s&&l.push(Ts("x",s.add(d),n)),i&&o&&l.push(Ts("y",o.add(d),i)),{snappedPagePoint:c,nudge:d,indicators:l}}},Ba=class{editor;_brushBoxSignal;brushBoxSignal;brushBoxActiveSignal;_bindingPreviewSignal;bindingPreviewSignal;bindingPreviewActiveSignal;_terminalBindingGuidesSignal;terminalBindingGuidesSignal;_dropTargetShapeIdSignal;dropTargetShapeIdSignal;_hoveredShapeIdSignal;hoveredShapeIdSignal;_selectionTranslationActiveSignal;selectionTranslationActiveSignal;terminalBindingResolver=(e,t)=>(({rawPagePoint:e})=>({pagePoint:e.clone(),binding:null,preview:null}))(t);constructor(e){this.editor=e;const{atom:t,computed:n}=e.signals;this._brushBoxSignal=t("editor.brushBox",null),this.brushBoxSignal=this._brushBoxSignal,this.brushBoxActiveSignal=n("editor.brushBoxActive",()=>null!==this._brushBoxSignal.get()),this._bindingPreviewSignal=t("editor.bindingPreview",null),this.bindingPreviewSignal=this._bindingPreviewSignal,this.bindingPreviewActiveSignal=n("editor.bindingPreviewActive",()=>null!==this._bindingPreviewSignal.get()),this._terminalBindingGuidesSignal=t("editor.terminalBindingGuides",[]),this.terminalBindingGuidesSignal=this._terminalBindingGuidesSignal,this._dropTargetShapeIdSignal=t("editor.dropTargetShapeId",null),this.dropTargetShapeIdSignal=this._dropTargetShapeIdSignal,this._hoveredShapeIdSignal=t("editor.hoveredShapeId",null),this.hoveredShapeIdSignal=this._hoveredShapeIdSignal,this._selectionTranslationActiveSignal=t("editor.selectionTranslationActive",!1),this.selectionTranslationActiveSignal=this._selectionTranslationActiveSignal}setBrushBox(e){se(this._brushBoxSignal.get(),e)||this._brushBoxSignal.set(e?e.clone():null)}setBindingPreview(e){var t,n;(t=this._bindingPreviewSignal.get())===(n=e)||(t&&n?t.terminal===n.terminal&&t.targetShapeId===n.targetShapeId&&te(t.rawPagePoint,n.rawPagePoint)&&te(t.resolvedPagePoint,n.resolvedPagePoint)&&(t.guidePath??null)===(n.guidePath??null):t===n)||this._bindingPreviewSignal.set(e?{...e,rawPagePoint:e.rawPagePoint.clone(),resolvedPagePoint:e.resolvedPagePoint.clone()}:null)}setTerminalBindingGuides(e){const t=e??[];((e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],s=t[n];if(!i||!s||!zn(i,s))return!1}return!0})(this._terminalBindingGuidesSignal.get(),t)||this._terminalBindingGuidesSignal.set(t.map(Dn))}setDropTargetShapeId(e){this._dropTargetShapeIdSignal.get()!==e&&this._dropTargetShapeIdSignal.set(e)}setHoveredShapeId(e){this._hoveredShapeIdSignal.get()!==e&&this._hoveredShapeIdSignal.set(e)}setSelectionTranslationActive(e){this._selectionTranslationActiveSignal.get()!==e&&this._selectionTranslationActiveSignal.set(e)}setSnapIndicators(e){e?this.editor.snaps.setIndicators(e):this.editor.snaps.clearIndicators()}setTerminalBindingResolver(e){this.terminalBindingResolver=e}resolveTerminalBinding(e){return this.terminalBindingResolver(this.editor,e)}clearSelectionTransients(){this.setBrushBox(null),this.setBindingPreview(null),this.setTerminalBindingGuides(null),this.setDropTargetShapeId(null),this.setHoveredShapeId(null),this.setSelectionTranslationActive(!1),this.setSnapIndicators(null)}},ka=class{editor;animationScheduler;_viewportScreenSizeSignal;viewportScreenSizeSignal;_cameraLockSignal;cameraLockSignal;animationFrame=null;animationGeneration=0;constructor(e,t){this.editor=e,this.animationScheduler=t,this._viewportScreenSizeSignal=e.signals.atom("editor.viewportScreenSize",{w:0,h:0}),this.viewportScreenSizeSignal=this._viewportScreenSizeSignal,this._cameraLockSignal=e.signals.atom("editor.cameraLock",null),this.cameraLockSignal=this._cameraLockSignal}getCurrentCamera(){return this.editor.state.camera.get()}getCamera(e=this.editor.pages.getCurrentId()){return this.editor.state.session.get().pageCameraById[e]??Yr}pageToScreen(e,t=this.editor.pages.getCurrentId()){const n=this.getCamera(t);return new e.constructor((e.x-n.x)*n.z,(e.y-n.y)*n.z)}screenToPage(e,t=this.editor.pages.getCurrentId()){const n=this.getCamera(t);return new e.constructor(e.x/n.z+n.x,e.y/n.z+n.y)}setCamera(e,t){this.cancelAnimation(),this.writeCamera(e,t)}setLock(e){if(null===e)return this.cancelAnimation(),this._cameraLockSignal.set(null),!0;if(!Number.isFinite(e.x)||!Number.isFinite(e.y))return!1;this.cancelAnimation(),this.editor.interaction.cancelForCommand();const t=this.editor.pages.getCurrentId();return this._cameraLockSignal.set({pageId:t,pagePoint:{x:e.x,y:e.y}}),this.writeCamera({},{pageId:t,source:"system"}),!0}animateCameraTo(e,t){this.cancelAnimation();const n=this.animationScheduler,i=t.pageId??this.editor.pages.getCurrentId(),s=t.source??"system",o=this.getCamera(i),r=Number.isFinite(t.durationMs)&&t.durationMs>0?t.durationMs:0;if(!n||!0===n.prefersReducedMotion?.()||0===r||(a=o).x===(d=e).x&&a.y===d.y&&a.z===d.z)return void this.writeCamera(e,{pageId:i,source:s});var a,d;const c=this.animationGeneration;let l=null;const h=t=>{if(c!==this.animationGeneration)return;l??=t;const a=Math.min(1,Math.max(0,(t-l)/r)),d=(e=>1-(1-e)**3)(a);this.writeCamera({x:Ys(o.x,e.x,d),y:Ys(o.y,e.y,d),z:Ys(o.z,e.z,d)},{pageId:i,source:s}),c===this.animationGeneration&&(this.animationFrame=a>=1?null:{handle:n.requestFrame(h)})};this.animationFrame={handle:n.requestFrame(h)}}cancelAnimation(){this.animationGeneration+=1,this.animationFrame&&(this.animationScheduler?.cancelFrame(this.animationFrame.handle),this.animationFrame=null)}dispose(){this.cancelAnimation()}writeCamera(e,t){const n=t?.source??"system",i=t?.pageId??this.editor.pages.getCurrentId(),s=this.getCamera(i);let o="number"==typeof e.x?e.x:s.x,r="number"==typeof e.y?e.y:s.y;const a=kn("number"==typeof e.z?e.z:s.z),d=this._cameraLockSignal.peek();if(d?.pageId===i){const e=this._viewportScreenSizeSignal.peek();e.w>0&&e.h>0?(o=d.pagePoint.x-e.w/(2*a),r=d.pagePoint.y-e.h/(2*a)):(o=s.x,r=s.y)}const c={x:o,y:r,z:a};c.x===s.x&&c.y===s.y&&c.z===s.z||this.editor.session.update({pageCameraById:{...this.editor.state.session.get().pageCameraById,[i]:c}},n)}panCamera(e,t="system"){const n=this.getCurrentCamera();this.setCamera({x:n.x+e.x/n.z,y:n.y+e.y/n.z},{source:t})}zoomCameraAtScreenPoint(e,t,n="system"){const i=kn(this.getCurrentCamera().z*Math.exp(.0015*-t));this.zoomCameraToScreenPoint(e,i,n)}zoomCameraToScreenPoint(e,t,n="system"){const i=kn(t),s=this.screenToPage(e);this.setCamera({x:s.x-e.x/i,y:s.y-e.y/i,z:i},{source:n})}zoomAtViewportCenter(e,t="system"){const n=this.viewportScreenSizeSignal.get(),i=new Lr(n.w/2,n.h/2);this.zoomCameraAtScreenPoint(i,e,t)}resetZoom(e="user"){const t=this.viewportScreenSizeSignal.get(),n=new Lr(t.w/2,t.h/2),i=this.screenToPage(n);this.editor.commands.setCamera({camera:{x:i.x-n.x,y:i.y-n.y,z:1}},{source:e})}setViewportScreenSize(e){const t={w:Math.max(0,e.w),h:Math.max(0,e.h)},n=this._viewportScreenSizeSignal.get();n.w===t.w&&n.h===t.h||(this._viewportScreenSizeSignal.set(t),this._cameraLockSignal.peek()&&this.writeCamera({},{source:"system"}))}},Ea=class{shapeRenderOrderByIdSignal;culledShapeIdsSignal;culledShapeIdSetSignal;selectedShapeIdsOutsideCulledSignal;selectedShapeIdsOutsideCulledSetSignal;renderVisibleShapeIdsSignal;retainedShapeIdsSignal;renderVisibleShapeIdSetSignal;renderItemsSignal;retainedBaseShapeWindowSnapshotSignal;retainedShapeWindowSnapshotSignal;constructor(e,t){const{computed:n}=e.signals;this.shapeRenderOrderByIdSignal=n("editor.shapeRenderOrderById",()=>{const e=new Map;for(const[n,i]of t.currentPageShapeIds.get().entries())e.set(i,n);return e}),this.culledShapeIdsSignal=n("editor.culledShapeIds",()=>{const n=t.currentPageId.get(),i=t.renderViewportPageBounds.get();return i?e.shapes.getIdsInViewport(i,{pageId:n}):t.currentPageShapeIds.get()},{isEqual:J}),this.retainedBaseShapeWindowSnapshotSignal=n("editor.retainedBaseShapeWindowSnapshot",e=>{const n=t.currentPageShapeIds.get(),i=null!==t.viewportPageBounds.get(),s=((e,t,n=0)=>Fs(e.map(e=>t.get(e)).filter(e=>void 0!==e).map(e=>({start:e,end:e+1})),n))(this.culledShapeIdsSignal.get(),this.getPageIndexById(n));if(e!==xr&&e&&e.viewportReady&&s.length>0){const t=((e,t)=>{if(e.length!==t.length||0===t.length)return null;const n=t.map((n,i)=>{const s=e[i];if(!s)return null;if(s.end+2<n.start||s.start>n.end+2)return null;const o=i>0?t[i-1]:null,r=i<t.length-1?t[i+1]:null,a=r?r.start-3:1/0,d={start:Math.min(n.start,Math.max(o?o.end+3:-1/0,s.start)),end:Math.max(n.end,Math.min(a,s.end))};return d.end-d.start>n.end-n.start+4?null:d});if(n.some(e=>null===e))return null;const i=n;if(Fs(i).length!==t.length)return null;const s=Os(t);return Os(i)>s+12?null:i})(Fs(e.ranges.map(e=>({...e}))),s);if(t)return zs(n,t,{viewportReady:i})}return zs(n,s,{viewportReady:i})},{isEqual:(e,t)=>J(e.shapeIds,t.shapeIds)}),this.culledShapeIdSetSignal=n("editor.culledShapeIdSet",()=>new Set(this.culledShapeIdsSignal.get()),{isEqual:ee}),this.selectedShapeIdsOutsideCulledSignal=n("editor.selectedShapeIdsOutsideCulled",()=>{const e=t.selectedShapeIds.get();if(0===e.length)return[];const n=this.culledShapeIdSetSignal.get();return e.filter(e=>!n.has(e))},{isEqual:J}),this.selectedShapeIdsOutsideCulledSetSignal=n("editor.selectedShapeIdsOutsideCulledSet",()=>new Set(this.selectedShapeIdsOutsideCulledSignal.get()),{isEqual:ee}),this.renderVisibleShapeIdsSignal=n("editor.renderVisibleShapeIds",()=>{if(0===this.selectedShapeIdsOutsideCulledSignal.get().length)return this.culledShapeIdsSignal.get();const e=this.culledShapeIdSetSignal.get(),n=this.selectedShapeIdsOutsideCulledSetSignal.get();return t.currentPageShapeIds.get().filter(t=>e.has(t)||n.has(t))},{isEqual:J}),this.retainedShapeWindowSnapshotSignal=n("editor.retainedShapeWindowSnapshot",e=>{const n=t.currentPageShapeIds.get(),i=null!==t.viewportPageBounds.get(),s=this.retainedBaseShapeWindowSnapshotSignal.get().shapeIds,o=(r=s.length)<=0?0:Xs(Math.ceil(.5*r),12,96);var r;const a=((e,t,n,i)=>{if(0===e.length)return[];const s=new Map;for(const[a,d]of e.entries())s.set(d,a);const o=Fs(t.map(e=>s.get(e)).filter(e=>void 0!==e).sort((e,t)=>e-t).map(e=>({start:e,end:e+1})),2),r=[];if(o.length>0){const t=Xs(Math.ceil(i/(2*o.length)),8,32);for(const[n,i]of o.entries()){const s=n>0?o[n-1]:null,a=n<o.length-1?o[n+1]:null,d=a?a.start-i.end:1/0,c=Ds(s?i.start-s.end:1/0,t),l=Ds(d,t+4);r.push({start:Math.max(0,i.start-c),end:Math.min(e.length,i.end+l)})}}for(const a of n){const e=s.get(a);void 0!==e&&r.push({start:e,end:e+1})}return 0===r.length?[]:Fs(r,2)})(n,s,this.selectedShapeIdsOutsideCulledSetSignal.get(),o);if(i&&e!==xr&&e&&e.viewportReady&&e.ranges.length>0&&a.length>0){const t=Fs(e.ranges.map(e=>({...e})));if(((e,t)=>{if(0===t.length)return!0;if(0===e.length)return!1;let n=0;for(const i of t){for(;n<e.length;){const t=e[n];if(t&&i.start>=t.start&&i.end<=t.end)break;if(!(t&&i.end>t.end))return!1;n+=1}if(n>=e.length)return!1}return!0})(t,a))return zs(n,t,{viewportReady:i});const s=((e,t,n)=>{const i=t.map((n,i)=>{const s={...n};for(const t of e)t.end+6<n.start||t.start>n.end+6||(s.start=Math.min(s.start,t.start),s.end=Math.max(s.end,t.end));const o=i>0?t[i-1]:null,r=i<t.length-1?t[i+1]:null,a=r?r.start-3:1/0;return{start:Math.min(n.start,Math.max(o?o.end+3:-1/0,s.start)),end:Math.max(n.end,Math.min(a,s.end))}});if(Fs(i).length!==t.length)return null;const s=Os(t);return Os(i)>s+n?null:i})(t,a,o);if(s)return zs(n,s,{viewportReady:i})}return zs(n,a,{viewportReady:i})},{isEqual:(e,t)=>J(e.shapeIds,t.shapeIds)}),this.retainedShapeIdsSignal=n("editor.retainedShapeIds",()=>this.retainedShapeWindowSnapshotSignal.get().shapeIds,{isEqual:J}),this.renderVisibleShapeIdSetSignal=n("editor.renderVisibleShapeIdSet",()=>new Set(this.renderVisibleShapeIdsSignal.get()),{isEqual:ee}),this.renderItemsSignal=n("editor.renderItems",()=>{const n=t.selectedShapeIdSet.get(),i=[];for(const t of this.renderVisibleShapeIdsSignal.get()){const s=e.shapes.getSignal(t).get(),o=e.shapes.getPageBoundsSignal(t).get();s&&!s.isHidden&&o&&i.push({id:s.id,shape:s,bounds:o,isSelected:n.has(s.id)})}return i},{isEqual:Ks})}getPageIndexById(e){const t=new Map;for(const[n,i]of e.entries())t.set(i,n);return t}},Aa=class{signals=e();store;[Xr];inputs;tools;cameraManager;editing;shapeUtils=new Vr;shapeSvgExporters=new Ur;shapeSvgDecorations=new Hr;shapeHitTestDecorations=new Gr;bindingUtils=new Or;interactions=new ra;runtime=new qr;bindingQueries;shapeGeometryQueries;shapeTreeIndex;selectionGeometry;bindingManager;spatialIndex;snaps;renderWindowManager;shapeSignals;selectionOverlay;interactionManager;eventRouter;history;operations;commands;state;render;_shapeDefaultPropsByTypeSignal;assetUrlResolver=()=>null;_readonlySignal;writesClosed=!1;document={getMetadata:()=>{const e=this.store.get(Ar);return h(e)?e:void 0},updateMetadata:(e,t="user")=>this.commands.updateDocumentMeta({patch:e},{source:t}),setReadonly:e=>{if(!this.writesClosed&&this._readonlySignal.get()!==e){if(e){this.interaction.cancelForCommand(),this.state.shapeEditingSession.get()?.isComposing&&this.editing.setComposition(!1,"system"),this.editing.cancel("system");const e=this.state.tool.get().activeToolId;"select"!==e&&"hand"!==e&&this.tools.select("select","system")}this._readonlySignal.set(e)}}};session={get:()=>{const e=this.store.get(Kr);if(!u(e))throw new Error("Missing session record");return e},update:(e,t="system")=>{Le(this,e,t)}};pages={getAll:()=>this.state.pages.get(),get:e=>{const t=this.store.get(e);return l(t)?t:void 0},getCurrentId:()=>this.state.currentPageId.get(),createAndSelect:(e,t="user")=>{const n=this.commands.createPage(e,{source:t});return this.commands.setCurrentPageId(n.id,{source:t}),n},select:(e,t="user")=>{this.commands.setCurrentPageId(e,{source:t})},rename:(e,t,n="user")=>{this.commands.renamePage({id:e,name:t},{source:n})},updateMetadata:(e,t,n="user")=>this.commands.updatePageMeta({id:e,patch:t},{source:n}),delete:(e,t="user")=>(this.interaction.cancelForCommand(),this.commands.deletePage(e,{source:t}))};selection={getIds:(e=this.pages.getCurrentId())=>this.session.get().pageSelectedShapeIdsById[e]??[],set:(e,t)=>{Oe(this,e,t)},remove:(e,t="system")=>{((e,t,n="system")=>{if(0===t.length)return;const i=new Set(t),s=e.session.get(),o={};for(const r of e.pages.getAll())o[r.id]=(s.pageSelectedShapeIdsById[r.id]??[]).filter(e=>!i.has(e));e.session.update({pageSelectedShapeIdsById:o},n)})(this,e,t)},delete:(e="user")=>{this.shapes.delete(this.selection.getIds(),e)},createClipboardPayload:()=>Ee(this),pasteClipboardPayload:e=>(this.interaction.cancelForCommand(),Ae(this,e)),duplicate:(e={})=>(this.interaction.cancelForCommand(),((e,t={})=>{const n=Ee(e);return n?Ae(e,{payload:n,offset:t.offset??Jr,source:t.source}):[]})(this,e)),selectAll:(e="user")=>{this.interaction.cancelForCommand(),((e,t="user")=>{const n=e.pages.getCurrentId(),i=e.state.currentPageShapeIds.get().map(t=>e.shapes.get(t)).filter(t=>!!t&&t.parentId===n&&!e.shapes.isHidden(t.id)).map(e=>e.id);e.commands.setSelectedShapeIds(i,{source:t})})(this,e)},resetRotation:(e="user")=>{((e,t="user")=>{if(!e.selection.canRotate())return;const n=e.state.selectedShapes.get().filter(t=>e.shapes.getUtil(t).contributesToSelectionFrame(t,{editor:e}));if(0===n.length)return;const i=n.flatMap(t=>{const n=fn(e,t);if(!n)return[];const i=mn(e,t,n,{id:t.id,rotation:0});return i?[i]:[]});i.length>0&&e.commands.updateShapes(i,{source:t})})(this,e)},flip:(e,t="user")=>{const n=function(e,t){if(!e.selection.canFlip())return[];const n=e.selection.getTransformTargets(),i=e.selection.getFrame()??((e,t)=>{const n=t.flatMap(t=>{const n=fn(e,t);return n?e.shapes.getUtil(t).getSelectionPagePoints(n)??[]:[]});if(0===n.length)return null;const i=zr.FromPoints(n);return{bounds:i,rotation:0,rotationCenter:i.center,hasCompatibleRotation:!0}})(e,n);return i&&0!==n.length?n.map(n=>((e,t,n,i)=>{const s=e.shapes.getUtil(t),o=fn(e,t);if(!o)return null;const r=s.getSelectionPagePoints(o);if(!r&&!s.contributesToSelectionFrame(t,{editor:e}))return null;const a=(({points:e,transform:t})=>0===e.length?null:zr.FromPoints(e.map(e=>_n(e,t))))({points:r?[...r]:s.getPositionedOutlineVertices(t).map(n=>e.shapes.computePositionedToPageTransform(t).applyToPoint(n)),transform:n});return a?mn(e,t,o,s.flipSelectionBounds(o,{axis:i,selectionBounds:n.bounds,selectionLocalBounds:Wn({axis:i,bounds:a,selectionBounds:n.bounds}),selectionRotation:n.rotation,selectionRotationCenter:n.rotationCenter})):null})(e,n,i,t)).filter(e=>null!==e):[]}(this,e);0!==n.length&&(this.interaction.cancelForCommand(),this.commands.updateShapes(n,{source:t}))},canAlign:()=>Kn(this,2),align:(e,t="user")=>(this.interaction.cancelForCommand(),((e,t,n="user")=>{const i=Yn(e);if(i.length<2)return!1;const s=Xn(e,i[0].shape.parentId);if(!s)return!1;const o=zr.FromPoints(i.flatMap(e=>[new Lr(e.bounds.minX,e.bounds.minY),new Lr(e.bounds.maxX,e.bounds.maxY)])),r=i.map(({shape:e,bounds:n})=>{let i=0,r=0;switch(t){case"left":i=o.minX-n.minX;break;case"right":i=o.maxX-n.maxX;break;case"horizontal-center":i=o.center.x-n.center.x;break;case"top":r=o.minY-n.minY;break;case"bottom":r=o.maxY-n.maxY;break;case"vertical-center":r=o.center.y-n.center.y}const a=Fn(s,new Lr(i,r));return{id:e.id,x:e.x+a.x,y:e.y+a.y}});return e.commands.updateShapes(r,{source:n}),!0})(this,e,t)),canDistribute:()=>Kn(this,3),distribute:(e,t="user")=>(this.interaction.cancelForCommand(),((e,t,n="user")=>{const i=Yn(e);if(i.length<3)return!1;const s=Xn(e,i[0].shape.parentId);if(!s)return!1;const o="horizontal"===t,r=e=>o?e.w:e.h,a=e=>o?e.minX:e.minY,d=o?"x":"y",c=[...i].sort((e,t)=>e.bounds.center[d]-t.bounds.center[d]),l=c[0].bounds,h=c[c.length-1].bounds,p=((o?h.maxX:h.maxY)-a(l)-c.reduce((e,t)=>e+r(t.bounds),0))/(c.length-1);let u=a(l);const g=c.map(({shape:e,bounds:t},n)=>{const i=0===n||n===c.length-1?a(t):u,d=i-a(t);u=i+r(t)+p;const l=Fn(s,o?new Lr(d,0):new Lr(0,d));return{id:e.id,x:e.x+l.x,y:e.y+l.y}});return e.commands.updateShapes(g,{source:n}),!0})(this,e,t)),canResize:()=>(e=>{const t=Tn(e),n=1===t.length;return t.length>0&&t.every(t=>e.shapes.getUtil(t).canParticipateInSelectionResize(t,{editor:e,isOnlyAffectedShape:n}))})(this),canFlip:()=>Mn(this),canRotate:()=>(e=>{const t=Tn(e),n=1===t.length;return t.length>0&&t.every(t=>e.shapes.getUtil(t).canParticipateInSelectionRotation(t,{editor:e,isOnlyAffectedShape:n}))})(this),getTransformTargets:()=>{return xn(e=this,e.selection.getIds()).map(t=>e.shapes.get(t)).filter(e=>!!e);var e},getResizeTargets:()=>(e=>{const t=[],n=new Set,i=s=>{if(!n.has(s.id))if(n.add(s.id),e.shapes.getUtil(s).shouldResizeDescendants(s))for(const t of e.layers.getChildren(s.id))i(t);else t.push(s)};for(const s of Bn(e,e.selection.getIds())){const t=e.shapes.get(s);t&&i(t)}return t})(this),getRotationTargets:()=>{return Cn(e=this,e.selection.getIds()).map(t=>e.shapes.get(t)).filter(e=>!!e);var e},getPageBounds:()=>this.selectionGeometry.pageBounds.get()?.clone()??null,getFrame:()=>vi(this),containsPoint:e=>((e,t)=>{const n=vi(e);if(!n)return!1;const i=xi(e,t);return!!i&&n.bounds.containsPoint(i)})(this,e),toFramePoint:e=>xi(this,e),getPageOutlineVertices:()=>this.selectionGeometry.pageOutlineVertices.get().map(e=>e.clone()),getAnchorPagePoint:()=>this.selectionGeometry.selectionAnchorPagePoint.get()?.clone()??null,getLocalBounds:()=>this.selectionGeometry.localBounds.get()?.clone()??null,getRotationCenter:()=>this.selectionGeometry.rotationCenter.get()?.clone()??null,getRotation:()=>this.selectionGeometry.rotation.get(),hasCompatibleRotation:()=>this.selectionGeometry.hasCompatibleRotation.get(),hitTestHandle:e=>this.selectionOverlay.hitTestHandle(e)};shapes={get:e=>{const t=this.store.get(e);return p(t)?t:void 0},getForPage:e=>this.shapeTreeIndex.getShapesForPage(e),getSignal:e=>this.shapeSignals.getShapeSignal(e),getContentCutoutLocalPolygonsSignal:e=>this.shapeSignals.getContentCutoutLocalPolygonsSignal(e),getLocalToPageTransformSignal:e=>this.shapeGeometryQueries.getShapeLocalToPageTransformSignal(e),getLocalToPageTransform:e=>this.shapeGeometryQueries.getShapeLocalToPageTransform(e)??null,getPageBoundsSignal:e=>this.shapeGeometryQueries.getShapePageBoundsSignal(e),getSelectedSignal:e=>this.shapeSignals.getSelectedSignal(e),getRenderOrderSignal:e=>this.shapeSignals.getRenderOrderSignal(e),getRenderVisibleSignal:e=>this.shapeSignals.getRenderVisibleSignal(e),getDocumentVisibleSignal:e=>this.shapeSignals.getDocumentVisibleSignal(e),getEffectiveOpacitySignal:e=>this.shapeSignals.getEffectiveOpacitySignal(e),getEditingSessionSignal:e=>this.shapeSignals.getEditingSessionSignal(e),getDropTargetSignal:e=>this.shapeSignals.getDropTargetSignal(e),getHoveredSignal:e=>this.shapeSignals.getHoveredSignal(e),isHidden:e=>this.shapeSignals.isDocumentHidden(e),getDefaultProps:e=>{const t=this.shapeUtils.get(e),n=this._shapeDefaultPropsByTypeSignal.get().get(e)??{};return t.validateProps({...t.getDefaultProps(),...n})},updateDefaultProps:(e,t)=>{const n=this.shapeUtils.get(e),i=this._shapeDefaultPropsByTypeSignal.get().get(e)??{},s=n.validateProps({...n.getDefaultProps(),...i,...t}),o=n.validateProps(n.getDefaultProps()),r={};for(const[d,c]of Object.entries(s))o[d]!==c&&(r[d]=c);if(((e,t)=>{if(e===t)return!0;const n=Object.entries(e),i=Object.entries(t);if(n.length!==i.length)return!1;for(const[s,o]of n)if(!oe(o,t[s]))return!1;return!0})(i,r))return;const a=new Map(this._shapeDefaultPropsByTypeSignal.get());0===Object.keys(r).length?a.delete(e):a.set(e,r),this._shapeDefaultPropsByTypeSignal.set(a)},delete:(e,t="user")=>{const n=Array.from(new Set(e));0!==n.length&&(this.interaction.cancelForCommand(),this.commands.deleteShapes(n,{source:t}))},setHidden:(e,t,n="user")=>ot(this,e,{flag:"isHidden",value:t,source:n}),setLocked:(e,t,n="user")=>ot(this,e,{flag:"isLocked",value:t,source:n}),getUtil:e=>this.shapeUtils.get(e.type),computePositionedBounds:e=>((e,t)=>e.shapes.getUtil(t).getPositionedBounds(t))(this,e),computeLocalBounds:e=>((e,t)=>e.shapes.getUtil(t).getLocalBounds(t))(this,e),computeRenderBounds:e=>((e,t)=>e.shapes.getUtil(t).getRenderBounds(t))(this,e),computeExportBounds:e=>wi(this,e),computeExportBoundsInShapeSpace:(e,t)=>function(e,t,n){if(t.id===n.id)return wi(e,t);if(!((e,t,n)=>{let i=e.shapes.get(t);const s=new Set;for(;i?.parentId.startsWith("shape:");){const t=i.parentId;if(t===n)return!0;if(s.has(t))return!1;s.add(t),i=e.shapes.get(t)}return!1})(e,t.id,n.id))return null;const i=Pi(e,n).tryInvert();return i?Be(t,e.shapes.getUtil(t),i.compose(Pi(e,t))):null}(this,e,t),computeLocalToPageTransform:e=>Pi(this,e),computeRenderToPageTransform:e=>function(e,t){return((e,t,n)=>be(e,t,n))(t,e.shapes.getUtil(t),Ii(e,t))}(this,e),computeExportToPageTransform:e=>((e,t)=>xe(t,e.shapes.getUtil(t),Ii(e,t)))(this,e),computePageBounds:e=>function(e,t){return((e,t,n)=>zr.FromPoints(Te(e,t,n)))(t,e.shapes.getUtil(t),Ii(e,t))}(this,e),computeExportPageBounds:e=>function(e,t){return((e,t,n)=>Be(e,t,xe(e,t,n)))(t,e.shapes.getUtil(t),Ii(e,t))}(this,e),computeGeometry:e=>bi(this,e),computePositionedToPageTransform:e=>((e,t)=>ve(t,e.shapes.getUtil(t),Ii(e,t)))(this,e),computePageCenter:e=>bi(this,e).center,computePageCorners:e=>bi(this,e).corners,computePageOutlineVertices:e=>bi(this,e).outlineVertices,getPositionedBounds:e=>this.shapeGeometryQueries.getShapePositionedBounds(e)??null,getPageBounds:e=>this.shapeGeometryQueries.getShapePageBounds(e)??null,getGeometry:e=>this.shapeGeometryQueries.getShapeGeometry(e)??null,getPositionedToPageTransform:e=>this.shapeGeometryQueries.getShapePositionedToPageTransform(e)??null,getPageCenter:e=>this.shapeGeometryQueries.getShapePageCenter(e)??null,getPageCorners:e=>this.shapeGeometryQueries.getShapePageCorners(e)??null,getPageOutlineVertices:e=>this.shapeGeometryQueries.getShapePageOutlineVertices(e)??[],getClipAncestorIds:e=>this.shapeGeometryQueries.getShapeClipAncestorIds(e),getClipAncestorIdsSignal:e=>this.shapeGeometryQueries.getShapeClipAncestorIdsSignal(e),isPagePointInClip:(e,t)=>this.shapeGeometryQueries.isPagePointInShapeClip(e,t),getClippedPageBounds:e=>this.shapeGeometryQueries.getShapeClippedPageBounds(e),hitTest:e=>this.shapes.hitTestPoint(e)[0]??null,hitTestPoint:(e,t)=>this.spatialIndex.getShapesAtPoint(e,{...t,filter:n=>!this.shapes.isHidden(n.id)&&this.shapes.isPagePointInClip(n.id,e)&&(t?.filter?.(n)??!0)}),hitTestLineSegment:(e,t,n)=>this.spatialIndex.getShapesHitByLineSegment(e,t,{...n,filter:e=>!this.shapes.isHidden(e.id)&&(n?.filter?.(e)??!0)}),getIdsInBounds:(e,t)=>this.spatialIndex.getShapeIdsInBounds(e,t).filter(e=>!this.shapes.isHidden(e)),getInBounds:(e,t)=>this.spatialIndex.getShapesInBounds(e,t).filter(e=>!this.shapes.isHidden(e.id)),getInViewport:(e,t)=>this.spatialIndex.getShapesInViewport(e,t).filter(e=>!this.shapes.isHidden(e.id)),getIdsInViewport:(e,t)=>this.spatialIndex.getShapeIdsInViewport(e,t)};layers={getSelectionParentOrderState:()=>Ri(this),getSelectionGroupState:()=>Ci(this),canGroupSelection:()=>null!==Ci(this),canGroup:e=>((e,t)=>null!==Mi(e,t))(this,e),group:(e,t="user")=>Bi(this,e,t),groupSelection:(e="user")=>((e,t="user")=>{const n=Bi(e,e.selection.getIds(),t);return n&&e.commands.setSelectedShapeIds([n.id],{source:t}),n})(this,e),getUngroupableSelectionIds:()=>ki(this),getUngroupableIds:e=>Ei(this,e),canUngroupSelection:()=>ki(this).length>0,canUngroup:e=>((e,t)=>Ei(e,t).length>0)(this,e),ungroup:(e,t="user")=>Ai(this,e,t),ungroupSelection:(e="user")=>((e,t="user")=>Ai(e,e.selection.getIds(),t))(this,e),getSelectionSiblingOrderState:()=>Ki(this),canMoveSelectionWithinParent:e=>((e,t)=>{const n=Ki(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this,e),canMoveSelection:e=>((e,t)=>{const n=Ri(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this,e),canMove:(e,t)=>((e,t,n)=>{const i=Yi(e,t);return"backward"===n?i?.canMoveBackward??!1:i?.canMoveForward??!1})(this,e,t),move:(e,t,n="user")=>Xi(this,e,t,n),moveToEdge:(e,t,n="user")=>Fi(this,e,t,n),moveSelectionWithinParent:(e,t="user")=>((e,t,n="user")=>{const i=e.state.selectedShapes.get();if(1!==i.length)return!1;const[s]=i;if(!s||s.isLocked)return!1;const o=Ki(e);if(!o)return!1;const r=e.layers.getChildren(o.parentId),a=o.index;if(r[a]?.id!==s.id)return!1;const d="backward"===t?a-1:a+1;if(d<0||d>=r.length)return!1;const c=[...r],[l]=c.splice(a,1);return!!l&&(c.splice(d,0,l),e.interaction.cancelForCommand(),e.commands.updateShapes(c.map((t,n)=>({id:t.id,index:re(e).createShapeIndex(n+1)})),{source:n}),!0)})(this,e,t),moveToPlacement:(e,t="user")=>function(e,t,n="user"){const i=Array.from(new Set(t.ids));if(0===i.length)return{ok:!1,reason:"notFound"};const s=i.map(t=>e.shapes.get(t)).filter(e=>!!e);if(s.length!==i.length)return{ok:!1,reason:"notFound"};for(const r of s){if(r.isLocked)return{ok:!1,reason:"locked"};if(e.shapes.isHidden(r.id))return{ok:!1,reason:"hidden"}}for(const r of i){const n=t.parentId;if(n.startsWith("page:")){if(!e.pages.get(n))return{ok:!1,reason:"invalidParent"}}else{const t=e.shapes.get(n);if(!t)return{ok:!1,reason:"invalidParent"};if(t.id===r||e.layers.getDescendantIds(r).includes(t.id))return{ok:!1,reason:"cycle"};if(!e.layers.canReceiveChild(t.id,r))return{ok:!1,reason:"invalidParent"}}}const o=((e,t,n,i,s)=>{const o=((e,t,n,i)=>{const s=new Set(n),o=t.parentId.startsWith("shape:")?e.shapes.get(t.parentId):null,r=S(e).getAll().filter(e=>p(e)&&e.parentId===t.parentId).filter(e=>!s.has(e.id));r.sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id));let a=r.length;if(t.beforeId){const e=r.findIndex(e=>e.id===t.beforeId);if(-1===e)return{ok:!1,reason:"invalidBeforeId"};a=e}r.splice(a,0,...i);const d=new Map;for(const c of i){if(c.parentId===t.parentId)continue;const n=Ue(e,c,t.parentId);if(!n)return{ok:!1,reason:"unsupportedTransform"};d.set(c.id,n)}return{ok:!0,updates:r.map((n,i)=>{const s=n.parentId!==t.parentId&&o?e.shapes.getUtil(o).getChildPlacementMeta(o,n,{editor:e,reason:"reparent"}):n.meta;return{id:n.id,parentId:t.parentId,index:re(e).createShapeIndex(i+1),...d.get(n.id),meta:s===n.meta?void 0:s}})}})(e,t,n,i);return o.ok?(e.interaction.cancelForCommand(),e.commands.updateShapes(o.updates,{source:s}),o):o})(e,t,i,s,n);return o.ok?{ok:!0,movedIds:i}:{ok:!1,reason:o.reason}}(this,e,t),moveSelection:(e,t="user")=>((e,t,n="user")=>Xi(e,e.selection.getIds(),t,n))(this,e,t),moveSelectionToEdge:(e,t="user")=>((e,t,n="user")=>Fi(e,e.selection.getIds(),t,n))(this,e,t),getChildIds:e=>this.shapeTreeIndex.getChildShapeIds(e),getChildren:e=>this.shapeTreeIndex.getChildShapes(e),getDescendantIds:e=>this.shapeTreeIndex.getDescendantShapeIds(e),getDescendantPageBounds:e=>((e,t)=>bn(e,e.layers.getDescendantIds(t)))(this,e),getSubtreePageBounds:e=>((e,t)=>bn(e,[t,...e.layers.getDescendantIds(t)]))(this,e),getPageId:e=>this.shapeTreeIndex.getPageIdForShape(e),isOrAncestorLocked:e=>((e,t)=>{const n=new Set;let i=e.shapes.get(t);for(;i;){if(i.isLocked)return!0;if(!i.parentId.startsWith("shape:"))return!1;const t=i.parentId;if(n.has(t))return!1;n.add(t),i=e.shapes.get(t)}return!1})(this,e),isOrAncestorInSet:(e,t)=>((e,t,n)=>{let i=e.shapes.get(t);const s=new Set;for(;i;){if(n.has(i.id))return!0;if(!i.parentId.startsWith("shape:"))return!1;const t=i.parentId;if(s.has(t))return!1;s.add(t),i=e.shapes.get(t)}return!1})(this,e,t),hasLockedDescendant:e=>((e,t)=>e.layers.getDescendantIds(t).some(t=>e.shapes.get(t)?.isLocked??!1))(this,e),getOutermostSelectableId:e=>((e,t)=>{let n=t,i=e.shapes.get(t);const s=new Set([t]);for(;i?.parentId.startsWith("shape:");){const t=i.parentId;if(s.has(t))break;s.add(t);const o=e.shapes.get(t);if(!o)break;e.shapes.getUtil(o).isSelectionTransformContainer(o)&&(n=o.id),i=o}return n})(this,e),includeDescendants:e=>Pn(this,e),getSelectionTransformIds:e=>xn(this,e),getSelectionRotationIds:e=>Cn(this,e),getExportTraversalIds:e=>((e,t)=>{const n=Pn(e,t).filter(t=>!e.shapes.isHidden(t)),i=new Set(n);for(const s of n)for(const t of e.bindings.getForShape(s)){const s=e.bindings.getUtil(t).getExportShapeIds?.(e,t);for(const t of s??[])for(const s of Pn(e,[t]))i.has(s)||e.shapes.isHidden(s)||(i.add(s),n.push(s))}return n})(this,e),getContainment:(e,t)=>fi(this,this.shapeGeometryQueries,e,t),getContainingParentId:e=>((e,t,n,i)=>mi({editor:e,shapeTree:t,geometry:n,shapeIds:i}))(this,this.shapeTreeIndex,this.shapeGeometryQueries,e),getContainingParentIdAtPoint:(e,t)=>((e,t,n,i,s)=>mi({editor:e,shapeTree:t,geometry:n,shapeIds:i,point:s}))(this,this.shapeTreeIndex,this.shapeGeometryQueries,e,t),getContainingParentIdForShape:e=>((e,t,n)=>{const i=(t=>{const n=new Set;let i=t;for(;i.startsWith("shape:");){const t=i;if(n.has(t))return null;n.add(t);const s=e.shapes.get(t);if(!s)return null;i=s.parentId}return e.pages.get(i)?i:null})(n.parentId);if(!i)return null;const s=Lt(e,n.parentId,t=>e.shapes.get(t));if(!s)return null;const o=ke(n,e.shapes.getUtil(n),s),r=new Map;for(const g of S(e).getAll().filter(p)){const e=r.get(g.parentId)??[];e.push(g),r.set(g.parentId,e)}for(const p of r.values())p.sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id));const a=[],d=new Set,c=e=>{for(const t of r.get(e)??[])d.has(t.id)||(d.add(t.id),a.push(t),c(t.id))};c(i);let l=null,h=1/0,u=-1;for(let p=0;p<a.length;p+=1){const t=a[p];if(!t||t.id===n.id||e.shapes.isHidden(t.id)||e.layers.isOrAncestorLocked(t.id))continue;const i=e.shapes.getUtil(t);if(!yi(t,i))continue;if(!e.layers.canReceiveChild(t.id,n.id))continue;const s=e.shapes.computePageBounds(t),r=i.getLocalBounds(t),d=e.shapes.computeLocalToPageTransform(t).tryInvert();d&&o.outlineVertices.length>0&&o.outlineVertices.every(e=>r.containsPoint(d.applyToPoint(e)))&&Si(s,p,l,h,u)&&(l=t,h=s.w*s.h,u=p)}return l?.id??i})(this,0,e),getIdsInContainerBounds:(e,t={})=>((e,t,n={})=>{const i=e.layers.getPageId(t),s=e.shapes.getPageBounds(t);return i&&s?e.shapes.getIdsInBounds(s,{pageId:i}).filter(i=>{if(i===t)return!1;const s=e.layers.getContainment(t,i);return"inside"===s||n.includeIntersecting&&"intersecting"===s}):[]})(this,e,t),canReceiveChildren:e=>((e,t)=>{if(t.startsWith("page:"))return!!e.pages.get(t);const n=e.shapes.get(t);return!!n&&!$e(n,e.shapes.getUtil(n))&&e.shapes.getUtil(n).canReceiveChildren(n)})(this,e),canReceiveChild:(e,t)=>((e,t,n)=>{if(t.startsWith("page:"))return!!e.pages.get(t);const i=e.shapes.get(t);if(!i)return!1;if($e(i,e.shapes.getUtil(i)))return!1;const s=e.shapes.get(n);return!!s&&i.id!==n&&!e.layers.getDescendantIds(n).includes(i.id)&&e.shapes.getUtil(i).canReceiveChild(i,s)})(this,e,t)};assets={get:e=>{const t=this.store.get(e);return f(t)?t:void 0},getAll:()=>this.store.getAll().filter(f).sort((e,t)=>e.id.localeCompare(t.id)),resolveUrl:e=>this.assetUrlResolver(e)};bindings={get:e=>{const t=this.store.get(e);return g(t)?t:void 0},getOwnedByShape:e=>this.bindingQueries.getBindingsOwnedByShape(e),getOwnedByShapeSignal:e=>this.bindingQueries.getBindingsOwnedByShapeSignal(e),getTargetingShape:e=>this.bindingQueries.getBindingsTargetingShape(e),getTargetingShapeSignal:e=>this.bindingQueries.getBindingsTargetingShapeSignal(e),getForShape:e=>this.bindingQueries.getBindingsForShape(e),getForShapeSignal:e=>this.bindingQueries.getBindingsForShapeSignal(e),getUtil:e=>this.bindingUtils.get(e.type),getSuppressedReactionIds:()=>this.bindingManager.getSuppressedReactionIds(),runWithSuppressedReactions:(e,t)=>this.bindingManager.runWithSuppressedReactions(e,t),getConflicting:e=>this.bindingManager.getConflictingBindings(e),canBind:e=>this.bindingManager.canBind(e),syncCreated:(e,t)=>this.bindingManager.syncCreatedBinding(e,t),syncUpdated:(e,t,n)=>this.bindingManager.syncUpdatedBinding(e,t,n),repairLoaded:e=>this.bindingManager.repairLoadedBindings(e),handleShapeChanges:(e,t)=>this.bindingManager.handleShapeChanges(e,t),getShapeCompanionRootId:e=>this.bindingManager.getShapeCompanionRootId(e),getShapeCompanionRootIds:(e,t)=>this.bindingManager.getShapeCompanionRootIds(e,t),getShapeCompanionMemberIds:e=>this.bindingManager.getShapeCompanionMemberIds(e),cleanupForDeletedShapes:(e,t)=>this.bindingManager.cleanupBindingsForDeletedShapes([...e],t),cleanup:(e,t)=>this.bindingManager.cleanupBindings(Array.from(e),t),setTerminalResolver:e=>this.interactionManager.setTerminalBindingResolver(e),resolveTerminal:e=>this.interactionManager.resolveTerminalBinding(e)};viewport={getCamera:(e=this.pages.getCurrentId())=>this.cameraManager.getCamera(e),pageToScreen:(e,t=this.pages.getCurrentId())=>this.cameraManager.pageToScreen(e,t),screenToPage:(e,t=this.pages.getCurrentId())=>this.cameraManager.screenToPage(e,t),setCamera:(e,t)=>this.cameraManager.setCamera(e,t),setLock:e=>this.cameraManager.setLock(e),pan:(e,t="system")=>this.cameraManager.panCamera(e,t),zoomAtScreenPoint:(e,t,n="system")=>this.cameraManager.zoomCameraAtScreenPoint(e,t,n),zoomToScreenPoint:(e,t,n="system")=>this.cameraManager.zoomCameraToScreenPoint(e,t,n),zoomAtCenter:(e,t="system")=>this.cameraManager.zoomAtViewportCenter(e,t),resetZoom:(e="user")=>this.cameraManager.resetZoom(e),setScreenSize:e=>this.cameraManager.setViewportScreenSize(e),stopCameraAnimation:()=>this.cameraManager.cancelAnimation(),getCurrentPageBounds:(e=this.pages.getCurrentId())=>En(this,e),centerOnShape:(e,t={})=>{const n=t.source??"user",i=this.layers.getPageId(e);if(!i)return!1;const s=this.layers.getSubtreePageBounds(e);if(!s)return!1;const o=this.state.viewportScreenSize.get();if(o.w<=0||o.h<=0)return!1;const r=this.viewport.getCamera(i),a=i===this.pages.getCurrentId();a||this.commands.setCurrentPageId(i,{source:n});const d={x:s.center.x-o.w/(2*r.z),y:s.center.y-o.h/(2*r.z),z:r.z};return a&&t.animation?this.cameraManager.animateCameraTo(d,{durationMs:t.animation.durationMs,pageId:i,source:n}):this.commands.setCamera({pageId:i,camera:d},{source:n}),!0},zoomToBounds:(e,t)=>An(this,e,t),zoomToFit:e=>((e,t)=>{const n=En(e);return!!n&&An(e,n,t)})(this,e),zoomToSelection:e=>((e,t)=>{const n=Rn(e,e.selection.getIds());return!!n&&An(e,n,t)})(this,e)};interaction={setBrushBox:e=>this.interactionManager.setBrushBox(e),setBindingPreview:e=>this.interactionManager.setBindingPreview(e),setTerminalBindingGuides:e=>this.interactionManager.setTerminalBindingGuides(e),setDropTargetShapeId:e=>this.interactionManager.setDropTargetShapeId(e),setHoveredShapeId:e=>this.interactionManager.setHoveredShapeId(e),setSelectionTranslationActive:e=>this.interactionManager.setSelectionTranslationActive(e),setSnapIndicators:e=>this.interactionManager.setSnapIndicators(e),clearSelection:()=>this.interactionManager.clearSelectionTransients(),cancelForCommand:()=>this.eventRouter.cancelInteraction("command"),cancel:(e,t={})=>this.eventRouter.cancelInteraction(e,t)};snapshots={getDocument:()=>(e=>{const t=e.store.getAll();return{schemaVersion:4,records:[t.find(h)??a(),...e.pages.getAll(),...t.filter(f).sort((e,t)=>e.id.localeCompare(t.id)),...t.filter(p).sort((e,t)=>e.parentId===t.parentId?e.index.localeCompare(t.index):e.parentId.localeCompare(t.parentId)),...t.filter(g).sort((e,t)=>e.id.localeCompare(t.id))]}})(this),getSession:()=>({schemaVersion:1,records:[this.state.session.get()]}),loadDocument:(e,t)=>((e,t,n)=>{e.assertDocumentWriteAllowed();const i=n?.source??"system",s=function(e,t,n){const i=rn(e,"document"),s=new Set,o=[];return i.records.forEach((e,i)=>{if(!Zt(e))throw new ma("Invalid document record: expected object");if("string"!=typeof e.id)throw new ma("Invalid document record id");if(s.has(e.id))throw new ma(`Duplicate document record id: ${e.id}`);if(s.add(e.id),"document"!==e.typeName)if("page"!==e.typeName)if("shape"!==e.typeName)if("binding"!==e.typeName){if("asset"!==e.typeName)throw new ma(`Unsupported document record type: ${String(e.typeName)}`);o.push((e=>{if("string"!=typeof e.id||!e.id.startsWith("asset:"))throw new ma("Invalid asset record id");if("string"!=typeof e.type)throw new ma("Invalid asset record type");return{id:e.id,typeName:"asset",scope:"document",type:e.type,props:Zt(e.props)?e.props:{},meta:nn(e.meta)}})(e))}else o.push(((e,t)=>{if("string"!=typeof e.id||!e.id.startsWith("binding:"))throw new ma("Invalid binding record id");if("string"!=typeof e.type)throw new ma("Invalid binding record type");if("string"!=typeof e.ownerId||!e.ownerId.startsWith("shape:"))throw new ma(`Invalid owner id for binding ${e.id}`);if(!Array.isArray(e.endpoints)||0===e.endpoints.length)throw new ma(`Invalid endpoints for binding ${e.id}`);const n=e.type,i=t.get(n),s=new Set,o=e.endpoints.map(t=>{if(!Zt(t)||"string"!=typeof t.slot||!t.slot)throw new ma(`Invalid endpoint slot for binding ${e.id}`);if(s.has(t.slot))throw new ma(`Duplicate endpoint slot for binding ${e.id}: ${t.slot}`);if(s.add(t.slot),"string"!=typeof t.targetId||!t.targetId.startsWith("shape:"))throw new ma(`Invalid endpoint target for binding ${e.id}`);return{slot:t.slot,targetId:t.targetId,props:i.validateEndpointProps(t.slot,t.props),meta:nn(t.meta)}});return o.sort((e,t)=>e.slot.localeCompare(t.slot)),{id:e.id,typeName:"binding",scope:"document",type:n,ownerId:e.ownerId,endpoints:o,meta:nn(e.meta)}})(e,n));else o.push(((e,t,n)=>{if("string"!=typeof e.id||!e.id.startsWith("shape:"))throw new ma("Invalid shape record id");if("string"!=typeof e.type)throw new ma("Invalid shape record type");if("string"!=typeof e.parentId||!e.parentId.startsWith("page:")&&!e.parentId.startsWith("shape:"))throw new ma(`Invalid parent id for shape ${e.id}`);return{id:e.id,typeName:"shape",scope:"document",parentId:e.parentId,index:Jt(e.index,String(n+1).padStart(6,"0")),x:en(e.x,0),y:en(e.y,0),rotation:en(e.rotation,0),scaleX:en(e.scaleX,1),scaleY:en(e.scaleY,1),opacity:Math.min(1,Math.max(0,en(e.opacity,1))),isHidden:tn(e.isHidden,!1),isLocked:tn(e.isLocked,!1),meta:nn(e.meta),type:e.type,subType:"string"==typeof e.subType?e.subType:null,props:t.get(e.type).validateProps(e.props)}})(e,t,i));else o.push(((e,t)=>{if("string"!=typeof e.id||!e.id.startsWith("page:"))throw new ma("Invalid page record id");return{id:e.id,typeName:"page",scope:"document",name:Jt(e.name,`Page ${t+1}`),index:Jt(e.index,String(t+1).padStart(4,"0")),meta:nn(e.meta)}})(e,i));else o.push((e=>{if("document:main"!==e.id)throw new ma("Invalid document metadata record id");return{id:Ar,typeName:"document",scope:"document",meta:nn(e.meta)}})(e))}),{schemaVersion:4,records:an(o,t,n)}}(t,e.shapeUtils,e.bindingUtils);e.interaction.cancel("restore"),e.editing.end({runEditEnd:!1,source:i}),e.editing.cancelOperation();const o=e.state.session.get();hn(e,[...s.records,o],i),ln(e),e.history.clear(),e.bindings.repairLoaded(i)})(this,e,t),loadSession:(e,t)=>cn(this,e,t),syncAfterDocumentRestore:()=>ln(this)};exports={getSvgString:(e=this.selection.getIds(),t)=>function(e,t,n,i={}){const s=Array.from(t),o=e.layers.getExportTraversalIds(s),r=new Set(o),a=[],d=[];for(const b of o){const t=e.shapes.get(b);t?d.push(t):a.push({id:b,reason:"missing-shape"})}if(0===d.length)return null;const c=[];for(const b of d){if(!e.shapes.getUtil(b).contributesToExportBounds(b))continue;const t=$(e,b,r);t&&(M(t)?c.push(t):a.push({id:b.id,reason:"missing-bounds"}))}if(0===c.length)return null;const l=j(c).expand(i.padding??16),h=[],p={editor:e,bounds:l,addDef(e){const t=`land-svg-def-${h.length+1}`;return h.push({...e,attrs:{...e.attrs,id:t}}),t},resolveAssetUrl:t=>e.assets.resolveUrl(t),resolveColor:e=>z(e,i.resolveThemeColor)},u=[],g=[],f=new Map,m=[],S=(t,n)=>{const i=e.shapes.computeExportToPageTransform(t),s=((e,t)=>{let n=t.opacity,i=t.parentId;const s=new Set([t.id]);for(;i.startsWith("shape:");){const t=i;if(s.has(t))break;s.add(t);const o=e.shapes.get(t);if(!o)break;n*=o.opacity,i=o.parentId}return n})(e,t),o=((e,t,n,i,s)=>{const o=[];for(const r of U(e,t,n)){const t=H(e,r,i,s);t&&o.push(t)}return o})(e,t,r,f,p);let a={tag:"g",attrs:{transform:i.toSvgString(),opacity:1===s?void 0:s},children:[n]};for(let e=o.length-1;e>=0;e-=1)a={tag:"g",attrs:{"clip-path":`url(#${o[e]})`},children:[a]};g.push(a)},y=e=>{const t=[],i=n.get(e.type)?.toSvgForeground?.(e,p);i&&t.push(i),t.length>0&&S(e,{tag:"g",children:t})};for(const b of d){for(;m.length>0&&!_(e,m[m.length-1].id,b);)y(m.pop());const t=n.get(b.type);if(!t){a.push({id:b.id,reason:"missing-exporter"});continue}const i=t.toSvg(b,p);if(!i){a.push({id:b.id,reason:"empty-output"});continue}if(!M(N(e,b))){a.push({id:b.id,reason:"missing-bounds"});continue}const s=[],o=[];for(const n of e.shapeSvgDecorations.get(b.subType)){const e=n.toSvgBackground?.(b,p);e&&s.push(e);const t=n.toSvg?.(b,p);t&&o.push(t)}const r=0===s.length&&0===o.length?i:{tag:"g",children:[...s,i,...o]};u.push(b.id),S(b,r),t.toSvgForeground&&m.push(b)}for(;m.length>0;)y(m.pop());if(0===u.length)return null;const I=Math.max(1,l.w),w=Math.max(1,l.h),P=[];return h.length>0&&P.push({tag:"defs",children:h}),i.background&&P.push({tag:"rect",attrs:{x:l.x,y:l.y,width:l.w,height:l.h,fill:i.background}}),P.push(...g),{svg:V({tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",width:I,height:w,viewBox:`${Z(l.x)} ${Z(l.y)} ${Z(I)} ${Z(w)}`},children:P}),bounds:l,width:I,height:w,requestedShapeIds:s,exportedShapeIds:u,skippedShapes:a}}(this,e,this.shapeSvgExporters,t),getIntegrityReport:(e=this.selection.getIds())=>x({editor:this,exporters:this.shapeSvgExporters,shapeIds:e}),repairIntegrity:(e=this.selection.getIds())=>(({editor:e,exporters:t,shapeIds:n})=>{const i=Array.from(n),s=x({editor:e,exporters:t,shapeIds:i});s.repairableIssueCount>0&&e.bindings.repairLoaded("system");const o=x({editor:e,exporters:t,shapeIds:i});return{before:s,after:o,repaired:s.issues.length!==o.issues.length}})({editor:this,exporters:this.shapeSvgExporters,shapeIds:e})};constructor(e={}){const{computed:t}=this.signals;this.inputs=new oa(this.signals),this._shapeDefaultPropsByTypeSignal=this.signals.atom("editor.shapeDefaultPropsByType",new Map),this._readonlySignal=this.signals.atom("editor.readonly",!1),e.resolveAssetUrl&&(this.assetUrlResolver=e.resolveAssetUrl);for(const a of e.shapeUtils??[])this.shapeUtils.register(a);for(const a of e.shapeSvgExporters??[])this.shapeSvgExporters.register(a);for(const a of e.shapeSvgDecorations??[])this.shapeSvgDecorations.register(a);for(const a of e.shapeHitTestDecorations??[])this.shapeHitTestDecorations.register(a);for(const a of e.bindingUtils??[])this.bindingUtils.register(a);const n=new Er(((e={})=>[a(e),d(),c()])(e.documentMeta??{}),{signals:this.signals,writeGuard:e=>this.assertStoreChangeAllowed(e)});((e,t)=>{e[Xr]=t})(this,n),this.store=n,this.tools=new jr(this),this.cameraManager=new ka(this,e.cameraAnimationScheduler),this.editing=new Pa(this),this.interactionManager=new Ba(this);const i=t("editor.session",()=>{const e=n.getRecordSignal(Kr).get();if(!u(e))throw new Error("Missing session record");return e}),s=t("editor.currentPageId",()=>i.get().currentPageId),o=t("editor.toolState",()=>{const e=i.get();return{activeToolId:e.activeToolId,isToolLocked:e.isToolLocked}}),r=t("editor.editingShapeId",()=>i.get().editingShapeId),l=t("editor.shapeEditingSession",()=>i.get().shapeEditingSession),h=t("editor.shapeEditingState",()=>({editingShapeId:r.get(),session:l.get()})),p=t("editor.currentCamera",()=>i.get().pageCameraById[s.get()]??Yr),g=t("editor.selectedShapeIds",()=>{const e=i.get();return e.pageSelectedShapeIdsById[e.currentPageId]??[]},{isEqual:J}),f=t("editor.selectionCount",()=>g.get().length),m=t("editor.selectedShapeIdSet",()=>new Set(g.get()),{isEqual:ee}),S=t("editor.pageTransform",()=>{const e=p.get();return Wr.Scale(e.z,e.z).compose(Wr.Translate(-e.x,-e.y))}),y=t("editor.cameraZoom",()=>p.get().z),I=t("editor.viewportPageBounds",()=>{const{w:e,h:t}=this.cameraManager.viewportScreenSizeSignal.get();if(e<=0||t<=0)return null;const n=p.get();return new zr(n.x,n.y,e/n.z,t/n.z)});(e=>{const t=new Zr(e);Qr.set(e,t)})(this),this.shapeSignals=new va(this),this.shapeGeometryQueries=new pa(this),this.shapeTreeIndex=new ua(this,s),this.bindingQueries=new ha(this),this.bindingManager=new Dr(this),this.spatialIndex=new fa(this,this.shapeTreeIndex,this.shapeGeometryQueries),this.snaps=new Ta(this,e.snapDiagnostics),this.selectionGeometry=((e,t,n)=>{const i=e.signals.computed("editor.query.selectionGeometry",()=>wn(e,t,n),{isEqual:Sn}),s=e.signals.computed("editor.query.selectionPageOutlineVertices",()=>i.get().outlineVertices,{isEqual:ne}),o=e.signals.computed("editor.query.selectionPageBounds",()=>i.get().pageBounds,{isEqual:se}),r=e.signals.computed("editor.query.selectionLocalBounds",()=>i.get().localBounds,{isEqual:se}),a=e.signals.computed("editor.query.selectionRotation",()=>i.get().rotation);return{geometry:i,pageOutlineVertices:s,pageBounds:o,localBounds:r,hasRotation:e.signals.computed("editor.query.selectionHasRotation",()=>i.get().hasRotation),rotation:a,rotationCenter:e.signals.computed("editor.query.selectionRotationCenter",()=>i.get().rotationCenter,{isEqual:te}),hasCompatibleRotation:e.signals.computed("editor.query.selectionHasCompatibleRotation",()=>i.get().hasCompatibleRotation),selectionAnchorPagePoint:e.signals.computed("editor.query.selectionAnchorPagePoint",()=>i.get().selectionAnchorPagePoint,{isEqual:te})}})(this,g,e=>this.shapeGeometryQueries.getCachedShapeGeometry(e));const w=t("editor.selectedShapes",()=>g.get().map(e=>this.shapes.getSignal(e).get()).filter(e=>!!e)),P=t("editor.selectionCanFlip",()=>Mn(this,g.get())),b=t("editor.selectionState",()=>{const e=g.get(),t=1===e.length?this.shapes.getSignal(e[0]).get()??null:null,n=w.get(),i=(e=>{let t=null;for(const n of e)if(null===t)t=n.type;else if(t!==n.type)return null;return t})(n),s=1===n.length,o=n.map(e=>this.shapes.getUtil(e).getSelectionHandleAnchors(e,{isOnlySelected:s,editor:this})).some(e=>e.terminalHandleAnchors.length>0||e.middleHandleAnchors.length>0||(e.customHandleAnchors?.length??0)>0),r=n.some(e=>this.shapes.getUtil(e).contributesToSelectionFrame(e,{editor:this})),a=o&&r,d=t?this.shapes.getUtil(t).getSelectionHandleAnchors(t,{isOnlySelected:s,editor:this}):null,c=1===e.length&&!!d&&(d.terminalHandleAnchors.length>0||(d.customHandleAnchors?.length??0)>0),l=this.selectionGeometry.hasRotation.get();return{count:e.length,singleShapeType:t?.type??null,commonShapeType:i,canFlipSelection:P.get(),hasPointHandleSelection:o,hasFrameSelection:r,isMixedFrameAndPointHandleSelection:a,canDragPointHandles:c,hasSelectionRotation:l,hasMixedSelectionRotation:!this.selectionGeometry.hasCompatibleRotation.get(),canResetSelectionRotation:l&&r,localBounds:this.selectionGeometry.localBounds.get(),frameRotation:this.selectionGeometry.rotation.get(),frameRotationCenter:this.selectionGeometry.rotationCenter.get(),selectionAnchorPagePoint:this.selectionGeometry.selectionAnchorPagePoint.get()}}),v=t("editor.selectionMetadata",()=>{const e=b.get();return{count:e.count,singleShapeType:e.singleShapeType,commonShapeType:e.commonShapeType,canFlipSelection:e.canFlipSelection,hasPointHandleSelection:e.hasPointHandleSelection,hasFrameSelection:e.hasFrameSelection,isMixedFrameAndPointHandleSelection:e.isMixedFrameAndPointHandleSelection,canDragPointHandles:e.canDragPointHandles,hasSelectionRotation:e.hasSelectionRotation,hasMixedSelectionRotation:e.hasMixedSelectionRotation,canResetSelectionRotation:e.canResetSelectionRotation}},{isEqual:Rs}),x=t("editor.renderViewportPageBounds",e=>{const t=I.get();return t?e!==xr&&e&&(i=t).minX>=(n=e).minX&&i.maxX<=n.maxX&&i.minY>=n.minY&&i.maxY<=n.maxY?e:t.expand(160/y.get()):null;var n,i},{isEqual:se});this.renderWindowManager=new Ea(this,{currentPageId:s,currentPageShapeIds:this.shapeTreeIndex.currentPageShapeIdsSignal,selectedShapeIds:g,selectedShapeIdSet:m,viewportPageBounds:I,renderViewportPageBounds:x}),this.selectionOverlay=new wa(this,{tool:o,selectedShapeIds:g,selectedShapes:w,cameraZoom:y}),this.operations=new ca(this,e.onUnhandledError),this.history=new aa(this),this.state=Object.freeze({readonly:this._readonlySignal,session:i,pages:this.shapeTreeIndex.pagesSignal,currentPageId:s,currentPageShapeIds:this.shapeTreeIndex.currentPageShapeIdsSignal,currentPageShapes:this.shapeTreeIndex.currentPageShapesSignal,currentPageShapeTree:this.shapeTreeIndex.currentPageShapeTreeSignal,tool:o,editingShapeId:r,shapeEditingSession:l,shapeEditing:h,shapeEditingEntryRequest:this.editing.entryRequestSignal,selectedShapeIds:g,selectedShapeIdSet:m,selectedShapes:w,selectionCount:f,selection:b,selectionMetadata:v,selectionPageBounds:this.selectionGeometry.pageBounds,selectionLocalBounds:this.selectionGeometry.localBounds,selectionAnchorPagePoint:this.selectionGeometry.selectionAnchorPagePoint,camera:p,cameraLock:this.cameraManager.cameraLockSignal,cameraZoom:y,pageTransform:S,viewportScreenSize:this.cameraManager.viewportScreenSizeSignal,viewportPageBounds:I,history:this.history.state}),this.render=Object.freeze({viewport:Object.freeze({pageBounds:x,items:this.renderWindowManager.renderItemsSignal,shapeOrderById:this.renderWindowManager.shapeRenderOrderByIdSignal,culledShapeIds:this.renderWindowManager.culledShapeIdsSignal,culledShapeIdSet:this.renderWindowManager.culledShapeIdSetSignal,selectedShapeIdsOutsideCulled:this.renderWindowManager.selectedShapeIdsOutsideCulledSignal,selectedShapeIdsOutsideCulledSet:this.renderWindowManager.selectedShapeIdsOutsideCulledSetSignal,visibleShapeIds:this.renderWindowManager.renderVisibleShapeIdsSignal,visibleShapeIdSet:this.renderWindowManager.renderVisibleShapeIdSetSignal,retainedShapeIds:this.renderWindowManager.retainedShapeIdsSignal}),overlay:Object.freeze({selectedShapeItems:this.selectionOverlay.selectedShapeItemsSignal,frameGeometry:this.selectionOverlay.frameGeometrySignal,companionFrameGeometries:this.selectionOverlay.companionFrameGeometriesSignal,path:this.selectionOverlay.pathSignal,pageClipPath:this.selectionOverlay.pageClipPathSignal,bindingSegments:this.selectionOverlay.bindingSegmentsSignal,frameStyle:this.selectionOverlay.frameStyleSignal,handleAnchors:this.selectionOverlay.handleAnchorsSignal,handles:this.selectionOverlay.handlesSignal}),interaction:Object.freeze({brushBox:this.interactionManager.brushBoxSignal,brushBoxActive:this.interactionManager.brushBoxActiveSignal,bindingPreview:this.interactionManager.bindingPreviewSignal,bindingPreviewActive:this.interactionManager.bindingPreviewActiveSignal,terminalBindingGuides:this.interactionManager.terminalBindingGuidesSignal,dropTargetShapeId:this.interactionManager.dropTargetShapeIdSignal,hoveredShapeId:this.interactionManager.hoveredShapeIdSignal,selectionTranslationActive:this.interactionManager.selectionTranslationActiveSignal,snapIndicators:this.snaps.indicatorsSignal,snapIndicatorsActive:this.snaps.activeSignal})}),this.commands=st(this),this.eventRouter=new sa(this),this.bindings.repairLoaded("system"),this.registerBuiltInInteractions()}closeWrites(){this.writesClosed=!0}assertDocumentWriteAllowed(){if(this.writesClosed)throw new Error("Disposed editor rejected store write.");if(this._readonlySignal.get())throw new Error("Readonly canvas rejected document write.")}assertStoreChangeAllowed(e){if(this.writesClosed)throw new Error("Disposed editor rejected store write.");(e.diff.added.some(m)||e.diff.removed.some(m)||e.diff.updated.some(({before:e,after:t})=>m(e)||m(t)))&&this.assertDocumentWriteAllowed()}registerBuiltInInteractions(){this.interactions.register(function(){let e=!1,t=null;const n=()=>{t=null};return{id:"land.camera.canvas-navigation",enabledInReadonly:!0,editorEvent:{handleEvent(i,s){if("cancel"===s.type)return"blur"!==s.reason&&"dispose"!==s.reason||(e=!1),void n();if("wheel"===s.type)return((e,t)=>{if(t.ctrlKey){const n=e.state.camera.get(),i=t.delta.y,s=(Math.abs(i)>10?10*Math.sign(i):i)/100;return void e.viewport.zoomToScreenPoint(t.screenPoint,n.z-1*s*n.z)}e.state.cameraLock.get()||e.viewport.pan(t.delta)})(i,s),ea;if("keyboard"===s.type&&(e=>"Space"===e.code)(s)){if("key_up"===s.name){const t=e;return e=!1,t?ea:void 0}if(i.state.shapeEditingSession.get())return;return e=!0,ea}if("tick"===s.type&&t){const e=i.inputs.state.get();return e.pointerId===t.pointerId&&e.currentScreenPoint&&at(i,t.camera,e.currentScreenPoint),ea}if("pointer"===s.type&&"mouse"===s.pointerType){if("pointer_down"===s.name){n();const o=((e,{allowLeftButton:t})=>1===e.button?4:t&&0===e.button?1:null)(s,{allowLeftButton:i.inputs.isSpacePressed.get()&&!i.state.shapeEditingSession.get()});if(null===o)return;return i.state.cameraLock.get()||(0===s.button&&(e=!0),t={pointerId:s.pointerId,buttons:o,camera:rt(i,s.screenPoint)}),ta}if(t&&s.pointerId===t.pointerId)return"pointer_move"===s.name?(0===(s.buttons&t.buttons)&&n(),ea):"pointer_up"===s.name?(at(i,t.camera,s.screenPoint),n(),ea):"pointer_cancel"===s.name?(n(),ea):void 0}}}}}())}handleEvent(e){return this.eventRouter.handle(e)}listen(e){return this.store.listen(t=>e(t))}dispose(){this.closeWrites();let e=null;for(const n of[()=>this.cameraManager.dispose(),()=>this.bindingQueries.dispose(),()=>this.shapeTreeIndex.dispose(),()=>this.shapeGeometryQueries.dispose(),()=>this.shapeSignals.dispose(),()=>this.runtime.dispose(),()=>this.history.dispose()])try{n()}catch(t){e??=t}if(null!==e)throw e}},Ra=class{editor;id;parent;children=new Map;currentChild=null;initial=null;constructor(e,t,n){this.editor=e,this.id=t,this.parent=n}addChild(e){this.children.set(e.id,e)}enter(e){if(this.onEnter(e),!this.initial)return;const t=this.children.get(this.initial);if(!t)throw new Error(`Missing child state "${this.initial}" on "${this.id}"`);this.currentChild=t,t.enter(e)}exit(e){this.currentChild&&(this.currentChild.exit(e),this.currentChild=null),this.onExit(e)}transition(e,t){if(!this.parent){const n=this.children.get(e);if(!n)throw new Error(`Missing root child state "${e}" on tool "${this.id}"`);if(this.currentChild===n)return;return this.currentChild?.exit(t),this.currentChild=n,void n.enter(t)}this.parent.transition(e,t)}isInInitialState(){return!this.currentChild||!!this.initial&&this.currentChild.id===this.initial&&this.currentChild.isInInitialState()}dispatch(e,t){if(this.currentChild)return this.currentChild.dispatch(e,t);switch(e.type){case"pointer":return this.handlePointerEvent(e,t);case"keyboard":return this.handleKeyboardEvent(e,t);case"wheel":return this.onWheel(e,t);case"tick":return this.onTick(e,t);case"cancel":return this.onCancel(e,t)}}onEnter(e){}onExit(e){}onPointerDown(e,t){}onPointerMove(e,t){}onPointerUp(e,t){}onCancel(e,t){}onKeyDown(e,t){}onKeyUp(e,t){}onWheel(e,t){}onTick(e,t){}handlePointerEvent(e,t){switch(e.name){case"pointer_down":return this.onPointerDown(e,t);case"pointer_move":return this.onPointerMove(e,t);case"pointer_up":return this.onPointerUp(e,t);case"pointer_cancel":return this.onCancel({type:"cancel",reason:"pointer_cancel"},t)}}handleKeyboardEvent(e,t){return"key_down"===e.name?this.onKeyDown(e,t):this.onKeyUp(e,t)}},Ka=class extends Ra{constructor(e){super(e,"hand"),this.initial="idle",this.addChild(new Ya(e,this)),this.addChild(new Xa(e,this))}},Ya=class extends Ra{constructor(e,t){super(e,"idle",t)}onPointerDown(e){0===e.button&&this.transition("panning",rt(this.editor,e.screenPoint))}},Xa=class extends Ra{info=null;constructor(e,t){super(e,"panning",t)}onEnter(e){this.info=e}onTick(e){if(!this.info)return;const t=this.editor.inputs.state.get().currentScreenPoint;t&&at(this.editor,this.info,t)}onPointerUp(e){this.info&&at(this.editor,this.info,e.screenPoint),this.transition("idle")}onCancel(){this.transition("idle")}onExit(){this.info=null}},Fa=Math.PI/180*15,Da=Math.PI/2,Oa=Math.PI/180*5,La=class extends Ra{info=null;onEnter(e){this.info=e,this.onInfoEnter()}onExit(){this.onInfoExit(),this.info=null}onInfoEnter(){}onInfoExit(){}},za=class extends La{onPointerMove(e){if(!this.info)return;const t=this.editor.inputs.state.get().originScreenPoint;t&&((e,t)=>e.dist2(t)>=9)(t,e.screenPoint)&&this.onDragThresholdExceeded(e)}},_a=class extends La{operation=null;onInfoEnter(){if(this.info){const e=this.getOperationKind(this.info);this.operation=this.editor.operations.begin({kind:e,label:e,source:"user",history:"record"})}this.onDragStart()}onDragStart(){}onTick(e){if(!this.info)return;const t=qs(this.editor,e,"always_apply");t&&this.apply(t)}onKeyDown(){this.applyFromInputs()}onKeyUp(){this.applyFromInputs()}applyFromInputs(){Gs(this.editor,e=>this.apply(e))}commitOperation(){const e=this.operation;this.operation=null,e?.commit()}cancelOperation(){const e=this.operation;this.operation=null,e?.cancel()}},$a=class extends La{constructor(e,t){super(e,"brushing",t)}onInfoEnter(){if(!this.info)return;const e=this.editor.inputs.state.get();this.updateBrush(this.info.originPagePoint,this.info.additiveSelection,Zs(e))}onPointerMove(e){this.info&&this.updateBrush(e.pagePoint,Qs(e),Zs(e))}onTick(e){if(!this.info)return;const t=qs(this.editor,e,"apply_after_scroll_or_without_screen_point");t&&this.updateBrush(t.pagePoint,Qs(t),Zs(t))}onKeyDown(){this.updateBrushFromInputs()}onKeyUp(){this.updateBrushFromInputs()}onPointerUp(e){this.info&&this.updateBrush(e.pagePoint,Qs(e),Zs(e)),this.complete()}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}updateBrush(e,t,n){if(!this.info)return;const i=((e,t)=>{const n=Math.min(e.x,t.x),i=Math.min(e.y,t.y),s=Math.max(e.x,t.x),o=Math.max(e.y,t.y);return new zr(n,i,s-n,o-i)})(this.info.originPagePoint,e),s=((e,t)=>{const n=[],i=new Set;for(const s of t){const t=e.shapes.get(s);if(!t)continue;const o=e.shapes.getUtil(t).getSelectionTargetId(t,{editor:e}),r=e.layers.getOutermostSelectableId(o);i.has(r)||(i.add(r),n.push(r))}return n})(this.editor,this.editor.shapes.getIdsInBounds(i).filter(e=>((e,t,n,i)=>{const s=e.shapes.get(n);return!(!s||!((e,t)=>{const n=e.shapes.get(t);return!!n&&e.shapes.getUtil(n).canBeDirectlyBrushSelected(n)})(e,s.id))&&e.shapes.getUtil(s).canSelectByBrush(s,{editor:e,brushBounds:t,isWrapping:i,pageOutlineVertices:e.shapes.getPageOutlineVertices(s.id),pageBounds:e.shapes.getPageBounds(s.id)})})(this.editor,i,e,n))),o=t?((e,t)=>{const n=new Set(e);for(const i of t)n.has(i)?n.delete(i):n.add(i);return Array.from(n)})(this.info.previousSelection,s):s;this.editor.interaction.setBrushBox(i),this.editor.commands.setSelectedShapeIds(o,{source:"system"})}updateBrushFromInputs(){Gs(this.editor,e=>this.updateBrush(e.pagePoint,Qs(e),Zs(e)))}complete(){this.transition("idle")}cancel(){this.transition("idle")}},Na=class extends _a{constructor(e,t){super(e,"dragging_plugin_interaction",t)}getOperationKind(e){return e.session.operationKind}onDragStart(){this.info?.session.onDragStart?.({editor:this.editor})}onPointerUp(e){this.apply(e),this.complete()}onCancel(e){const t=this.info?.previousSelection;this.editor.signals.transact(()=>{t&&!J(t,this.editor.selection.getIds())&&this.editor.commands.setSelectedShapeIds(t,{source:"system"}),this.info&&(this.editor.interaction.clearSelection(),this.cancelOperation())}),this.info?.session.onCancel?.({editor:this.editor,reason:e.reason}),this.transition("idle")}onInfoExit(){this.info?.session.shouldClearBindingPreviewOnExit&&this.editor.interaction.setBindingPreview(null),this.editor.interaction.setSnapIndicators(null)}apply({pagePoint:e,shiftKey:t,altKey:n,accelKey:i}){if(!this.info)return;if(e.x===this.info.lastPagePointX&&e.y===this.info.lastPagePointY&&t===this.info.lastShiftKey&&n===this.info.lastAltKey&&i===this.info.lastAccelKey)return;this.info.lastPagePointX=e.x,this.info.lastPagePointY=e.y,this.info.lastShiftKey=t,this.info.lastAltKey=n,this.info.lastAccelKey=i;const s=this.info.snapMode,o=this.info.snapSnapshot,r=!i&&"none"!==s&&null!==o,a=r&&o?this.editor.snaps.snapHandle({mode:s,pagePoint:e,snapshot:o,threshold:8/this.editor.state.camera.get().z}):null;r||this.editor.snaps.clearIndicators();const d=a?.snappedPagePoint??e,c=this.info.session.update({editor:this.editor,pagePoint:d,accelKey:i,source:"user"}),l="string"==typeof c?c:c.status,h="string"==typeof c?d:c.finalPagePoint;!a||!h||h.dist2(a.snappedPagePoint)<=1e-6||this.editor.snaps.clearIndicators(),"stop"===l&&this.complete()}complete(){const e=this.info;e&&(this.editor.interaction.setSnapIndicators(null),e.session.onComplete?.({editor:this.editor}),this.commitOperation(),this.transition("idle"))}},Ua=class extends Ra{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.interaction.clearSelection()}onPointerDown(e){const t=this.editor.selection.getIds(),n=this.editor.state.readonly.get()?null:this.editor.selection.hitTestHandle(e.pagePoint);if("rotate"===n?.kind)return void this.transition("pointing_rotate_handle",{originPagePoint:e.pagePoint.clone(),previousSelection:t});if("resize"===n?.kind)return void this.transition("pointing_resize_handle",{handleId:n.id,originPagePoint:e.pagePoint.clone(),cursorHandleOffset:e.pagePoint.sub(n.point),previousSelection:t});let i=null;if(n){const s=this.editor.state.selectedShapes.get()[0]??null;if(s){const o=this.editor.interactions.createSelectionHandleSession(this.editor,{handle:n,shape:s,originPagePoint:e.pagePoint.clone()});if(o){const s=o.handleSnapMode??"none";i={originPagePoint:e.pagePoint.clone(),previousSelection:t,session:o,snapSnapshot:"none"===s?null:this.editor.snaps.createHandleSnapshot({context:o.handleSnapContext??{shapeId:o.shapeId,handle:n},currentPagePoint:e.pagePoint,allowSelfSnap:o.allowSelfSnap??!1,excludedShapeIds:o.excludedSnapShapeIds})}}}}const s=this.editor.shapes.hitTest(e.pagePoint);let o=null;if(s){const n=this.editor.shapes.getUtil(s).getSelectionTargetId(s,{editor:this.editor}),i=this.editor.shapes.getUtil(s).getTranslateTargetId(s,{editor:this.editor}),r=Qs(e),a=Vs(this.editor,n,t),d=r?null:((e,t,n)=>{const i=new Set(n);for(const s of js(e,t))if(i.has(s.ancestorId))return s.ancestorId;return null})(this.editor,n,t),c=r?null:d?a:null,l=Vs(this.editor,i,t),h=null===c?l:d??l,p=this.editor.state.readonly.get()?null:this.editor.interactions.createShapePointerSession(this.editor,{shape:s,selectionTargetId:a,originPagePoint:e.pagePoint.clone(),event:e});o={shapeId:a,translateTargetId:h,originPagePoint:e.pagePoint.clone(),originTimestamp:e.timestamp,previousSelection:t,additiveSelection:r,wasSelected:t.includes(a),fromSelectionBounds:!1,quickClickSelectionTargetId:c,dragSession:p}}if(!i||"binding_middle"!==n?.kind&&"custom"!==n?.kind)if(o?.dragSession)this.transition("pointing_shape",o);else if(i)this.transition("pointing_selection_handle_interaction",i);else if(o)this.transition("pointing_shape",o);else{if(!this.editor.state.readonly.get()&&!Qs(e)&&t.length>0){const n=this.editor.state.selectedShapes.get()[0];if(n&&this.editor.shapes.getUtil(n).canStartTranslateFromSelectionBounds(n,{editor:this.editor})&&this.editor.selection.containsPoint(e.pagePoint))return void this.transition("pointing_shape",{shapeId:n.id,translateTargetId:n.id,originPagePoint:e.pagePoint.clone(),originTimestamp:e.timestamp,previousSelection:t,additiveSelection:!1,wasSelected:!0,fromSelectionBounds:!0,quickClickSelectionTargetId:null,dragSession:null})}this.transition("pointing_canvas",{originPagePoint:e.pagePoint.clone(),previousSelection:t,additiveSelection:Qs(e)})}else this.transition("pointing_selection_handle_interaction",i)}},Ha=class extends za{constructor(e,t){super(e,"pointing_canvas",t)}onDragThresholdExceeded(e){this.info&&this.transition("brushing",{...this.info,additiveSelection:Qs(e)})}onPointerUp(e){Qs(e)||this.editor.commands.setSelectedShapeIds([],{source:"system"}),this.transition("idle")}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.transition("idle")}},Wa=class extends za{constructor(e,t){super(e,"pointing_resize_handle",t)}onDragThresholdExceeded(){if(!this.info)return;const e=this.editor.selection.getFrame();if(!e)return void this.transition("idle");if(!this.editor.selection.canResize())return void this.transition("idle");const t=this.editor.selection.getResizeTargets(),n=new Map(t.flatMap(e=>{const t=fn(this.editor,e);return t?[[e.id,t]]:[]})),i=t.filter(e=>n.has(e.id));if(0===i.length)return void this.transition("idle");const s=((e,t,n,i)=>0===t.length?[]:Vn(e,t,n,Gn(e,t,i)))(this.editor,i,this.info.handleId,e.rotation);if(0===s.length)return void this.transition("idle");const o=(({shapes:e,selectionFrame:t,getShapeSelectionResizePageOutlineVertices:n,getShapeSelectionPagePoints:i,getShapeSelectionPageMiddlePoint:s,getShapePageRecord:o})=>{const r={rotation:t.rotation,rotationCenter:t.rotationCenter},a=[],d=[];for(const c of e){const e=o(c),t=i(e);t?d.push({shape:c,pageShape:e,startLocalPagePoint:_n(t[0],r),endLocalPagePoint:_n(t[1],r),middleLocalPagePoint:(()=>{const t=s(e);return t?_n(t,r):null})()}):a.push({shape:c,pageShape:e,localBounds:zr.FromPoints(n(c).map(e=>_n(e,r))),rotation:e.rotation})}return{startBounds:t.bounds.clone(),rotation:t.rotation,rotationCenter:t.rotationCenter.clone(),aspectRatio:0===t.bounds.h?1:t.bounds.w/t.bounds.h,shapes:a,pointShapes:d}})({shapes:i,selectionFrame:e,getShapeSelectionResizePageOutlineVertices:e=>function(e,t){const n=e.shapes.getUtil(t).getSelectionResizeLocalBounds(t),i=e.shapes.computeLocalToPageTransform(t);return(e=>[new Lr(e.minX,e.minY),new Lr(e.maxX,e.minY),new Lr(e.maxX,e.maxY),new Lr(e.minX,e.maxY)])(n).map(e=>i.applyToPoint(e))}(this.editor,e),getShapeSelectionPagePoints:e=>this.editor.shapes.getUtil(e).getSelectionPagePoints(e),getShapeSelectionPageMiddlePoint:e=>this.editor.shapes.getUtil(e).getSelectionPageMiddlePoint(e),getShapePageRecord:e=>n.get(e.id)});var r,a;this.transition("resizing",{...this.info,startBounds:o.startBounds,rotation:o.rotation,rotationCenter:o.rotationCenter,aspectRatio:o.aspectRatio,snapSnapshot:this.editor.snaps.createResizeSnapshot({resizingShapeIds:this.editor.layers.getSelectionTransformIds(this.editor.selection.getIds()),coordinateSpace:{rotation:o.rotation,rotationCenter:o.rotationCenter}}),shapes:o.shapes,pointShapes:o.pointShapes,updates:(r=o.shapes,a=o.pointShapes,[...r.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY})),...a.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY}))]),allowedResizeModes:s,lastPagePointX:NaN,lastPagePointY:NaN,lastShiftKey:!1,lastAltKey:!1,lastAccelKey:!1})}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}},qa=class extends za{constructor(e,t){super(e,"pointing_rotate_handle",t)}onDragThresholdExceeded(){if(!this.info)return;const e=this.editor.selection.getFrame();if(!e)return void this.transition("idle");if(!this.editor.selection.canRotate())return void this.transition("idle");const t=new Map(this.editor.selection.getRotationTargets().flatMap(e=>{const t=fn(this.editor,e);return t?[[e.id,t]]:[]})),n=this.editor.selection.getRotationTargets().filter(e=>t.has(e.id));if(0===n.length)return void this.transition("idle");const i=(({shapes:e,selectionFrame:t,getShapeLocalBounds:n,getShapeSelectionPagePoints:i,getShapeSelectionPageMiddlePoint:s,getShapePageRecord:o})=>{const r=[],a=[];for(const d of e){const e=o(d),t=i(e);t?a.push({shape:d,pageShape:e,startPagePoint:t[0],endPagePoint:t[1],middlePagePoint:s(e)}):r.push({shape:d,pageShape:e,localBounds:n(d),rotation:e.rotation})}return{center:t.rotationCenter.clone(),initialSelectionRotation:t.rotation,shapes:r,pointShapes:a}})({shapes:n,selectionFrame:e,getShapeLocalBounds:e=>this.editor.shapes.computeLocalBounds(e),getShapeSelectionPagePoints:e=>this.editor.shapes.getUtil(e).getSelectionPagePoints(e),getShapeSelectionPageMiddlePoint:e=>this.editor.shapes.getUtil(e).getSelectionPageMiddlePoint(e),getShapePageRecord:e=>t.get(e.id)});var s,o;this.transition("rotating",{...this.info,center:i.center,startAngle:Lr.Angle(i.center,this.info.originPagePoint),initialSelectionRotation:i.initialSelectionRotation,shapes:i.shapes,pointShapes:i.pointShapes,updates:(s=i.shapes,o=i.pointShapes,[...s.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY})),...o.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY}))]),lastPointerX:NaN,lastPointerY:NaN,lastShiftKey:!1,lastAccelKey:!1})}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}},Ga=class extends za{constructor(e,t){super(e,"pointing_selection_handle_interaction",t)}onDragThresholdExceeded(){this.info&&this.transition("dragging_plugin_interaction",{...this.info,snapMode:this.info.session.handleSnapMode??"none",lastPagePointX:NaN,lastPagePointY:NaN,lastShiftKey:!1,lastAltKey:!1,lastAccelKey:!1})}onPointerUp(e,t){if(this.info){const e={editor:this.editor,source:"user"};(t.pointer?.clickCount??1)>=2&&this.info.session.onDoubleClick?this.info.session.onDoubleClick(e):this.info.session.onClick?.(e)}this.transition("idle")}onCancel(e){this.info?.session.onCancel?.({editor:this.editor,reason:e.reason}),this.transition("idle")}},Va=class extends za{constructor(e,t){super(e,"pointing_shape",t)}onInfoEnter(){this.info&&(this.info.quickClickSelectionTargetId||(this.info.additiveSelection?this.info.wasSelected||this.editor.commands.setSelectedShapeIds([...this.info.previousSelection,this.info.shapeId],{source:"system"}):this.info.wasSelected||this.editor.commands.setSelectedShapeIds([this.info.shapeId],{source:"system"})))}onDragThresholdExceeded(e){if(!this.info||this.editor.state.readonly.get())return;if(this.info.dragSession)return void this.transition("dragging_plugin_interaction",{originPagePoint:this.info.originPagePoint,previousSelection:this.info.previousSelection,session:this.info.dragSession,snapMode:"none",snapSnapshot:null,lastPagePointX:NaN,lastPagePointY:NaN,lastShiftKey:!1,lastAltKey:!1,lastAccelKey:!1});const t=this.editor.state.selectedShapes.get(),n=this.info.wasSelected?t.map(e=>e.id):[this.info.translateTargetId];this.info.wasSelected||1!==n.length||n[0]===this.info.shapeId||this.editor.commands.setSelectedShapeIds(n,{source:"system"});const i=this.editor.selection.getFrame(),s=((e,t)=>t.filter(t=>{const n=e.shapes.get(t);return!!n&&e.shapes.getUtil(n).canParticipateInSelectionTranslation(n,{editor:e})&&!e.layers.isOrAncestorLocked(n.id)&&!e.layers.hasLockedDescendant(n.id)}).map(t=>e.shapes.get(t)).filter(e=>!!e).flatMap(t=>(t.parentId.startsWith("shape:")?e.shapes.computeLocalToPageTransform(e.shapes.get(t.parentId)):Wr.Identity()).tryInvert()?[{id:t.id,x:t.x,y:t.y,startLocalToPage:e.shapes.computeLocalToPageTransform(t)}]:[]))(this.editor,n);if(0===s.length)return void this.transition("brushing",{originPagePoint:this.info.originPagePoint,previousSelection:this.info.previousSelection,additiveSelection:Qs(e)});const o=s.map(e=>e.id),r=i?.hasCompatibleRotation?i.rotation:0,a=i?.rotationCenter.clone()??Lr.Zero(),d=i?.hasCompatibleRotation?i.bounds.clone():this.editor.selection.getPageBounds();var c;this.transition("translating",{originPagePoint:this.info.originPagePoint,previousSelection:this.info.previousSelection,movingShapeIds:o,startBounds:d,snapSnapshot:this.editor.snaps.createTranslateSnapshot({movingShapeIds:o,coordinateSpace:{rotation:r,rotationCenter:a}}),snapRotation:r,selectedShapes:s,updates:(c=s,c.map(e=>({id:e.id,x:e.x,y:e.y}))),lockedAxis:null,lastDeltaX:NaN,lastDeltaY:NaN})}onPointerUp(e,t){let n;if(this.info?.quickClickSelectionTargetId){const i=((e,t)=>t.timestamp-e.originTimestamp<=250)(this.info,e);i&&this.editor.commands.setSelectedShapeIds([this.info.quickClickSelectionTargetId],{source:"system"}),i&&(t.pointer?.clickCount??1)>=2||(n={clickSequence:"break"})}else Qs(e)&&this.info?.wasSelected?this.editor.commands.setSelectedShapeIds(this.info.previousSelection.filter(e=>e!==this.info?.shapeId),{source:"system"}):this.info&&!this.info.additiveSelection&&this.info.wasSelected&&!this.info.fromSelectionBounds&&this.info.previousSelection.length>1&&this.editor.commands.setSelectedShapeIds([this.info.shapeId],{source:"system"});return this.transition("idle"),n}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.transition("idle")}},ja=class extends _a{constructor(e,t){super(e,"resizing",t)}getOperationKind(){return"select.resize"}onDragStart(){this.editor.interaction.setSnapIndicators(null)}onPointerUp(e){this.apply(e),this.complete()}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}onInfoExit(){this.editor.interaction.setSnapIndicators(null)}apply({pagePoint:e,shiftKey:t,altKey:n,accelKey:i}){if(!this.info)return;if(e.x===this.info.lastPagePointX&&e.y===this.info.lastPagePointY&&t===this.info.lastShiftKey&&n===this.info.lastAltKey&&i===this.info.lastAccelKey)return;this.info.lastPagePointX=e.x,this.info.lastPagePointY=e.y,this.info.lastShiftKey=t,this.info.lastAltKey=n,this.info.lastAccelKey=i;const s=no(this.info.rotationCenter,this.info.rotation),o=_n(e.sub(this.info.cursorHandleOffset),s),r=((e,t)=>{const n=e.includes("free"),i=e.includes("aspect_ratio_locked");return n||i?n?i&&t?"aspect_ratio_locked":"free":"aspect_ratio_locked":null})(this.info.allowedResizeModes,t);if(!r)return;const a="aspect_ratio_locked"===r,d=function({startBounds:e,handleId:t,pagePoint:n,isAspectRatioLocked:i,isResizingFromCenter:s,aspectRatio:o}){const r=s?(({startBounds:e,handleId:t,pagePoint:n})=>{const i=e.center,s=n.x-i.x,o=n.y-i.y,r=Math.max(Math.abs(s),.5),a=Math.max(Math.abs(o),.5),d=Oi(t)||Li(t)?s*(Oi(t)?-2:2)/Math.max(1,e.w):1,c=zi(t)||_i(t)?o*(zi(t)?-2:2)/Math.max(1,e.h):1;switch(t){case"top":case"bottom":return{bounds:new zr(e.minX,i.y-a,e.w,2*a),scaleX:d,scaleY:c};case"left":case"right":return{bounds:new zr(i.x-r,e.minY,2*r,e.h),scaleX:d,scaleY:c};default:return{bounds:new zr(i.x-r,i.y-a,2*r,2*a),scaleX:d,scaleY:c}}})({startBounds:e,handleId:t,pagePoint:n}):(({startBounds:e,handleId:t,pagePoint:n})=>{const i=e.minX,s=e.maxX,o=e.minY,r=e.maxY;let a=Oi(t)?i:s,d=Oi(t)?s:i,c=zi(t)?o:r,l=zi(t)?r:o;Oi(t)||Li(t)?a=n.x:(a=s,d=i),zi(t)||_i(t)?c=n.y:(c=r,l=o);const h=a-d,p=c-l,u=Oi(t)?d-a:h,g=zi(t)?l-c:p,f=Oi(t)||Li(t)?u/Math.max(1,e.w):1,m=zi(t)||_i(t)?g/Math.max(1,e.h):1;return{bounds:new zr(Math.min(a,d),Math.min(c,l),Math.max(1,Math.abs(h)),Math.max(1,Math.abs(p))),scaleX:f,scaleY:m}})({startBounds:e,handleId:t,pagePoint:n});return i?Ui({bounds:r.bounds,startBounds:e,handleId:t,aspectRatio:o,isResizingFromCenter:s,scaleX:r.scaleX,scaleY:r.scaleY}):r}({startBounds:this.info.startBounds,handleId:this.info.handleId,pagePoint:o,isAspectRatioLocked:a,isResizingFromCenter:n,aspectRatio:this.info.aspectRatio}),c=!i&&this.info.snapSnapshot.points.length>0,l=c?this.editor.snaps.snapResize({handleId:this.info.handleId,initialSelectionBounds:this.info.startBounds,resizedSelectionBounds:d.bounds,scaleX:d.scaleX,scaleY:d.scaleY,snapshot:this.info.snapSnapshot,threshold:8/this.editor.state.camera.get().z,isAspectRatioLocked:a,isResizingFromCenter:n}):d;c||this.editor.snaps.clearIndicators();const h=this.info.shapes.length+this.info.pointShapes.length===1;for(let p=0;p<this.info.shapes.length;p+=1){const e=this.info.shapes[p],t=this.info.updates[p];e&&t&&to(this.editor,e,this.info.startBounds,l.bounds,l.scaleX,l.scaleY,this.info.handleId,h,n,this.info.rotationCenter,this.info.rotation,t)}for(let p=0;p<this.info.pointShapes.length;p+=1){const e=this.info.pointShapes[p],t=this.info.updates[this.info.shapes.length+p];e&&t&&io(this.editor,e,this.info.startBounds,0,l.scaleX,l.scaleY,this.info.handleId,n,this.info.rotationCenter,this.info.rotation,t)}this.editor.commands.updateShapes(this.info.updates)}complete(){this.editor.interaction.setSnapIndicators(null),this.commitOperation(),this.transition("idle")}cancel(){this.editor.interaction.setSnapIndicators(null),this.cancelOperation(),this.transition("idle")}},Qa=class extends _a{constructor(e,t){super(e,"rotating",t)}getOperationKind(){return"select.rotate"}onPointerUp(e){this.apply(e),this.complete()}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}apply({pagePoint:e,shiftKey:t,accelKey:n}){if(!this.info)return;if(e.x===this.info.lastPointerX&&e.y===this.info.lastPointerY&&t===this.info.lastShiftKey&&n===this.info.lastAccelKey)return;this.info.lastPointerX=e.x,this.info.lastPointerY=e.y,this.info.lastShiftKey=t,this.info.lastAccelKey=n;let i=Js(Lr.Angle(this.info.center,e)-this.info.startAngle);if(t)i=eo(i,Fa);else if(!n&&this.editor.inputs.state.get().screenVelocity.len()<.5){const e=this.info.initialSelectionRotation+i,t=eo(e,Da),n=Js(t-e);Math.abs(n)<=Oa&&(i=Js(t-this.info.initialSelectionRotation))}for(let s=0;s<this.info.shapes.length;s+=1){const e=this.info.shapes[s],t=this.info.updates[s];e&&t&&oo(this.editor,e,this.info.center,i,t)}for(let s=0;s<this.info.pointShapes.length;s+=1){const e=this.info.pointShapes[s],t=this.info.updates[this.info.shapes.length+s];e&&t&&ro(this.editor,e,this.info.center,i,t)}this.editor.commands.updateShapes(this.info.updates)}complete(){this.commitOperation(),this.transition("idle")}cancel(){this.cancelOperation(),this.transition("idle")}},Za=class extends _a{constructor(e,t){super(e,"translating",t)}getOperationKind(){return"select.translate"}onDragStart(){this.editor.interaction.setSelectionTranslationActive(!0),this.editor.interaction.setSnapIndicators(null)}onPointerUp(e){this.apply(e),this.complete(e.pagePoint)}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}onInfoExit(){this.editor.interaction.setSelectionTranslationActive(!1),this.editor.interaction.setSnapIndicators(null)}apply({pagePoint:e,shiftKey:t,accelKey:n}){if(!this.info)return;const i=e.x-this.info.originPagePoint.x,s=e.y-this.info.originPagePoint.y;t?this.info.lockedAxis||0===i&&0===s||(this.info.lockedAxis=Math.abs(i)>=Math.abs(s)?"x":"y"):this.info.lockedAxis=null;let o=i,r=s;"x"===this.info.lockedAxis?r=0:"y"===this.info.lockedAxis&&(o=0);const a=this.info.startBounds;if(!n&&a&&(this.info.snapSnapshot.points.length>0||this.info.snapSnapshot.nodes.length>0)&&this.editor.inputs.state.get().screenVelocity.len()<.5&&a){const e=this.info.snapRotation,t=8/this.editor.state.camera.get().z,n=0===e?new Lr(o,r):new Lr(o,r).rot(-e),{nudge:i}=this.editor.snaps.snapTranslate({lockedAxis:this.info.lockedAxis,initialSelectionBounds:a,dragDelta:n,snapshot:this.info.snapSnapshot,threshold:t}),s=0===e?i:i.rot(e);o+="y"===this.info.lockedAxis?0:s.x,r+="x"===this.info.lockedAxis?0:s.y}else this.editor.snaps.clearIndicators();if(o!==this.info.lastDeltaX||r!==this.info.lastDeltaY){this.info.lastDeltaX=o,this.info.lastDeltaY=r;for(let e=0;e<this.info.selectedShapes.length;e+=1){const t=this.info.selectedShapes[e],n=this.info.updates[e];if(!t||!n)continue;const i=this.editor.shapes.get(t.id);if(!i)continue;const s=i.parentId.startsWith("shape:")?this.editor.shapes.get(i.parentId):null,a=(s?this.editor.shapes.computeLocalToPageTransform(s):Wr.Identity()).tryInvert();if(!a)continue;const d=Pe(a.compose(Wr.Translate(o,r).compose(t.startLocalToPage)),this.editor.shapes.computeLocalBounds(i),{preferredRotation:i.rotation,preferredScaleXSign:i.scaleX,preferredScaleYSign:i.scaleY});d&&Object.assign(n,d)}this.editor.commands.updateShapes(this.info.updates)}lo(this.editor,this.info.movingShapeIds,e),((e,t,n)=>{const i=co(e,t,n);if(i===ao(e,t))return void e.interaction.setDropTargetShapeId(null);const s=i?e.shapes.get(i):null;e.interaction.setDropTargetShapeId(s?.id??null)})(this.editor,this.info.movingShapeIds,e)}complete(e){this.info&&lo(this.editor,this.info.movingShapeIds,e),this.editor.interaction.setDropTargetShapeId(null),this.editor.interaction.setSnapIndicators(null),this.commitOperation(),this.transition("idle")}cancel(){this.editor.interaction.setDropTargetShapeId(null),this.editor.interaction.setSnapIndicators(null),this.cancelOperation(),this.transition("idle")}},Ja=class extends Ra{constructor(e){super(e,"select"),this.initial="idle",this.addChild(new Ua(e,this)),this.addChild(new Ha(e,this)),this.addChild(new $a(e,this)),this.addChild(new Va(e,this)),this.addChild(new Za(e,this)),this.addChild(new Wa(e,this)),this.addChild(new ja(e,this)),this.addChild(new qa(e,this)),this.addChild(new Qa(e,this)),this.addChild(new Ga(e,this)),this.addChild(new Na(e,this))}},ed=cr(null),td=cr(go([])),nd="var(--land-shape-hover, var(--land-selection, #2563eb))",id=2,sd=lr(e=>{const{Component:t,editor:n,isSelected:i,shape:s,shapeEditingSession:o}=e;
22
+ br("div",{"data-ui":h.name,"data-shape-id":t.id,role:m&&!n?"button":void 0,"aria-label":m&&!n?`${c}: ${k}`:void 0,onClick:m?D:void 0,onPointerDown:m?F:void 0,style:{background:m&&n?"var(--land-surface-bg, white)":void 0,borderRadius:4,boxShadow:m&&n?"inset 0 0 0 1.5px var(--land-selection, #2563eb)":void 0,color:m&&n?"transparent":"inherit",cursor:m?"text":"grab",height:m&&n?"100%":void 0,minWidth:m&&n?32:void 0,overflow:m&&n?"visible":"hidden",padding:S?`0 6px 0 ${y?0:6}px`:0,pointerEvents:"auto",position:"relative",textOverflow:"ellipsis",whiteSpace:"pre",width:m&&n?"auto":void 0},children:[m?Pr("input",{ref:I,"data-ui":h.input,"data-shape-id":t.id,"aria-label":l,value:i,autoComplete:"off",disabled:!n,readOnly:!n,spellCheck:!1,onBlur:R,onChange:A,onCompositionStart:K,onCompositionEnd:Y,onKeyDown:X,onPointerDown:F,style:{background:"none",border:0,borderRadius:4,boxSizing:"border-box",color:"var(--land-text-primary, #0f172a)",cursor:"text",display:n?void 0:"none",font:"inherit",height:"100%",inset:0,lineHeight:"24px",minWidth:0,outline:0,padding:"0 6px",position:"absolute",userSelect:"text",width:"100%"}}):null,k+String.fromCharCode(8203)]})]})})})}import{createContext as cr,memo as lr,useCallback as hr,useContext as pr,useEffect as ur,useId as gr,useLayoutEffect as fr,useMemo as mr,useRef as Sr,useState as yr,useSyncExternalStore as Ir}from"react";import{Fragment as wr,jsx as Pr,jsxs as br}from"react/jsx-runtime";var vr=class{graph;name;current;isEqual;lastChangedEpoch;consumers=new Set;constructor(e,t,n,i){this.graph=e,this.name=t,this.current=n,this.isEqual=i,this.lastChangedEpoch=e.getEpoch()}get(){return this.graph.trackDependency(this),this.current}peek(){return this.current}__unsafe__isEqual(e,t){return this.isEqual?this.isEqual(e,t):Object.is(e,t)}__unsafe__restore(e,t){this.current=e,this.lastChangedEpoch=t}set(e){const t=this.current;return this.__unsafe__isEqual(t,e)?t:(this.graph.noteInitialValue(this,t,this.lastChangedEpoch),this.graph.advanceEpoch(),this.lastChangedEpoch=this.graph.getEpoch(),this.current=e,this.graph.atomDidChange(this),e)}update(e){return this.set(e(this.current))}},xr=Symbol("UNINITIALIZED"),Cr=class{graph;name;derive;isEqual;isComputed=!0;lastChangedEpoch;lastCheckedEpoch=-1;consumers=new Set;state=xr;dependencies=[];dependencyEpochs=[];consumerNodeValue=null;constructor(e,t,n,i){this.graph=e,this.name=t,this.derive=n,this.isEqual=i,this.lastChangedEpoch=e.getEpoch()}get(){return this.graph.trackDependency(this),this.peek()}peek(){if(this.lastCheckedEpoch===this.graph.getEpoch())return this.state;if(this.state!==xr&&!this.haveDependenciesChanged())return this.lastCheckedEpoch=this.graph.getEpoch(),this.state;let e,t;this.graph.startCapture(this.consumerNode);try{e=this.derive(this.state)}finally{t=this.graph.stopCapture()}for(const n of this.dependencies)t.has(n)||n.consumers.delete(this.consumerNode);this.dependencies=[...t],this.dependencyEpochs=this.dependencies.map(e=>e.lastChangedEpoch);for(const n of this.dependencies)n.consumers.add(this.consumerNode);return this.state!==xr&&(this.isEqual?this.isEqual(this.state,e):Object.is(this.state,e))||(this.state=e,this.graph.advanceEpoch(),this.lastChangedEpoch=this.graph.getEpoch()),this.lastCheckedEpoch=this.graph.getEpoch(),this.state}get consumerNode(){return this.consumerNodeValue||(this.consumerNodeValue={type:"computed",signal:this}),this.consumerNodeValue}haveDependenciesChanged(){for(let e=0;e<this.dependencies.length;e++){const t=this.dependencies[e];if(t.peek(),t.lastChangedEpoch!==this.dependencyEpochs[e])return!0}return!1}},Mr=class{graph;name;fn;options;dependencies=[];dependencyEpochs=[];lastReactedEpoch=-1;isActive=!1;consumerNode={type:"effect",notify:()=>this.maybeSchedule()};constructor(e,t,n,i){this.graph=e,this.name=t,this.fn=n,this.options=i}attach(){this.isActive=!0,this.execute()}detach(){this.isActive=!1;for(const e of this.dependencies)e.consumers.delete(this.consumerNode);this.dependencies=[],this.dependencyEpochs=[]}maybeSchedule(){this.isActive&&this.lastReactedEpoch!==this.graph.getEpoch()&&(this.haveDependenciesChanged()?this.options?.scheduleEffect?this.options.scheduleEffect(()=>this.execute()):this.execute():this.lastReactedEpoch=this.graph.getEpoch())}execute(){if(this.isActive){for(const e of this.dependencies)e.consumers.delete(this.consumerNode);this.graph.startCapture(this.consumerNode);try{this.fn()}finally{const e=this.graph.stopCapture();this.dependencies=[...e],this.dependencyEpochs=this.dependencies.map(e=>e.lastChangedEpoch);for(const t of this.dependencies)t.consumers.add(this.consumerNode);this.lastReactedEpoch=this.graph.getEpoch()}}}haveDependenciesChanged(){for(let e=0;e<this.dependencies.length;e++){const t=this.dependencies[e];if(t.peek(),t.lastChangedEpoch!==this.dependencyEpochs[e])return!0}return!1}},Tr=null,Br=class{epoch=0;currentTransaction=null;captureStack=null;atom=(e,t,n)=>((e,t,n,i)=>new vr(e,t,n,i?.isEqual))(this,e,t,n);computed=(e,t,n)=>((e,t,n,i)=>new Cr(e,t,n,i?.isEqual))(this,e,t,n);effect=(e,t,n)=>((e,t,n,i)=>{const s=new Mr(e,t,n,i);return s.attach(),()=>s.detach()})(this,e,t,n);transact=e=>{if(this.currentTransaction)return void e();const t={initialAtomSnapshots:new Map};this.currentTransaction=t;try{e()}catch(s){throw this.restoreInitialAtomSnapshots(t),this.currentTransaction=null,s}const n=[];let i=!1;for(const[o,r]of t.initialAtomSnapshots){const e=o.peek();o.__unsafe__isEqual(r.value,e)?(o.__unsafe__restore(r.value,r.lastChangedEpoch),i=!0):n.push(o)}i&&this.advanceEpoch(),this.currentTransaction=null,this.flushChanges(n)};getEpoch(){return this.epoch}isComputingSignal(){return"computed"===this.captureStack?.consumer.type}advanceEpoch(){return++this.epoch}noteInitialValue(e,t,n){this.currentTransaction&&!this.currentTransaction.initialAtomSnapshots.has(e)&&this.currentTransaction.initialAtomSnapshots.set(e,{value:t,lastChangedEpoch:n})}startCapture(e){this.captureStack={consumer:e,dependencies:new Set,previous:this.captureStack},Tr={graph:this,previous:Tr}}stopCapture(){if(!this.captureStack)throw new Error("Cannot stop dependency capture because no capture is active.");if(Tr?.graph!==this)throw new Error("SignalGraph dependency capture stack is out of order.");const e=this.captureStack;return this.captureStack=e.previous,Tr=Tr.previous,e.dependencies}trackDependency(e){if(Tr&&Tr.graph!==this)throw new Error("Cannot read signals across different SignalGraph instances while capturing dependencies.");this.captureStack&&(this.captureStack.dependencies.add(e),e.consumers.add(this.captureStack.consumer))}atomDidChange(e){this.currentTransaction||this.flushChanges([e])}restoreInitialAtomSnapshots(e){if(0!==e.initialAtomSnapshots.size){for(const[t,n]of e.initialAtomSnapshots)t.__unsafe__restore(n.value,n.lastChangedEpoch);this.advanceEpoch()}}flushChanges(e){const t=new Set,n=new Set,i=e=>{for(const s of e)n.has(s)||(n.add(s),"effect"===s.type?t.add(s):i(s.signal.consumers))};for(const a of e)i(a.consumers);let s,o=!1;for(const a of t)try{a.notify()}catch(r){o||(s=r,o=!0)}if(o)throw s}},kr=class{undoStack=[];redoStack=[];get canUndo(){return this.undoStack.length>0}get canRedo(){return this.redoStack.length>0}clear(){this.undoStack.length=0,this.redoStack.length=0}append(e,n="change"){t(e)||(this.undoStack.push(((e,t)=>({forward:t,inverse:i(t),label:e}))(n,e)),this.redoStack.length=0)}undo(){const e=this.undoStack.pop()??null;return e?(this.redoStack.push(e),e):null}redo(){const e=this.redoStack.pop()??null;return e?(this.undoStack.push(e),e):null}rollbackUndo(e){if(this.redoStack.at(-1)!==e)throw new Error("Cannot roll back an outdated history undo.");this.redoStack.pop(),this.undoStack.push(e)}rollbackRedo(e){if(this.undoStack.at(-1)!==e)throw new Error("Cannot roll back an outdated history redo.");this.undoStack.pop(),this.redoStack.push(e)}getEntries(){return this.undoStack}},Er=class{signals;records;activeTransaction=null;recordAtoms=new Map;revisionAtom;draftRevisionAtom;listeners=new Set;writeGuard;constructor(t,n={}){this.signals=n.signals??e(),this.revisionAtom=this.signals.atom("store.revision",0),this.draftRevisionAtom=this.signals.atom("store.draftRevision",0),this.records=new Map(t.map(e=>[e.id,e])),this.writeGuard=n.writeGuard}get(e){const t=this.activeTransaction?.journal.get(e);return t?t.after:this.records.get(e)}getRevision(){return this.revisionAtom.get()}getActiveTransactionRevision(){const e=this.activeTransaction;return e?(this.draftRevisionAtom.get(),e.revision):null}getActiveTransactionDiff(){const e=this.activeTransaction;if(!e)throw new Error("Store.getActiveTransactionDiff() requires an active transaction.");return o(e.journal)}getRecordSignal(e){let t=this.recordAtoms.get(e);if(t)return t;const n=this.records.get(e);t=this.signals.atom(`store.record.${e}`,n),this.recordAtoms.set(e,t);const i=this.get(e);return i!==n&&t.set(i),t}getAll(){if(this.signals.isComputingSignal())throw new Error("Store.getAll() cannot run while deriving a computed signal. Read a keyed record or indexed query signal instead.");return Array.from(this.getReadableRecords().values())}getByScope(e){return this.getAll().filter(t=>"scope"in t&&t.scope===e)}listen(e){return this.listeners.add(e),()=>this.listeners.delete(e)}atomic(e,n="system"){if(this.activeTransaction)return void e();let i,s=[],a=!1;try{this.signals.transact(()=>{const i=this.draftRevisionAtom.peek(),a={revision:i,initialDraftRevision:i,journal:new Map};this.activeTransaction=a,this.bumpDraftRevision(a);let d=!1;try{e();const i=o(a.journal);if(t(i))return;const c={source:n,diff:i};this.writeGuard?.(c),r(this.records,a.journal),d=!0,this.revisionAtom.set(this.revisionAtom.peek()+1),this.activeTransaction=null,s=this.notifyListeners(c)}catch(c){throw d||this.restoreTransactionSignals(a),c}finally{this.activeTransaction=null}})}catch(d){i=d,a=!0}if(s.length>0)throw s[0];if(a)throw i}put(e,t="system"){this.atomic(()=>{for(const t of e)this.stageRecord(t.id,t)},t)}remove(e,t="system"){this.atomic(()=>{for(const t of e)this.stageRecord(t,void 0)},t)}applyDiff(e,t="system"){this.atomic(()=>{for(const t of e.added)this.stageRecord(t.id,t);for(const t of e.updated)this.stageRecord(t.after.id,t.after);for(const t of e.removed)this.stageRecord(t.id,void 0)},t)}stageRecord(e,t){const n=this.requireActiveTransaction(),i=this.get(e);if(i===t)return;const s=n.journal.get(e)??{before:this.records.get(e),after:t,moveToEnd:!1};s.after=t,void 0===i&&void 0!==t&&(s.moveToEnd=!0,n.journal.delete(e)),n.journal.set(e,s),this.bumpDraftRevision(n),this.recordAtoms.get(e)?.set(t)}getReadableRecords(){const e=this.activeTransaction;if(!e)return this.records;const t=new Map(this.records);return r(t,e.journal),t}requireActiveTransaction(){if(!this.activeTransaction)throw new Error("Store mutations must run inside store.atomic");return this.activeTransaction}bumpDraftRevision(e){const t=this.draftRevisionAtom.peek()+1;e.revision=t,this.draftRevisionAtom.set(t)}restoreTransactionSignals(e){for(const[t]of e.journal)this.recordAtoms.get(t)?.set(this.records.get(t));this.draftRevisionAtom.set(e.initialDraftRevision)}notifyListeners(e){const t=[];for(const i of this.listeners)try{i(e)}catch(n){t.push(n)}return t}},Ar="document:main",Rr="page:default",Kr="session:main",Yr={x:0,y:0,z:1},Xr=Symbol("editorStore"),Fr=new Set,Dr=class{editor;suppressedReactionIds=Fr;constructor(e){this.editor=e}getSuppressedReactionIds(){return this.suppressedReactionIds}runWithSuppressedReactions(e,t,...n){const i=this.suppressedReactionIds,s=new Set(i);for(const o of e)s.add(o);if(s.size===i.size)return v(t);this.suppressedReactionIds=s;try{return v(t)}finally{this.suppressedReactionIds=i}}getConflictingBindings(e){const t=this.getExclusiveBindingKey(e);return t?this.getAllBindings().filter(n=>n.id!==e.id&&n.type===e.type&&this.getExclusiveBindingKey(n)===t):[]}canBind(e){const t=this.getEndpointContext(e);return!(!t||0===e.endpoints.length)&&(this.editor.bindings.getUtil(e).canBind?.(this.editor,e,t)??!0)}syncCreatedBinding(e,t){const n=this.editor.bindings.getUtil(e).onBindingCreate?.(this.editor,e);this.applyEffect(n,t,e.id),this.syncShapeCompanionState(P(e),t,e.id)}syncUpdatedBinding(e,t,n){const i=this.editor.bindings.getUtil(t).onBindingUpdate?.(this.editor,e,t);this.applyEffect(i,n,t.id),this.syncShapeCompanionState([...P(e),...P(t)],n,t.id)}repairLoadedBindings(e){S(this.editor).atomic(()=>{const t=new Set,n=new Set;for(const s of this.getAllBindings()){if(!this.getEndpointContext(s)){this.applyEffect(this.editor.bindings.getUtil(s).onInvalidBindingLoad?.(this.editor,s),e,s.id),S(this.editor).remove([s.id],e);continue}if(!this.canBind(s)){this.applyEffect(this.editor.bindings.getUtil(s).onInvalidBindingLoad?.(this.editor,s),e,s.id),S(this.editor).remove([s.id],e);continue}const i=this.getExclusiveBindingKey(s);if(i){if(t.has(i)){S(this.editor).remove([s.id],e);continue}t.add(i)}const o=this.editor.bindings.getUtil(s).onBindingLoad?.(this.editor,s);this.applyEffect(o,e,s.id);for(const e of P(s))n.add(e)}const i=S(this.editor).getAll().filter(p).filter(e=>!this.editor.shapes.getUtil(e).isValidAfterBindingLoad(e,{editor:this.editor})).map(e=>e.id);i.length>0&&this.editor.commands.deleteShapes(i,{source:e}),this.syncShapeCompanionState(Array.from(n),e)},e)}handleShapeChanges(e,t){if(0===e.length)return;const n=this.suppressedReactionIds,i=new Set(e.map(e=>e.after.id)),s=new Set,o=new Set,r=(e,i,r,a)=>{for(const d of this.editor.bindings.getForShape(e.id)){if(n.has(d.id))continue;if("ancestry"===a&&o.has(d.id))continue;const c=`${d.id}:${e.id}:${a}`;if(s.has(c))continue;s.add(c),"self"===a&&o.add(d.id);const l=b(d,e.id),h=this.editor.bindings.getUtil(d).onAfterShapeChange?.(this.editor,d,{before:i,after:r,...l,reason:a});this.applyEffect(h,t,d.id)}};for(const a of e)r(a.after,a.before,a.after,"self");for(const a of e)if(w(a))for(const e of this.editor.layers.getDescendantIds(a.after.id)){if(i.has(e))continue;const t=this.editor.shapes.get(e);t&&r(t,t,t,"ancestry")}this.syncShapeCompanionState(e.filter(({before:e,after:t})=>e.isHidden!==t.isHidden||e.isLocked!==t.isLocked).map(({after:e})=>e.id),t)}getShapeCompanionRootId(e){return this.getShapeCompanionRootIds([e]).get(e)??e}getShapeCompanionRootIds(e,t=this.getAllBindings()){const n=I(e,t,e=>this.editor.bindings.getUtil(e)),i=new Map;for(const s of e){const e=n.get(s)??s;i.set(s,this.editor.shapes.get(e)?e:s)}return i}getShapeCompanionMemberIds(e){const t=this.getShapeCompanionContext(),n=[],i=new Set;for(const s of e){const e=t.rootIdByShapeId.get(s)??s;if(t.shapeById.has(e))for(const s of[e,...t.memberIdsByRootId.get(e)??[]])i.has(s)||(i.add(s),n.push(s))}return n}cleanupBindingsForDeletedShapes(e,t){if(0===e.length)return;const n=new Set(e),i=new Map;for(const s of e)for(const e of this.editor.bindings.getForShape(s))i.set(e.id,e);for(const s of i.values()){const e=P(s).filter(e=>n.has(e));for(const n of e){const e=this.editor.shapes.get(n);if(!e)continue;const i=this.editor.bindings.getUtil(s).onBeforeDeleteShape?.(this.editor,s,{shape:e,...b(s,n)});this.applyEffect(i,t,s.id)}if(n.has(s.ownerId)){S(this.editor).remove([s.id],t);continue}const i=this.editor.bindings.get(s.id);if(!i)continue;const o=i.endpoints.filter(({targetId:e})=>!n.has(e));o.length!==i.endpoints.length&&(0===o.length?S(this.editor).remove([i.id],t):S(this.editor).put([{...i,endpoints:o}],t))}}cleanupBindings(e,t){for(const n of e){const e=this.editor.bindings.get(n);if(!e)continue;const i=this.editor.bindings.getUtil(e).onBeforeDeleteBinding?.(this.editor,e);this.applyEffect(i,t,e.id)}}applyEffect(e,t,n){if(!e)return;const i=new Set(e.suppressBindingIds??[]);n&&i.add(n),this.runWithSuppressedReactions(i,()=>{e.deleteBindingIds&&e.deleteBindingIds.length>0&&S(this.editor).remove(Array.from(new Set(e.deleteBindingIds)),t),e.bindings&&e.bindings.length>0&&S(this.editor).put(e.bindings,t),e.shapes&&e.shapes.length>0&&this.editor.commands.updateShapes(e.shapes.map(e=>({id:e.id,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,parentId:e.parentId,index:e.index,props:e.props,meta:e.meta})),{source:t}),e.deleteShapeIds&&e.deleteShapeIds.length>0&&this.editor.commands.deleteShapes(Array.from(new Set(e.deleteShapeIds)),{source:t})})}syncShapeCompanionState(e,t,n){if(0===e.length)return;const i=this.getShapeCompanionContext(),s=new Set,o=[];for(const r of e){const e=i.rootIdByShapeId.get(r)??r;if(s.has(e))continue;s.add(e);const t=i.shapeById.get(e);if(t)for(const n of i.memberIdsByRootId.get(e)??[]){const e=i.shapeById.get(n);!e||e.isHidden===t.isHidden&&e.isLocked===t.isLocked||o.push({...e,isHidden:t.isHidden,isLocked:t.isLocked})}}o.length>0&&this.applyEffect({shapes:o},t,n)}getShapeCompanionContext(){const e=S(this.editor).getAll(),t=e.filter(p).sort((e,t)=>e.parentId===t.parentId?e.index.localeCompare(t.index)||e.id.localeCompare(t.id):e.parentId.localeCompare(t.parentId)),n=new Map(t.map(e=>[e.id,e])),i=new Map(I(t.map(e=>e.id),e.filter(g),e=>this.editor.bindings.getUtil(e))),s=new Map;for(const o of t){const e=i.get(o.id)??o.id,t=n.has(e)?e:o.id;if(i.set(o.id,t),t===o.id)continue;const r=s.get(t);r?r.push(o.id):s.set(t,[o.id])}return{memberIdsByRootId:s,rootIdByShapeId:i,shapeById:n}}getAllBindings(){return S(this.editor).getAll().filter(g).sort((e,t)=>e.id.localeCompare(t.id))}getEndpointContext(e){const t=this.editor.shapes.get(e.ownerId);if(!t)return null;const n=e.endpoints.map(e=>{const t=this.editor.shapes.get(e.targetId);return t?{endpoint:e,targetShape:t}:null});return n.some(e=>!e)?null:{ownerShape:t,endpoints:n.filter(e=>!!e)}}getExclusiveBindingKey(e){const t=this.editor.bindings.getUtil(e).getExclusiveBindingKey?.(e);return t?`${e.type}:${t}`:null}},Or=class{registry=new Map;register(e){this.registry.set(e.type,e)}values(){return this.registry.values()}get(e){const t=this.registry.get(e);if(!t)throw new Error(`Missing binding util for type "${e}"`);return t}},Lr=class e{x;y;constructor(e,t){this.x=e,this.y=t}add(t){return new e(this.x+t.x,this.y+t.y)}sub(t){return new e(this.x-t.x,this.y-t.y)}mul(t){return new e(this.x*t,this.y*t)}div(t){return new e(this.x/t,this.y/t)}len2(){return this.x*this.x+this.y*this.y}len(){return Math.sqrt(this.len2())}dist2(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}dist(e){return Math.sqrt(this.dist2(e))}rot(t){const n=Math.cos(t),i=Math.sin(t);return new e(this.x*n-this.y*i,this.x*i+this.y*n)}per(){return new e(-this.y,this.x)}normalize(){const t=this.len();return 0===t?new e(0,0):this.div(t)}equals(e){return this.x===e.x&&this.y===e.y}clone(){return new e(this.x,this.y)}static From(t,n){return new e(t,n)}static Zero(){return new e(0,0)}static Med(t,n){return new e((t.x+n.x)/2,(t.y+n.y)/2)}static Lrp(t,n,i){return new e(t.x+(n.x-t.x)*i,t.y+(n.y-t.y)*i)}static Dist(e,t){return e.dist(t)}static Dist2(e,t){return e.dist2(t)}static Angle(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}static Nudge(e,t,n){const i=t.sub(e),s=i.len();return 0===s?e.clone():e.add(i.mul(n/s))}static RotWith(t,n,i){const s=t.x-n.x,o=t.y-n.y,r=Math.cos(i),a=Math.sin(i);return new e(n.x+s*r-o*a,n.y+s*a+o*r)}static IsNaN(e){return isNaN(e.x)||isNaN(e.y)}},zr=class e{x;y;w;h;constructor(e,t,n,i){this.x=e,this.y=t,this.w=n,this.h=i}get minX(){return this.x}get minY(){return this.y}get maxX(){return this.x+this.w}get maxY(){return this.y+this.h}get center(){return new Lr(this.x+this.w/2,this.y+this.h/2)}containsPoint(e){return e.x>=this.minX&&e.x<=this.maxX&&e.y>=this.minY&&e.y<=this.maxY}containsBox(e){return e.minX>=this.minX&&e.maxX<=this.maxX&&e.minY>=this.minY&&e.maxY<=this.maxY}intersects(e){return this.minX<e.maxX&&this.maxX>e.minX&&this.minY<e.maxY&&this.maxY>e.minY}expand(t){return new e(this.x-t,this.y-t,this.w+2*t,this.h+2*t)}clone(){return new e(this.x,this.y,this.w,this.h)}static FromPoints(t){let n=1/0,i=1/0,s=-1/0,o=-1/0;for(const e of t)n=Math.min(n,e.x),i=Math.min(i,e.y),s=Math.max(s,e.x),o=Math.max(o,e.y);return new e(n,i,s-n,o-i)}},_r=["fill-blue","fill-green","fill-red","fill-amber","fill-white","fill-slate","stroke-blue","stroke-green","stroke-red","stroke-orange","stroke-slate","stroke-muted","text-slate","text-blue","text-green","text-red"],$r=Object.fromEntries(_r.map(e=>[e,`--land-shape-${e}`])),Nr={"fill-blue":"#dbeafe","fill-green":"#dcfce7","fill-red":"#fee2e2","fill-amber":"#fff7ed","fill-white":"#f8fafc","fill-slate":"#e2e8f0","stroke-blue":"#1d4ed8","stroke-green":"#15803d","stroke-red":"#dc2626","stroke-orange":"#ea580c","stroke-slate":"#334155","stroke-muted":"#94a3b8","text-slate":"#0f172a","text-blue":"#1d4ed8","text-green":"#15803d","text-red":"#dc2626"},Ur=class{registry=new Map;register(e){this.registry.set(e.type,e)}get(e){return this.registry.get(e)??null}has(e){return this.registry.has(e)}unregister(e){return this.registry.delete(e)}values(){return this.registry.values()}},Hr=class{ids=new Set;registry=new Map;register(e){if(this.ids.has(e.id))throw new Error(`Duplicate shape SVG decoration id: ${e.id}.`);this.ids.add(e.id);const t=this.registry.get(e.subType)??[];t.push(e),this.registry.set(e.subType,t)}get(e){return null===e?[]:this.registry.get(e)??[]}},Wr=class e{a;b;c;d;e;f;constructor(e,t,n,i,s,o){this.a=e,this.b=t,this.c=n,this.d=i,this.e=s,this.f=o}static Identity(){return new e(1,0,0,1,0,0)}static Translate(t,n){return new e(1,0,0,1,t,n)}static Rotate(t){const n=Math.cos(t),i=Math.sin(t);return new e(n,i,-i,n,0,0)}static Scale(t,n){return new e(t,0,0,n,0,0)}compose(t){return new e(this.a*t.a+this.c*t.b,this.b*t.a+this.d*t.b,this.a*t.c+this.c*t.d,this.b*t.c+this.d*t.d,this.a*t.e+this.c*t.f+this.e,this.b*t.e+this.d*t.f+this.f)}applyToPoint(e){return new Lr(this.a*e.x+this.c*e.y+this.e,this.b*e.x+this.d*e.y+this.f)}determinant(){return this.a*this.d-this.b*this.c}getMaximumLinearScale(){const e=this.a*this.a+this.b*this.b+this.c*this.c+this.d*this.d,t=this.determinant(),n=Math.max(0,e*e-4*t*t);return Math.sqrt((e+Math.sqrt(n))/2)}tryInvert(t=0){const n=this.determinant(),i=Number.isFinite(t)?Math.max(0,t):0;if(!Number.isFinite(n)||Math.abs(n)<=i)return null;const s=1/n;return new e(this.d*s,-this.b*s,-this.c*s,this.a*s,(this.c*this.f-this.d*this.e)*s,(this.b*this.e-this.a*this.f)*s)}invert(){return this.tryInvert()??e.Identity()}toCssString(){return`matrix(${this.a},${this.b},${this.c},${this.d},${this.e},${this.f})`}toSvgString(){return`matrix(${this.a} ${this.b} ${this.c} ${this.d} ${this.e} ${this.f})`}static ForShape(t,n,i,s=1,o=1){const r=e.Translate(t,n),a=0===i?e.Identity():e.Rotate(i),d=1===s&&1===o?e.Identity():e.Scale(s,o);return r.compose(a).compose(d)}},qr=class{values=new Map;disposers=[];isDisposed=!1;provide(e,t,n){if(this.isDisposed)throw new Error("Cannot provide an editor runtime after disposal.");if(this.values.has(e.id))throw new Error(`Editor runtime already provided: ${e.id}`);return this.values.set(e.id,t),n&&this.disposers.push(()=>n(t)),t}get(e){return this.values.get(e.id)??null}require(e){const t=this.get(e);if(null===t)throw new Error(`Missing editor runtime: ${e.id}`);return t}onDispose(e){this.isDisposed?e():this.disposers.push(e)}dispose(){if(this.isDisposed)return;this.isDisposed=!0;let e=null;try{for(const n of this.disposers.splice(0).reverse())try{n()}catch(t){e??=t}}finally{this.values.clear()}if(null!==e)throw e}},Gr=class{ids=new Set;registry=new Map;register(e){if(this.ids.has(e.id))throw new Error(`Duplicate shape hit-test decoration id: ${e.id}.`);this.ids.add(e.id);const t=this.registry.get(e.subType)??[];t.push(e),this.registry.set(e.subType,t)}get(e){return null===e?[]:this.registry.get(e)??[]}},Vr=class{registry=new Map;register(e){this.registry.set(e.type,e)}has(e){return this.registry.has(e)}values(){return this.registry.values()}get(e){const t=this.registry.get(e);if(!t)throw new Error(`Missing shape util for type "${e}"`);return t}},jr=class{editor;activeToolId;isToolLocked;registry=new Map;activeTool=null;constructor(e){this.editor=e,this.activeToolId=e.signals.atom("tools.activeToolId","select"),this.isToolLocked=e.signals.atom("tools.isToolLocked",!1)}register(e,t){this.registry.set(e,t)}hasTool(e){return this.registry.has(e)}select(e,t="system"){this.editor.commands.setActiveTool(e,{source:t})}setLocked(e,t="system"){this.editor.commands.setToolLocked(e,{source:t})}toggleLocked(e="system"){this.setLocked(!this.editor.state.tool.get().isToolLocked,e)}syncActiveTool(e,t="tool_switch"){const n=this.registry.get(e);if(!n)throw new Error(`Unknown tool "${e}"`);this.activeTool&&this.activeToolId.get()===e||(this.activeTool&&(this.editor.interaction.cancel(t),this.activeTool.exit({reason:t})),this.activeToolId.set(e),this.activeTool=n(this.editor),this.activeTool.enter())}dispatch(e,t){return this.activeTool?.dispatch(e,t)}syncLockedState(e){this.isToolLocked.set(e)}isInInitialState(){return this.activeTool?.isInInitialState()??!0}},Qr=new WeakMap,Zr=class{editor;nextShapeNumber=1;nextPageNumber=1;nextBindingNumber=1;nextAssetNumber=1;constructor(e){this.editor=e,this.syncCounters()}createPage(e){const t=this.nextPageNumber;return this.nextPageNumber+=1,{id:`page:${t}`,typeName:"page",scope:"document",name:e?.name??`Page ${t}`,index:e?.index??String(t).padStart(4,"0"),meta:e?.meta??{}}}createShape(e){const t=e.parentId??this.editor.state.session.get().currentPageId;if(!this.editor.layers.canReceiveChildren(t))throw new Error("Invalid parent id for shape");const n=this.nextShapeNumber;this.nextShapeNumber+=1;const i=this.editor.shapeUtils.get(e.type).validateProps({...this.editor.shapes.getDefaultProps(e.type),...e.props});return{id:`shape:${n}`,typeName:"shape",scope:"document",type:e.type,subType:e.subType??null,parentId:t,index:e.index??this.createShapeIndex(n),x:e.x,y:e.y,rotation:e.rotation??0,scaleX:e.scaleX??1,scaleY:e.scaleY??1,opacity:e.opacity??1,isHidden:e.isHidden??!1,isLocked:e.isLocked??!1,props:i,meta:e.meta??{}}}createBinding(e){const t=e.id??`binding:${this.nextBindingNumber}`;e.id||(this.nextBindingNumber+=1);const n=this.editor.bindingUtils.get(e.type),i=new Set,s=e.endpoints.map(e=>{if(i.has(e.slot))throw new Error(`Duplicate binding endpoint slot: ${e.slot}`);return i.add(e.slot),{slot:e.slot,targetId:e.targetId,props:n.validateEndpointProps(e.slot,{...n.getDefaultEndpointProps(e.slot),...e.props}),meta:e.meta??{}}}).sort((e,t)=>e.slot.localeCompare(t.slot));if(0===s.length)throw new Error("A binding must have at least one endpoint");return{id:t,typeName:"binding",scope:"document",type:e.type,ownerId:e.ownerId,endpoints:s,meta:e.meta??{}}}createAsset(e){const t=e.id??`asset:${this.nextAssetNumber}`;return e.id||(this.nextAssetNumber+=1),{id:t,typeName:"asset",scope:"document",type:e.type,props:e.props??{},meta:e.meta??{}}}createShapeIndex(e){return String(e).padStart(6,"0")}syncCounters(){let e=0,t=0,n=0,i=0;for(const s of S(this.editor).getAll())if(p(s))e=Math.max(e,ae(s.id));else if(l(s)){const e=s.id.split(":")[1]??"",n=Number("default"===e?1:e);Number.isFinite(n)&&(t=Math.max(t,n))}else g(s)?n=Math.max(n,ae(s.id)):f(s)&&(i=Math.max(i,ae(s.id)));this.nextShapeNumber=e+1,this.nextPageNumber=t+1,this.nextBindingNumber=n+1,this.nextAssetNumber=i+1}},Jr=new Lr(24,24),ea={propagation:"stop"},ta={propagation:"stop",clickSequence:"break"},na=class{lastPointerDown=null;lastPointerUp=null;currentClickCount=1;createContext(e,t){return"pointer"!==e.type?{origin:t,pointer:null}:("pointer_down"===e.name&&(this.currentClickCount=this.isContinuation(e)?2:1,this.lastPointerDown=ct(e)),{origin:t,pointer:{clickCount:this.matchesCurrentPointer(e)?this.currentClickCount:1}})}complete(e,t,n){return"break"===n?.clickSequence?(this.reset(),null):"pointer"!==e.type||"pointer_up"!==e.name?null:this.matchesCurrentPointer(e)?(this.lastPointerUp=ct(e),(t.pointer?.clickCount??1)<2||"stop"===n?.propagation?null:{type:"double_click",timestamp:e.timestamp,pointerId:e.pointerId,button:e.button,buttons:e.buttons,pointerType:e.pointerType,screenPoint:e.screenPoint.clone(),pagePoint:e.pagePoint.clone(),pressure:e.pressure,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}):(this.reset(),null)}isContinuation(e){const t=this.lastPointerDown,n=this.lastPointerUp;return!!(t&&n&&n.timestamp>=t.timestamp&&e.timestamp-n.timestamp<=250&&n.screenPoint.dist2(e.screenPoint)<=1600&&lt(t,e)&&lt(n,e))}matchesCurrentPointer(e){return!this.lastPointerDown||lt(this.lastPointerDown,e)}reset(){this.lastPointerDown=null,this.lastPointerUp=null,this.currentClickCount=1}},ia={propagation:"stop",clickSequence:"break"},sa=class{editor;clickRecognizer=new na;activeRoutes=new WeakMap;constructor(e){this.editor=e}handle(e){const t=this.activeRoutes.get(e);return t?(t.effect=dt(t.effect,this.routeAfterInputs(e,t.context)),ht(t.effect)):ht(this.routeNewEvent(e,"external"))}cancelInteraction(e,t={}){this.routeNewEvent({type:"cancel",reason:e},"derived",t)}routeNewEvent(e,t,n){const i=this.clickRecognizer.createContext(e,t),s={context:i};this.activeRoutes.set(e,s);try{this.editor.inputs.handleEvent(e),s.effect=dt(s.effect,"cancel"===e.type?this.routeCancellation(e,i,n):this.routeAfterInputs(e,i));const t=this.clickRecognizer.complete(e,i,s.effect);return t&&(s.effect=dt(s.effect,this.routeNewEvent(t,"derived"))),s.effect}finally{this.activeRoutes.delete(e)}}routeAfterInputs(e,t){if("cancel"===e.type)return this.routeCancellation(e,t);if("pointer"===e.type&&"pointer_cancel"===e.name){const n=this.editor.interactions.broadcastEvent(this.editor,e,t),i=this.editor.tools.dispatch(e,t);return this.editor.interaction.clearSelection(),dt(dt(n,i),ia)}if((e=>"keyboard"===e.type&&"key_down"===e.name&&"Escape"===e.key&&!e.shiftKey&&!e.altKey&&!e.accelKey)(e))return this.routeEscape();const n=!!this.editor.state.shapeEditingSession.get(),i=this.editor.interactions.handleEvent(this.editor,e,t);return"stop"===i?.propagation||"double_click"===e.type||n&&"keyboard"===e.type?i:dt(i,this.editor.tools.dispatch(e,t))}routeCancellation(e,t,n={}){const i=!1===n.notifyInteractionHandlers?void 0:this.editor.interactions.broadcastEvent(this.editor,e,t),s=this.editor.tools.dispatch(e,t);return this.editor.interaction.clearSelection(),dt(dt(i,s),ia)}routeEscape(){const e=!this.editor.tools.isInInitialState(),t=!!this.editor.state.shapeEditingSession.get(),n=this.routeNewEvent({type:"cancel",reason:"escape"},"derived");return t&&this.editor.state.shapeEditingSession.get()&&this.editor.editing.cancel("user"),e||"select"===this.editor.state.tool.get().activeToolId||this.editor.commands.setActiveTool("select",{source:"system"}),dt(n,ia)}},oa=class{pressedKeyCodes;isSpacePressed;state;constructor(e){this.pressedKeyCodes=e.atom("inputs.pressedKeyCodes",new Set),this.isSpacePressed=e.computed("inputs.isSpacePressed",()=>this.pressedKeyCodes.get().has("Space")),this.state=e.atom("inputs.state",{originPagePoint:null,currentPagePoint:null,previousPagePoint:null,originScreenPoint:null,currentScreenPoint:null,previousScreenPoint:null,currentTimestamp:null,previousTimestamp:null,pageVelocity:pt(),screenVelocity:pt(),pointerId:null,pointerType:null,buttons:0,isPointing:!1,isDragging:!1,dragPhase:"idle",shiftKey:!1,altKey:!1,ctrlKey:!1,metaKey:!1,accelKey:!1})}setCurrentPointerPoint(e){this.state.update(t=>{if(t.currentPagePoint?.equals(e.pagePoint)&&t.currentScreenPoint?.equals(e.screenPoint)&&t.currentTimestamp===e.timestamp&&t.shiftKey===e.shiftKey&&t.altKey===e.altKey&&t.ctrlKey===e.ctrlKey&&t.metaKey===e.metaKey&&t.accelKey===e.accelKey)return t;const n=t.currentPagePoint??e.pagePoint,i=t.currentScreenPoint??e.screenPoint,s=t.currentTimestamp??e.timestamp,o=e.timestamp-s;return{...t,previousPagePoint:n,previousScreenPoint:i,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:s,currentTimestamp:e.timestamp,pageVelocity:ut(n,e.pagePoint,o),screenVelocity:ut(i,e.screenPoint,o),shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}})}handleEvent(e){switch(e.type){case"pointer":return void this.handlePointerEvent(e);case"keyboard":return void this.handleKeyboardEvent(e);case"wheel":return void this.handleWheelEvent(e);case"cancel":return this.resetPointer(),void("blur"!==e.reason&&"dispose"!==e.reason||this.resetKeyboard())}}resetPointer(){this.state.update(e=>({...e,originPagePoint:null,currentPagePoint:null,previousPagePoint:null,originScreenPoint:null,currentScreenPoint:null,previousScreenPoint:null,currentTimestamp:null,previousTimestamp:null,pageVelocity:pt(),screenVelocity:pt(),pointerId:null,pointerType:null,buttons:0,isPointing:!1,isDragging:!1,dragPhase:"idle"}))}handlePointerEvent(e){this.state.update(t=>{switch(e.name){case"pointer_down":return{...t,originPagePoint:e.pagePoint,currentPagePoint:e.pagePoint,previousPagePoint:e.pagePoint,originScreenPoint:e.screenPoint,currentScreenPoint:e.screenPoint,previousScreenPoint:e.screenPoint,currentTimestamp:e.timestamp,previousTimestamp:e.timestamp,pageVelocity:pt(),screenVelocity:pt(),pointerId:e.pointerId,pointerType:e.pointerType,buttons:e.buttons,isPointing:!0,isDragging:!1,dragPhase:"pointing",shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey};case"pointer_move":{if(t.currentPagePoint?.equals(e.pagePoint)&&t.currentScreenPoint?.equals(e.screenPoint)&&t.currentTimestamp===e.timestamp&&t.buttons===e.buttons&&gt(t,e))return t;const n=t.currentPagePoint??e.pagePoint,i=t.currentScreenPoint??e.screenPoint,s=t.isPointing&&(t.isDragging||(t.originScreenPoint??e.screenPoint).dist2(e.screenPoint)>=9),o=t.currentTimestamp??e.timestamp,r=e.timestamp-o;return{...t,previousPagePoint:n,previousScreenPoint:i,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:o,currentTimestamp:e.timestamp,pageVelocity:ut(n,e.pagePoint,r),screenVelocity:ut(i,e.screenPoint,r),buttons:e.buttons,isDragging:s,dragPhase:t.isPointing?s?"dragging":"pointing":"idle",shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}}case"pointer_up":case"pointer_cancel":return{...t,previousPagePoint:t.currentPagePoint,previousScreenPoint:t.currentScreenPoint,currentPagePoint:e.pagePoint,currentScreenPoint:e.screenPoint,previousTimestamp:t.currentTimestamp,currentTimestamp:e.timestamp,pageVelocity:pt(),screenVelocity:pt(),buttons:e.buttons,isPointing:!1,isDragging:!1,dragPhase:"idle",shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey}}})}handleKeyboardEvent(e){this.pressedKeyCodes.update(t=>{const n="key_down"===e.name;if(t.has(e.code)===n)return t;const i=new Set(t);return n?i.add(e.code):i.delete(e.code),i}),this.state.update(t=>gt(t,e)?t:{...t,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey})}resetKeyboard(){this.pressedKeyCodes.get().size>0&&this.pressedKeyCodes.set(new Set),this.state.update(e=>e.shiftKey||e.altKey||e.ctrlKey||e.metaKey||e.accelKey?{...e,shiftKey:!1,altKey:!1,ctrlKey:!1,metaKey:!1,accelKey:!1}:e)}handleWheelEvent(e){this.state.update(t=>gt(t,e)?t:{...t,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey})}},ra=class{handlers=[];registeredIds=new Set;register(e){this.registeredIds.has(e.id)||(this.handlers.push(e),this.handlers.sort((e,t)=>(t.priority??0)-(e.priority??0)),this.registeredIds.add(e.id))}getHandlers(){return this.handlers}handleEvent(e,t,n){let i;for(const s of this.handlers)if((!e.state.readonly.get()||!0===s.enabledInReadonly)&&(i=dt(i,s.editorEvent?.handleEvent(e,t,n)),"stop"===i?.propagation))return i;return i}broadcastEvent(e,t,n){let i;for(const s of this.handlers)i=dt(i,s.editorEvent?.handleEvent(e,t,n));return i}createSelectionHandleSession(e,t){if(e.state.readonly.get())return null;for(const n of this.handlers){const i=n.selectionHandle?.createSession(e,t);if(i)return i}return null}createShapePointerSession(e,t){if(e.state.readonly.get())return null;for(const n of this.handlers){const i=n.shapePointer?.createSession(e,t);if(i)return i}return null}},aa=class{editor;buffer;activeScopes=[];stateAtom;unsubscribeOperations;isDisposed=!1;state;constructor(e){this.editor=e,this.buffer=new kr,this.stateAtom=e.signals.atom("editor.history.state",{canUndo:!1,canRedo:!1},{isEqual:ft}),this.state=this.stateAtom,this.unsubscribeOperations=this.editor.operations.subscribe(e=>{this.handleCommit(e)})}clear(){this.buffer.clear(),this.publishEffectiveState()}activateScope(e){if(this.isDisposed)throw new Error("Cannot activate a history scope after disposal.");const t={scope:e,unsubscribe:()=>{}};return t.unsubscribe=e.subscribe(()=>{this.activeScopes.includes(t)&&this.publishEffectiveState()}),this.activeScopes.push(t),this.publishEffectiveState(),()=>{this.deactivateScope(t)}}dispose(){if(this.isDisposed)return;this.isDisposed=!0,this.unsubscribeOperations();let e=null;for(const n of this.activeScopes.splice(0).reverse())try{n.unsubscribe()}catch(t){e??=t}if(null!==e)throw e}undo(){return this.step("undo")}redo(){return this.step("redo")}getEntries(){return this.buffer.getEntries()}handleCommit(e){"record"===e.history&&"user"===e.source&&(this.buffer.append(e.diff,e.label),this.publishEffectiveState())}deactivateScope(e){const t=this.activeScopes.indexOf(e);if(!(t<0)){this.activeScopes.splice(t,1);try{e.unsubscribe()}finally{this.isDisposed||this.publishEffectiveState()}}}step(e){this.editor.assertDocumentWriteAllowed();const t=this.activeScopes.at(-1)?.scope;if(t){const n="undo"===e?t.undo():t.redo();return this.publishEffectiveState(),n}this.editor.interaction.cancelForCommand();const n="undo"===e?this.buffer.undo():this.buffer.redo();return!!n&&(this.replay(e,n),this.publishEffectiveState(),!0)}replay(e,t){try{this.editor.operations.run({kind:`history.${e}`,label:t.label,source:"history",history:"ignore"},()=>{const n="undo"===e?t.inverse:t.forward;S(this.editor).applyDiff(n,"history"),this.editor.snapshots.syncAfterDocumentRestore()})}catch(n){throw"undo"===e?this.buffer.rollbackUndo(t):this.buffer.rollbackRedo(t),this.publishEffectiveState(),n}}publishEffectiveState(){const e=this.activeScopes.at(-1)?.scope;var t;this.stateAtom.set({canUndo:(t=e?.getState()??{canUndo:this.buffer.canUndo,canRedo:this.buffer.canRedo}).canUndo,canRedo:t.canRedo})}},da=class{manager;state;constructor(e,t){this.manager=e,this.state=t}get id(){return this.state.id}get kind(){return this.state.kind}get source(){return this.state.source}get isActive(){return"active"===this.state.status}commit(){return this.manager.commit(this.state)}cancel(){this.manager.cancel(this.state)}},ca=class{editor;onUnhandledError;stack=[];commitListeners=new Set;commitQueue=[];nextOperationId=1;revision=0;isDrainingCommitQueue=!1;constructor(e,t=()=>{}){this.editor=e,this.onUnhandledError=t,S(e).listen(e=>this.handleStoreChange(e))}begin(e){const t=e.source??"user",n=this.getActiveState(),i={id:"operation:"+this.nextOperationId++,kind:e.kind,label:e.label??e.kind,source:t,history:e.history??("user"===t?"record":"ignore"),parent:n,diff:{added:[],updated:[],removed:[]},status:"active"};return this.stack.push(i),new da(this,i)}run(e,t){const n=this.begin(e);try{const e=t();return n.commit(),e}catch(i){throw n.isActive&&n.cancel(),i}}getActive(){const e=this.getActiveState();return e?new da(this,e):null}subscribe(e){return this.commitListeners.add(e),()=>{this.commitListeners.delete(e)}}commit(e){this.assertTopActive(e);const n=mt(e.diff);if(this.stack.pop(),e.status="committed",e.parent)return e.parent.diff=s(e.parent.diff,n),null;if(t(n))return null;const i={id:e.id,revision:++this.revision,kind:e.kind,label:e.label,source:e.source,history:e.history,diff:n,snapshot:yt(this.editor.snapshots.getDocument()),sessionSnapshot:It(this.editor.snapshots.getSession())};return this.enqueueCommit(i),i}cancel(e){this.assertTopActive(e);const n=mt(e.diff);if(!t(n))try{S(this.editor).applyDiff(i(n),e.source),this.editor.snapshots.syncAfterDocumentRestore()}catch(s){if(!t(mt(e.diff)))throw s;return this.stack.pop(),e.status="cancelled",void this.reportUnhandledError(s)}this.stack.pop(),e.status="cancelled"}handleStoreChange(e){const n=((e,t)=>({added:e.added.filter(t),updated:e.updated.filter(e=>t(e.before)&&t(e.after)),removed:e.removed.filter(t)}))(e.diff,m);if(t(n))return;const i=this.getActiveState();if(i)return void(i.diff=s(i.diff,n));const o=mt(n);t(o)||this.enqueueCommit({id:"operation:"+this.nextOperationId++,revision:++this.revision,kind:"editor.change",label:"change",source:e.source,history:"user"===e.source?"record":"ignore",diff:o,snapshot:yt(this.editor.snapshots.getDocument()),sessionSnapshot:It(this.editor.snapshots.getSession())})}getActiveState(){return this.stack.at(-1)??null}assertTopActive(e){if("active"!==e.status)throw new Error(`Editor operation "${e.kind}" is no longer active.`);if(this.getActiveState()!==e)throw new Error(`Editor operation "${e.kind}" must be completed in LIFO order.`)}enqueueCommit(e){if(this.commitQueue.push(e),!this.isDrainingCommitQueue){this.isDrainingCommitQueue=!0;try{for(;this.commitQueue.length>0;){const e=this.commitQueue.shift();for(const n of this.commitListeners)try{n(e)}catch(t){this.reportUnhandledError(t)}}}finally{this.isDrainingCommitQueue=!1}}}reportUnhandledError(e){try{this.onUnhandledError(e)}catch{}}},la=["owner","target","related"],ha=class{editor;state;bindingsOwnedByShapeSignals=new Map;bindingsTargetingShapeSignals=new Map;bindingsForShapeSignals=new Map;draftBindingIndex=null;unsubscribeFromStore;constructor(e){this.editor=e;const t=S(e);this.state=(e=>{const t=e.filter(g).sort(bt),n={bindingById:new Map,bindingIdsByOwnerShape:new Map,bindingIdsByTargetShape:new Map,relatedBindingIdsByShape:new Map};for(const i of t){n.bindingById.set(i.id,i),wt(n.bindingIdsByOwnerShape,i.ownerId,i.id),wt(n.relatedBindingIdsByShape,i.ownerId,i.id);for(const e of Bt(i))wt(n.bindingIdsByTargetShape,e,i.id),e!==i.ownerId&&wt(n.relatedBindingIdsByShape,e,i.id)}return n})(t.getAll()),this.unsubscribeFromStore=t.listen(e=>{this.handleStoreChange(e)})}dispose(){this.unsubscribeFromStore(),this.bindingsOwnedByShapeSignals.clear(),this.bindingsTargetingShapeSignals.clear(),this.bindingsForShapeSignals.clear(),this.draftBindingIndex=null}getBindingsOwnedByShape(e){const t=this.getDraftBindingIndex();return t?[...this.getDraftBindingsForRelation("owner",e,t)]:[...this.getBindingsOwnedByShapeSignal(e).get()]}getBindingsOwnedByShapeSignal(e){let t=this.bindingsOwnedByShapeSignals.get(e);return t||(t=this.editor.signals.atom(`editor.query.bindingsOwnedByShape.${e}`,this.getBindingsOwnedByState(this.state,e),{isEqual:J}),this.bindingsOwnedByShapeSignals.set(e,t)),t}getBindingsTargetingShape(e){const t=this.getDraftBindingIndex();return t?[...this.getDraftBindingsForRelation("target",e,t)]:[...this.getBindingsTargetingShapeSignal(e).get()]}getBindingsTargetingShapeSignal(e){let t=this.bindingsTargetingShapeSignals.get(e);return t||(t=this.editor.signals.atom(`editor.query.bindingsTargetingShape.${e}`,this.getBindingsTargetingState(this.state,e),{isEqual:J}),this.bindingsTargetingShapeSignals.set(e,t)),t}getBindingsForShape(e){const t=this.getDraftBindingIndex();return t?[...this.getDraftBindingsForRelation("related",e,t)]:[...this.getBindingsForShapeSignal(e).get()]}getBindingsForShapeSignal(e){let t=this.bindingsForShapeSignals.get(e);return t||(t=this.editor.signals.atom(`editor.query.bindingsForShape.${e}`,this.getBindingsForState(this.state,e),{isEqual:J}),this.bindingsForShapeSignals.set(e,t)),t}handleStoreChange(e){const t=this.state,n=((e,t)=>{const n=t.diff.added.filter(g),i=t.diff.updated.filter(Ct),s=t.diff.removed.filter(g);if(0===n.length&&0===i.length&&0===s.length)return e;const o={bindingById:new Map(e.bindingById),bindingIdsByOwnerShape:new Map(e.bindingIdsByOwnerShape),bindingIdsByTargetShape:new Map(e.bindingIdsByTargetShape),relatedBindingIdsByShape:new Map(e.relatedBindingIdsByShape)};for(const r of s)o.bindingById.delete(r.id),Mt(o,r);for(const{before:r,after:a}of i)kt(r,a)&&Mt(o,r);for(const r of n)o.bindingById.set(r.id,r);for(const{after:r}of i)o.bindingById.set(r.id,r);for(const r of n)Tt(o,r);for(const{before:r,after:a}of i)kt(r,a)&&Tt(o,a);return o})(t,e);n!==t&&(this.state=n,this.updateCachedSignals(e,n))}updateCachedSignals(e,t){const n=new Set,i=new Set,s=new Set,o=e=>{if(g(e)){n.add(e.ownerId),s.add(e.ownerId);for(const{targetId:t}of e.endpoints)i.add(t),s.add(t)}};for(const r of e.diff.added)o(r);for(const r of e.diff.removed)o(r);for(const r of e.diff.updated)o(r.before),o(r.after);for(const r of n)this.bindingsOwnedByShapeSignals.get(r)?.set(this.getBindingsOwnedByState(t,r));for(const r of i)this.bindingsTargetingShapeSignals.get(r)?.set(this.getBindingsTargetingState(t,r));for(const r of s)this.bindingsForShapeSignals.get(r)?.set(this.getBindingsForState(t,r))}getBindingsOwnedByState(e,t){return this.getBindingsForIds(e,e.bindingIdsByOwnerShape.get(t))}getBindingsTargetingState(e,t){return this.getBindingsForIds(e,e.bindingIdsByTargetShape.get(t))}getBindingsForState(e,t){return this.getBindingsForIds(e,e.relatedBindingIdsByShape.get(t))}getBindingsForIds(e,t){return t&&0!==t.length?t.map(t=>e.bindingById.get(t)).filter(e=>!!e):[]}getDraftBindingIndex(){const e=S(this.editor),t=e.getActiveTransactionRevision();return null===t?null:(this.draftBindingIndex?.revision===t||(this.draftBindingIndex=((e,t)=>{const n={revision:e,relations:{owner:Et(),target:Et(),related:Et()}};for(const i of t.removed)g(i)&&At(n,i,void 0);for(const i of t.updated)g(i.before)&&At(n,i.before,void 0),g(i.after)&&At(n,i.after,i.after);for(const i of t.added)g(i)&&At(n,i,i);return n})(t,e.getActiveTransactionDiff())),this.draftBindingIndex)}getDraftBindingsForRelation(e,t,n){return(({committed:e,draftIndex:t,relation:n,shapeId:i})=>{const s=t.relations[n],o=s.cacheByShape.get(i);if(o)return o;const r=s.changesByShape.get(i);if(!r)return s.cacheByShape.set(i,e),e;const a=new Map(e.map(e=>[e.id,e]));for(const[c,l]of r)l?a.set(c,l):a.delete(c);const d=Array.from(a.values()).sort(bt);return s.cacheByShape.set(i,d),d})({committed:"owner"===e?this.getBindingsOwnedByState(this.state,t):"target"===e?this.getBindingsTargetingState(this.state,t):this.getBindingsForState(this.state,t),draftIndex:n,relation:e,shapeId:t})}},pa=class{editor;signalsByShapeId=new Map;unsubscribeFromStore;constructor(e){this.editor=e,this.unsubscribeFromStore=e.listen(({diff:e})=>{for(const t of e.removed)p(t)&&this.signalsByShapeId.delete(t.id)})}dispose(){this.unsubscribeFromStore(),this.signalsByShapeId.clear()}getCachedShapeGeometry(e){return this.getOrCreateSignals(e).pageGeometry.get()}getShapePageBoundsSignal(e){return this.getOrCreateSignals(e).pageBounds}getShapeLocalToPageTransformSignal(e){return this.getOrCreateSignals(e).localToPageTransform}getShapeGeometry(e){return(e=>{if(e)return{bounds:e.bounds.clone(),center:e.center.clone(),corners:e.corners.map(e=>e.clone()),outlineVertices:e.outlineVertices.map(e=>e.clone())}})(this.getCachedShapeGeometry(e))}getShapeLocalToPageTransform(e){return Dt(this.getShapeLocalToPageTransformSignal(e).get())}getShapeParentToPageTransform(e){return e.startsWith("page:")?this.editor.pages.get(e)?Wr.Identity():void 0:Dt(this.getOrCreateSignals(e).localToPageTransform.get())}getShapePositionedToPageTransform(e){return Dt(this.getOrCreateSignals(e).positionedToPageTransform.get())}getShapePageBounds(e){return Xt(this.getShapePageBoundsSignal(e).get())??void 0}getShapePositionedBounds(e){return Xt(this.getOrCreateSignals(e).positionedBounds.get())??void 0}getShapePageCenter(e){return t=this.getCachedShapeGeometry(e)?.center,(t?t.clone():t)??void 0;var t}getShapePageCorners(e){return Ft(this.getCachedShapeGeometry(e)?.corners)}getShapePageOutlineVertices(e){return Ft(this.getCachedShapeGeometry(e)?.outlineVertices)}getShapeClipAncestorIds(e){return[...this.getShapeClipAncestorIdsSignal(e).get()]}getShapeClipAncestorIdsSignal(e){return this.getOrCreateSignals(e).clipAncestorIds}isPagePointInShapeClip(e,t){const n=this.editor.shapes.get(e);if(!n)return!1;for(const i of zt(this.editor,n,e=>this.editor.shapes.get(e))){const e=this.editor.shapes.getUtil(i).getChildClipLocalPolygons(i);if(!e||!E(e))continue;const n=this.getOrCreateSignals(i.id).localToPageTransform.get()?.tryInvert();if(!n||!R(n.applyToPoint(t),e))return!1}return!0}getShapeClippedPageBounds(e){const t=this.editor.shapes.get(e);let n=this.getShapePageBounds(e);if(!t||!n)return null;for(const i of zt(this.editor,t,e=>this.editor.shapes.get(e))){const e=this.editor.shapes.getUtil(i).getChildClipLocalPolygons(i),t=e?E(e):null,s=this.getOrCreateSignals(i.id).localToPageTransform.get();if(!t||!s)continue;const o=$t(n,_t(t,s));if(!o)return null;n=o}return n}getOrCreateSignals(e){let t=this.signalsByShapeId.get(e);if(!t){const n=e=>this.editor.shapes.getSignal(e).get(),i=this.editor.signals.computed(`editor.query.shapePositionedBounds.${e}`,()=>{const t=n(e);return t?this.editor.shapes.getUtil(t).getPositionedBounds(t):void 0},{isEqual:se}),s=this.editor.signals.computed(`editor.query.shapeLocalToPageTransform.${e}`,()=>{const t=n(e);return t?Ot(this.editor,t,n):void 0},{isEqual:Kt}),o=this.editor.signals.computed(`editor.query.shapeGeometry.${e}`,()=>{const t=n(e);if(!t)return;const i=Lt(this.editor,t.parentId,n);return i?ke(t,this.editor.shapes.getUtil(t),i):void 0},{isEqual:Yt});t={positionedBounds:i,pageGeometry:o,localToPageTransform:s,positionedToPageTransform:this.editor.signals.computed(`editor.query.shapePositionedToPageTransform.${e}`,()=>{const t=n(e);if(!t)return;const i=Lt(this.editor,t.parentId,n);return i?ve(t,this.editor.shapes.getUtil(t),i):void 0},{isEqual:Kt}),pageBounds:this.editor.signals.computed(`editor.query.shapePageBounds.${e}`,()=>o.get()?.bounds,{isEqual:se}),clipAncestorIds:this.editor.signals.computed(`editor.query.shapeClipAncestorIds.${e}`,()=>{const t=n(e);return t?zt(this.editor,t,n).map(e=>e.id):[]},{isEqual:J})},this.signalsByShapeId.set(e,t)}return t}},ua=class{editor;pagesSignal;currentPageShapeIdsSignal;currentPageShapesSignal;currentPageShapeTreeSignal;stateAtom;pagesAtom;pageShapeIdsSignals=new Map;unsubscribeFromStore;constructor(e,t){this.editor=e;const{atom:n,computed:i}=e.signals,s=S(e),o=s.getAll();this.stateAtom=n("editor.query.shapeTree",(e=>{const t=e.filter(l).sort((e,t)=>e.index.localeCompare(t.index)),n=e.filter(p).sort((e,t)=>e.parentId===t.parentId?((e,t)=>e.index.localeCompare(t.index))(e,t):e.parentId.localeCompare(t.parentId)),i=new Map,s=new Map,o=new Map,r=new Map(n.map(e=>[e.id,e]));for(const d of n)Nt(s,d.parentId,d.id);const a=(e,t)=>{for(const n of s.get(t)??[]){const t=r.get(n);t&&(Nt(i,e,t.id),o.set(t.id,e),a(e,t.id))}};for(const d of t)a(d.id,d.id);return{pageShapeIdsByPage:i,childShapeIdsByParent:s,pageIdByShape:o}})(o)),this.pagesAtom=n("editor.query.pages",o.filter(l).sort((e,t)=>e.index.localeCompare(t.index)),{isEqual:J}),this.pagesSignal=this.pagesAtom,this.unsubscribeFromStore=s.listen(e=>{this.handleStoreChange(e)}),this.currentPageShapeIdsSignal=i("editor.query.currentPageShapeIds",()=>this.getShapeIdsForPageSnapshot(t.get()),{isEqual:J}),this.currentPageShapesSignal=i("editor.query.currentPageShapes",()=>this.currentPageShapeIdsSignal.get().map(e=>this.editor.shapes.getSignal(e).get()).filter(e=>!!e)),this.currentPageShapeTreeSignal=i("editor.query.currentPageShapeTree",()=>this.currentPageShapeIdsSignal.get().map(e=>this.editor.shapes.getSignal(e).get()).filter(e=>!!e).map(e=>({id:e.id,parentId:e.parentId,type:e.type,subType:e.subType})),{isEqual:qt})}dispose(){this.unsubscribeFromStore(),this.pageShapeIdsSignals.clear()}getShapeIdsForPageSignal(e){let t=this.pageShapeIdsSignals.get(e);return t||(t=this.editor.signals.computed(`editor.query.pageShapeIds.${e}`,()=>this.getShapeIdsForPageSnapshot(e),{isEqual:J}),this.pageShapeIdsSignals.set(e,t)),t}getShapeIdsForPage(e){return[...this.getShapeIdsForPageSnapshot(e)]}getShapesForPage(e){return this.getShapeIdsForPageSnapshot(e).map(e=>this.editor.shapes.get(e)).filter(e=>!!e)}getChildShapeIds(e){return[...this.getChildShapeIdsSnapshot(e)]}getChildShapes(e){return this.getChildShapeIdsSnapshot(e).map(e=>this.editor.shapes.get(e)).filter(e=>!!e)}getDescendantShapeIds(e){const t=[],n=new Set,i=e=>{for(const s of this.getChildShapeIdsSnapshot(e))n.has(s)||(n.add(s),t.push(s),i(s))};return i(e),t}getPageIdForShape(e){return this.stateAtom.get().pageIdByShape.get(e)??null}getShapeIdsForPageSnapshot(e){return this.stateAtom.get().pageShapeIdsByPage.get(e)??[]}getChildShapeIdsSnapshot(e){return this.stateAtom.get().childShapeIdsByParent.get(e)??[]}handleStoreChange(e){const t=S(this.editor),n=this.stateAtom.peek(),i=((e,t,n)=>{const i=t.diff.added.filter(p),s=t.diff.updated.filter(Wt),o=t.diff.removed.filter(p);if(!(i.length>0||o.length>0||s.some(({before:e,after:t})=>e.parentId!==t.parentId||e.index!==t.index)))return e;const r={pageShapeIdsByPage:new Map(e.pageShapeIdsByPage),childShapeIdsByParent:new Map(e.childShapeIdsByParent),pageIdByShape:new Map(e.pageIdByShape)},a=e=>{const t=n(e);return p(t)?t.index:void 0},d=new Set,c=e=>{let t=e;const i=new Set;for(;t&&!i.has(t);){i.add(t);const e=n(t);if(!e)return null;if(l(e))return e.id;if(!p(e))return null;t=e.parentId}return null};for(const l of o){Ut(r.childShapeIdsByParent,l.parentId,l.id);const t=e.pageIdByShape.get(l.id);t&&d.add(t)}for(const{before:l,after:h}of s){if(l.parentId===h.parentId&&l.index===h.index)continue;Ut(r.childShapeIdsByParent,l.parentId,l.id),Ht(r.childShapeIdsByParent,h.parentId,h,a);const t=e.pageIdByShape.get(l.id);t&&d.add(t);const n=c(h.parentId);n&&d.add(n)}for(const l of i)Ht(r.childShapeIdsByParent,l.parentId,l,a);for(const l of i){const e=c(l.parentId);e&&d.add(e)}if(d.size>0){const t=new Map(e.pageShapeIdsByPage),i=new Map(e.pageIdByShape);for(const[n,o]of e.pageIdByShape)d.has(o)&&i.delete(n);const s=(e,t)=>{const o=[];for(const a of r.childShapeIdsByParent.get(t)??[])n(a)&&(o.push(a),i.set(a,e),o.push(...s(e,a)));return o};for(const e of d){const n=s(e,e);n.length>0?t.set(e,n):t.delete(e)}r.pageShapeIdsByPage=t,r.pageIdByShape=i}return r})(n,e,e=>t.get(e));i!==n&&this.stateAtom.set(i);const s=this.pagesAtom.peek(),o=((e,t)=>{if(!(t.diff.added.some(l)||t.diff.removed.some(l)||t.diff.updated.some(({before:e,after:t})=>l(e)||l(t))))return e;const n=new Map(e.map(e=>[e.id,e]));for(const i of t.diff.removed)l(i)&&n.delete(i.id);for(const i of t.diff.updated)l(i.before)&&n.delete(i.before.id),l(i.after)&&n.set(i.after.id,i.after);for(const i of t.diff.added)l(i)&&n.set(i.id,i);return Array.from(n.values()).sort((e,t)=>e.index.localeCompare(t.index))})(s,e);o!==s&&this.pagesAtom.set([...o])}},ga=class{entries;cellSize;cells=new Map;order=new Map;constructor(e){this.entries=e,this.cellSize=(e=>{if(0===e.length)return 256;let t=0;for(const n of e)t+=Math.max(n.queryBounds.w,n.queryBounds.h);return Math.max(16,Math.round(t/e.length)||256)})(e);for(let t=0;t<e.length;t+=1){const n=e[t];n&&(this.order.set(n,t),this.insert(n))}}cellKey(e,t){return`${e}:${t}`}insert(e){const t=Math.floor(e.queryBounds.minX/this.cellSize),n=Math.floor(e.queryBounds.minY/this.cellSize),i=Math.floor(e.queryBounds.maxX/this.cellSize),s=Math.floor(e.queryBounds.maxY/this.cellSize);for(let o=n;o<=s;o+=1)for(let n=t;n<=i;n+=1){const t=this.cellKey(n,o),i=this.cells.get(t);i?i.push(e):this.cells.set(t,[e])}}search(e){const t=Math.floor(e.minX/this.cellSize),n=Math.floor(e.minY/this.cellSize),i=Math.floor(e.maxX/this.cellSize),s=Math.floor(e.maxY/this.cellSize);if((i-t+1)*(s-n+1)>this.entries.length)return this.entries.filter(t=>t.queryBounds.intersects(e));const o=new Set,r=[];for(let a=n;a<=s;a+=1)for(let n=t;n<=i;n+=1){const t=this.cells.get(this.cellKey(n,a));if(t)for(const n of t)o.has(n)||(o.add(n),n.queryBounds.intersects(e)&&r.push(n))}return r.length>1&&r.sort((e,t)=>(this.order.get(e)??0)-(this.order.get(t)??0)),r}},fa=class{editor;shapeTree;geometry;pageIndexSignals=new Map;constructor(e,t,n){this.editor=e,this.shapeTree=t,this.geometry=n}getShapesInBounds(e,t){return this.getShapeIdsInBounds(e,t).map(e=>this.editor.shapes.get(e)).filter(e=>!!e)}getShapeIdsInBounds(e,t){return this.getPageIndex(t?.pageId).search(e).filter(t=>t.shapeBounds.intersects(e)).map(e=>e.shapeId)}getShapesInViewport(e,t){return this.getShapesInBounds(e,t)}getShapeIdsInViewport(e,t){return this.getShapeIdsInBounds(e,t)}getShapeAtPoint(e,t){return this.getShapesAtPoint(e,t)[0]??null}getShapesAtPoint(e,t){const n=this.getPageIndex(t?.pageId).search((e=>new zr(e.x-.5,e.y-.5,1,1))(e)),i=[];for(let s=n.length-1;s>=0;s-=1){const o=n[s];if(!o?.pointHitTestBounds.containsPoint(e))continue;const r=this.editor.shapes.get(o.shapeId);if(!r)continue;if(t?.filter&&!t.filter(r))continue;const a=this.editor.shapes.getUtil(r),d=this.geometry.getShapeParentToPageTransform(r.parentId);if(!d)continue;const c=Me(r,e,a,d),l={editor:this.editor,pagePoint:e,positionedPoint:c};("bindingTarget"===t?.hitTest?a.hitTestBindingTarget(r,c,l):a.hitTest(r,c,l)||this.editor.shapeHitTestDecorations.get(r.subType).some(e=>e.hitTest(r,c,l)))&&i.push(r)}return i}getShapesHitByLineSegment(e,t,n){const i=n?.margin??0,s=((e,t,n)=>zr.FromPoints([e,t]).expand(Math.max(.5,n)))(e,t,i),o=this.getPageIndex(n?.pageId).search(s),r=[];for(let a=o.length-1;a>=0;a-=1){const s=o[a];if(!s)continue;const d=this.geometry.getShapeClippedPageBounds(s.shapeId);if(!d||!Vt(e,t,d.expand(i)))continue;if(!this.doesLineSegmentIntersectShapeClip(s.shapeId,e,t,i))continue;const c=this.editor.shapes.get(s.shapeId);if(!c)continue;if(n?.filter&&!n.filter(c))continue;const l=this.editor.shapes.getUtil(c),h=this.geometry.getShapeParentToPageTransform(c.parentId);if(!h)continue;const p=Me(c,e,l,h),u=Me(c,t,l,h),g=this.geometry.getShapePositionedToPageTransform(c.id)?.tryInvert(),f=g?i*g.getMaximumLinearScale():i;l.hitTestLineSegment(c,{editor:this.editor,pageStart:e,pageEnd:t,pageMargin:i,positionedStart:p,positionedEnd:u,positionedMargin:f})&&r.push(c)}return r}doesLineSegmentIntersectShapeClip(e,t,n,i){for(const s of this.geometry.getShapeClipAncestorIds(e)){const e=this.editor.shapes.get(s);if(!e)return!1;const o=this.editor.shapes.getUtil(e).getChildClipLocalPolygons(e);if(!o)continue;const r=this.editor.shapes.computeLocalToPageTransform(e).tryInvert();if(!r)return!1;const a=i*Math.sqrt(r.a*r.a+r.b*r.b+r.c*r.c+r.d*r.d),d=r.applyToPoint(t),c=r.applyToPoint(n);if(!o.some(e=>K(d,c,e,a)))return!1}return!0}getPageIndexSignal(e){let t=this.pageIndexSignals.get(e);return t||(t=this.editor.signals.computed(`editor.spatialIndex.page.${e}`,()=>{const t=this.shapeTree.getShapeIdsForPageSignal(e).get(),n=[];for(const e of t){const t=this.editor.shapes.getSignal(e).get();if(!t)continue;this.editor.shapes.getUtil(t);const i=this.geometry.getShapePageBoundsSignal(e).get();if(!i)continue;const s=this.geometry.getShapePositionedToPageTransform(e);if(!s)continue;const o=jt(Qt(this.editor,t),s),r=zr.FromPoints([new Lr(i.minX,i.minY),new Lr(i.maxX,i.maxY),new Lr(o.minX,o.minY),new Lr(o.maxX,o.maxY)]);n.push({shapeId:e,shapeBounds:i,queryBounds:r,pointHitTestBounds:o})}return new ga(n)}),this.pageIndexSignals.set(e,t)),t}getPageIndex(e=this.editor.pages.getCurrentId()){return this.getPageIndexSignal(e).get()}},ma=class extends Error{constructor(e){super(e),this.name="SnapshotParseError"}},Sa=.001,ya=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"],Ia=["free","aspect_ratio_locked"],wa=class{editor;signals;selectedShapeItemsSignal;frameGeometrySignal;companionFrameGeometriesSignal;pathSignal;pageClipPathSignal;bindingSegmentsSignal;frameStyleSignal;handleAnchorsSignal;handlesSignal;constructor(e,t){this.editor=e,this.signals=t;const{computed:n}=e.signals;this.selectedShapeItemsSignal=n("editor.selectedShapeOverlayItems",()=>"select"!==t.tool.get().activeToolId?[]:t.selectedShapeIds.get().map(t=>e.shapes.getSignal(t).get()).filter(e=>!!e).map(t=>{const n=e.shapes.getUtil(t).getSelectionOverlayInfo(t,{editor:e});return{id:t.id,usesSelectionPathOverlay:n.usesSelectionPathOverlay,startPagePoint:n.startPagePoint,endPagePoint:n.endPagePoint,middlePagePoint:n.middlePagePoint,path:n.path,pathStyle:n.pathStyle,pageClipPath:n.pageClipPath??null,bindingSegments:n.bindingSegments??[]}}),{isEqual:Qn}),this.frameGeometrySignal=n("editor.selectionOverlayFrameGeometry",()=>{const t=this.selectedShapeItemsSignal.get();if(0===t.length)return null;if(gi(t))return null;const n=e.selection.getFrame();return n?{bounds:n.bounds,rotation:n.rotation,rotationCenter:n.rotationCenter}:null},{isEqual:Zn}),this.companionFrameGeometriesSignal=n("editor.selectionOverlayCompanionFrameGeometries",()=>{if("select"!==t.tool.get().activeToolId)return[];const n=[];for(const i of t.selectedShapes.get())for(const t of e.bindings.getForShape(i.id))n.push(...e.bindings.getUtil(t).getSelectionCompanionFrameGeometries?.(e,t,{selectedShape:i})??[]);return n},{isEqual:Jn}),this.pathSignal=n("editor.selectionOverlayPath",()=>{const e=this.selectedShapeItemsSignal.get();return gi(e)?e[0]?.path??null:null}),this.pageClipPathSignal=n("editor.selectionOverlayPageClipPath",()=>{const e=this.selectedShapeItemsSignal.get();return gi(e)?e[0]?.pageClipPath??null:null}),this.bindingSegmentsSignal=n("editor.selectionOverlayBindingSegments",()=>{const e=this.selectedShapeItemsSignal.get();return gi(e)?[...e[0]?.bindingSegments??[]]:[]},{isEqual:Ln}),this.frameStyleSignal=n("editor.selectionOverlayFrameStyle",()=>{const e=t.cameraZoom.get();return{strokeWidth:2/e,cornerRadius:3/e}},{isEqual:ei}),this.handleAnchorsSignal=n("editor.selectionOverlayHandleAnchors",()=>{if("select"!==t.tool.get().activeToolId)return null;const n=t.selectedShapes.get();if(0===n.length)return null;const i=e.selection.getFrame(),s=t.cameraZoom.get(),o=1===n.length,r=e.selection.canResize(),a=e.selection.canRotate();return((t,n,i,s,d,c,l)=>{const h=t.map(t=>(t=>e.shapes.getUtil(t).getSelectionHandleAnchors(t,{isOnlySelected:o,editor:e}))(t)),p=t.every(t=>(t=>r&&e.shapes.getUtil(t).canUseSelectionResizeHandles(t,{editor:e}))(t)),u=t.every(t=>(t=>a&&e.shapes.getUtil(t).canUseSelectionRotateHandle(t,{editor:e}))(t)),g=new Set(l),f=h.flatMap(e=>e.terminalHandleAnchors),m=h.flatMap(e=>e.middleHandleAnchors),S=h.flatMap(e=>e.customHandleAnchors??[]),y=f.length>0||m.length>0||S.length>0;if(!n)return{resizeHandleAnchors:[],rotateHandleAnchors:[],terminalHandleAnchors:f,middleHandleAnchors:m,customHandleAnchors:S};const{bounds:I,rotation:w,rotationCenter:P,hasCompatibleRotation:b}=n,v=t[0]?.rotation??w,x=8/i,C=14/i,M=I.w<2*x,T=I.h<2*x,B=e=>0===w?e:Lr.RotWith(e,P,w),k=new Lr(I.minX,I.minY),E=new Lr(I.center.x,I.minY),A=new Lr(I.maxX,I.minY),R=new Lr(I.maxX,I.center.y),K=new Lr(I.maxX,I.maxY),Y=new Lr(I.center.x,I.maxY),X=new Lr(I.minX,I.maxY),F=new Lr(I.minX,I.center.y);return{resizeHandleAnchors:!p||y?[]:[{kind:"resize",id:"top_left",point:B(k)},...M?[]:[{kind:"resize",id:"top",point:B(E)}],...M&&T?[]:[{kind:"resize",id:"top_right",point:B(A)}],...T?[]:[{kind:"resize",id:"right",point:B(R)}],...M||T?[]:[{kind:"resize",id:"bottom_right",point:B(K)}],...M?[]:[{kind:"resize",id:"bottom",point:B(Y)}],...M||T?[]:[{kind:"resize",id:"bottom_left",point:B(X)}],...T?[]:[{kind:"resize",id:"left",point:B(F)}]].filter(e=>g.has(e.id)),rotateHandleAnchors:!u||y||!b||M||T?[]:[{kind:"rotate",id:"bottom_left_rotate",point:B(ui({bounds:I,rotateOffset:C,referenceRotation:v,frameRotation:w}))}],terminalHandleAnchors:f,middleHandleAnchors:m,customHandleAnchors:S}})(n,i,s,0,0,0,((e,t,n)=>{if(0===t.length)return[];const i=1===t.length,s=t.map(t=>e.shapes.getUtil(t).getSelectionResizeHandleIds(t,{editor:e,isOnlyResizeTarget:i})),o=Gn(e,t,n);return ya.filter(n=>s.every(e=>e.includes(n))&&Vn(e,t,n,o).length>0)})(e,e.selection.getResizeTargets(),i?.rotation??0))},{isEqual:pi}),this.handlesSignal=n("editor.selectionOverlayHandles",()=>{const e=this.handleAnchorsSignal.get();if(!e)return null;const n=t.cameraZoom.get(),{resizeHandles:i,rotateHandles:s,terminalHandles:o,middleHandles:r,customHandles:a}=((e,t)=>{const n=8/t,i=n/2,s=e=>new zr(e.x-i,e.y-i,n,n);return{resizeHandles:e.resizeHandleAnchors.map(e=>({...e,bounds:s(e.point)})),rotateHandles:e.rotateHandleAnchors.map(e=>({...e,bounds:s(e.point)})),terminalHandles:e.terminalHandleAnchors.map(e=>({...e,bounds:s(e.point)})),middleHandles:e.middleHandleAnchors.map(e=>({...e,bounds:s(e.point)})),customHandles:e.customHandleAnchors.map(e=>({...e,bounds:s(e.point)}))}})(e,n);return{resizeHandles:i,rotateHandles:s,terminalHandles:o,middleHandles:r,customHandles:a,strokeWidth:2/n}},{isEqual:hi})}hitTestHandle(e){const t=this.handlesSignal.get();return t?function({point:e,selectionFrame:t,handles:n,hitDistance:i}){const{middleHandles:s,terminalHandles:o,customHandles:r,resizeHandles:a,rotateHandles:d}=n;for(const c of s)if(c.bounds.expand(i).containsPoint(e))return c;for(const c of o)if(c.bounds.expand(i).containsPoint(e))return c;for(const c of r)if(c.bounds.expand(i).containsPoint(e))return c;for(const c of a)if(c.bounds.containsPoint(e))return c;if(t){const n=((e,t,n,i)=>{const s=new Set(n.map(e=>e.id)),o=_n(e,t),{bounds:r}=t,a=[];o.x>=r.minX&&o.x<=r.maxX&&(s.has("top")&&a.push({id:"top",distance:Math.abs(o.y-r.minY)}),s.has("bottom")&&a.push({id:"bottom",distance:Math.abs(o.y-r.maxY)})),o.y>=r.minY&&o.y<=r.maxY&&(s.has("right")&&a.push({id:"right",distance:Math.abs(o.x-r.maxX)}),s.has("left")&&a.push({id:"left",distance:Math.abs(o.x-r.minX)}));const d=a.filter(e=>e.distance<=i).sort((e,t)=>e.distance-t.distance)[0];return d?{kind:"resize",id:d.id,point:e.clone(),bounds:new zr(e.x-i,e.y-i,2*i,2*i)}:null})(e,t,a,i);if(n)return n}for(const c of d)if(c.bounds.expand(i).containsPoint(e))return c;return null}({point:e,selectionFrame:this.editor.selection.getFrame(),handles:t,hitDistance:6/this.signals.cameraZoom.get()}):null}},Pa=class{editor;entryRequestAtom;entryRequestSignal;nextEntryRequestId=1;operation=null;constructor(e){this.editor=e,this.entryRequestAtom=e.signals.atom("editor.shapeEditingEntryRequest",null),this.entryRequestSignal=this.entryRequestAtom}canEditShape(e){const t="string"==typeof e?this.editor.shapes.get(e):e;return!!t&&!t.isLocked&&this.editor.shapes.getUtil(t).canEdit(t)}start(e,t="user"){let n=this.editor.shapes.get(e.shapeId);if(!n||!this.canEditShape(n))return null;const i=this.editor.state.shapeEditingSession.get();if(i?.shapeId===n.id){const s={...i,entryMode:e.entryMode??i.entryMode,caretPagePoint:e.caretPagePoint?{...e.caretPagePoint}:i.caretPagePoint};return this.editor.session.update({editingShapeId:n.id,shapeEditingSession:s},t),this.publishEntryRequest({shapeId:n.id,entryMode:s.entryMode,caretPagePoint:s.caretPagePoint}),s}if(e.preserveInteraction||this.editor.interaction.cancelForCommand(),this.editor.state.shapeEditingSession.get()&&!this.complete(t))return null;if(n=this.editor.shapes.get(e.shapeId),!n||!this.canEditShape(n))return null;const s=e.operationKind??`editing:${n.id}`;if(e.reuseActiveOperation){const e=this.editor.operations.getActive();if(!e||e.source!==t)throw new Error("Shape editing can only reuse an active operation with the same source.");this.operation=e}else this.operation=this.editor.operations.begin({kind:s,label:"shape.edit",source:"user",history:"record"});const o={shapeId:n.id,operationKind:s,entryMode:e.entryMode??"focusEnd",caretPagePoint:e.caretPagePoint?{...e.caretPagePoint}:void 0,isComposing:!1};return this.editor.commands.setSelectedShapeIds([n.id],{source:t}),this.editor.session.update({editingShapeId:n.id,shapeEditingSession:o},t),this.publishEntryRequest({shapeId:n.id,entryMode:o.entryMode,caretPagePoint:o.caretPagePoint}),o}complete(e="user"){const t=this.editor.state.shapeEditingSession.get();return!!t&&!t.isComposing&&(this.end({runEditEnd:!0,source:e}),this.commitOperation(),!0)}cancel(e="user"){const t=this.editor.state.shapeEditingSession.get();return!!t&&!t.isComposing&&(this.editor.session.update({editingShapeId:null,shapeEditingSession:null},e),this.cancelOperation(),!0)}setComposition(e,t="system"){const n=this.editor.state.shapeEditingSession.get();n&&n.isComposing!==e&&this.editor.session.update({shapeEditingSession:{...n,isComposing:e}},t)}consumeEntryRequest(e){const t=this.entryRequestAtom.get();t&&t.id===e&&this.entryRequestAtom.set(null)}removeShapeIds(e,t="system"){const n=this.editor.state.shapeEditingSession.get();n&&e.includes(n.shapeId)&&(this.end({runEditEnd:!1,source:t}),this.commitOperation())}prepareForShapeRemoval(e,t="system"){const n=this.editor.state.shapeEditingSession.get();if(!n||!e.includes(n.shapeId))return;this.editor.tools.isInInitialState()||this.editor.interaction.cancelForCommand();const i=this.editor.state.shapeEditingSession.get();i&&e.includes(i.shapeId)&&(this.end({runEditEnd:!1,source:t}),this.commitOperation())}end(e){const t=this.editor.state.shapeEditingSession.get();if(!t)return;this.entryRequestAtom.set(null);const n=this.editor.shapes.get(t.shapeId);if(this.editor.session.update({editingShapeId:null,shapeEditingSession:null},e.source),!e.runEditEnd||!n)return;const i=this.editor.shapes.getUtil(n).onEditEnd(n,{editor:this.editor});i?.deleteShapeIds&&i.deleteShapeIds.length>0&&this.editor.commands.deleteShapes(i.deleteShapeIds,{source:e.source})}cancelOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.cancel()}commitOperation(){const e=this.operation;this.operation=null,e?.isActive&&e.commit()}publishEntryRequest(e){this.entryRequestAtom.set({id:this.nextEntryRequestId++,shapeId:e.shapeId,entryMode:e.entryMode,caretPagePoint:e.caretPagePoint?{...e.caretPagePoint}:void 0})}},ba=class extends Error{},va=class{editor;unsubscribeFromStore;shapeSignals=new Map;contentCutoutLocalPolygonSignals=new Map;selectedSignals=new Map;renderOrderSignals=new Map;renderVisibleSignals=new Map;documentVisibleSignals=new Map;effectiveOpacitySignals=new Map;editingSessionSignals=new Map;dropTargetSignals=new Map;hoveredSignals=new Map;constructor(e){this.editor=e,this.unsubscribeFromStore=e.listen(({diff:e})=>{for(const t of e.removed)p(t)&&this.evict(t.id)})}dispose(){this.unsubscribeFromStore(),this.shapeSignals.clear(),this.contentCutoutLocalPolygonSignals.clear(),this.selectedSignals.clear(),this.renderOrderSignals.clear(),this.renderVisibleSignals.clear(),this.documentVisibleSignals.clear(),this.effectiveOpacitySignals.clear(),this.editingSessionSignals.clear(),this.dropTargetSignals.clear(),this.hoveredSignals.clear()}isDocumentHidden(e){return!1===Di(this.editor,e,e=>this.editor.shapes.get(e))}getShapeSignal(e){let t=this.shapeSignals.get(e);return t||(t=this.editor.signals.computed(`editor.shape.${e}`,()=>{const t=this.editor.store.getRecordSignal(e).get();return p(t)?t:void 0}),this.shapeSignals.set(e,t)),t}getContentCutoutLocalPolygonsSignal(e){let t=this.contentCutoutLocalPolygonSignals.get(e);return t||(t=this.editor.signals.computed(`editor.shapeContentCutouts.${e}`,()=>{const t=this.getShapeSignal(e).get();return t?this.editor.bindings.getTargetingShapeSignal(e).get().flatMap(n=>{const i=this.getShapeSignal(n.ownerId).get();return i?n.endpoints.filter(({targetId:t})=>t===e).flatMap(e=>this.editor.bindings.getUtil(n).getTargetShapeContentCutoutLocalPolygons?.(this.editor,n,{ownerShape:i,endpoint:e,targetShape:t})??[]):[]}):[]},{isEqual:ie}),this.contentCutoutLocalPolygonSignals.set(e,t)),t}getSelectedSignal(e){let t=this.selectedSignals.get(e);return t||(t=this.editor.signals.computed(`editor.shapeSelected.${e}`,()=>this.editor.state.selectedShapeIdSet.get().has(e)),this.selectedSignals.set(e,t)),t}getRenderOrderSignal(e){let t=this.renderOrderSignals.get(e);return t||(t=this.editor.signals.computed(`editor.shapeRenderOrder.${e}`,()=>this.editor.render.viewport.shapeOrderById.get().get(e)??-1),this.renderOrderSignals.set(e,t)),t}getRenderVisibleSignal(e){let t=this.renderVisibleSignals.get(e);return t||(t=this.editor.signals.computed(`editor.shapeRenderVisible.${e}`,()=>{const t=this.editor.shapes.getClipAncestorIdsSignal(e).get().length>0;return this.editor.render.viewport.visibleShapeIdSet.get().has(e)&&this.getDocumentVisibleSignal(e).get()&&(!t||null!==this.editor.shapes.getClippedPageBounds(e))}),this.renderVisibleSignals.set(e,t)),t}getDocumentVisibleSignal(e){let t=this.documentVisibleSignals.get(e);return t||(t=this.editor.signals.computed(`editor.shapeDocumentVisible.${e}`,()=>Di(this.editor,e,e=>this.getShapeSignal(e).get())??!1),this.documentVisibleSignals.set(e,t)),t}getEffectiveOpacitySignal(e){let t=this.effectiveOpacitySignals.get(e);return t||(t=this.editor.signals.computed(`editor.shapeEffectiveOpacity.${e}`,()=>{const t=new Set([e]);let n=1,i=this.getShapeSignal(e).get();for(;i&&(n*=i.opacity,i.parentId.startsWith("shape:"));){const e=i.parentId;if(t.has(e))break;t.add(e),i=this.getShapeSignal(e).get()}return n}),this.effectiveOpacitySignals.set(e,t)),t}getEditingSessionSignal(e){let t=this.editingSessionSignals.get(e);return t||(t=this.editor.signals.computed(`editor.shapeEditingSessionForShape.${e}`,()=>{const t=this.editor.state.shapeEditingSession.get();return t?.shapeId===e?t:null}),this.editingSessionSignals.set(e,t)),t}getDropTargetSignal(e){let t=this.dropTargetSignals.get(e);return t||(t=this.editor.signals.computed(`editor.shapeDropTarget.${e}`,()=>this.editor.render.interaction.dropTargetShapeId.get()===e),this.dropTargetSignals.set(e,t)),t}getHoveredSignal(e){let t=this.hoveredSignals.get(e);return t||(t=this.editor.signals.computed(`editor.shapeHovered.${e}`,()=>{const t=this.editor.render.interaction.hoveredShapeId.get();if(!t)return!1;const n=this.getShapeSignal(e).get();return!!n&&this.editor.shapes.getUtil(n).getHoverDecorationTargetId(n,{editor:this.editor})===t}),this.hoveredSignals.set(e,t)),t}evict(e){this.shapeSignals.delete(e),this.contentCutoutLocalPolygonSignals.delete(e),this.selectedSignals.delete(e),this.renderOrderSignals.delete(e),this.renderVisibleSignals.delete(e),this.documentVisibleSignals.delete(e),this.effectiveOpacitySignals.delete(e),this.editingSessionSignals.delete(e),this.dropTargetSignals.delete(e),this.hoveredSignals.delete(e)}},xa=["corner","edge_midpoint","corner","edge_midpoint","center","edge_midpoint","corner","edge_midpoint","corner"],Ca={corner:0,edge_midpoint:1,center:2,custom:3},Ma=class{editor;constructor(e){this.editor=e}createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t}){return this.createBoundsSnapSnapshot({movingShapeIds:e,coordinateSpace:t})}createResizeSnapshot({resizingShapeIds:e,coordinateSpace:t}){return this.createBoundsSnapSnapshot({movingShapeIds:e,coordinateSpace:t})}createHandleSnapshot({context:e,currentPagePoint:t,allowSelfSnap:n=!1,excludedShapeIds:i=[]}){const s=this.editor.shapes.get(e.shapeId),o=new Set(this.editor.layers.includeDescendants([e.shapeId]));this.collectBindingDrivenExcludedShapeIds([e.shapeId],o);for(const l of i)o.add(l);const r=[],a=[],d=this.getSnapScopeParentId([e.shapeId]),c=this.getCandidateShapeIds({excludedShapeIds:o,scopeParentId:d});s&&n&&this.collectSelfHandleSnapGeometry({shape:s,context:e,currentPagePoint:t,points:r,outlines:a});for(const l of c){const e=this.editor.shapes.get(l);e&&this.collectHandleSnapGeometry({shape:e,points:r,outlines:a})}return{points:r,outlines:a,scopeParentId:d,candidateShapeIds:c}}collectHandleSnapGeometry({shape:e,points:t,outlines:n}){const i=this.editor.shapes.getUtil(e);if(!i.canSnap(e,{editor:this.editor}))return;const s=this.editor.shapes.getClippedPageBounds(e.id);if(!s)return;const o=this.editor.shapes.computeLocalToPageTransform(e),r=i.getHandleSnapGeometry(e);for(const l of r.points??[]){const n=Es(l),i=o.applyToPoint(n.point);this.editor.shapes.isPagePointInClip(e.id,i)&&t.push({id:`${e.id}:point:${t.length}`,nodeId:e.id,point:i,kind:n.kind,weight:n.weight})}const a=r.outline;if(null===a)return;const d=this.editor.shapes.getClipAncestorIds(e.id).length>0?es(s):(a??(c=i.getLocalBounds(e),[new Lr(c.minX,c.minY),new Lr(c.maxX,c.minY),new Lr(c.maxX,c.maxY),new Lr(c.minX,c.maxY)])).map(e=>o.applyToPoint(e));var c;d.length>0&&n.push({id:e.id,points:d})}collectSelfHandleSnapGeometry({shape:e,context:t,currentPagePoint:n,points:i,outlines:s}){const o=this.editor.shapes.getUtil(e);if(!o.canSnap(e,{editor:this.editor}))return;const r=this.editor.shapes.getClippedPageBounds(e.id);if(!r)return;const a=o.getHandleSnapGeometry(e),d=this.editor.shapes.computeLocalToPageTransform(e),c={...t,currentPagePoint:n.clone()};for(const p of a.getSelfSnapPoints?.(c)??[]){const t=Es(p),n=d.applyToPoint(t.point);this.editor.shapes.isPagePointInClip(e.id,n)&&i.push({id:`${e.id}:self-point:${i.length}`,nodeId:e.id,point:n,kind:t.kind,weight:t.weight})}const l=a.getSelfSnapOutline?.(c)??null;if(!l)return;const h=this.editor.shapes.getClipAncestorIds(e.id).length>0?es(r):l.map(e=>d.applyToPoint(e));h.length>0&&s.push({id:e.id,points:h})}createBoundsSnapSnapshot({movingShapeIds:e,coordinateSpace:t}){const n=Array.from(e),i=new Set(this.editor.layers.includeDescendants(n));this.collectBindingDrivenExcludedShapeIds(n,i);const s=[],o=[],r={rotation:t.rotation,rotationCenter:t.rotationCenter},a=this.getSnapScopeParentId(n),d=this.getCandidateShapeIds({excludedShapeIds:i,scopeParentId:a});for(const c of d){const e=this.editor.shapes.get(c);if(!e)continue;const n=this.editor.shapes.getUtil(e);if(!n.canSnap(e,{editor:this.editor}))continue;const i=this.editor.shapes.getClippedPageBounds(e.id);if(!i)continue;const a=(this.editor.shapes.getClipAncestorIds(e.id).length>0?es(i):this.editor.shapes.getPageOutlineVertices(e.id)).map(e=>0===t.rotation?e.clone():_n(e,r));if(0===a.length)continue;const d=zr.FromPoints(a);o.push({id:e.id,bounds:d});const l=n.getBoundsSnapGeometry(e).points,h=[];if(void 0===l)Hi(d).forEach((e,t)=>{h.push({point:e,kind:xa[t]??"custom"})});else{const n=this.editor.shapes.computeLocalToPageTransform(e);for(const i of l){const s=Es(i),o=n.applyToPoint(s.point);this.editor.shapes.isPagePointInClip(e.id,o)&&h.push({point:0===t.rotation?o:_n(o,r),kind:s.kind,weight:s.weight})}}h.forEach((t,n)=>{s.push({id:`${e.id}:${n}`,nodeId:e.id,point:t.point,kind:t.kind,weight:t.weight})})}return{points:s,pointIndex:cs(s),nodes:o,coordinateSpace:{rotation:t.rotation,rotationCenter:t.rotationCenter.clone()},scopeParentId:a,candidateShapeIds:d}}collectBindingDrivenExcludedShapeIds(e,t){const n=new Set,i=[...e];for(;i.length>0;){const e=i.pop();if(!e||n.has(e))continue;n.add(e);const s=this.editor.shapes.get(e);if(s)for(const n of this.editor.bindings.getForShape(e)){const o=n.ownerId===e,r=n.endpoints.filter(({targetId:t})=>t===e).map(({slot:e})=>e);if(!o&&0===r.length)continue;const a=this.editor.bindings.getUtil(n).getGeometryDependentShapeIds?.(this.editor,n,{shape:s,owner:o,endpointSlots:r})??[];for(const e of a)for(const n of this.editor.layers.includeDescendants([e]))t.has(n)||(t.add(n),i.push(n))}}}getSnapScopeParentId(e){let t=null;for(const n of e){const e=this.editor.shapes.get(n);if(e)if(t){if(e.parentId!==t)return this.editor.pages.getCurrentId()}else t=e.parentId}return t??this.editor.pages.getCurrentId()}getCandidateShapeIds({excludedShapeIds:e,scopeParentId:t}){const n=this.editor.pages.getCurrentId(),i=this.editor.render.viewport.pageBounds.get(),s=new Set;if(t?.startsWith("shape:")){const e=this.editor.shapes.get(t);e&&this.editor.shapes.getUtil(e).canSnapChildrenToSelf(e)&&s.add(e.id)}const o=t??n;for(const r of this.editor.layers.getChildIds(o))s.add(r);return(null===i?Array.from(s):this.editor.shapes.getIdsInBounds(i,{pageId:n}).filter(e=>s.has(e))).filter(n=>{if(e.has(n))return!1;const s=this.editor.shapes.get(n);if(!s||s.parentId!==o)return n===t;const r=this.editor.shapes.getClippedPageBounds(n);return!!r&&(!i||r.intersects(i))})}},Ta=class{diagnostics;gapCache=new WeakMap;_indicatorsSignal;indicatorsSignal;activeSignal;snapshots;axisSnapMemory={x:null,y:null};constructor(e,t={}){this.diagnostics=t,this._indicatorsSignal=e.signals.atom("editor.snapIndicators",[]),this.indicatorsSignal=this._indicatorsSignal,this.activeSignal=e.signals.computed("editor.snapIndicatorsActive",()=>this._indicatorsSignal.get().length>0),this.snapshots=new Ma(e)}setIndicators(e){const t=e.map(ks);ys(this._indicatorsSignal.get(),t)||this._indicatorsSignal.set(t)}clearIndicators(){this._indicatorsSignal.get().length>0&&this._indicatorsSignal.set([]),this.clearAxisSnapMemory()}clearAxisSnapMemory(){this.axisSnapMemory.x=null,this.axisSnapMemory.y=null}getSwitchDistance(e){return Math.min(.25*e,2)}getReleaseThreshold(e){return 1.5*e}updateAxisSnapMemory(e,t){this.axisSnapMemory[e]=t?{type:t.type,id:t.id,candidatePointIds:"points"===t.type?t.candidatePointIds:void 0}:null}reportDiagnostics(e){this.diagnostics.onEvaluation?.(e)}getNow(){return this.diagnostics.now?.()??Date.now()}createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t}){const n=this.snapshots.createTranslateSnapshot({movingShapeIds:e,coordinateSpace:t});return this.gapCache.set(n,{x:os(n.nodes,"x"),y:os(n.nodes,"y")}),n}createResizeSnapshot({resizingShapeIds:e,coordinateSpace:t}){return this.snapshots.createResizeSnapshot({resizingShapeIds:e,coordinateSpace:t})}createHandleSnapshot(e){return this.snapshots.createHandleSnapshot(e)}snapTranslate(e){const t=this.getNow(),n=Zi(e.initialSelectionBounds,e.dragDelta),i=(s=Hi(e.initialSelectionBounds),o=e.dragDelta,s.map(e=>e.add(o)));var s,o;const r=this.gapCache.get(e.snapshot)??{x:os(e.snapshot.nodes,"x"),y:os(e.snapshot.nodes,"y")},a=this.getReleaseThreshold(e.threshold),d=this.getSwitchDistance(e.threshold),c=this.axisSnapMemory.x,l=this.axisSnapMemory.y,h={candidatePointCount:0,matchedPointCount:0},p="y"===e.lockedAxis?null:Ss(fs("x",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===c?.type?new Set(c.candidatePointIds??[]):void 0,releaseThreshold:a,selectionPointKinds:xa,switchDistance:d,stats:h}),ds("x",n,r.x,e.threshold,{previousSnapId:"gaps"===c?.type?c.id:null,releaseThreshold:a,switchDistance:d}),{previousSnap:c,switchDistance:d}),u="x"===e.lockedAxis?null:Ss(fs("y",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===l?.type?new Set(l.candidatePointIds??[]):void 0,releaseThreshold:a,selectionPointKinds:xa,switchDistance:d,stats:h}),ds("y",n,r.y,e.threshold,{previousSnapId:"gaps"===l?.type?l.id:null,releaseThreshold:a,switchDistance:d}),{previousSnap:l,switchDistance:d}),g=new Lr(p?.nudge??0,u?.nudge??0),f=[];return"points"===p?.type?f.push(...Ps("x",p,g,e.snapshot.coordinateSpace)):"gaps"===p?.type&&f.push(Bs(p,e.snapshot.coordinateSpace,g)),"points"===u?.type?f.push(...Ps("y",u,g,e.snapshot.coordinateSpace)):"gaps"===u?.type&&f.push(Bs(u,e.snapshot.coordinateSpace,g)),this.setIndicators(f),this.updateAxisSnapMemory("x",p),this.updateAxisSnapMemory("y",u),this.reportDiagnostics({operation:"translate",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:e.snapshot.nodes.length,candidatePointCount:h.candidatePointCount,candidateGapCount:("y"===e.lockedAxis?0:r.x.length)+("x"===e.lockedAxis?0:r.y.length),matchedPointCount:h.matchedPointCount,xSnapId:p?.id??null,ySnapId:u?.id??null,indicatorCount:f.length}),{nudge:g,indicators:f}}snapResize(e){const t=this.getNow(),n=$i({handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY}),i=ms(n,e.resizedSelectionBounds),s="top"===n||"bottom"===n,o="left"===n||"right"===n,r=this.getReleaseThreshold(e.threshold),a=this.getSwitchDistance(e.threshold),d=this.axisSnapMemory.x,c=this.axisSnapMemory.y,l={candidatePointCount:0,matchedPointCount:0},h=s?null:fs("x",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===d?.type?new Set(d.candidatePointIds??[]):void 0,releaseThreshold:r,switchDistance:a,stats:l}),p=o?null:fs("y",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===c?.type?new Set(c.candidatePointIds??[]):void 0,releaseThreshold:r,switchDistance:a,stats:l}),u={x:null!==h,y:null!==p},g=new Lr(h?.nudge??0,p?.nudge??0);if(e.isAspectRatioLocked&&Oi(f=n)!==Li(f)&&zi(f)!==_i(f)&&(0!==g.x||0!==g.y)){const t=h&&p?Math.abs(g.x)<Math.abs(g.y)?"x":"y":h?"x":"y",i=0===e.initialSelectionBounds.h?1:e.initialSelectionBounds.w/e.initialSelectionBounds.h;"x"===t?(u.y=!1,g.y=g.x/i,"bottom_left"!==n&&"top_right"!==n||(g.y=-g.y)):(u.x=!1,g.x=g.y*i,"bottom_left"!==n&&"top_right"!==n||(g.x=-g.x))}var f;const m=function(e,t){const n=$i({handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY});let i=e.resizedSelectionBounds.minX,s=e.resizedSelectionBounds.maxX,o=e.resizedSelectionBounds.minY,r=e.resizedSelectionBounds.maxY;e.isResizingFromCenter?(Oi(n)?(i+=t.x,s-=t.x):Li(n)&&(i-=t.x,s+=t.x),zi(n)?(o+=t.y,r-=t.y):_i(n)&&(o-=t.y,r+=t.y)):(Oi(n)?i+=t.x:Li(n)&&(s+=t.x),zi(n)?o+=t.y:_i(n)&&(r+=t.y));const a=(({minX:e,minY:t,maxX:n,maxY:i})=>{const s=Math.min(e,n),o=Math.min(t,i),r=Math.max(e,n),a=Math.max(t,i);return new zr(s,o,Math.max(1,r-s),Math.max(1,a-o))})({minX:i,minY:o,maxX:s,maxY:r});if(!e.isAspectRatioLocked){const t=(({startBounds:e,bounds:t,handleId:n,scaleX:i,scaleY:s,isResizingFromCenter:o=!1})=>{const r=Ni({axis:"x",startBounds:e,bounds:t,handleId:n,scale:i,isResizingFromCenter:o}),a=Ni({axis:"y",startBounds:e,bounds:t,handleId:n,scale:s,isResizingFromCenter:o});return{scaleX:Oi(n)||Li(n)?r*(t.w/Math.max(1,e.w)):i??1,scaleY:zi(n)||_i(n)?a*(t.h/Math.max(1,e.h)):s??1}})({startBounds:e.initialSelectionBounds,bounds:a,handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY,isResizingFromCenter:e.isResizingFromCenter});return{bounds:a,scaleX:t.scaleX,scaleY:t.scaleY}}return Ui({startBounds:e.initialSelectionBounds,bounds:a,handleId:e.handleId,aspectRatio:0===e.initialSelectionBounds.h?1:e.initialSelectionBounds.w/e.initialSelectionBounds.h,isResizingFromCenter:e.isResizingFromCenter,scaleX:e.scaleX,scaleY:e.scaleY})}(e,g),{bounds:S}=m,y=ms("any",S),I=[];if(u.x){const t=fs("x",y,e.snapshot.pointIndex,1e-8,{stats:l});t&&I.push(...Ms("x",t,Lr.Zero(),e.snapshot.coordinateSpace,S,e.snapshot.nodes))}if(u.y){const t=fs("y",y,e.snapshot.pointIndex,1e-8,{stats:l});t&&I.push(...Ms("y",t,Lr.Zero(),e.snapshot.coordinateSpace,S,e.snapshot.nodes))}return this.setIndicators(I),this.updateAxisSnapMemory("x",u.x?h:null),this.updateAxisSnapMemory("y",u.y?p:null),this.reportDiagnostics({operation:"resize",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:e.snapshot.nodes.length,candidatePointCount:l.candidatePointCount,candidateGapCount:0,matchedPointCount:l.matchedPointCount,xSnapId:u.x?h?.id??null:null,ySnapId:u.y?p?.id??null:null,indicatorCount:I.length}),{nudge:g,bounds:S,scaleX:m.scaleX,scaleY:m.scaleY,indicators:I}}snapHandle(e){const t=this.getNow();if("none"===e.mode)return this.clearIndicators(),this.reportDiagnostics({operation:"handle",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:0,outlineCount:e.snapshot.outlines.length,candidatePointCount:e.snapshot.points.length,candidateGapCount:0,matchedPointCount:0,indicatorCount:0}),null;const n="point"===e.mode?this.snapHandlePoint(e):this.snapHandleAlign(e);return n?(this.setIndicators(n.indicators),this.reportDiagnostics({operation:"handle",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:0,outlineCount:e.snapshot.outlines.length,candidatePointCount:e.snapshot.points.length,candidateGapCount:0,matchedPointCount:n.indicators.length,indicatorCount:n.indicators.length}),n):(this.clearIndicators(),this.reportDiagnostics({operation:"handle",durationMs:this.getNow()-t,pointCount:e.snapshot.points.length,nodeCount:0,outlineCount:e.snapshot.outlines.length,candidatePointCount:e.snapshot.points.length,candidateGapCount:0,matchedPointCount:0,indicatorCount:0}),null)}snapHandlePoint(e){const t=As(e);let n=null,i=null,s=e.threshold*e.threshold;for(const a of t)for(const t of e.snapshot.points){const e=a.dist2(t.point);e>s||(s=e,n=t.point,i=a)}if(!n)for(const a of t)for(const t of e.snapshot.outlines){const e=is(a,t.points);!e||e.distanceSquared>s||(s=e.distanceSquared,n=e.point,i=a)}if(!n||!i)return null;const o=n.sub(i);return{snappedPagePoint:e.pagePoint.add(o),nudge:o,indicators:[(r=n,{id:Cs("x",[r,r],[r]),type:"points",axis:"x",line:[r.clone(),r.clone()],points:[r.clone()],rotation:0,rotationCenter:r.clone()})]};var r}snapHandleAlign(e){const t=As(e);let n=null,i=null,s=null,o=null,r=e.threshold,a=e.threshold;for(const h of t)for(const t of e.snapshot.points){const e=Math.abs(t.point.x-h.x);e<=r&&(r=e,n=t.point,s=h);const d=Math.abs(t.point.y-h.y);d<=a&&(a=d,i=t.point,o=h)}if(!n&&!i)return null;const d=new Lr(n&&s?n.x-s.x:0,i&&o?i.y-o.y:0),c=e.pagePoint.add(d),l=[];return n&&s&&l.push(Ts("x",s.add(d),n)),i&&o&&l.push(Ts("y",o.add(d),i)),{snappedPagePoint:c,nudge:d,indicators:l}}},Ba=class{editor;_brushBoxSignal;brushBoxSignal;brushBoxActiveSignal;_bindingPreviewSignal;bindingPreviewSignal;bindingPreviewActiveSignal;_terminalBindingGuidesSignal;terminalBindingGuidesSignal;_dropTargetShapeIdSignal;dropTargetShapeIdSignal;_hoveredShapeIdSignal;hoveredShapeIdSignal;_selectionTranslationActiveSignal;selectionTranslationActiveSignal;terminalBindingResolver=(e,t)=>(({rawPagePoint:e})=>({pagePoint:e.clone(),binding:null,preview:null}))(t);constructor(e){this.editor=e;const{atom:t,computed:n}=e.signals;this._brushBoxSignal=t("editor.brushBox",null),this.brushBoxSignal=this._brushBoxSignal,this.brushBoxActiveSignal=n("editor.brushBoxActive",()=>null!==this._brushBoxSignal.get()),this._bindingPreviewSignal=t("editor.bindingPreview",null),this.bindingPreviewSignal=this._bindingPreviewSignal,this.bindingPreviewActiveSignal=n("editor.bindingPreviewActive",()=>null!==this._bindingPreviewSignal.get()),this._terminalBindingGuidesSignal=t("editor.terminalBindingGuides",[]),this.terminalBindingGuidesSignal=this._terminalBindingGuidesSignal,this._dropTargetShapeIdSignal=t("editor.dropTargetShapeId",null),this.dropTargetShapeIdSignal=this._dropTargetShapeIdSignal,this._hoveredShapeIdSignal=t("editor.hoveredShapeId",null),this.hoveredShapeIdSignal=this._hoveredShapeIdSignal,this._selectionTranslationActiveSignal=t("editor.selectionTranslationActive",!1),this.selectionTranslationActiveSignal=this._selectionTranslationActiveSignal}setBrushBox(e){se(this._brushBoxSignal.get(),e)||this._brushBoxSignal.set(e?e.clone():null)}setBindingPreview(e){var t,n;(t=this._bindingPreviewSignal.get())===(n=e)||(t&&n?t.terminal===n.terminal&&t.targetShapeId===n.targetShapeId&&te(t.rawPagePoint,n.rawPagePoint)&&te(t.resolvedPagePoint,n.resolvedPagePoint)&&(t.guidePath??null)===(n.guidePath??null):t===n)||this._bindingPreviewSignal.set(e?{...e,rawPagePoint:e.rawPagePoint.clone(),resolvedPagePoint:e.resolvedPagePoint.clone()}:null)}setTerminalBindingGuides(e){const t=e??[];((e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n],s=t[n];if(!i||!s||!zn(i,s))return!1}return!0})(this._terminalBindingGuidesSignal.get(),t)||this._terminalBindingGuidesSignal.set(t.map(Dn))}setDropTargetShapeId(e){this._dropTargetShapeIdSignal.get()!==e&&this._dropTargetShapeIdSignal.set(e)}setHoveredShapeId(e){this._hoveredShapeIdSignal.get()!==e&&this._hoveredShapeIdSignal.set(e)}setSelectionTranslationActive(e){this._selectionTranslationActiveSignal.get()!==e&&this._selectionTranslationActiveSignal.set(e)}setSnapIndicators(e){e?this.editor.snaps.setIndicators(e):this.editor.snaps.clearIndicators()}setTerminalBindingResolver(e){this.terminalBindingResolver=e}resolveTerminalBinding(e){return this.terminalBindingResolver(this.editor,e)}clearSelectionTransients(){this.setBrushBox(null),this.setBindingPreview(null),this.setTerminalBindingGuides(null),this.setDropTargetShapeId(null),this.setHoveredShapeId(null),this.setSelectionTranslationActive(!1),this.setSnapIndicators(null)}},ka=class{editor;animationScheduler;_viewportScreenSizeSignal;viewportScreenSizeSignal;_cameraLockSignal;cameraLockSignal;animationFrame=null;animationGeneration=0;constructor(e,t){this.editor=e,this.animationScheduler=t,this._viewportScreenSizeSignal=e.signals.atom("editor.viewportScreenSize",{w:0,h:0}),this.viewportScreenSizeSignal=this._viewportScreenSizeSignal,this._cameraLockSignal=e.signals.atom("editor.cameraLock",null),this.cameraLockSignal=this._cameraLockSignal}getCurrentCamera(){return this.editor.state.camera.get()}getCamera(e=this.editor.pages.getCurrentId()){return this.editor.state.session.get().pageCameraById[e]??Yr}pageToScreen(e,t=this.editor.pages.getCurrentId()){const n=this.getCamera(t);return new e.constructor((e.x-n.x)*n.z,(e.y-n.y)*n.z)}screenToPage(e,t=this.editor.pages.getCurrentId()){const n=this.getCamera(t);return new e.constructor(e.x/n.z+n.x,e.y/n.z+n.y)}setCamera(e,t){this.cancelAnimation(),this.writeCamera(e,t)}setLock(e){if(null===e)return this.cancelAnimation(),this._cameraLockSignal.set(null),!0;if(!Number.isFinite(e.x)||!Number.isFinite(e.y))return!1;this.cancelAnimation(),this.editor.interaction.cancelForCommand();const t=this.editor.pages.getCurrentId();return this._cameraLockSignal.set({pageId:t,pagePoint:{x:e.x,y:e.y}}),this.writeCamera({},{pageId:t,source:"system"}),!0}animateCameraTo(e,t){this.cancelAnimation();const n=this.animationScheduler,i=t.pageId??this.editor.pages.getCurrentId(),s=t.source??"system",o=this.getCamera(i),r=Number.isFinite(t.durationMs)&&t.durationMs>0?t.durationMs:0;if(!n||!0===n.prefersReducedMotion?.()||0===r||(a=o).x===(d=e).x&&a.y===d.y&&a.z===d.z)return void this.writeCamera(e,{pageId:i,source:s});var a,d;const c=this.animationGeneration;let l=null;const h=t=>{if(c!==this.animationGeneration)return;l??=t;const a=Math.min(1,Math.max(0,(t-l)/r)),d=(e=>1-(1-e)**3)(a);this.writeCamera({x:Ys(o.x,e.x,d),y:Ys(o.y,e.y,d),z:Ys(o.z,e.z,d)},{pageId:i,source:s}),c===this.animationGeneration&&(this.animationFrame=a>=1?null:{handle:n.requestFrame(h)})};this.animationFrame={handle:n.requestFrame(h)}}cancelAnimation(){this.animationGeneration+=1,this.animationFrame&&(this.animationScheduler?.cancelFrame(this.animationFrame.handle),this.animationFrame=null)}dispose(){this.cancelAnimation()}writeCamera(e,t){const n=t?.source??"system",i=t?.pageId??this.editor.pages.getCurrentId(),s=this.getCamera(i);let o="number"==typeof e.x?e.x:s.x,r="number"==typeof e.y?e.y:s.y;const a=kn("number"==typeof e.z?e.z:s.z),d=this._cameraLockSignal.peek();if(d?.pageId===i){const e=this._viewportScreenSizeSignal.peek();e.w>0&&e.h>0?(o=d.pagePoint.x-e.w/(2*a),r=d.pagePoint.y-e.h/(2*a)):(o=s.x,r=s.y)}const c={x:o,y:r,z:a};c.x===s.x&&c.y===s.y&&c.z===s.z||this.editor.session.update({pageCameraById:{...this.editor.state.session.get().pageCameraById,[i]:c}},n)}panCamera(e,t="system"){const n=this.getCurrentCamera();this.setCamera({x:n.x+e.x/n.z,y:n.y+e.y/n.z},{source:t})}zoomCameraAtScreenPoint(e,t,n="system"){const i=kn(this.getCurrentCamera().z*Math.exp(.0015*-t));this.zoomCameraToScreenPoint(e,i,n)}zoomCameraToScreenPoint(e,t,n="system"){const i=kn(t),s=this.screenToPage(e);this.setCamera({x:s.x-e.x/i,y:s.y-e.y/i,z:i},{source:n})}zoomAtViewportCenter(e,t="system"){const n=this.viewportScreenSizeSignal.get(),i=new Lr(n.w/2,n.h/2);this.zoomCameraAtScreenPoint(i,e,t)}resetZoom(e="user"){const t=this.viewportScreenSizeSignal.get(),n=new Lr(t.w/2,t.h/2),i=this.screenToPage(n);this.editor.commands.setCamera({camera:{x:i.x-n.x,y:i.y-n.y,z:1}},{source:e})}setViewportScreenSize(e){const t={w:Math.max(0,e.w),h:Math.max(0,e.h)},n=this._viewportScreenSizeSignal.get();n.w===t.w&&n.h===t.h||(this._viewportScreenSizeSignal.set(t),this._cameraLockSignal.peek()&&this.writeCamera({},{source:"system"}))}},Ea=class{shapeRenderOrderByIdSignal;culledShapeIdsSignal;culledShapeIdSetSignal;selectedShapeIdsOutsideCulledSignal;selectedShapeIdsOutsideCulledSetSignal;renderVisibleShapeIdsSignal;retainedShapeIdsSignal;renderVisibleShapeIdSetSignal;renderItemsSignal;retainedBaseShapeWindowSnapshotSignal;retainedShapeWindowSnapshotSignal;constructor(e,t){const{computed:n}=e.signals;this.shapeRenderOrderByIdSignal=n("editor.shapeRenderOrderById",()=>{const e=new Map;for(const[n,i]of t.currentPageShapeIds.get().entries())e.set(i,n);return e}),this.culledShapeIdsSignal=n("editor.culledShapeIds",()=>{const n=t.currentPageId.get(),i=t.renderViewportPageBounds.get();return i?e.shapes.getIdsInViewport(i,{pageId:n}):t.currentPageShapeIds.get()},{isEqual:J}),this.retainedBaseShapeWindowSnapshotSignal=n("editor.retainedBaseShapeWindowSnapshot",e=>{const n=t.currentPageShapeIds.get(),i=null!==t.viewportPageBounds.get(),s=((e,t,n=0)=>Fs(e.map(e=>t.get(e)).filter(e=>void 0!==e).map(e=>({start:e,end:e+1})),n))(this.culledShapeIdsSignal.get(),this.getPageIndexById(n));if(e!==xr&&e&&e.viewportReady&&s.length>0){const t=((e,t)=>{if(e.length!==t.length||0===t.length)return null;const n=t.map((n,i)=>{const s=e[i];if(!s)return null;if(s.end+2<n.start||s.start>n.end+2)return null;const o=i>0?t[i-1]:null,r=i<t.length-1?t[i+1]:null,a=r?r.start-3:1/0,d={start:Math.min(n.start,Math.max(o?o.end+3:-1/0,s.start)),end:Math.max(n.end,Math.min(a,s.end))};return d.end-d.start>n.end-n.start+4?null:d});if(n.some(e=>null===e))return null;const i=n;if(Fs(i).length!==t.length)return null;const s=Os(t);return Os(i)>s+12?null:i})(Fs(e.ranges.map(e=>({...e}))),s);if(t)return zs(n,t,{viewportReady:i})}return zs(n,s,{viewportReady:i})},{isEqual:(e,t)=>J(e.shapeIds,t.shapeIds)}),this.culledShapeIdSetSignal=n("editor.culledShapeIdSet",()=>new Set(this.culledShapeIdsSignal.get()),{isEqual:ee}),this.selectedShapeIdsOutsideCulledSignal=n("editor.selectedShapeIdsOutsideCulled",()=>{const e=t.selectedShapeIds.get();if(0===e.length)return[];const n=this.culledShapeIdSetSignal.get();return e.filter(e=>!n.has(e))},{isEqual:J}),this.selectedShapeIdsOutsideCulledSetSignal=n("editor.selectedShapeIdsOutsideCulledSet",()=>new Set(this.selectedShapeIdsOutsideCulledSignal.get()),{isEqual:ee}),this.renderVisibleShapeIdsSignal=n("editor.renderVisibleShapeIds",()=>{if(0===this.selectedShapeIdsOutsideCulledSignal.get().length)return this.culledShapeIdsSignal.get();const e=this.culledShapeIdSetSignal.get(),n=this.selectedShapeIdsOutsideCulledSetSignal.get();return t.currentPageShapeIds.get().filter(t=>e.has(t)||n.has(t))},{isEqual:J}),this.retainedShapeWindowSnapshotSignal=n("editor.retainedShapeWindowSnapshot",e=>{const n=t.currentPageShapeIds.get(),i=null!==t.viewportPageBounds.get(),s=this.retainedBaseShapeWindowSnapshotSignal.get().shapeIds,o=(r=s.length)<=0?0:Xs(Math.ceil(.5*r),12,96);var r;const a=((e,t,n,i)=>{if(0===e.length)return[];const s=new Map;for(const[a,d]of e.entries())s.set(d,a);const o=Fs(t.map(e=>s.get(e)).filter(e=>void 0!==e).sort((e,t)=>e-t).map(e=>({start:e,end:e+1})),2),r=[];if(o.length>0){const t=Xs(Math.ceil(i/(2*o.length)),8,32);for(const[n,i]of o.entries()){const s=n>0?o[n-1]:null,a=n<o.length-1?o[n+1]:null,d=a?a.start-i.end:1/0,c=Ds(s?i.start-s.end:1/0,t),l=Ds(d,t+4);r.push({start:Math.max(0,i.start-c),end:Math.min(e.length,i.end+l)})}}for(const a of n){const e=s.get(a);void 0!==e&&r.push({start:e,end:e+1})}return 0===r.length?[]:Fs(r,2)})(n,s,this.selectedShapeIdsOutsideCulledSetSignal.get(),o);if(i&&e!==xr&&e&&e.viewportReady&&e.ranges.length>0&&a.length>0){const t=Fs(e.ranges.map(e=>({...e})));if(((e,t)=>{if(0===t.length)return!0;if(0===e.length)return!1;let n=0;for(const i of t){for(;n<e.length;){const t=e[n];if(t&&i.start>=t.start&&i.end<=t.end)break;if(!(t&&i.end>t.end))return!1;n+=1}if(n>=e.length)return!1}return!0})(t,a))return zs(n,t,{viewportReady:i});const s=((e,t,n)=>{const i=t.map((n,i)=>{const s={...n};for(const t of e)t.end+6<n.start||t.start>n.end+6||(s.start=Math.min(s.start,t.start),s.end=Math.max(s.end,t.end));const o=i>0?t[i-1]:null,r=i<t.length-1?t[i+1]:null,a=r?r.start-3:1/0;return{start:Math.min(n.start,Math.max(o?o.end+3:-1/0,s.start)),end:Math.max(n.end,Math.min(a,s.end))}});if(Fs(i).length!==t.length)return null;const s=Os(t);return Os(i)>s+n?null:i})(t,a,o);if(s)return zs(n,s,{viewportReady:i})}return zs(n,a,{viewportReady:i})},{isEqual:(e,t)=>J(e.shapeIds,t.shapeIds)}),this.retainedShapeIdsSignal=n("editor.retainedShapeIds",()=>this.retainedShapeWindowSnapshotSignal.get().shapeIds,{isEqual:J}),this.renderVisibleShapeIdSetSignal=n("editor.renderVisibleShapeIdSet",()=>new Set(this.renderVisibleShapeIdsSignal.get()),{isEqual:ee}),this.renderItemsSignal=n("editor.renderItems",()=>{const n=t.selectedShapeIdSet.get(),i=[];for(const t of this.renderVisibleShapeIdsSignal.get()){const s=e.shapes.getSignal(t).get(),o=e.shapes.getPageBoundsSignal(t).get();s&&!s.isHidden&&o&&i.push({id:s.id,shape:s,bounds:o,isSelected:n.has(s.id)})}return i},{isEqual:Ks})}getPageIndexById(e){const t=new Map;for(const[n,i]of e.entries())t.set(i,n);return t}},Aa=class{signals=e();store;[Xr];inputs;tools;cameraManager;editing;shapeUtils=new Vr;shapeSvgExporters=new Ur;shapeSvgDecorations=new Hr;shapeHitTestDecorations=new Gr;bindingUtils=new Or;interactions=new ra;runtime=new qr;bindingQueries;shapeGeometryQueries;shapeTreeIndex;selectionGeometry;bindingManager;spatialIndex;snaps;renderWindowManager;shapeSignals;selectionOverlay;interactionManager;eventRouter;history;operations;commands;state;render;_shapeDefaultPropsByTypeSignal;assetUrlResolver=()=>null;_readonlySignal;writesClosed=!1;document={getMetadata:()=>{const e=this.store.get(Ar);return h(e)?e:void 0},updateMetadata:(e,t="user")=>this.commands.updateDocumentMeta({patch:e},{source:t}),setReadonly:e=>{if(!this.writesClosed&&this._readonlySignal.get()!==e){if(e){this.interaction.cancelForCommand(),this.state.shapeEditingSession.get()?.isComposing&&this.editing.setComposition(!1,"system"),this.editing.cancel("system");const e=this.state.tool.get().activeToolId;"select"!==e&&"hand"!==e&&this.tools.select("select","system")}this._readonlySignal.set(e)}}};session={get:()=>{const e=this.store.get(Kr);if(!u(e))throw new Error("Missing session record");return e},update:(e,t="system")=>{Le(this,e,t)}};pages={getAll:()=>this.state.pages.get(),get:e=>{const t=this.store.get(e);return l(t)?t:void 0},getCurrentId:()=>this.state.currentPageId.get(),createAndSelect:(e,t="user")=>{const n=this.commands.createPage(e,{source:t});return this.commands.setCurrentPageId(n.id,{source:t}),n},select:(e,t="user")=>{this.commands.setCurrentPageId(e,{source:t})},rename:(e,t,n="user")=>{this.commands.renamePage({id:e,name:t},{source:n})},updateMetadata:(e,t,n="user")=>this.commands.updatePageMeta({id:e,patch:t},{source:n}),delete:(e,t="user")=>(this.interaction.cancelForCommand(),this.commands.deletePage(e,{source:t}))};selection={getIds:(e=this.pages.getCurrentId())=>this.session.get().pageSelectedShapeIdsById[e]??[],set:(e,t)=>{Oe(this,e,t)},remove:(e,t="system")=>{((e,t,n="system")=>{if(0===t.length)return;const i=new Set(t),s=e.session.get(),o={};for(const r of e.pages.getAll())o[r.id]=(s.pageSelectedShapeIdsById[r.id]??[]).filter(e=>!i.has(e));e.session.update({pageSelectedShapeIdsById:o},n)})(this,e,t)},delete:(e="user")=>{this.shapes.delete(this.selection.getIds(),e)},createClipboardPayload:()=>Ee(this),pasteClipboardPayload:e=>(this.interaction.cancelForCommand(),Ae(this,e)),duplicate:(e={})=>(this.interaction.cancelForCommand(),((e,t={})=>{const n=Ee(e);return n?Ae(e,{payload:n,offset:t.offset??Jr,source:t.source}):[]})(this,e)),selectAll:(e="user")=>{this.interaction.cancelForCommand(),((e,t="user")=>{const n=e.pages.getCurrentId(),i=e.state.currentPageShapeIds.get().map(t=>e.shapes.get(t)).filter(t=>!!t&&t.parentId===n&&!e.shapes.isHidden(t.id)).map(e=>e.id);e.commands.setSelectedShapeIds(i,{source:t})})(this,e)},resetRotation:(e="user")=>{((e,t="user")=>{if(!e.selection.canRotate())return;const n=e.state.selectedShapes.get().filter(t=>e.shapes.getUtil(t).contributesToSelectionFrame(t,{editor:e}));if(0===n.length)return;const i=n.flatMap(t=>{const n=fn(e,t);if(!n)return[];const i=mn(e,t,n,{id:t.id,rotation:0});return i?[i]:[]});i.length>0&&e.commands.updateShapes(i,{source:t})})(this,e)},flip:(e,t="user")=>{const n=function(e,t){if(!e.selection.canFlip())return[];const n=e.selection.getTransformTargets(),i=e.selection.getFrame()??((e,t)=>{const n=t.flatMap(t=>{const n=fn(e,t);return n?e.shapes.getUtil(t).getSelectionPagePoints(n)??[]:[]});if(0===n.length)return null;const i=zr.FromPoints(n);return{bounds:i,rotation:0,rotationCenter:i.center,hasCompatibleRotation:!0}})(e,n);return i&&0!==n.length?n.map(n=>((e,t,n,i)=>{const s=e.shapes.getUtil(t),o=fn(e,t);if(!o)return null;const r=s.getSelectionPagePoints(o);if(!r&&!s.contributesToSelectionFrame(t,{editor:e}))return null;const a=(({points:e,transform:t})=>0===e.length?null:zr.FromPoints(e.map(e=>_n(e,t))))({points:r?[...r]:s.getPositionedOutlineVertices(t).map(n=>e.shapes.computePositionedToPageTransform(t).applyToPoint(n)),transform:n});return a?mn(e,t,o,s.flipSelectionBounds(o,{axis:i,selectionBounds:n.bounds,selectionLocalBounds:Wn({axis:i,bounds:a,selectionBounds:n.bounds}),selectionRotation:n.rotation,selectionRotationCenter:n.rotationCenter})):null})(e,n,i,t)).filter(e=>null!==e):[]}(this,e);0!==n.length&&(this.interaction.cancelForCommand(),this.commands.updateShapes(n,{source:t}))},canAlign:()=>Kn(this,2),align:(e,t="user")=>(this.interaction.cancelForCommand(),((e,t,n="user")=>{const i=Yn(e);if(i.length<2)return!1;const s=Xn(e,i[0].shape.parentId);if(!s)return!1;const o=zr.FromPoints(i.flatMap(e=>[new Lr(e.bounds.minX,e.bounds.minY),new Lr(e.bounds.maxX,e.bounds.maxY)])),r=i.map(({shape:e,bounds:n})=>{let i=0,r=0;switch(t){case"left":i=o.minX-n.minX;break;case"right":i=o.maxX-n.maxX;break;case"horizontal-center":i=o.center.x-n.center.x;break;case"top":r=o.minY-n.minY;break;case"bottom":r=o.maxY-n.maxY;break;case"vertical-center":r=o.center.y-n.center.y}const a=Fn(s,new Lr(i,r));return{id:e.id,x:e.x+a.x,y:e.y+a.y}});return e.commands.updateShapes(r,{source:n}),!0})(this,e,t)),canDistribute:()=>Kn(this,3),distribute:(e,t="user")=>(this.interaction.cancelForCommand(),((e,t,n="user")=>{const i=Yn(e);if(i.length<3)return!1;const s=Xn(e,i[0].shape.parentId);if(!s)return!1;const o="horizontal"===t,r=e=>o?e.w:e.h,a=e=>o?e.minX:e.minY,d=o?"x":"y",c=[...i].sort((e,t)=>e.bounds.center[d]-t.bounds.center[d]),l=c[0].bounds,h=c[c.length-1].bounds,p=((o?h.maxX:h.maxY)-a(l)-c.reduce((e,t)=>e+r(t.bounds),0))/(c.length-1);let u=a(l);const g=c.map(({shape:e,bounds:t},n)=>{const i=0===n||n===c.length-1?a(t):u,d=i-a(t);u=i+r(t)+p;const l=Fn(s,o?new Lr(d,0):new Lr(0,d));return{id:e.id,x:e.x+l.x,y:e.y+l.y}});return e.commands.updateShapes(g,{source:n}),!0})(this,e,t)),canResize:()=>(e=>{const t=Tn(e),n=1===t.length;return t.length>0&&t.every(t=>e.shapes.getUtil(t).canParticipateInSelectionResize(t,{editor:e,isOnlyAffectedShape:n}))})(this),canFlip:()=>Mn(this),canRotate:()=>(e=>{const t=Tn(e),n=1===t.length;return t.length>0&&t.every(t=>e.shapes.getUtil(t).canParticipateInSelectionRotation(t,{editor:e,isOnlyAffectedShape:n}))})(this),getTransformTargets:()=>{return xn(e=this,e.selection.getIds()).map(t=>e.shapes.get(t)).filter(e=>!!e);var e},getResizeTargets:()=>(e=>{const t=[],n=new Set,i=s=>{if(!n.has(s.id))if(n.add(s.id),e.shapes.getUtil(s).shouldResizeDescendants(s))for(const t of e.layers.getChildren(s.id))i(t);else t.push(s)};for(const s of Bn(e,e.selection.getIds())){const t=e.shapes.get(s);t&&i(t)}return t})(this),getRotationTargets:()=>{return Cn(e=this,e.selection.getIds()).map(t=>e.shapes.get(t)).filter(e=>!!e);var e},getPageBounds:()=>this.selectionGeometry.pageBounds.get()?.clone()??null,getFrame:()=>vi(this),containsPoint:e=>((e,t)=>{const n=vi(e);if(!n)return!1;const i=xi(e,t);return!!i&&n.bounds.containsPoint(i)})(this,e),toFramePoint:e=>xi(this,e),getPageOutlineVertices:()=>this.selectionGeometry.pageOutlineVertices.get().map(e=>e.clone()),getAnchorPagePoint:()=>this.selectionGeometry.selectionAnchorPagePoint.get()?.clone()??null,getLocalBounds:()=>this.selectionGeometry.localBounds.get()?.clone()??null,getRotationCenter:()=>this.selectionGeometry.rotationCenter.get()?.clone()??null,getRotation:()=>this.selectionGeometry.rotation.get(),hasCompatibleRotation:()=>this.selectionGeometry.hasCompatibleRotation.get(),hitTestHandle:e=>this.selectionOverlay.hitTestHandle(e)};shapes={get:e=>{const t=this.store.get(e);return p(t)?t:void 0},getForPage:e=>this.shapeTreeIndex.getShapesForPage(e),getSignal:e=>this.shapeSignals.getShapeSignal(e),getContentCutoutLocalPolygonsSignal:e=>this.shapeSignals.getContentCutoutLocalPolygonsSignal(e),getLocalToPageTransformSignal:e=>this.shapeGeometryQueries.getShapeLocalToPageTransformSignal(e),getLocalToPageTransform:e=>this.shapeGeometryQueries.getShapeLocalToPageTransform(e)??null,getPageBoundsSignal:e=>this.shapeGeometryQueries.getShapePageBoundsSignal(e),getSelectedSignal:e=>this.shapeSignals.getSelectedSignal(e),getRenderOrderSignal:e=>this.shapeSignals.getRenderOrderSignal(e),getRenderVisibleSignal:e=>this.shapeSignals.getRenderVisibleSignal(e),getDocumentVisibleSignal:e=>this.shapeSignals.getDocumentVisibleSignal(e),getEffectiveOpacitySignal:e=>this.shapeSignals.getEffectiveOpacitySignal(e),getEditingSessionSignal:e=>this.shapeSignals.getEditingSessionSignal(e),getDropTargetSignal:e=>this.shapeSignals.getDropTargetSignal(e),getHoveredSignal:e=>this.shapeSignals.getHoveredSignal(e),isHidden:e=>this.shapeSignals.isDocumentHidden(e),getDefaultProps:e=>{const t=this.shapeUtils.get(e),n=this._shapeDefaultPropsByTypeSignal.get().get(e)??{};return t.validateProps({...t.getDefaultProps(),...n})},updateDefaultProps:(e,t)=>{const n=this.shapeUtils.get(e),i=this._shapeDefaultPropsByTypeSignal.get().get(e)??{},s=n.validateProps({...n.getDefaultProps(),...i,...t}),o=n.validateProps(n.getDefaultProps()),r={};for(const[d,c]of Object.entries(s))o[d]!==c&&(r[d]=c);if(((e,t)=>{if(e===t)return!0;const n=Object.entries(e),i=Object.entries(t);if(n.length!==i.length)return!1;for(const[s,o]of n)if(!oe(o,t[s]))return!1;return!0})(i,r))return;const a=new Map(this._shapeDefaultPropsByTypeSignal.get());0===Object.keys(r).length?a.delete(e):a.set(e,r),this._shapeDefaultPropsByTypeSignal.set(a)},delete:(e,t="user")=>{const n=Array.from(new Set(e));0!==n.length&&(this.interaction.cancelForCommand(),this.commands.deleteShapes(n,{source:t}))},setHidden:(e,t,n="user")=>ot(this,e,{flag:"isHidden",value:t,source:n}),setLocked:(e,t,n="user")=>ot(this,e,{flag:"isLocked",value:t,source:n}),getUtil:e=>this.shapeUtils.get(e.type),computePositionedBounds:e=>((e,t)=>e.shapes.getUtil(t).getPositionedBounds(t))(this,e),computeLocalBounds:e=>((e,t)=>e.shapes.getUtil(t).getLocalBounds(t))(this,e),computeRenderBounds:e=>((e,t)=>e.shapes.getUtil(t).getRenderBounds(t))(this,e),computeExportBounds:e=>wi(this,e),computeExportBoundsInShapeSpace:(e,t)=>function(e,t,n){if(t.id===n.id)return wi(e,t);if(!((e,t,n)=>{let i=e.shapes.get(t);const s=new Set;for(;i?.parentId.startsWith("shape:");){const t=i.parentId;if(t===n)return!0;if(s.has(t))return!1;s.add(t),i=e.shapes.get(t)}return!1})(e,t.id,n.id))return null;const i=Pi(e,n).tryInvert();return i?Be(t,e.shapes.getUtil(t),i.compose(Pi(e,t))):null}(this,e,t),computeLocalToPageTransform:e=>Pi(this,e),computeRenderToPageTransform:e=>function(e,t){return((e,t,n)=>be(e,t,n))(t,e.shapes.getUtil(t),Ii(e,t))}(this,e),computeExportToPageTransform:e=>((e,t)=>xe(t,e.shapes.getUtil(t),Ii(e,t)))(this,e),computePageBounds:e=>function(e,t){return((e,t,n)=>zr.FromPoints(Te(e,t,n)))(t,e.shapes.getUtil(t),Ii(e,t))}(this,e),computeExportPageBounds:e=>function(e,t){return((e,t,n)=>Be(e,t,xe(e,t,n)))(t,e.shapes.getUtil(t),Ii(e,t))}(this,e),computeGeometry:e=>bi(this,e),computePositionedToPageTransform:e=>((e,t)=>ve(t,e.shapes.getUtil(t),Ii(e,t)))(this,e),computePageCenter:e=>bi(this,e).center,computePageCorners:e=>bi(this,e).corners,computePageOutlineVertices:e=>bi(this,e).outlineVertices,getPositionedBounds:e=>this.shapeGeometryQueries.getShapePositionedBounds(e)??null,getPageBounds:e=>this.shapeGeometryQueries.getShapePageBounds(e)??null,getGeometry:e=>this.shapeGeometryQueries.getShapeGeometry(e)??null,getPositionedToPageTransform:e=>this.shapeGeometryQueries.getShapePositionedToPageTransform(e)??null,getPageCenter:e=>this.shapeGeometryQueries.getShapePageCenter(e)??null,getPageCorners:e=>this.shapeGeometryQueries.getShapePageCorners(e)??null,getPageOutlineVertices:e=>this.shapeGeometryQueries.getShapePageOutlineVertices(e)??[],getClipAncestorIds:e=>this.shapeGeometryQueries.getShapeClipAncestorIds(e),getClipAncestorIdsSignal:e=>this.shapeGeometryQueries.getShapeClipAncestorIdsSignal(e),isPagePointInClip:(e,t)=>this.shapeGeometryQueries.isPagePointInShapeClip(e,t),getClippedPageBounds:e=>this.shapeGeometryQueries.getShapeClippedPageBounds(e),hitTest:e=>this.shapes.hitTestPoint(e)[0]??null,hitTestPoint:(e,t)=>this.spatialIndex.getShapesAtPoint(e,{...t,filter:n=>!this.shapes.isHidden(n.id)&&this.shapes.isPagePointInClip(n.id,e)&&(t?.filter?.(n)??!0)}),hitTestLineSegment:(e,t,n)=>this.spatialIndex.getShapesHitByLineSegment(e,t,{...n,filter:e=>!this.shapes.isHidden(e.id)&&(n?.filter?.(e)??!0)}),getIdsInBounds:(e,t)=>this.spatialIndex.getShapeIdsInBounds(e,t).filter(e=>!this.shapes.isHidden(e)),getInBounds:(e,t)=>this.spatialIndex.getShapesInBounds(e,t).filter(e=>!this.shapes.isHidden(e.id)),getInViewport:(e,t)=>this.spatialIndex.getShapesInViewport(e,t).filter(e=>!this.shapes.isHidden(e.id)),getIdsInViewport:(e,t)=>this.spatialIndex.getShapeIdsInViewport(e,t)};layers={getSelectionParentOrderState:()=>Ri(this),getSelectionGroupState:()=>Ci(this),canGroupSelection:()=>null!==Ci(this),canGroup:e=>((e,t)=>null!==Mi(e,t))(this,e),group:(e,t="user")=>Bi(this,e,t),groupSelection:(e="user")=>((e,t="user")=>{const n=Bi(e,e.selection.getIds(),t);return n&&e.commands.setSelectedShapeIds([n.id],{source:t}),n})(this,e),getUngroupableSelectionIds:()=>ki(this),getUngroupableIds:e=>Ei(this,e),canUngroupSelection:()=>ki(this).length>0,canUngroup:e=>((e,t)=>Ei(e,t).length>0)(this,e),ungroup:(e,t="user")=>Ai(this,e,t),ungroupSelection:(e="user")=>((e,t="user")=>Ai(e,e.selection.getIds(),t))(this,e),getSelectionSiblingOrderState:()=>Ki(this),canMoveSelectionWithinParent:e=>((e,t)=>{const n=Ki(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this,e),canMoveSelection:e=>((e,t)=>{const n=Ri(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this,e),canMove:(e,t)=>((e,t,n)=>{const i=Yi(e,t);return"backward"===n?i?.canMoveBackward??!1:i?.canMoveForward??!1})(this,e,t),move:(e,t,n="user")=>Xi(this,e,t,n),moveToEdge:(e,t,n="user")=>Fi(this,e,t,n),moveSelectionWithinParent:(e,t="user")=>((e,t,n="user")=>{const i=e.state.selectedShapes.get();if(1!==i.length)return!1;const[s]=i;if(!s||s.isLocked)return!1;const o=Ki(e);if(!o)return!1;const r=e.layers.getChildren(o.parentId),a=o.index;if(r[a]?.id!==s.id)return!1;const d="backward"===t?a-1:a+1;if(d<0||d>=r.length)return!1;const c=[...r],[l]=c.splice(a,1);return!!l&&(c.splice(d,0,l),e.interaction.cancelForCommand(),e.commands.updateShapes(c.map((t,n)=>({id:t.id,index:re(e).createShapeIndex(n+1)})),{source:n}),!0)})(this,e,t),moveToPlacement:(e,t="user")=>function(e,t,n="user"){const i=Array.from(new Set(t.ids));if(0===i.length)return{ok:!1,reason:"notFound"};const s=i.map(t=>e.shapes.get(t)).filter(e=>!!e);if(s.length!==i.length)return{ok:!1,reason:"notFound"};for(const r of s){if(r.isLocked)return{ok:!1,reason:"locked"};if(e.shapes.isHidden(r.id))return{ok:!1,reason:"hidden"}}for(const r of i){const n=t.parentId;if(n.startsWith("page:")){if(!e.pages.get(n))return{ok:!1,reason:"invalidParent"}}else{const t=e.shapes.get(n);if(!t)return{ok:!1,reason:"invalidParent"};if(t.id===r||e.layers.getDescendantIds(r).includes(t.id))return{ok:!1,reason:"cycle"};if(!e.layers.canReceiveChild(t.id,r))return{ok:!1,reason:"invalidParent"}}}const o=((e,t,n,i,s)=>{const o=((e,t,n,i)=>{const s=new Set(n),o=t.parentId.startsWith("shape:")?e.shapes.get(t.parentId):null,r=S(e).getAll().filter(e=>p(e)&&e.parentId===t.parentId).filter(e=>!s.has(e.id));r.sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id));let a=r.length;if(t.beforeId){const e=r.findIndex(e=>e.id===t.beforeId);if(-1===e)return{ok:!1,reason:"invalidBeforeId"};a=e}r.splice(a,0,...i);const d=new Map;for(const c of i){if(c.parentId===t.parentId)continue;const n=Ue(e,c,t.parentId);if(!n)return{ok:!1,reason:"unsupportedTransform"};d.set(c.id,n)}return{ok:!0,updates:r.map((n,i)=>{const s=n.parentId!==t.parentId&&o?e.shapes.getUtil(o).getChildPlacementMeta(o,n,{editor:e,reason:"reparent"}):n.meta;return{id:n.id,parentId:t.parentId,index:re(e).createShapeIndex(i+1),...d.get(n.id),meta:s===n.meta?void 0:s}})}})(e,t,n,i);return o.ok?(e.interaction.cancelForCommand(),e.commands.updateShapes(o.updates,{source:s}),o):o})(e,t,i,s,n);return o.ok?{ok:!0,movedIds:i}:{ok:!1,reason:o.reason}}(this,e,t),moveSelection:(e,t="user")=>((e,t,n="user")=>Xi(e,e.selection.getIds(),t,n))(this,e,t),moveSelectionToEdge:(e,t="user")=>((e,t,n="user")=>Fi(e,e.selection.getIds(),t,n))(this,e,t),getChildIds:e=>this.shapeTreeIndex.getChildShapeIds(e),getChildren:e=>this.shapeTreeIndex.getChildShapes(e),getDescendantIds:e=>this.shapeTreeIndex.getDescendantShapeIds(e),getDescendantPageBounds:e=>((e,t)=>bn(e,e.layers.getDescendantIds(t)))(this,e),getSubtreePageBounds:e=>((e,t)=>bn(e,[t,...e.layers.getDescendantIds(t)]))(this,e),getPageId:e=>this.shapeTreeIndex.getPageIdForShape(e),isOrAncestorLocked:e=>((e,t)=>{const n=new Set;let i=e.shapes.get(t);for(;i;){if(i.isLocked)return!0;if(!i.parentId.startsWith("shape:"))return!1;const t=i.parentId;if(n.has(t))return!1;n.add(t),i=e.shapes.get(t)}return!1})(this,e),isOrAncestorInSet:(e,t)=>((e,t,n)=>{let i=e.shapes.get(t);const s=new Set;for(;i;){if(n.has(i.id))return!0;if(!i.parentId.startsWith("shape:"))return!1;const t=i.parentId;if(s.has(t))return!1;s.add(t),i=e.shapes.get(t)}return!1})(this,e,t),hasLockedDescendant:e=>((e,t)=>e.layers.getDescendantIds(t).some(t=>e.shapes.get(t)?.isLocked??!1))(this,e),getOutermostSelectableId:e=>((e,t)=>{let n=t,i=e.shapes.get(t);const s=new Set([t]);for(;i?.parentId.startsWith("shape:");){const t=i.parentId;if(s.has(t))break;s.add(t);const o=e.shapes.get(t);if(!o)break;e.shapes.getUtil(o).isSelectionTransformContainer(o)&&(n=o.id),i=o}return n})(this,e),includeDescendants:e=>Pn(this,e),getSelectionTransformIds:e=>xn(this,e),getSelectionRotationIds:e=>Cn(this,e),getExportTraversalIds:e=>((e,t)=>{const n=Pn(e,t).filter(t=>!e.shapes.isHidden(t)),i=new Set(n);for(const s of n)for(const t of e.bindings.getForShape(s)){const s=e.bindings.getUtil(t).getExportShapeIds?.(e,t);for(const t of s??[])for(const s of Pn(e,[t]))i.has(s)||e.shapes.isHidden(s)||(i.add(s),n.push(s))}return n})(this,e),getContainment:(e,t)=>fi(this,this.shapeGeometryQueries,e,t),getContainingParentId:e=>((e,t,n,i)=>mi({editor:e,shapeTree:t,geometry:n,shapeIds:i}))(this,this.shapeTreeIndex,this.shapeGeometryQueries,e),getContainingParentIdAtPoint:(e,t)=>((e,t,n,i,s)=>mi({editor:e,shapeTree:t,geometry:n,shapeIds:i,point:s}))(this,this.shapeTreeIndex,this.shapeGeometryQueries,e,t),getContainingParentIdForShape:e=>((e,t,n)=>{const i=(t=>{const n=new Set;let i=t;for(;i.startsWith("shape:");){const t=i;if(n.has(t))return null;n.add(t);const s=e.shapes.get(t);if(!s)return null;i=s.parentId}return e.pages.get(i)?i:null})(n.parentId);if(!i)return null;const s=Lt(e,n.parentId,t=>e.shapes.get(t));if(!s)return null;const o=ke(n,e.shapes.getUtil(n),s),r=new Map;for(const g of S(e).getAll().filter(p)){const e=r.get(g.parentId)??[];e.push(g),r.set(g.parentId,e)}for(const p of r.values())p.sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id));const a=[],d=new Set,c=e=>{for(const t of r.get(e)??[])d.has(t.id)||(d.add(t.id),a.push(t),c(t.id))};c(i);let l=null,h=1/0,u=-1;for(let p=0;p<a.length;p+=1){const t=a[p];if(!t||t.id===n.id||e.shapes.isHidden(t.id)||e.layers.isOrAncestorLocked(t.id))continue;const i=e.shapes.getUtil(t);if(!yi(t,i))continue;if(!e.layers.canReceiveChild(t.id,n.id))continue;const s=e.shapes.computePageBounds(t),r=i.getLocalBounds(t),d=e.shapes.computeLocalToPageTransform(t).tryInvert();d&&o.outlineVertices.length>0&&o.outlineVertices.every(e=>r.containsPoint(d.applyToPoint(e)))&&Si(s,p,l,h,u)&&(l=t,h=s.w*s.h,u=p)}return l?.id??i})(this,0,e),getIdsInContainerBounds:(e,t={})=>((e,t,n={})=>{const i=e.layers.getPageId(t),s=e.shapes.getPageBounds(t);return i&&s?e.shapes.getIdsInBounds(s,{pageId:i}).filter(i=>{if(i===t)return!1;const s=e.layers.getContainment(t,i);return"inside"===s||n.includeIntersecting&&"intersecting"===s}):[]})(this,e,t),canReceiveChildren:e=>((e,t)=>{if(t.startsWith("page:"))return!!e.pages.get(t);const n=e.shapes.get(t);return!!n&&!$e(n,e.shapes.getUtil(n))&&e.shapes.getUtil(n).canReceiveChildren(n)})(this,e),canReceiveChild:(e,t)=>((e,t,n)=>{if(t.startsWith("page:"))return!!e.pages.get(t);const i=e.shapes.get(t);if(!i)return!1;if($e(i,e.shapes.getUtil(i)))return!1;const s=e.shapes.get(n);return!!s&&i.id!==n&&!e.layers.getDescendantIds(n).includes(i.id)&&e.shapes.getUtil(i).canReceiveChild(i,s)})(this,e,t)};assets={get:e=>{const t=this.store.get(e);return f(t)?t:void 0},getAll:()=>this.store.getAll().filter(f).sort((e,t)=>e.id.localeCompare(t.id)),resolveUrl:e=>this.assetUrlResolver(e)};bindings={get:e=>{const t=this.store.get(e);return g(t)?t:void 0},getOwnedByShape:e=>this.bindingQueries.getBindingsOwnedByShape(e),getOwnedByShapeSignal:e=>this.bindingQueries.getBindingsOwnedByShapeSignal(e),getTargetingShape:e=>this.bindingQueries.getBindingsTargetingShape(e),getTargetingShapeSignal:e=>this.bindingQueries.getBindingsTargetingShapeSignal(e),getForShape:e=>this.bindingQueries.getBindingsForShape(e),getForShapeSignal:e=>this.bindingQueries.getBindingsForShapeSignal(e),getUtil:e=>this.bindingUtils.get(e.type),getSuppressedReactionIds:()=>this.bindingManager.getSuppressedReactionIds(),runWithSuppressedReactions:(e,t)=>this.bindingManager.runWithSuppressedReactions(e,t),getConflicting:e=>this.bindingManager.getConflictingBindings(e),canBind:e=>this.bindingManager.canBind(e),syncCreated:(e,t)=>this.bindingManager.syncCreatedBinding(e,t),syncUpdated:(e,t,n)=>this.bindingManager.syncUpdatedBinding(e,t,n),repairLoaded:e=>this.bindingManager.repairLoadedBindings(e),handleShapeChanges:(e,t)=>this.bindingManager.handleShapeChanges(e,t),getShapeCompanionRootId:e=>this.bindingManager.getShapeCompanionRootId(e),getShapeCompanionRootIds:(e,t)=>this.bindingManager.getShapeCompanionRootIds(e,t),getShapeCompanionMemberIds:e=>this.bindingManager.getShapeCompanionMemberIds(e),cleanupForDeletedShapes:(e,t)=>this.bindingManager.cleanupBindingsForDeletedShapes([...e],t),cleanup:(e,t)=>this.bindingManager.cleanupBindings(Array.from(e),t),setTerminalResolver:e=>this.interactionManager.setTerminalBindingResolver(e),resolveTerminal:e=>this.interactionManager.resolveTerminalBinding(e)};viewport={getCamera:(e=this.pages.getCurrentId())=>this.cameraManager.getCamera(e),pageToScreen:(e,t=this.pages.getCurrentId())=>this.cameraManager.pageToScreen(e,t),screenToPage:(e,t=this.pages.getCurrentId())=>this.cameraManager.screenToPage(e,t),setCamera:(e,t)=>this.cameraManager.setCamera(e,t),setLock:e=>this.cameraManager.setLock(e),pan:(e,t="system")=>this.cameraManager.panCamera(e,t),zoomAtScreenPoint:(e,t,n="system")=>this.cameraManager.zoomCameraAtScreenPoint(e,t,n),zoomToScreenPoint:(e,t,n="system")=>this.cameraManager.zoomCameraToScreenPoint(e,t,n),zoomAtCenter:(e,t="system")=>this.cameraManager.zoomAtViewportCenter(e,t),resetZoom:(e="user")=>this.cameraManager.resetZoom(e),setScreenSize:e=>this.cameraManager.setViewportScreenSize(e),stopCameraAnimation:()=>this.cameraManager.cancelAnimation(),getCurrentPageBounds:(e=this.pages.getCurrentId())=>En(this,e),centerOnShape:(e,t={})=>{const n=t.source??"user",i=this.layers.getPageId(e);if(!i)return!1;const s=this.layers.getSubtreePageBounds(e);if(!s)return!1;const o=this.state.viewportScreenSize.get();if(o.w<=0||o.h<=0)return!1;const r=this.viewport.getCamera(i),a=i===this.pages.getCurrentId();a||this.commands.setCurrentPageId(i,{source:n});const d={x:s.center.x-o.w/(2*r.z),y:s.center.y-o.h/(2*r.z),z:r.z};return a&&t.animation?this.cameraManager.animateCameraTo(d,{durationMs:t.animation.durationMs,pageId:i,source:n}):this.commands.setCamera({pageId:i,camera:d},{source:n}),!0},zoomToBounds:(e,t)=>An(this,e,t),zoomToFit:e=>((e,t)=>{const n=En(e);return!!n&&An(e,n,t)})(this,e),zoomToSelection:e=>((e,t)=>{const n=Rn(e,e.selection.getIds());return!!n&&An(e,n,t)})(this,e)};interaction={setBrushBox:e=>this.interactionManager.setBrushBox(e),setBindingPreview:e=>this.interactionManager.setBindingPreview(e),setTerminalBindingGuides:e=>this.interactionManager.setTerminalBindingGuides(e),setDropTargetShapeId:e=>this.interactionManager.setDropTargetShapeId(e),setHoveredShapeId:e=>this.interactionManager.setHoveredShapeId(e),setSelectionTranslationActive:e=>this.interactionManager.setSelectionTranslationActive(e),setSnapIndicators:e=>this.interactionManager.setSnapIndicators(e),clearSelection:()=>this.interactionManager.clearSelectionTransients(),cancelForCommand:()=>this.eventRouter.cancelInteraction("command"),cancel:(e,t={})=>this.eventRouter.cancelInteraction(e,t)};snapshots={getDocument:()=>(e=>{const t=e.store.getAll();return{schemaVersion:4,records:[t.find(h)??a(),...e.pages.getAll(),...t.filter(f).sort((e,t)=>e.id.localeCompare(t.id)),...t.filter(p).sort((e,t)=>e.parentId===t.parentId?e.index.localeCompare(t.index):e.parentId.localeCompare(t.parentId)),...t.filter(g).sort((e,t)=>e.id.localeCompare(t.id))]}})(this),getSession:()=>({schemaVersion:1,records:[this.state.session.get()]}),loadDocument:(e,t)=>((e,t,n)=>{e.assertDocumentWriteAllowed();const i=n?.source??"system",s=function(e,t,n){const i=rn(e,"document"),s=new Set,o=[];return i.records.forEach((e,i)=>{if(!Zt(e))throw new ma("Invalid document record: expected object");if("string"!=typeof e.id)throw new ma("Invalid document record id");if(s.has(e.id))throw new ma(`Duplicate document record id: ${e.id}`);if(s.add(e.id),"document"!==e.typeName)if("page"!==e.typeName)if("shape"!==e.typeName)if("binding"!==e.typeName){if("asset"!==e.typeName)throw new ma(`Unsupported document record type: ${String(e.typeName)}`);o.push((e=>{if("string"!=typeof e.id||!e.id.startsWith("asset:"))throw new ma("Invalid asset record id");if("string"!=typeof e.type)throw new ma("Invalid asset record type");return{id:e.id,typeName:"asset",scope:"document",type:e.type,props:Zt(e.props)?e.props:{},meta:nn(e.meta)}})(e))}else o.push(((e,t)=>{if("string"!=typeof e.id||!e.id.startsWith("binding:"))throw new ma("Invalid binding record id");if("string"!=typeof e.type)throw new ma("Invalid binding record type");if("string"!=typeof e.ownerId||!e.ownerId.startsWith("shape:"))throw new ma(`Invalid owner id for binding ${e.id}`);if(!Array.isArray(e.endpoints)||0===e.endpoints.length)throw new ma(`Invalid endpoints for binding ${e.id}`);const n=e.type,i=t.get(n),s=new Set,o=e.endpoints.map(t=>{if(!Zt(t)||"string"!=typeof t.slot||!t.slot)throw new ma(`Invalid endpoint slot for binding ${e.id}`);if(s.has(t.slot))throw new ma(`Duplicate endpoint slot for binding ${e.id}: ${t.slot}`);if(s.add(t.slot),"string"!=typeof t.targetId||!t.targetId.startsWith("shape:"))throw new ma(`Invalid endpoint target for binding ${e.id}`);return{slot:t.slot,targetId:t.targetId,props:i.validateEndpointProps(t.slot,t.props),meta:nn(t.meta)}});return o.sort((e,t)=>e.slot.localeCompare(t.slot)),{id:e.id,typeName:"binding",scope:"document",type:n,ownerId:e.ownerId,endpoints:o,meta:nn(e.meta)}})(e,n));else o.push(((e,t,n)=>{if("string"!=typeof e.id||!e.id.startsWith("shape:"))throw new ma("Invalid shape record id");if("string"!=typeof e.type)throw new ma("Invalid shape record type");if("string"!=typeof e.parentId||!e.parentId.startsWith("page:")&&!e.parentId.startsWith("shape:"))throw new ma(`Invalid parent id for shape ${e.id}`);return{id:e.id,typeName:"shape",scope:"document",parentId:e.parentId,index:Jt(e.index,String(n+1).padStart(6,"0")),x:en(e.x,0),y:en(e.y,0),rotation:en(e.rotation,0),scaleX:en(e.scaleX,1),scaleY:en(e.scaleY,1),opacity:Math.min(1,Math.max(0,en(e.opacity,1))),isHidden:tn(e.isHidden,!1),isLocked:tn(e.isLocked,!1),meta:nn(e.meta),type:e.type,subType:"string"==typeof e.subType?e.subType:null,props:t.get(e.type).validateProps(e.props)}})(e,t,i));else o.push(((e,t)=>{if("string"!=typeof e.id||!e.id.startsWith("page:"))throw new ma("Invalid page record id");return{id:e.id,typeName:"page",scope:"document",name:Jt(e.name,`Page ${t+1}`),index:Jt(e.index,String(t+1).padStart(4,"0")),meta:nn(e.meta)}})(e,i));else o.push((e=>{if("document:main"!==e.id)throw new ma("Invalid document metadata record id");return{id:Ar,typeName:"document",scope:"document",meta:nn(e.meta)}})(e))}),{schemaVersion:4,records:an(o,t,n)}}(t,e.shapeUtils,e.bindingUtils);e.interaction.cancel("restore"),e.editing.end({runEditEnd:!1,source:i}),e.editing.cancelOperation();const o=e.state.session.get();hn(e,[...s.records,o],i),ln(e),e.history.clear(),e.bindings.repairLoaded(i)})(this,e,t),loadSession:(e,t)=>cn(this,e,t),syncAfterDocumentRestore:()=>ln(this)};exports={getSvgString:(e=this.selection.getIds(),t)=>function(e,t,n,i={}){const s=Array.from(t),o=e.layers.getExportTraversalIds(s),r=new Set(o),a=[],d=[];for(const b of o){const t=e.shapes.get(b);t?d.push(t):a.push({id:b,reason:"missing-shape"})}if(0===d.length)return null;const c=[];for(const b of d){if(!e.shapes.getUtil(b).contributesToExportBounds(b))continue;const t=$(e,b,r);t&&(M(t)?c.push(t):a.push({id:b.id,reason:"missing-bounds"}))}if(0===c.length)return null;const l=j(c).expand(i.padding??16),h=[],p={editor:e,bounds:l,addDef(e){const t=`land-svg-def-${h.length+1}`;return h.push({...e,attrs:{...e.attrs,id:t}}),t},resolveAssetUrl:t=>e.assets.resolveUrl(t),resolveColor:e=>z(e,i.resolveThemeColor)},u=[],g=[],f=new Map,m=[],S=(t,n)=>{const i=e.shapes.computeExportToPageTransform(t),s=((e,t)=>{let n=t.opacity,i=t.parentId;const s=new Set([t.id]);for(;i.startsWith("shape:");){const t=i;if(s.has(t))break;s.add(t);const o=e.shapes.get(t);if(!o)break;n*=o.opacity,i=o.parentId}return n})(e,t),o=((e,t,n,i,s)=>{const o=[];for(const r of U(e,t,n)){const t=H(e,r,i,s);t&&o.push(t)}return o})(e,t,r,f,p);let a={tag:"g",attrs:{transform:i.toSvgString(),opacity:1===s?void 0:s},children:[n]};for(let e=o.length-1;e>=0;e-=1)a={tag:"g",attrs:{"clip-path":`url(#${o[e]})`},children:[a]};g.push(a)},y=e=>{const t=[],i=n.get(e.type)?.toSvgForeground?.(e,p);i&&t.push(i),t.length>0&&S(e,{tag:"g",children:t})};for(const b of d){for(;m.length>0&&!_(e,m[m.length-1].id,b);)y(m.pop());const t=n.get(b.type);if(!t){a.push({id:b.id,reason:"missing-exporter"});continue}const i=t.toSvg(b,p);if(!i){a.push({id:b.id,reason:"empty-output"});continue}if(!M(N(e,b))){a.push({id:b.id,reason:"missing-bounds"});continue}const s=[],o=[];for(const n of e.shapeSvgDecorations.get(b.subType)){const e=n.toSvgBackground?.(b,p);e&&s.push(e);const t=n.toSvg?.(b,p);t&&o.push(t)}const r=0===s.length&&0===o.length?i:{tag:"g",children:[...s,i,...o]};u.push(b.id),S(b,r),t.toSvgForeground&&m.push(b)}for(;m.length>0;)y(m.pop());if(0===u.length)return null;const I=Math.max(1,l.w),w=Math.max(1,l.h),P=[];return h.length>0&&P.push({tag:"defs",children:h}),i.background&&P.push({tag:"rect",attrs:{x:l.x,y:l.y,width:l.w,height:l.h,fill:i.background}}),P.push(...g),{svg:V({tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",width:I,height:w,viewBox:`${Z(l.x)} ${Z(l.y)} ${Z(I)} ${Z(w)}`},children:P}),bounds:l,width:I,height:w,requestedShapeIds:s,exportedShapeIds:u,skippedShapes:a}}(this,e,this.shapeSvgExporters,t),getIntegrityReport:(e=this.selection.getIds())=>x({editor:this,exporters:this.shapeSvgExporters,shapeIds:e}),repairIntegrity:(e=this.selection.getIds())=>(({editor:e,exporters:t,shapeIds:n})=>{const i=Array.from(n),s=x({editor:e,exporters:t,shapeIds:i});s.repairableIssueCount>0&&e.bindings.repairLoaded("system");const o=x({editor:e,exporters:t,shapeIds:i});return{before:s,after:o,repaired:s.issues.length!==o.issues.length}})({editor:this,exporters:this.shapeSvgExporters,shapeIds:e})};constructor(e={}){const{computed:t}=this.signals;this.inputs=new oa(this.signals),this._shapeDefaultPropsByTypeSignal=this.signals.atom("editor.shapeDefaultPropsByType",new Map),this._readonlySignal=this.signals.atom("editor.readonly",!1),e.resolveAssetUrl&&(this.assetUrlResolver=e.resolveAssetUrl);for(const a of e.shapeUtils??[])this.shapeUtils.register(a);for(const a of e.shapeSvgExporters??[])this.shapeSvgExporters.register(a);for(const a of e.shapeSvgDecorations??[])this.shapeSvgDecorations.register(a);for(const a of e.shapeHitTestDecorations??[])this.shapeHitTestDecorations.register(a);for(const a of e.bindingUtils??[])this.bindingUtils.register(a);const n=new Er(((e={})=>[a(e),d(),c()])(e.documentMeta??{}),{signals:this.signals,writeGuard:e=>this.assertStoreChangeAllowed(e)});((e,t)=>{e[Xr]=t})(this,n),this.store=n,this.tools=new jr(this),this.cameraManager=new ka(this,e.cameraAnimationScheduler),this.editing=new Pa(this),this.interactionManager=new Ba(this);const i=t("editor.session",()=>{const e=n.getRecordSignal(Kr).get();if(!u(e))throw new Error("Missing session record");return e}),s=t("editor.currentPageId",()=>i.get().currentPageId),o=t("editor.toolState",()=>{const e=i.get();return{activeToolId:e.activeToolId,isToolLocked:e.isToolLocked}}),r=t("editor.editingShapeId",()=>i.get().editingShapeId),l=t("editor.shapeEditingSession",()=>i.get().shapeEditingSession),h=t("editor.shapeEditingState",()=>({editingShapeId:r.get(),session:l.get()})),p=t("editor.currentCamera",()=>i.get().pageCameraById[s.get()]??Yr),g=t("editor.selectedShapeIds",()=>{const e=i.get();return e.pageSelectedShapeIdsById[e.currentPageId]??[]},{isEqual:J}),f=t("editor.selectionCount",()=>g.get().length),m=t("editor.selectedShapeIdSet",()=>new Set(g.get()),{isEqual:ee}),S=t("editor.pageTransform",()=>{const e=p.get();return Wr.Scale(e.z,e.z).compose(Wr.Translate(-e.x,-e.y))}),y=t("editor.cameraZoom",()=>p.get().z),I=t("editor.viewportPageBounds",()=>{const{w:e,h:t}=this.cameraManager.viewportScreenSizeSignal.get();if(e<=0||t<=0)return null;const n=p.get();return new zr(n.x,n.y,e/n.z,t/n.z)});(e=>{const t=new Zr(e);Qr.set(e,t)})(this),this.shapeSignals=new va(this),this.shapeGeometryQueries=new pa(this),this.shapeTreeIndex=new ua(this,s),this.bindingQueries=new ha(this),this.bindingManager=new Dr(this),this.spatialIndex=new fa(this,this.shapeTreeIndex,this.shapeGeometryQueries),this.snaps=new Ta(this,e.snapDiagnostics),this.selectionGeometry=((e,t,n)=>{const i=e.signals.computed("editor.query.selectionGeometry",()=>wn(e,t,n),{isEqual:Sn}),s=e.signals.computed("editor.query.selectionPageOutlineVertices",()=>i.get().outlineVertices,{isEqual:ne}),o=e.signals.computed("editor.query.selectionPageBounds",()=>i.get().pageBounds,{isEqual:se}),r=e.signals.computed("editor.query.selectionLocalBounds",()=>i.get().localBounds,{isEqual:se}),a=e.signals.computed("editor.query.selectionRotation",()=>i.get().rotation);return{geometry:i,pageOutlineVertices:s,pageBounds:o,localBounds:r,hasRotation:e.signals.computed("editor.query.selectionHasRotation",()=>i.get().hasRotation),rotation:a,rotationCenter:e.signals.computed("editor.query.selectionRotationCenter",()=>i.get().rotationCenter,{isEqual:te}),hasCompatibleRotation:e.signals.computed("editor.query.selectionHasCompatibleRotation",()=>i.get().hasCompatibleRotation),selectionAnchorPagePoint:e.signals.computed("editor.query.selectionAnchorPagePoint",()=>i.get().selectionAnchorPagePoint,{isEqual:te})}})(this,g,e=>this.shapeGeometryQueries.getCachedShapeGeometry(e));const w=t("editor.selectedShapes",()=>g.get().map(e=>this.shapes.getSignal(e).get()).filter(e=>!!e)),P=t("editor.selectionCanFlip",()=>Mn(this,g.get())),b=t("editor.selectionState",()=>{const e=g.get(),t=1===e.length?this.shapes.getSignal(e[0]).get()??null:null,n=w.get(),i=(e=>{let t=null;for(const n of e)if(null===t)t=n.type;else if(t!==n.type)return null;return t})(n),s=1===n.length,o=n.map(e=>this.shapes.getUtil(e).getSelectionHandleAnchors(e,{isOnlySelected:s,editor:this})).some(e=>e.terminalHandleAnchors.length>0||e.middleHandleAnchors.length>0||(e.customHandleAnchors?.length??0)>0),r=n.some(e=>this.shapes.getUtil(e).contributesToSelectionFrame(e,{editor:this})),a=o&&r,d=t?this.shapes.getUtil(t).getSelectionHandleAnchors(t,{isOnlySelected:s,editor:this}):null,c=1===e.length&&!!d&&(d.terminalHandleAnchors.length>0||(d.customHandleAnchors?.length??0)>0),l=this.selectionGeometry.hasRotation.get();return{count:e.length,singleShapeType:t?.type??null,commonShapeType:i,canFlipSelection:P.get(),hasPointHandleSelection:o,hasFrameSelection:r,isMixedFrameAndPointHandleSelection:a,canDragPointHandles:c,hasSelectionRotation:l,hasMixedSelectionRotation:!this.selectionGeometry.hasCompatibleRotation.get(),canResetSelectionRotation:l&&r,localBounds:this.selectionGeometry.localBounds.get(),frameRotation:this.selectionGeometry.rotation.get(),frameRotationCenter:this.selectionGeometry.rotationCenter.get(),selectionAnchorPagePoint:this.selectionGeometry.selectionAnchorPagePoint.get()}}),v=t("editor.selectionMetadata",()=>{const e=b.get();return{count:e.count,singleShapeType:e.singleShapeType,commonShapeType:e.commonShapeType,canFlipSelection:e.canFlipSelection,hasPointHandleSelection:e.hasPointHandleSelection,hasFrameSelection:e.hasFrameSelection,isMixedFrameAndPointHandleSelection:e.isMixedFrameAndPointHandleSelection,canDragPointHandles:e.canDragPointHandles,hasSelectionRotation:e.hasSelectionRotation,hasMixedSelectionRotation:e.hasMixedSelectionRotation,canResetSelectionRotation:e.canResetSelectionRotation}},{isEqual:Rs}),x=t("editor.renderViewportPageBounds",e=>{const t=I.get();return t?e!==xr&&e&&(i=t).minX>=(n=e).minX&&i.maxX<=n.maxX&&i.minY>=n.minY&&i.maxY<=n.maxY?e:t.expand(160/y.get()):null;var n,i},{isEqual:se});this.renderWindowManager=new Ea(this,{currentPageId:s,currentPageShapeIds:this.shapeTreeIndex.currentPageShapeIdsSignal,selectedShapeIds:g,selectedShapeIdSet:m,viewportPageBounds:I,renderViewportPageBounds:x}),this.selectionOverlay=new wa(this,{tool:o,selectedShapeIds:g,selectedShapes:w,cameraZoom:y}),this.operations=new ca(this,e.onUnhandledError),this.history=new aa(this),this.state=Object.freeze({readonly:this._readonlySignal,session:i,pages:this.shapeTreeIndex.pagesSignal,currentPageId:s,currentPageShapeIds:this.shapeTreeIndex.currentPageShapeIdsSignal,currentPageShapes:this.shapeTreeIndex.currentPageShapesSignal,currentPageShapeTree:this.shapeTreeIndex.currentPageShapeTreeSignal,tool:o,editingShapeId:r,shapeEditingSession:l,shapeEditing:h,shapeEditingEntryRequest:this.editing.entryRequestSignal,selectedShapeIds:g,selectedShapeIdSet:m,selectedShapes:w,selectionCount:f,selection:b,selectionMetadata:v,selectionPageBounds:this.selectionGeometry.pageBounds,selectionLocalBounds:this.selectionGeometry.localBounds,selectionAnchorPagePoint:this.selectionGeometry.selectionAnchorPagePoint,camera:p,cameraLock:this.cameraManager.cameraLockSignal,cameraZoom:y,pageTransform:S,viewportScreenSize:this.cameraManager.viewportScreenSizeSignal,viewportPageBounds:I,history:this.history.state}),this.render=Object.freeze({viewport:Object.freeze({pageBounds:x,items:this.renderWindowManager.renderItemsSignal,shapeOrderById:this.renderWindowManager.shapeRenderOrderByIdSignal,culledShapeIds:this.renderWindowManager.culledShapeIdsSignal,culledShapeIdSet:this.renderWindowManager.culledShapeIdSetSignal,selectedShapeIdsOutsideCulled:this.renderWindowManager.selectedShapeIdsOutsideCulledSignal,selectedShapeIdsOutsideCulledSet:this.renderWindowManager.selectedShapeIdsOutsideCulledSetSignal,visibleShapeIds:this.renderWindowManager.renderVisibleShapeIdsSignal,visibleShapeIdSet:this.renderWindowManager.renderVisibleShapeIdSetSignal,retainedShapeIds:this.renderWindowManager.retainedShapeIdsSignal}),overlay:Object.freeze({selectedShapeItems:this.selectionOverlay.selectedShapeItemsSignal,frameGeometry:this.selectionOverlay.frameGeometrySignal,companionFrameGeometries:this.selectionOverlay.companionFrameGeometriesSignal,path:this.selectionOverlay.pathSignal,pageClipPath:this.selectionOverlay.pageClipPathSignal,bindingSegments:this.selectionOverlay.bindingSegmentsSignal,frameStyle:this.selectionOverlay.frameStyleSignal,handleAnchors:this.selectionOverlay.handleAnchorsSignal,handles:this.selectionOverlay.handlesSignal}),interaction:Object.freeze({brushBox:this.interactionManager.brushBoxSignal,brushBoxActive:this.interactionManager.brushBoxActiveSignal,bindingPreview:this.interactionManager.bindingPreviewSignal,bindingPreviewActive:this.interactionManager.bindingPreviewActiveSignal,terminalBindingGuides:this.interactionManager.terminalBindingGuidesSignal,dropTargetShapeId:this.interactionManager.dropTargetShapeIdSignal,hoveredShapeId:this.interactionManager.hoveredShapeIdSignal,selectionTranslationActive:this.interactionManager.selectionTranslationActiveSignal,snapIndicators:this.snaps.indicatorsSignal,snapIndicatorsActive:this.snaps.activeSignal})}),this.commands=st(this),this.eventRouter=new sa(this),this.bindings.repairLoaded("system"),this.registerBuiltInInteractions()}closeWrites(){this.writesClosed=!0}assertDocumentWriteAllowed(){if(this.writesClosed)throw new Error("Disposed editor rejected store write.");if(this._readonlySignal.get())throw new Error("Readonly canvas rejected document write.")}assertStoreChangeAllowed(e){if(this.writesClosed)throw new Error("Disposed editor rejected store write.");(e.diff.added.some(m)||e.diff.removed.some(m)||e.diff.updated.some(({before:e,after:t})=>m(e)||m(t)))&&this.assertDocumentWriteAllowed()}registerBuiltInInteractions(){this.interactions.register(function(){let e=!1,t=null;const n=()=>{t=null};return{id:"land.camera.canvas-navigation",enabledInReadonly:!0,editorEvent:{handleEvent(i,s){if("cancel"===s.type)return"blur"!==s.reason&&"dispose"!==s.reason||(e=!1),void n();if("wheel"===s.type)return((e,t)=>{if(t.ctrlKey){const n=e.state.camera.get(),i=t.delta.y,s=(Math.abs(i)>10?10*Math.sign(i):i)/100;return void e.viewport.zoomToScreenPoint(t.screenPoint,n.z-1*s*n.z)}e.state.cameraLock.get()?e.viewport.zoomAtCenter(t.delta.y):e.viewport.pan(t.delta)})(i,s),ea;if("keyboard"===s.type&&(e=>"Space"===e.code)(s)){if("key_up"===s.name){const t=e;return e=!1,t?ea:void 0}if(i.state.shapeEditingSession.get())return;return e=!0,ea}if("tick"===s.type&&t){const e=i.inputs.state.get();return e.pointerId===t.pointerId&&e.currentScreenPoint&&at(i,t.camera,e.currentScreenPoint),ea}if("pointer"===s.type&&"mouse"===s.pointerType){if("pointer_down"===s.name){n();const o=((e,{allowLeftButton:t})=>1===e.button?4:t&&0===e.button?1:null)(s,{allowLeftButton:i.inputs.isSpacePressed.get()&&!i.state.shapeEditingSession.get()});if(null===o)return;return i.state.cameraLock.get()||(0===s.button&&(e=!0),t={pointerId:s.pointerId,buttons:o,camera:rt(i,s.screenPoint)}),ta}if(t&&s.pointerId===t.pointerId)return"pointer_move"===s.name?(0===(s.buttons&t.buttons)&&n(),ea):"pointer_up"===s.name?(at(i,t.camera,s.screenPoint),n(),ea):"pointer_cancel"===s.name?(n(),ea):void 0}}}}}())}handleEvent(e){return this.eventRouter.handle(e)}listen(e){return this.store.listen(t=>e(t))}dispose(){this.closeWrites();let e=null;for(const n of[()=>this.cameraManager.dispose(),()=>this.bindingQueries.dispose(),()=>this.shapeTreeIndex.dispose(),()=>this.shapeGeometryQueries.dispose(),()=>this.shapeSignals.dispose(),()=>this.runtime.dispose(),()=>this.history.dispose()])try{n()}catch(t){e??=t}if(null!==e)throw e}},Ra=class{editor;id;parent;children=new Map;currentChild=null;initial=null;constructor(e,t,n){this.editor=e,this.id=t,this.parent=n}addChild(e){this.children.set(e.id,e)}enter(e){if(this.onEnter(e),!this.initial)return;const t=this.children.get(this.initial);if(!t)throw new Error(`Missing child state "${this.initial}" on "${this.id}"`);this.currentChild=t,t.enter(e)}exit(e){this.currentChild&&(this.currentChild.exit(e),this.currentChild=null),this.onExit(e)}transition(e,t){if(!this.parent){const n=this.children.get(e);if(!n)throw new Error(`Missing root child state "${e}" on tool "${this.id}"`);if(this.currentChild===n)return;return this.currentChild?.exit(t),this.currentChild=n,void n.enter(t)}this.parent.transition(e,t)}isInInitialState(){return!this.currentChild||!!this.initial&&this.currentChild.id===this.initial&&this.currentChild.isInInitialState()}dispatch(e,t){if(this.currentChild)return this.currentChild.dispatch(e,t);switch(e.type){case"pointer":return this.handlePointerEvent(e,t);case"keyboard":return this.handleKeyboardEvent(e,t);case"wheel":return this.onWheel(e,t);case"tick":return this.onTick(e,t);case"cancel":return this.onCancel(e,t)}}onEnter(e){}onExit(e){}onPointerDown(e,t){}onPointerMove(e,t){}onPointerUp(e,t){}onCancel(e,t){}onKeyDown(e,t){}onKeyUp(e,t){}onWheel(e,t){}onTick(e,t){}handlePointerEvent(e,t){switch(e.name){case"pointer_down":return this.onPointerDown(e,t);case"pointer_move":return this.onPointerMove(e,t);case"pointer_up":return this.onPointerUp(e,t);case"pointer_cancel":return this.onCancel({type:"cancel",reason:"pointer_cancel"},t)}}handleKeyboardEvent(e,t){return"key_down"===e.name?this.onKeyDown(e,t):this.onKeyUp(e,t)}},Ka=class extends Ra{constructor(e){super(e,"hand"),this.initial="idle",this.addChild(new Ya(e,this)),this.addChild(new Xa(e,this))}},Ya=class extends Ra{constructor(e,t){super(e,"idle",t)}onPointerDown(e){0===e.button&&this.transition("panning",rt(this.editor,e.screenPoint))}},Xa=class extends Ra{info=null;constructor(e,t){super(e,"panning",t)}onEnter(e){this.info=e}onTick(e){if(!this.info)return;const t=this.editor.inputs.state.get().currentScreenPoint;t&&at(this.editor,this.info,t)}onPointerUp(e){this.info&&at(this.editor,this.info,e.screenPoint),this.transition("idle")}onCancel(){this.transition("idle")}onExit(){this.info=null}},Fa=Math.PI/180*15,Da=Math.PI/2,Oa=Math.PI/180*5,La=class extends Ra{info=null;onEnter(e){this.info=e,this.onInfoEnter()}onExit(){this.onInfoExit(),this.info=null}onInfoEnter(){}onInfoExit(){}},za=class extends La{onPointerMove(e){if(!this.info)return;const t=this.editor.inputs.state.get().originScreenPoint;t&&((e,t)=>e.dist2(t)>=9)(t,e.screenPoint)&&this.onDragThresholdExceeded(e)}},_a=class extends La{operation=null;onInfoEnter(){if(this.info){const e=this.getOperationKind(this.info);this.operation=this.editor.operations.begin({kind:e,label:e,source:"user",history:"record"})}this.onDragStart()}onDragStart(){}onTick(e){if(!this.info)return;const t=qs(this.editor,e,"always_apply");t&&this.apply(t)}onKeyDown(){this.applyFromInputs()}onKeyUp(){this.applyFromInputs()}applyFromInputs(){Gs(this.editor,e=>this.apply(e))}commitOperation(){const e=this.operation;this.operation=null,e?.commit()}cancelOperation(){const e=this.operation;this.operation=null,e?.cancel()}},$a=class extends La{constructor(e,t){super(e,"brushing",t)}onInfoEnter(){if(!this.info)return;const e=this.editor.inputs.state.get();this.updateBrush(this.info.originPagePoint,this.info.additiveSelection,Zs(e))}onPointerMove(e){this.info&&this.updateBrush(e.pagePoint,Qs(e),Zs(e))}onTick(e){if(!this.info)return;const t=qs(this.editor,e,"apply_after_scroll_or_without_screen_point");t&&this.updateBrush(t.pagePoint,Qs(t),Zs(t))}onKeyDown(){this.updateBrushFromInputs()}onKeyUp(){this.updateBrushFromInputs()}onPointerUp(e){this.info&&this.updateBrush(e.pagePoint,Qs(e),Zs(e)),this.complete()}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}updateBrush(e,t,n){if(!this.info)return;const i=((e,t)=>{const n=Math.min(e.x,t.x),i=Math.min(e.y,t.y),s=Math.max(e.x,t.x),o=Math.max(e.y,t.y);return new zr(n,i,s-n,o-i)})(this.info.originPagePoint,e),s=((e,t)=>{const n=[],i=new Set;for(const s of t){const t=e.shapes.get(s);if(!t)continue;const o=e.shapes.getUtil(t).getSelectionTargetId(t,{editor:e}),r=e.layers.getOutermostSelectableId(o);i.has(r)||(i.add(r),n.push(r))}return n})(this.editor,this.editor.shapes.getIdsInBounds(i).filter(e=>((e,t,n,i)=>{const s=e.shapes.get(n);return!(!s||!((e,t)=>{const n=e.shapes.get(t);return!!n&&e.shapes.getUtil(n).canBeDirectlyBrushSelected(n)})(e,s.id))&&e.shapes.getUtil(s).canSelectByBrush(s,{editor:e,brushBounds:t,isWrapping:i,pageOutlineVertices:e.shapes.getPageOutlineVertices(s.id),pageBounds:e.shapes.getPageBounds(s.id)})})(this.editor,i,e,n))),o=t?((e,t)=>{const n=new Set(e);for(const i of t)n.has(i)?n.delete(i):n.add(i);return Array.from(n)})(this.info.previousSelection,s):s;this.editor.interaction.setBrushBox(i),this.editor.commands.setSelectedShapeIds(o,{source:"system"})}updateBrushFromInputs(){Gs(this.editor,e=>this.updateBrush(e.pagePoint,Qs(e),Zs(e)))}complete(){this.transition("idle")}cancel(){this.transition("idle")}},Na=class extends _a{constructor(e,t){super(e,"dragging_plugin_interaction",t)}getOperationKind(e){return e.session.operationKind}onDragStart(){this.info?.session.onDragStart?.({editor:this.editor})}onPointerUp(e){this.apply(e),this.complete()}onCancel(e){const t=this.info?.previousSelection;this.editor.signals.transact(()=>{t&&!J(t,this.editor.selection.getIds())&&this.editor.commands.setSelectedShapeIds(t,{source:"system"}),this.info&&(this.editor.interaction.clearSelection(),this.cancelOperation())}),this.info?.session.onCancel?.({editor:this.editor,reason:e.reason}),this.transition("idle")}onInfoExit(){this.info?.session.shouldClearBindingPreviewOnExit&&this.editor.interaction.setBindingPreview(null),this.editor.interaction.setSnapIndicators(null)}apply({pagePoint:e,shiftKey:t,altKey:n,accelKey:i}){if(!this.info)return;if(e.x===this.info.lastPagePointX&&e.y===this.info.lastPagePointY&&t===this.info.lastShiftKey&&n===this.info.lastAltKey&&i===this.info.lastAccelKey)return;this.info.lastPagePointX=e.x,this.info.lastPagePointY=e.y,this.info.lastShiftKey=t,this.info.lastAltKey=n,this.info.lastAccelKey=i;const s=this.info.snapMode,o=this.info.snapSnapshot,r=!i&&"none"!==s&&null!==o,a=r&&o?this.editor.snaps.snapHandle({mode:s,pagePoint:e,snapshot:o,threshold:8/this.editor.state.camera.get().z}):null;r||this.editor.snaps.clearIndicators();const d=a?.snappedPagePoint??e,c=this.info.session.update({editor:this.editor,pagePoint:d,accelKey:i,source:"user"}),l="string"==typeof c?c:c.status,h="string"==typeof c?d:c.finalPagePoint;!a||!h||h.dist2(a.snappedPagePoint)<=1e-6||this.editor.snaps.clearIndicators(),"stop"===l&&this.complete()}complete(){const e=this.info;e&&(this.editor.interaction.setSnapIndicators(null),e.session.onComplete?.({editor:this.editor}),this.commitOperation(),this.transition("idle"))}},Ua=class extends Ra{constructor(e,t){super(e,"idle",t)}onEnter(){this.editor.interaction.clearSelection()}onPointerDown(e){const t=this.editor.selection.getIds(),n=this.editor.state.readonly.get()?null:this.editor.selection.hitTestHandle(e.pagePoint);if("rotate"===n?.kind)return void this.transition("pointing_rotate_handle",{originPagePoint:e.pagePoint.clone(),previousSelection:t});if("resize"===n?.kind)return void this.transition("pointing_resize_handle",{handleId:n.id,originPagePoint:e.pagePoint.clone(),cursorHandleOffset:e.pagePoint.sub(n.point),previousSelection:t});let i=null;if(n){const s=this.editor.state.selectedShapes.get()[0]??null;if(s){const o=this.editor.interactions.createSelectionHandleSession(this.editor,{handle:n,shape:s,originPagePoint:e.pagePoint.clone()});if(o){const s=o.handleSnapMode??"none";i={originPagePoint:e.pagePoint.clone(),previousSelection:t,session:o,snapSnapshot:"none"===s?null:this.editor.snaps.createHandleSnapshot({context:o.handleSnapContext??{shapeId:o.shapeId,handle:n},currentPagePoint:e.pagePoint,allowSelfSnap:o.allowSelfSnap??!1,excludedShapeIds:o.excludedSnapShapeIds})}}}}const s=this.editor.shapes.hitTest(e.pagePoint);let o=null;if(s){const n=this.editor.shapes.getUtil(s).getSelectionTargetId(s,{editor:this.editor}),i=this.editor.shapes.getUtil(s).getTranslateTargetId(s,{editor:this.editor}),r=Qs(e),a=Vs(this.editor,n,t),d=r?null:((e,t,n)=>{const i=new Set(n);for(const s of js(e,t))if(i.has(s.ancestorId))return s.ancestorId;return null})(this.editor,n,t),c=r?null:d?a:null,l=Vs(this.editor,i,t),h=null===c?l:d??l,p=this.editor.state.readonly.get()?null:this.editor.interactions.createShapePointerSession(this.editor,{shape:s,selectionTargetId:a,originPagePoint:e.pagePoint.clone(),event:e});o={shapeId:a,translateTargetId:h,originPagePoint:e.pagePoint.clone(),originTimestamp:e.timestamp,previousSelection:t,additiveSelection:r,wasSelected:t.includes(a),fromSelectionBounds:!1,quickClickSelectionTargetId:c,dragSession:p}}if(!i||"binding_middle"!==n?.kind&&"custom"!==n?.kind)if(o?.dragSession)this.transition("pointing_shape",o);else if(i)this.transition("pointing_selection_handle_interaction",i);else if(o)this.transition("pointing_shape",o);else{if(!this.editor.state.readonly.get()&&!Qs(e)&&t.length>0){const n=this.editor.state.selectedShapes.get()[0];if(n&&this.editor.shapes.getUtil(n).canStartTranslateFromSelectionBounds(n,{editor:this.editor})&&this.editor.selection.containsPoint(e.pagePoint))return void this.transition("pointing_shape",{shapeId:n.id,translateTargetId:n.id,originPagePoint:e.pagePoint.clone(),originTimestamp:e.timestamp,previousSelection:t,additiveSelection:!1,wasSelected:!0,fromSelectionBounds:!0,quickClickSelectionTargetId:null,dragSession:null})}this.transition("pointing_canvas",{originPagePoint:e.pagePoint.clone(),previousSelection:t,additiveSelection:Qs(e)})}else this.transition("pointing_selection_handle_interaction",i)}},Ha=class extends za{constructor(e,t){super(e,"pointing_canvas",t)}onDragThresholdExceeded(e){this.info&&this.transition("brushing",{...this.info,additiveSelection:Qs(e)})}onPointerUp(e){Qs(e)||this.editor.commands.setSelectedShapeIds([],{source:"system"}),this.transition("idle")}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.transition("idle")}},Wa=class extends za{constructor(e,t){super(e,"pointing_resize_handle",t)}onDragThresholdExceeded(){if(!this.info)return;const e=this.editor.selection.getFrame();if(!e)return void this.transition("idle");if(!this.editor.selection.canResize())return void this.transition("idle");const t=this.editor.selection.getResizeTargets(),n=new Map(t.flatMap(e=>{const t=fn(this.editor,e);return t?[[e.id,t]]:[]})),i=t.filter(e=>n.has(e.id));if(0===i.length)return void this.transition("idle");const s=((e,t,n,i)=>0===t.length?[]:Vn(e,t,n,Gn(e,t,i)))(this.editor,i,this.info.handleId,e.rotation);if(0===s.length)return void this.transition("idle");const o=(({shapes:e,selectionFrame:t,getShapeSelectionResizePageOutlineVertices:n,getShapeSelectionPagePoints:i,getShapeSelectionPageMiddlePoint:s,getShapePageRecord:o})=>{const r={rotation:t.rotation,rotationCenter:t.rotationCenter},a=[],d=[];for(const c of e){const e=o(c),t=i(e);t?d.push({shape:c,pageShape:e,startLocalPagePoint:_n(t[0],r),endLocalPagePoint:_n(t[1],r),middleLocalPagePoint:(()=>{const t=s(e);return t?_n(t,r):null})()}):a.push({shape:c,pageShape:e,localBounds:zr.FromPoints(n(c).map(e=>_n(e,r))),rotation:e.rotation})}return{startBounds:t.bounds.clone(),rotation:t.rotation,rotationCenter:t.rotationCenter.clone(),aspectRatio:0===t.bounds.h?1:t.bounds.w/t.bounds.h,shapes:a,pointShapes:d}})({shapes:i,selectionFrame:e,getShapeSelectionResizePageOutlineVertices:e=>function(e,t){const n=e.shapes.getUtil(t).getSelectionResizeLocalBounds(t),i=e.shapes.computeLocalToPageTransform(t);return(e=>[new Lr(e.minX,e.minY),new Lr(e.maxX,e.minY),new Lr(e.maxX,e.maxY),new Lr(e.minX,e.maxY)])(n).map(e=>i.applyToPoint(e))}(this.editor,e),getShapeSelectionPagePoints:e=>this.editor.shapes.getUtil(e).getSelectionPagePoints(e),getShapeSelectionPageMiddlePoint:e=>this.editor.shapes.getUtil(e).getSelectionPageMiddlePoint(e),getShapePageRecord:e=>n.get(e.id)});var r,a;this.transition("resizing",{...this.info,startBounds:o.startBounds,rotation:o.rotation,rotationCenter:o.rotationCenter,aspectRatio:o.aspectRatio,snapSnapshot:this.editor.snaps.createResizeSnapshot({resizingShapeIds:this.editor.layers.getSelectionTransformIds(this.editor.selection.getIds()),coordinateSpace:{rotation:o.rotation,rotationCenter:o.rotationCenter}}),shapes:o.shapes,pointShapes:o.pointShapes,updates:(r=o.shapes,a=o.pointShapes,[...r.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY})),...a.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY}))]),allowedResizeModes:s,lastPagePointX:NaN,lastPagePointY:NaN,lastShiftKey:!1,lastAltKey:!1,lastAccelKey:!1})}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}},qa=class extends za{constructor(e,t){super(e,"pointing_rotate_handle",t)}onDragThresholdExceeded(){if(!this.info)return;const e=this.editor.selection.getFrame();if(!e)return void this.transition("idle");if(!this.editor.selection.canRotate())return void this.transition("idle");const t=new Map(this.editor.selection.getRotationTargets().flatMap(e=>{const t=fn(this.editor,e);return t?[[e.id,t]]:[]})),n=this.editor.selection.getRotationTargets().filter(e=>t.has(e.id));if(0===n.length)return void this.transition("idle");const i=(({shapes:e,selectionFrame:t,getShapeLocalBounds:n,getShapeSelectionPagePoints:i,getShapeSelectionPageMiddlePoint:s,getShapePageRecord:o})=>{const r=[],a=[];for(const d of e){const e=o(d),t=i(e);t?a.push({shape:d,pageShape:e,startPagePoint:t[0],endPagePoint:t[1],middlePagePoint:s(e)}):r.push({shape:d,pageShape:e,localBounds:n(d),rotation:e.rotation})}return{center:t.rotationCenter.clone(),initialSelectionRotation:t.rotation,shapes:r,pointShapes:a}})({shapes:n,selectionFrame:e,getShapeLocalBounds:e=>this.editor.shapes.computeLocalBounds(e),getShapeSelectionPagePoints:e=>this.editor.shapes.getUtil(e).getSelectionPagePoints(e),getShapeSelectionPageMiddlePoint:e=>this.editor.shapes.getUtil(e).getSelectionPageMiddlePoint(e),getShapePageRecord:e=>t.get(e.id)});var s,o;this.transition("rotating",{...this.info,center:i.center,startAngle:Lr.Angle(i.center,this.info.originPagePoint),initialSelectionRotation:i.initialSelectionRotation,shapes:i.shapes,pointShapes:i.pointShapes,updates:(s=i.shapes,o=i.pointShapes,[...s.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY})),...o.map(e=>({id:e.shape.id,x:e.shape.x,y:e.shape.y,rotation:e.shape.rotation,scaleX:e.shape.scaleX,scaleY:e.shape.scaleY}))]),lastPointerX:NaN,lastPointerY:NaN,lastShiftKey:!1,lastAccelKey:!1})}onPointerUp(){this.transition("idle")}onCancel(){this.transition("idle")}},Ga=class extends za{constructor(e,t){super(e,"pointing_selection_handle_interaction",t)}onDragThresholdExceeded(){this.info&&this.transition("dragging_plugin_interaction",{...this.info,snapMode:this.info.session.handleSnapMode??"none",lastPagePointX:NaN,lastPagePointY:NaN,lastShiftKey:!1,lastAltKey:!1,lastAccelKey:!1})}onPointerUp(e,t){if(this.info){const e={editor:this.editor,source:"user"};(t.pointer?.clickCount??1)>=2&&this.info.session.onDoubleClick?this.info.session.onDoubleClick(e):this.info.session.onClick?.(e)}this.transition("idle")}onCancel(e){this.info?.session.onCancel?.({editor:this.editor,reason:e.reason}),this.transition("idle")}},Va=class extends za{constructor(e,t){super(e,"pointing_shape",t)}onInfoEnter(){this.info&&(this.info.quickClickSelectionTargetId||(this.info.additiveSelection?this.info.wasSelected||this.editor.commands.setSelectedShapeIds([...this.info.previousSelection,this.info.shapeId],{source:"system"}):this.info.wasSelected||this.editor.commands.setSelectedShapeIds([this.info.shapeId],{source:"system"})))}onDragThresholdExceeded(e){if(!this.info||this.editor.state.readonly.get())return;if(this.info.dragSession)return void this.transition("dragging_plugin_interaction",{originPagePoint:this.info.originPagePoint,previousSelection:this.info.previousSelection,session:this.info.dragSession,snapMode:"none",snapSnapshot:null,lastPagePointX:NaN,lastPagePointY:NaN,lastShiftKey:!1,lastAltKey:!1,lastAccelKey:!1});const t=this.editor.state.selectedShapes.get(),n=this.info.wasSelected?t.map(e=>e.id):[this.info.translateTargetId];this.info.wasSelected||1!==n.length||n[0]===this.info.shapeId||this.editor.commands.setSelectedShapeIds(n,{source:"system"});const i=this.editor.selection.getFrame(),s=((e,t)=>t.filter(t=>{const n=e.shapes.get(t);return!!n&&e.shapes.getUtil(n).canParticipateInSelectionTranslation(n,{editor:e})&&!e.layers.isOrAncestorLocked(n.id)&&!e.layers.hasLockedDescendant(n.id)}).map(t=>e.shapes.get(t)).filter(e=>!!e).flatMap(t=>(t.parentId.startsWith("shape:")?e.shapes.computeLocalToPageTransform(e.shapes.get(t.parentId)):Wr.Identity()).tryInvert()?[{id:t.id,x:t.x,y:t.y,startLocalToPage:e.shapes.computeLocalToPageTransform(t)}]:[]))(this.editor,n);if(0===s.length)return void this.transition("brushing",{originPagePoint:this.info.originPagePoint,previousSelection:this.info.previousSelection,additiveSelection:Qs(e)});const o=s.map(e=>e.id),r=i?.hasCompatibleRotation?i.rotation:0,a=i?.rotationCenter.clone()??Lr.Zero(),d=i?.hasCompatibleRotation?i.bounds.clone():this.editor.selection.getPageBounds();var c;this.transition("translating",{originPagePoint:this.info.originPagePoint,previousSelection:this.info.previousSelection,movingShapeIds:o,startBounds:d,snapSnapshot:this.editor.snaps.createTranslateSnapshot({movingShapeIds:o,coordinateSpace:{rotation:r,rotationCenter:a}}),snapRotation:r,selectedShapes:s,updates:(c=s,c.map(e=>({id:e.id,x:e.x,y:e.y}))),lockedAxis:null,lastDeltaX:NaN,lastDeltaY:NaN})}onPointerUp(e,t){let n;if(this.info?.quickClickSelectionTargetId){const i=((e,t)=>t.timestamp-e.originTimestamp<=250)(this.info,e);i&&this.editor.commands.setSelectedShapeIds([this.info.quickClickSelectionTargetId],{source:"system"}),i&&(t.pointer?.clickCount??1)>=2||(n={clickSequence:"break"})}else Qs(e)&&this.info?.wasSelected?this.editor.commands.setSelectedShapeIds(this.info.previousSelection.filter(e=>e!==this.info?.shapeId),{source:"system"}):this.info&&!this.info.additiveSelection&&this.info.wasSelected&&!this.info.fromSelectionBounds&&this.info.previousSelection.length>1&&this.editor.commands.setSelectedShapeIds([this.info.shapeId],{source:"system"});return this.transition("idle"),n}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.transition("idle")}},ja=class extends _a{constructor(e,t){super(e,"resizing",t)}getOperationKind(){return"select.resize"}onDragStart(){this.editor.interaction.setSnapIndicators(null)}onPointerUp(e){this.apply(e),this.complete()}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}onInfoExit(){this.editor.interaction.setSnapIndicators(null)}apply({pagePoint:e,shiftKey:t,altKey:n,accelKey:i}){if(!this.info)return;if(e.x===this.info.lastPagePointX&&e.y===this.info.lastPagePointY&&t===this.info.lastShiftKey&&n===this.info.lastAltKey&&i===this.info.lastAccelKey)return;this.info.lastPagePointX=e.x,this.info.lastPagePointY=e.y,this.info.lastShiftKey=t,this.info.lastAltKey=n,this.info.lastAccelKey=i;const s=no(this.info.rotationCenter,this.info.rotation),o=_n(e.sub(this.info.cursorHandleOffset),s),r=((e,t)=>{const n=e.includes("free"),i=e.includes("aspect_ratio_locked");return n||i?n?i&&t?"aspect_ratio_locked":"free":"aspect_ratio_locked":null})(this.info.allowedResizeModes,t);if(!r)return;const a="aspect_ratio_locked"===r,d=function({startBounds:e,handleId:t,pagePoint:n,isAspectRatioLocked:i,isResizingFromCenter:s,aspectRatio:o}){const r=s?(({startBounds:e,handleId:t,pagePoint:n})=>{const i=e.center,s=n.x-i.x,o=n.y-i.y,r=Math.max(Math.abs(s),.5),a=Math.max(Math.abs(o),.5),d=Oi(t)||Li(t)?s*(Oi(t)?-2:2)/Math.max(1,e.w):1,c=zi(t)||_i(t)?o*(zi(t)?-2:2)/Math.max(1,e.h):1;switch(t){case"top":case"bottom":return{bounds:new zr(e.minX,i.y-a,e.w,2*a),scaleX:d,scaleY:c};case"left":case"right":return{bounds:new zr(i.x-r,e.minY,2*r,e.h),scaleX:d,scaleY:c};default:return{bounds:new zr(i.x-r,i.y-a,2*r,2*a),scaleX:d,scaleY:c}}})({startBounds:e,handleId:t,pagePoint:n}):(({startBounds:e,handleId:t,pagePoint:n})=>{const i=e.minX,s=e.maxX,o=e.minY,r=e.maxY;let a=Oi(t)?i:s,d=Oi(t)?s:i,c=zi(t)?o:r,l=zi(t)?r:o;Oi(t)||Li(t)?a=n.x:(a=s,d=i),zi(t)||_i(t)?c=n.y:(c=r,l=o);const h=a-d,p=c-l,u=Oi(t)?d-a:h,g=zi(t)?l-c:p,f=Oi(t)||Li(t)?u/Math.max(1,e.w):1,m=zi(t)||_i(t)?g/Math.max(1,e.h):1;return{bounds:new zr(Math.min(a,d),Math.min(c,l),Math.max(1,Math.abs(h)),Math.max(1,Math.abs(p))),scaleX:f,scaleY:m}})({startBounds:e,handleId:t,pagePoint:n});return i?Ui({bounds:r.bounds,startBounds:e,handleId:t,aspectRatio:o,isResizingFromCenter:s,scaleX:r.scaleX,scaleY:r.scaleY}):r}({startBounds:this.info.startBounds,handleId:this.info.handleId,pagePoint:o,isAspectRatioLocked:a,isResizingFromCenter:n,aspectRatio:this.info.aspectRatio}),c=!i&&this.info.snapSnapshot.points.length>0,l=c?this.editor.snaps.snapResize({handleId:this.info.handleId,initialSelectionBounds:this.info.startBounds,resizedSelectionBounds:d.bounds,scaleX:d.scaleX,scaleY:d.scaleY,snapshot:this.info.snapSnapshot,threshold:8/this.editor.state.camera.get().z,isAspectRatioLocked:a,isResizingFromCenter:n}):d;c||this.editor.snaps.clearIndicators();const h=this.info.shapes.length+this.info.pointShapes.length===1;for(let p=0;p<this.info.shapes.length;p+=1){const e=this.info.shapes[p],t=this.info.updates[p];e&&t&&to(this.editor,e,this.info.startBounds,l.bounds,l.scaleX,l.scaleY,this.info.handleId,h,n,this.info.rotationCenter,this.info.rotation,t)}for(let p=0;p<this.info.pointShapes.length;p+=1){const e=this.info.pointShapes[p],t=this.info.updates[this.info.shapes.length+p];e&&t&&io(this.editor,e,this.info.startBounds,0,l.scaleX,l.scaleY,this.info.handleId,n,this.info.rotationCenter,this.info.rotation,t)}this.editor.commands.updateShapes(this.info.updates)}complete(){this.editor.interaction.setSnapIndicators(null),this.commitOperation(),this.transition("idle")}cancel(){this.editor.interaction.setSnapIndicators(null),this.cancelOperation(),this.transition("idle")}},Qa=class extends _a{constructor(e,t){super(e,"rotating",t)}getOperationKind(){return"select.rotate"}onPointerUp(e){this.apply(e),this.complete()}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}apply({pagePoint:e,shiftKey:t,accelKey:n}){if(!this.info)return;if(e.x===this.info.lastPointerX&&e.y===this.info.lastPointerY&&t===this.info.lastShiftKey&&n===this.info.lastAccelKey)return;this.info.lastPointerX=e.x,this.info.lastPointerY=e.y,this.info.lastShiftKey=t,this.info.lastAccelKey=n;let i=Js(Lr.Angle(this.info.center,e)-this.info.startAngle);if(t)i=eo(i,Fa);else if(!n&&this.editor.inputs.state.get().screenVelocity.len()<.5){const e=this.info.initialSelectionRotation+i,t=eo(e,Da),n=Js(t-e);Math.abs(n)<=Oa&&(i=Js(t-this.info.initialSelectionRotation))}for(let s=0;s<this.info.shapes.length;s+=1){const e=this.info.shapes[s],t=this.info.updates[s];e&&t&&oo(this.editor,e,this.info.center,i,t)}for(let s=0;s<this.info.pointShapes.length;s+=1){const e=this.info.pointShapes[s],t=this.info.updates[this.info.shapes.length+s];e&&t&&ro(this.editor,e,this.info.center,i,t)}this.editor.commands.updateShapes(this.info.updates)}complete(){this.commitOperation(),this.transition("idle")}cancel(){this.cancelOperation(),this.transition("idle")}},Za=class extends _a{constructor(e,t){super(e,"translating",t)}getOperationKind(){return"select.translate"}onDragStart(){this.editor.interaction.setSelectionTranslationActive(!0),this.editor.interaction.setSnapIndicators(null)}onPointerUp(e){this.apply(e),this.complete(e.pagePoint)}onCancel(){this.info&&this.editor.commands.setSelectedShapeIds(this.info.previousSelection,{source:"system"}),this.cancel()}onInfoExit(){this.editor.interaction.setSelectionTranslationActive(!1),this.editor.interaction.setSnapIndicators(null)}apply({pagePoint:e,shiftKey:t,accelKey:n}){if(!this.info)return;const i=e.x-this.info.originPagePoint.x,s=e.y-this.info.originPagePoint.y;t?this.info.lockedAxis||0===i&&0===s||(this.info.lockedAxis=Math.abs(i)>=Math.abs(s)?"x":"y"):this.info.lockedAxis=null;let o=i,r=s;"x"===this.info.lockedAxis?r=0:"y"===this.info.lockedAxis&&(o=0);const a=this.info.startBounds;if(!n&&a&&(this.info.snapSnapshot.points.length>0||this.info.snapSnapshot.nodes.length>0)&&this.editor.inputs.state.get().screenVelocity.len()<.5&&a){const e=this.info.snapRotation,t=8/this.editor.state.camera.get().z,n=0===e?new Lr(o,r):new Lr(o,r).rot(-e),{nudge:i}=this.editor.snaps.snapTranslate({lockedAxis:this.info.lockedAxis,initialSelectionBounds:a,dragDelta:n,snapshot:this.info.snapSnapshot,threshold:t}),s=0===e?i:i.rot(e);o+="y"===this.info.lockedAxis?0:s.x,r+="x"===this.info.lockedAxis?0:s.y}else this.editor.snaps.clearIndicators();if(o!==this.info.lastDeltaX||r!==this.info.lastDeltaY){this.info.lastDeltaX=o,this.info.lastDeltaY=r;for(let e=0;e<this.info.selectedShapes.length;e+=1){const t=this.info.selectedShapes[e],n=this.info.updates[e];if(!t||!n)continue;const i=this.editor.shapes.get(t.id);if(!i)continue;const s=i.parentId.startsWith("shape:")?this.editor.shapes.get(i.parentId):null,a=(s?this.editor.shapes.computeLocalToPageTransform(s):Wr.Identity()).tryInvert();if(!a)continue;const d=Pe(a.compose(Wr.Translate(o,r).compose(t.startLocalToPage)),this.editor.shapes.computeLocalBounds(i),{preferredRotation:i.rotation,preferredScaleXSign:i.scaleX,preferredScaleYSign:i.scaleY});d&&Object.assign(n,d)}this.editor.commands.updateShapes(this.info.updates)}lo(this.editor,this.info.movingShapeIds,e),((e,t,n)=>{const i=co(e,t,n);if(i===ao(e,t))return void e.interaction.setDropTargetShapeId(null);const s=i?e.shapes.get(i):null;e.interaction.setDropTargetShapeId(s?.id??null)})(this.editor,this.info.movingShapeIds,e)}complete(e){this.info&&lo(this.editor,this.info.movingShapeIds,e),this.editor.interaction.setDropTargetShapeId(null),this.editor.interaction.setSnapIndicators(null),this.commitOperation(),this.transition("idle")}cancel(){this.editor.interaction.setDropTargetShapeId(null),this.editor.interaction.setSnapIndicators(null),this.cancelOperation(),this.transition("idle")}},Ja=class extends Ra{constructor(e){super(e,"select"),this.initial="idle",this.addChild(new Ua(e,this)),this.addChild(new Ha(e,this)),this.addChild(new $a(e,this)),this.addChild(new Va(e,this)),this.addChild(new Za(e,this)),this.addChild(new Wa(e,this)),this.addChild(new ja(e,this)),this.addChild(new qa(e,this)),this.addChild(new Qa(e,this)),this.addChild(new Ga(e,this)),this.addChild(new Na(e,this))}},ed=cr(null),td=cr(go([])),nd="var(--land-shape-hover, var(--land-selection, #2563eb))",id=2,sd=lr(e=>{const{Component:t,editor:n,isSelected:i,shape:s,shapeEditingSession:o}=e;
23
23
  return Pr(t,{editor:n,isSelected:i,shape:s,shapeEditingSession:o})}),od=lr(({shapeId:e,stackingOrder:t})=>{const n=po(),i=Po(n.shapes.getSignal(e)),s=Po(n.shapes.getLocalToPageTransformSignal(e)),o=Po(n.shapes.getRenderVisibleSignal(e)),r=Po(n.shapes.getSelectedSignal(e)),a=Po(n.shapes.getEditingSessionSignal(e)),d=Po(n.shapes.getEffectiveOpacitySignal(e)),c=Po(n.shapes.getClipAncestorIdsSignal(e)),l=Io(),h=Po(mr(()=>l.getShapeOpacityValue(n,e),[n,l,e]));if(!i||!s)return null;const p=l.getShapeRenderer(i.type)?.foregroundComponent;if(!p)return null;const u=Bo(n,i,s),g=d*h;
24
24
  return Pr("div",{"data-ui":"shape-foreground","data-owner-shape-id":i.id,"data-owner-shape-type":i.type,"data-owner-shape-sub-type":i.subType??void 0,style:{position:"absolute",display:o?void 0:"none",left:u.left,top:u.top,width:u.width,height:u.height,opacity:1===g?void 0:g,transform:u.transform,transformOrigin:u.transformOrigin,pointerEvents:"none",zIndex:t+1},children:o?Pr(bo,{clipAncestorIds:c,shapeElementToPage:u.elementToPage,children:Pr(sd,{Component:p,shape:i,editor:n,isSelected:r,shapeEditingSession:a})}):null})}),rd=lr(({shapeId:e,stackingOrder:t})=>{const n=po(),i=Po(n.shapes.getSignal(e)),s=Po(n.shapes.getLocalToPageTransformSignal(e)),o=Po(n.shapes.getHoveredSignal(e)),r=Po(n.state.selectionCount),a=Po(n.render.interaction.brushBoxActive),d=Po(n.shapes.getRenderVisibleSignal(e)),c=Po(n.state.tool).activeToolId,l=Po(n.shapes.getSelectedSignal(e)),h="select"===c&&l,p=Po(n.shapes.getEditingSessionSignal(e)),u=Po(n.shapes.getRenderOrderSignal(e)),g=Po(n.shapes.getDropTargetSignal(e)),f=Po(n.shapes.getEffectiveOpacitySignal(e)),m=Po(n.shapes.getClipAncestorIdsSignal(e)),S=Io(),y=Po(mr(()=>S.getShapeOpacityValue(n,e),[n,S,e]));if(!i||!s)return null;const I=S.getShapeRenderer(i.type);if(!I)return null;const w=I.component,P=I.hoverComponent,b=S.getShapeDecorations(i.subType),v=o&&!(1===r&&h)&&!a,x=Bo(n,i,s),C=f*y;
25
25
  return br("div",{"data-ui":"shape-instance","data-shape-id":i.id,"data-shape-type":i.type,"data-selected":h?"true":"false","data-hovered":v?"true":"false","data-drop-target":g?"true":"false","data-visible":d?"true":"false","data-render-order":u>=0?String(u):void 0,"data-clip-ancestor-count":m.length,style:{position:"absolute",display:d?void 0:"none",left:x.left,top:x.top,width:x.width,height:x.height,opacity:1===C?void 0:C,transform:x.transform,transformOrigin:x.transformOrigin,pointerEvents:"none",outline:g?"2px solid #2563eb":void 0,outlineOffset:g?4:void 0,boxShadow:g?"0 0 0 6px rgba(37, 99, 235, 0.16)":void 0,zIndex:t+1},children:[d?br(bo,{clipAncestorIds:m,shapeElementToPage:x.elementToPage,children:[
package/index.mjs CHANGED
@@ -3,4 +3,4 @@ return Vt(_t.Provider,{value:o,children:e})}function i(){const{registerTarget:e}
3
3
  return Vt(Yt.Provider,{value:e,children:t})}function u(){const e=Bt(Yt);if(!e)throw new Error("useCanvasKit must be used inside CanvasKitProvider.");return e}function p(e){return jt(e.subscribe,e.getSnapshot,e.getSnapshot)}function h({contributions:e,getHostElement:t,isEditing:n,onError:s,screenToPage:o}){return Nt(()=>{const r=o=>{if(!y(t(),o)||n()||Tt(o.target))return;const r=w({source:"clipboard",dataTransfer:o.clipboardData});f(e,r)&&(o.preventDefault(),m(e,r).catch(e=>{s(new Error("Canvas clipboard import failed.",{cause:e}))}))},i=s=>{!y(t(),s)||n()||Tt(s.target)||g(e,v(s.dataTransfer))&&(s.preventDefault(),s.dataTransfer&&(s.dataTransfer.dropEffect="copy"))},a=r=>{const i=y(t(),r);if(!i||n()||Tt(r.target))return;const a=g(e,v(r.dataTransfer)),c=w({source:"drop",dataTransfer:r.dataTransfer,pagePoint:o(At(r,i))});f(e,c)?(r.preventDefault(),m(e,c).catch(e=>{s(new Error("Canvas drop import failed.",{cause:e}))})):a&&(r.preventDefault(),r.dataTransfer&&(r.dataTransfer.dropEffect="none"))};return window.addEventListener("paste",r),window.addEventListener("dragover",i),window.addEventListener("drop",a),()=>{window.removeEventListener("paste",r),window.removeEventListener("dragover",i),window.removeEventListener("drop",a)}},[e,t,n,s,o]),null}function f(e,t){return e.some(e=>e.accepts(t))}function g(e,t){return e.some(e=>e.acceptsPreview?.(t)??!1)}async function m(e,t){for(const n of e)if(n.accepts(t)&&"handled"===await n.import(t))return"handled";return"ignored"}function v(e){return e?{source:"drop",dataTypes:Array.from(e.types),fileTypes:Array.from(e.items).filter(e=>"file"===e.kind).map(e=>e.type).filter(Boolean)}:{source:"drop",dataTypes:[],fileTypes:[]}}function w({dataTransfer:e,pagePoint:t,source:n}){const s=e?.getData("text/plain")||void 0,o=e?.getData("text/html")||void 0,r=[...(e?.getData("text/uri-list")||void 0)?.split(/\r?\n/).filter(e=>e&&!e.startsWith("#"))??[],...s&&x(s.trim())?[s.trim()]:[]];return{source:n,files:b(e),text:s,html:o,...r.length>0?{urls:r}:{},pagePoint:t}}function y(e,t){if(!e)return null;const n=(t.target instanceof Element?t.target:document.activeElement)?.closest(Ct);return n instanceof HTMLElement&&e.contains(n)?n:null}function b(e){if(!e)return[];const t=Array.from(e.files);return t.length>0?t:Array.from(e.items).flatMap(e=>{if("file"!==e.kind)return[];const t=e.getAsFile();return t?[t]:[]})}function x(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return e.startsWith("data:image/")}}function S({bindings:e,getHostElement:t,onError:n}){const s=u(),o=p(s.viewport.grid.state),{editor:r,importContributions:i,renderBindings:a,setContextMenu:c}=e,l=Ft(()=>s.tools.state.getSnapshot().isEditing,[s]),d=Ft(e=>r.viewport.screenToPage(e),[r]);
4
4
  return Wt(zt,{children:[Vt(ht.Provider,{value:r,children:Vt(Lt,{onContextMenuRequest:c,renderBindings:a,showGrid:o})}),Vt(h,{contributions:i,getHostElement:t,isEditing:l,onError:n,screenToPage:d})]})}function E(e){return void 0===e?[]:Array.isArray(e)?e:[e]}function I(e,t){if(!t||0===Object.keys(t).length)return e;const n=new Set(Object.keys(t)),s=e.map(e=>{if(!Object.prototype.hasOwnProperty.call(t,e.id))return e;n.delete(e.id);const s=t[e.id];return{...e,shortcut:s??void 0}});if(n.size>0)throw new Error(`Unknown CanvasAction shortcut override ids: ${[...n].join(", ")}.`);return s}function C(e,t){if(e.api&&!t?.api)throw new Error(`Canvas plugin "${e.id}" declares API "${e.api.id}" but setup returned no API value.`);if(!e.api&&t?.api)throw new Error(`Canvas plugin "${e.id}" returned an API value without declaring an API token.`)}function T(e,t){return new Set((e.requires??[]).flatMap(e=>{const n=t.get(e.id);return n?.api?[n.api.id]:[]}))}function P(e,t){const n=new Set;for(const s of e){if(n.has(s))throw new Error(`Duplicate ${t} id: ${s}.`);n.add(s)}}function k(e){return"provider"===e.kind}function R(e){return"svg-inliner"===e.kind}function L(e,t){const n=new Set;for(const s of e){if(n.has(s))throw new Error(`Duplicate ${t}: ${s}.`);n.add(s)}}function A(){if("undefined"!=typeof window&&"function"==typeof window.requestAnimationFrame&&"function"==typeof window.cancelAnimationFrame)return{requestFrame:e=>window.requestAnimationFrame(e),cancelFrame:e=>window.cancelAnimationFrame(e),prefersReducedMotion:()=>"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}}function D(e){return{id:e.id,name:e.name,index:e.index,meta:{...e.meta}}}function M(e){return{id:e?.id??"document:main",meta:{...e?.meta??{}}}}function O(e,t){return{id:e.id,type:e.type,subType:e.subType,parentId:e.parentId,pageId:t,index:e.index,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,props:{...e.props},meta:{...e.meta}}}function F(e){const{editor:t}=e,n=t.state.session.get(),s=n.activeToolId;e.assertToolId(s);const o=t.pages.getAll().map(e=>({pageId:e.id,selectedShapeIds:[...t.selection.getIds(e.id)],camera:{...t.viewport.getCamera(e.id)}}));return{currentPageId:n.currentPageId,activeToolId:s,isToolLocked:n.isToolLocked,meta:{...n.meta},pages:o}}function B(e){return{type:e.type,subType:e.subType,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,parentId:e.parentId,index:e.index,props:e.props?{...e.props}:void 0,meta:e.meta?{...e.meta}:void 0}}function N(e){return{id:e.id,subType:e.subType,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,parentId:e.parentId,index:e.index,props:e.props?{...e.props}:void 0,meta:void 0===e.meta?void 0:{...e.meta}}}function $({childIds:e,companionIds:t,context:n,depth:s,editor:o,index:r,pageId:i,shape:a}){return{id:a.id,parentId:a.parentId,pageId:i,type:a.type,companionIds:t,childIds:e,siblingIndex:r,depth:s,canReceiveChildren:o.layers.canReceiveChildren(a.id),isHidden:a.isHidden,isLocked:a.isLocked,isEffectivelyHidden:z(o,n,a.id),isEffectivelyLocked:V(n,a.id)}}function H({bindings:e,editor:t,shapes:n}){const s=new Map(n.map(e=>[e.id,e])),o=t.bindings.getShapeCompanionRootIds(n.map(({id:e})=>e),e),r=new Map,i=new Map,a=new Map;for(const c of n){const e=o.get(c.id)??c.id,t=s.has(e)?e:c.id;if(r.set(c.id,t),t===c.id){const e=a.get(c.parentId);e?e.push(c):a.set(c.parentId,[c])}else{const e=i.get(t);e?e.push(c.id):i.set(t,[c.id])}}return{childShapesByParentId:a,companionIdsByRootId:i,rootIdByShapeId:r,shapeById:s}}function K(e,t){return e.childShapesByParentId.get(t)??[]}function j(e,t){let n=0,s=e.shapeById.get(t);const o=new Set([t]);for(;s?.parentId.startsWith("shape:");){const t=s.parentId;if(o.has(t))break;o.add(t),s=e.shapeById.get(t),n+=1}return n}function z(e,t,n){const s=new Set;let o=t.shapeById.get(n);for(;o;){if(o.isHidden)return!0;if(!o.parentId.startsWith("shape:"))return!1;const n=o.parentId;if(s.has(n))return!1;s.add(n);const r=t.shapeById.get(n);if(!r)return!1;if(!e.shapes.getUtil(r).isChildVisible(r,o,{editor:e}))return!0;o=r}return!1}function V(e,t){const n=new Set;let s=e.shapeById.get(t);for(;s;){if(s.isLocked)return!0;if(!s.parentId.startsWith("shape:"))return!1;const t=s.parentId;if(n.has(t))return!1;n.add(t),s=e.shapeById.get(t)}return!1}function W(e){let t=e;const n=new Set;return{readable:{getSnapshot:()=>t,subscribe:e=>(n.add(e),()=>n.delete(e))},set(e){if(!Object.is(t,e)){t=e;for(const e of[...n])e()}}}}function q({getDependencies:e,getSnapshot:t,name:n,signals:s}){let o,r=[],i=!1;const a=()=>{const n=e();return i&&((e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Object.is(e[n],t[n]))return!1;return!0})(r,n)||(r=n,o=t(n),i=!0),o};return{getSnapshot:a,subscribe(t){let o=a();return It(n,{get:e,graph:s},()=>{const e=a();Object.is(o,e)||(o=e,t())},{fireImmediately:!1})}}}function U({apis:e,editor:t,exports:n,productId:s,startup:o}){const r=e=>(e?e.map(e=>t.shapes.get(e)).filter(e=>!!e):t.pages.getAll().flatMap(e=>t.shapes.getForPage(e.id))).map(e=>O(e,t.layers.getPageId(e.id))),i=e=>{const[n,...s]=e;return(({bindings:e,editor:t,pageId:n,shapes:s})=>{const o=[],r=H({bindings:e,editor:t,shapes:s}),i=(e,s)=>{K(r,e).forEach((e,a)=>{const c=K(r,e.id).map(e=>e.id);o.push($({childIds:c,companionIds:r.companionIdsByRootId.get(e.id)??[],context:r,depth:s,editor:t,index:a,pageId:n,shape:e})),i(e.id,s+1)})};return i(n,0),o})({bindings:s.filter(Et),editor:t,pageId:n,shapes:s.filter(Mt)})},a=e=>{if(!t.tools.hasTool(e))throw new Error(`Unknown canvas kit tool "${e}".`)},c={assertToolId:a,editor:t,productId:s},{readable:l,set:d}=W(!1),{readable:u,set:p}=W(null),h=q({signals:t.signals,name:"CanvasKit.document",getDependencies:()=>[t.document.getMetadata()],getSnapshot:([e])=>M(e)}),f=q({signals:t.signals,name:"CanvasKit.document.readonlyState",getDependencies:()=>[t.state.readonly.get()],getSnapshot:([e])=>e}),g=q({signals:t.signals,name:"CanvasKit.session",getDependencies:()=>[t.state.session.get().meta],getSnapshot:([e])=>({meta:{...e}})}),m=q({signals:t.signals,name:"CanvasKit.selection",getDependencies:()=>[t.state.selectedShapeIds.get(),t.state.selectedShapes.get(),t.state.selectionMetadata.get(),t.state.selectionPageBounds.get(),t.state.selectionAnchorPagePoint.get(),t.render.interaction.selectionTranslationActive.get(),t.state.currentPageId.get()],getSnapshot:([e,t,n,s,o,r,i])=>({...n,ids:[...e],shapes:t.map(e=>O(e,i)),pageBounds:s?{x:s.minX,y:s.minY,width:s.w,height:s.h}:null,anchorPagePoint:o?{x:o.x,y:o.y}:null,isTranslating:r})}),v=q({signals:t.signals,name:"CanvasKit.pages",getDependencies:()=>[t.state.pages.get(),t.state.currentPageId.get(),t.state.currentPageShapeIds.get()],getSnapshot:([e,t,n])=>{const s=e.map(D),o=s.find(e=>e.id===t)??null;return{pages:s,currentPage:o,currentPageId:t,currentPageShapeIds:[...n],canDeleteCurrentPage:s.length>1&&null!==o}}}),w=q({signals:t.signals,name:"CanvasKit.history",getDependencies:()=>[t.state.history.get()],getSnapshot:([e])=>({...e})}),y=q({signals:t.signals,name:"CanvasKit.viewport",getDependencies:()=>[t.state.camera.get(),t.state.cameraLock.get(),t.state.pageTransform.get()],getSnapshot:([e,t,n])=>({camera:{...e},lock:t?{...t.pagePoint}:null,zoom:e.z,pageTransform:n.toCssString()})}),b=q({signals:t.signals,name:"CanvasKit.tools",getDependencies:()=>[t.state.tool.get(),t.state.shapeEditing.get()],getSnapshot:([e,t])=>(a(e.activeToolId),{currentToolId:e.activeToolId,isLocked:e.isToolLocked,isEditing:null!==t.session})}),x=q({signals:t.signals,name:"CanvasKit.layers",getDependencies:()=>_(t,t.pages.getCurrentId()),getSnapshot:i});return{canvas:{startup:o,api:t=>e.get(t)??void 0,document:{state:h,readonlyState:f,getSnapshot:()=>(e=>{const{editor:t}=e,n=t.state.tool.get().activeToolId;return e.assertToolId(n),{productId:e.productId,document:M(t.document.getMetadata()),pageId:t.pages.getCurrentId(),activeToolId:n,selectedShapeIds:[...t.selection.getIds()],shapeCount:t.state.currentPageShapeIds.get().length,session:F(e)}})(c),updateMeta:e=>(t.document.updateMetadata({...e},"user"),M(t.document.getMetadata()))},session:{state:g,updateMeta(e){const n=t.session.get();return t.session.update({meta:{...n.meta,...e}},"user"),{meta:{...t.state.session.get().meta}}}},selection:{state:m,select:e=>t.commands.setSelectedShapeIds([...e],{source:"user"}),selectAll:()=>t.selection.selectAll("user"),clear:()=>t.commands.setSelectedShapeIds([],{source:"user"}),delete:()=>t.selection.delete("user"),duplicate:()=>t.selection.duplicate({source:"user"}),resetRotation:()=>t.selection.resetRotation("user"),flip:e=>t.selection.flip(e,"user"),setOpacity:e=>((e,t)=>{if(!Number.isFinite(t))return;const n=Math.min(1,Math.max(0,t)),s=e.state.selectedShapes.get().filter(e=>e.opacity!==n).map(e=>({id:e.id,opacity:n}));s.length>0&&e.commands.updateShapes(s,{source:"user"})})(t,e),align:e=>t.selection.align(e,"user"),distribute:e=>t.selection.distribute(e,"user")},pages:{state:v,create:e=>D(t.pages.createAndSelect(e?{name:e.name,meta:e.meta?{...e.meta}:void 0}:void 0,"user")),rename:(e,n)=>t.pages.rename(e,n,"user"),updateMeta:(e,n)=>t.pages.updateMetadata(e,{...n},"user")?.id??null,delete:e=>t.pages.delete(e,"user"),deleteCurrent:()=>t.pages.delete(t.pages.getCurrentId(),"user"),setCurrent:e=>t.pages.select(e,"user")},history:{state:w,clear:()=>t.history.clear(),undo:()=>t.history.undo(),redo:()=>t.history.redo()},viewport:{state:y,grid:{state:l,setVisible:d,toggle:()=>d(!l.getSnapshot())},setCamera:(e,n)=>t.commands.setCamera({pageId:n,camera:e},{source:"user"}),setLock:e=>t.viewport.setLock(e),zoomIn:()=>t.viewport.zoomAtCenter(-120,"system"),zoomOut:()=>t.viewport.zoomAtCenter(120,"system"),resetZoom:()=>t.viewport.resetZoom("user"),reset:()=>t.commands.setCamera({camera:{x:0,y:0,z:1}},{source:"user"})},tools:{state:b,setCurrent:e=>{if(!t.tools.hasTool(e))throw new Error(`Unknown product tool "${e}".`);t.tools.select(e,"user")},setLocked:e=>t.tools.setLocked(e,"user"),toggleLocked:()=>t.tools.toggleLocked("user")},shapes:{create:e=>((e,t)=>0===t.length?[]:e.commands.createShapes(t.map(B),{source:"user"}).map(e=>e.id))(t,e),get:e=>{const n=t.shapes.get(e);return n?O(n,t.layers.getPageId(n.id)):null},getMany:e=>r(e),getAll:()=>r(),getExportBounds:(e,n)=>{const s=t.shapes.get(e);if(!s)return null;let o;switch(n.space.type){case"shape-local":{const e=t.shapes.get(n.space.shapeId);if(!e)return null;if(o=t.shapes.computeExportBoundsInShapeSpace(s,e),!o)return null;break}case"page":o=t.shapes.computeExportPageBounds(s);break;default:throw new Error(`Unsupported canvas shape export bounds space "${String(n.space)}".`)}return![o.x,o.y,o.w,o.h].every(Number.isFinite)||o.w<0||o.h<0?null:{x:o.x,y:o.y,width:o.w,height:o.h}},update:e=>function(e,t){const n=t.filter(t=>{const n=e.shapes.get(t.id);return!!n&&((e,t)=>{return!(!t.props&&void 0===t.meta)||(void 0===t.subType?e.subType:t.subType)!==e.subType||(t.x??e.x)!==e.x||(t.y??e.y)!==e.y||(t.rotation??e.rotation)!==e.rotation||(t.scaleX??e.scaleX)!==e.scaleX||(t.scaleY??e.scaleY)!==e.scaleY||(void 0===t.opacity?e.opacity:(s=e.opacity,"number"==typeof(n=t.opacity)&&Number.isFinite(n)?Math.min(1,Math.max(0,n)):s))!==e.opacity||(t.isHidden??e.isHidden)!==e.isHidden||(t.isLocked??e.isLocked)!==e.isLocked||(t.parentId??e.parentId)!==e.parentId||(t.index??e.index)!==e.index;var n,s})(n,t)}).map(N);return 0===n.length?[]:(e.commands.updateShapes(n,{source:"user"}),n.map(e=>e.id))}(t,e),updateMeta:(e,n)=>{const s=t.shapes.get(e);return s?(t.commands.updateShapes([{id:e,meta:{...s.meta,...n}}],{source:"user"}),e):null},delete:e=>t.shapes.delete([...e],"user")},assets:{get:e=>{const n=t.assets.get(e);return n?(e=>({id:e.id,type:e.type,props:{...e.props},meta:{...e.meta}}))(n):null},resolveUrl:e=>t.assets.resolveUrl(e)},layers:{state:x,getTree:e=>i(_(t,e??t.pages.getCurrentId())),getNode:e=>(({editor:e,id:t})=>{const n=e.shapes.get(t),s=n?e.layers.getPageId(n.id):null;if(!n||!s)return null;const o=e.shapes.getForPage(s),r=H({bindings:o.flatMap(t=>e.bindings.getForShape(t.id)),editor:e,shapes:o}),i=r.rootIdByShapeId.get(n.id)??n.id,a=r.shapeById.get(i);if(!a)return null;const c=K(r,a.parentId);return $({childIds:K(r,a.id).map(e=>e.id),companionIds:r.companionIdsByRootId.get(a.id)??[],context:r,depth:j(r,a.id),editor:e,index:c.findIndex(e=>e.id===a.id),pageId:s,shape:a})})({editor:t,id:e}),getActionState:e=>({canGroup:t.layers.canGroup(e),canUngroup:t.layers.canUngroup(e),canMoveBackward:t.layers.canMove(e,"backward"),canMoveForward:t.layers.canMove(e,"forward")}),centerOn:(e,n)=>t.viewport.centerOnShape(e,{...n,source:"user"}),setHidden:(e,n)=>t.shapes.setHidden([...e],n,"user"),setLocked:(e,n)=>t.shapes.setLocked([...e],n,"user"),group:e=>t.layers.group([...e],"user")?.id??null,ungroup:e=>t.layers.ungroup([...e],"user"),move:(e,n)=>t.layers.move([...e],n,"user"),moveToEdge:(e,n)=>t.layers.moveToEdge([...e],n,"user"),moveToPlacement:(e,n)=>{const s=t.layers.moveToPlacement({ids:[...e],parentId:n.parentId,beforeId:n.beforeId??void 0},"user");return s.ok?{ok:!0,ids:s.movedIds}:{ok:!1,reason:"locked"===s.reason?"locked":"cycle"===s.reason?"cycle":"invalidBeforeId"===s.reason?"invalid-before":"unsupportedTransform"===s.reason?"mixed-parent":"notFound"===s.reason&&0===e.length?"empty-selection":"invalid-parent"}}},contextMenu:{state:u,dismiss:()=>p(null)},exports:{state:{getSnapshot:()=>n.getStatus(),subscribe:e=>n.subscribe(e)},getFormats:()=>n.getFormats(),getStatus:()=>n.getStatus(),export:(e,t)=>n.export(e,t)}},host:{setContextMenu:p}}}function _(e,t){const n=e.shapes.getForPage(t),s=new Map;for(const o of n)for(const t of e.bindings.getForShape(o.id))s.set(t.id,t);return[t,...n,...s.values()]}function Y(){const e=new Map;let t=!1;return{register({token:n,api:s,pluginId:o}){if(t)throw new Error("Canvas API registry is disposed.");if(e.has(n.id))throw new Error(`Duplicate canvas API token: ${n.id}.`);e.set(n.id,{token:n,api:s,pluginId:o})},view:t=>(({allowedTokenIds:t,ownerLabel:n})=>{const s=s=>{if(t&&!t.has(s.id))throw new Error(`${n} attempted to read undeclared canvas API "${s.id}".`);const o=e.get(s.id);return o?o.api:null};return{get:s,require(e){const t=s(e);if(null===t)throw new Error(`${n} requires unavailable canvas API "${e.id}".`);return t}}})(t),clear(){t||(t=!0,e.clear())}}}async function X(e,t={}){(e=>{if(!e||!Array.isArray(e.plugins))throw new Error("CanvasKit requires an explicit plugins array.");if(!("persistence"in e))throw new Error("CanvasKit requires an explicit persistence option.")})(e),t.signal?.throwIfAborted();const{canvasPlugins:n,editorPlugins:s,renderPlugins:o}=function(e){const t=(e=>e.flat(1/0))(e);L(t.map(({id:e})=>e),"canvas plugin id");const n=(e=>{const t=new Map(e.map(e=>[e.id,e])),n=[],s=new Set,o=new Set,r=e=>{if(!o.has(e.id)){if(s.has(e.id))throw new Error(`Circular canvas plugin dependency detected at "${e.id}".`);s.add(e.id);for(const n of e.requires??[]){const s=t.get(n.id);if(!s)throw new Error(`Canvas plugin "${e.id}" requires missing plugin "${n.id}".`);r(s)}s.delete(e.id),o.add(e.id),n.push(e)}};for(const i of e)r(i);return n})(t),s=n.flatMap(e=>e.editor?[e.editor]:[]),o=n.flatMap(e=>e.render?[e.render]:[]);return L(s.map(({id:e})=>e),"editor plugin id"),L(n.flatMap(e=>e.api?[e.api.id]:[]),"canvas API token"),{canvasPlugins:n,editorPlugins:s,renderPlugins:o}}(e.plugins),r=Dt(o),i=new Jt,a=t.signal?AbortSignal.any([i.signal,t.signal]):i.signal;try{const o=e.id??"canvas-kit",c=e.persistence;c&&i.own(c,e=>e.dispose?.());let l=[];const d=i.own((e=>{const t=kt({cameraAnimationScheduler:A(),documentMeta:e.documentMeta,onUnhandledError:e.onUnhandledError,plugins:e.editorPlugins,resolveAssetUrl:e.resolveAssetUrl});return t.tools.register("select",e=>new gt(e)),t.tools.register("hand",e=>new ft(e)),t.tools.syncLockedState(t.state.tool.get().isToolLocked),t.commands.setActiveTool("select",{source:"system"}),t.history.clear(),t})({documentMeta:e.documentMeta?{...e.documentMeta}:void 0,onUnhandledError:e.onError,editorPlugins:s,resolveAssetUrl(e){for(const t of l){const n=t.resolve(e);if(n)return n}return null}}),e=>e.dispose()),u=c?i.own(new Zt(d,c,{flushEvents:t.persistenceFlushEvents,onError:e.onError}),{shutdown:e=>e.shutdown(),rollback:e=>e.rollback()}):null,{apis:p,contributions:{assetResolvers:h,exports:f,imports:g}}=function({apis:e,canvasPlugins:t,editor:n,owner:s,productId:o}){const r=new Map(t.map(e=>[e.id,e])),i=[];for(const c of t){s.signal.throwIfAborted();const t=c.setup?.({editor:n,productId:o,apis:e.view({allowedTokenIds:T(c,r),ownerLabel:`Canvas plugin "${c.id}" setup`}),tasks:s.tasks});t&&(s.own(t,e=>e.dispose?.()),i.push({plugin:c,instance:t})),C(c,t),c.api&&t?.api&&e.register({token:c.api,api:t.api,pluginId:c.id})}const a=(e=>{const t=e.flatMap(({instance:e})=>e.imports??[]),n=e.flatMap(({instance:e})=>e.exports??[]),s=e.flatMap(({instance:e})=>e.assetResolvers??[]);return P(t.map(({id:e})=>e),"import contribution"),P(n.map(({id:e})=>e),"export contribution"),P(n.flatMap(e=>"provider"===e.kind?[e.format]:[]),"export format"),P(s.map(({id:e})=>e),"asset resolver contribution"),Object.freeze({imports:Object.freeze((o=t,o.map((e,t)=>({value:e,index:t})).sort((e,t)=>(e.value.order??0)-(t.value.order??0)||e.index-t.index).map(({value:e})=>e))),exports:Object.freeze([...n]),assetResolvers:Object.freeze([...s])});var o})(i);return{apis:e.view({ownerLabel:"CanvasKit"}),contributions:a}}({apis:i.own(Y(),e=>e.clear()),canvasPlugins:n,editor:d,owner:i,productId:o});l=h;const m=await(async({assetResolvers:e,editor:t,initialDocumentSnapshot:n,persistenceAdapter:s,persistenceCoordinator:o,signal:r})=>{const i=t.snapshots.getSession(),a=[],c=s?.load?await s.load({signal:r}):{documentSnapshot:null,sessionSnapshot:null};let l;r.throwIfAborted(),null!==c.documentSnapshot?(t.snapshots.loadDocument(c.documentSnapshot,{source:"system"}),l="restored"):void 0!==n?(t.snapshots.loadDocument(n,{source:"system"}),l="initial"):l="empty",r.throwIfAborted();let d=!1;if("restored"===l&&null!==c.sessionSnapshot)try{t.snapshots.loadSession(c.sessionSnapshot,{source:"system"}),d=!0}catch(u){r.throwIfAborted(),a.push(u),t.snapshots.loadSession(i,{source:"system"})}t.history.clear();for(const p of e){r.throwIfAborted();try{await(p.preload?.({editor:t,signal:r})),"restored"===l&&await(p.cleanupAfterRestore?.({editor:t,signal:r}))}catch(u){r.throwIfAborted(),a.push(u)}}return r.throwIfAborted(),o?.start(),{documentSource:l,sessionRestored:d,warnings:[...a]}})({assetResolvers:l,editor:d,initialDocumentSnapshot:e.initialDocumentSnapshot,persistenceAdapter:c,persistenceCoordinator:u,signal:a});!0===e.readonly&&d.document.setReadonly(!0),i.signal.throwIfAborted();const v=i.own(function({editor:e,contributions:t,tasks:n}){const s=t.filter(k),o=t.filter(R),r=new Map;for(const d of s){if(r.has(d.format))throw new Error(`Duplicate canvas export format: ${d.format}.`);r.set(d.format,d)}let i=Xt,a=!1;const c=new Set,l=e=>{if(!Object.is(i,e)){i=e;for(const e of[...c])e()}};return{getFormats:()=>s.map(({format:e,label:t,mimeType:n,fileExtension:s})=>({format:e,label:t,mimeType:n,fileExtension:s})),getStatus:()=>i,subscribe:e=>(c.add(e),()=>c.delete(e)),export:async(t,s)=>n.run(async n=>{if(a)throw new Error("Canvas export controller is disposed.");if("exporting"===i.state)throw new Error("An export is already in progress.");const c=r.get(t);if(!c)throw new Error(`Canvas export format is unavailable: ${t}.`);l({state:"exporting",format:t});try{const t=((e,t)=>{if("selection"===t.scope)return e.selection.getIds();if("page"===t.scope)return e.state.currentPageShapeIds.get();if(!t.shapeIds)throw new Error("Canvas export requires a scope or shapeIds.");return t.shapeIds})(e,s);for(const s of o)n.throwIfAborted(),await(s.prepare?.({editor:e,requestedShapeIds:t,signal:n}));n.throwIfAborted();const r=await c.export({editor:e,shapeIds:t,options:s.options},{signal:n,async inlineSvg(e){let t=e.svg;for(const s of o)n.throwIfAborted(),t=await s.inline({editor:e.editor,exportedShapes:e.exportedShapes,exportedShapeIds:e.exportedShapeIds,svg:t,signal:n});return n.throwIfAborted(),t}});return n.throwIfAborted(),{format:c.format,label:c.label,mimeType:c.mimeType,fileExtension:c.fileExtension,...r}}finally{l(Xt)}}),dispose(){a||(a=!0,l(Xt),c.clear())}}}({editor:d,contributions:f,tasks:i.tasks}),e=>e.dispose());i.signal.throwIfAborted();const{canvas:w,host:y}=U({apis:p,editor:d,exports:v,productId:o,startup:m});return{canvas:w,dispose:i.publish({beforeShutdown:()=>d.closeWrites()}),productId:o,render:{editor:d,importContributions:g,onError:e.onError,renderBindings:r,setContextMenu:y.setContextMenu}}}catch(c){return i.rollback(c)}}function J(e){try{const t=globalThis.reportError;if("function"==typeof t)return void t(e)}catch(t){console.error(t)}console.error(e)}function G({actions:e=en,chromeRenderer:t,onCanvasChange:n,options:s}){const o=(e=>{const[t,n]=Kt(null);return Nt(()=>{let t=!0,s=null;const o=new AbortController,r=e.onError??J;return n({options:e,state:Qt}),X(e,{persistenceFlushEvents:{subscribe(e){const t=()=>{"hidden"===document.visibilityState&&e()},n=()=>e();return document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",n),window.addEventListener("beforeunload",n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",n),window.removeEventListener("beforeunload",n)}}},signal:o.signal}).then(o=>{s=o,t?n({options:e,state:{status:"ready",runtime:o}}):o.dispose().catch(r)},s=>{t&&n({options:e,state:{status:"error",error:s}})}),()=>{t=!1,o.abort(new DOMException("CanvasKitRoot was cleaned up.","AbortError")),s?.dispose().catch(r)}},[e]),t?.options===e?t.state:Qt})(s);if("error"===o.status)throw o.error;return"ready"!==o.status?null:Vt(Z,{actions:e,chromeRenderer:t,onCanvasChange:n,runtime:o.runtime})}function Z({actions:e=en,chromeRenderer:t,onCanvasChange:n,runtime:s}){const o=Ht(n),a=Ht(null),c=Ft(()=>a.current,[]),{canvas:l,productId:u,render:p}=s,h=p.onError??J,f=Ft(()=>l.tools.state.getSnapshot().isEditing,[l]);return o.current=n,Nt(()=>(o.current?.(l),()=>o.current?.(null)),[l]),function({actions:e,canvas:t,isEditing:n,onError:s}){Nt(()=>{(e=>{const t=new Set;for(const n of e){if(t.has(n.id))throw new Error(`Duplicate CanvasAction id "${n.id}".`);t.add(n.id)}})(e);const o=o=>{if(n()||Tt(o.target))return;const r={key:o.key,shiftKey:o.shiftKey,altKey:o.altKey,ctrlKey:o.ctrlKey,metaKey:o.metaKey,accelKey:o.metaKey||o.ctrlKey},i=e.find(e=>void 0!==e.shortcut&&E(e.shortcut).some(e=>xt(e,r)));if(!i)return;if(o.preventDefault(),o.stopPropagation(),!i.isEnabled(t))return;let a;try{a=i.run(t)}catch(c){return void s(new Error(`Canvas action "${i.id}" failed.`,{cause:c}))}a instanceof Promise&&a.catch(e=>{s(new Error(`Canvas action "${i.id}" failed.`,{cause:e}))})};return window.addEventListener("keydown",o,!0),()=>window.removeEventListener("keydown",o,!0)},[e,t,n,s])}({actions:e,canvas:l,isEditing:f,onError:h}),Vt(d,{canvas:l,children:Vt(r,{children:Vt("div",{ref:a,"data-ui":"app-shell","data-canvas-kit":u,className:"land-canvas-kit__shell",children:Wt("main",{"data-ui":"workspace-viewport",className:"land-canvas-kit__viewport",children:[
5
5
  Vt(S,{bindings:p,getHostElement:c,onError:h}),t?.(l)??null,
6
- Vt(i,{})]})})})})}function Q(){return"undefined"==typeof indexedDB?Promise.resolve(null):(nn||(nn=new Promise((e,t)=>{const n=indexedDB.open("canvas-kit.persistence",2);n.addEventListener("upgradeneeded",()=>{var e;(e=n.result).objectStoreNames.contains("snapshots")||e.createObjectStore(tn)}),n.addEventListener("success",()=>{const t=n.result;t.addEventListener("versionchange",()=>{t.close(),nn=null}),e(t)}),n.addEventListener("error",()=>{nn=null,t(n.error)})})),nn)}function ee(e={}){return{async load({signal:t}){t.throwIfAborted();const n=await ne(e);return t.throwIfAborted(),n},saveDocument:t=>te({documentSnapshot:JSON.stringify(t),sessionSnapshot:null},e),saveSession:t=>te({documentSnapshot:null,sessionSnapshot:JSON.stringify(t)},e)}}async function te(e,t){const n=[];null!==e.documentSnapshot&&n.push([re(t),e.documentSnapshot]),null!==e.sessionSnapshot&&n.push([ie(t),e.sessionSnapshot]),0!==n.length&&await(async(e,t)=>{if(0===t.length)return;const n=await Q();n&&await new Promise((s,o)=>{const r=n.transaction(e,"readwrite"),i=r.objectStore(e);r.addEventListener("complete",()=>s()),r.addEventListener("abort",()=>o(r.error)),r.addEventListener("error",()=>o(r.error));for(const[e,n]of t)i.put(n,e)})})(tn,n)}async function ne(e={}){const[t,n]=await ce([re(e),ie(e)]);return{documentSnapshot:t,sessionSnapshot:n}}async function se(){return ae(sn)}async function oe(){return ae(on)}function re(e){return e.storageNamespace?`${e.storageNamespace}.document`:sn}function ie(e){return e.storageNamespace?`${e.storageNamespace}.session`:on}async function ae(e){const[t]=await ce([e]);return t??null}async function ce(e){return(await(async(e,t)=>{if(0===t.length)return[];const n=await Q();return n?new Promise((s,o)=>{const r=n.transaction(e,"readonly"),i=r.objectStore(e),a=new Array(t.length).fill(null);r.addEventListener("complete",()=>s(a)),r.addEventListener("abort",()=>o(r.error)),r.addEventListener("error",()=>o(r.error)),t.forEach((e,t)=>{const n=i.get(e);n.addEventListener("success",()=>{a[t]=n.result??null}),n.addEventListener("error",()=>o(n.error))})}):null})("snapshots",e)??e.map(()=>null)).map(le)}function le(e){if(null==e)return null;if("string"!=typeof e)throw new Error("Persisted canvas snapshot is not a JSON string.");try{return JSON.parse(e)}catch(t){throw new Error("Persisted canvas snapshot contains invalid JSON.",{cause:t})}}function de({children:e,className:t,dataUi:n="canvas-kit-floating-toolbar-layer"}){const s=a();return s?qt(Vt("div",{"data-ui":n,className:ue("land-canvas__floating-toolbar-layer",t),children:e}),s):null}function ue(...e){return e.filter(Boolean).join(" ")}function pe(e,t){return"function"==typeof e?e(t):e}function he(e){return e.split("-")[0]}function fe(e){return e.split("-")[1]}function ge(e){return"y"===e?"height":"width"}function me(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function ve(e){return"x"===me(e)?"y":"x"}function we(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}function ye(e){const t=he(e);return un[t]+e.slice(t.length)}function be(e){const{x:t,y:n,width:s,height:o}=e;return{width:s,height:o,top:n,left:t,right:t+s,bottom:n+o,x:t,y:n}}function xe(e,t,n){let{reference:s,floating:o}=e;const r=me(t),i=ve(t),a=ge(i),c=he(t),l="y"===r,d=s.x+s.width/2-o.width/2,u=s.y+s.height/2-o.height/2,p=s[a]/2-o[a]/2;let h;switch(c){case"top":h={x:d,y:s.y-o.height};break;case"bottom":h={x:d,y:s.y+s.height};break;case"right":h={x:s.x+s.width,y:u};break;case"left":h={x:s.x-o.width,y:u};break;default:h={x:s.x,y:s.y}}switch(fe(t)){case"start":h[i]-=p*(n&&l?-1:1);break;case"end":h[i]+=p*(n&&l?-1:1)}return h}async function Se(e,t){var n;void 0===t&&(t={});const{x:s,y:o,platform:r,rects:i,elements:a,strategy:c}=e,{boundary:l="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:p=!1,padding:h=0}=pe(t,e),f=(e=>"number"!=typeof e?(e=>({top:0,right:0,bottom:0,left:0,...e}))(e):{top:e,right:e,bottom:e,left:e})(h),g=a[p?"floating"===u?"reference":"floating":u],m=be(await r.getClippingRect({element:null==(n=await(null==r.isElement?void 0:r.isElement(g)))||n?g:g.contextElement||await(null==r.getDocumentElement?void 0:r.getDocumentElement(a.floating)),boundary:l,rootBoundary:d,strategy:c})),v="floating"===u?{x:s,y:o,width:i.floating.width,height:i.floating.height}:i.reference,w=await(null==r.getOffsetParent?void 0:r.getOffsetParent(a.floating)),y=await(null==r.isElement?void 0:r.isElement(w))&&await(null==r.getScale?void 0:r.getScale(w))||{x:1,y:1},b=be(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:v,offsetParent:w,strategy:c}):v);return{top:(m.top-b.top+f.top)/y.y,bottom:(b.bottom-m.bottom+f.bottom)/y.y,left:(m.left-b.left+f.left)/y.x,right:(b.right-m.right+f.right)/y.x}}function Ee(){return"undefined"!=typeof window}function Ie(e){return Pe(e)?(e.nodeName||"").toLowerCase():"#document"}function Ce(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Te(e){var t;return null==(t=(Pe(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function Pe(e){return!!Ee()&&(e instanceof Node||e instanceof Ce(e).Node)}function ke(e){return!!Ee()&&(e instanceof Element||e instanceof Ce(e).Element)}function Re(e){return!!Ee()&&(e instanceof HTMLElement||e instanceof Ce(e).HTMLElement)}function Le(e){return!(!Ee()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Ce(e).ShadowRoot)}function Ae(e){const{overflow:t,overflowX:n,overflowY:s,display:o}=Ne(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+n)&&"inline"!==o&&"contents"!==o}function De(e){return/^(table|td|th)$/.test(Ie(e))}function Me(e){try{if(e.matches(":popover-open"))return!0}catch(t){}try{return e.matches(":modal")}catch(t){return!1}}function Oe(e){const t=ke(e)?Ne(e):e;return yn(t.transform)||yn(t.translate)||yn(t.scale)||yn(t.rotate)||yn(t.perspective)||!Fe()&&(yn(t.backdropFilter)||yn(t.filter))||vn.test(t.willChange||"")||wn.test(t.contain||"")}function Fe(){return null==Ut&&(Ut="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Ut}function Be(e){return/^(html|body|#document)$/.test(Ie(e))}function Ne(e){return Ce(e).getComputedStyle(e)}function $e(e){return ke(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function He(e){if("html"===Ie(e))return e;const t=e.assignedSlot||e.parentNode||Le(e)&&e.host||Te(e);return Le(t)?t.host:t}function Ke(e){const t=He(e);return Be(t)?e.ownerDocument?e.ownerDocument.body:e.body:Re(t)&&Ae(t)?t:Ke(t)}function je(e,t,n){var s;void 0===t&&(t=[]),void 0===n&&(n=!0);const o=Ke(e),r=o===(null==(s=e.ownerDocument)?void 0:s.body),i=Ce(o);if(r){const e=ze(i);return t.concat(i,i.visualViewport||[],Ae(o)?o:[],e&&n?je(e):[])}return t.concat(o,je(o,[],n))}function ze(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Ve(e){const t=Ne(e);let n=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const o=Re(e),r=o?e.offsetWidth:n,i=o?e.offsetHeight:s,a=cn(n)!==r||cn(s)!==i;return a&&(n=r,s=i),{width:n,height:s,$:a}}function We(e){return ke(e)?e:e.contextElement}function qe(e){const t=We(e);if(!Re(t))return dn(1);const n=t.getBoundingClientRect(),{width:s,height:o,$:r}=Ve(t);let i=(r?cn(n.width):n.width)/s,a=(r?cn(n.height):n.height)/o;return i&&Number.isFinite(i)||(i=1),a&&Number.isFinite(a)||(a=1),{x:i,y:a}}function Ue(e){const t=Ce(e);return Fe()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:bn}function _e(e,t,n,s){void 0===t&&(t=!1),void 0===n&&(n=!1);const o=e.getBoundingClientRect(),r=We(e);let i=dn(1);t&&(s?ke(s)&&(i=qe(s)):i=qe(e));const a=((e,t,n)=>(void 0===t&&(t=!1),!(!n||t&&n!==Ce(e))&&t))(r,n,s)?Ue(r):dn(0);let c=(o.left+a.x)/i.x,l=(o.top+a.y)/i.y,d=o.width/i.x,u=o.height/i.y;if(r){const e=Ce(r),t=s&&ke(s)?Ce(s):s;let n=e,o=ze(n);for(;o&&s&&t!==n;){const e=qe(o),t=o.getBoundingClientRect(),s=Ne(o),r=t.left+(o.clientLeft+parseFloat(s.paddingLeft))*e.x,i=t.top+(o.clientTop+parseFloat(s.paddingTop))*e.y;c*=e.x,l*=e.y,d*=e.x,u*=e.y,c+=r,l+=i,n=Ce(o),o=ze(n)}}return be({width:d,height:u,x:c,y:l})}function Ye(e,t){const n=$e(e).scrollLeft;return t?t.left+n:_e(Te(e)).left+n}function Xe(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-Ye(e,n),y:n.top+t.scrollTop}}function Je(e,t,n){let s;if("viewport"===t)s=((e,t)=>{const n=Ce(e),s=Te(e),o=n.visualViewport;let r=s.clientWidth,i=s.clientHeight,a=0,c=0;if(o){r=o.width,i=o.height;const e=Fe();(!e||e&&"fixed"===t)&&(a=o.offsetLeft,c=o.offsetTop)}const l=Ye(s);if(l<=0){const e=s.ownerDocument,t=e.body,n=getComputedStyle(t),o="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(s.clientWidth-t.clientWidth-o);i<=25&&(r-=i)}else l<=25&&(r+=l);return{width:r,height:i,x:a,y:c}})(e,n);else if("document"===t)s=(e=>{const t=Te(e),n=$e(e),s=e.ownerDocument.body,o=an(t.scrollWidth,t.clientWidth,s.scrollWidth,s.clientWidth),r=an(t.scrollHeight,t.clientHeight,s.scrollHeight,s.clientHeight);let i=-n.scrollLeft+Ye(e);const a=-n.scrollTop;return"rtl"===Ne(s).direction&&(i+=an(t.clientWidth,s.clientWidth)-o),{width:o,height:r,x:i,y:a}})(Te(e));else if(ke(t))s=((e,t)=>{const n=_e(e,!0,"fixed"===t),s=n.top+e.clientTop,o=n.left+e.clientLeft,r=Re(e)?qe(e):dn(1);return{width:e.clientWidth*r.x,height:e.clientHeight*r.y,x:o*r.x,y:s*r.y}})(t,n);else{const n=Ue(e);s={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return be(s)}function Ge(e,t){const n=He(e);return!(n===t||!ke(n)||Be(n))&&("fixed"===Ne(n).position||Ge(n,t))}function Ze(e,t){const n=t.get(e);if(n)return n;let s=je(e,[],!1).filter(e=>ke(e)&&"body"!==Ie(e)),o=null;const r="fixed"===Ne(e).position;let i=r?He(e):e;for(;ke(i)&&!Be(i);){const t=Ne(i),n=Oe(i);n||"fixed"!==t.position||(o=null),(r?!n&&!o:!n&&"static"===t.position&&o&&("absolute"===o.position||"fixed"===o.position)||Ae(i)&&!n&&Ge(e,i))?s=s.filter(e=>e!==i):o=t,i=He(i)}return t.set(e,s),s}function Qe(e,t,n){function s(){l.x=Ye(r)}const o=Re(t),r=Te(t),i="fixed"===n,a=_e(e,!0,i,t);let c={scrollLeft:0,scrollTop:0};const l=dn(0);if(o||!o&&!i)if(("body"!==Ie(t)||Ae(r))&&(c=$e(t)),o){const e=_e(t,!0,i,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}else r&&s();i&&!o&&r&&s();const d=!r||o||i?dn(0):Xe(r,c);return{x:a.left+c.scrollLeft-l.x-d.x,y:a.top+c.scrollTop-l.y-d.y,width:a.width,height:a.height}}function et(e){return"static"===Ne(e).position}function tt(e,t){if(!Re(e)||"fixed"===Ne(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Te(e)===n&&(n=n.ownerDocument.body),n}function nt(e,t){const n=Ce(e);if(Me(e))return n;if(!Re(e)){let t=He(e);for(;t&&!Be(t);){if(ke(t)&&!et(t))return t;t=He(t)}return n}let s=tt(e,t);for(;s&&De(s)&&et(s);)s=tt(s,t);return s&&Be(s)&&et(s)&&!Oe(s)?n:s||(e=>{let t=He(e);for(;Re(t)&&!Be(t);){if(Oe(t))return t;if(Me(t))return null;t=He(t)}return null})(e)||n}function st(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function ot({viewport:e,fallbackPlacements:t,floatingRef:n,getReferenceElement:s,onPlacementChange:o,offset:r,placement:i,visible:a=!0}){Nt(()=>{const c=s(),l=n.current;if(!c||!l)return;let d=!1,u=0;l.style.visibility="hidden";const p=()=>{const e=++u,n=it("--toolbar-floating-collision-padding",8);((e,t,n)=>{const s={platform:xn,...n},o={...s.platform,_c:new Map};return(async(e,t,n)=>{const{placement:s="bottom",strategy:o="absolute",middleware:r=[],platform:i}=n,a=i.detectOverflow?i:{...i,detectOverflow:Se},c=await(null==i.isRTL?void 0:i.isRTL(t));let l=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:u}=xe(l,s,c),p=s,h=0;const f={};for(let g=0;g<r.length;g++){const n=r[g];if(!n)continue;const{name:m,fn:v}=n,{x:w,y:y,data:b,reset:x}=await v({x:d,y:u,initialPlacement:s,placement:p,strategy:o,middlewareData:f,rects:l,platform:a,elements:{reference:e,floating:t}});d=null!=w?w:d,u=null!=y?y:u,f[m]={...f[m],...b},x&&h<50&&(h++,"object"==typeof x&&(x.placement&&(p=x.placement),x.rects&&(l=!0===x.rects?await i.getElementRects({reference:e,floating:t,strategy:o}):x.rects),({x:d,y:u}=xe(l,p,c))),g=-1)}return{x:d,y:u,placement:p,strategy:o,middlewareData:f}})(e,t,{...s,platform:o})})(c,l,{strategy:"fixed",placement:i,middleware:rt({fallbackPlacements:t,offset:r??it("--toolbar-floating-offset",38),padding:{top:it("--toolbar-floating-safe-top",64),right:n,bottom:n,left:n}})}).then(({placement:t,x:n,y:s})=>{d||e!==u||(l.dataset.placement=t,o?.(t),l.style.transform=`translate3d(${Math.round(n)}px, ${Math.round(s)}px, 0)`,l.style.visibility=a?"visible":"hidden")})},h=function(e,t,n,s){void 0===s&&(s={});const{ancestorScroll:o=!0,ancestorResize:r=!0,elementResize:i="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:c=!1}=s,l=We(e),d=o||r?[...l?je(l):[],...t?je(t):[]]:[];d.forEach(e=>{o&&e.addEventListener("scroll",n,{passive:!0}),r&&e.addEventListener("resize",n)});const u=l&&a?((e,t)=>{function n(){var e;clearTimeout(s),null==(e=o)||e.disconnect(),o=null}let s,o=null;const r=Te(e);return function i(a,c){function l(t){const n=t[0].intersectionRatio;if(n!==c){if(!m)return i();n?i(!1,n):s=setTimeout(()=>{i(!1,1e-7)},1e3)}1!==n||st(d,e.getBoundingClientRect())||i(),m=!1}void 0===a&&(a=!1),void 0===c&&(c=1),n();const d=e.getBoundingClientRect(),{left:u,top:p,width:h,height:f}=d;if(a||t(),!h||!f)return;const g={rootMargin:-ln(p)+"px "+-ln(r.clientWidth-(u+h))+"px "+-ln(r.clientHeight-(p+f))+"px "+-ln(u)+"px",threshold:an(0,rn(1,c))||1};let m=!0;try{o=new IntersectionObserver(l,{...g,root:r.ownerDocument})}catch(v){o=new IntersectionObserver(l,g)}o.observe(e)}(!0),n})(l,n):null;let p,h=-1,f=null;i&&(f=new ResizeObserver(e=>{let[s]=e;s&&s.target===l&&f&&t&&(f.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),n()}),l&&!c&&f.observe(l),t&&f.observe(t));let g=c?_e(e):null;return c&&function t(){const s=_e(e);g&&!st(g,s)&&n(),g=s,p=requestAnimationFrame(t)}(),n(),()=>{var e;d.forEach(e=>{o&&e.removeEventListener("scroll",n),r&&e.removeEventListener("resize",n)}),u?.(),null==(e=f)||e.disconnect(),f=null,c&&cancelAnimationFrame(p)}}(c,l,p,{ancestorResize:!0,ancestorScroll:!0,elementResize:!0,layoutShift:!0}),f=e.subscribe(p);return p(),()=>{d=!0,l.style.visibility="hidden",h(),f()}},[e,t,n,s,o,r,i,a])}function rt({fallbackPlacements:e,offset:t,padding:n}){return[Sn(t),En({fallbackPlacements:[...e],padding:n})]}function it(e,t){if("undefined"==typeof document)return t;const n=getComputedStyle(document.documentElement).getPropertyValue(e).trim();if(!n)return t;const s=Number.parseFloat(n);return Number.isFinite(s)?n.endsWith("rem")?16*s:s:t}function at(e){const t=a();return t?qt(Vt(ct,{...e}),t):null}function ct({fallbackPlacements:e=In,offset:t=8,placement:n="top",referenceElement:o,...r}){const i=u(),a=Ht(null),c=Ft(()=>o,[o]);return s(a),ot({viewport:i.viewport.state,fallbackPlacements:e,floatingRef:a,getReferenceElement:c,offset:t,placement:n}),Vt("div",{...r,ref:a})}function lt(){return Bt(Pn)}function dt({children:e,className:t,dataUi:n="floating-selection-toolbar-slot",horizontalAlign:o="start",offset:r,visible:i=!0}){const a=u(),c=p(a.selection.state),l=p(a.viewport.state),d=Ht(null),h=Ht(null),[f,g]=Kt("center"===o?"top":"top-start"),m=c.pageBounds??(c.anchorPagePoint?{x:c.anchorPagePoint.x,y:c.anchorPagePoint.y,width:0,height:0}:null),v=i&&null!==m,w=v&&!c.isTranslating,y=Ft(()=>d.current,[m?.height,m?.width,m?.x,m?.y]),b=Ft(()=>d.current?.getBoundingClientRect()??null,[]),x=$t(()=>({placement:f,getContentBounds:b}),[m?.height,m?.width,m?.x,m?.y,b,f,l.pageTransform]);return s(h),ot({viewport:a.viewport.state,fallbackPlacements:"center"===o?Tn:Cn,floatingRef:h,getReferenceElement:y,onPlacementChange:g,offset:r,placement:"center"===o?"top":"top-start",visible:w}),v&&m?Wt(zt,{children:[Vt("div",{"data-ui":`${n}-page-space`,className:"land-canvas__floating-selection-page-space",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",transform:l.pageTransform,transformOrigin:"0 0"},children:Vt("div",{ref:d,"aria-hidden":"true",style:{position:"absolute",left:m.x,top:m.y,width:m.width,height:m.height,pointerEvents:"none"}})}),Vt("div",{ref:h,"data-ui":n,className:ut("land-canvas__floating-selection-anchor",t),style:{position:"fixed",left:0,top:0,visibility:"hidden",willChange:"transform"},children:Vt(Pn.Provider,{value:x,children:e})})]}):null}function ut(...e){return e.filter(Boolean).join(" ")}import{A as pt,C as ht,D as ft,E as gt,F as mt,I as vt,L as wt,M as yt,N as bt,O as xt,P as St,R as Et,T as It,a as Ct,f as Tt,j as Pt,k as kt,o as Rt,r as Lt,u as At,x as Dt,z as Mt}from"./host-CW9xZzD2.mjs";import{createContext as Ot,useCallback as Ft,useContext as Bt,useEffect as Nt,useMemo as $t,useRef as Ht,useState as Kt,useSyncExternalStore as jt}from"react";import{Fragment as zt,jsx as Vt,jsxs as Wt}from"react/jsx-runtime";import{createPortal as qt}from"react-dom";var Ut,_t=Ot(null),Yt=Ot(null),Xt={state:"idle"},Jt=class{abortController=new AbortController;activeTasks=new Set;disposers=[];phase="starting";close=null;signal=this.abortController.signal;tasks={run:e=>this.runTask(e)};own(e,t){if("starting"!==this.phase)throw new Error("Cannot register a resource after the Canvas Runtime is published or disposal starts.");return this.disposers.push(n=>"function"==typeof t?t(e):"rollback"===n&&t.rollback?t.rollback(e):t.shutdown(e)),e}publish({beforeShutdown:e}={}){if("starting"!==this.phase)throw new Error(`Only a starting Canvas Runtime can be published; received runtime in "${this.phase}" phase.`);return this.phase="ready",()=>null!==this.close?"shutdown"===this.close.mode?this.close.result:Promise.reject(new Error("Cannot shut down a Canvas Runtime during rollback.")):this.beginClose({mode:"shutdown",beforeShutdown:e})}rollback(e){return null!==this.close?"rollback"===this.close.mode?this.close.result:Promise.reject(new Error("Cannot roll back a Canvas Runtime during shutdown.")):"starting"!==this.phase?Promise.reject(new Error(`Only a starting Canvas Runtime can roll back; received runtime in "${this.phase}" phase.`)):this.beginClose({mode:"rollback",cause:e})}beginClose(e){const t=[],n=Promise.resolve().then(async()=>{const n=[...t,...await this.disposeResources(e.mode)];if(this.phase="disposed","rollback"===e.mode){if(n.length>0)throw new AggregateError([e.cause,...n],"CanvasKit Runtime initialization failed and cleanup reported errors.",{cause:e.cause});throw e.cause}if(n.length>0)throw new AggregateError(n,"Failed to dispose one or more CanvasKit Runtime resources.")});if(this.close={mode:e.mode,result:n},"shutdown"===e.mode)try{e.beforeShutdown?.()}catch(s){t.push(s)}return this.phase="disposing",this.abortController.abort("rollback"===e.mode?e.cause:new DOMException("Canvas runtime is disposing.","AbortError")),n}runTask(e){if("ready"!==this.phase)throw new Error(`Canvas tasks require a ready runtime; received runtime in "${this.phase}" phase.`);this.signal.throwIfAborted();const t=Promise.resolve().then(()=>e(this.signal));return this.activeTasks.add(t),t.finally(()=>this.activeTasks.delete(t)).catch(()=>{}),t}async disposeResources(e){await Promise.allSettled([...this.activeTasks]);const t=[];for(;this.disposers.length>0;){const s=this.disposers.pop();try{await s(e)}catch(n){t.push(n)}}return t}},Gt=[500,1e3,2e3,5e3],Zt=class{editor;adapter;options;unsubscribeDocument=null;unsubscribeSession=null;unsubscribeFlushEvents=null;documentTimer=null;sessionTimer=null;pendingDocument=null;pendingSession=null;documentVersion=0;sessionVersion=0;documentRetryCount=0;sessionRetryCount=0;writeChain=Promise.resolve();flushChain=Promise.resolve();isRunning=!1;disposeMode=null;disposePromise=null;constructor(e,t,n={}){this.editor=e,this.adapter=t,this.options=n}start(){if(null!==this.disposeMode)throw new Error("Cannot start disposed canvas persistence.");this.isRunning||(this.isRunning=!0,this.adapter.saveDocument&&(this.unsubscribeDocument=this.editor.operations.subscribe(e=>{var t;this.documentVersion+=1,this.documentRetryCount=0,this.pendingDocument={snapshot:(t=e.snapshot,JSON.parse(JSON.stringify(t))),version:this.documentVersion},this.scheduleDocumentSave(200)})),this.adapter.saveSession&&(this.unsubscribeSession=this.editor.listen(e=>{var t,n;((t=e.diff).added.some(e=>"session"===e.scope)||t.updated.some(e=>"session"===e.before.scope||"session"===e.after.scope)||t.removed.some(e=>"session"===e.scope))&&(this.sessionVersion+=1,this.sessionRetryCount=0,this.pendingSession={snapshot:(n=this.editor.snapshots.getSession(),JSON.parse(JSON.stringify(n))),version:this.sessionVersion},this.scheduleSessionSave(200))})),this.unsubscribeFlushEvents=this.options.flushEvents?.subscribe(this.flushForHostLifecycle)??null)}flush(){if(null!==this.disposeMode)return Promise.reject(new Error("Cannot flush disposed canvas persistence."));const e=this.flushChain.then(()=>this.flushNow());return this.flushChain=e.catch(()=>{}),e}shutdown(){return this.dispose("shutdown")}rollback(){return this.dispose("rollback")}dispose(e){return null!==this.disposeMode?this.disposeMode!==e?Promise.reject(new Error(`Canvas persistence disposal already started in "${this.disposeMode}" mode.`)):this.disposePromise:(this.disposeMode=e,this.disposePromise=Promise.resolve().then(()=>"shutdown"===e?this.finishShutdown():this.finishRollback()),this.disposePromise)}async finishShutdown(){this.stopIntake(),await this.flushChain,await this.flushNow()}async finishRollback(){this.stopIntake(),this.discardPendingSnapshots(),await this.flushChain,await this.writeChain,this.discardPendingSnapshots()}stopIntake(){this.isRunning=!1,this.cancelDocumentTimer(),this.cancelSessionTimer(),this.unsubscribeDocument?.(),this.unsubscribeSession?.(),this.unsubscribeFlushEvents?.(),this.unsubscribeDocument=null,this.unsubscribeSession=null,this.unsubscribeFlushEvents=null}async flushNow(){const e=await this.flushPendingSnapshots();try{await(this.adapter.flush?.())}catch(t){e.push(t)}if(e.length>0)throw new AggregateError(e,"Failed to flush canvas persistence.")}async flushPendingSnapshots(){this.cancelDocumentTimer(),this.cancelSessionTimer();const e=this.savePendingDocument(),t=this.savePendingSession();return(await Promise.allSettled([e,t])).flatMap(e=>"rejected"===e.status?[e.reason]:[])}discardPendingSnapshots(){this.cancelDocumentTimer(),this.cancelSessionTimer(),this.pendingDocument=null,this.pendingSession=null}savePendingDocument(){const e=this.pendingDocument;if(!e||!this.adapter.saveDocument)return this.writeChain;this.pendingDocument=null;const t=this.queueWrite(()=>Promise.resolve(this.adapter.saveDocument(e.snapshot))).then(()=>{this.documentVersion===e.version&&(this.documentRetryCount=0)}).catch(t=>{throw this.documentVersion===e.version&&null===this.pendingDocument&&(this.pendingDocument=e,this.scheduleDocumentRetry()),t});return this.writeChain=t.catch(()=>{}),t}savePendingSession(){const e=this.pendingSession;if(!e||!this.adapter.saveSession)return this.writeChain;this.pendingSession=null;const t=this.queueWrite(()=>Promise.resolve(this.adapter.saveSession(e.snapshot))).then(()=>{this.sessionVersion===e.version&&(this.sessionRetryCount=0)}).catch(t=>{throw this.sessionVersion===e.version&&null===this.pendingSession&&(this.pendingSession=e,this.scheduleSessionRetry()),t});return this.writeChain=t.catch(()=>{}),t}queueWrite(e){return this.writeChain.then(e)}scheduleDocumentSave(e){this.cancelDocumentTimer(),this.documentTimer=setTimeout(()=>{this.documentTimer=null,this.savePendingDocument().catch(e=>{this.reportError("Could not persist canvas document.",e)})},e)}scheduleSessionSave(e){this.cancelSessionTimer(),this.sessionTimer=setTimeout(()=>{this.sessionTimer=null,this.savePendingSession().catch(e=>{this.reportError("Could not persist canvas session.",e)})},e)}scheduleDocumentRetry(){if(!this.isRunning||null!==this.documentTimer)return;const e=Gt[this.documentRetryCount];void 0!==e&&(this.documentRetryCount+=1,this.scheduleDocumentSave(e))}scheduleSessionRetry(){if(!this.isRunning||null!==this.sessionTimer)return;const e=Gt[this.sessionRetryCount];void 0!==e&&(this.sessionRetryCount+=1,this.scheduleSessionSave(e))}cancelDocumentTimer(){null!==this.documentTimer&&(clearTimeout(this.documentTimer),this.documentTimer=null)}cancelSessionTimer(){null!==this.sessionTimer&&(clearTimeout(this.sessionTimer),this.sessionTimer=null)}flushForHostLifecycle=()=>{this.flush().catch(e=>{this.reportError("Could not persist canvas snapshot.",e)})};reportError(e,t){try{this.options.onError?.(new Error(e,{cause:t}))}catch{}}},Qt={status:"starting"},en=[],tn="snapshots",nn=null,sn="canvas-kit.document",on="canvas-kit.session",rn=Math.min,an=Math.max,cn=Math.round,ln=Math.floor,dn=e=>({x:e,y:e}),un={left:"right",right:"left",bottom:"top",top:"bottom"},pn=["left","right"],hn=["right","left"],fn=["top","bottom"],gn=["bottom","top"],mn=new Set(["left","top"]),vn=/transform|translate|scale|rotate|perspective|filter/,wn=/paint|layout|strict|content/,yn=e=>!!e&&"none"!==e,bn=dn(0),xn={convertOffsetParentRelativeRectToViewportRelativeRect:e=>{let{elements:t,rect:n,offsetParent:s,strategy:o}=e;const r="fixed"===o,i=Te(s),a=!!t&&Me(t.floating);if(s===i||a&&r)return n;let c={scrollLeft:0,scrollTop:0},l=dn(1);const d=dn(0),u=Re(s);if((u||!u&&!r)&&(("body"!==Ie(s)||Ae(i))&&(c=$e(s)),u)){const e=_e(s);l=qe(s),d.x=e.x+s.clientLeft,d.y=e.y+s.clientTop}const p=!i||u||r?dn(0):Xe(i,c);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+d.x+p.x,y:n.y*l.y-c.scrollTop*l.y+d.y+p.y}},getDocumentElement:Te,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:s,strategy:o}=e;const r=[..."clippingAncestors"===n?Me(t)?[]:Ze(t,this._c):[].concat(n),s],i=Je(t,r[0],o);let a=i.top,c=i.right,l=i.bottom,d=i.left;for(let u=1;u<r.length;u++){const e=Je(t,r[u],o);a=an(e.top,a),c=rn(e.right,c),l=rn(e.bottom,l),d=an(e.left,d)}return{width:c-d,height:l-a,x:d,y:a}},getOffsetParent:nt,getElementRects:async function(e){const t=this.getOffsetParent||nt,n=this.getDimensions,s=await n(e.floating);return{reference:Qe(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}},getClientRects:e=>Array.from(e.getClientRects()),getDimensions:e=>{const{width:t,height:n}=Ve(e);return{width:t,height:n}},getScale:qe,isElement:ke,isRTL:e=>"rtl"===Ne(e).direction},Sn=e=>(void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var n,s;const{x:o,y:r,placement:i,middlewareData:a}=t,c=await(async(e,t)=>{const{placement:n,platform:s,elements:o}=e,r=await(null==s.isRTL?void 0:s.isRTL(o.floating)),i=he(n),a=fe(n),c="y"===me(n),l=mn.has(i)?-1:1,d=r&&c?-1:1,u=pe(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:f}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&"number"==typeof f&&(h="end"===a?-1*f:f),c?{x:h*d,y:p*l}:{x:p*l,y:h*d}})(t,e);return i===(null==(n=a.offset)?void 0:n.placement)&&null!=(s=a.arrow)&&s.alignmentOffset?{}:{x:o+c.x,y:r+c.y,data:{...c,placement:i}}}}),En=e=>(void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,s;const{placement:o,middlewareData:r,rects:i,initialPlacement:a,platform:c,elements:l}=t,{mainAxis:d=!0,crossAxis:u=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:g=!0,...m}=pe(e,t);if(null!=(n=r.arrow)&&n.alignmentOffset)return{};const v=he(o),w=me(a),y=he(a)===a,b=await(null==c.isRTL?void 0:c.isRTL(l.floating)),x=p||(y||!g?[ye(a)]:(e=>{const t=ye(e);return[we(e),t,we(t)]})(a)),S="none"!==f;!p&&S&&x.push(...function(e,t,n,s){const o=fe(e);let r=((e,t,n)=>{switch(e){case"top":case"bottom":return n?t?hn:pn:t?pn:hn;case"left":case"right":return t?fn:gn;default:return[]}})(he(e),"start"===n,s);return o&&(r=r.map(e=>e+"-"+o),t&&(r=r.concat(r.map(we)))),r}(a,g,f,b));const E=[a,...x],I=await c.detectOverflow(t,m),C=[];let T=(null==(s=r.flip)?void 0:s.overflows)||[];if(d&&C.push(I[v]),u){const e=((e,t,n)=>{void 0===n&&(n=!1);const s=fe(e),o=ve(e),r=ge(o);let i="x"===o?s===(n?"end":"start")?"right":"left":"start"===s?"bottom":"top";return t.reference[r]>t.floating[r]&&(i=ye(i)),[i,ye(i)]})(o,i,b);C.push(I[e[0]],I[e[1]])}if(T=[...T,{placement:o,overflows:C}],!C.every(e=>e<=0)){var P,k;const e=((null==(P=r.flip)?void 0:P.index)||0)+1,t=E[e];if(t&&("alignment"!==u||w===me(t)||T.every(e=>me(e.placement)!==w||e.overflows[0]>0)))return{data:{index:e,overflows:T},reset:{placement:t}};let n=null==(k=T.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:k.placement;if(!n)switch(h){case"bestFit":{var R;const e=null==(R=T.filter(e=>{if(S){const t=me(e.placement);return t===w||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:R[0];e&&(n=e);break}case"initialPlacement":n=a}if(o!==n)return{reset:{placement:n}}}return{}}}),In=["bottom"],Cn=["bottom-start"],Tn=["bottom"],Pn=Ot(null);export{at as CanvasKitFloatingContent,de as CanvasKitFloatingToolbarLayer,d as CanvasKitProvider,G as CanvasKitRoot,dt as FloatingSelectionToolbarPageSpace,I as applyCanvasActionShortcutOverrides,t as createCanvasApiToken,pt as createCustomShapeColor,ee as createLocalSnapshotPersistence,Pt as createThemeShapeColor,e as defineCanvasPlugin,E as getCanvasActionShortcuts,yt as getThemeColorTokenName,bt as isCustomShapeColorRef,St as isThemeShapeColorRef,se as readPersistedDocumentSnapshot,ne as readPersistedEditorSnapshots,oe as readPersistedSessionSnapshot,n as requireApi,mt as resolveShapeColor,vt as shapeColorToCssColor,u as useCanvasKit,c as useCanvasKitFloatingPortalContainer,s as useCanvasKitWheelCapture,p as useCanvasValue,lt as useFloatingSelectionToolbarPosition};
6
+ Vt(i,{})]})})})})}function Q(){return"undefined"==typeof indexedDB?Promise.resolve(null):(nn||(nn=new Promise((e,t)=>{const n=indexedDB.open("canvas-kit.persistence",2);n.addEventListener("upgradeneeded",()=>{var e;(e=n.result).objectStoreNames.contains("snapshots")||e.createObjectStore(tn)}),n.addEventListener("success",()=>{const t=n.result;t.addEventListener("versionchange",()=>{t.close(),nn=null}),e(t)}),n.addEventListener("error",()=>{nn=null,t(n.error)})})),nn)}function ee(e={}){return{async load({signal:t}){t.throwIfAborted();const n=await ne(e);return t.throwIfAborted(),n},saveDocument:t=>te({documentSnapshot:JSON.stringify(t),sessionSnapshot:null},e),saveSession:t=>te({documentSnapshot:null,sessionSnapshot:JSON.stringify(t)},e)}}async function te(e,t){const n=[];null!==e.documentSnapshot&&n.push([re(t),e.documentSnapshot]),null!==e.sessionSnapshot&&n.push([ie(t),e.sessionSnapshot]),0!==n.length&&await(async(e,t)=>{if(0===t.length)return;const n=await Q();n&&await new Promise((s,o)=>{const r=n.transaction(e,"readwrite"),i=r.objectStore(e);r.addEventListener("complete",()=>s()),r.addEventListener("abort",()=>o(r.error)),r.addEventListener("error",()=>o(r.error));for(const[e,n]of t)i.put(n,e)})})(tn,n)}async function ne(e={}){const[t,n]=await ce([re(e),ie(e)]);return{documentSnapshot:t,sessionSnapshot:n}}async function se(){return ae(sn)}async function oe(){return ae(on)}function re(e){return e.storageNamespace?`${e.storageNamespace}.document`:sn}function ie(e){return e.storageNamespace?`${e.storageNamespace}.session`:on}async function ae(e){const[t]=await ce([e]);return t??null}async function ce(e){return(await(async(e,t)=>{if(0===t.length)return[];const n=await Q();return n?new Promise((s,o)=>{const r=n.transaction(e,"readonly"),i=r.objectStore(e),a=new Array(t.length).fill(null);r.addEventListener("complete",()=>s(a)),r.addEventListener("abort",()=>o(r.error)),r.addEventListener("error",()=>o(r.error)),t.forEach((e,t)=>{const n=i.get(e);n.addEventListener("success",()=>{a[t]=n.result??null}),n.addEventListener("error",()=>o(n.error))})}):null})("snapshots",e)??e.map(()=>null)).map(le)}function le(e){if(null==e)return null;if("string"!=typeof e)throw new Error("Persisted canvas snapshot is not a JSON string.");try{return JSON.parse(e)}catch(t){throw new Error("Persisted canvas snapshot contains invalid JSON.",{cause:t})}}function de({children:e,className:t,dataUi:n="canvas-kit-floating-toolbar-layer"}){const s=a();return s?qt(Vt("div",{"data-ui":n,className:ue("land-canvas__floating-toolbar-layer",t),children:e}),s):null}function ue(...e){return e.filter(Boolean).join(" ")}function pe(e,t){return"function"==typeof e?e(t):e}function he(e){return e.split("-")[0]}function fe(e){return e.split("-")[1]}function ge(e){return"y"===e?"height":"width"}function me(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function ve(e){return"x"===me(e)?"y":"x"}function we(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}function ye(e){const t=he(e);return un[t]+e.slice(t.length)}function be(e){const{x:t,y:n,width:s,height:o}=e;return{width:s,height:o,top:n,left:t,right:t+s,bottom:n+o,x:t,y:n}}function xe(e,t,n){let{reference:s,floating:o}=e;const r=me(t),i=ve(t),a=ge(i),c=he(t),l="y"===r,d=s.x+s.width/2-o.width/2,u=s.y+s.height/2-o.height/2,p=s[a]/2-o[a]/2;let h;switch(c){case"top":h={x:d,y:s.y-o.height};break;case"bottom":h={x:d,y:s.y+s.height};break;case"right":h={x:s.x+s.width,y:u};break;case"left":h={x:s.x-o.width,y:u};break;default:h={x:s.x,y:s.y}}switch(fe(t)){case"start":h[i]-=p*(n&&l?-1:1);break;case"end":h[i]+=p*(n&&l?-1:1)}return h}async function Se(e,t){var n;void 0===t&&(t={});const{x:s,y:o,platform:r,rects:i,elements:a,strategy:c}=e,{boundary:l="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:p=!1,padding:h=0}=pe(t,e),f=(e=>"number"!=typeof e?(e=>({top:0,right:0,bottom:0,left:0,...e}))(e):{top:e,right:e,bottom:e,left:e})(h),g=a[p?"floating"===u?"reference":"floating":u],m=be(await r.getClippingRect({element:null==(n=await(null==r.isElement?void 0:r.isElement(g)))||n?g:g.contextElement||await(null==r.getDocumentElement?void 0:r.getDocumentElement(a.floating)),boundary:l,rootBoundary:d,strategy:c})),v="floating"===u?{x:s,y:o,width:i.floating.width,height:i.floating.height}:i.reference,w=await(null==r.getOffsetParent?void 0:r.getOffsetParent(a.floating)),y=await(null==r.isElement?void 0:r.isElement(w))&&await(null==r.getScale?void 0:r.getScale(w))||{x:1,y:1},b=be(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:v,offsetParent:w,strategy:c}):v);return{top:(m.top-b.top+f.top)/y.y,bottom:(b.bottom-m.bottom+f.bottom)/y.y,left:(m.left-b.left+f.left)/y.x,right:(b.right-m.right+f.right)/y.x}}function Ee(){return"undefined"!=typeof window}function Ie(e){return Pe(e)?(e.nodeName||"").toLowerCase():"#document"}function Ce(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Te(e){var t;return null==(t=(Pe(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function Pe(e){return!!Ee()&&(e instanceof Node||e instanceof Ce(e).Node)}function ke(e){return!!Ee()&&(e instanceof Element||e instanceof Ce(e).Element)}function Re(e){return!!Ee()&&(e instanceof HTMLElement||e instanceof Ce(e).HTMLElement)}function Le(e){return!(!Ee()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Ce(e).ShadowRoot)}function Ae(e){const{overflow:t,overflowX:n,overflowY:s,display:o}=Ne(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+n)&&"inline"!==o&&"contents"!==o}function De(e){return/^(table|td|th)$/.test(Ie(e))}function Me(e){try{if(e.matches(":popover-open"))return!0}catch(t){}try{return e.matches(":modal")}catch(t){return!1}}function Oe(e){const t=ke(e)?Ne(e):e;return yn(t.transform)||yn(t.translate)||yn(t.scale)||yn(t.rotate)||yn(t.perspective)||!Fe()&&(yn(t.backdropFilter)||yn(t.filter))||vn.test(t.willChange||"")||wn.test(t.contain||"")}function Fe(){return null==Ut&&(Ut="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Ut}function Be(e){return/^(html|body|#document)$/.test(Ie(e))}function Ne(e){return Ce(e).getComputedStyle(e)}function $e(e){return ke(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function He(e){if("html"===Ie(e))return e;const t=e.assignedSlot||e.parentNode||Le(e)&&e.host||Te(e);return Le(t)?t.host:t}function Ke(e){const t=He(e);return Be(t)?e.ownerDocument?e.ownerDocument.body:e.body:Re(t)&&Ae(t)?t:Ke(t)}function je(e,t,n){var s;void 0===t&&(t=[]),void 0===n&&(n=!0);const o=Ke(e),r=o===(null==(s=e.ownerDocument)?void 0:s.body),i=Ce(o);if(r){const e=ze(i);return t.concat(i,i.visualViewport||[],Ae(o)?o:[],e&&n?je(e):[])}return t.concat(o,je(o,[],n))}function ze(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function Ve(e){const t=Ne(e);let n=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const o=Re(e),r=o?e.offsetWidth:n,i=o?e.offsetHeight:s,a=cn(n)!==r||cn(s)!==i;return a&&(n=r,s=i),{width:n,height:s,$:a}}function We(e){return ke(e)?e:e.contextElement}function qe(e){const t=We(e);if(!Re(t))return dn(1);const n=t.getBoundingClientRect(),{width:s,height:o,$:r}=Ve(t);let i=(r?cn(n.width):n.width)/s,a=(r?cn(n.height):n.height)/o;return i&&Number.isFinite(i)||(i=1),a&&Number.isFinite(a)||(a=1),{x:i,y:a}}function Ue(e){const t=Ce(e);return Fe()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:bn}function _e(e,t,n,s){void 0===t&&(t=!1),void 0===n&&(n=!1);const o=e.getBoundingClientRect(),r=We(e);let i=dn(1);t&&(s?ke(s)&&(i=qe(s)):i=qe(e));const a=((e,t,n)=>(void 0===t&&(t=!1),!(!n||t&&n!==Ce(e))&&t))(r,n,s)?Ue(r):dn(0);let c=(o.left+a.x)/i.x,l=(o.top+a.y)/i.y,d=o.width/i.x,u=o.height/i.y;if(r){const e=Ce(r),t=s&&ke(s)?Ce(s):s;let n=e,o=ze(n);for(;o&&s&&t!==n;){const e=qe(o),t=o.getBoundingClientRect(),s=Ne(o),r=t.left+(o.clientLeft+parseFloat(s.paddingLeft))*e.x,i=t.top+(o.clientTop+parseFloat(s.paddingTop))*e.y;c*=e.x,l*=e.y,d*=e.x,u*=e.y,c+=r,l+=i,n=Ce(o),o=ze(n)}}return be({width:d,height:u,x:c,y:l})}function Ye(e,t){const n=$e(e).scrollLeft;return t?t.left+n:_e(Te(e)).left+n}function Xe(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-Ye(e,n),y:n.top+t.scrollTop}}function Je(e,t,n){let s;if("viewport"===t)s=((e,t)=>{const n=Ce(e),s=Te(e),o=n.visualViewport;let r=s.clientWidth,i=s.clientHeight,a=0,c=0;if(o){r=o.width,i=o.height;const e=Fe();(!e||e&&"fixed"===t)&&(a=o.offsetLeft,c=o.offsetTop)}const l=Ye(s);if(l<=0){const e=s.ownerDocument,t=e.body,n=getComputedStyle(t),o="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(s.clientWidth-t.clientWidth-o);i<=25&&(r-=i)}else l<=25&&(r+=l);return{width:r,height:i,x:a,y:c}})(e,n);else if("document"===t)s=(e=>{const t=Te(e),n=$e(e),s=e.ownerDocument.body,o=an(t.scrollWidth,t.clientWidth,s.scrollWidth,s.clientWidth),r=an(t.scrollHeight,t.clientHeight,s.scrollHeight,s.clientHeight);let i=-n.scrollLeft+Ye(e);const a=-n.scrollTop;return"rtl"===Ne(s).direction&&(i+=an(t.clientWidth,s.clientWidth)-o),{width:o,height:r,x:i,y:a}})(Te(e));else if(ke(t))s=((e,t)=>{const n=_e(e,!0,"fixed"===t),s=n.top+e.clientTop,o=n.left+e.clientLeft,r=Re(e)?qe(e):dn(1);return{width:e.clientWidth*r.x,height:e.clientHeight*r.y,x:o*r.x,y:s*r.y}})(t,n);else{const n=Ue(e);s={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return be(s)}function Ge(e,t){const n=He(e);return!(n===t||!ke(n)||Be(n))&&("fixed"===Ne(n).position||Ge(n,t))}function Ze(e,t){const n=t.get(e);if(n)return n;let s=je(e,[],!1).filter(e=>ke(e)&&"body"!==Ie(e)),o=null;const r="fixed"===Ne(e).position;let i=r?He(e):e;for(;ke(i)&&!Be(i);){const t=Ne(i),n=Oe(i);n||"fixed"!==t.position||(o=null),(r?!n&&!o:!n&&"static"===t.position&&o&&("absolute"===o.position||"fixed"===o.position)||Ae(i)&&!n&&Ge(e,i))?s=s.filter(e=>e!==i):o=t,i=He(i)}return t.set(e,s),s}function Qe(e,t,n){function s(){l.x=Ye(r)}const o=Re(t),r=Te(t),i="fixed"===n,a=_e(e,!0,i,t);let c={scrollLeft:0,scrollTop:0};const l=dn(0);if(o||!o&&!i)if(("body"!==Ie(t)||Ae(r))&&(c=$e(t)),o){const e=_e(t,!0,i,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}else r&&s();i&&!o&&r&&s();const d=!r||o||i?dn(0):Xe(r,c);return{x:a.left+c.scrollLeft-l.x-d.x,y:a.top+c.scrollTop-l.y-d.y,width:a.width,height:a.height}}function et(e){return"static"===Ne(e).position}function tt(e,t){if(!Re(e)||"fixed"===Ne(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Te(e)===n&&(n=n.ownerDocument.body),n}function nt(e,t){const n=Ce(e);if(Me(e))return n;if(!Re(e)){let t=He(e);for(;t&&!Be(t);){if(ke(t)&&!et(t))return t;t=He(t)}return n}let s=tt(e,t);for(;s&&De(s)&&et(s);)s=tt(s,t);return s&&Be(s)&&et(s)&&!Oe(s)?n:s||(e=>{let t=He(e);for(;Re(t)&&!Be(t);){if(Oe(t))return t;if(Me(t))return null;t=He(t)}return null})(e)||n}function st(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function ot({viewport:e,fallbackPlacements:t,floatingRef:n,getReferenceElement:s,onPlacementChange:o,offset:r,placement:i,visible:a=!0}){Nt(()=>{const c=s(),l=n.current;if(!c||!l)return;let d=!1,u=0;l.style.visibility="hidden";const p=()=>{const e=++u,n=it("--toolbar-floating-collision-padding",8);((e,t,n)=>{const s={platform:xn,...n},o={...s.platform,_c:new Map};return(async(e,t,n)=>{const{placement:s="bottom",strategy:o="absolute",middleware:r=[],platform:i}=n,a=i.detectOverflow?i:{...i,detectOverflow:Se},c=await(null==i.isRTL?void 0:i.isRTL(t));let l=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:u}=xe(l,s,c),p=s,h=0;const f={};for(let g=0;g<r.length;g++){const n=r[g];if(!n)continue;const{name:m,fn:v}=n,{x:w,y:y,data:b,reset:x}=await v({x:d,y:u,initialPlacement:s,placement:p,strategy:o,middlewareData:f,rects:l,platform:a,elements:{reference:e,floating:t}});d=null!=w?w:d,u=null!=y?y:u,f[m]={...f[m],...b},x&&h<50&&(h++,"object"==typeof x&&(x.placement&&(p=x.placement),x.rects&&(l=!0===x.rects?await i.getElementRects({reference:e,floating:t,strategy:o}):x.rects),({x:d,y:u}=xe(l,p,c))),g=-1)}return{x:d,y:u,placement:p,strategy:o,middlewareData:f}})(e,t,{...s,platform:o})})(c,l,{strategy:"fixed",placement:i,middleware:rt({fallbackPlacements:t,offset:r??it("--toolbar-floating-offset",38),padding:{top:it("--toolbar-floating-safe-top",64),right:n,bottom:n,left:n}})}).then(({placement:t,x:n,y:s})=>{d||e!==u||(l.dataset.placement=t,o?.(t),l.style.transform=`translate3d(${Math.round(n)}px, ${Math.round(s)}px, 0)`,l.style.visibility=a?"visible":"hidden")})},h=function(e,t,n,s){void 0===s&&(s={});const{ancestorScroll:o=!0,ancestorResize:r=!0,elementResize:i="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:c=!1}=s,l=We(e),d=o||r?[...l?je(l):[],...t?je(t):[]]:[];d.forEach(e=>{o&&e.addEventListener("scroll",n,{passive:!0}),r&&e.addEventListener("resize",n)});const u=l&&a?((e,t)=>{function n(){var e;clearTimeout(s),null==(e=o)||e.disconnect(),o=null}let s,o=null;const r=Te(e);return function i(a,c){function l(t){const n=t[0].intersectionRatio;if(n!==c){if(!m)return i();n?i(!1,n):s=setTimeout(()=>{i(!1,1e-7)},1e3)}1!==n||st(d,e.getBoundingClientRect())||i(),m=!1}void 0===a&&(a=!1),void 0===c&&(c=1),n();const d=e.getBoundingClientRect(),{left:u,top:p,width:h,height:f}=d;if(a||t(),!h||!f)return;const g={rootMargin:-ln(p)+"px "+-ln(r.clientWidth-(u+h))+"px "+-ln(r.clientHeight-(p+f))+"px "+-ln(u)+"px",threshold:an(0,rn(1,c))||1};let m=!0;try{o=new IntersectionObserver(l,{...g,root:r.ownerDocument})}catch(v){o=new IntersectionObserver(l,g)}o.observe(e)}(!0),n})(l,n):null;let p,h=-1,f=null;i&&(f=new ResizeObserver(e=>{let[s]=e;s&&s.target===l&&f&&t&&(f.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),n()}),l&&!c&&f.observe(l),t&&f.observe(t));let g=c?_e(e):null;return c&&function t(){const s=_e(e);g&&!st(g,s)&&n(),g=s,p=requestAnimationFrame(t)}(),n(),()=>{var e;d.forEach(e=>{o&&e.removeEventListener("scroll",n),r&&e.removeEventListener("resize",n)}),u?.(),null==(e=f)||e.disconnect(),f=null,c&&cancelAnimationFrame(p)}}(c,l,p,{ancestorResize:!0,ancestorScroll:!0,elementResize:!0,layoutShift:!0}),f=e.subscribe(p);return p(),()=>{d=!0,l.style.visibility="hidden",h(),f()}},[e,t,n,s,o,r,i,a])}function rt({fallbackPlacements:e,offset:t,padding:n}){return[Sn(t),En({fallbackPlacements:[...e],padding:n})]}function it(e,t){if("undefined"==typeof document)return t;const n=getComputedStyle(document.documentElement).getPropertyValue(e).trim();if(!n)return t;const s=Number.parseFloat(n);return Number.isFinite(s)?n.endsWith("rem")?16*s:s:t}function at(e){const t=a();return t?qt(Vt(ct,{...e}),t):null}function ct({fallbackPlacements:e=In,offset:t=8,placement:n="top",referenceElement:o,...r}){const i=u(),a=Ht(null),c=Ft(()=>o,[o]);return s(a),ot({viewport:i.viewport.state,fallbackPlacements:e,floatingRef:a,getReferenceElement:c,offset:t,placement:n}),Vt("div",{...r,ref:a})}function lt(){return Bt(Pn)}function dt({children:e,className:t,dataUi:n="floating-selection-toolbar-slot",horizontalAlign:o="start",offset:r,visible:i=!0}){const a=u(),c=p(a.selection.state),l=p(a.viewport.state),d=Ht(null),h=Ht(null),[f,g]=Kt("center"===o?"top":"top-start"),m=c.pageBounds??(c.anchorPagePoint?{x:c.anchorPagePoint.x,y:c.anchorPagePoint.y,width:0,height:0}:null),v=i&&null!==m,w=v&&!c.isTranslating,y=Ft(()=>d.current,[m?.height,m?.width,m?.x,m?.y]),b=Ft(()=>d.current?.getBoundingClientRect()??null,[]),x=$t(()=>({placement:f,getContentBounds:b}),[m?.height,m?.width,m?.x,m?.y,b,f,l.pageTransform]);return s(h),ot({viewport:a.viewport.state,fallbackPlacements:"center"===o?Tn:Cn,floatingRef:h,getReferenceElement:y,onPlacementChange:g,offset:r,placement:"center"===o?"top":"top-start",visible:w}),v&&m?Wt(zt,{children:[Vt("div",{"data-ui":`${n}-page-space`,className:"land-canvas__floating-selection-page-space",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",transform:l.pageTransform,transformOrigin:"0 0"},children:Vt("div",{ref:d,"aria-hidden":"true",style:{position:"absolute",left:m.x,top:m.y,width:m.width,height:m.height,pointerEvents:"none"}})}),Vt("div",{ref:h,"data-ui":n,className:ut("land-canvas__floating-selection-anchor",t),style:{position:"fixed",left:0,top:0,visibility:"hidden",willChange:"transform"},children:Vt(Pn.Provider,{value:x,children:e})})]}):null}function ut(...e){return e.filter(Boolean).join(" ")}import{A as pt,C as ht,D as ft,E as gt,F as mt,I as vt,L as wt,M as yt,N as bt,O as xt,P as St,R as Et,T as It,a as Ct,f as Tt,j as Pt,k as kt,o as Rt,r as Lt,u as At,x as Dt,z as Mt}from"./host-s4jdMA_d.mjs";import{createContext as Ot,useCallback as Ft,useContext as Bt,useEffect as Nt,useMemo as $t,useRef as Ht,useState as Kt,useSyncExternalStore as jt}from"react";import{Fragment as zt,jsx as Vt,jsxs as Wt}from"react/jsx-runtime";import{createPortal as qt}from"react-dom";var Ut,_t=Ot(null),Yt=Ot(null),Xt={state:"idle"},Jt=class{abortController=new AbortController;activeTasks=new Set;disposers=[];phase="starting";close=null;signal=this.abortController.signal;tasks={run:e=>this.runTask(e)};own(e,t){if("starting"!==this.phase)throw new Error("Cannot register a resource after the Canvas Runtime is published or disposal starts.");return this.disposers.push(n=>"function"==typeof t?t(e):"rollback"===n&&t.rollback?t.rollback(e):t.shutdown(e)),e}publish({beforeShutdown:e}={}){if("starting"!==this.phase)throw new Error(`Only a starting Canvas Runtime can be published; received runtime in "${this.phase}" phase.`);return this.phase="ready",()=>null!==this.close?"shutdown"===this.close.mode?this.close.result:Promise.reject(new Error("Cannot shut down a Canvas Runtime during rollback.")):this.beginClose({mode:"shutdown",beforeShutdown:e})}rollback(e){return null!==this.close?"rollback"===this.close.mode?this.close.result:Promise.reject(new Error("Cannot roll back a Canvas Runtime during shutdown.")):"starting"!==this.phase?Promise.reject(new Error(`Only a starting Canvas Runtime can roll back; received runtime in "${this.phase}" phase.`)):this.beginClose({mode:"rollback",cause:e})}beginClose(e){const t=[],n=Promise.resolve().then(async()=>{const n=[...t,...await this.disposeResources(e.mode)];if(this.phase="disposed","rollback"===e.mode){if(n.length>0)throw new AggregateError([e.cause,...n],"CanvasKit Runtime initialization failed and cleanup reported errors.",{cause:e.cause});throw e.cause}if(n.length>0)throw new AggregateError(n,"Failed to dispose one or more CanvasKit Runtime resources.")});if(this.close={mode:e.mode,result:n},"shutdown"===e.mode)try{e.beforeShutdown?.()}catch(s){t.push(s)}return this.phase="disposing",this.abortController.abort("rollback"===e.mode?e.cause:new DOMException("Canvas runtime is disposing.","AbortError")),n}runTask(e){if("ready"!==this.phase)throw new Error(`Canvas tasks require a ready runtime; received runtime in "${this.phase}" phase.`);this.signal.throwIfAborted();const t=Promise.resolve().then(()=>e(this.signal));return this.activeTasks.add(t),t.finally(()=>this.activeTasks.delete(t)).catch(()=>{}),t}async disposeResources(e){await Promise.allSettled([...this.activeTasks]);const t=[];for(;this.disposers.length>0;){const s=this.disposers.pop();try{await s(e)}catch(n){t.push(n)}}return t}},Gt=[500,1e3,2e3,5e3],Zt=class{editor;adapter;options;unsubscribeDocument=null;unsubscribeSession=null;unsubscribeFlushEvents=null;documentTimer=null;sessionTimer=null;pendingDocument=null;pendingSession=null;documentVersion=0;sessionVersion=0;documentRetryCount=0;sessionRetryCount=0;writeChain=Promise.resolve();flushChain=Promise.resolve();isRunning=!1;disposeMode=null;disposePromise=null;constructor(e,t,n={}){this.editor=e,this.adapter=t,this.options=n}start(){if(null!==this.disposeMode)throw new Error("Cannot start disposed canvas persistence.");this.isRunning||(this.isRunning=!0,this.adapter.saveDocument&&(this.unsubscribeDocument=this.editor.operations.subscribe(e=>{var t;this.documentVersion+=1,this.documentRetryCount=0,this.pendingDocument={snapshot:(t=e.snapshot,JSON.parse(JSON.stringify(t))),version:this.documentVersion},this.scheduleDocumentSave(200)})),this.adapter.saveSession&&(this.unsubscribeSession=this.editor.listen(e=>{var t,n;((t=e.diff).added.some(e=>"session"===e.scope)||t.updated.some(e=>"session"===e.before.scope||"session"===e.after.scope)||t.removed.some(e=>"session"===e.scope))&&(this.sessionVersion+=1,this.sessionRetryCount=0,this.pendingSession={snapshot:(n=this.editor.snapshots.getSession(),JSON.parse(JSON.stringify(n))),version:this.sessionVersion},this.scheduleSessionSave(200))})),this.unsubscribeFlushEvents=this.options.flushEvents?.subscribe(this.flushForHostLifecycle)??null)}flush(){if(null!==this.disposeMode)return Promise.reject(new Error("Cannot flush disposed canvas persistence."));const e=this.flushChain.then(()=>this.flushNow());return this.flushChain=e.catch(()=>{}),e}shutdown(){return this.dispose("shutdown")}rollback(){return this.dispose("rollback")}dispose(e){return null!==this.disposeMode?this.disposeMode!==e?Promise.reject(new Error(`Canvas persistence disposal already started in "${this.disposeMode}" mode.`)):this.disposePromise:(this.disposeMode=e,this.disposePromise=Promise.resolve().then(()=>"shutdown"===e?this.finishShutdown():this.finishRollback()),this.disposePromise)}async finishShutdown(){this.stopIntake(),await this.flushChain,await this.flushNow()}async finishRollback(){this.stopIntake(),this.discardPendingSnapshots(),await this.flushChain,await this.writeChain,this.discardPendingSnapshots()}stopIntake(){this.isRunning=!1,this.cancelDocumentTimer(),this.cancelSessionTimer(),this.unsubscribeDocument?.(),this.unsubscribeSession?.(),this.unsubscribeFlushEvents?.(),this.unsubscribeDocument=null,this.unsubscribeSession=null,this.unsubscribeFlushEvents=null}async flushNow(){const e=await this.flushPendingSnapshots();try{await(this.adapter.flush?.())}catch(t){e.push(t)}if(e.length>0)throw new AggregateError(e,"Failed to flush canvas persistence.")}async flushPendingSnapshots(){this.cancelDocumentTimer(),this.cancelSessionTimer();const e=this.savePendingDocument(),t=this.savePendingSession();return(await Promise.allSettled([e,t])).flatMap(e=>"rejected"===e.status?[e.reason]:[])}discardPendingSnapshots(){this.cancelDocumentTimer(),this.cancelSessionTimer(),this.pendingDocument=null,this.pendingSession=null}savePendingDocument(){const e=this.pendingDocument;if(!e||!this.adapter.saveDocument)return this.writeChain;this.pendingDocument=null;const t=this.queueWrite(()=>Promise.resolve(this.adapter.saveDocument(e.snapshot))).then(()=>{this.documentVersion===e.version&&(this.documentRetryCount=0)}).catch(t=>{throw this.documentVersion===e.version&&null===this.pendingDocument&&(this.pendingDocument=e,this.scheduleDocumentRetry()),t});return this.writeChain=t.catch(()=>{}),t}savePendingSession(){const e=this.pendingSession;if(!e||!this.adapter.saveSession)return this.writeChain;this.pendingSession=null;const t=this.queueWrite(()=>Promise.resolve(this.adapter.saveSession(e.snapshot))).then(()=>{this.sessionVersion===e.version&&(this.sessionRetryCount=0)}).catch(t=>{throw this.sessionVersion===e.version&&null===this.pendingSession&&(this.pendingSession=e,this.scheduleSessionRetry()),t});return this.writeChain=t.catch(()=>{}),t}queueWrite(e){return this.writeChain.then(e)}scheduleDocumentSave(e){this.cancelDocumentTimer(),this.documentTimer=setTimeout(()=>{this.documentTimer=null,this.savePendingDocument().catch(e=>{this.reportError("Could not persist canvas document.",e)})},e)}scheduleSessionSave(e){this.cancelSessionTimer(),this.sessionTimer=setTimeout(()=>{this.sessionTimer=null,this.savePendingSession().catch(e=>{this.reportError("Could not persist canvas session.",e)})},e)}scheduleDocumentRetry(){if(!this.isRunning||null!==this.documentTimer)return;const e=Gt[this.documentRetryCount];void 0!==e&&(this.documentRetryCount+=1,this.scheduleDocumentSave(e))}scheduleSessionRetry(){if(!this.isRunning||null!==this.sessionTimer)return;const e=Gt[this.sessionRetryCount];void 0!==e&&(this.sessionRetryCount+=1,this.scheduleSessionSave(e))}cancelDocumentTimer(){null!==this.documentTimer&&(clearTimeout(this.documentTimer),this.documentTimer=null)}cancelSessionTimer(){null!==this.sessionTimer&&(clearTimeout(this.sessionTimer),this.sessionTimer=null)}flushForHostLifecycle=()=>{this.flush().catch(e=>{this.reportError("Could not persist canvas snapshot.",e)})};reportError(e,t){try{this.options.onError?.(new Error(e,{cause:t}))}catch{}}},Qt={status:"starting"},en=[],tn="snapshots",nn=null,sn="canvas-kit.document",on="canvas-kit.session",rn=Math.min,an=Math.max,cn=Math.round,ln=Math.floor,dn=e=>({x:e,y:e}),un={left:"right",right:"left",bottom:"top",top:"bottom"},pn=["left","right"],hn=["right","left"],fn=["top","bottom"],gn=["bottom","top"],mn=new Set(["left","top"]),vn=/transform|translate|scale|rotate|perspective|filter/,wn=/paint|layout|strict|content/,yn=e=>!!e&&"none"!==e,bn=dn(0),xn={convertOffsetParentRelativeRectToViewportRelativeRect:e=>{let{elements:t,rect:n,offsetParent:s,strategy:o}=e;const r="fixed"===o,i=Te(s),a=!!t&&Me(t.floating);if(s===i||a&&r)return n;let c={scrollLeft:0,scrollTop:0},l=dn(1);const d=dn(0),u=Re(s);if((u||!u&&!r)&&(("body"!==Ie(s)||Ae(i))&&(c=$e(s)),u)){const e=_e(s);l=qe(s),d.x=e.x+s.clientLeft,d.y=e.y+s.clientTop}const p=!i||u||r?dn(0):Xe(i,c);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+d.x+p.x,y:n.y*l.y-c.scrollTop*l.y+d.y+p.y}},getDocumentElement:Te,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:s,strategy:o}=e;const r=[..."clippingAncestors"===n?Me(t)?[]:Ze(t,this._c):[].concat(n),s],i=Je(t,r[0],o);let a=i.top,c=i.right,l=i.bottom,d=i.left;for(let u=1;u<r.length;u++){const e=Je(t,r[u],o);a=an(e.top,a),c=rn(e.right,c),l=rn(e.bottom,l),d=an(e.left,d)}return{width:c-d,height:l-a,x:d,y:a}},getOffsetParent:nt,getElementRects:async function(e){const t=this.getOffsetParent||nt,n=this.getDimensions,s=await n(e.floating);return{reference:Qe(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}},getClientRects:e=>Array.from(e.getClientRects()),getDimensions:e=>{const{width:t,height:n}=Ve(e);return{width:t,height:n}},getScale:qe,isElement:ke,isRTL:e=>"rtl"===Ne(e).direction},Sn=e=>(void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var n,s;const{x:o,y:r,placement:i,middlewareData:a}=t,c=await(async(e,t)=>{const{placement:n,platform:s,elements:o}=e,r=await(null==s.isRTL?void 0:s.isRTL(o.floating)),i=he(n),a=fe(n),c="y"===me(n),l=mn.has(i)?-1:1,d=r&&c?-1:1,u=pe(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:f}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&"number"==typeof f&&(h="end"===a?-1*f:f),c?{x:h*d,y:p*l}:{x:p*l,y:h*d}})(t,e);return i===(null==(n=a.offset)?void 0:n.placement)&&null!=(s=a.arrow)&&s.alignmentOffset?{}:{x:o+c.x,y:r+c.y,data:{...c,placement:i}}}}),En=e=>(void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,s;const{placement:o,middlewareData:r,rects:i,initialPlacement:a,platform:c,elements:l}=t,{mainAxis:d=!0,crossAxis:u=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:g=!0,...m}=pe(e,t);if(null!=(n=r.arrow)&&n.alignmentOffset)return{};const v=he(o),w=me(a),y=he(a)===a,b=await(null==c.isRTL?void 0:c.isRTL(l.floating)),x=p||(y||!g?[ye(a)]:(e=>{const t=ye(e);return[we(e),t,we(t)]})(a)),S="none"!==f;!p&&S&&x.push(...function(e,t,n,s){const o=fe(e);let r=((e,t,n)=>{switch(e){case"top":case"bottom":return n?t?hn:pn:t?pn:hn;case"left":case"right":return t?fn:gn;default:return[]}})(he(e),"start"===n,s);return o&&(r=r.map(e=>e+"-"+o),t&&(r=r.concat(r.map(we)))),r}(a,g,f,b));const E=[a,...x],I=await c.detectOverflow(t,m),C=[];let T=(null==(s=r.flip)?void 0:s.overflows)||[];if(d&&C.push(I[v]),u){const e=((e,t,n)=>{void 0===n&&(n=!1);const s=fe(e),o=ve(e),r=ge(o);let i="x"===o?s===(n?"end":"start")?"right":"left":"start"===s?"bottom":"top";return t.reference[r]>t.floating[r]&&(i=ye(i)),[i,ye(i)]})(o,i,b);C.push(I[e[0]],I[e[1]])}if(T=[...T,{placement:o,overflows:C}],!C.every(e=>e<=0)){var P,k;const e=((null==(P=r.flip)?void 0:P.index)||0)+1,t=E[e];if(t&&("alignment"!==u||w===me(t)||T.every(e=>me(e.placement)!==w||e.overflows[0]>0)))return{data:{index:e,overflows:T},reset:{placement:t}};let n=null==(k=T.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:k.placement;if(!n)switch(h){case"bestFit":{var R;const e=null==(R=T.filter(e=>{if(S){const t=me(e.placement);return t===w||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:R[0];e&&(n=e);break}case"initialPlacement":n=a}if(o!==n)return{reset:{placement:n}}}return{}}}),In=["bottom"],Cn=["bottom-start"],Tn=["bottom"],Pn=Ot(null);export{at as CanvasKitFloatingContent,de as CanvasKitFloatingToolbarLayer,d as CanvasKitProvider,G as CanvasKitRoot,dt as FloatingSelectionToolbarPageSpace,I as applyCanvasActionShortcutOverrides,t as createCanvasApiToken,pt as createCustomShapeColor,ee as createLocalSnapshotPersistence,Pt as createThemeShapeColor,e as defineCanvasPlugin,E as getCanvasActionShortcuts,yt as getThemeColorTokenName,bt as isCustomShapeColorRef,St as isThemeShapeColorRef,se as readPersistedDocumentSnapshot,ne as readPersistedEditorSnapshots,oe as readPersistedSessionSnapshot,n as requireApi,mt as resolveShapeColor,vt as shapeColorToCssColor,u as useCanvasKit,c as useCanvasKitFloatingPortalContainer,s as useCanvasKitWheelCapture,p as useCanvasValue,lt as useFloatingSelectionToolbarPosition};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yuzhouu/canvas-kit",
3
- "version": "0.1.19",
3
+ "version": "0.1.20",
4
4
  "description": "Extensible Land canvas runtime, React product primitives, and typed API surface.",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
@@ -1 +1 @@
1
- import{C as s,S as a,_ as o,a as m,b as r,c as t,d as p,f,g as h,h as i,i as x,l as b,m as c,n as d,o as e,p as g,r as j,s as l,t as n,u,v,w,x as y,y as C}from"./host-CW9xZzD2.mjs";export{x as CANVAS_SURFACE_DATA_UI,m as CANVAS_SURFACE_SELECTOR,j as Canvas,o as CanvasRenderBindingsContext,g as DefaultGrid,s as EditorContext,a as PageSpace,c as SHAPE_HOVER_STROKE,i as SHAPE_HOVER_STROKE_WIDTH,n as ShapeHeadingControl,y as createCanvasRenderBindings,d as createShapeHeadingDomEventGuard,e as forwardWheelEventToCanvasSurface,l as getCanvasSurfaceElement,t as getCanvasSurfaceElementForNode,b as getCanvasSurfacePagePoint,u as getCanvasSurfaceScreenPoint,p as getEditableEventTarget,f as isEditableEventTarget,v as useCanvasOverlays,C as useCanvasRenderBindings,r as useCanvasRenderers,w as useEditor,h as useValue};
1
+ import{C as s,S as a,_ as o,a as m,b as r,c as t,d as p,f,g as h,h as i,i as x,l as b,m as c,n as d,o as e,p as g,r as j,s as l,t as n,u,v,w,x as y,y as C}from"./host-s4jdMA_d.mjs";export{x as CANVAS_SURFACE_DATA_UI,m as CANVAS_SURFACE_SELECTOR,j as Canvas,o as CanvasRenderBindingsContext,g as DefaultGrid,s as EditorContext,a as PageSpace,c as SHAPE_HOVER_STROKE,i as SHAPE_HOVER_STROKE_WIDTH,n as ShapeHeadingControl,y as createCanvasRenderBindings,d as createShapeHeadingDomEventGuard,e as forwardWheelEventToCanvasSurface,l as getCanvasSurfaceElement,t as getCanvasSurfaceElementForNode,b as getCanvasSurfacePagePoint,u as getCanvasSurfaceScreenPoint,p as getEditableEventTarget,f as isEditableEventTarget,v as useCanvasOverlays,C as useCanvasRenderBindings,r as useCanvasRenderers,w as useEditor,h as useValue};