@yuzhouu/canvas-kit 0.1.20 → 0.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/host-s4jdMA_d.mjs DELETED
@@ -1,49 +0,0 @@
1
- function e(){return new Br}function t(e){return 0===e.added.length&&0===e.updated.length&&0===e.removed.length}function n(e){return e instanceof Map?new Map(e):new Map(Array.from(e,e=>[e.id,e]))}function i(e){return{added:[...e.removed],updated:e.updated.map(e=>({before:e.after,after:e.before})),removed:[...e.added]}}function s(e,t){const n=new Map,i=new Map,s=new Map;for(const r of e.added)n.set(r.id,r);for(const r of e.updated)i.set(r.after.id,r);for(const r of e.removed)s.set(r.id,r);for(const r of t.added){const e=s.get(r.id);if(e){s.delete(r.id),i.set(r.id,{before:e,after:r});continue}const t=i.get(r.id);t?i.set(r.id,{before:t.before,after:r}):n.set(r.id,r)}for(const r of t.updated){if(n.get(r.after.id)){n.set(r.after.id,r.after);continue}const e=s.get(r.after.id);if(e){s.delete(r.after.id),i.set(r.after.id,{before:e,after:r.after});continue}const t=i.get(r.after.id);i.set(r.after.id,t?{before:t.before,after:r.after}:{before:r.before,after:r.after})}for(const r of t.removed){if(n.get(r.id)){n.delete(r.id);continue}const e=i.get(r.id);e?(i.delete(r.id),s.set(r.id,e.before)):s.set(r.id,r)}const o={added:[],updated:[],removed:[]};for(const r of n.values())o.added.push(r);for(const r of i.values())r.before!==r.after&&o.updated.push(r);for(const r of s.values())o.removed.push(r);return o}function o(e){const t={added:[],updated:[],removed:[]};for(const{before:n,after:i}of e.values())n!==i&&(!n&&i?t.added.push(i):n&&!i?t.removed.push(n):n&&i&&t.updated.push({before:n,after:i}));return t}function r(e,t){for(const[n,i]of t)i.after?(i.moveToEnd&&e.delete(n),e.set(n,i.after)):e.delete(n)}function a(e={}){return{id:Ar,typeName:"document",scope:"document",meta:{...e}}}function d(){return{id:Rr,typeName:"page",scope:"document",name:"Page 1",index:"0001",meta:{}}}function c(e=Rr){return{id:Kr,typeName:"session",scope:"session",currentPageId:e,activeToolId:"select",isToolLocked:!1,editingShapeId:null,shapeEditingSession:null,pageCameraById:{[e]:{...Yr}},pageSelectedShapeIdsById:{[e]:[]},meta:{}}}function l(e){return!!e&&"page"===e.typeName}function h(e){return!!e&&"document"===e.typeName}function p(e){return!!e&&"shape"===e.typeName}function u(e){return!!e&&"session"===e.typeName}function g(e){return!!e&&"binding"===e.typeName}function f(e){return!!e&&"asset"===e.typeName}function m(e){return"document"===e.scope}function S(e){return e[Xr]}function y(e,t,n){return I([e],t,n).get(e)??e}function I(e,t,n){const i=[...t].sort((e,t)=>e.id.localeCompare(t.id)),s=new Map;for(const r of i){const e=Array.from(new Set([r.ownerId,...r.endpoints.map(({targetId:e})=>e)]));for(const t of e){if(s.has(t))continue;const e=n(r).getShapeCompanionRootId?.(r,t);e&&e!==t&&s.set(t,e)}}const o=new Map;for(const r of e){if(o.has(r))continue;const e=new Set([r]);let t=r;for(;;){const n=s.get(t);if(!n){o.set(r,t);break}if(e.has(n)){o.set(r,r);break}e.add(n),t=n}}return o}function w({before:e,after:t}){return e.parentId!==t.parentId||e.x!==t.x||e.y!==t.y||e.rotation!==t.rotation||e.scaleX!==t.scaleX||e.scaleY!==t.scaleY||e.props!==t.props}function P(e){return Array.from(new Set([e.ownerId,...e.endpoints.map(({targetId:e})=>e)]))}function b(e,t){return{owner:e.ownerId===t,endpointSlots:e.endpoints.filter(({targetId:e})=>e===t).map(({slot:e})=>e)}}function v(e){const t=e();if(("object"==typeof(n=t)&&null!==n||"function"==typeof n)&&"function"==typeof n.then)throw new Error("Binding reaction scope callbacks must be synchronous");var n;return t}function x({editor:e,exporters:t,shapeIds:n}){const i=Array.from(n),s=e.layers.getExportTraversalIds(i),o=[];for(const h of s){const n=e.shapes.get(h);n?(C(e.shapes.computeExportPageBounds(n))||o.push({kind:"missing-bounds",id:n.id,canRepair:!1}),t.get(n.type)||o.push({kind:"missing-exporter",id:n.id,canRepair:!1})):o.push({kind:"missing-shape",id:h,canRepair:!1})}const r=new Set(s),a=new Set,d=S(e).getAll().filter(g).sort((e,t)=>e.id.localeCompare(t.id));for(const h of d){if(!r.has(h.ownerId)&&h.endpoints.every(({targetId:e})=>!r.has(e)))continue;const t=e.shapes.get(h.ownerId),n=h.endpoints.some(({targetId:t})=>!e.shapes.get(t));t&&!n?e.bindings.canBind(h)?(e.bindings.getConflicting(h).some(e=>a.has(e.id))&&o.push({kind:"duplicate-exclusive-binding",id:h.id,canRepair:!0}),a.add(h.id)):o.push({kind:"invalid-binding",id:h.id,canRepair:!0}):o.push({kind:"missing-binding-endpoint",id:h.id,canRepair:!0})}const c=o.filter(e=>e.canRepair).length,l=o.length-c;return{requestedShapeIds:i,issues:o,repairableIssueCount:c,fatalIssueCount:l,canExport:0===l}}function C(e){return Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.w)&&Number.isFinite(e.h)&&e.w>=0&&e.h>=0}function M(e){return Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.w)&&Number.isFinite(e.h)&&e.w>=0&&e.h>=0}function T(e,t,n){return e.dist(((e,t,n)=>{const i=t.sub(e),s=n.sub(e),o=i.x*i.x+i.y*i.y;if(0===o)return e;const r=Math.max(0,Math.min(1,(s.x*i.x+s.y*i.y)/o));return new Lr(e.x+i.x*r,e.y+i.y*r)})(t,n,e))}function B(e,t,n,i){return((e,t,n,i)=>{const s=t.sub(e),o=i.sub(n),r=s.x*o.y-s.y*o.x;if(Math.abs(r)<1e-8)return!1;const a=n.sub(e),d=(a.x*o.y-a.y*o.x)/r,c=(a.x*s.y-a.y*s.x)/r;return d>=0&&d<=1&&c>=0&&c<=1})(e,t,n,i)?0:Math.min(T(e,n,i),T(t,n,i),T(n,e,t),T(i,e,t))}function k(e){return e.length>=3&&e.every(e=>Number.isFinite(e.x)&&Number.isFinite(e.y))}function E(e){const t=e.filter(k).flatMap(e=>e);return t.length>0?zr.FromPoints(t):null}function A(e,t){if(!k(t))return!1;let n=!1;for(let i=0;i<t.length;i+=1){const s=t[i],o=t[(i+t.length-1)%t.length];if(T(e,o,s)<=1e-8)return!0;s.y>e.y!=o.y>e.y&&e.x<(o.x-s.x)*(e.y-s.y)/(o.y-s.y)+s.x&&(n=!n)}return n}function R(e,t){return t.some(t=>A(e,t))}function K(e,t,n,i=0){if(!k(n))return!1;if(A(e,n)||A(t,n))return!0;for(let s=0;s<n.length;s+=1)if(B(e,t,n[s],n[(s+1)%n.length])<=Math.max(0,i))return!0;return!1}function Y(e){return{kind:"theme",slot:e}}function X(e){return{kind:"custom",value:e}}function F(e){return!!e&&"object"==typeof e&&"theme"===e.kind&&_r.includes(e.slot)}function D(e){return!!e&&"object"==typeof e&&"custom"===e.kind&&"string"==typeof e.value}function O(e){return $r[e]}function L(e){return"custom"===e.kind?e.value:`var(${O(e.slot)}, ${Nr[e.slot]})`}function z(e,t){if("custom"===e.kind)return e.value;const n=O(e.slot),i=Nr[e.slot];return t?.(n,i)??i}function _(e,t,n){const i=new Set;let s=n.parentId;for(;s.startsWith("shape:");){const n=s;if(n===t)return!0;if(i.has(n))return!1;i.add(n);const o=e.shapes.get(n);if(!o)return!1;s=o.parentId}return!1}function $(e,t,n){let i=((e,t)=>{const n=N(e,t),i=e.shapes.computeExportToPageTransform(t);return zr.FromPoints([new Lr(n.minX,n.minY),new Lr(n.maxX,n.minY),new Lr(n.maxX,n.maxY),new Lr(n.minX,n.maxY)].map(e=>i.applyToPoint(e)))})(e,t);if(!M(i))return i;for(const s of((e,t,n)=>{const i=[];for(const s of U(e,t,n)){const t=W(e,s);t&&M(t)&&i.push(t)}return i})(e,t,n)){const e=G(i,s);if(!e)return null;i=e}return i}function N(e,t){const n=[e.shapes.computeExportBounds(t)];for(const i of e.shapeSvgDecorations.get(t.subType)){const e=i.getExportBounds?.(t);e&&n.push(e)}return j(n)}function U(e,t,n){const i=[],s=new Set;let o=t.parentId;for(;o.startsWith("shape:");){const t=o;if(s.has(t))break;s.add(t);const r=e.shapes.get(t);if(!r)break;n.has(r.id)&&i.push(r),o=r.parentId}return i.reverse()}function H(e,t,n,i){if(n.has(t.id))return n.get(t.id)??null;const s=e.shapes.getUtil(t),o=s.getChildExportClipLocalPolygons(t);if(!o||!E(o))return n.set(t.id,null),null;const r=e.shapes.computeExportToPageTransform(t).toSvgString(),a=s.getChildExportClipLocalBounds(t),[d]=o,c=1===o.length&&d&&a&&((e,t)=>{const n=[new Lr(t.minX,t.minY),new Lr(t.maxX,t.minY),new Lr(t.maxX,t.maxY),new Lr(t.minX,t.maxY)];return e.length===n.length&&e.every((e,t)=>e.equals(n[t]))})(d,a)?[{tag:"rect",attrs:{x:a.x,y:a.y,width:a.w,height:a.h,transform:r}}]:o.map(e=>({tag:"path",attrs:{d:q(e),transform:r}})),l=i.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:c});return n.set(t.id,l),l}function W(e,t){const n=e.shapes.getUtil(t).getChildExportClipLocalPolygons(t);if(!n||!E(n))return null;const i=e.shapes.computeExportToPageTransform(t);return E(n.map(e=>e.map(e=>i.applyToPoint(e))))}function q(e){return e.map((e,t)=>`${0===t?"M":"L"} ${e.x} ${e.y}`).concat("Z").join(" ")}function G(e,t){const n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),s=Math.min(e.maxX,t.maxX),o=Math.min(e.maxY,t.maxY);return s<n||o<i?null:new zr(n,i,s-n,o-i)}function V(e){if("string"==typeof e)return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;");const t=(e=>{const t=[];for(const[n,i]of Object.entries(e))null!=i&&!1!==i&&t.push(`${n}="${Q("number"==typeof i?Z(i):String(i))}"`);return 0===t.length?"":` ${t.join(" ")}`})(e.attrs??{}),n=e.children?.map(V).join("")??"";return n?`<${e.tag}${t}>${n}</${e.tag}>`:`<${e.tag}${t}/>`}function j(e){let t=1/0,n=1/0,i=-1/0,s=-1/0;for(const o of e)t=Math.min(t,o.minX),n=Math.min(n,o.minY),i=Math.max(i,o.maxX),s=Math.max(s,o.maxY);return new zr(t,n,i-t,s-n)}function Q(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Z(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function J(e,t,n=Object.is){if(e===t)return!0;if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1)if(!n(e[i],t[i]))return!1;return!0}function ee(e,t){if(e===t)return!0;if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function te(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function ne(e,t){return J(e,t,te)}function ie(e,t){return J(e,t,ne)}function se(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y&&e.w===t.w&&e.h===t.h:e===t)}function oe(e,t){if(Object.is(e,t))return!0;if(typeof e!=typeof t)return!1;if(!e||!t||"object"!=typeof e||"object"!=typeof t)return!1;if(Array.isArray(e)||Array.isArray(t))return!(!Array.isArray(e)||!Array.isArray(t))&&J(e,t,oe);const n=e,i=t,s=Object.keys(n),o=Object.keys(i);return s.length===o.length&&s.every(e=>Object.prototype.hasOwnProperty.call(i,e)&&oe(n[e],i[e]))}function re(e){const t=Qr.get(e);if(!t)throw new Error("Editor record factory is not initialized");return t}function ae(e){const t=Number(e.split(":")[1]??0);return Number.isFinite(t)?t:0}function de(e,t,n){const i=new Set([e.id]);let s=e.parentId;for(;s.startsWith("shape:");){const e=s;if(i.has(e))return null;i.add(e);const n=t.get(e);if(!n)return null;s=n.parentId}return n.has(s)?s:null}function ce(e){const t=e.props.assetId;return"string"==typeof t&&t.startsWith("asset:")?t:null}function le(e,t){const n=[],i=new Set;for(const s of t)for(const t of he(s)){if(i.has(t))continue;const s=e.assets.get(t);s&&(i.add(t),n.push(me(s)))}return n}function he(e){const t=[],n=new Set,i=ce(e);return i&&(n.add(i),t.push(i)),pe(e.props,n,t),t}function pe(e,t,n){if(Se(e))t.has(e)||(t.add(e),n.push(e));else if(Array.isArray(e))for(const i of e)pe(i,t,n);else if(e&&"object"==typeof e)for(const i of Object.values(e))pe(i,t,n)}function ue(e,t){return ge(e,t)}function ge(e,t){if(Se(e))return t.get(e)??e;if(Array.isArray(e))return e.map(e=>ge(e,t));if(!e||"object"!=typeof e)return e;const n={};for(const[i,s]of Object.entries(e))n[i]=ge(s,t);return n}function fe(e){return me(e)}function me(e){if(Array.isArray(e))return e.map(me);if(!e||"object"!=typeof e)return e;const t={};for(const[n,i]of Object.entries(e))t[n]=me(i);return t}function Se(e){return"string"==typeof e&&e.startsWith("asset:")}function ye(e){return void 0!==e&&e<0?-1:1}function Ie(e,t){if(void 0===t)return e;const n=2*Math.PI;return e+Math.round((t-e)/n)*n}function we(e,t){const n=2*Math.PI,i=((e-t+Math.PI)%n+n)%n-Math.PI;return Math.abs(i)}function Pe(e,t,n={}){if(!(e=>[e.a,e.b,e.c,e.d,e.e,e.f].every(Number.isFinite))(e)||![t.x,t.y,t.w,t.h].every(Number.isFinite))return null;const i=Number.isFinite(n.epsilon)?Math.max(0,n.epsilon??0):1e-8,s=Math.hypot(e.a,e.b),o=Math.hypot(e.c,e.d),r=e.determinant(),a=({rotation:n,scaleX:i,scaleY:s})=>{const o=t.center,r=e.applyToPoint(o),a={x:r.x-o.x,y:r.y-o.y,rotation:n,scaleX:i,scaleY:s};return Object.values(a).every(Number.isFinite)?a:null},d=i*Math.max(1,s,o),c=s<=d,l=o<=d;if(c||l){if(c&&l)return a({rotation:n.preferredRotation??0,scaleX:0,scaleY:0});if(c){const t=o*ye(n.preferredScaleYSign);return a({rotation:Ie(Math.atan2(-e.c/t,e.d/t),n.preferredRotation),scaleX:0,scaleY:t})}const t=s*ye(n.preferredScaleXSign);return a({rotation:Ie(Math.atan2(e.b/t,e.a/t),n.preferredRotation),scaleX:t,scaleY:0})}if(Math.abs(e.a*e.c+e.b*e.d)/(s*o)>i)return null;if(Math.abs(r)<=i*s*o)return null;const h=Math.atan2(e.b,e.a),p=s,u=o*(r<0?-1:1),g=[{rotation:Ie(h,n.preferredRotation),scaleX:p,scaleY:u},{rotation:Ie(h+Math.PI,n.preferredRotation),scaleX:-p,scaleY:-u}],f=ye(n.preferredScaleXSign),m=ye(n.preferredScaleYSign),S=e=>{let t=0;return void 0!==n.preferredScaleXSign&&ye(e.scaleX)===f&&(t+=1),void 0!==n.preferredScaleYSign&&ye(e.scaleY)===m&&(t+=1),{signMatches:t,rotationDistance:void 0===n.preferredRotation?0:we(e.rotation,n.preferredRotation)}},y=S(g[0]),I=S(g[1]),w=I.signMatches>y.signMatches||I.signMatches===y.signMatches&&I.rotationDistance<y.rotationDistance?g[1]:g[0];return a({rotation:w.rotation,scaleX:w.scaleX,scaleY:w.scaleY})}function be(e,t,n){return n.compose(t.getLocalTransform(e))}function ve(e,t,n){return n.compose(t.getPositionedTransform(e))}function xe(e,t,n){return be(e,t,n)}function Ce(e,t,n){return be(e,t,n).applyToPoint(t.getLocalBounds(e).center)}function Me(e,t,n,i){const s=ve(e,n,i).tryInvert();if(s)return s.applyToPoint(t);const o=n.getLocalBounds(e).center,r=new Lr(e.x+o.x,e.y+o.y),a=i.tryInvert();if(!a)return r;const d=a.applyToPoint(t).sub(r).rot(-e.rotation);return r.add(new Lr(0===e.scaleX?0:d.x/e.scaleX,0===e.scaleY?0:d.y/e.scaleY))}function Te(e,t,n){const i=ve(e,t,n);return((e,t)=>t.getPositionedOutlineVertices(e))(e,t).map(e=>i.applyToPoint(e))}function Be(e,t,n){const i=t.getExportBounds(e);return zr.FromPoints([new Lr(i.minX,i.minY),new Lr(i.maxX,i.minY),new Lr(i.maxX,i.maxY),new Lr(i.minX,i.maxY)].map(e=>n.applyToPoint(e)))}function ke(e,t,n){const i=Te(e,t,n),s=((e,t,n)=>{const i=t.getLocalBounds(e),s=be(e,t,n);return[new Lr(i.minX,i.minY),new Lr(i.maxX,i.minY),new Lr(i.maxX,i.maxY),new Lr(i.minX,i.maxY)].map(e=>s.applyToPoint(e))})(e,t,n);return{bounds:zr.FromPoints(i),center:Ce(e,t,n),corners:s,outlineVertices:i}}function Ee(e){const t=(e=>{const t=new Set(e.selection.getIds());return 0===t.size?[]:e.state.currentPageShapeIds.get().filter(e=>t.has(e)).filter(n=>!((e,t,n)=>{const i=new Set([t]);let s=e.shapes.get(t);for(;s?.parentId.startsWith("shape:");){const t=s.parentId;if(n.has(t))return!0;if(i.has(t))return!1;i.add(t),s=e.shapes.get(t)}return!1})(e,n,t))})(e);if(0===t.length)return null;const n=((e,t)=>{const n=((e,t)=>{const n=e.layers.includeDescendants(t),i=new Set(n);for(let s=0;s<n.length;s+=1){const t=n[s];if(t)for(const s of e.bindings.getForShape(t)){const t=e.bindings.getUtil(s).getExportShapeIds?.(e,s);for(const s of t??[])for(const t of e.layers.includeDescendants([s]))i.has(t)||(i.add(t),n.push(t))}}return n})(e,t),i=new Set(n);return e.state.currentPageShapeIds.get().filter(e=>i.has(e))})(e,t),i=new Set(n),s=new Set;for(const c of n){const t=e.shapes.get(c);if(!(!t||t.parentId.startsWith("shape:")&&i.has(t.parentId)||Re(e,t,i))){s.add(t.id);for(const n of e.layers.getDescendantIds(t.id))s.add(n)}}const o=n.filter(e=>!s.has(e)),r=new Set(o),a=o.map(t=>e.shapes.get(t)).filter(e=>!!e).flatMap(t=>{const n=Re(e,t,r);return n?[n]:[]});if(0===a.length)return null;const d=t.filter(e=>r.has(e));return 0===d.length?null:{type:"land/clipboard",version:3,source:{app:"land"},rootShapeIds:d,records:{shapes:a,bindings:Ke(e,a,r),assets:le(e,a)},bounds:Ye(e,o)}}function Ae(e,t){const{payload:n}=t;if(!(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"land/clipboard"===t.type&&3===t.version&&!!t.records&&Array.isArray(t.rootShapeIds)&&Array.isArray(t.records.shapes)&&Array.isArray(t.records.bindings)&&Array.isArray(t.records.assets)})(n)||0===n.records.shapes.length)return[];const i=t.source??"user",s=e.pages.getCurrentId(),o=(e=>{const t=e.payload.bounds;return e.pagePoint?e.pagePoint.sub(new Lr(t.x+t.w/2,t.y+t.h/2)):e.offset??Jr})(t),r=new Map,a=new Map,d=[],c=new Set(n.records.shapes.map(e=>e.id)),l=new Set(n.records.shapes.filter(e=>!e.parentId.startsWith("shape:")||!c.has(e.parentId)).map(e=>e.id));S(e).atomic(()=>{const t=n.records.assets.map(t=>{const n=re(e).createAsset({type:t.type,props:fe(t.props),meta:fe(t.meta)});return r.set(t.id,n.id),n});t.length>0&&e.commands.createAssetsFromRecords(t,{source:i});const d=n.records.shapes.map(t=>{const n=ue(t.props,r),i=l.has(t.id),d=re(e).createShape({type:t.type,subType:t.subType,x:t.x+(i?o.x:0),y:t.y+(i?o.y:0),props:n,parentId:s,rotation:t.rotation,scaleX:t.scaleX,scaleY:t.scaleY,opacity:t.opacity,isHidden:t.isHidden,isLocked:t.isLocked,meta:fe(t.meta)});return a.set(t.id,d.id),{original:t,draft:d}}).map(({original:e,draft:t})=>({...t,parentId:Xe(e.parentId,a,s)}));d.length>0&&e.commands.createShapesFromRecords(d,{source:i});for(const s of n.records.bindings){const t=a.get(s.ownerId),n=s.endpoints.flatMap(e=>{const t=a.get(e.targetId);return t?[{slot:e.slot,targetId:t,props:fe(e.props),meta:fe(e.meta)}]:[]});t&&n.length===s.endpoints.length&&e.commands.createBinding({type:s.type,ownerId:t,endpoints:n,meta:fe(s.meta)},{source:i})}},i);for(const h of n.rootShapeIds){const e=a.get(h);e&&d.push(e)}return d.length>0&&e.commands.setSelectedShapeIds(d,{source:i}),d}function Re(e,t,n){if(!e.shapes.getUtil(t).canCopyToClipboard(t,{editor:e,copiedShapeIds:n}))return null;const i=me(t);if(t.parentId.startsWith("shape:")&&n.has(t.parentId))return i;const s=e.shapes.computeLocalBounds(t),o=Pe(e.shapes.computeLocalToPageTransform(t),s,{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});return o?{...i,parentId:e.layers.getPageId(t.id)??i.parentId,...o}:null}function Ke(e,t,n){const i=[],s=new Set;for(const o of t)for(const t of e.bindings.getForShape(o.id))s.has(t.id)||n.has(t.ownerId)&&!t.endpoints.some(({targetId:e})=>!n.has(e))&&(s.add(t.id),i.push(me(t)));return i}function Ye(e,t){const n=(e=>{if(0===e.length)return null;let t=1/0,n=1/0,i=-1/0,s=-1/0;for(const o of e)t=Math.min(t,o.minX),n=Math.min(n,o.minY),i=Math.max(i,o.maxX),s=Math.max(s,o.maxY);return new zr(t,n,i-t,s-n)})(t.map(t=>e.shapes.getPageBounds(t)).filter(e=>!!e))??new zr(0,0,0,0);return{x:n.x,y:n.y,w:n.w,h:n.h}}function Xe(e,t,n){return e.startsWith("shape:")?t.get(e)??n:n}function Fe(e){return Array.from(new Set([e.ownerId,...e.endpoints.map(({targetId:e})=>e)]))}function De(e,t,n){for(const i of t){const t=e.shapes.get(i);t?.parentId.startsWith("shape:")&&n.add(t.parentId)}}function Oe(e,t,n){const i=n?.pageId??e.pages.getCurrentId(),s=n?.source??"user",o=((e,t)=>{const n=new Set(t);return t.filter(t=>{const i=e.shapes.get(t);if(!i)return!1;let s=i.parentId;const o=new Set([t]);for(;s.startsWith("shape:");){const t=s;if(o.has(t))return!0;if(n.has(t))return!1;o.add(t);const i=e.shapes.get(t);if(!i)return!0;s=i.parentId}return!0})})(e,Array.from(new Set(t.filter(t=>e.layers.getPageId(t)===i&&!e.shapes.isHidden(t))))),r=e.session.get(),a=r.pageSelectedShapeIdsById[i]??[];e.state.shapeEditingSession.get()&&!e.editing.complete(s)||J(a,o)||(e.interaction.setBindingPreview(null),e.interaction.setSnapIndicators(null),e.session.update({pageSelectedShapeIdsById:{...r.pageSelectedShapeIdsById,[i]:o}},s))}function Le(e,t,n="system"){S(e).put([{...e.session.get(),...t}],n)}function ze(e){return e.map((e,t)=>({...e,index:String(t+1).padStart(4,"0")}))}function _e(e,t,n){return Math.abs(e-t)<=n*Math.max(1,Math.abs(e),Math.abs(t))}function $e(e,t,n=1e-8){if(!t.canReceiveChildren(e))return null;const i=t.getChildTransformPolicy(e),s=Math.abs(e.scaleX),o=Math.abs(e.scaleY);return Number.isFinite(s)&&Number.isFinite(o)&&("isometry"===i?_e(s,1,n)&&_e(o,1,n):s>n&&o>n&&_e(s,o,n))?null:{shapeId:e.id,shapeType:e.type,policy:i,scaleX:e.scaleX,scaleY:e.scaleY}}function Ne(e){return`Container shape ${e.shapeId} (${e.shapeType}) violates ${e.policy} child transform policy with scale (${e.scaleX}, ${e.scaleY})`}function Ue(e,t,n){const i=n.startsWith("shape:")?e.shapes.get(n):null,s=(i?e.shapes.computeLocalToPageTransform(i):Wr.Identity()).tryInvert();if(!s)return null;const o=e.shapes.computeLocalToPageTransform(t);return Pe(s.compose(o),e.shapes.computeLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY})}function He(e,t,n){const i=Array.from(new Set(t)).filter(t=>e.shapes.get(t));return 0===i.length?[]:(e.bindings.cleanupForDeletedShapes(i,n.source),S(e).remove(i,n.source),n.afterRemove?.(i),e.selection.remove(i,n.source),e.editing.removeShapeIds(i,n.source),i)}function We(e,t,n,i=new Set){const s=[...t].sort((t,n)=>qe(e,n)-qe(e,t));for(const o of s){if(i.has(o))continue;const t=e.shapes.get(o);if(!t)continue;const s=e.shapes.getUtil(t);if(!s.shouldResizeDescendants(t))continue;const r=Ge(e,t.id);if(0===r.length)continue;const a=r.flatMap(t=>{const n=e.shapes.getUtil(t),i=n.getPositionedTransform(t);return n.getPositionedOutlineVertices(t).map(e=>i.applyToPoint(e))});if(0===a.length)continue;const d=zr.FromPoints(a),c=s.getResizeToFitDescendantsProps(t,d);if(!c)continue;const l=s.validateProps(c),h={...t,props:l},p=Pe(s.getLocalTransform(t).compose(Wr.Translate(d.x,d.y)),s.getLocalBounds(h),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});if(!p)continue;const u=[...r.map(e=>({before:e,after:{...e,x:e.x-d.x,y:e.y-d.y}})),{before:t,after:{...t,...p,props:l}}].filter(({before:e,after:t})=>{return!((n=e).x===(i=t).x&&n.y===i.y&&n.rotation===i.rotation&&n.scaleX===i.scaleX&&n.scaleY===i.scaleY&&((e,t)=>{if(e===t)return!0;const n=Object.entries(e),i=Object.entries(t);return n.length===i.length&&n.every(([e,n])=>Object.is(n,t[e]))})(n.props,i.props));var n,i});0!==u.length&&(S(e).put(u.map(e=>e.after),n),e.bindings.handleShapeChanges(u,n))}}function qe(e,t){let n=0,i=e.shapes.get(t);const s=new Set;for(;i?.parentId.startsWith("shape:");){const t=i.parentId;if(s.has(t))break;s.add(t),n+=1,i=e.shapes.get(t)}return n}function Ge(e,t){return S(e).getAll().filter(p).filter(e=>e.parentId===t).sort((e,t)=>e.index.localeCompare(t.index))}function Ve(e,t,n){const i=new Set([t.id]);let s=t.parentId;for(;s.startsWith("shape:");){const t=e.shapes.get(s);if(!t||i.has(t.id))return;i.add(t.id),e.shapes.getUtil(t).shouldResizeDescendants(t)&&n.add(t.id),s=t.parentId}}function je(e,t){const n=new Set;for(const i of t){const t=e.shapes.get(i);t&&Ve(e,t,n)}return n}function Qe(e,t,n,i){const s=[],o=[...t].sort((t,n)=>e.layers.getDescendantIds(n).length-e.layers.getDescendantIds(t).length);for(let r=0;r<o.length;r+=1){const t=o[r];if(!t||n.has(t))continue;const a=e.shapes.get(t);if(!a)continue;const d=e.shapes.getUtil(a).getMinimumChildCount(a);if(d<=0)continue;const c=Ge(e,a.id).filter(e=>!n.has(e.id)),l=new Set(c.map(e=>e.id));if(new Set(c.map(t=>{const n=e.bindings.getShapeCompanionRootId(t.id);return l.has(n)?n:t.id})).size>=d)continue;const h=Ge(e,a.parentId).filter(e=>!n.has(e.id)).flatMap(e=>e.id===a.id?c.map(e=>e.id):[e.id]),p=new Map(h.map((t,n)=>[t,re(e).createShapeIndex(n+1)])),u=[];let g=!0;for(const n of c){if(!e.layers.canReceiveChild(a.parentId,n.id)){g=!1;break}const t=Ue(e,n,a.parentId);if(!t){g=!1;break}u.push({before:n,after:{...n,...t,parentId:a.parentId,index:p.get(n.id)??a.index}})}if(!g)continue;const f=new Set;Ve(e,a,f);for(const e of f)o.push(e);const m=new Set(u.map(e=>e.after.id)),y=h.flatMap(t=>{if(m.has(t))return[];const n=e.shapes.get(t),i=p.get(t);return n&&i&&n.index!==i?[{before:n,after:{...n,index:i}}]:[]}),I=[...u,...y];I.length>0&&(S(e).put(I.map(e=>e.after),i),e.bindings.handleShapeChanges(I,i));const w=e.selection.getIds();if(w.includes(a.id)){const t=Array.from(new Set(u.map(t=>{const n=e.bindings.getShapeCompanionRootId(t.after.id);return m.has(n)?n:t.after.id})));e.commands.setSelectedShapeIds(w.flatMap(e=>e===a.id?t:[e]),{source:i})}const P=He(e,[a.id],{source:i});for(const e of P)n.add(e),s.push(e)}return s}function Ze(e,t,n){const i=n?.source??"user";e.bindings.runWithSuppressedReactions(n?.suppressBindingIds??[],()=>((e,t,n)=>{S(e).atomic(()=>{const i=((e,t)=>{const n=[],i=[];for(const s of t){const t=e.shapes.get(s.id);if(!t)continue;const o=s.x??t.x,r=s.y??t.y,a=void 0===s.subType?t.subType:s.subType,d=s.rotation??t.rotation,c=s.scaleX??t.scaleX,l=s.scaleY??t.scaleY,h=void 0===s.opacity?t.opacity:nt(s.opacity,t.opacity),p=s.isHidden??t.isHidden,u=s.isLocked??t.isLocked,g=s.parentId??t.parentId,f=s.index??t.index,m=void 0===s.meta?t.meta:{...s.meta};if(!s.props&&void 0===s.meta&&a===t.subType&&o===t.x&&r===t.y&&d===t.rotation&&c===t.scaleX&&l===t.scaleY&&h===t.opacity&&p===t.isHidden&&u===t.isLocked&&g===t.parentId&&f===t.index)continue;const S=e.shapeUtils.get(t.type),y={...t,subType:a,x:o,y:r,rotation:d,scaleX:c,scaleY:l,opacity:h,isHidden:p,isLocked:u,parentId:g,index:f,props:s.props?S.validateProps({...t.props,...s.props}):t.props,meta:m};n.push(y),i.push({before:t,after:y})}return n.length>0&&Je(e,n),{records:n,changes:i}})(e,t);0!==i.records.length&&((e,t,n)=>{S(e).put(t.records,n),t.changes.some(({before:e,after:t})=>e.parentId!==t.parentId)&&et(e,n),e.bindings.handleShapeChanges(t.changes,n),((e,t,n)=>{const i=new Set,s=new Set;for(const r of t)Ve(e,r.before,i),Ve(e,r.after,i),r.before.parentId!==r.after.parentId&&r.before.parentId.startsWith("shape:")&&s.add(r.before.parentId),e.shapes.getUtil(r.after).shouldResizeDescendants(r.after)&&i.add(r.after.id);const o=new Set;Qe(e,s,o,n),We(e,i,n,o)})(e,t.changes,n)})(e,i,n)},n)})(e,t,i))}function Je(e,t){const n=new Set;for(const o of t){if(n.has(o.id))throw new Error(`Duplicate shape id ${o.id}`);n.add(o.id)}const i=new Map(S(e).getAll().filter(p).map(e=>[e.id,e]));for(const o of t)i.set(o.id,o);for(const o of i.values()){const t=$e(o,e.shapes.getUtil(o));if(t)throw new Error(Ne(t))}const s=new Map(t.map(e=>[e.id,e]));for(const o of i.values())o.parentId.startsWith("shape:")&&n.has(o.parentId)&&s.set(o.id,o);for(const o of s.values()){const t=new Set([o.id]);let n=o;for(;n.parentId.startsWith("shape:");){const s=n.parentId;if(t.has(s))throw new Error(`Shape parent cycle includes ${o.id}`);t.add(s);const r=i.get(s);if(!r)throw new Error(`Missing parent ${s} for shape ${n.id}`);if(!e.shapes.getUtil(r).canReceiveChild(r,n))throw new Error(`Shape ${s} cannot receive shape ${n.id}`);n=r}if(!e.pages.get(n.parentId))throw new Error(`Missing page parent ${n.parentId} for shape ${n.id}`)}}function et(e,t){const n=e.session.get();let i=!1;const s={};for(const[o,r]of Object.entries(n.pageSelectedShapeIdsById)){const t=o,n=r??[],a=Array.from(new Set(n)).filter(n=>tt(e,n)===t&&!e.shapes.isHidden(n)),d=new Set(a),c=a.filter(t=>{let n=e.shapes.get(t);const i=new Set([t]);for(;n?.parentId.startsWith("shape:");){const t=n.parentId;if(i.has(t))return!0;if(d.has(t))return!1;i.add(t),n=e.shapes.get(t)}return!0});s[t]=c,c.length!==n.length&&(i=!0)}i&&e.session.update({pageSelectedShapeIdsById:s},t)}function tt(e,t){let n=e.shapes.get(t);const i=new Set;for(;n?.parentId.startsWith("shape:");){const t=n.parentId;if(i.has(t))return null;i.add(t),n=e.shapes.get(t)}return n&&e.pages.get(n.parentId)?n.parentId:null}function nt(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function it(e,t,n){const i=((e,t)=>{const n=Array.from(new Set(t.ids)).map(t=>e.shapes.get(t)).filter(e=>!!e&&e.parentId!==t.parentId);if(0===n.length)return[];const i=Ge(e,t.parentId).reduce((e,t)=>{const n=Number.parseInt(t.index,10);return Number.isFinite(n)?Math.max(e,n):e},0),s=t.parentId.startsWith("shape:")?e.shapes.get(t.parentId):null,o=new Map;for(const r of n){if(!e.layers.canReceiveChild(t.parentId,r.id))return null;const n=Ue(e,r,t.parentId);if(!n)return null;o.set(r.id,n)}return n.map((n,r)=>{const a=s?e.shapes.getUtil(s).getChildPlacementMeta(s,n,{editor:e,reason:"reparent"}):n.meta;return{id:n.id,parentId:t.parentId,index:re(e).createShapeIndex(i+r+1),...o.get(n.id),meta:a===n.meta?void 0:a}})})(e,t);return!!i&&(0===i.length||Ze(e,i,n),!0)}function st(e){const t=t=>(e.assertDocumentWriteAllowed(),t()),n=function(e,t){return{createBinding(n,i){const s=i?.source??"user",o=re(e).createBinding(n);if(!e.bindings.canBind(o))throw new Error(`Invalid binding endpoints for ${o.type} binding`);const r=new Set;return De(e,Fe(o),r),S(e).atomic(()=>{const n=e.bindings.getConflicting(o).map(e=>e.id);n.length>0&&e.bindings.cleanup(n,s),S(e).put([o],s),e.bindings.syncCreated(o,s),De(e,Fe(o),r),t(r,new Set,s)},s),o},updateBinding(n,i){const s=i?.source??"user",o=e.bindings.get(n.id);if(!o)return null;const r=e.bindings.getUtil(o);if(0===n.endpoints?.length)return S(e).atomic(()=>{e.bindings.cleanup([o.id],s),S(e).remove([o.id],s)},s),null;const a=new Set,d=n.endpoints?n.endpoints.map(e=>{if(a.has(e.slot))throw new Error(`Duplicate binding endpoint slot: ${e.slot}`);a.add(e.slot);const t=o.endpoints.find(({slot:t})=>t===e.slot);return{slot:e.slot,targetId:e.targetId,props:r.validateEndpointProps(e.slot,{...r.getDefaultEndpointProps(e.slot),...t?.props,...e.props}),meta:e.meta??t?.meta??{}}}).sort((e,t)=>e.slot.localeCompare(t.slot)):o.endpoints,c={...o,ownerId:n.ownerId??o.ownerId,endpoints:d,meta:n.meta??o.meta};if(!e.bindings.canBind(c))throw new Error(`Invalid binding endpoints for ${c.type} binding`);const l=new Set;return De(e,[...Fe(o),...Fe(c)],l),S(e).atomic(()=>{const n=e.bindings.getConflicting(c).map(e=>e.id);n.length>0&&e.bindings.cleanup(n,s),S(e).put([c],s),e.bindings.syncUpdated(o,c,s),De(e,[...Fe(o),...Fe(c)],l),t(l,new Set,s)},s),c},setBindingEndpoint(t,n){const i=e.bindings.get(t.bindingId);if(!i)return null;const s=i.endpoints.filter(({slot:e})=>e!==t.endpoint.slot).map(e=>({...e,props:e.props}));return s.push({slot:t.endpoint.slot,targetId:t.endpoint.targetId,props:t.endpoint.props??{},meta:t.endpoint.meta??{}}),this.updateBinding({id:i.id,endpoints:s},n)},clearBindingEndpoint(t,n){const i=e.bindings.get(t.bindingId);return i?this.updateBinding({id:i.id,endpoints:i.endpoints.filter(({slot:e})=>e!==t.slot).map(e=>({...e,props:e.props}))},n):null},deleteBinding(t,n){const i=n?.source??"user",s=e.bindings.get(t);return!!s&&(S(e).atomic(()=>{e.bindings.cleanup([s.id],i),S(e).remove([s.id],i)},i),!0)}}}(e,(t,n,i)=>{Qe(e,t,n,i)});return{createPage:(n,i)=>t(()=>function(e,t,n){const i=n?.source??"user",s=re(e).createPage(t);let o=s;return S(e).atomic(()=>{const t=ze([...e.pages.getAll(),s]);o=t.find(e=>e.id===s.id)??s,S(e).put(t,i),((e,t,n="system")=>{const i=e.state.session.get(),s=i.pageCameraById[t]??{...Yr},o=i.pageSelectedShapeIdsById[t]??[];Le(e,{pageCameraById:{...i.pageCameraById,[t]:s},pageSelectedShapeIdsById:{...i.pageSelectedShapeIdsById,[t]:o}},n)})(e,o.id,i)},i),o}(e,n,i)),deletePage:(n,i)=>t(()=>function(e,t,n){const i=n?.source??"user",s=e.pages.getAll();if(s.length<=1)return!1;const o=s.findIndex(e=>e.id===t);if(o<0)return!1;const r=e.shapes.getForPage(t).map(e=>e.id),a=ze(s.filter(e=>e.id!==t)),d=s[o+1]?.id??s[o-1]?.id??s[0]?.id,c=e.pages.getCurrentId()===t&&d?d:e.pages.getCurrentId();return S(e).atomic(()=>{r.length>0&&e.commands.deleteShapes(r,n),S(e).remove([t],i),((e,t,n,i="system")=>{const s=e.state.session.get(),o={...s.pageCameraById},r={...s.pageSelectedShapeIdsById};delete o[t],delete r[t],Le(e,{currentPageId:n,pageCameraById:o,pageSelectedShapeIdsById:r},i)})(e,t,c,i),S(e).put(a,i)},i),!0}(e,n,i)),renamePage(n,i){t(()=>((e,t,n)=>{const i=n?.source??"user",s=e.pages.get(t.id);if(!s)return;const o=t.name.trim();o&&o!==s.name&&S(e).atomic(()=>{S(e).put([{...s,name:o}],i)},i)})(e,n,i))},updateDocumentMeta:(n,i)=>t(()=>((e,t,n)=>{const i=n?.source??"user",{document:s}=e,o=s.getMetadata()??a(),r={...o,meta:{...o.meta,...t.patch}};return S(e).atomic(()=>{S(e).put([r],i)},i),r})(e,n,i)),updatePageMeta:(n,i)=>t(()=>((e,t,n)=>{const i=n?.source??"user",s=e.pages.get(t.id);if(!s)return null;const o={...s,meta:{...s.meta,...t.patch}};return S(e).atomic(()=>{S(e).put([o],i)},i),o})(e,n,i)),movePage(n,i){t(()=>((e,t,n)=>{const i=n?.source??"user",s=e.pages.getAll(),o=s.findIndex(e=>e.id===t.id);if(o<0)return;const r=Math.max(0,Math.min(t.toIndex,s.length-1));if(o===r)return;const a=[...s],[d]=a.splice(o,1);d&&(a.splice(r,0,d),S(e).atomic(()=>{S(e).put(ze(a),i)},i))})(e,n,i))},createShapes:(n,i)=>t(()=>function(e,t,n){const i=[],s=n?.source??"user";return S(e).atomic(()=>{const o=t.map(t=>re(e).createShape(t)),r=new Map(o.map(e=>[e.id,e])),a=o.map(t=>{if(!t.parentId.startsWith("shape:"))return t;const n=r.get(t.parentId)??e.shapes.get(t.parentId);if(!n)return t;const i=e.shapes.getUtil(n).getChildPlacementMeta(n,t,{editor:e,reason:"create"});return i===t.meta?t:{...t,meta:i}});if(Je(e,a),S(e).put(a,s),"user"===s&&!1!==n?.autoReparent){const i=new Map;for(let n=0;n<a.length;n+=1){const s=a[n],o=t[n];if(!s||!o||o.parentId)continue;const r=e.layers.getContainingParentIdForShape(s);r&&r!==s.parentId&&i.set(s.id,r)}((e,t)=>{const n=new Set;for(const i of e.keys()){const s=[],o=new Map;let r=i;for(;r;){const i=o.get(r);if(void 0!==i){for(const e of s.slice(i))n.add(e);break}o.set(r,s.length),s.push(r);const a=e.get(r);r=a?.startsWith("shape:")&&t.has(a)?a:null}}for(const i of n)e.delete(i)})(i,new Set(a.map(e=>e.id)));const s=new Map;for(const e of a){const t=i.get(e.id);if(!t)continue;const n=s.get(t)??[];n.push(e.id),s.set(t,n)}for(const[t,o]of s)it(e,{ids:o,parentId:t},n)}const d=je(e,a.map(e=>e.id)),c=new Set;if(!n?.deferMinimumChildRepair){const t=new Set;for(const n of a){const i=e.shapes.get(n.id);i&&e.shapes.getUtil(i).getMinimumChildCount(i)>0&&t.add(i.id)}Qe(e,t,c,s)}We(e,d,s,c),i.push(...a.map(t=>e.shapes.get(t.id)).filter(e=>!!e))},s),i}(e,n,i)),createShapesFromRecords:(n,i)=>t(()=>((e,t,n)=>{const i=n?.source??"user";if(0===t.length)return[];for(const s of t)if(e.shapes.get(s.id))throw new Error(`Shape ${s.id} already exists`);return Je(e,t),S(e).atomic(()=>{S(e).put(t,i),et(e,i);const n=je(e,t.map(e=>e.id));for(const i of t){const t=e.shapes.get(i.id);t&&e.shapes.getUtil(t).getMinimumChildCount(t)>0&&n.add(t.id)}const s=new Set;Qe(e,n,s,i),We(e,n,i,s)},i),t.map(t=>e.shapes.get(t.id)).filter(e=>!!e)})(e,n,i)),updateShapes(n,i){t(()=>Ze(e,n,i))},reparentShapes:(n,i)=>t(()=>it(e,n,i)),deleteShapes(n,i){t(()=>function(e,t,n){const i=n?.source??"user",s=e.layers.includeDescendants(t),o=je(e,s),r=new Set(s),a=((e,t)=>{if(0===t.length)return[];const n=new Set(t),i=new Set,s=new Set;for(const o of S(e).getAll().filter(p)){const e=ce(o);e&&(n.has(o.id)?i.add(e):s.add(e))}return e.assets.getAll().map(e=>e.id).filter(e=>i.has(e)&&!s.has(e))})(e,s);e.editing.prepareForShapeRemoval(s,i),S(e).atomic(()=>{He(e,s,{source:i,afterRemove:()=>{a.length>0&&S(e).remove(a,i),Qe(e,o,r,i),We(e,o,i,r)}})},i)}(e,n,i))},createAsset:(n,i)=>t(()=>((e,t,n)=>{const i=n?.source??"user",s=re(e).createAsset(t);return S(e).atomic(()=>{S(e).put([s],i)},i),s})(e,n,i)),createAssetsFromRecords:(n,i)=>t(()=>((e,t,n)=>{const i=n?.source??"user";return 0===t.length?[]:(S(e).atomic(()=>{S(e).put(t,i)},i),t)})(e,n,i)),updateAsset:(n,i)=>t(()=>((e,t,n)=>{const i=n?.source??"user",s=e.assets.get(t.id);if(!s)return null;const o={...s,props:t.props?{...s.props,...t.props}:s.props,meta:t.meta??s.meta};return S(e).atomic(()=>{S(e).put([o],i)},i),o})(e,n,i)),deleteAsset:(n,i)=>t(()=>((e,t,n)=>{const i=n?.source??"user";return!!e.assets.get(t)&&(S(e).atomic(()=>{S(e).remove([t],i)},i),!0)})(e,n,i)),createBinding:(e,i)=>t(()=>n.createBinding(e,i)),updateBinding:(e,i)=>t(()=>n.updateBinding(e,i)),setBindingEndpoint:(e,i)=>t(()=>n.setBindingEndpoint(e,i)),clearBindingEndpoint:(e,i)=>t(()=>n.clearBindingEndpoint(e,i)),deleteBinding:(e,i)=>t(()=>n.deleteBinding(e,i)),setCurrentPageId(t,n){((e,t,n)=>{const i=n?.source??"system";if(!e.pages.get(t))return;t!==e.pages.getCurrentId()&&(e.viewport.stopCameraAnimation(),e.viewport.setLock(null),e.interaction.cancel("page_switch"),e.editing.complete(i));const s=e.state.session.get();Le(e,{currentPageId:t,pageCameraById:{...s.pageCameraById,[t]:s.pageCameraById[t]??{...Yr}},pageSelectedShapeIdsById:{...s.pageSelectedShapeIdsById,[t]:s.pageSelectedShapeIdsById[t]??[]}},i)})(e,t,n)},setCamera(t,n){((e,t,n)=>{e.viewport.setCamera(t.camera,{pageId:t.pageId,source:n?.source??"system"})})(e,t,n)},setSelectedShapeIds(t,n){((e,t,n)=>{Oe(e,t,{source:n?.source??"user"})})(e,t,n)},setActiveTool(t,n){((e,t,n)=>{const i=n?.source??"system";e.tools.syncActiveTool(t),e.editing.complete(i),Le(e,{activeToolId:t},i)})(e,t,n)},setToolLocked(t,n){((e,t,n)=>{const i=n?.source??"system";e.tools.syncLockedState(t),Le(e,{isToolLocked:t},i)})(e,t,n)}}}function ot(e,t,n){const i=e.bindings.getShapeCompanionMemberIds(t),s=Array.from(new Set(i.filter(t=>{const i=e.shapes.get(t);return!!i&&i[n.flag]!==n.value})));if(0===s.length)return[];e.interaction.cancelForCommand();const o=s.map("isHidden"===n.flag?e=>({id:e,isHidden:n.value}):e=>({id:e,isLocked:n.value}));if(e.commands.updateShapes(o,{source:n.source}),n.value){const t=e.layers.includeDescendants(s);e.selection.remove(t,n.source),e.editing.removeShapeIds(t,n.source)}return s}function rt(e,t){return{originScreenPoint:t.clone(),originCamera:e.state.camera.get()}}function at(e,t,n){const i=n.sub(t.originScreenPoint),s=t.originCamera.z;e.viewport.setCamera({x:t.originCamera.x-i.x/s,y:t.originCamera.y-i.y/s},{source:"user"})}function dt(e,t){return e?t?e.propagation===t.propagation&&e.clickSequence===t.clickSequence?e:{propagation:"stop"===e.propagation||"stop"===t.propagation?"stop":void 0,clickSequence:"break"===e.clickSequence||"break"===t.clickSequence?"break":void 0}:e:t||void 0}function ct(e){return{timestamp:e.timestamp,screenPoint:e.screenPoint.clone(),pointerId:e.pointerId,button:e.button,pointerType:e.pointerType}}function lt(e,t){return e.pointerId===t.pointerId&&e.button===t.button&&e.pointerType===t.pointerType}function ht(e){return{claimed:"stop"===e?.propagation}}function pt(){return Lr.Zero()}function ut(e,t,n){if(n<=0)return pt();const i=t.x-e.x,s=t.y-e.y;return 0===i&&0===s?pt():new Lr(i/n,s/n)}function gt(e,t){return e.shiftKey===t.shiftKey&&e.altKey===t.altKey&&e.ctrlKey===t.ctrlKey&&e.metaKey===t.metaKey&&e.accelKey===t.accelKey}function ft(e,t){return e.canUndo===t.canUndo&&e.canRedo===t.canRedo}function mt(e){return{added:[...e.added],updated:e.updated.filter(({before:e,after:t})=>!St(e,t)),removed:[...e.removed]}}function St(e,t){if(Object.is(e,t))return!0;if(typeof e!=typeof t||null===e||null===t)return!1;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>St(e,t[n]));if("object"!=typeof e||"object"!=typeof t)return!1;const n=e,i=t,s=Object.keys(n),o=Object.keys(i);return s.length===o.length&&s.every(e=>Object.prototype.hasOwnProperty.call(i,e)&&St(n[e],i[e]))}function yt(e){return JSON.parse(JSON.stringify(e))}function It(e){return JSON.parse(JSON.stringify(e))}function wt(e,t,n){const i=e.get(t);i?i.push(n):e.set(t,[n])}function Pt(e,t,n){const i=e.get(t);if(!i)return!1;const s=i.indexOf(n);if(s<0)return!1;if(1===i.length)return e.delete(t),!0;const o=i.slice();return o.splice(s,1),e.set(t,o),!0}function bt(e,t){return e.ownerId===t.ownerId?e.id.localeCompare(t.id):e.ownerId.localeCompare(t.ownerId)}function vt(e,t,n){return bt(t,n)}function xt(e,t,n,i,s){const o=e.get(t);if(!o)return e.set(t,[n.id]),!0;if(o.includes(n.id))return!1;const r=o.slice();return r.splice(((e,t,n,i)=>{for(let s=0;s<e.length;s+=1){const n=i(e[s]);if(n&&vt(0,t,n)<0)return s}return e.length})(o,n,0,s),0,n.id),e.set(t,r),!0}function Ct(e){return g(e.before)&&g(e.after)}function Mt(e,t){Pt(e.bindingIdsByOwnerShape,t.ownerId,t.id),Pt(e.relatedBindingIdsByShape,t.ownerId,t.id);for(const n of Bt(t))Pt(e.bindingIdsByTargetShape,n,t.id),n!==t.ownerId&&Pt(e.relatedBindingIdsByShape,n,t.id)}function Tt(e,t){const n=t=>e.bindingById.get(t);xt(e.bindingIdsByOwnerShape,t.ownerId,t,0,n),xt(e.relatedBindingIdsByShape,t.ownerId,t,0,n);for(const i of Bt(t))xt(e.bindingIdsByTargetShape,i,t,0,n),i!==t.ownerId&&xt(e.relatedBindingIdsByShape,i,t,0,n)}function Bt(e){return Array.from(new Set(e.endpoints.map(({targetId:e})=>e)))}function kt(e,t){if(e.ownerId!==t.ownerId)return!0;const n=Bt(e),i=Bt(t);return n.length!==i.length||n.some((e,t)=>e!==i[t])}function Et(){return{changesByShape:new Map,cacheByShape:new Map}}function At(e,t,n){for(const i of la)for(const s of Rt(i,t)){const o=e.relations[i];let r=o.changesByShape.get(s);r||(r=new Map,o.changesByShape.set(s,r)),r.set(t.id,n)}}function Rt(e,t){switch(e){case"owner":return[t.ownerId];case"target":return Array.from(new Set(t.endpoints.map(({targetId:e})=>e)));case"related":return Array.from(new Set([t.ownerId,...t.endpoints.map(({targetId:e})=>e)]))}}function Kt(e,t){return e===t||(e&&t?e.a===t.a&&e.b===t.b&&e.c===t.c&&e.d===t.d&&e.e===t.e&&e.f===t.f:e===t)}function Yt(e,t){return e===t||(e&&t?se(e.bounds,t.bounds)&&te(e.center,t.center)&&ne(e.corners,t.corners)&&ne(e.outlineVertices,t.outlineVertices):e===t)}function Xt(e){return e?e.clone():e}function Ft(e){return e?.map(e=>e.clone())}function Dt(e){return e?new Wr(e.a,e.b,e.c,e.d,e.e,e.f):void 0}function Ot(e,t,n){const i=[],s=new Set;let o=t;for(;o;){if(s.has(o.id))return;if(s.add(o.id),i.push(o),o.parentId.startsWith("page:")){if(!e.pages.get(o.parentId))return;break}if(o=n(o.parentId),!o)return}let r=Wr.Identity();for(let a=i.length-1;a>=0;a-=1){const t=i[a];t&&(r=be(t,e.shapes.getUtil(t),r))}return r}function Lt(e,t,n){if(t.startsWith("page:"))return e.pages.get(t)?Wr.Identity():void 0;const i=n(t);return i?Ot(e,i,n):void 0}function zt(e,t,n){const i=[],s=new Set;let o=t.parentId;for(;o.startsWith("shape:");){const t=o;if(s.has(t))break;s.add(t);const r=n(t);if(!r)break;const a=e.shapes.getUtil(r).getChildClipLocalPolygons(r);a&&E(a)&&i.push(r),o=r.parentId}return i.reverse()}function _t(e,t){return zr.FromPoints([new Lr(e.minX,e.minY),new Lr(e.maxX,e.minY),new Lr(e.maxX,e.maxY),new Lr(e.minX,e.maxY)].map(e=>t.applyToPoint(e)))}function $t(e,t){const n=Math.max(e.minX,t.minX),i=Math.max(e.minY,t.minY),s=Math.min(e.maxX,t.maxX),o=Math.min(e.maxY,t.maxY);return s<n||o<i?null:new zr(n,i,s-n,o-i)}function Nt(e,t,n){const i=e.get(t);i?i.push(n):e.set(t,[n])}function Ut(e,t,n){const i=e.get(t);if(!i)return!1;const s=i.indexOf(n);if(s<0)return!1;if(1===i.length)return e.delete(t),!0;const o=i.slice();return o.splice(s,1),e.set(t,o),!0}function Ht(e,t,n,i){const s=e.get(t);if(!s)return void e.set(t,[n.id]);if(s.includes(n.id))return;let o=s.length;for(let a=0;a<s.length;a+=1){const e=i(s[a]);if(void 0!==e&&e.localeCompare(n.index)>0){o=a;break}}const r=s.slice();r.splice(o,0,n.id),e.set(t,r)}function Wt(e){return p(e.before)&&p(e.after)}function qt(e,t){return e.length===t.length&&e.every((e,n)=>{const i=t[n];return!!i&&e.id===i.id&&e.parentId===i.parentId&&e.type===i.type&&e.subType===i.subType})}function Gt(e,t,n,i){const s=t.sub(e),o=i.sub(n),r=s.x*o.y-s.y*o.x;if(Math.abs(r)<1e-8)return null;const a=n.sub(e),d=(a.x*o.y-a.y*o.x)/r,c=(a.x*s.y-a.y*s.x)/r;return d>=0&&d<=1&&c>=0&&c<=1?d:null}function Vt(e,t,n){if(n.containsPoint(e)||n.containsPoint(t))return!0;const i=[new Lr(n.minX,n.minY),new Lr(n.maxX,n.minY),new Lr(n.maxX,n.maxY),new Lr(n.minX,n.maxY)];for(let s=0;s<i.length;s+=1){const n=i[s],o=i[(s+1)%i.length];if(n&&o&&null!==Gt(e,t,n,o))return!0}return!1}function jt(e,t){return zr.FromPoints([new Lr(e.minX,e.minY),new Lr(e.maxX,e.minY),new Lr(e.maxX,e.maxY),new Lr(e.minX,e.maxY)].map(e=>t.applyToPoint(e)))}function Qt(e,t){const n={editor:e},i=[e.shapes.getUtil(t).getPointHitTestBounds(t,n)];for(const o of e.shapeHitTestDecorations.get(t.subType))i.push(o.getPointHitTestBounds(t,n));if(1===i.length)return i[0];const s=[];for(const o of i)s.push(new Lr(o.minX,o.minY),new Lr(o.maxX,o.maxY));return zr.FromPoints(s)}function Zt(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Jt(e,t){return"string"==typeof e?e:t}function en(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function tn(e,t){return"boolean"==typeof e?e:t}function nn(e){return Zt(e)?e:{}}function sn(e){return Zt(e)?{x:en(e.x,Yr.x),y:en(e.y,Yr.y),z:Math.min(8,Math.max(.1,en(e.z,Yr.z)))}:null}function on(e){return Array.from(new Set((e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[])(e).filter(e=>e.startsWith("shape:"))))}function rn(e,t){if(!Zt(e))throw new ma(`Invalid ${t} snapshot: expected object`);const n=e.schemaVersion,i=en(n,NaN),s="document"===t?4:1;if(i!==s)throw new ma(`Unsupported ${t} snapshot schema version: expected ${s}, received ${String(n)}`);if(!Array.isArray(e.records))throw new ma(`Invalid ${t} snapshot: records must be an array`);return{schemaVersion:i,records:e.records}}function an(e,t,n){const i=e.find(h)??a(),s=e.filter(e=>"page"===e.typeName),o=e.filter(e=>"shape"===e.typeName),r=e.filter(g),c=e.filter(f),l=(s.length>0?[...s].sort((e,t)=>e.index.localeCompare(t.index)):[d()]).map((e,t)=>({...e,index:String(t+1).padStart(4,"0")})),p=l[0]?.id??"page:default",u=new Set(l.map(e=>e.id)),m=[...o].sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id)),S=new Map(m.map(e=>[e.id,e])),I=new Map,w=new Set,P=m.map((e,n)=>{const i=(e=>{const n=I.get(e.id);if(n)return n;const i=[{stage:"enter",shape:e}];for(;i.length>0;){const e=i[i.length-1];if("waiting-for-parent"===e.stage){I.set(e.shape.id,e.parent.id),w.delete(e.shape.id),i.pop();continue}const n=e.shape;if(I.has(n.id)){i.pop();continue}if(w.add(n.id),n.parentId.startsWith("page:")){I.set(n.id,u.has(n.parentId)?n.parentId:p),w.delete(n.id),i.pop();continue}const s=S.get(n.parentId);s&&!w.has(s.id)&&t.get(s.type).canReceiveChild(s,n)?(i[i.length-1]={stage:"waiting-for-parent",shape:n,parent:s},I.has(s.id)||i.push({stage:"enter",shape:s})):(I.set(n.id,p),w.delete(n.id),i.pop())}return I.get(e.id)??p})(e);return{...e,parentId:i,index:e.index||String(n+1).padStart(6,"0")}});for(const a of P){const e=$e(a,t.get(a.type));if(e)throw new ma(Ne(e))}const b=((e,t,n,i)=>{const s=new Map(e.map(e=>[e.id,e])),o=t.filter(e=>{const t=s.get(e.ownerId),n=e.endpoints.map(e=>{const t=s.get(e.targetId);return t?{endpoint:e,targetShape:t}:null});if(!t||n.some(e=>!e))return!1;const o=i.get(e.type);return!!o.getShapeCompanionRootId&&(o.canUseShapeCompanion?.(e,{ownerShape:t,endpoints:n.filter(e=>!!e)})??!1)});let r=!0;for(;r;){r=!1;for(const e of[...s.values()]){const t=n.get(e.type),a=t.getMinimumChildCount(e);if(a<=0)continue;const d=[...s.values()].filter(t=>t.parentId===e.id).sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id)),c=new Set(d.map(e=>e.id));if(new Set(d.map(e=>{const t=y(e.id,o,e=>i.get(e.type));return c.has(t)?t:e.id})).size>=a)continue;if(0===d.length){s.delete(e.id),r=!0;break}const l=[...s.values()].filter(t=>t.parentId===e.parentId).sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id)).flatMap(t=>t.id===e.id?d.map(e=>e.id):[t.id]),h=new Map(l.map((e,t)=>[e,String(t+1).padStart(6,"0")])),p=t.getLocalTransform(e),u=[];for(const i of d){if(e.parentId.startsWith("shape:")&&!dn(s,n,e.parentId,i)){u.length=0;break}const t=n.get(i.type),o=Pe(p.compose(t.getLocalTransform(i)),t.getLocalBounds(i),{preferredRotation:i.rotation,preferredScaleXSign:i.scaleX,preferredScaleYSign:i.scaleY});if(!o){u.length=0;break}u.push({...i,...o,parentId:e.parentId,index:h.get(i.id)??e.index})}if(u.length===d.length){for(const e of u)s.set(e.id,e);for(const e of l){const t=s.get(e),n=h.get(e);t&&n&&t.index!==n&&s.set(t.id,{...t,index:n})}s.delete(e.id),r=!0;break}}}return e.flatMap(e=>{const t=s.get(e.id);return t?[t]:[]})})(P,r,t,n),v=new Set(b.map(e=>e.id)),x=r.filter(e=>v.has(e.ownerId)&&e.endpoints.every(({targetId:e})=>v.has(e)));return[i,...l,...c,...b,...x]}function dn(e,t,n,i){const s=e.get(n);return!!s&&t.get(s.type).canReceiveChild(s,i)}function cn(e,t,n){const i=n?.source??"system",s=function(e){const t=rn(e,"session").records[0];if(!Zt(t))return{schemaVersion:1,records:[c()]};const n=c(),i="string"==typeof t.currentPageId&&t.currentPageId.startsWith("page:")?t.currentPageId:n.currentPageId,s=(e=>{if(!Zt(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,sn(t)]).filter(e=>null!==e[1]);return Object.fromEntries(t)})(t.pageCameraById),o=(e=>{if(!Zt(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,on(t)]);return Object.fromEntries(t)})(t.pageSelectedShapeIdsById);return{schemaVersion:1,records:[{...n,id:n.id,typeName:"session",scope:"session",currentPageId:i,activeToolId:Jt(t.activeToolId,n.activeToolId),isToolLocked:"boolean"==typeof t.isToolLocked?t.isToolLocked:n.isToolLocked,editingShapeId:null,shapeEditingSession:null,pageCameraById:Object.keys(s).length>0?s:n.pageCameraById,pageSelectedShapeIdsById:Object.keys(o).length>0?o:n.pageSelectedShapeIdsById,meta:nn(t.meta)}]}}(t).records[0]??c(),o=S(e).getAll().filter(m);e.interaction.cancel("restore"),e.editing.end({runEditEnd:!1,source:i}),e.editing.cancelOperation(),hn(e,[...o,s],i),pn(e),((e,t)=>{const{activeToolId:n,isToolLocked:i}=e.state.session.get();e.tools.hasTool(n)?e.tools.syncActiveTool(n,"restore"):(e.tools.syncActiveTool("select","restore"),Le(e,{activeToolId:"select"},t)),e.tools.syncLockedState(i)})(e,i)}function ln(e){pn(e),re(e).syncCounters()}function hn(e,t,i){const s=S(e);s.applyDiff(((e,t)=>{const i=n(e),s=n(t),o={added:[],updated:[],removed:[]};for(const[n,r]of i){const e=s.get(n);e?e!==r&&o.updated.push({before:r,after:e}):o.removed.push(r)}for(const[n,r]of s)i.has(n)||o.added.push(r);return o})(s.getAll(),t),i)}function pn(e){const t=S(e),n=t.getAll(),i=n.filter(l).sort((e,t)=>e.index.localeCompare(t.index)),s=i[0]?.id??"page:default",o=new Set(i.map(e=>e.id)),r=n.filter(p),a=new Set(r.map(e=>e.id)),d=new Map(r.map(e=>[e.id,e])),h=new Map;for(const c of r)h.set(c.id,de(c,d,o)??s);const g=n.find(e=>e.id===Kr),f=u(g)?g:c(s),m={...f,currentPageId:o.has(f.currentPageId)?f.currentPageId:s,pageCameraById:un(f.pageCameraById,o),pageSelectedShapeIdsById:gn(f.pageSelectedShapeIdsById,o,a,h)};t.put([m],"system")}function un(e,t){const n={};for(const i of t){const t=e[i]??Yr;n[i]={x:Number.isFinite(t.x)?t.x:Yr.x,y:Number.isFinite(t.y)?t.y:Yr.y,z:Math.min(8,Math.max(.1,Number.isFinite(t.z)?t.z:Yr.z))}}return n}function gn(e,t,n,i){const s={};for(const o of t)s[o]=Array.from(new Set((e[o]??[]).filter(e=>n.has(e)&&i.get(e)===o)));return s}function fn(e,t){const n=Pe(e.shapes.computeLocalToPageTransform(t),e.shapes.computeLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});return n?{...t,...n}:null}function mn(e,t,n,i){const s=e.shapes.getUtil(t),o={...n,x:i.x??n.x,y:i.y??n.y,rotation:i.rotation??n.rotation,scaleX:i.scaleX??n.scaleX,scaleY:i.scaleY??n.scaleY,props:i.props?s.validateProps({...n.props,...i.props}):n.props},r=t.parentId.startsWith("shape:")?e.shapes.get(t.parentId):null,a=(r?e.shapes.computeLocalToPageTransform(r):Wr.Identity()).tryInvert();if(!a)return null;const d=Pe(a.compose(s.getLocalTransform(o)),s.getLocalBounds(o),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});return d?{id:t.id,...d,props:i.props}:null}function Sn(e,t){return ne(e.outlineVertices,t.outlineVertices)&&se(e.pageBounds,t.pageBounds)&&se(e.localBounds,t.localBounds)&&e.rotation===t.rotation&&te(e.rotationCenter,t.rotationCenter)&&te(e.selectionAnchorPagePoint,t.selectionAnchorPagePoint)&&e.hasRotation===t.hasRotation&&e.hasCompatibleRotation===t.hasCompatibleRotation}function yn(e){let t=(e=>{let t=e;for(;t<=-Math.PI;)t+=2*Math.PI;for(;t>Math.PI;)t-=2*Math.PI;return t})(e);for(;t<=-Math.PI/2;)t+=Math.PI;for(;t>Math.PI/2;)t-=Math.PI;return Math.abs(t)<Sa?0:t}function In(e,t){const n=e.shapes.computeLocalToPageTransform(t);return Math.atan2(n.b,n.a)}function wn(e,t,n){const i=t.get();if(0===i.length)return{outlineVertices:[],pageBounds:null,localBounds:null,rotation:0,rotationCenter:null,selectionAnchorPagePoint:null,hasRotation:!1,hasCompatibleRotation:!0};const s=[],o=[],r=[];let a=1/0,d=1/0,c=-1/0,l=-1/0;for(const y of i){const t=e.shapes.getSignal(y).get();if(!t)continue;const i=e.shapes.getUtil(t),h=fn(e,t),p=h?i.getSelectionPagePoints(h):null;if(p&&o.push(...p),!i.contributesToSelectionFrame(t,{editor:e}))continue;r.push(t);const u=n(y);if(!u)continue;const g=i.getSelectionFramePositionedOutlineVertices(t,{editor:e}),f=g?(()=>{const n=e.shapes.computePositionedToPageTransform(t);return g.map(e=>n.applyToPoint(e))})():u.outlineVertices;s.push(...f);for(const e of f)a=Math.min(a,e.x),d=Math.min(d,e.y),c=Math.max(c,e.x),l=Math.max(l,e.y)}const h=Number.isFinite(a)&&Number.isFinite(d)&&Number.isFinite(c)&&Number.isFinite(l)?new zr(a,d,c-a,l-d):null,p=!(r.length>0)||function(e,t){if(0===t.length)return!0;const n=t[0],i=yn(n?In(e,n):0);return t.every(t=>((e,t)=>{const n=yn(e)-yn(t),i=Math.PI/2;return Math.abs(n-Math.round(n/i)*i)<Sa})(In(e,t),i))}(e,r),u=((e,t,n)=>{if(0===t.length||!n)return 0;const i=t[0];return yn(i?In(e,i):0)})(e,r,p),g=((e,t)=>t.some(t=>Math.abs(yn(In(e,t)))>Sa))(e,r),f=h?.center??null,m=0===s.length?null:Math.abs(u)<Sa||!f?zr.FromPoints(s):zr.FromPoints(s.map(e=>Lr.RotWith(e,f,-u))),S=o.length>0?zr.FromPoints(o):null;return{outlineVertices:s,pageBounds:h,localBounds:m,rotation:u,rotationCenter:f,selectionAnchorPagePoint:m&&f?Math.abs(u)<Sa?new Lr(m.center.x,m.minY):Lr.RotWith(new Lr(m.center.x,m.minY),f,u):S?new Lr(S.center.x,S.minY):null,hasRotation:g,hasCompatibleRotation:p}}function Pn(e,t){const n=[],i=new Set;for(const s of t)if(!i.has(s)){i.add(s),n.push(s);for(const t of e.layers.getDescendantIds(s))i.has(t)||(i.add(t),n.push(t))}return n}function bn(e,t){let n=1/0,i=1/0,s=-1/0,o=-1/0;for(const r of t){const t=e.shapes.getPageBounds(r);t&&(n=Math.min(n,t.minX),i=Math.min(i,t.minY),s=Math.max(s,t.maxX),o=Math.max(o,t.maxY))}return Number.isFinite(n)?new zr(n,i,s-n,o-i):null}function vn(e,t,n){let i=e.shapes.get(t);const s=new Set;for(;i?.parentId.startsWith("shape:");){const t=i.parentId;if(n.has(t))return!0;if(s.has(t))return!1;s.add(t),i=e.shapes.get(t)}return!1}function xn(e,t){return Bn(e,t)}function Cn(e,t){return Bn(e,t)}function Mn(e,t=e.selection.getIds()){const n=Tn(e,t),i=1===n.length;return n.length>0&&n.every(t=>e.shapes.getUtil(t).canParticipateInSelectionFlip(t,{editor:e,isOnlyAffectedShape:i}))}function Tn(e,t=e.selection.getIds()){return Pn(e,Bn(e,t)).map(t=>e.shapes.getSignal(t).get()).filter(e=>!!e)}function Bn(e,t){const n=Array.from(new Set(t)),i=new Set(n);return n.filter(t=>{const n=e.shapes.get(t);return!(!n||e.layers.isOrAncestorLocked(n.id)||e.layers.hasLockedDescendant(n.id)||vn(e,n.id,i))})}function kn(e){return Math.min(8,Math.max(.1,e))}function En(e,t=e.pages.getCurrentId()){return Rn(e,e.shapes.getForPage(t).map(({id:e})=>e))}function An(e,t,n){const i=e.state.viewportScreenSize.get();if(i.w<=0||i.h<=0||!M(t))return!1;if(t.w<=0&&t.h<=0)return!1;const s=n?.padding??64,o=Math.max(1,i.w-2*s),r=Math.max(1,i.h-2*s),a=kn(Math.min(t.w>0?o/t.w:1/0,t.h>0?r/t.h:1/0,n?.maxZoom??1)),d=t.center;return e.viewport.setCamera({x:d.x-i.w/2/a,y:d.y-i.h/2/a,z:a},{source:n?.source??"user"}),!0}function Rn(e,t){const n=[];for(const s of t){const t=e.shapes.getPageBounds(s);t&&M(t)&&n.push(new Lr(t.minX,t.minY),new Lr(t.maxX,t.maxY))}if(0===n.length)return null;const i=zr.FromPoints(n);return M(i)?i:null}function Kn(e,t){const n=Yn(e);return n.length>=t&&null!==Xn(e,n[0].shape.parentId)}function Yn(e){const t=e.selection.getIds().map(t=>e.shapes.get(t)).filter(t=>!!t&&!e.layers.isOrAncestorLocked(t.id)),n=t[0]?.parentId;if(!n||t.some(e=>e.parentId!==n))return[];const i=[];for(const s of t){const t=e.shapes.getPageBounds(s.id);t&&M(t)&&i.push({shape:s,bounds:t})}return i}function Xn(e,t){const n=t.startsWith("shape:")?e.shapes.get(t):null;return n?e.shapes.computeLocalToPageTransform(n).tryInvert():Wr.Identity()}function Fn(e,t){const n=e.applyToPoint(Lr.Zero());return e.applyToPoint(t).sub(n)}function Dn(e){return{...e,anchorPagePoint:e.anchorPagePoint.clone(),boundaryPagePoint:e.boundaryPagePoint.clone()}}function On(e,t){return e.terminal===t.terminal&&te(e.anchorPagePoint,t.anchorPagePoint)&&te(e.boundaryPagePoint,t.boundaryPagePoint)&&(e.guidePath??null)===(t.guidePath??null)}function Ln(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||!On(i,s))return!1}return!0}function zn(e,t){return On(e,t)&&e.ownerShapeId===t.ownerShapeId&&(e.targetShapeId??null)===(t.targetShapeId??null)}function _n(e,t){return 0===t.rotation?e.clone():Lr.RotWith(e,t.rotationCenter,-t.rotation)}function $n(e,t){return 0===t.rotation?e.clone():Lr.RotWith(e,t.rotationCenter,t.rotation)}function Nn(e,t){return $n(e,t)}function Un(e,t,n,i,s){return 0===n?i:i+(e-t)/n*s}function Hn({point:e,fromBounds:t,toBounds:n}){return new Lr(Un(e.x,t.minX,t.w,n.minX,n.w),Un(e.y,t.minY,t.h,n.minY,n.h))}function Wn({axis:e,bounds:t,selectionBounds:n}){return"horizontal"===e?new zr(n.minX+n.maxX-t.maxX,t.minY,t.w,t.h):new zr(t.minX,n.minY+n.maxY-t.maxY,t.w,t.h)}function qn(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))return null;const n=Math.PI/2,i=Math.round((e-t)/n);return Math.abs(e-t-i*n)>=.001?null:Math.abs(i)%2==0?"parallel":"perpendicular"}function Gn(e,t,n){return t.every(t=>{const i=e.shapes.computeLocalToPageTransform(t);return null!==qn(Math.atan2(i.b,i.a),n)})}function Vn(e,t,n,i){const s=1===t.length,o=(r=t.map(t=>e.shapes.getUtil(t).getAllowedSelectionResizeModes(t,{editor:e,handleId:n,isOnlyResizeTarget:s})),Ia.filter(e=>r.every(t=>t.includes(e))));var r;return i?o:o.filter(e=>"free"!==e)}function jn(e,t){return e===t||(e&&t?e.localPath===t.localPath&&((e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]))(e.localDecorationPaths,t.localDecorationPaths)&&se(e.localBounds,t.localBounds)&&((e,t)=>e.a===t.a&&e.b===t.b&&e.c===t.c&&e.d===t.d&&e.e===t.e&&e.f===t.f)(e.localToPage,t.localToPage)&&e.strokeWidth===t.strokeWidth&&e.strokeDasharray===t.strokeDasharray:e===t)}function Qn(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)return!1;if(!(i.id===s.id&&i.usesSelectionPathOverlay===s.usesSelectionPathOverlay&&te(i.startPagePoint,s.startPagePoint)&&te(i.endPagePoint,s.endPagePoint)&&te(i.middlePagePoint,s.middlePagePoint)&&jn(i.pathStyle,s.pathStyle)&&Ln(i.bindingSegments,s.bindingSegments)&&i.path===s.path&&i.pageClipPath===s.pageClipPath))return!1}return!0}function Zn(e,t){return e===t||(e&&t?se(e.bounds,t.bounds)&&e.rotation===t.rotation&&te(e.rotationCenter,t.rotationCenter):e===t)}function Jn(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Zn(e[n]??null,t[n]??null))return!1;return!0}function ei(e,t){return e.strokeWidth===t.strokeWidth&&e.cornerRadius===t.cornerRadius}function ti(e,t){return e.id===t.id&&te(e.point,t.point)&&se(e.bounds,t.bounds)}function ni(e,t){return e.id===t.id&&te(e.point,t.point)&&se(e.bounds,t.bounds)}function ii(e,t){return e.terminal===t.terminal&&te(e.point,t.point)&&se(e.bounds,t.bounds)}function si(e,t){return te(e.point,t.point)&&se(e.bounds,t.bounds)}function oi(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&te(e.point,t.point)&&se(e.bounds,t.bounds)}function ri(e,t){return e.id===t.id&&te(e.point,t.point)}function ai(e,t){return e.id===t.id&&te(e.point,t.point)}function di(e,t){return e.terminal===t.terminal&&te(e.point,t.point)}function ci(e,t){return te(e.point,t.point)}function li(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&te(e.point,t.point)}function hi(e,t){return e===t||(e&&t?e.strokeWidth===t.strokeWidth&&J(e.resizeHandles,t.resizeHandles,ti)&&J(e.rotateHandles,t.rotateHandles,ni)&&J(e.terminalHandles,t.terminalHandles,ii)&&J(e.middleHandles,t.middleHandles,si)&&J(e.customHandles,t.customHandles,oi):e===t)}function pi(e,t){return e===t||(e&&t?J(e.resizeHandleAnchors,t.resizeHandleAnchors,ri)&&J(e.rotateHandleAnchors,t.rotateHandleAnchors,ai)&&J(e.terminalHandleAnchors,t.terminalHandleAnchors,di)&&J(e.middleHandleAnchors,t.middleHandleAnchors,ci)&&J(e.customHandleAnchors,t.customHandleAnchors,li):e===t)}function ui({bounds:e,rotateOffset:t,referenceRotation:n,frameRotation:i}){return((e,t)=>{const n=Math.round((e-t)/Math.PI);return 1===Math.abs(n%2)})(n,i)?new Lr(e.maxX+t,e.minY-t):new Lr(e.minX-t,e.maxY+t)}function gi(e){return 1===e.length&&!!e[0]?.usesSelectionPathOverlay}function fi(e,t,n,i){const s=e.shapes.get(n);if(!s)return null;const o=t.getCachedShapeGeometry(n),r=t.getCachedShapeGeometry(i);if(!o||!r)return null;const a=e.shapes.getUtil(s).getLocalBounds(s),d=t.getShapeLocalToPageTransformSignal(n).get()?.tryInvert();return d&&r.outlineVertices.length>0&&r.outlineVertices.every(e=>a.containsPoint(d.applyToPoint(e)))?"inside":o.bounds.intersects(r.bounds)?"intersecting":"outside"}function mi({editor:e,shapeTree:t,geometry:n,shapeIds:i,point:s}){const o=Array.from(new Set(i));if(0===o.length)return null;const r=o.map(t=>e.shapes.get(t)).filter(e=>!!e);if(r.length!==o.length)return null;const a=t.getPageIdForShape(r[0].id);if(!a)return null;if(r.some(e=>t.getPageIdForShape(e.id)!==a))return null;const d=new Set;for(const u of r){d.add(u.id);for(const e of t.getDescendantShapeIds(u.id))d.add(e)}let c=null,l=1/0,h=-1;const p=t.getShapeIdsForPage(a);for(let u=0;u<p.length;u+=1){const t=p[u];if(d.has(t))continue;const i=e.shapes.get(t);if(!i||e.shapes.isHidden(i.id)||e.layers.isOrAncestorLocked(i.id))continue;const o=e.shapes.getUtil(i);if(!yi(i,o))continue;if(!r.every(t=>e.layers.canReceiveChild(i.id,t.id)))continue;if(s){if(!e.shapes.isPagePointInClip(i.id,s))continue;const t=o.getLocalBounds(i),r=n.getShapeLocalToPageTransformSignal(i.id).get()?.tryInvert();if(!r||!t.containsPoint(r.applyToPoint(s)))continue}else if(!r.every(t=>"inside"===fi(e,n,i.id,t.id)))continue;const a=n.getShapePageBounds(i.id);a&&Si(a,u,c,l,h)&&(c=i,l=a.w*a.h,h=u)}return c?.id??a}function Si(e,t,n,i,s){const o=e.w*e.h;return!n||o<i||o===i&&t>s}function yi(e,t){return t.canAutomaticallyReceiveChildren(e)}function Ii(e,t,n=new Set([t.id])){if(!t.parentId.startsWith("shape:"))return Wr.Identity();const i=e.shapes.get(t.parentId);if(!i||n.has(i.id))return Wr.Identity();const s=new Set(n);return s.add(i.id),be(i,e.shapes.getUtil(i),Ii(e,i,s))}function wi(e,t){return e.shapes.getUtil(t).getExportBounds(t)}function Pi(e,t){return be(t,e.shapes.getUtil(t),Ii(e,t))}function bi(e,t){return ke(t,e.shapes.getUtil(t),Ii(e,t))}function vi(e){const t=e.selection.getLocalBounds(),n=e.selection.getRotationCenter();return t&&n?{bounds:t,rotation:e.selection.getRotation(),rotationCenter:n,hasCompatibleRotation:e.selection.hasCompatibleRotation()}:null}function xi(e,t){const n=vi(e);return n?_n(t,n):null}function Ci(e){return Mi(e,e.selection.getIds())}function Mi(e,t){const n=Array.from(new Set(t.map(t=>e.bindings.getShapeCompanionRootId(t)))),i=n.map(t=>e.shapes.get(t)).filter(e=>!!e);if(i.length!==n.length)return null;const s=new Set(n),o=i.filter(t=>!vn(e,t.id,s));if(o.length<2)return null;if(o.some(t=>e.layers.isOrAncestorLocked(t.id)||e.layers.hasLockedDescendant(t.id)||e.shapes.isHidden(t.id)))return null;const r=o[0]?.parentId;if(!r)return null;if(o.some(e=>e.parentId!==r))return null;const a=e.layers.getChildren(r),d=new Set(o.map(e=>e.id)),c=a.filter(e=>d.has(e.id)).map(e=>e.id);if(c.length!==o.length)return null;const l=r.startsWith("shape:")?e.shapes.get(r):null,h=l?e.shapes.computeLocalToPageTransform(l).tryInvert():null;if(l&&!h)return null;const p=c.flatMap(t=>e.shapes.getPageOutlineVertices(t).map(e=>h?h.applyToPoint(e):e)),u=p.length>0?zr.FromPoints(p):null;if(!u||!M(u))return null;const g={parentId:r,shapeIds:c,parentLocalBounds:u};return Ti(e,g)?g:null}function Ti(e,t){let n=null;for(const i of e.shapeUtils.values()){const e=i.getGroupingShapeCreateInput({parentId:t.parentId,parentLocalBounds:t.parentLocalBounds});if(e){if(e.type!==i.type)throw new Error(`Shape util "${i.type}" created grouping type "${e.type}" instead of its registered type`);if(e.parentId!==t.parentId)throw new Error(`Shape util "${i.type}" must preserve the requested grouping parent`);if(n)throw new Error(`Multiple shape utils define grouping creation: "${n.shapeUtilType}" and "${i.type}"`);n={shapeInput:e,shapeUtilType:i.type}}}return n?.shapeInput??null}function Bi(e,t,n="user"){const i=Mi(e,t);return i?((e,t,n)=>{const i=Ti(e,t);if(!i)return null;const s=e.layers.getChildren(t.parentId),o=new Set(t.shapeIds);let r;for(const c of s)o.has(c.id)&&(r=c);if(!r)return null;e.interaction.cancelForCommand();let a=null;try{S(e).atomic(()=>{const[d]=e.commands.createShapes([i],{source:n,deferMinimumChildRepair:!0});if(!d)throw new ba;if(a=d.id,!e.commands.reparentShapes({ids:t.shapeIds,parentId:d.id},{source:n}))throw new ba;const c=[];for(const e of s)o.has(e.id)?e.id===r.id&&c.push(d.id):c.push(e.id);e.commands.updateShapes([...c.map((t,n)=>({id:t,index:re(e).createShapeIndex(n+1)})),...t.shapeIds.map((t,n)=>({id:t,index:re(e).createShapeIndex(n+1)}))],{source:n})},n)}catch(d){if(d instanceof ba)return null;throw d}return a?e.shapes.get(a)??null:null})(e,i,n):null}function ki(e){return Ei(e,e.selection.getIds())}function Ei(e,t){return t.map(t=>e.shapes.get(t)).filter(e=>!!e).filter(t=>e.shapes.getUtil(t).canUngroupChildren(t)).filter(t=>!e.layers.isOrAncestorLocked(t.id)&&!e.layers.hasLockedDescendant(t.id)&&!e.shapes.isHidden(t.id)&&e.layers.getChildIds(t.id).length>0&&e.layers.getChildren(t.id).every(n=>e.layers.canReceiveChild(t.parentId,n.id)&&!!Ue(e,n,t.parentId))).map(e=>e.id)}function Ai(e,t,n="user"){const i=Array.from(new Set(t)),s=new Set(((e,t)=>{const n=Ei(e,t),i=new Set(n);return n.filter(t=>!vn(e,t,i))})(e,i));if(0===s.size)return[];const o=i.map(t=>e.shapes.get(t)).filter(e=>!!e),r=o.filter(e=>s.has(e.id)).map(t=>({group:t,children:e.layers.getChildren(t.id)}));if(r.some(t=>t.children.some(n=>!Ue(e,n,t.group.parentId))))return[];const a=new Map(r.map(e=>[e.group.id,e])),d=new Set(r.map(e=>e.group.parentId)),c=new Map;for(const u of d){const t=[];for(const n of e.layers.getChildren(u)){const e=a.get(n.id);e?t.push(...e.children.map(e=>e.id)):t.push(n.id)}c.set(u,t)}e.interaction.cancelForCommand();const l=[],h=new Set;try{S(e).atomic(()=>{const t=[];for(const i of o){if(!s.has(i.id)){h.has(i.id)||(h.add(i.id),l.push(i.id));continue}const t=a.get(i.id);if(!t)continue;if(!e.commands.reparentShapes({ids:t.children.map(e=>e.id),parentId:t.group.parentId},{source:n}))throw new ba;const o=new Set(t.children.map(e=>e.id));for(const n of t.children){const t=e.bindings.getShapeCompanionRootId(n.id),i=o.has(t)?t:n.id;h.has(i)||(h.add(i),l.push(i))}}for(const n of c.values())t.push(...n.map((t,n)=>({id:t,index:re(e).createShapeIndex(n+1)})));t.length>0&&e.commands.updateShapes(t,{source:n}),((e,t,n)=>{if(0===t.length)return;const i=Array.from(new Set(t)).filter(t=>e.shapes.get(t));0!==i.length&&He(e,i,{source:n})})(e,r.map(e=>e.group.id),n)},n)}catch(p){if(p instanceof ba)return[];throw p}return l.length>0&&e.commands.setSelectedShapeIds(l,{source:n}),l}function Ri(e){const t=e.state.selectedShapes.get();if(0===t.length)return null;if(t.some(e=>e.isLocked))return null;const n=t[0]?.parentId;if(!n)return null;if(t.some(e=>e.parentId!==n))return null;const i=e.layers.getChildren(n),s=new Set(t.map(e=>e.id)),o=i.map((e,t)=>s.has(e.id)?t:-1).filter(e=>e>=0);return o.length!==t.length?null:{parentId:n,selectedCount:t.length,count:i.length,canMoveBackward:o.some(e=>e>0&&!s.has(i[e-1].id)),canMoveForward:o.some(e=>e<i.length-1&&!s.has(i[e+1].id))}}function Ki(e){const t=e.state.selectedShapes.get();if(1!==t.length)return null;const[n]=t;if(!n||n.isLocked)return null;const i=e.layers.getChildren(n.parentId),s=i.findIndex(e=>e.id===n.id);return s<0?null:{parentId:n.parentId,index:s,count:i.length,canMoveBackward:s>0,canMoveForward:s<i.length-1}}function Yi(e,t){const n=t.map(t=>e.shapes.get(t)).filter(e=>!!e);if(0===n.length)return null;if(n.some(t=>t.isLocked||e.shapes.isHidden(t.id)))return null;const i=n[0]?.parentId;if(!i)return null;if(n.some(e=>e.parentId!==i))return null;const s=e.layers.getChildren(i),o=new Set(n.map(e=>e.id)),r=s.map((e,t)=>o.has(e.id)?t:-1).filter(e=>e>=0);return r.length!==n.length?null:{parentId:i,selectedCount:n.length,count:s.length,canMoveBackward:r.some(e=>e>0&&!o.has(s[e-1].id)),canMoveForward:r.some(e=>e<s.length-1&&!o.has(s[e+1].id))}}function Xi(e,t,n,i="user"){const s=Yi(e,t);if(!s)return!1;const o=e.layers.getChildren(s.parentId),r=new Set(t),a=[...o];let d=!1;if("backward"===n)for(let c=1;c<a.length;c+=1){const e=a[c],t=a[c-1];e&&t&&r.has(e.id)&&!r.has(t.id)&&(a[c-1]=e,a[c]=t,d=!0)}else for(let c=a.length-2;c>=0;c-=1){const e=a[c],t=a[c+1];e&&t&&r.has(e.id)&&!r.has(t.id)&&(a[c]=t,a[c+1]=e,d=!0)}return!!d&&(e.interaction.cancelForCommand(),e.commands.updateShapes(a.map((t,n)=>({id:t.id,index:re(e).createShapeIndex(n+1)})),{source:i}),!0)}function Fi(e,t,n,i="user"){const s=Yi(e,t);if(!s)return!1;const o=e.layers.getChildren(s.parentId),r=new Set(t),a=[],d=[];for(const l of o)r.has(l.id)?a.push(l):d.push(l);if(a.length!==r.size)return!1;if(!("back"===n?s.canMoveBackward:s.canMoveForward))return!1;const c="back"===n?[...a,...d]:[...d,...a];return e.interaction.cancelForCommand(),e.commands.updateShapes(c.map((t,n)=>({id:t.id,index:re(e).createShapeIndex(n+1)})),{source:i}),!0}function Di(e,t,n){const i=new Set([t]);let s=n(t);if(!s)return null;for(;s;){if(s.isHidden)return!1;if(!s.parentId.startsWith("shape:"))return!0;const t=s.parentId;if(i.has(t))return!0;i.add(t);const o=n(t);if(!o)return!0;if(!e.shapes.getUtil(o).isChildVisible(o,s,{editor:e}))return!1;s=o}return!0}function Oi(e){return"top_left"===e||"left"===e||"bottom_left"===e}function Li(e){return"top_right"===e||"right"===e||"bottom_right"===e}function zi(e){return"top_left"===e||"top"===e||"top_right"===e}function _i(e){return"bottom_left"===e||"bottom"===e||"bottom_right"===e}function $i({handleId:e,scaleX:t,scaleY:n}){const i=Oi(e)?t<0?"right":"left":Li(e)?t<0?"left":"right":null,s=zi(e)?n<0?"bottom":"top":_i(e)?n<0?"top":"bottom":null;return"top"===s&&"left"===i?"top_left":"top"===s&&"right"===i?"top_right":"bottom"===s&&"right"===i?"bottom_right":"bottom"===s&&"left"===i?"bottom_left":s||i||e}function Ni({axis:e,startBounds:t,bounds:n,handleId:i,scale:s,isResizingFromCenter:o}){const r=Math.sign(s??1)||1;return o?r:"x"===e?Oi(i)?n.minX>=t.maxX?-1:1:Li(i)?n.maxX<=t.minX?-1:1:r:zi(i)?n.minY>=t.maxY?-1:1:_i(i)?n.maxY<=t.minY?-1:1:r}function Ui({bounds:e,startBounds:t,handleId:n,aspectRatio:i,isResizingFromCenter:s,scaleX:o,scaleY:r}){if(i<=0)return{bounds:e,scaleX:o??e.w/Math.max(1,t.w),scaleY:r??e.h/Math.max(1,t.h)};let a=e.w,d=e.h;const c=Math.sign(o??1)||1,l=Math.sign(r??1)||1;switch(n){case"left":case"right":d=a/i;break;case"top":case"bottom":a=d*i;break;default:{const e=a/Math.max(1,t.w),n=d/Math.max(1,t.h);Math.abs(e)>Math.abs(n)?d=a/i:a=d*i;break}}if(s){const e=t.center;return{bounds:new zr(e.x-a/2,e.y-d/2,a,d),scaleX:c*(a/Math.max(1,t.w)),scaleY:l*(d/Math.max(1,t.h))}}let h;switch(n){case"top_left":h=new zr(c<0?e.minX:e.maxX-a,l<0?e.minY:e.maxY-d,a,d);break;case"top_right":h=new zr(c<0?e.maxX-a:e.minX,l<0?e.minY:e.maxY-d,a,d);break;case"bottom_right":h=new zr(c<0?e.maxX-a:e.minX,l<0?e.maxY-d:e.minY,a,d);break;case"bottom_left":h=new zr(c<0?e.minX:e.maxX-a,l<0?e.maxY-d:e.minY,a,d);break;case"top":h=new zr(t.center.x-a/2,l<0?t.maxY:t.maxY-d,a,d);break;case"right":h=new zr(c<0?t.minX-a:t.minX,t.center.y-d/2,a,d);break;case"bottom":h=new zr(t.center.x-a/2,l<0?t.minY-d:t.minY,a,d);break;case"left":h=new zr(c<0?t.maxX:t.maxX-a,t.center.y-d/2,a,d)}return{bounds:h,scaleX:c*(a/Math.max(1,t.w)),scaleY:l*(d/Math.max(1,t.h))}}function Hi(e){return[new Lr(e.minX,e.minY),new Lr(e.center.x,e.minY),new Lr(e.maxX,e.minY),new Lr(e.minX,e.center.y),e.center,new Lr(e.maxX,e.center.y),new Lr(e.minX,e.maxY),new Lr(e.center.x,e.maxY),new Lr(e.maxX,e.maxY)]}function Wi(e,t){return"x"===t?e.x:e.y}function qi(e,t){return"x"===t?e.minX:e.minY}function Gi(e,t){return"x"===t?e.maxX:e.maxY}function Vi(e,t){return"x"===t?[e.minY,e.maxY]:[e.minX,e.maxX]}function ji(e,t){const n=Math.max(e[0],t[0]),i=Math.min(e[1],t[1]);return n<=i?[n,i]:null}function Qi(e,t){return null!==ji(e,t)}function Zi(e,t){return new zr(e.x+t.x,e.y+t.y,e.w,e.h)}function Ji(e,t,n){return Zi(e,((e,t)=>"x"===e?new Lr(t,0):new Lr(0,t))(t,n))}function es(e){return[new Lr(e.minX,e.minY),new Lr(e.maxX,e.minY),new Lr(e.maxX,e.maxY),new Lr(e.minX,e.maxY)]}function ts(e,t,n){const i=n.sub(t),s=i.len2();if(s<=1e-8)return e.dist2(t);const o=Math.max(0,Math.min(1,((e.x-t.x)*i.x+(e.y-t.y)*i.y)/s));return e.dist2(new Lr(t.x+i.x*o,t.y+i.y*o))}function ns(e,t,n){const i=n.sub(t),s=i.len2();if(s<=1e-8)return t.clone();const o=Math.max(0,Math.min(1,((e.x-t.x)*i.x+(e.y-t.y)*i.y)/s));return new Lr(t.x+i.x*o,t.y+i.y*o)}function is(e,t){if(0===t.length)return null;if(1===t.length){const n=t[0].clone();return{point:n,distanceSquared:e.dist2(n)}}let n=null,i=Number.POSITIVE_INFINITY;const s=2===t.length?1:t.length;for(let o=0;o<s;o+=1){const s=t[o],r=t[(o+1)%t.length];if(!s||!r)continue;const a=ts(e,s,r);a>=i||(i=a,n=ns(e,s,r))}return n?{point:n,distanceSquared:i}:null}function ss(e){const t=[],n=new Set;for(const i of e){const e=`${i.x.toFixed(8)}:${i.y.toFixed(8)}`;n.has(e)||(n.add(e),t.push(i))}return t}function os(e,t){const n="x"===t?"horizontal":"vertical",i=[...e].sort((e,n)=>qi(e.bounds,t)-qi(n.bounds,t)),s=[];for(let o=0;o<i.length;o+=1){const e=i[o];if(!e)continue;let r=Number.POSITIVE_INFINITY;for(let a=o+1;a<i.length;a+=1){const o=i[a];if(!o)continue;const d=Gi(e.bounds,t),c=qi(o.bounds,t);if(c>r+1e-8)break;if(d>=c)continue;const l=ji(Vi(e.bounds,t),Vi(o.bounds,t));l&&(r=c,s.push({direction:n,startNode:e,endNode:o,length:c-d,breadthIntersection:l}))}}return s}function rs(e,t,n,i){const s=ji(Vi(t.bounds,i),Vi(n.bounds,i));return s?{direction:e,startNode:t,endNode:n,length:qi(n.bounds,i)-Gi(t.bounds,i),breadthIntersection:s}:null}function as(e,t){return[e,t.direction,t.startNode.id,t.endNode.id,t.length.toFixed(8)].join(":")}function ds(e,t,n,i,s={}){const o=Vi(t,e),r=((e,t)=>"x"===t?e.w:e.h)(t,e),a=s.releaseThreshold??i,d=s.switchDistance??0;let c=i+1,l=null,h=null;const p=(e,t,n)=>{const o=Math.abs(e);0!==t.length&&(o<=i&&o<c-1e-8&&(c=o,l={type:"gaps",id:n,nudge:e,distance:o,gaps:t}),s.previousSnapId===n&&o<=a&&(!h||o<h.distance-1e-8)&&(h={type:"gaps",id:n,nudge:e,distance:o,gaps:t}))},u=n=>({id:"selection",bounds:Ji(t,e,n)});for(const g of n){if(r<=g.length&&Qi(o,g.breadthIntersection)){const n=Gi(g.startNode.bounds,e)+(g.length-r)/2-qi(t,e),i=u(n);p(n,[rs(g.direction,g.startNode,i,e),rs(g.direction,i,g.endNode,e)].filter(e=>null!==e),`${as(e,g)}:center`)}const n=Gi(g.endNode.bounds,e)+g.length-qi(t,e),i=u(n);if(Qi(Vi(i.bounds,e),g.breadthIntersection)){const t=rs(g.direction,g.endNode,i,e);p(n,t?[g,t]:[],`${as(e,g)}:after`)}const s=qi(g.startNode.bounds,e)-g.length-Gi(t,e),a=u(s);if(Qi(Vi(a.bounds,e),g.breadthIntersection)){const t=rs(g.direction,a,g.startNode,e);p(s,t?[t,g]:[],`${as(e,g)}:before`)}}return h&&(!l||l.distance+d>=h.distance)?h:l}function cs(e){const t=e.map(e=>({value:e.point.x,point:e})),n=e.map(e=>({value:e.point.y,point:e}));return t.sort(ls),n.sort(ls),{x:t,y:n}}function ls(e,t){return e.value-t.value||e.point.id.localeCompare(t.point.id)}function hs(e,t,n,i){const s=((e,t)=>"x"===t?e.x:e.y)(e,t),o=[];for(let r=((e,t)=>{let n=0,i=e.length;for(;n<i;){const s=Math.floor((n+i)/2),o=e[s];o&&o.value<t?n=s+1:i=s}return n})(s,n);r<s.length;r+=1){const e=s[r];if(!e||e.value>i)break;o.push(e.point)}return o}function ps(e){return e.weight??(e.kind?Ca[e.kind]:0)}function us(e,t){return`points:${e}:${[...t].sort().join("|")}`}function gs(e,t,n){if(!t)return!0;const i=(e=>Math.min(.2*e,1.5))(n);return e.distance<t.distance-1e-8?!(t.weight>e.weight+1e-8&&t.distance-e.distance<=i):e.distance<=t.distance+i&&e.weight>t.weight+1e-8}function fs(e,t,n,i,s={}){const o=s.releaseThreshold??i,r=Math.max(i,o),a=s.switchDistance??0;let d=null,c=null;for(const g of t){const t=Wi(g,e),a=hs(n,e,t-r,t+r);s.stats&&(s.stats.candidatePointCount+=a.length);for(const n of a){const r=Wi(n.point,e)-t,a=Math.abs(r),l={offset:r,distance:a,weight:ps(n),fromPrevious:!1};if(a<=i&&gs(l,d,i)&&(d=l),s.previousCandidatePointIds?.has(n.id)&&a<=o){const e={...l,fromPrevious:!0};gs(e,c,o)&&(c=e)}}}const l=c&&(!d||d.distance+a>=c.distance)?c:d;if(!l)return null;const h=l.fromPrevious&&l.distance>i?o:i,p=[];for(const[g,f]of t.entries()){const t=Wi(f,e),i=hs(n,e,t-h,t+h);for(const n of i){const i=Wi(n.point,e)-t;Math.abs(i)>h||Math.abs(i-l.offset)>1e-8||p.push({selectionPoint:f,selectionPointKind:s.selectionPointKinds?.[g],candidatePoint:n.point,candidatePointKind:n.kind,candidatePointId:n.id,candidateNodeId:n.nodeId})}}s.stats&&(s.stats.matchedPointCount+=p.length);const u=Array.from(new Set(p.map(e=>e.candidatePointId)));return p.length>0?{type:"points",id:us(e,u),nudge:l.offset,distance:l.distance,weight:l.weight,candidatePointIds:u,pairs:p}:null}function ms(e,t){const n=[];switch(e){case"top":case"left":case"top_left":case"any":n.push(new Lr(t.minX,t.minY))}switch(e){case"top":case"right":case"top_right":case"any":n.push(new Lr(t.maxX,t.minY))}switch(e){case"bottom":case"right":case"bottom_right":case"any":n.push(new Lr(t.maxX,t.maxY))}switch(e){case"bottom":case"left":case"bottom_left":case"any":n.push(new Lr(t.minX,t.maxY))}return n}function Ss(e,t,n={}){if(!e)return t;if(!t)return e;const i=n.switchDistance??0;return"points"===n.previousSnap?.type&&n.previousSnap.id===e.id?Math.abs(t.nudge)+i<Math.abs(e.nudge)?t:e:"gaps"===n.previousSnap?.type&&n.previousSnap.id===t.id?Math.abs(e.nudge)+i<Math.abs(t.nudge)?e:t:Math.abs(e.nudge)<=Math.abs(t.nudge)?e:t}function ys(e,t){return e===t||e.length===t.length&&e.every((e,n)=>{const i=t[n];return!(!i||e.type!==i.type)&&("points"===e.type&&"points"===i.type?((e,t)=>e.id===t.id&&e.axis===t.axis&&e.rotation===t.rotation&&te(e.rotationCenter,t.rotationCenter)&&te(e.line[0],t.line[0])&&te(e.line[1],t.line[1])&&e.points.length===t.points.length&&e.points.every((e,n)=>{const i=t.points[n];return!!i&&te(e,i)}))(e,i):"gaps"===e.type&&"gaps"===i.type&&function(e,t){return e.id===t.id&&e.direction===t.direction&&e.rotation===t.rotation&&te(e.rotationCenter,t.rotationCenter)&&e.gaps.length===t.gaps.length&&e.gaps.every((e,n)=>{const i=t.gaps[n];return!!i&&((e,t)=>te(e.startEdge[0],t.startEdge[0])&&te(e.startEdge[1],t.startEdge[1])&&te(e.endEdge[0],t.endEdge[0])&&te(e.endEdge[1],t.endEdge[1]))(e,i)})}(e,i))})}function Is(e){return"horizontal"===e.direction?{startEdge:[new Lr(e.startNode.bounds.maxX,e.startNode.bounds.minY),new Lr(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new Lr(e.endNode.bounds.minX,e.endNode.bounds.minY),new Lr(e.endNode.bounds.minX,e.endNode.bounds.maxY)]}:{startEdge:[new Lr(e.startNode.bounds.minX,e.startNode.bounds.maxY),new Lr(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new Lr(e.endNode.bounds.minX,e.endNode.bounds.minY),new Lr(e.endNode.bounds.maxX,e.endNode.bounds.minY)]}}function ws(e,t,n,i){const s=t.pairs.some(({candidatePointKind:e,selectionPointKind:t})=>"center"===e&&"center"===t),o=ss([...t.pairs.map(({selectionPoint:e})=>e.add(n)),...t.pairs.map(({candidatePoint:e})=>e.clone())]),r=ss([...t.pairs.filter(({selectionPointKind:e})=>"center"===e).map(({selectionPoint:e})=>e.add(n)),...t.pairs.filter(({candidatePointKind:e})=>"center"===e).map(({candidatePoint:e})=>e.clone())]),a=s?r:o,d=s?r:ss([...t.pairs.filter(({selectionPointKind:e})=>"center"!==e&&"edge_midpoint"!==e).map(({selectionPoint:e})=>e.add(n)),...t.pairs.filter(({candidatePointKind:e})=>"center"!==e&&"edge_midpoint"!==e).map(({candidatePoint:e})=>e.clone())]),c=xs(e,a);return{id:Cs(e,c,d),type:"points",axis:e,line:c,points:d,rotation:i.rotation,rotationCenter:i.rotationCenter.clone()}}function Ps(e,t,n,i){return bs(e,t,n).map(t=>ws(e,t,n,i))}function bs(e,t,n){const i=new Map;for(const s of t.pairs){const t=Wi(s.selectionPoint.add(n),e).toFixed(8),o=i.get(t);o?o.push(s):i.set(t,[s])}return Array.from(i.values()).map(e=>({type:"points",id:t.id,nudge:t.nudge,distance:t.distance,weight:t.weight,candidatePointIds:Array.from(new Set(e.map(e=>e.candidatePointId))),pairs:e}))}function vs(e,t,n){return"x"===e?[new Lr(t,n.minY),new Lr(t,n.maxY)]:[new Lr(n.minX,t),new Lr(n.maxX,t)]}function xs(e,t){if(0===t.length)return[Lr.Zero(),Lr.Zero()];let n=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY,s=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY;for(const r of t)n=Math.min(n,r.x),i=Math.max(i,r.x),s=Math.min(s,r.y),o=Math.max(o,r.y);return"x"===e?[new Lr(n,s),new Lr(n,o)]:[new Lr(n,s),new Lr(i,s)]}function Cs(e,t,n){return`points:${e}:line:${t.map(e=>`${e.x.toFixed(4)},${e.y.toFixed(4)}`).join("|")}:points:${n.map(e=>`${e.x.toFixed(4)},${e.y.toFixed(4)}`).join("|")}`}function Ms(e,t,n,i,s,o){return bs(e,t,n).map(t=>((e,t,n,i,s,o)=>{const r=ws(e,t,n,i),a=t.pairs[0],d=Wi(a?.selectionPoint.add(n)??s.center,e),c=new Map(o.map(e=>[e.id,e.bounds])),l=[],h=new Set;for(const g of t.pairs){if(h.has(g.candidateNodeId))continue;h.add(g.candidateNodeId);const t=c.get(g.candidateNodeId);t&&l.push(...vs(e,d,t))}const p=ss([...r.points,...vs(e,d,s),...l]),u=xs(e,ss([...vs(e,d,s),...l]));return{...r,id:Cs(e,u,p),line:u,points:p}})(e,t,n,i,s,o))}function Ts(e,t,n){const i="x"===e?new Lr(n.x,t.y):new Lr(t.x,n.y),s=ss([n.clone(),i]),o=xs(e,s);return{id:Cs(e,o,s),type:"points",axis:e,line:o,points:s,rotation:0,rotationCenter:Lr.Zero()}}function Bs(e,t,n){const i="horizontal"===e.gaps[0]?.direction?new Lr(0,n.y):new Lr(n.x,0),s=e.gaps.map(e=>({...e,startNode:"selection"===e.startNode.id?{...e.startNode,bounds:Zi(e.startNode.bounds,i)}:e.startNode,endNode:"selection"===e.endNode.id?{...e.endNode,bounds:Zi(e.endNode.bounds,i)}:e.endNode}));return{id:`gaps:${s.map(e=>`${e.startNode.id}:${e.endNode.id}:${e.length.toFixed(4)}`).join("|")}`,type:"gaps",direction:s[0]?.direction??"horizontal",gaps:s.map(Is),rotation:t.rotation,rotationCenter:t.rotationCenter.clone()}}function ks(e){return"points"===e.type?{...e,line:[e.line[0].clone(),e.line[1].clone()],points:e.points.map(e=>e.clone()),rotationCenter:e.rotationCenter.clone()}:{...e,gaps:e.gaps.map(e=>({startEdge:[e.startEdge[0].clone(),e.startEdge[1].clone()],endEdge:[e.endEdge[0].clone(),e.endEdge[1].clone()]})),rotationCenter:e.rotationCenter.clone()}}function Es(e){return{point:e.point,kind:e.kind??"custom",weight:e.weight}}function As(e){const t=e.sourcePointOffsets;return t&&t.length>0?t.map(t=>e.pagePoint.add(t)):[e.pagePoint]}function Rs(e,t){return e.count===t.count&&e.singleShapeType===t.singleShapeType&&e.commonShapeType===t.commonShapeType&&e.canFlipSelection===t.canFlipSelection&&e.hasPointHandleSelection===t.hasPointHandleSelection&&e.hasFrameSelection===t.hasFrameSelection&&e.isMixedFrameAndPointHandleSelection===t.isMixedFrameAndPointHandleSelection&&e.canDragPointHandles===t.canDragPointHandles&&e.hasSelectionRotation===t.hasSelectionRotation&&e.hasMixedSelectionRotation===t.hasMixedSelectionRotation&&e.canResetSelectionRotation===t.canResetSelectionRotation}function Ks(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||i.id!==s.id||i.shape!==s.shape||i.isSelected!==s.isSelected||i.bounds.x!==s.bounds.x||i.bounds.y!==s.bounds.y||i.bounds.w!==s.bounds.w||i.bounds.h!==s.bounds.h)return!1}return!0}function Ys(e,t,n){return e+(t-e)*n}function Xs(e,t,n){return Math.min(n,Math.max(t,e))}function Fs(e,t=0){if(0===e.length)return[];const n=[...e].sort((e,t)=>e.start-t.start),i=[];for(const s of n){const e=i[i.length-1];!e||s.start>e.end+t?i.push({...s}):e.end=Math.max(e.end,s.end)}return i}function Ds(e,t){if(!Number.isFinite(e))return t;const n=Math.max(0,Math.floor((e-3)/2));return Math.min(t,n)}function Os(e){return e.reduce((e,t)=>e+(t.end-t.start),0)}function Ls(e,t){const n=[];for(const i of t)n.push(...e.slice(i.start,i.end));return n}function zs(e,t,n){return{viewportReady:n?.viewportReady??!0,ranges:t.map(e=>({...e})),shapeIds:Ls(e,t)}}function _s(e){return{shapeUtils:e.flatMap(e=>e.shapeUtils??[]),shapeSvgExporters:e.flatMap(e=>e.shapeSvgExporters??[]),shapeSvgDecorations:e.flatMap(e=>e.shapeSvgDecorations??[]),shapeHitTestDecorations:e.flatMap(e=>e.shapeHitTestDecorations??[]),bindingUtils:e.flatMap(e=>e.bindingUtils??[])}}function $s(e){let t=null;for(const i of e.splice(0).reverse())try{i()}catch(n){t??=n}return t}function Ns(e={}){const{plugins:t=[],...n}=e,i=new Aa({...n,..._s(t)});try{return i.runtime.onDispose(((e,t)=>{const n=[];try{for(const i of t){for(const n of i.interactionHandlers??[])e.interactions.register(n);const t=i.setup?.(e);t&&n.push(t)}}catch(i){throw $s(n),i}return()=>{const e=$s(n);if(null!==e)throw e}})(i,t)),i}catch(s){try{i.dispose()}catch{}throw s}}function Us(e,t){return((e,t)=>!(Hs(t.key)!==e.key||t.altKey!==e.altKey||t.shiftKey!==e.shiftKey||void 0!==e.accelKey&&t.accelKey!==e.accelKey||void 0!==e.ctrlKey&&t.ctrlKey!==e.ctrlKey||void 0!==e.metaKey&&t.metaKey!==e.metaKey||void 0===e.accelKey&&void 0===e.ctrlKey&&void 0===e.metaKey&&t.accelKey))((e=>{const t="string"==typeof e?{key:e}:e;return{key:Hs(t.key),altKey:t.altKey??!1,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey??!1,accelKey:t.accelKey}})(e),t)}function Hs(e){return e.toLowerCase()}function Ws(e){return Math.min(1,Math.max(0,(96-e)/96))}function qs(e,t,n){const i=e.inputs.state.get();if("dragging"!==i.dragPhase||!i.currentPagePoint)return null;let s=i.currentPagePoint;if(!i.currentScreenPoint)return"apply_after_scroll"===n?null:{pagePoint:s,shiftKey:i.shiftKey,altKey:i.altKey,accelKey:i.accelKey,ctrlKey:i.ctrlKey};const o=((e,t,n)=>{if(t.w<=0||t.h<=0||n<=0)return Lr.Zero();const i=Math.min(n,32),s=Ws(e.x),o=Ws(t.w-e.x),r=Ws(e.y),a=1.25*(o-s)*i,d=1.25*(Ws(t.h-e.y)-r)*i;return 0===a&&0===d?Lr.Zero():new Lr(a,d)})(i.currentScreenPoint,e.state.viewportScreenSize.get(),t.elapsed),r=0!==o.x||0!==o.y;return r||"always_apply"===n?(r&&(e.viewport.pan(o),s=e.viewport.screenToPage(i.currentScreenPoint)),{pagePoint:s,shiftKey:i.shiftKey,altKey:i.altKey,accelKey:i.accelKey,ctrlKey:i.ctrlKey}):null}function Gs(e,t){const n=(e=>{const t=e.inputs.state.get();return"dragging"===t.dragPhase&&t.currentPagePoint?{pagePoint:t.currentPagePoint,shiftKey:t.shiftKey,altKey:t.altKey,accelKey:t.accelKey,ctrlKey:t.ctrlKey}:null})(e);n&&t(n)}function Vs(e,t,n){const i=new Set(n);if(i.has(t))return t;const s=js(e,t);for(const r of s)if(i.has(r.ancestorId))return r.childId;const o=s[0]?.ancestorId;return o&&n.some(t=>((e,t)=>js(e,t)[0]?.ancestorId??null)(e,t)===o)?t:s[s.length-1]?.ancestorId??t}function js(e,t){const n=[];let i=e.shapes.get(t),s=t;const o=new Set([t]);for(;i?.parentId.startsWith("shape:");){const t=i.parentId;if(o.has(t))return n;o.add(t);const r=e.shapes.get(t);if(!r)return n;e.shapes.getUtil(r).isSelectionTransformContainer(r)&&n.push({ancestorId:r.id,childId:s}),s=r.id,i=r}return n}function Qs({shiftKey:e,accelKey:t}){return e||t}function Zs({ctrlKey:e}){return e}function Js(e){let t=e;for(;t<=-Math.PI;)t+=2*Math.PI;for(;t>Math.PI;)t-=2*Math.PI;return t}function eo(e,t){return Math.round(e/t)*t}function to(e,t,n,i,s,o,r,a,d,c,l,h){const p=no(c,l),u=so({point:t.localBounds.center,startBounds:n,scaleX:s,scaleY:o,handleId:r,isResizingFromCenter:d}),g=(({bounds:e,fromBounds:t,toBounds:n})=>{const i=Hn({point:new Lr(e.minX,e.minY),fromBounds:t,toBounds:n}),s=Hn({point:new Lr(e.maxX,e.maxY),fromBounds:t,toBounds:n});return new zr(Math.min(i.x,s.x),Math.min(i.y,s.y),Math.abs(s.x-i.x),Math.abs(s.y-i.y))})({bounds:t.localBounds,fromBounds:n,toBounds:i}),f=new zr(u.x-g.w/2,u.y-g.h/2,g.w,g.h),m=$n(u,p),S=e.shapes.getUtil(t.pageShape),y=qn(t.pageShape.rotation,l),I=null!==y,w="perpendicular"===y?new zr(f.center.x-f.h/2,f.center.y-f.w/2,f.h,f.w):f,P=I?w:(()=>{const e=S.getSelectionResizeLocalBounds(t.pageShape),n=(({localWidth:e,localHeight:t,scaleX:n,scaleY:i})=>({width:Math.abs(n)*e,height:Math.abs(i)*t}))({localWidth:e.w,localHeight:e.h,scaleX:t.pageShape.scaleX,scaleY:t.pageShape.scaleY}),i=n.width*Math.abs(s),r=n.height*Math.abs(o);return new zr(m.x-i/2,m.y-r/2,i,r)})(),b=S.resizeSelectionBounds(t.pageShape,{handleId:r,isOnlyResizeTarget:a,pageCenter:m,selectionLocalBounds:P,scaleX:s,scaleY:o,isResizingFromCenter:d,selectionRotation:I?l:t.pageShape.rotation,selectionRotationCenter:I?c:m}),v=mn(e,t.shape,t.pageShape,b);v&&Object.assign(h,v)}function no(e,t){return{rotation:t,rotationCenter:e}}function io(e,t,n,i,s,o,r,a,d,c,l){const h=no(d,c),p=$n(so({point:t.startLocalPagePoint,startBounds:n,scaleX:s,scaleY:o,handleId:r,isResizingFromCenter:a}),h),u=$n(so({point:t.endLocalPagePoint,startBounds:n,scaleX:s,scaleY:o,handleId:r,isResizingFromCenter:a}),h),g=t.middleLocalPagePoint?$n(so({point:t.middleLocalPagePoint,startBounds:n,scaleX:s,scaleY:o,handleId:r,isResizingFromCenter:a}),h):void 0,f=e.shapes.getUtil(t.pageShape).updateSelectionPagePoints(t.pageShape,{pagePoints:[p,u],pageMiddlePoint:g}),m=mn(e,t.shape,t.pageShape,f);m&&Object.assign(l,m)}function so({point:e,startBounds:t,scaleX:n,scaleY:i,handleId:s,isResizingFromCenter:o}){const r=(({startBounds:e,handleId:t,isResizingFromCenter:n})=>n?e.center.x:Oi(t)?e.maxX:Li(t)?e.minX:e.center.x)({startBounds:t,handleId:s,isResizingFromCenter:o}),a=(({startBounds:e,handleId:t,isResizingFromCenter:n})=>n?e.center.y:zi(t)?e.maxY:_i(t)?e.minY:e.center.y)({startBounds:t,handleId:s,isResizingFromCenter:o});return new Lr(r+(e.x-r)*n,a+(e.y-a)*i)}function oo(e,t,n,i,s){const o=t.localBounds.center,r=Nn(new Lr(t.pageShape.x+o.x,t.pageShape.y+o.y),{rotation:i,rotationCenter:n}),a=mn(e,t.shape,t.pageShape,{id:t.shape.id,x:r.x-o.x,y:r.y-o.y,rotation:t.rotation+i});a&&Object.assign(s,a)}function ro(e,t,n,i,s){const o=e.shapes.getUtil(t.pageShape).updateSelectionPagePoints(t.pageShape,{pagePoints:[Nn(t.startPagePoint,{rotation:i,rotationCenter:n}),Nn(t.endPagePoint,{rotation:i,rotationCenter:n})],pageMiddlePoint:t.middlePagePoint?Nn(t.middlePagePoint,{rotation:i,rotationCenter:n}):void 0}),r=mn(e,t.shape,t.pageShape,o);r&&Object.assign(s,r)}function ao(e,t){let n=null;for(const i of t){const t=e.shapes.get(i);if(!t)return null;if(n){if(t.parentId!==n)return null}else n=t.parentId}return n}function co(e,t,n){const i=n?e.layers.getContainingParentIdAtPoint(t,n):e.layers.getContainingParentId(t);if(!i)return null;const s=ao(e,t);if(!s||!s.startsWith("shape:")||i===s)return i;const o=e.shapes.get(s);return o&&e.shapes.getUtil(o).canReceiveChildren(o)?e.shapes.getUtil(o).canAutomaticallyReceiveChildren(o)?n?i:t.every(t=>{const n=e.layers.getContainment(o.id,t);return"inside"===n||"intersecting"===n})?s:i:s:i}function lo(e,t,n){const i=co(e,t,n);i&&t.some(t=>e.shapes.get(t)?.parentId!==i)&&e.commands.reparentShapes({ids:[...t],parentId:i})}function ho(e,t,n,i={}){let s=!0;return t.graph.effect(e,()=>{t.get(),s&&!1===i.fireImmediately?s=!1:(s=!1,n())})}function po(){const e=pr(ed);if(!e)throw new Error("useEditor must be used within EditorContext.Provider");return e}function uo({children:e,className:t,dataUi:n}){const i=po(),s=Sr(null);return fr(()=>ho("PageSpace.transform",i.state.pageTransform,()=>{const e=s.current;e&&(e.style.transform=i.state.pageTransform.get().toCssString())}),[i]),Pr("div",{ref:s,"data-ui":n,className:t,style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",transformOrigin:"0 0"},children:e})}function go(e){const t=new Set,n=new Map,i=new Set,s=new Map,o=[],r=new Set,a=new Map,d=new Map,c=[],l=new Set,h=[],p=new Set;for(const y of e){mo(t,y.id,"canvas render plugin id");for(const e of y.shapeRenderers??[])fo(n,e.type,e,"shape renderer type");for(const e of y.shapeDecorations??[]){mo(i,e.id,"shape decoration id");const t=s.get(e.subType)??[];t.push(e),s.set(e.subType,t)}for(const e of y.shapeOpacityModifiers??[])mo(r,e.id,"shape opacity modifier id"),o.push(e);for(const e of y.canvasOverlays??[])fo(a,e.id,e,"canvas overlay id");for(const e of y.selectionCustomHandleRenderers??[])fo(d,e.type,e,"selection handle renderer type");for(const e of y.domEventGuards??[])mo(l,e.id,"DOM event guard id"),c.push(e);for(const e of y.canvasComponents??[])mo(p,e.id,"canvas component id"),h.push(e)}const u=Object.freeze([...a.values()].sort(So));for(const[y,I]of s)s.set(y,Object.freeze([...I]));const g=Object.freeze([]),f=Object.freeze({getShapeRenderer:e=>n.get(e)??null,getShapeDecorations:e=>null===e?g:s.get(e)??g,getShapeOpacityValue(e,t){const n=o.map(n=>n.getOpacityValue(e,t));return Object.freeze({graph:e.signals,get:()=>n.reduce((e,t)=>e*t.get(),1)})}}),m=Object.freeze({getCanvasOverlays:()=>u,getSelectionCustomHandleRenderer:e=>d.get(e)??null}),S=Object.freeze({handle(e){for(const t of c)if("handled"===t.handle(e))return"handled";return"continue"},getCursor(e){for(const t of c){const n=t.getCursor?.(e);if(void 0!==n)return n}}});return Object.freeze({canvasComponents:Object.freeze(h),renderers:f,overlays:m,domEventGuards:S})}function fo(e,t,n,i){if(e.has(t))throw new Error(`Duplicate ${i}: ${t}.`);e.set(t,n)}function mo(e,t,n){if(e.has(t))throw new Error(`Duplicate ${n}: ${t}.`);e.add(t)}function So(e,t){return(e.order??0)-(t.order??0)}function yo(){return pr(td)}function Io(){return yo().renderers}function wo(){return yo().overlays}function Po(e){const t=hr(t=>ho("useValue",e,t,{fireImmediately:!1}),[e]),n=hr(()=>e.get(),[e]);return Ir(t,n,n)}function bo({children:e,clipAncestorIds:t,shapeElementToPage:n}){return 0===t.length?Pr(wr,{children:e}):t.reduceRight((e,t)=>Pr(vo,{ancestorId:t,shapeElementToPage:n,children:e},t),e)}function vo({ancestorId:e,children:t,shapeElementToPage:n}){const i=po(),s=Po(i.shapes.getSignal(e));if(!s)return Pr(wr,{children:t});const o=((e,t,n)=>{const i=e.shapes.getUtil(t).getChildClipLocalPolygons(t);if(!i)return null;const s=e.shapes.computeRenderToPageTransform(t),o=n.tryInvert();if(!o)return null;const r=i.filter(e=>e.length>=3).map(e=>e.map(e=>o.applyToPoint(s.applyToPoint(e)))).filter(e=>e.every(e=>Number.isFinite(e.x)&&Number.isFinite(e.y)));return 0===r.length?null:1===r.length?`polygon(${r[0].map(Co).join(", ")})`:`path("${r.map(xo).join(" ")}")`})(i,s,n);return o?Pr("div",{"data-ui":"shape-clip-boundary","data-clip-ancestor-id":e,style:{position:"absolute",inset:0,width:"100%",height:"100%",clipPath:o,WebkitClipPath:o,overflow:"visible"},children:t}):Pr(wr,{children:t})}function xo(e){return e.map((e,t)=>`${0===t?"M":"L"} ${Mo(e.x)} ${Mo(e.y)}`).concat("Z").join(" ")}function Co(e){return`${Mo(e.x)}px ${Mo(e.y)}px`}function Mo(e){return Number.isFinite(e)?Number(e.toFixed(3)).toString():"0"}function To({Component:e,editor:t,shape:n}){
2
- return Pr("div",{"aria-hidden":"true","data-ui":"shape-hover-decoration",style:{position:"absolute",inset:0,pointerEvents:"none"},children:Pr(e,{shape:n,editor:t,strokeWidth:2/Po(t.state.cameraZoom)})})}function Bo(e,t,n){const i=e.shapes.computeRenderBounds(t),s=n.compose(Wr.Translate(i.x,i.y));return{left:0,top:0,width:i.w,height:i.h,transform:s.toCssString(),transformOrigin:"0 0",elementToPage:s}}function ko(){
3
- return Pr("div",{"data-ui":"shape-drop-target-label",style:{position:"absolute",left:10,top:10,display:"flex",alignItems:"center",height:24,padding:"0 10px",borderRadius:999,background:"#2563eb",color:"white",fontFamily:"Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:12,fontWeight:700,lineHeight:"24px",boxShadow:"0 10px 24px rgba(37, 99, 235, 0.24)",whiteSpace:"nowrap",pointerEvents:"none"},children:"Drop into container"})}function Eo(e,t,n){const i=new Set;let s=t.parentId;for(;s.startsWith("shape:");){const t=s;if(t===e)return!0;if(i.has(t))return!1;i.add(t);const o=n.get(t);if(!o)return!1;s=o.parentId}return!1}function Ao(){
4
- return Pr("div",{"data-ui":"shape-layer",className:"land-canvas__shape-layer",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%"},children:Pr(uo,{dataUi:"shape-page-space",className:"land-canvas__shape-page-space",children:Pr(ad,{})})})}function Ro(e,t){return"binding-preview"===e?{underlay:{"data-binding-preview-segment-underlay":t},segment:{"data-binding-preview-segment":t}}:"terminal-binding-guide"===e?{underlay:{"data-terminal-binding-guide-underlay":t},segment:{"data-terminal-binding-guide":t}}:{underlay:{"data-selection-binding-segment-underlay":t},segment:{"data-selection-binding-segment":t}}}function Ko({start:e,end:t,startInset:n,endInset:i,strokeWidth:s,dashSize:o,gapSize:r,kind:a,terminal:d}){const c=(({start:e,end:t,startInset:n,endInset:i})=>{const s=t.x-e.x,o=t.y-e.y,r=Math.hypot(s,o);if(r<1e-6)return null;const a=Math.max(0,r/2-.001),d=Math.min(n,a),c=Math.min(i,a),l=s/r,h=o/r;return{start:{x:e.x+l*d,y:e.y+h*d},end:{x:t.x-l*c,y:t.y-h*c}}})({start:e,end:t,startInset:n,endInset:i});if(!c)return null;const l=Ro(a,d);
5
- return br("g",{style:{pointerEvents:"none"},children:[Pr("line",{...l.underlay,x1:c.start.x,y1:c.start.y,x2:c.end.x,y2:c.end.y,fill:"none",stroke:cd,strokeLinecap:"round",strokeWidth:2.2*s}),Pr("line",{...l.segment,x1:c.start.x,y1:c.start.y,x2:c.end.x,y2:c.end.y,fill:"none",stroke:dd,strokeDasharray:`${o} ${r}`,strokeLinecap:"round",strokeWidth:s})]})}function Yo({path:e,strokeWidth:t,dashSize:n,gapSize:i,kind:s,terminal:o}){const r=Ro(s,o);
6
- return br("g",{style:{pointerEvents:"none"},children:[Pr("path",{...r.underlay,d:e,fill:"none",stroke:cd,strokeLinecap:"round",strokeWidth:2.2*t}),Pr("path",{...r.segment,d:e,fill:"none",stroke:dd,strokeDasharray:`${n} ${i}`,strokeLinecap:"round",strokeWidth:t})]})}function Xo({editor:e,shape:t,stroke:n,fill:i,strokeWidth:s}){const o=e.shapes.getPageOutlineVertices(t.id);return 0===o.length?null:Pr("polygon",{points:o.map(e=>`${e.x},${e.y}`).join(" "),fill:i,stroke:n,strokeWidth:s,strokeLinejoin:"round",strokeLinecap:"round"})}function Fo({frame:e,handleId:t,zoom:n}){const i=((e,t)=>{const{bounds:n}=e;switch(t){case"top":return{x1:n.minX,y1:n.minY,x2:n.maxX,y2:n.minY};case"right":return{x1:n.maxX,y1:n.minY,x2:n.maxX,y2:n.maxY};case"bottom":return{x1:n.minX,y1:n.maxY,x2:n.maxX,y2:n.maxY};case"left":return{x1:n.minX,y1:n.minY,x2:n.minX,y2:n.maxY};default:return null}})(e,t);return i?Pr("line",{"data-selection-resize-border":t,x1:i.x1,y1:i.y1,x2:i.x2,y2:i.y2,fill:"none",stroke:"transparent",strokeWidth:12/n,strokeLinecap:"butt",style:{cursor:Do(t,e.rotation),pointerEvents:"stroke"}}):null}function Do(e,t){const n=(((e=>{switch(e){case"top_left":case"bottom_right":return Math.PI/4;case"top":case"bottom":return Math.PI/2;case"top_right":case"bottom_left":return 3*Math.PI/4;case"right":case"left":return 0}})(e)+t)%Math.PI+Math.PI)%Math.PI/(Math.PI/4);return Pd[Math.round(n)%Pd.length]??"default"}function Oo({handle:e,strokeWidth:t}){
7
- return Pr("rect",{"data-selection-custom-handle":e.id,"data-selection-custom-handle-type":e.type,"data-selection-custom-handle-id":e.id,"data-selection-custom-handle-visual":"default",x:e.bounds.x,y:e.bounds.y,width:e.bounds.w,height:e.bounds.h,rx:3,ry:3,fill:"rgba(255,255,255,0.98)",stroke:"rgba(37, 99, 235, 0.92)",strokeWidth:t,style:{cursor:e.cursor??"grab",pointerEvents:"auto"}})}function Lo({dataPrefix:e,pathStyle:t,stroke:n,strokeWidth:i}){
8
- return br(wr,{children:[Pr("path",{"data-selection-overlay":e,d:t.localPath,fill:"none",stroke:n,strokeWidth:i,strokeDasharray:t.strokeDasharray,strokeLinecap:"round",strokeLinejoin:"round",pointerEvents:"none"}),t.localDecorationPaths.map((t,s)=>Pr("path",{"data-selection-overlay":`${e}-decoration`,d:t,fill:"none",stroke:n,strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round",pointerEvents:"none"},`${s}:${t}`))]})}function zo(e,t){const n=Math.max(e[0],t[0]),i=Math.min(e[1],t[1]);return n<=i?[n,i]:null}function _o(){
9
- return Pr("div",{"data-ui":"overlay-layer",className:"land-canvas__overlay-layer",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",pointerEvents:"none"},children:Pr(uo,{dataUi:"overlay-page-space",className:"land-canvas__overlay-page-space",children:Pr(Rd,{})})})}function $o(e,t){return(e%t+t)%t}function No(){const e=Po(po().state.camera);
10
- return br("svg",{"data-ui":"canvas-grid","aria-hidden":"true",className:"land-canvas__grid",xmlns:"http://www.w3.org/2000/svg",style:{position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"},children:[Pr("defs",{children:Yd.map(({min:t,mid:n,step:i})=>{const s=15*i*e.z,o=((e,t)=>({x:$o(.5-e.x*e.z,t),y:$o(.5-e.y*e.z,t)}))(e,s),r=e.z<n?(a=((e,[t,n],[i,s])=>i+(e-t)/(n-t)*(s-i))(e.z,[t,n],[0,1]),Math.max(0,Math.min(1,a))):1;var a;
11
- return Pr("pattern",{id:`land-canvas-grid-${i}`,width:s,height:s,patternUnits:"userSpaceOnUse",children:Pr("circle",{cx:o.x,cy:o.y,r:1,fill:"var(--land-canvas-grid-minor, var(--canvas-dot))",opacity:r})},i)})}),Yd.map(({step:e})=>Pr("rect",{width:"100%",height:"100%",fill:`url(#land-canvas-grid-${e})`},e))]})}function Uo(e){return e instanceof HTMLElement?e:null}function Ho(e){const t=Uo(e);return!!t&&(!!t.isContentEditable||!!t.closest('[contenteditable="true"]')||t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)}function Wo(e){return(e??("undefined"==typeof document?null:document))?.querySelector(Fd)??null}function qo(e){const t=e?.getRootNode();return t instanceof Document||t instanceof ShadowRoot?Wo(t):Wo()}function Go(e,t,n){const i=n?Wo(n):qo(t);return!!i&&(i.dispatchEvent(new WheelEvent("wheel",{altKey:e.altKey,bubbles:!0,cancelable:!0,clientX:e.clientX,clientY:e.clientY,composed:!0,ctrlKey:e.ctrlKey,deltaMode:e.deltaMode,deltaX:e.deltaX,deltaY:e.deltaY,deltaZ:e.deltaZ,metaKey:e.metaKey,screenX:e.screenX,screenY:e.screenY,shiftKey:e.shiftKey,view:window})),!0)}function Vo(e,t=Wo()){if(!t)return new Lr(e.clientX,e.clientY);const n=t.getBoundingClientRect();return new Lr(e.clientX-n.left,e.clientY-n.top)}function jo(e,t,n){return e.viewport.screenToPage(Vo(t,n))}function Qo(e,t){return{type:"keyboard",name:e,...Jo(t),code:t.code}}function Zo(e,t,n){return e.state.shapeEditingSession.get(),n?null:e.handleEvent(Qo("key_up",t))}function Jo(e){return{key:e.key,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}}function er(e){return"Space"===e.code}function tr(e,t){const n=t.ownerDocument;return e===n||e===n.body||e===n.documentElement||e instanceof Node&&t.contains(e)}function nr(e,t,n,i){return{type:"pointer",name:e,timestamp:t.timeStamp,pointerId:t.pointerId,button:t.button,buttons:t.buttons,pointerType:(s=t.pointerType,"touch"===s||"pen"===s?s:"mouse"),screenPoint:n,pagePoint:i,pressure:t.pressure,shiftKey:t.shiftKey,altKey:t.altKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,accelKey:t.metaKey||t.ctrlKey};var s}function ir(e,t){return new Lr(e.clientX-t.left,e.clientY-t.top)}function sr(e,t){return e instanceof Node&&t.contains(e)}function or(e,t,n,i){return n||"hand"===e&&t?"grabbing":i||"hand"===e?"grab":"select"===e?void 0:"crosshair"}function rr({onContextMenuRequest:e,renderBindings:t,showGrid:n=!1}){const i=po(),{canvasComponents:s,domEventGuards:o}=t,r=Po(i.state.tool).activeToolId,a=Po(i.state.shapeEditing).session,d=Po(i.inputs.isSpacePressed)&&null===a,{containerRef:c,handlers:l,isPointerActive:h,isCameraPanning:p,surfaceCursor:u}=function({activeDomEventGuards:e,activeToolId:t,editor:n,onContextMenuRequest:i,shapeEditingSession:s}){const o=Sr(null),r=Sr(null),a=Sr(null),d=Sr(null),c=Sr(null),l=Sr(null),h=Sr(null),p=Sr(null),u=Sr(null),[g,f]=yr(!1),[m,S]=yr(!1),[y,I]=yr(void 0),w=null!==s;ur(()=>{("select"!==t||w)&&n.interaction.setHoveredShapeId(null)},[t,n,w]);const P=hr(()=>{null!==c.current&&(cancelAnimationFrame(c.current),c.current=null),l.current=null},[]),b=hr(e=>{if(null===a.current)return void P();const t=l.current??e;l.current=e,n.handleEvent({type:"tick",timestamp:e,elapsed:e-t}),c.current=requestAnimationFrame(b)},[n,P]),v=hr(()=>{null===c.current&&(l.current=null,c.current=requestAnimationFrame(b))},[b]),x=hr(()=>{null!==u.current&&(cancelAnimationFrame(u.current),u.current=null),p.current=null},[]),C=hr(()=>{null!==u.current&&(cancelAnimationFrame(u.current),u.current=null);const e=p.current;p.current=null,e&&n.handleEvent({...e,pagePoint:n.viewport.screenToPage(e.screenPoint)})},[n]);return ur(()=>{const i=o.current;if(!i)return;let s=null;const c=()=>{const e=i.getBoundingClientRect(),t={left:e.left,top:e.top};return r.current=t,t},l=()=>r.current??c(),g=()=>{null!==s&&(window.cancelAnimationFrame(s),s=null)},m=({clientPoint:e,target:s})=>{if(g(),!e||null!==a.current||"select"!==t||w)return void n.interaction.setHoveredShapeId(null);const o=i.getBoundingClientRect();if(!sr(s,i)||e.x<o.left||e.x>o.right||e.y<o.top||e.y>o.bottom)return void n.interaction.setHoveredShapeId(null);const r=l(),d=new Lr(e.x-r.left,e.y-r.top),c=n.shapes.hitTest(n.viewport.screenToPage(d));if(!c)return void n.interaction.setHoveredShapeId(null);const h=n.shapes.getUtil(c).getHoverTargetId(c,{editor:n});n.interaction.setHoveredShapeId(n.layers.getOutermostSelectableId(h))},y=()=>{const e=h.current;m({clientPoint:e,target:e?document.elementFromPoint(e.x,e.y):null})},b=()=>{null===s&&(s=window.requestAnimationFrame(()=>{s=null,y()}))},v=(t,s)=>"handled"===e.handle({name:t,event:s,editor:n,container:i}),M=()=>{if(!w)return void I(void 0);const t=h.current;I(t?e.getCursor({clientPoint:t,element:document.elementFromPoint(t.x,t.y),editor:n,container:i}):void 0)},T=(e,t)=>{if(!o.current)return;const i=ir(t,l());n.handleEvent(nr(e,t,i,n.viewport.screenToPage(i)))},B=()=>{n.viewport.setScreenSize({w:i.clientWidth,h:i.clientHeight})};c(),B();const k=e=>{if(!v("key_down",e)){if(n.state.shapeEditingSession.get()){if(Ho(e.target))return;return n.handleEvent(Qo("key_down",e)).claimed?(e.preventDefault(),void e.stopPropagation()):void("Enter"===e.key&&(e.metaKey||e.ctrlKey)&&n.editing.complete("user"))}Ho(e.target)||er(e)&&!tr(e.target,i)||n.handleEvent(Qo("key_down",e)).claimed&&e.preventDefault()}},E=e=>{if(er(e)&&n.inputs.pressedKeyCodes.get().has(e.code)&&!n.state.shapeEditingSession.get())return e.preventDefault(),void Zo(n,e,!1);v("key_up",e)||er(e)&&!tr(e.target,i)||Zo(n,e,Ho(e.target))?.claimed&&e.preventDefault()},A=()=>{C(),a.current=null,d.current=null,f(!1),S(!1),n.interaction.setHoveredShapeId(null),P(),n.handleEvent({type:"cancel",reason:"blur"})},R=e=>{if(v("wheel",e))return;e.preventDefault();const t={x:e.clientX,y:e.clientY};h.current=t;const i=ir(e,l()),s=((e,t,n)=>({type:"wheel",screenPoint:t,pagePoint:n,delta:new Lr(e.deltaX,e.deltaY),shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}))(e,i,n.viewport.screenToPage(i));if(s.ctrlKey)return C(),n.handleEvent(s),void m({clientPoint:t,target:document.elementFromPoint(t.x,t.y)});const o=p.current;p.current=o?{...s,delta:o.delta.add(s.delta)}:s,null===u.current&&(u.current=window.requestAnimationFrame(()=>{u.current=null,C()}))},K=e=>{if(h.current={x:e.clientX,y:e.clientY},m({clientPoint:h.current,target:e.target}),M(),e.pointerId!==a.current){const t=ir(e,l());if(n.inputs.setCurrentPointerPoint({timestamp:e.timeStamp,screenPoint:t,pagePoint:n.viewport.screenToPage(t),shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}),v("pointer_move",e))return;if(!((e,t)=>{const n=t.getBoundingClientRect();return e.clientX>=n.left&&e.clientX<=n.right&&e.clientY>=n.top&&e.clientY<=n.bottom})(e,i)||!sr(e.target,i)||Ho(e.target))return;return void T("pointer_move",e)}const t={clientX:e.clientX,clientY:e.clientY,buttons:e.buttons,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey};var s,o;o=t,(s=d.current)&&s.clientX===o.clientX&&s.clientY===o.clientY&&s.buttons===o.buttons&&s.shiftKey===o.shiftKey&&s.altKey===o.altKey&&s.ctrlKey===o.ctrlKey&&s.metaKey===o.metaKey||(d.current=t,T("pointer_move",e))},Y=(e,t)=>{t.pointerId===a.current&&(a.current=null,d.current=null,f(!1),S(!1),P(),i.hasPointerCapture(t.pointerId)&&i.releasePointerCapture(t.pointerId),T(e,t),"pointer_up"===e?y():n.interaction.setHoveredShapeId(null))},X=()=>{h.current=null,n.interaction.setHoveredShapeId(null),M()},F=e=>{h.current={x:e.clientX,y:e.clientY},window.setTimeout(M,0),e.pointerId===a.current?Y("pointer_up",e):v("pointer_up",e)},D=e=>{h.current={x:e.clientX,y:e.clientY},M(),e.pointerId===a.current?Y("pointer_cancel",e):v("pointer_cancel",e)},O=new ResizeObserver(()=>{c(),B(),b()}),L=()=>{c(),b()},z=n.listen(b);window.addEventListener("keydown",k),window.addEventListener("keyup",E),window.addEventListener("blur",A),window.addEventListener("scroll",L,{passive:!0,capture:!0}),window.addEventListener("pointermove",K,{passive:!0}),window.addEventListener("pointerup",F),window.addEventListener("pointercancel",D),i.addEventListener("pointerleave",X),i.addEventListener("wheel",R,{passive:!1}),O.observe(i);const _=window.requestAnimationFrame(M);return b(),()=>{P(),x(),g(),z(),f(!1),S(!1),n.interaction.setHoveredShapeId(null),window.cancelAnimationFrame(_),window.removeEventListener("keydown",k),window.removeEventListener("keyup",E),window.removeEventListener("blur",A),window.removeEventListener("scroll",L,!0),window.removeEventListener("pointermove",K),window.removeEventListener("pointerup",F),window.removeEventListener("pointercancel",D),i.removeEventListener("pointerleave",X),i.removeEventListener("wheel",R),O.disconnect()}},[e,t,x,n,C,w,P]),{containerRef:o,handlers:{onPointerDown:hr(t=>{const i=o.current;if(!i)return;if(h.current={x:t.clientX,y:t.clientY},2===t.button)return void i.focus();if("handled"===e.handle({name:"pointer_down",event:t.nativeEvent,editor:n,container:i}))return;if(Ho(t.target))return;C(),t.preventDefault(),i.focus(),i.setPointerCapture(t.pointerId);const s=i.getBoundingClientRect();r.current={left:s.left,top:s.top},a.current=t.pointerId,f(!0),S(1===t.button||0===t.button&&n.inputs.isSpacePressed.get()&&!n.state.shapeEditingSession.get()),d.current=null,v();const c=ir(t,r.current);n.interaction.setHoveredShapeId(null),n.handleEvent(nr("pointer_down",t,c,n.viewport.screenToPage(c)))},[e,n,C,v]),onAuxClick:hr(e=>{1!==e.button||Ho(e.target)||(e.preventDefault(),e.stopPropagation())},[]),onContextMenu:hr(e=>{const t=o.current;if(!t||!i||Ho(e.target))return;e.preventDefault(),e.stopPropagation(),C();const s=t.getBoundingClientRect();if(r.current={left:s.left,top:s.top},null!==a.current){const i=a.current;t.hasPointerCapture(i)&&t.releasePointerCapture(i),a.current=null,d.current=null,f(!1),S(!1),P();const s=ir(e,r.current);n.handleEvent({type:"pointer",name:"pointer_cancel",timestamp:e.timeStamp,pointerId:i,button:e.button,buttons:0,pointerType:n.inputs.state.get().pointerType??"mouse",screenPoint:s,pagePoint:n.viewport.screenToPage(s),pressure:0,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey})}if(n.state.shapeEditingSession.get())return;t.focus();const c=ir(e,r.current),l=n.viewport.screenToPage(c),h=n.shapes.hitTest(l);let p;if(h){const e=n.selection.getIds(),t=e.find(e=>e===h.id||n.layers.getDescendantIds(e).includes(h.id))??n.layers.getOutermostSelectableId(h.id),i=e.includes(t);i||n.commands.setSelectedShapeIds([t],{source:"user"}),p={anchor:{screenPoint:c,pagePoint:l},target:{type:"selection",selectedShapeIds:i?e:[t]}}}else p={anchor:{screenPoint:c,pagePoint:l},target:{type:"canvas"}};i(p)},[n,C,i,P])},isPointerActive:g,isCameraPanning:m,surfaceCursor:y}}({activeDomEventGuards:o,activeToolId:r,editor:i,onContextMenuRequest:e,shapeEditingSession:a});
12
- return br("div",{ref:c,"data-ui":Xd,className:"land-canvas__surface",tabIndex:0,style:{position:"relative",width:"100%",height:"100%",overflow:"hidden",touchAction:"none",userSelect:"none",backgroundColor:"var(--land-canvas-bg, var(--canvas-background))",cursor:u??or(r,h,p,d)},...l,children:[n?Pr(No,{}):null,br(td.Provider,{value:t,children:[
13
- Pr(Ao,{}),s.map(({id:e,component:t})=>Pr(t,{},e)),
14
- Pr(_o,{})]})]})}function ar({id:e,selector:t}){return{id:e,handle({event:e}){const n=e.target;return n instanceof Element&&n.closest(t)?"handled":"continue"},getCursor:({element:e})=>e?.closest(t)?"text":void 0}}function dr({editor:e,shape:t,isEditing:n,value:i,fallback:s,bodyWidth:o,bodyHeight:r,renderHeight:a,operationKind:d,editAriaLabel:c,inputAriaLabel:l,dataUi:h,onValueChange:p,leading:u,color:g="var(--land-text-primary, #0f172a)",offsetX:f=-7,editable:m=!0,showBackground:S=!0,showDragHandle:y=!0}){const I=Sr(null),[w,P]=yr(!1),b=Po(e.state.cameraZoom),v=Po(e.shapes.getLocalToPageTransformSignal(t.id)),x=Math.max(b,1e-4),C=(e=>Math.min(1/Math.max(e,1e-4),3.5))(x),M=(e=>{const t=2*Math.PI;return Math.floor(2*((e%t+t)%t+Math.PI/4)/Math.PI%4)})(v?Math.atan2(v.b,v.a):0),T=0===M||2===M?o:r,B=(({bodyHeight:e,bodyWidth:t,side:n})=>{switch(n){case 0:return"";case 1:return`translate(0px, ${e}px) rotate(270deg)`;case 2:return`translate(${t}px, ${e}px) rotate(180deg)`;case 3:return`translate(${t}px, 0px) rotate(90deg)`}})({bodyHeight:r,bodyWidth:o,side:M}),k=/^\s*$/.test(i)?s:i;ur(()=>{const e=I.current;m&&n&&e&&(e.focus(),e.select())},[m,n]);const E=hr(()=>{m&&e.editing.canEditShape(t)&&e.editing.start({shapeId:t.id,entryMode:"selectAll",operationKind:d},"user")},[m,e,d,t]),A=hr(e=>{p(e.currentTarget.value)},[p]),R=hr(t=>{e.editing.complete("user")},[e]),K=hr(t=>{e.editing.setComposition(!0,"system")},[e]),Y=hr(t=>{e.editing.setComposition(!1,"system")},[e]),X=hr(t=>{if(t.stopPropagation(),!t.nativeEvent.isComposing)return"Enter"===t.key?(t.preventDefault(),void e.editing.complete("user")):void("Escape"===t.key&&(t.preventDefault(),e.editing.cancel("user")))},[e]),F=hr(e=>{e.stopPropagation()},[]),D=hr(e=>{e.stopPropagation(),n||E()},[n,E]);
15
- return Pr("div",{style:{height:0,left:0,overflow:"visible",pointerEvents:"none",position:"absolute",top:a,width:0},children:Pr("div",{"data-ui":h.heading,"data-shape-id":t.id,style:{alignItems:"center",bottom:0,display:"flex",fontFamily:Dd,fontSize:12,fontWeight:400,maxWidth:T*x+24,minWidth:32,overflow:"visible",paddingBottom:4,pointerEvents:t.isLocked?"none":"auto",position:"absolute",transform:`${B} scale(${C}) translateX(${f}px)`,transformOrigin:"0 100%",userSelect:"none",whiteSpace:"pre"},children:br("div",{style:{alignItems:"center",background:S?"var(--land-canvas-bg, white)":"transparent",borderRadius:S?4:0,boxShadow:S?"inset 0 0 0 1px var(--land-canvas-bg, white)":"none",color:g,cursor:m?void 0:"grab",display:"flex",height:24,pointerEvents:"auto",width:"100%"},children:[y?Pr("div",{"aria-hidden":"true","data-ui":h.dragHandle,onPointerEnter:()=>P(!0),onPointerLeave:()=>P(!1),style:{alignItems:"center",backgroundColor:w?"rgba(37, 99, 235, 0.12)":"transparent",borderRadius:4,boxShadow:w?"inset 0 0 0 1px rgba(37, 99, 235, 0.28)":"none",cursor:"grab",display:"flex",flex:"0 0 28px",height:28,justifyContent:"center",pointerEvents:"auto",transition:"background-color 120ms ease, box-shadow 120ms ease"},children:br("svg",{width:"10",height:"14",viewBox:"0 0 10 14",fill:"currentColor",children:[
16
- Pr("circle",{cx:"3",cy:"3",r:"1"}),
17
- Pr("circle",{cx:"7",cy:"3",r:"1"}),
18
- Pr("circle",{cx:"3",cy:"7",r:"1"}),
19
- Pr("circle",{cx:"7",cy:"7",r:"1"}),
20
- Pr("circle",{cx:"3",cy:"11",r:"1"}),
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.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
- 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
- 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
- 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:[
26
- Pr(sd,{Component:w,shape:i,editor:n,isSelected:h,shapeEditingSession:p}),b.map(e=>Pr(sd,{Component:e.component,shape:i,editor:n,isSelected:h,shapeEditingSession:p},e.id)),v&&P?Pr(To,{Component:P,editor:n,shape:i}):null]}):null,d&&g?Pr(ko,{}):null]})}),ad=lr(()=>{const e=po();return((e,t,n)=>{const i=[],s=[],o=new Map(t.map(e=>[e.id,e]));for(const r of e){const e=o.get(r);if(e){for(;s.length>0&&!Eo(s[s.length-1],e,o);)i.push({layer:"foreground",shapeId:s.pop()});i.push({layer:"shape",shapeId:r}),n.getShapeRenderer(e.type)?.foregroundComponent&&s.push(r)}}for(;s.length>0;)i.push({layer:"foreground",shapeId:s.pop()});return i})(Po(e.render.viewport.retainedShapeIds),Po(e.state.currentPageShapeTree),Io()).map((e,t)=>"shape"===e.layer?Pr(rd,{shapeId:e.shapeId,stackingOrder:t},e.shapeId):Pr(od,{shapeId:e.shapeId,stackingOrder:t},`${e.shapeId}:foreground`))}),dd="rgba(100, 116, 139, 0.82)",cd="rgba(255, 255, 255, 0.84)",ld=lr(()=>Po(po().render.interaction.bindingPreviewActive)?Pr(hd,{}):null),hd=lr(()=>{const e=po(),t=Po(e.render.interaction.bindingPreview),n=Po(e.render.interaction.terminalBindingGuides);if(!t)return null;const i=n.some(e=>e.terminal===t.terminal&&e.targetShapeId===t.targetShapeId);
27
- return br(wr,{children:[Pr(pd,{targetShapeId:t.targetShapeId}),Pr(ud,{bindingPreview:t,showGuide:!i})]})}),pd=lr(({targetShapeId:e})=>{const t=po(),n=Po(t.state.cameraZoom),i=Po(t.shapes.getSignal(e));return i?Pr(Xo,{editor:t,shape:i,stroke:"rgba(14, 165, 233, 0.78)",fill:"rgba(14, 165, 233, 0.08)",strokeWidth:2/n}):null}),ud=lr(({bindingPreview:e,showGuide:t})=>{const n=Po(po().state.cameraZoom),i=2/n,s=6/n,o=4/n;
28
- return br(wr,{children:[t?e.guidePath?Pr(Yo,{path:e.guidePath,strokeWidth:i,dashSize:s,gapSize:o,kind:"binding-preview",terminal:e.terminal}):Pr(Ko,{start:e.rawPagePoint,end:e.resolvedPagePoint,startInset:8/n,endInset:6/n,strokeWidth:i,dashSize:s,gapSize:o,kind:"binding-preview",terminal:e.terminal}):null,
29
- Pr("circle",{"data-binding-preview-point":"raw",cx:e.rawPagePoint.x,cy:e.rawPagePoint.y,r:6,fill:"rgba(255,255,255,0.96)",stroke:"rgba(14, 165, 233, 0.8)",strokeWidth:2}),
30
- Pr("circle",{"data-binding-preview-point":"resolved",cx:e.resolvedPagePoint.x,cy:e.resolvedPagePoint.y,r:7,fill:"rgba(14, 165, 233, 0.18)",stroke:"rgba(2, 132, 199, 0.9)",strokeWidth:2})]})}),gd=lr(()=>Po(po().render.interaction.brushBoxActive)?Pr(fd,{}):null),fd=lr(()=>{const e=Po(po().render.interaction.brushBox);return e?Pr("rect",{"data-ui":"brush-box-overlay",x:e.x,y:e.y,width:e.w,height:e.h,fill:"rgba(59, 130, 246, 0.14)",stroke:"rgba(37, 99, 235, 0.92)",strokeDasharray:"4 3",strokeWidth:1}):null}),md=lr(()=>{const e=po(),t=Po(e.render.overlay.frameGeometry),n=Po(e.render.overlay.companionFrameGeometries);return t||0!==n.length?br(wr,{children:[t?Pr(Sd,{frameGeometry:t}):null,n.map((e,t)=>Pr(Sd,{frameGeometry:e},`companion-${t}`))]}):null}),Sd=lr(({frameGeometry:e})=>{const t=Po(po().render.overlay.frameStyle),{bounds:n,rotation:i,rotationCenter:s}=e,{cornerRadius:o,strokeWidth:r}=t,a=r/2,d=180*i/Math.PI;
31
- return Pr("g",{transform:0===i?void 0:`rotate(${d} ${s.x} ${s.y})`,children:Pr("rect",{"data-selection-overlay":"bounds",x:n.x-a,y:n.y-a,width:n.w+r,height:n.h+r,rx:o+a,ry:o+a,fill:"none",stroke:"rgba(37, 99, 235, 0.88)",strokeWidth:r})})}),yd=new Set(["top_left","top_right","bottom_right","bottom_left"]),Id=lr(()=>{const e=po(),t=Po(e.state.readonly),n=Po(e.render.overlay.handleAnchors);return t||!n?null:Pr(wd,{anchors:n})}),wd=lr(({})=>{const e=po(),t=Po(e.render.overlay.handles),n=Po(e.render.overlay.frameGeometry),i=wo(),s=Po(e.state.cameraZoom);if(!t)return null;const{resizeHandles:o,rotateHandles:r,strokeWidth:a,terminalHandles:d,middleHandles:c,customHandles:l}=t,h=o.filter(e=>yd.has(e.id)),p=o.filter(e=>!yd.has(e.id)),u=n?.rotation??0,g=180*u/Math.PI;
32
- return br(wr,{children:[n?Pr("g",{transform:n&&0!==u?`rotate(${g} ${n.rotationCenter.x} ${n.rotationCenter.y})`:void 0,children:p.map(e=>Pr(Fo,{frame:n,handleId:e.id,zoom:s},e.id))}):null,h.map(e=>Pr("rect",{"data-selection-resize-handle":e.id,x:e.bounds.x,y:e.bounds.y,width:e.bounds.w,height:e.bounds.h,rx:2/s,ry:2/s,fill:"rgba(255,255,255,0.98)",stroke:"rgba(37, 99, 235, 0.92)",strokeWidth:a,style:{cursor:Do(e.id,u),pointerEvents:"auto"}},e.id)),r.map(e=>br("g",{"data-selection-rotate-handle":e.id,transform:`translate(${e.bounds.center.x-6/s} ${e.bounds.center.y-6/s}) scale(${.6/s})`,fill:"none",stroke:"rgba(37, 99, 235, 0.96)",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",children:[Pr("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),Pr("path",{d:"M21 3v5h-5"})]},e.id)),d.map(e=>Pr("circle",{"data-selection-terminal":e.terminal,cx:e.bounds.center.x,cy:e.bounds.center.y,r:Math.min(e.bounds.w,e.bounds.h)/2,fill:"rgba(255,255,255,0.98)",stroke:"rgba(37, 99, 235, 0.92)",strokeWidth:a,style:{cursor:"grab",pointerEvents:"auto"}},e.terminal)),c.map(e=>Pr("rect",{"data-selection-binding-middle":"true",x:e.bounds.x,y:e.bounds.y,width:e.bounds.w,height:e.bounds.h,rx:2,ry:2,fill:"rgba(255,255,255,0.98)",stroke:"rgba(37, 99, 235, 0.92)",strokeWidth:a,transform:`rotate(45 ${e.bounds.center.x} ${e.bounds.center.y})`,style:{cursor:"grab",pointerEvents:"auto"}},"middle")),l.map(e=>{const t=i.getSelectionCustomHandleRenderer(e.type);
33
- return Pr(t?t.component:Oo,{handle:e,strokeWidth:a},`${e.type}:${e.id}`)})]})}),Pd=["ew-resize","nwse-resize","ns-resize","nesw-resize"],bd=1e-6,vd=lr(()=>{const e=po(),t=Po(e.render.overlay.path),n=Po(e.render.overlay.pageClipPath),i=Po(e.render.overlay.bindingSegments),s=Po(e.render.overlay.selectedShapeItems),o=Po(e.render.overlay.frameStyle),r=gr().replace(/[^a-zA-Z0-9_-]/g,"-"),a=`selection-content-clip-${r}`,d=`selection-path-halo-${r}`,c=1===s.length?s[0]?.pathStyle??null:null,l=c?((e,t)=>{const n=e.localToPage.getMaximumLinearScale(),i=n>bd?Math.abs(e.localToPage.determinant())/n:0;return e.strokeWidth+2*t/(i>bd?i:n>bd?n:1)})(c,o.strokeWidth):null,h=c&&null!==l?c.localBounds.expand(l):null;return t?br(wr,{children:[
34
- Pr(xd,{bindingSegments:i,strokeWidth:o.strokeWidth}),n||c&&h?br("defs",{children:[n?Pr("clipPath",{id:a,clipPathUnits:"userSpaceOnUse",children:Pr("path",{d:n,clipRule:"evenodd",fillRule:"evenodd"})}):null,c&&null!==l&&h?br("mask",{id:d,maskUnits:"userSpaceOnUse",maskContentUnits:"userSpaceOnUse",x:h.x,y:h.y,width:h.w,height:h.h,children:[Pr(Lo,{dataPrefix:"path-halo-mask-outer",pathStyle:c,stroke:"white",strokeWidth:l}),Pr(Lo,{dataPrefix:"path-halo-mask-center",pathStyle:c,stroke:"black",strokeWidth:c.strokeWidth})]}):null]}):null,
35
- Pr("g",{"data-selection-overlay":"lines",clipPath:n?`url(#${a})`:void 0,children:c&&null!==l?Pr("g",{"data-selection-overlay":"path-halo-transform",transform:c.localToPage.toSvgString(),children:Pr("g",{mask:`url(#${d})`,children:Pr(Lo,{dataPrefix:"path-halo",pathStyle:c,stroke:"rgba(37, 99, 235, 0.45)",strokeWidth:l})})}):br(wr,{children:[Pr("path",{"data-selection-overlay":"path-underlay",d:t,fill:"none",stroke:"rgba(255,255,255,0.92)",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2*o.strokeWidth}),Pr("path",{"data-selection-overlay":"path",d:t,fill:"none",stroke:"rgba(37, 99, 235, 0.88)",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:o.strokeWidth})]})})]}):null}),xd=lr(({bindingSegments:e,kind:t="selection-binding",strokeWidth:n})=>{if(0===e.length)return null;const i=3*n,s=2*n,o=4*n,r=3*n;
36
- return Pr(wr,{children:e.map(e=>e.guidePath?Pr(Yo,{path:e.guidePath,strokeWidth:n,dashSize:i,gapSize:s,kind:t,terminal:e.terminal},e.terminal):Pr(Ko,{start:e.anchorPagePoint,end:e.boundaryPagePoint,startInset:o,endInset:r,strokeWidth:n,dashSize:i,gapSize:s,kind:t,terminal:e.terminal},e.terminal))})}),Cd=lr(()=>Po(po().render.interaction.selectionTranslationActive)?null:br(wr,{children:[
37
- Pr(vd,{}),
38
- Pr(md,{}),
39
- Pr(Id,{})]})),Md="rgba(37, 99, 235, 0.9)",Td=lr(()=>{const e=po(),t=Po(e.state.readonly),n=Po(e.render.interaction.snapIndicators);return t||0===n.length?null:Pr(Bd,{indicators:n})}),Bd=lr(({indicators:e})=>{const t=Po(po().state.cameraZoom);
40
- return Pr(wr,{children:e.map(e=>Pr("points"===e.type?kd:Ed,{indicator:e,zoom:t},e.id))})}),kd=lr(({indicator:e,zoom:t})=>{const n=2.5/t,i=1/t,[s,o]=e.line,r=180*e.rotation/Math.PI;
41
- return br("g",{"data-ui":"snap-indicator",transform:0===e.rotation?void 0:`rotate(${r} ${e.rotationCenter.x} ${e.rotationCenter.y})`,children:[Pr("path",{"data-ui":"snap-indicator-line",d:`M ${s.x} ${s.y} L ${o.x} ${o.y}`,fill:"none",stroke:Md,strokeWidth:i,strokeLinecap:"round"}),e.points.map((t,s)=>Pr("path",{"data-ui":"snap-indicator-cross",d:`M ${t.x-n} ${t.y-n} L ${t.x+n} ${t.y+n} M ${t.x-n} ${t.y+n} L ${t.x+n} ${t.y-n}`,fill:"none",stroke:Md,strokeWidth:i,strokeLinecap:"round"},`${e.id}:${s}`))]})}),Ed=lr(({indicator:e,zoom:t})=>{if(0===e.gaps.length)return null;const n="horizontal"===e.direction;let i=[Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY];for(const l of e.gaps){const e=zo(i,[n?l.startEdge[0].y:l.startEdge[0].x,n?l.startEdge[1].y:l.startEdge[1].x]);e&&(i=e);const t=zo(i,[n?l.endEdge[0].y:l.endEdge[0].x,n?l.endEdge[1].y:l.endEdge[1].x]);t&&(i=t)}if(!Number.isFinite(i[0])||!Number.isFinite(i[1]))return null;const s=(i[0]+i[1])/2,o=3.5/t,r=2*o,a=[];for(const{startEdge:l,endEdge:h}of e.gaps)if(n){a.push(`M ${l[0].x} ${s-r} L ${l[1].x} ${s+r}`,`M ${h[0].x} ${s-r} L ${h[1].x} ${s+r}`,`M ${l[0].x} ${s} L ${h[0].x} ${s}`);const e=(l[0].x+h[0].x)/2;a.push(`M ${e} ${s-o} L ${e} ${s+o}`)}else{a.push(`M ${s-r} ${l[0].y} L ${s+r} ${l[1].y}`,`M ${s-r} ${h[0].y} L ${s+r} ${h[1].y}`,`M ${s} ${l[0].y} L ${s} ${h[0].y}`);const e=(l[0].y+h[0].y)/2;a.push(`M ${s-o} ${e} L ${s+o} ${e}`)}const d=180*e.rotation/Math.PI,c=0===e.rotation?void 0:`rotate(${d} ${e.rotationCenter.x} ${e.rotationCenter.y})`;
42
- return Pr("path",{"data-ui":"snap-gap-indicator",d:a.join(" "),transform:c,fill:"none",stroke:Md,strokeWidth:1/t,strokeLinecap:"round",strokeLinejoin:"round"})}),Ad=lr(()=>{const e=po(),t=Po(e.render.interaction.terminalBindingGuides),n=Po(e.render.overlay.frameStyle);return 0===t.length?null:Pr(xd,{bindingSegments:t,kind:"terminal-binding-guide",strokeWidth:n.strokeWidth})}),Rd=lr(()=>br("svg",{width:"100%",height:"100%",style:{display:"block",width:"100%",height:"100%",overflow:"visible"},children:[
43
- Pr("style",{children:'\n [data-selection-terminal],\n [data-selection-binding-middle],\n [data-selection-custom-handle-visual="default"] {\n transition: fill 120ms ease, stroke 120ms ease;\n }\n [data-selection-terminal]:hover,\n [data-selection-binding-middle]:hover,\n [data-selection-custom-handle-visual="default"]:hover {\n fill: rgba(219, 234, 254, 0.98);\n stroke: rgba(29, 78, 216, 0.98);\n }\n [data-selection-terminal]:active,\n [data-selection-binding-middle]:active,\n [data-selection-custom-handle]:active {\n cursor: grabbing;\n }\n '}),
44
- Pr(Td,{}),
45
- Pr(Ad,{}),
46
- Pr(ld,{}),
47
- Pr(gd,{}),
48
- Pr(Cd,{}),
49
- Pr(Kd,{})]})),Kd=lr(()=>{const e=wo().getCanvasOverlays();return 0===e.length?null:Pr(wr,{children:e.map(({id:e,component:t})=>Pr(t,{},e))})}),Yd=[{min:-1,mid:.15,step:64},{min:.05,mid:.375,step:16},{min:.15,mid:1,step:4},{min:.7,mid:2.5,step:1}],Xd="canvas-surface",Fd=`[data-ui="${Xd}"]`,Dd=["Inter","ui-sans-serif","system-ui","-apple-system","BlinkMacSystemFont","'Segoe UI'","sans-serif"].join(", ");export{X as A,ed as C,Ka as D,Ja as E,z as F,L as I,Ar as L,O as M,D as N,Us as O,F as P,g as R,uo as S,ho as T,td as _,Fd as a,Io as b,qo as c,Uo as d,Ho as f,Po as g,id as h,Xd as i,Y as j,Ns as k,jo as l,nd as m,ar as n,Go as o,No as p,rr as r,Wo as s,dr as t,Vo as u,wo as v,po as w,go as x,yo as y,p as z};