@yuzhouu/canvas-kit 0.1.15 → 0.1.17
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/_vendor/canvas-core/editor/commands/commandTypes.d.ts +2 -0
- package/_vendor/canvas-core/editor/createEditor.d.ts +1 -1
- package/_vendor/canvas-core/editor/editor.d.ts +7 -2
- package/_vendor/canvas-core/editor/events/interactions.d.ts +1 -0
- package/_vendor/canvas-core/editor/selection/selectionGeometry.d.ts +2 -2
- package/_vendor/canvas-core/editor/state/editorReadModels.d.ts +3 -2
- package/_vendor/canvas-core/editor/state/editorSignals.d.ts +1 -1
- package/_vendor/canvas-core/exports/svg.d.ts +14 -1
- package/_vendor/canvas-core/index.d.ts +6 -2
- package/_vendor/canvas-core/plugins/editorRuntimePlugin.d.ts +6 -1
- package/_vendor/canvas-core/schema/records.d.ts +1 -0
- package/_vendor/canvas-core/shapes/shapeHeading.d.ts +20 -0
- package/_vendor/canvas-core/shapes/shapeHitTestDecoration.d.ts +16 -0
- package/_vendor/canvas-core/shapes/shapeUtil.d.ts +4 -0
- package/_vendor/canvas-extension-contracts/operations.d.ts +18 -0
- package/_vendor/canvas-react/host/ShapeHeadingControl.d.ts +4 -2
- package/_vendor/canvas-react/host/canvasRenderBindings.d.ts +2 -1
- package/_vendor/canvas-react/host/canvasRenderPlugin.d.ts +6 -0
- package/_vendor/canvas-react/host/index.d.ts +1 -1
- package/host-DYfq8ME2.mjs +49 -0
- package/index.d.ts +1 -1
- package/index.mjs +6 -6
- package/package.json +1 -1
- package/plugin-runtime.d.ts +2 -3
- package/plugin-runtime.mjs +1 -1
- package/runtime/canvasKitContracts.d.ts +2 -1
- package/runtime/facade/canvasProductData.d.ts +2 -1
- package/host-VhUj_Gf6.mjs +0 -48
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
function e(){return new wr}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:Mr,typeName:"document",scope:"document",meta:{...e}}}function d(){return{id:Tr,typeName:"page",scope:"document",name:"Page 1",index:"0001",meta:{}}}function c(e=Tr){return{id:Br,typeName:"session",scope:"session",currentPageId:e,activeToolId:"select",isToolLocked:!1,editingShapeId:null,shapeEditingSession:null,pageCameraById:{[e]:{...kr}},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[Er]}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=r.fromId===r.toId?[r.fromId]:[r.fromId,r.toId];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 P({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 b(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 v({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?(w(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.fromId)&&!r.has(h.toId))continue;const t=e.shapes.get(h.fromId),n=e.shapes.get(h.toId);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 w(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 x(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 C(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 Fr(e.x+i.x*r,e.y+i.y*r)})(t,n,e))}function M(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(C(e,n,i),C(t,n,i),C(n,e,t),C(i,e,t))}function T(e){return e.length>=3&&e.every(e=>Number.isFinite(e.x)&&Number.isFinite(e.y))}function B(e){const t=e.filter(T).flatMap(e=>e);return t.length>0?Yr.FromPoints(t):null}function k(e,t){if(!T(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(C(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 E(e,t){return t.some(t=>k(e,t))}function A(e,t,n,i=0){if(!T(n))return!1;if(k(e,n)||k(t,n))return!0;for(let s=0;s<n.length;s+=1)if(M(e,t,n[s],n[(s+1)%n.length])<=Math.max(0,i))return!0;return!1}function R(e){return{kind:"theme",slot:e}}function K(e){return{kind:"custom",value:e}}function F(e){return!!e&&"object"==typeof e&&"theme"===e.kind&&Xr.includes(e.slot)}function Y(e){return!!e&&"object"==typeof e&&"custom"===e.kind&&"string"==typeof e.value}function X(e){return Dr[e]}function D(e){return"custom"===e.kind?e.value:`var(${X(e.slot)}, ${zr[e.slot]})`}function z(e,t){if("custom"===e.kind)return e.value;const n=X(e.slot),i=zr[e.slot];return t?.(n,i)??i}function L(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 O(e,t,n){let i=((e,t)=>{const n=$(e,t),i=e.shapes.computeExportToPageTransform(t);return Yr.FromPoints([new Fr(n.minX,n.minY),new Fr(n.maxX,n.minY),new Fr(n.maxX,n.maxY),new Fr(n.minX,n.maxY)].map(e=>i.applyToPoint(e)))})(e,t);if(!x(i))return i;for(const s of((e,t,n)=>{const i=[];for(const s of _(e,t,n)){const t=U(e,s);t&&x(t)&&i.push(t)}return i})(e,t,n)){const e=W(i,s);if(!e)return null;i=e}return i}function $(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 G(n)}function _(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 N(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||!B(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 Fr(t.minX,t.minY),new Fr(t.maxX,t.minY),new Fr(t.maxX,t.maxY),new Fr(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:H(e),transform:r}})),l=i.addDef({tag:"clipPath",attrs:{clipPathUnits:"userSpaceOnUse"},children:c});return n.set(t.id,l),l}function U(e,t){const n=e.shapes.getUtil(t).getChildExportClipLocalPolygons(t);if(!n||!B(n))return null;const i=e.shapes.computeExportToPageTransform(t);return B(n.map(e=>e.map(e=>i.applyToPoint(e))))}function H(e){return e.map((e,t)=>`${0===t?"M":"L"} ${e.x} ${e.y}`).concat("Z").join(" ")}function W(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 Yr(n,i,s-n,o-i)}function q(e){if("string"==typeof e)return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">");const t=(e=>{const t=[];for(const[n,i]of Object.entries(e))null!=i&&!1!==i&&t.push(`${n}="${V("number"==typeof i?j(i):String(i))}"`);return 0===t.length?"":` ${t.join(" ")}`})(e.attrs??{}),n=e.children?.map(q).join("")??"";return n?`<${e.tag}${t}>${n}</${e.tag}>`:`<${e.tag}${t}/>`}function G(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 Yr(t,n,i-t,s-n)}function V(e){return e.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<").replaceAll(">",">")}function j(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function Q(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 Z(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 J(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function ee(e,t){return Q(e,t,J)}function te(e,t){return Q(e,t,ee)}function ne(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 ie(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))&&Q(e,t,ie);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)&&ie(n[e],i[e]))}function se(e){const t=Wr.get(e);if(!t)throw new Error("Editor record factory is not initialized");return t}function oe(e){const t=Number(e.split(":")[1]??0);return Number.isFinite(t)?t:0}function re(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 ae(e){const t=e.props.assetId;return"string"==typeof t&&t.startsWith("asset:")?t:null}function de(e,t){const n=[],i=new Set;for(const s of t)for(const t of ce(s)){if(i.has(t))continue;const s=e.assets.get(t);s&&(i.add(t),n.push(ge(s)))}return n}function ce(e){const t=[],n=new Set,i=ae(e);return i&&(n.add(i),t.push(i)),le(e.props,n,t),t}function le(e,t,n){if(fe(e))t.has(e)||(t.add(e),n.push(e));else if(Array.isArray(e))for(const i of e)le(i,t,n);else if(e&&"object"==typeof e)for(const i of Object.values(e))le(i,t,n)}function he(e,t){return pe(e,t)}function pe(e,t){if(fe(e))return t.get(e)??e;if(Array.isArray(e))return e.map(e=>pe(e,t));if(!e||"object"!=typeof e)return e;const n={};for(const[i,s]of Object.entries(e))n[i]=pe(s,t);return n}function ue(e){return ge(e)}function ge(e){if(Array.isArray(e))return e.map(ge);if(!e||"object"!=typeof e)return e;const t={};for(const[n,i]of Object.entries(e))t[n]=ge(i);return t}function fe(e){return"string"==typeof e&&e.startsWith("asset:")}function me(e){return void 0!==e&&e<0?-1:1}function Se(e,t){if(void 0===t)return e;const n=2*Math.PI;return e+Math.round((t-e)/n)*n}function ye(e,t){const n=2*Math.PI,i=((e-t+Math.PI)%n+n)%n-Math.PI;return Math.abs(i)}function Ie(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*me(n.preferredScaleYSign);return a({rotation:Se(Math.atan2(-e.c/t,e.d/t),n.preferredRotation),scaleX:0,scaleY:t})}const t=s*me(n.preferredScaleXSign);return a({rotation:Se(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:Se(h,n.preferredRotation),scaleX:p,scaleY:u},{rotation:Se(h+Math.PI,n.preferredRotation),scaleX:-p,scaleY:-u}],f=me(n.preferredScaleXSign),m=me(n.preferredScaleYSign),S=e=>{let t=0;return void 0!==n.preferredScaleXSign&&me(e.scaleX)===f&&(t+=1),void 0!==n.preferredScaleYSign&&me(e.scaleY)===m&&(t+=1),{signMatches:t,rotationDistance:void 0===n.preferredRotation?0:ye(e.rotation,n.preferredRotation)}},y=S(g[0]),I=S(g[1]),P=I.signMatches>y.signMatches||I.signMatches===y.signMatches&&I.rotationDistance<y.rotationDistance?g[1]:g[0];return a({rotation:P.rotation,scaleX:P.scaleX,scaleY:P.scaleY})}function Pe(e,t,n){return n.compose(t.getLocalTransform(e))}function be(e,t,n){return n.compose(t.getPositionedTransform(e))}function ve(e,t,n){return Pe(e,t,n)}function we(e,t,n){return Pe(e,t,n).applyToPoint(t.getLocalBounds(e).center)}function xe(e,t,n,i){const s=be(e,n,i).tryInvert();if(s)return s.applyToPoint(t);const o=n.getLocalBounds(e).center,r=new Fr(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 Fr(0===e.scaleX?0:d.x/e.scaleX,0===e.scaleY?0:d.y/e.scaleY))}function Ce(e,t,n){const i=be(e,t,n);return((e,t)=>t.getPositionedOutlineVertices(e))(e,t).map(e=>i.applyToPoint(e))}function Me(e,t,n){const i=t.getExportBounds(e);return Yr.FromPoints([new Fr(i.minX,i.minY),new Fr(i.maxX,i.minY),new Fr(i.maxX,i.maxY),new Fr(i.minX,i.maxY)].map(e=>n.applyToPoint(e)))}function Te(e,t,n){const i=Ce(e,t,n),s=((e,t,n)=>{const i=t.getLocalBounds(e),s=Pe(e,t,n);return[new Fr(i.minX,i.minY),new Fr(i.maxX,i.minY),new Fr(i.maxX,i.maxY),new Fr(i.minX,i.maxY)].map(e=>s.applyToPoint(e))})(e,t,n);return{bounds:Yr.FromPoints(i),center:we(e,t,n),corners:s,outlineVertices:i}}function Be(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)||Ee(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=Ee(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:2,source:{app:"land"},rootShapeIds:d,records:{shapes:a,bindings:Ae(e,a,r),assets:de(e,a)},bounds:Re(e,o)}}function ke(e,t){const{payload:n}=t;if(!(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"land/clipboard"===t.type&&2===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 Fr(t.x+t.w/2,t.y+t.h/2)):e.offset??Gr})(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=se(e).createAsset({type:t.type,props:ue(t.props),meta:ue(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=he(t.props,r),i=l.has(t.id),d=se(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:ue(t.meta)});return a.set(t.id,d.id),{original:t,draft:d}}).map(({original:e,draft:t})=>({...t,parentId:Ke(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.fromId),n=a.get(s.toId);t&&n&&e.commands.createBinding({type:s.type,fromId:t,toId:n,props:ue(s.props),meta:ue(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 Ee(e,t,n){if(!e.shapes.getUtil(t).canCopyToClipboard(t,{editor:e,copiedShapeIds:n}))return null;const i=ge(t);if(t.parentId.startsWith("shape:")&&n.has(t.parentId))return i;const s=e.shapes.computeLocalBounds(t),o=Ie(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 Ae(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.fromId)&&n.has(t.toId)&&(s.add(t.id),i.push(ge(t)));return i}function Re(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 Yr(t,n,i-t,s-n)})(t.map(t=>e.shapes.getPageBounds(t)).filter(e=>!!e))??new Yr(0,0,0,0);return{x:n.x,y:n.y,w:n.w,h:n.h}}function Ke(e,t,n){return e.startsWith("shape:")?t.get(e)??n:n}function Fe(e,t,n){for(const i of t){const t=e.shapes.get(i);t?.parentId.startsWith("shape:")&&n.add(t.parentId)}}function Ye(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)||Q(a,o)||(e.interaction.setBindingPreview(null),e.interaction.setSnapIndicators(null),e.session.update({pageSelectedShapeIdsById:{...r.pageSelectedShapeIdsById,[i]:o}},s))}function Xe(e,t,n="system"){S(e).put([{...e.session.get(),...t}],n)}function De(e){return e.map((e,t)=>({...e,index:String(t+1).padStart(4,"0")}))}function ze(e,t,n){return Math.abs(e-t)<=n*Math.max(1,Math.abs(e),Math.abs(t))}function Le(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?ze(s,1,n)&&ze(o,1,n):s>n&&o>n&&ze(s,o,n))?null:{shapeId:e.id,shapeType:e.type,policy:i,scaleX:e.scaleX,scaleY:e.scaleY}}function Oe(e){return`Container shape ${e.shapeId} (${e.shapeType}) violates ${e.policy} child transform policy with scale (${e.scaleX}, ${e.scaleY})`}function $e(e,t,n){const i=n.startsWith("shape:")?e.shapes.get(n):null,s=(i?e.shapes.computeLocalToPageTransform(i):$r.Identity()).tryInvert();if(!s)return null;const o=e.shapes.computeLocalToPageTransform(t);return Ie(s.compose(o),e.shapes.computeLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY})}function _e(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 Ne(e,t,n,i=new Set){const s=[...t].sort((t,n)=>Ue(e,n)-Ue(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=He(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=Yr.FromPoints(a),c=s.getResizeToFitDescendantsProps(t,d);if(!c)continue;const l=s.validateProps(c),h={...t,props:l},p=Ie(s.getLocalTransform(t).compose($r.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 Ue(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 He(e,t){return S(e).getAll().filter(p).filter(e=>e.parentId===t).sort((e,t)=>e.index.localeCompare(t.index))}function We(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 qe(e,t){const n=new Set;for(const i of t){const t=e.shapes.get(i);t&&We(e,t,n)}return n}function Ge(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=He(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=He(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,se(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=$e(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;We(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 P=e.selection.getIds();if(P.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(P.flatMap(e=>e===a.id?t:[e]),{source:i})}const b=_e(e,[a.id],{source:i});for(const e of b)n.add(e),s.push(e)}return s}function Ve(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:Je(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)&&Qe(e,n),e.bindings.handleShapeChanges(t.changes,n),((e,t,n)=>{const i=new Set,s=new Set;for(const r of t)We(e,r.before,i),We(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;Ge(e,s,o,n),Ne(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=Le(o,e.shapes.getUtil(o));if(t)throw new Error(Oe(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 Qe(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=>Ze(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 Ze(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 Je(e,t){return"number"==typeof e&&Number.isFinite(e)?Math.min(1,Math.max(0,e)):t}function et(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=He(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=$e(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:se(e).createShapeIndex(i+r+1),...o.get(n.id),meta:a===n.meta?void 0:a}})})(e,t);return!!i&&(0===i.length||Ve(e,i,n),!0)}function tt(e){const t=t=>(e.assertDocumentWriteAllowed(),t()),n=((e,t)=>({createBinding(n,i){const s=i?.source??"user",o=se(e).createBinding(n);if(!e.bindings.canBind(o))throw new Error(`Invalid binding endpoints for ${o.type} binding`);const r=new Set;return Fe(e,[o.fromId,o.toId],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),Fe(e,[o.fromId,o.toId],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),a={...o,fromId:n.fromId??o.fromId,toId:n.toId??o.toId,props:n.props?r.validateProps({...o.props,...n.props}):o.props,meta:n.meta??o.meta};if(!e.bindings.canBind(a))throw new Error(`Invalid binding endpoints for ${a.type} binding`);const d=new Set;return Fe(e,[o.fromId,o.toId,a.fromId,a.toId],d),S(e).atomic(()=>{const n=e.bindings.getConflicting(a).map(e=>e.id);n.length>0&&e.bindings.cleanup(n,s),S(e).put([a],s),e.bindings.syncUpdated(o,a,s),Fe(e,[o.fromId,o.toId,a.fromId,a.toId],d),t(d,new Set,s)},s),a},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)=>{Ge(e,t,n,i)});return{createPage:(n,i)=>t(()=>function(e,t,n){const i=n?.source??"user",s=se(e).createPage(t);let o=s;return S(e).atomic(()=>{const t=De([...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]??{...kr},o=i.pageSelectedShapeIdsById[t]??[];Xe(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=De(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],Xe(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(De(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=>se(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)et(e,{ids:o,parentId:t},n)}const d=qe(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)}Ge(e,t,c,s)}Ne(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),Qe(e,i);const n=qe(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;Ge(e,n,s,i),Ne(e,n,i,s)},i),t.map(t=>e.shapes.get(t.id)).filter(e=>!!e)})(e,n,i)),updateShapes(n,i){t(()=>Ve(e,n,i))},reparentShapes:(n,i)=>t(()=>et(e,n,i)),deleteShapes(n,i){t(()=>function(e,t,n){const i=n?.source??"user",s=e.layers.includeDescendants(t),o=qe(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=ae(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(()=>{_e(e,s,{source:i,afterRemove:()=>{a.length>0&&S(e).remove(a,i),Ge(e,o,r,i),Ne(e,o,i,r)}})},i)}(e,n,i))},createAsset:(n,i)=>t(()=>((e,t,n)=>{const i=n?.source??"user",s=se(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)),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.interaction.cancel("page_switch"),e.editing.complete(i));const s=e.state.session.get();Xe(e,{currentPageId:t,pageCameraById:{...s.pageCameraById,[t]:s.pageCameraById[t]??{...kr}},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)=>{Ye(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),Xe(e,{activeToolId:t},i)})(e,t,n)},setToolLocked(t,n){((e,t,n)=>{const i=n?.source??"system";e.tools.syncLockedState(t),Xe(e,{isToolLocked:t},i)})(e,t,n)}}}function nt(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 it(e,t){return{originScreenPoint:t.clone(),originCamera:e.state.camera.get()}}function st(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 ot(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 rt(e){return{timestamp:e.timestamp,screenPoint:e.screenPoint.clone(),pointerId:e.pointerId,button:e.button,pointerType:e.pointerType}}function at(e,t){return e.pointerId===t.pointerId&&e.button===t.button&&e.pointerType===t.pointerType}function dt(e){return{claimed:"stop"===e?.propagation}}function ct(){return Fr.Zero()}function lt(e,t,n){if(n<=0)return ct();const i=t.x-e.x,s=t.y-e.y;return 0===i&&0===s?ct():new Fr(i/n,s/n)}function ht(e,t){return e.shiftKey===t.shiftKey&&e.altKey===t.altKey&&e.ctrlKey===t.ctrlKey&&e.metaKey===t.metaKey&&e.accelKey===t.accelKey}function pt(e,t){return e.canUndo===t.canUndo&&e.canRedo===t.canRedo}function ut(e){return{added:[...e.added],updated:e.updated.filter(({before:e,after:t})=>!gt(e,t)),removed:[...e.removed]}}function gt(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)=>gt(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)&>(n[e],i[e]))}function ft(e){return JSON.parse(JSON.stringify(e))}function mt(e){return JSON.parse(JSON.stringify(e))}function St(e,t,n){const i=e.get(t);i?i.push(n):e.set(t,[n])}function yt(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 It(e,t){return e.fromId===t.fromId?e.id.localeCompare(t.id):e.fromId.localeCompare(t.fromId)}function Pt(e,t,n){return"to"===e?t.toId===n.toId?t.fromId===n.fromId?t.id.localeCompare(n.id):t.fromId.localeCompare(n.fromId):t.toId.localeCompare(n.toId):It(t,n)}function bt(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 o=i(e[s]);if(o&&Pt(n,t,o)<0)return s}return e.length})(o,n,i,s),0,n.id),e.set(t,r),!0}function vt(e){return g(e.before)&&g(e.after)}function wt(e,t){yt(e.bindingIdsByFromShape,t.fromId,t.id),yt(e.bindingIdsByToShape,t.toId,t.id),yt(e.relatedBindingIdsByShape,t.fromId,t.id),yt(e.relatedBindingIdsByShape,t.toId,t.id)}function xt(e,t){const n=t=>e.bindingById.get(t);bt(e.bindingIdsByFromShape,t.fromId,t,"from",n),bt(e.bindingIdsByToShape,t.toId,t,"to",n),bt(e.relatedBindingIdsByShape,t.fromId,t,"related",n),bt(e.relatedBindingIdsByShape,t.toId,t,"related",n)}function Ct(){return{changesByShape:new Map,cacheByShape:new Map}}function Mt(e,t,n){for(const i of oa)for(const s of Tt(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 Tt(e,t){switch(e){case"from":return[t.fromId];case"to":return[t.toId];case"related":return t.fromId===t.toId?[t.fromId]:[t.fromId,t.toId]}}function Bt(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 kt(e,t){return e===t||(e&&t?ne(e.bounds,t.bounds)&&J(e.center,t.center)&&ee(e.corners,t.corners)&&ee(e.outlineVertices,t.outlineVertices):e===t)}function Et(e){return e?e.clone():e}function At(e){return e?.map(e=>e.clone())}function Rt(e){return e?new $r(e.a,e.b,e.c,e.d,e.e,e.f):void 0}function Kt(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=$r.Identity();for(let a=i.length-1;a>=0;a-=1){const t=i[a];t&&(r=Pe(t,e.shapes.getUtil(t),r))}return r}function Ft(e,t,n){if(t.startsWith("page:"))return e.pages.get(t)?$r.Identity():void 0;const i=n(t);return i?Kt(e,i,n):void 0}function Yt(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&&B(a)&&i.push(r),o=r.parentId}return i.reverse()}function Xt(e,t){return Yr.FromPoints([new Fr(e.minX,e.minY),new Fr(e.maxX,e.minY),new Fr(e.maxX,e.maxY),new Fr(e.minX,e.maxY)].map(e=>t.applyToPoint(e)))}function Dt(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 Yr(n,i,s-n,o-i)}function zt(e,t,n){const i=e.get(t);i?i.push(n):e.set(t,[n])}function Lt(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 Ot(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 $t(e){return p(e.before)&&p(e.after)}function _t(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 Nt(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 Ut(e,t,n){if(n.containsPoint(e)||n.containsPoint(t))return!0;const i=[new Fr(n.minX,n.minY),new Fr(n.maxX,n.minY),new Fr(n.maxX,n.maxY),new Fr(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!==Nt(e,t,n,o))return!0}return!1}function Ht(e,t){return Yr.FromPoints([new Fr(e.minX,e.minY),new Fr(e.maxX,e.minY),new Fr(e.maxX,e.maxY),new Fr(e.minX,e.maxY)].map(e=>t.applyToPoint(e)))}function Wt(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 Fr(o.minX,o.minY),new Fr(o.maxX,o.maxY));return Yr.FromPoints(s)}function qt(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Gt(e,t){return"string"==typeof e?e:t}function Vt(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function jt(e,t){return"boolean"==typeof e?e:t}function Qt(e){return qt(e)?e:{}}function Zt(e){return qt(e)?{x:Vt(e.x,kr.x),y:Vt(e.y,kr.y),z:Math.min(8,Math.max(.1,Vt(e.z,kr.z)))}:null}function Jt(e){return Array.from(new Set((e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[])(e).filter(e=>e.startsWith("shape:"))))}function en(e,t){if(!qt(e))throw new ha(`Invalid ${t} snapshot: expected object`);const n=e.schemaVersion,i=Vt(n,NaN),s="document"===t?3:1;if(i!==s)throw new ha(`Unsupported ${t} snapshot schema version: expected ${s}, received ${String(n)}`);if(!Array.isArray(e.records))throw new ha(`Invalid ${t} snapshot: records must be an array`);return{schemaVersion:i,records:e.records}}function tn(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,P=new Set,b=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),P.delete(e.shape.id),i.pop();continue}const n=e.shape;if(I.has(n.id)){i.pop();continue}if(P.add(n.id),n.parentId.startsWith("page:")){I.set(n.id,u.has(n.parentId)?n.parentId:p),P.delete(n.id),i.pop();continue}const s=S.get(n.parentId);s&&!P.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),P.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 b){const e=Le(a,t.get(a.type));if(e)throw new ha(Oe(e))}const v=((e,t,n,i)=>{const s=new Map(e.map(e=>[e.id,e])),o=t.filter(e=>{const t=s.get(e.fromId),n=s.get(e.toId);if(!t||!n)return!1;const o=i.get(e.type);return!!o.getShapeCompanionRootId&&(o.canUseShapeCompanion?.(e,{fromShape:t,toShape:n})??!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:")&&!nn(s,n,e.parentId,i)){u.length=0;break}const t=n.get(i.type),o=Ie(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]:[]})})(b,r,t,n),w=new Set(v.map(e=>e.id)),x=r.filter(e=>w.has(e.fromId)&&w.has(e.toId));return[i,...l,...c,...v,...x]}function nn(e,t,n,i){const s=e.get(n);return!!s&&t.get(s.type).canReceiveChild(s,i)}function sn(e,t,n){const i=n?.source??"system",s=function(e){const t=en(e,"session").records[0];if(!qt(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(!qt(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,Zt(t)]).filter(e=>null!==e[1]);return Object.fromEntries(t)})(t.pageCameraById),o=(e=>{if(!qt(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,Jt(t)]);return Object.fromEntries(t)})(t.pageSelectedShapeIdsById);return{schemaVersion:1,records:[{...n,id:n.id,typeName:"session",scope:"session",currentPageId:i,activeToolId:Gt(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:Qt(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(),rn(e,[...o,s],i),an(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"),Xe(e,{activeToolId:"select"},t)),e.tools.syncLockedState(i)})(e,i)}function on(e){an(e),se(e).syncCounters()}function rn(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 an(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,re(c,d,o)??s);const g=n.find(e=>e.id===Br),f=u(g)?g:c(s),m={...f,currentPageId:o.has(f.currentPageId)?f.currentPageId:s,pageCameraById:dn(f.pageCameraById,o),pageSelectedShapeIdsById:cn(f.pageSelectedShapeIdsById,o,a,h)};t.put([m],"system")}function dn(e,t){const n={};for(const i of t){const t=e[i]??kr;n[i]={x:Number.isFinite(t.x)?t.x:kr.x,y:Number.isFinite(t.y)?t.y:kr.y,z:Math.min(8,Math.max(.1,Number.isFinite(t.z)?t.z:kr.z))}}return n}function cn(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 ln(e,t){const n=Ie(e.shapes.computeLocalToPageTransform(t),e.shapes.computeLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});return n?{...t,...n}:null}function hn(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):$r.Identity()).tryInvert();if(!a)return null;const d=Ie(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 pn(e,t){return ee(e.outlineVertices,t.outlineVertices)&&ne(e.pageBounds,t.pageBounds)&&ne(e.localBounds,t.localBounds)&&e.rotation===t.rotation&&J(e.rotationCenter,t.rotationCenter)&&J(e.selectionAnchorPagePoint,t.selectionAnchorPagePoint)&&e.hasRotation===t.hasRotation&&e.hasCompatibleRotation===t.hasCompatibleRotation}function un(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)<pa?0:t}function gn(e,t){const n=e.shapes.computeLocalToPageTransform(t);return Math.atan2(n.b,n.a)}function fn(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=ln(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 Yr(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=un(n?gn(e,n):0);return t.every(t=>((e,t)=>{const n=un(e)-un(t),i=Math.PI/2;return Math.abs(n-Math.round(n/i)*i)<pa})(gn(e,t),i))}(e,r),u=((e,t,n)=>{if(0===t.length||!n)return 0;const i=t[0];return un(i?gn(e,i):0)})(e,r,p),g=((e,t)=>t.some(t=>Math.abs(un(gn(e,t)))>pa))(e,r),f=h?.center??null,m=0===s.length?null:Math.abs(u)<pa||!f?Yr.FromPoints(s):Yr.FromPoints(s.map(e=>Fr.RotWith(e,f,-u))),S=o.length>0?Yr.FromPoints(o):null;return{outlineVertices:s,pageBounds:h,localBounds:m,rotation:u,rotationCenter:f,selectionAnchorPagePoint:m&&f?Math.abs(u)<pa?new Fr(m.center.x,m.minY):Fr.RotWith(new Fr(m.center.x,m.minY),f,u):S?new Fr(S.center.x,S.minY):null,hasRotation:g,hasCompatibleRotation:p}}function mn(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 Sn(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 Yr(n,i,s-n,o-i):null}function yn(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 In(e,t){return wn(e,t)}function Pn(e,t){return wn(e,t)}function bn(e,t=e.selection.getIds()){const n=vn(e,t),i=1===n.length;return n.length>0&&n.every(t=>e.shapes.getUtil(t).canParticipateInSelectionFlip(t,{editor:e,isOnlyAffectedShape:i}))}function vn(e,t=e.selection.getIds()){return mn(e,wn(e,t)).map(t=>e.shapes.getSignal(t).get()).filter(e=>!!e)}function wn(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)||yn(e,n.id,i))})}function xn(e){return Math.min(8,Math.max(.1,e))}function Cn(e,t=e.pages.getCurrentId()){return Tn(e,e.shapes.getForPage(t).map(({id:e})=>e))}function Mn(e,t,n){const i=e.state.viewportScreenSize.get();if(i.w<=0||i.h<=0||!x(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=xn(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 Tn(e,t){const n=[];for(const s of t){const t=e.shapes.getPageBounds(s);t&&x(t)&&n.push(new Fr(t.minX,t.minY),new Fr(t.maxX,t.maxY))}if(0===n.length)return null;const i=Yr.FromPoints(n);return x(i)?i:null}function Bn(e,t){const n=kn(e);return n.length>=t&&null!==En(e,n[0].shape.parentId)}function kn(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&&x(t)&&i.push({shape:s,bounds:t})}return i}function En(e,t){const n=t.startsWith("shape:")?e.shapes.get(t):null;return n?e.shapes.computeLocalToPageTransform(n).tryInvert():$r.Identity()}function An(e,t){const n=e.applyToPoint(Fr.Zero());return e.applyToPoint(t).sub(n)}function Rn(e){return{...e,anchorPagePoint:e.anchorPagePoint.clone(),boundaryPagePoint:e.boundaryPagePoint.clone()}}function Kn(e,t){return e.terminal===t.terminal&&J(e.anchorPagePoint,t.anchorPagePoint)&&J(e.boundaryPagePoint,t.boundaryPagePoint)&&(e.guidePath??null)===(t.guidePath??null)}function Fn(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||!Kn(i,s))return!1}return!0}function Yn(e,t){return Kn(e,t)&&e.ownerShapeId===t.ownerShapeId&&(e.targetShapeId??null)===(t.targetShapeId??null)}function Xn(e,t){return 0===t.rotation?e.clone():Fr.RotWith(e,t.rotationCenter,-t.rotation)}function Dn(e,t){return 0===t.rotation?e.clone():Fr.RotWith(e,t.rotationCenter,t.rotation)}function zn(e,t){return Dn(e,t)}function Ln(e,t,n,i,s){return 0===n?i:i+(e-t)/n*s}function On({point:e,fromBounds:t,toBounds:n}){return new Fr(Ln(e.x,t.minX,t.w,n.minX,n.w),Ln(e.y,t.minY,t.h,n.minY,n.h))}function $n({axis:e,bounds:t,selectionBounds:n}){return"horizontal"===e?new Yr(n.minX+n.maxX-t.maxX,t.minY,t.w,t.h):new Yr(t.minX,n.minY+n.maxY-t.maxY,t.w,t.h)}function _n(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 Nn(e,t,n){return t.every(t=>{const i=e.shapes.computeLocalToPageTransform(t);return null!==_n(Math.atan2(i.b,i.a),n)})}function Un(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})),ga.filter(e=>r.every(t=>t.includes(e))));var r;return i?o:o.filter(e=>"free"!==e)}function Hn(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)&&ne(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 Wn(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&&J(i.startPagePoint,s.startPagePoint)&&J(i.endPagePoint,s.endPagePoint)&&J(i.middlePagePoint,s.middlePagePoint)&&Hn(i.pathStyle,s.pathStyle)&&Fn(i.bindingSegments,s.bindingSegments)&&i.path===s.path&&i.pageClipPath===s.pageClipPath))return!1}return!0}function qn(e,t){return e===t||(e&&t?ne(e.bounds,t.bounds)&&e.rotation===t.rotation&&J(e.rotationCenter,t.rotationCenter):e===t)}function Gn(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!qn(e[n]??null,t[n]??null))return!1;return!0}function Vn(e,t){return e.strokeWidth===t.strokeWidth&&e.cornerRadius===t.cornerRadius}function jn(e,t){return e.id===t.id&&J(e.point,t.point)&&ne(e.bounds,t.bounds)}function Qn(e,t){return e.id===t.id&&J(e.point,t.point)&&ne(e.bounds,t.bounds)}function Zn(e,t){return e.terminal===t.terminal&&J(e.point,t.point)&&ne(e.bounds,t.bounds)}function Jn(e,t){return J(e.point,t.point)&&ne(e.bounds,t.bounds)}function ei(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&J(e.point,t.point)&&ne(e.bounds,t.bounds)}function ti(e,t){return e.id===t.id&&J(e.point,t.point)}function ni(e,t){return e.id===t.id&&J(e.point,t.point)}function ii(e,t){return e.terminal===t.terminal&&J(e.point,t.point)}function si(e,t){return J(e.point,t.point)}function oi(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&J(e.point,t.point)}function ri(e,t){return e===t||(e&&t?e.strokeWidth===t.strokeWidth&&Q(e.resizeHandles,t.resizeHandles,jn)&&Q(e.rotateHandles,t.rotateHandles,Qn)&&Q(e.terminalHandles,t.terminalHandles,Zn)&&Q(e.middleHandles,t.middleHandles,Jn)&&Q(e.customHandles,t.customHandles,ei):e===t)}function ai(e,t){return e===t||(e&&t?Q(e.resizeHandleAnchors,t.resizeHandleAnchors,ti)&&Q(e.rotateHandleAnchors,t.rotateHandleAnchors,ni)&&Q(e.terminalHandleAnchors,t.terminalHandleAnchors,ii)&&Q(e.middleHandleAnchors,t.middleHandleAnchors,si)&&Q(e.customHandleAnchors,t.customHandleAnchors,oi):e===t)}function di({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 Fr(e.maxX+t,e.minY-t):new Fr(e.minX-t,e.maxY+t)}function ci(e){return 1===e.length&&!!e[0]?.usesSelectionPathOverlay}function li(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 hi({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(!ui(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"===li(e,n,i.id,t.id)))continue;const a=n.getShapePageBounds(i.id);a&&pi(a,u,c,l,h)&&(c=i,l=a.w*a.h,h=u)}return c?.id??a}function pi(e,t,n,i,s){const o=e.w*e.h;return!n||o<i||o===i&&t>s}function ui(e,t){return t.canAutomaticallyReceiveChildren(e)}function gi(e,t,n=new Set([t.id])){if(!t.parentId.startsWith("shape:"))return $r.Identity();const i=e.shapes.get(t.parentId);if(!i||n.has(i.id))return $r.Identity();const s=new Set(n);return s.add(i.id),Pe(i,e.shapes.getUtil(i),gi(e,i,s))}function fi(e,t){return e.shapes.getUtil(t).getExportBounds(t)}function mi(e,t){return Pe(t,e.shapes.getUtil(t),gi(e,t))}function Si(e,t){return Te(t,e.shapes.getUtil(t),gi(e,t))}function yi(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 Ii(e,t){const n=yi(e);return n?Xn(t,n):null}function Pi(e){return bi(e,e.selection.getIds())}function bi(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=>!yn(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?Yr.FromPoints(p):null;if(!u||!x(u))return null;const g={parentId:r,shapeIds:c,parentLocalBounds:u};return vi(e,g)?g:null}function vi(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 wi(e,t,n="user"){const i=bi(e,t);return i?((e,t,n)=>{const i=vi(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 Sa;if(a=d.id,!e.commands.reparentShapes({ids:t.shapeIds,parentId:d.id},{source:n}))throw new Sa;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:se(e).createShapeIndex(n+1)})),...t.shapeIds.map((t,n)=>({id:t,index:se(e).createShapeIndex(n+1)}))],{source:n})},n)}catch(d){if(d instanceof Sa)return null;throw d}return a?e.shapes.get(a)??null:null})(e,i,n):null}function xi(e){return Ci(e,e.selection.getIds())}function Ci(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)&&!!$e(e,n,t.parentId))).map(e=>e.id)}function Mi(e,t,n="user"){const i=Array.from(new Set(t)),s=new Set(((e,t)=>{const n=Ci(e,t),i=new Set(n);return n.filter(t=>!yn(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=>!$e(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 Sa;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:se(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&&_e(e,i,{source:n})})(e,r.map(e=>e.group.id),n)},n)}catch(p){if(p instanceof Sa)return[];throw p}return l.length>0&&e.commands.setSelectedShapeIds(l,{source:n}),l}function Ti(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 Bi(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 ki(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 Ei(e,t,n,i="user"){const s=ki(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:se(e).createShapeIndex(n+1)})),{source:i}),!0)}function Ai(e,t,n,i="user"){const s=ki(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:se(e).createShapeIndex(n+1)})),{source:i}),!0}function Ri(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 Ki(e){return"top_left"===e||"left"===e||"bottom_left"===e}function Fi(e){return"top_right"===e||"right"===e||"bottom_right"===e}function Yi(e){return"top_left"===e||"top"===e||"top_right"===e}function Xi(e){return"bottom_left"===e||"bottom"===e||"bottom_right"===e}function Di({handleId:e,scaleX:t,scaleY:n}){const i=Ki(e)?t<0?"right":"left":Fi(e)?t<0?"left":"right":null,s=Yi(e)?n<0?"bottom":"top":Xi(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 zi({axis:e,startBounds:t,bounds:n,handleId:i,scale:s,isResizingFromCenter:o}){const r=Math.sign(s??1)||1;return o?r:"x"===e?Ki(i)?n.minX>=t.maxX?-1:1:Fi(i)?n.maxX<=t.minX?-1:1:r:Yi(i)?n.minY>=t.maxY?-1:1:Xi(i)?n.maxY<=t.minY?-1:1:r}function Li({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 Yr(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 Yr(c<0?e.minX:e.maxX-a,l<0?e.minY:e.maxY-d,a,d);break;case"top_right":h=new Yr(c<0?e.maxX-a:e.minX,l<0?e.minY:e.maxY-d,a,d);break;case"bottom_right":h=new Yr(c<0?e.maxX-a:e.minX,l<0?e.maxY-d:e.minY,a,d);break;case"bottom_left":h=new Yr(c<0?e.minX:e.maxX-a,l<0?e.maxY-d:e.minY,a,d);break;case"top":h=new Yr(t.center.x-a/2,l<0?t.maxY:t.maxY-d,a,d);break;case"right":h=new Yr(c<0?t.minX-a:t.minX,t.center.y-d/2,a,d);break;case"bottom":h=new Yr(t.center.x-a/2,l<0?t.minY-d:t.minY,a,d);break;case"left":h=new Yr(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 Oi(e){return[new Fr(e.minX,e.minY),new Fr(e.center.x,e.minY),new Fr(e.maxX,e.minY),new Fr(e.minX,e.center.y),e.center,new Fr(e.maxX,e.center.y),new Fr(e.minX,e.maxY),new Fr(e.center.x,e.maxY),new Fr(e.maxX,e.maxY)]}function $i(e,t){return"x"===t?e.x:e.y}function _i(e,t){return"x"===t?e.minX:e.minY}function Ni(e,t){return"x"===t?e.maxX:e.maxY}function Ui(e,t){return"x"===t?[e.minY,e.maxY]:[e.minX,e.maxX]}function Hi(e,t){const n=Math.max(e[0],t[0]),i=Math.min(e[1],t[1]);return n<=i?[n,i]:null}function Wi(e,t){return null!==Hi(e,t)}function qi(e,t){return new Yr(e.x+t.x,e.y+t.y,e.w,e.h)}function Gi(e,t,n){return qi(e,((e,t)=>"x"===e?new Fr(t,0):new Fr(0,t))(t,n))}function Vi(e){return[new Fr(e.minX,e.minY),new Fr(e.maxX,e.minY),new Fr(e.maxX,e.maxY),new Fr(e.minX,e.maxY)]}function ji(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 Fr(t.x+i.x*o,t.y+i.y*o))}function Qi(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 Fr(t.x+i.x*o,t.y+i.y*o)}function Zi(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=ji(e,s,r);a>=i||(i=a,n=Qi(e,s,r))}return n?{point:n,distanceSquared:i}:null}function Ji(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 es(e,t){const n="x"===t?"horizontal":"vertical",i=[...e].sort((e,n)=>_i(e.bounds,t)-_i(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=Ni(e.bounds,t),c=_i(o.bounds,t);if(c>r+1e-8)break;if(d>=c)continue;const l=Hi(Ui(e.bounds,t),Ui(o.bounds,t));l&&(r=c,s.push({direction:n,startNode:e,endNode:o,length:c-d,breadthIntersection:l}))}}return s}function ts(e,t,n,i){const s=Hi(Ui(t.bounds,i),Ui(n.bounds,i));return s?{direction:e,startNode:t,endNode:n,length:_i(n.bounds,i)-Ni(t.bounds,i),breadthIntersection:s}:null}function ns(e,t){return[e,t.direction,t.startNode.id,t.endNode.id,t.length.toFixed(8)].join(":")}function is(e,t,n,i,s={}){const o=Ui(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:Gi(t,e,n)});for(const g of n){if(r<=g.length&&Wi(o,g.breadthIntersection)){const n=Ni(g.startNode.bounds,e)+(g.length-r)/2-_i(t,e),i=u(n);p(n,[ts(g.direction,g.startNode,i,e),ts(g.direction,i,g.endNode,e)].filter(e=>null!==e),`${ns(e,g)}:center`)}const n=Ni(g.endNode.bounds,e)+g.length-_i(t,e),i=u(n);if(Wi(Ui(i.bounds,e),g.breadthIntersection)){const t=ts(g.direction,g.endNode,i,e);p(n,t?[g,t]:[],`${ns(e,g)}:after`)}const s=_i(g.startNode.bounds,e)-g.length-Ni(t,e),a=u(s);if(Wi(Ui(a.bounds,e),g.breadthIntersection)){const t=ts(g.direction,a,g.startNode,e);p(s,t?[t,g]:[],`${ns(e,g)}:before`)}}return h&&(!l||l.distance+d>=h.distance)?h:l}function ss(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(os),n.sort(os),{x:t,y:n}}function os(e,t){return e.value-t.value||e.point.id.localeCompare(t.point.id)}function rs(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 as(e){return e.weight??(e.kind?Pa[e.kind]:0)}function ds(e,t){return`points:${e}:${[...t].sort().join("|")}`}function cs(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 ls(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=$i(g,e),a=rs(n,e,t-r,t+r);s.stats&&(s.stats.candidatePointCount+=a.length);for(const n of a){const r=$i(n.point,e)-t,a=Math.abs(r),l={offset:r,distance:a,weight:as(n),fromPrevious:!1};if(a<=i&&cs(l,d,i)&&(d=l),s.previousCandidatePointIds?.has(n.id)&&a<=o){const e={...l,fromPrevious:!0};cs(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=$i(f,e),i=rs(n,e,t-h,t+h);for(const n of i){const i=$i(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:ds(e,u),nudge:l.offset,distance:l.distance,weight:l.weight,candidatePointIds:u,pairs:p}:null}function hs(e,t){const n=[];switch(e){case"top":case"left":case"top_left":case"any":n.push(new Fr(t.minX,t.minY))}switch(e){case"top":case"right":case"top_right":case"any":n.push(new Fr(t.maxX,t.minY))}switch(e){case"bottom":case"right":case"bottom_right":case"any":n.push(new Fr(t.maxX,t.maxY))}switch(e){case"bottom":case"left":case"bottom_left":case"any":n.push(new Fr(t.minX,t.maxY))}return n}function ps(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 us(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&&J(e.rotationCenter,t.rotationCenter)&&J(e.line[0],t.line[0])&&J(e.line[1],t.line[1])&&e.points.length===t.points.length&&e.points.every((e,n)=>{const i=t.points[n];return!!i&&J(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&&J(e.rotationCenter,t.rotationCenter)&&e.gaps.length===t.gaps.length&&e.gaps.every((e,n)=>{const i=t.gaps[n];return!!i&&((e,t)=>J(e.startEdge[0],t.startEdge[0])&&J(e.startEdge[1],t.startEdge[1])&&J(e.endEdge[0],t.endEdge[0])&&J(e.endEdge[1],t.endEdge[1]))(e,i)})}(e,i))})}function gs(e){return"horizontal"===e.direction?{startEdge:[new Fr(e.startNode.bounds.maxX,e.startNode.bounds.minY),new Fr(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new Fr(e.endNode.bounds.minX,e.endNode.bounds.minY),new Fr(e.endNode.bounds.minX,e.endNode.bounds.maxY)]}:{startEdge:[new Fr(e.startNode.bounds.minX,e.startNode.bounds.maxY),new Fr(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new Fr(e.endNode.bounds.minX,e.endNode.bounds.minY),new Fr(e.endNode.bounds.maxX,e.endNode.bounds.minY)]}}function fs(e,t,n,i){const s=t.pairs.some(({candidatePointKind:e,selectionPointKind:t})=>"center"===e&&"center"===t),o=Ji([...t.pairs.map(({selectionPoint:e})=>e.add(n)),...t.pairs.map(({candidatePoint:e})=>e.clone())]),r=Ji([...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:Ji([...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=Is(e,a);return{id:Ps(e,c,d),type:"points",axis:e,line:c,points:d,rotation:i.rotation,rotationCenter:i.rotationCenter.clone()}}function ms(e,t,n,i){return Ss(e,t,n).map(t=>fs(e,t,n,i))}function Ss(e,t,n){const i=new Map;for(const s of t.pairs){const t=$i(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 ys(e,t,n){return"x"===e?[new Fr(t,n.minY),new Fr(t,n.maxY)]:[new Fr(n.minX,t),new Fr(n.maxX,t)]}function Is(e,t){if(0===t.length)return[Fr.Zero(),Fr.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 Fr(n,s),new Fr(n,o)]:[new Fr(n,s),new Fr(i,s)]}function Ps(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 bs(e,t,n,i,s,o){return Ss(e,t,n).map(t=>((e,t,n,i,s,o)=>{const r=fs(e,t,n,i),a=t.pairs[0],d=$i(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(...ys(e,d,t))}const p=Ji([...r.points,...ys(e,d,s),...l]),u=Is(e,Ji([...ys(e,d,s),...l]));return{...r,id:Ps(e,u,p),line:u,points:p}})(e,t,n,i,s,o))}function vs(e,t,n){const i="x"===e?new Fr(n.x,t.y):new Fr(t.x,n.y),s=Ji([n.clone(),i]),o=Is(e,s);return{id:Ps(e,o,s),type:"points",axis:e,line:o,points:s,rotation:0,rotationCenter:Fr.Zero()}}function ws(e,t,n){const i="horizontal"===e.gaps[0]?.direction?new Fr(0,n.y):new Fr(n.x,0),s=e.gaps.map(e=>({...e,startNode:"selection"===e.startNode.id?{...e.startNode,bounds:qi(e.startNode.bounds,i)}:e.startNode,endNode:"selection"===e.endNode.id?{...e.endNode,bounds:qi(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(gs),rotation:t.rotation,rotationCenter:t.rotationCenter.clone()}}function xs(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 Cs(e){return{point:e.point,kind:e.kind??"custom",weight:e.weight}}function Ms(e){const t=e.sourcePointOffsets;return t&&t.length>0?t.map(t=>e.pagePoint.add(t)):[e.pagePoint]}function Ts(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 Bs(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 ks(e,t,n){return e+(t-e)*n}function Es(e,t,n){return Math.min(n,Math.max(t,e))}function As(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 Rs(e,t){if(!Number.isFinite(e))return t;const n=Math.max(0,Math.floor((e-3)/2));return Math.min(t,n)}function Ks(e){return e.reduce((e,t)=>e+(t.end-t.start),0)}function Fs(e,t){const n=[];for(const i of t)n.push(...e.slice(i.start,i.end));return n}function Ys(e,t,n){return{viewportReady:n?.viewportReady??!0,ranges:t.map(e=>({...e})),shapeIds:Fs(e,t)}}function Xs(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 Ds(e){let t=null;for(const i of e.splice(0).reverse())try{i()}catch(n){t??=n}return t}function zs(e={}){const{plugins:t=[],...n}=e,i=new Ma({...n,...Xs(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 Ds(n),i}return()=>{const e=Ds(n);if(null!==e)throw e}})(i,t)),i}catch(s){try{i.dispose()}catch{}throw s}}function Ls(e,t){return((e,t)=>!(Os(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:Os(t.key),altKey:t.altKey??!1,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey??!1,accelKey:t.accelKey}})(e),t)}function Os(e){return e.toLowerCase()}function $s(e){return Math.min(1,Math.max(0,(96-e)/96))}function _s(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 Fr.Zero();const i=Math.min(n,32),s=$s(e.x),o=$s(t.w-e.x),r=$s(e.y),a=1.25*(o-s)*i,d=1.25*($s(t.h-e.y)-r)*i;return 0===a&&0===d?Fr.Zero():new Fr(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 Ns(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 Us(e,t,n){const i=new Set(n);if(i.has(t))return t;const s=Hs(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)=>Hs(e,t)[0]?.ancestorId??null)(e,t)===o)?t:s[s.length-1]?.ancestorId??t}function Hs(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 Ws({shiftKey:e,accelKey:t}){return e||t}function qs({ctrlKey:e}){return e}function Gs(e){let t=e;for(;t<=-Math.PI;)t+=2*Math.PI;for(;t>Math.PI;)t-=2*Math.PI;return t}function Vs(e,t){return Math.round(e/t)*t}function js(e,t,n,i,s,o,r,a,d,c,l,h){const p=Qs(c,l),u=Js({point:t.localBounds.center,startBounds:n,scaleX:s,scaleY:o,handleId:r,isResizingFromCenter:d}),g=(({bounds:e,fromBounds:t,toBounds:n})=>{const i=On({point:new Fr(e.minX,e.minY),fromBounds:t,toBounds:n}),s=On({point:new Fr(e.maxX,e.maxY),fromBounds:t,toBounds:n});return new Yr(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 Yr(u.x-g.w/2,u.y-g.h/2,g.w,g.h),m=Dn(u,p),S=e.shapes.getUtil(t.pageShape),y=_n(t.pageShape.rotation,l),I=null!==y,P="perpendicular"===y?new Yr(f.center.x-f.h/2,f.center.y-f.w/2,f.h,f.w):f,b=I?P:(()=>{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 Yr(m.x-i/2,m.y-r/2,i,r)})(),v=S.resizeSelectionBounds(t.pageShape,{handleId:r,isOnlyResizeTarget:a,pageCenter:m,selectionLocalBounds:b,scaleX:s,scaleY:o,isResizingFromCenter:d,selectionRotation:I?l:t.pageShape.rotation,selectionRotationCenter:I?c:m}),w=hn(e,t.shape,t.pageShape,v);w&&Object.assign(h,w)}function Qs(e,t){return{rotation:t,rotationCenter:e}}function Zs(e,t,n,i,s,o,r,a,d,c,l){const h=Qs(d,c),p=Dn(Js({point:t.startLocalPagePoint,startBounds:n,scaleX:s,scaleY:o,handleId:r,isResizingFromCenter:a}),h),u=Dn(Js({point:t.endLocalPagePoint,startBounds:n,scaleX:s,scaleY:o,handleId:r,isResizingFromCenter:a}),h),g=t.middleLocalPagePoint?Dn(Js({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=hn(e,t.shape,t.pageShape,f);m&&Object.assign(l,m)}function Js({point:e,startBounds:t,scaleX:n,scaleY:i,handleId:s,isResizingFromCenter:o}){const r=(({startBounds:e,handleId:t,isResizingFromCenter:n})=>n?e.center.x:Ki(t)?e.maxX:Fi(t)?e.minX:e.center.x)({startBounds:t,handleId:s,isResizingFromCenter:o}),a=(({startBounds:e,handleId:t,isResizingFromCenter:n})=>n?e.center.y:Yi(t)?e.maxY:Xi(t)?e.minY:e.center.y)({startBounds:t,handleId:s,isResizingFromCenter:o});return new Fr(r+(e.x-r)*n,a+(e.y-a)*i)}function eo(e,t,n,i,s){const o=t.localBounds.center,r=zn(new Fr(t.pageShape.x+o.x,t.pageShape.y+o.y),{rotation:i,rotationCenter:n}),a=hn(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 to(e,t,n,i,s){const o=e.shapes.getUtil(t.pageShape).updateSelectionPagePoints(t.pageShape,{pagePoints:[zn(t.startPagePoint,{rotation:i,rotationCenter:n}),zn(t.endPagePoint,{rotation:i,rotationCenter:n})],pageMiddlePoint:t.middlePagePoint?zn(t.middlePagePoint,{rotation:i,rotationCenter:n}):void 0}),r=hn(e,t.shape,t.pageShape,o);r&&Object.assign(s,r)}function no(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 io(e,t,n){const i=n?e.layers.getContainingParentIdAtPoint(t,n):e.layers.getContainingParentId(t);if(!i)return null;const s=no(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 so(e,t,n){const i=io(e,t,n);i&&t.some(t=>e.shapes.get(t)?.parentId!==i)&&e.commands.reparentShapes({ids:[...t],parentId:i})}function oo(e,t,n,i={}){let s=!0;return t.graph.effect(e,()=>{t.get(),s&&!1===i.fireImmediately?s=!1:(s=!1,n())})}function ro(){const e=ar(Va);if(!e)throw new Error("useEditor must be used within EditorContext.Provider");return e}function ao({children:e,className:t,dataUi:n}){const i=ro(),s=pr(null);return lr(()=>oo("PageSpace.transform",i.state.pageTransform,()=>{const e=s.current;e&&(e.style.transform=i.state.pageTransform.get().toCssString())}),[i]),mr("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 co(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){ho(t,y.id,"canvas render plugin id");for(const e of y.shapeRenderers??[])lo(n,e.type,e,"shape renderer type");for(const e of y.shapeDecorations??[]){ho(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??[])ho(r,e.id,"shape opacity modifier id"),o.push(e);for(const e of y.canvasOverlays??[])lo(a,e.id,e,"canvas overlay id");for(const e of y.selectionCustomHandleRenderers??[])lo(d,e.type,e,"selection handle renderer type");for(const e of y.domEventGuards??[])ho(l,e.id,"DOM event guard id"),c.push(e);for(const e of y.canvasComponents??[])ho(p,e.id,"canvas component id"),h.push(e)}const u=Object.freeze([...a.values()].sort(po));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 lo(e,t,n,i){if(e.has(t))throw new Error(`Duplicate ${i}: ${t}.`);e.set(t,n)}function ho(e,t,n){if(e.has(t))throw new Error(`Duplicate ${n}: ${t}.`);e.add(t)}function po(e,t){return(e.order??0)-(t.order??0)}function uo(){return ar(ja)}function go(){return uo().renderers}function fo(){return uo().overlays}function mo(e){const t=rr(t=>oo("useValue",e,t,{fireImmediately:!1}),[e]),n=rr(()=>e.get(),[e]);return gr(t,n,n)}function So({children:e,clipAncestorIds:t,shapeElementToPage:n}){return 0===t.length?mr(fr,{children:e}):t.reduceRight((e,t)=>mr(yo,{ancestorId:t,shapeElementToPage:n,children:e},t),e)}function yo({ancestorId:e,children:t,shapeElementToPage:n}){const i=ro(),s=mo(i.shapes.getSignal(e));if(!s)return mr(fr,{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(Po).join(", ")})`:`path("${r.map(Io).join(" ")}")`})(i,s,n);return o?mr("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}):mr(fr,{children:t})}function Io(e){return e.map((e,t)=>`${0===t?"M":"L"} ${bo(e.x)} ${bo(e.y)}`).concat("Z").join(" ")}function Po(e){return`${bo(e.x)}px ${bo(e.y)}px`}function bo(e){return Number.isFinite(e)?Number(e.toFixed(3)).toString():"0"}function vo({Component:e,editor:t,shape:n}){
|
|
2
|
+
return mr("div",{"aria-hidden":"true","data-ui":"shape-hover-decoration",style:{position:"absolute",inset:0,pointerEvents:"none"},children:mr(e,{shape:n,editor:t,strokeWidth:2/mo(t.state.cameraZoom)})})}function wo(e,t,n){const i=e.shapes.computeRenderBounds(t),s=n.compose($r.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 xo(){
|
|
3
|
+
return mr("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 Co(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 Mo(){
|
|
4
|
+
return mr("div",{"data-ui":"shape-layer",className:"land-canvas__shape-layer",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%"},children:mr(ao,{dataUi:"shape-page-space",className:"land-canvas__shape-page-space",children:mr(nd,{})})})}function To(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 Bo({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=To(a,d);
|
|
5
|
+
return Sr("g",{style:{pointerEvents:"none"},children:[mr("line",{...l.underlay,x1:c.start.x,y1:c.start.y,x2:c.end.x,y2:c.end.y,fill:"none",stroke:sd,strokeLinecap:"round",strokeWidth:2.2*s}),mr("line",{...l.segment,x1:c.start.x,y1:c.start.y,x2:c.end.x,y2:c.end.y,fill:"none",stroke:id,strokeDasharray:`${o} ${r}`,strokeLinecap:"round",strokeWidth:s})]})}function ko({path:e,strokeWidth:t,dashSize:n,gapSize:i,kind:s,terminal:o}){const r=To(s,o);
|
|
6
|
+
return Sr("g",{style:{pointerEvents:"none"},children:[mr("path",{...r.underlay,d:e,fill:"none",stroke:sd,strokeLinecap:"round",strokeWidth:2.2*t}),mr("path",{...r.segment,d:e,fill:"none",stroke:id,strokeDasharray:`${n} ${i}`,strokeLinecap:"round",strokeWidth:t})]})}function Eo({editor:e,shape:t,stroke:n,fill:i,strokeWidth:s}){const o=e.shapes.getPageOutlineVertices(t.id);return 0===o.length?null:mr("polygon",{points:o.map(e=>`${e.x},${e.y}`).join(" "),fill:i,stroke:n,strokeWidth:s,strokeLinejoin:"round",strokeLinecap:"round"})}function Ao({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?mr("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:Ro(t,e.rotation),pointerEvents:"stroke"}}):null}function Ro(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 md[Math.round(n)%md.length]??"default"}function Ko({handle:e,strokeWidth:t}){
|
|
7
|
+
return mr("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 Fo({dataPrefix:e,pathStyle:t,stroke:n,strokeWidth:i}){
|
|
8
|
+
return Sr(fr,{children:[mr("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)=>mr("path",{"data-selection-overlay":`${e}-decoration`,d:t,fill:"none",stroke:n,strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round",pointerEvents:"none"},`${s}:${t}`))]})}function Yo(e,t){const n=Math.max(e[0],t[0]),i=Math.min(e[1],t[1]);return n<=i?[n,i]:null}function Xo(){
|
|
9
|
+
return mr("div",{"data-ui":"overlay-layer",className:"land-canvas__overlay-layer",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",pointerEvents:"none"},children:mr(ao,{dataUi:"overlay-page-space",className:"land-canvas__overlay-page-space",children:mr(Td,{})})})}function Do(e,t){return(e%t+t)%t}function zo(){const e=mo(ro().state.camera);
|
|
10
|
+
return Sr("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:[mr("defs",{children:kd.map(({min:t,mid:n,step:i})=>{const s=15*i*e.z,o=((e,t)=>({x:Do(.5-e.x*e.z,t),y:Do(.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 mr("pattern",{id:`land-canvas-grid-${i}`,width:s,height:s,patternUnits:"userSpaceOnUse",children:mr("circle",{cx:o.x,cy:o.y,r:1,fill:"var(--land-canvas-grid-minor, var(--canvas-dot))",opacity:r})},i)})}),kd.map(({step:e})=>mr("rect",{width:"100%",height:"100%",fill:`url(#land-canvas-grid-${e})`},e))]})}function Lo(e){return e instanceof HTMLElement?e:null}function Oo(e){const t=Lo(e);return!!t&&(!!t.isContentEditable||!!t.closest('[contenteditable="true"]')||t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)}function $o(e){return(e??("undefined"==typeof document?null:document))?.querySelector(Ad)??null}function _o(e){const t=e?.getRootNode();return t instanceof Document||t instanceof ShadowRoot?$o(t):$o()}function No(e,t,n){const i=n?$o(n):_o(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 Uo(e,t=$o()){if(!t)return new Fr(e.clientX,e.clientY);const n=t.getBoundingClientRect();return new Fr(e.clientX-n.left,e.clientY-n.top)}function Ho(e,t,n){return e.viewport.screenToPage(Uo(t,n))}function Wo(e,t){return{type:"keyboard",name:e,...Go(t),code:t.code}}function qo(e,t,n){return e.state.shapeEditingSession.get(),n?null:e.handleEvent(Wo("key_up",t))}function Go(e){return{key:e.key,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}}function Vo(e){return"Space"===e.code}function jo(e,t){const n=t.ownerDocument;return e===n||e===n.body||e===n.documentElement||e instanceof Node&&t.contains(e)}function Qo(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 Zo(e,t){return new Fr(e.clientX-t.left,e.clientY-t.top)}function Jo(e,t){return e instanceof Node&&t.contains(e)}function er(e,t,n,i){return n||"hand"===e&&t?"grabbing":i||"hand"===e?"grab":"select"===e?void 0:"crosshair"}function tr({onContextMenuRequest:e,renderBindings:t,showGrid:n=!1}){const i=ro(),{canvasComponents:s,domEventGuards:o}=t,r=mo(i.state.tool).activeToolId,a=mo(i.state.shapeEditing).session,d=mo(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=pr(null),r=pr(null),a=pr(null),d=pr(null),c=pr(null),l=pr(null),h=pr(null),[p,u]=ur(!1),[g,f]=ur(!1),[m,S]=ur(void 0),y=null!==s;dr(()=>{("select"!==t||y)&&n.interaction.setHoveredShapeId(null)},[t,n,y]);const I=rr(()=>{null!==c.current&&(cancelAnimationFrame(c.current),c.current=null),l.current=null},[]),P=rr(e=>{if(null===a.current)return void I();const t=l.current??e;l.current=e,n.handleEvent({type:"tick",timestamp:e,elapsed:e-t}),c.current=requestAnimationFrame(P)},[n,I]),b=rr(()=>{null===c.current&&(l.current=null,c.current=requestAnimationFrame(P))},[P]);return dr(()=>{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(),p=()=>{null!==s&&(window.cancelAnimationFrame(s),s=null)},g=({clientPoint:e,target:s})=>{if(p(),!e||null!==a.current||"select"!==t||y)return void n.interaction.setHoveredShapeId(null);const o=i.getBoundingClientRect();if(!Jo(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 Fr(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))},m=()=>{const e=h.current;g({clientPoint:e,target:e?document.elementFromPoint(e.x,e.y):null})},P=()=>{null===s&&(s=window.requestAnimationFrame(()=>{s=null,m()}))},b=(t,s)=>"handled"===e.handle({name:t,event:s,editor:n,container:i}),v=()=>{if(!y)return void S(void 0);const t=h.current;S(t?e.getCursor({clientPoint:t,element:document.elementFromPoint(t.x,t.y),editor:n,container:i}):void 0)},w=(e,t)=>{if(!o.current)return;const i=Zo(t,l());n.handleEvent(Qo(e,t,i,n.viewport.screenToPage(i)))},x=()=>{n.viewport.setScreenSize({w:i.clientWidth,h:i.clientHeight})};c(),x();const C=e=>{if(!b("key_down",e)){if(n.state.shapeEditingSession.get()){if(Oo(e.target))return;return n.handleEvent(Wo("key_down",e)).claimed?(e.preventDefault(),void e.stopPropagation()):void("Enter"===e.key&&(e.metaKey||e.ctrlKey)&&n.editing.complete("user"))}Oo(e.target)||Vo(e)&&!jo(e.target,i)||n.handleEvent(Wo("key_down",e)).claimed&&e.preventDefault()}},M=e=>{if(Vo(e)&&n.inputs.pressedKeyCodes.get().has(e.code)&&!n.state.shapeEditingSession.get())return e.preventDefault(),void qo(n,e,!1);b("key_up",e)||Vo(e)&&!jo(e.target,i)||qo(n,e,Oo(e.target))?.claimed&&e.preventDefault()},T=()=>{a.current=null,d.current=null,u(!1),f(!1),n.interaction.setHoveredShapeId(null),I(),n.handleEvent({type:"cancel",reason:"blur"})},B=e=>{if(b("wheel",e))return;e.preventDefault();const t={x:e.clientX,y:e.clientY};h.current=t;const i=Zo(e,l()),s=n.viewport.screenToPage(i);n.handleEvent(((e,t,n)=>({type:"wheel",screenPoint:t,pagePoint:n,delta:new Fr(e.deltaX,e.deltaY),shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}))(e,i,s)),g({clientPoint:t,target:document.elementFromPoint(t.x,t.y)})},k=e=>{if(h.current={x:e.clientX,y:e.clientY},g({clientPoint:h.current,target:e.target}),v(),e.pointerId!==a.current){const t=Zo(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}),b("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)||!Jo(e.target,i)||Oo(e.target))return;return void w("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,w("pointer_move",e))},E=(e,t)=>{t.pointerId===a.current&&(a.current=null,d.current=null,u(!1),f(!1),I(),i.hasPointerCapture(t.pointerId)&&i.releasePointerCapture(t.pointerId),w(e,t),"pointer_up"===e?m():n.interaction.setHoveredShapeId(null))},A=()=>{h.current=null,n.interaction.setHoveredShapeId(null),v()},R=e=>{h.current={x:e.clientX,y:e.clientY},window.setTimeout(v,0),e.pointerId===a.current?E("pointer_up",e):b("pointer_up",e)},K=e=>{h.current={x:e.clientX,y:e.clientY},v(),e.pointerId===a.current?E("pointer_cancel",e):b("pointer_cancel",e)},F=new ResizeObserver(()=>{c(),x(),P()}),Y=()=>{c(),P()},X=n.listen(P);window.addEventListener("keydown",C),window.addEventListener("keyup",M),window.addEventListener("blur",T),window.addEventListener("scroll",Y,{passive:!0,capture:!0}),window.addEventListener("pointermove",k,{passive:!0}),window.addEventListener("pointerup",R),window.addEventListener("pointercancel",K),i.addEventListener("pointerleave",A),i.addEventListener("wheel",B,{passive:!1}),F.observe(i);const D=window.requestAnimationFrame(v);return P(),()=>{I(),p(),X(),u(!1),f(!1),n.interaction.setHoveredShapeId(null),window.cancelAnimationFrame(D),window.removeEventListener("keydown",C),window.removeEventListener("keyup",M),window.removeEventListener("blur",T),window.removeEventListener("scroll",Y,!0),window.removeEventListener("pointermove",k),window.removeEventListener("pointerup",R),window.removeEventListener("pointercancel",K),i.removeEventListener("pointerleave",A),i.removeEventListener("wheel",B),F.disconnect()}},[e,t,n,y,I]),{containerRef:o,handlers:{onPointerDown:rr(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(Oo(t.target))return;t.preventDefault(),i.focus(),i.setPointerCapture(t.pointerId);const s=i.getBoundingClientRect();r.current={left:s.left,top:s.top},a.current=t.pointerId,u(!0),f(1===t.button||0===t.button&&n.inputs.isSpacePressed.get()&&!n.state.shapeEditingSession.get()),d.current=null,b();const c=Zo(t,r.current);n.interaction.setHoveredShapeId(null),n.handleEvent(Qo("pointer_down",t,c,n.viewport.screenToPage(c)))},[e,n,b]),onAuxClick:rr(e=>{1!==e.button||Oo(e.target)||(e.preventDefault(),e.stopPropagation())},[]),onContextMenu:rr(e=>{const t=o.current;if(!t||!i||Oo(e.target))return;e.preventDefault(),e.stopPropagation();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,u(!1),f(!1),I();const s=Zo(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=Zo(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,i,I])},isPointerActive:p,isCameraPanning:g,surfaceCursor:m}}({activeDomEventGuards:o,activeToolId:r,editor:i,onContextMenuRequest:e,shapeEditingSession:a});
|
|
12
|
+
return Sr("div",{ref:c,"data-ui":Ed,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??er(r,h,p,d)},...l,children:[n?mr(zo,{}):null,Sr(ja.Provider,{value:t,children:[
|
|
13
|
+
mr(Mo,{}),s.map(({id:e,component:t})=>mr(t,{},e)),
|
|
14
|
+
mr(Xo,{})]})]})}function nr({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 ir({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=pr(null),[P,b]=ur(!1),v=mo(e.state.cameraZoom),w=mo(e.shapes.getLocalToPageTransformSignal(t.id)),x=Math.max(v,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)})(w?Math.atan2(w.b,w.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;dr(()=>{const e=I.current;m&&n&&e&&(e.focus(),e.select())},[m,n]);const E=rr(()=>{m&&e.editing.canEditShape(t)&&e.editing.start({shapeId:t.id,entryMode:"selectAll",operationKind:d},"user")},[m,e,d,t]),A=rr(e=>{p(e.currentTarget.value)},[p]),R=rr(t=>{e.editing.complete("user")},[e]),K=rr(t=>{e.editing.setComposition(!0,"system")},[e]),F=rr(t=>{e.editing.setComposition(!1,"system")},[e]),Y=rr(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]),X=rr(e=>{e.stopPropagation()},[]),D=rr(e=>{e.stopPropagation(),n||E()},[n,E]);
|
|
15
|
+
return mr("div",{style:{height:0,left:0,overflow:"visible",pointerEvents:"none",position:"absolute",top:a,width:0},children:mr("div",{"data-ui":h.heading,"data-shape-id":t.id,style:{alignItems:"center",bottom:0,display:"flex",fontFamily:Rd,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:Sr("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?mr("div",{"aria-hidden":"true","data-ui":h.dragHandle,onPointerEnter:()=>b(!0),onPointerLeave:()=>b(!1),style:{alignItems:"center",backgroundColor:P?"rgba(37, 99, 235, 0.12)":"transparent",borderRadius:4,boxShadow:P?"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:Sr("svg",{width:"10",height:"14",viewBox:"0 0 10 14",fill:"currentColor",children:[
|
|
16
|
+
mr("circle",{cx:"3",cy:"3",r:"1"}),
|
|
17
|
+
mr("circle",{cx:"7",cy:"3",r:"1"}),
|
|
18
|
+
mr("circle",{cx:"3",cy:"7",r:"1"}),
|
|
19
|
+
mr("circle",{cx:"7",cy:"7",r:"1"}),
|
|
20
|
+
mr("circle",{cx:"3",cy:"11",r:"1"}),
|
|
21
|
+
mr("circle",{cx:"7",cy:"11",r:"1"})]})}):null,u?mr("span",{"aria-hidden":"true",style:{alignItems:"center",display:"flex",flex:"0 0 auto",marginRight:4,pointerEvents:"none"},children:u}):null,
|
|
22
|
+
Sr("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?X: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?mr("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:F,onKeyDown:Y,onPointerDown:X,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 sr,memo as or,useCallback as rr,useContext as ar,useEffect as dr,useId as cr,useLayoutEffect as lr,useMemo as hr,useRef as pr,useState as ur,useSyncExternalStore as gr}from"react";import{Fragment as fr,jsx as mr,jsxs as Sr}from"react/jsx-runtime";var yr=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))}},Ir=Symbol("UNINITIALIZED"),Pr=class{graph;name;derive;isEqual;isComputed=!0;lastChangedEpoch;lastCheckedEpoch=-1;consumers=new Set;state=Ir;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!==Ir&&!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!==Ir&&(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}},br=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}},vr=null,wr=class{epoch=0;currentTransaction=null;captureStack=null;atom=(e,t,n)=>((e,t,n,i)=>new yr(e,t,n,i?.isEqual))(this,e,t,n);computed=(e,t,n)=>((e,t,n,i)=>new Pr(e,t,n,i?.isEqual))(this,e,t,n);effect=(e,t,n)=>((e,t,n,i)=>{const s=new br(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},vr={graph:this,previous:vr}}stopCapture(){if(!this.captureStack)throw new Error("Cannot stop dependency capture because no capture is active.");if(vr?.graph!==this)throw new Error("SignalGraph dependency capture stack is out of order.");const e=this.captureStack;return this.captureStack=e.previous,vr=vr.previous,e.dependencies}trackDependency(e){if(vr&&vr.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}},xr=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}},Cr=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}},Mr="document:main",Tr="page:default",Br="session:main",kr={x:0,y:0,z:1},Er=Symbol("editorStore"),Ar=new Set,Rr=class{editor;suppressedReactionIds=Ar;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 b(t);this.suppressedReactionIds=s;try{return b(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.editor.shapes.get(e.fromId),n=this.editor.shapes.get(e.toId);return!(!t||!n)&&(this.editor.bindings.getUtil(e).canBind?.(this.editor,e,{fromShape:t,toShape:n})??!0)}syncCreatedBinding(e,t){const n=this.editor.bindings.getUtil(e).onBindingCreate?.(this.editor,e);this.applyEffect(n,t,e.id),this.syncShapeCompanionState([e.fromId,e.toId],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([t.fromId,t.toId],n,t.id)}repairLoadedBindings(e){S(this.editor).atomic(()=>{const t=new Set,n=new Set;for(const s of this.getAllBindings()){const i=this.editor.shapes.get(s.fromId),o=this.editor.shapes.get(s.toId);if(!i||!o){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 r=this.getExclusiveBindingKey(s);if(r){if(t.has(r)){S(this.editor).remove([s.id],e);continue}t.add(r)}const a=this.editor.bindings.getUtil(s).onBindingLoad?.(this.editor,s);this.applyEffect(a,e,s.id),n.add(s.fromId),n.add(s.toId)}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=d.fromId===e.id?"from":"to",h=this.editor.bindings.getUtil(d).onAfterShapeChange?.(this.editor,d,{before:i,after:r,role: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(P(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 Set;for(const s of e){const e=this.editor.shapes.get(s);if(e)for(const o of this.editor.bindings.getForShape(s)){if(i.has(o.id))continue;i.add(o.id);const r=o.fromId===s?"from":"to";if("to"===r&&n.has(o.fromId)){S(this.editor).remove([o.id],t);continue}const a=this.editor.bindings.getUtil(o).onBeforeDeleteShape?.(this.editor,o,{shape:e,role:r});this.applyEffect(a,t,o.id)}}}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))}getExclusiveBindingKey(e){const t=this.editor.bindings.getUtil(e).getExclusiveBindingKey?.(e);return t?`${e.type}:${t}`:null}},Kr=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}},Fr=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)}},Yr=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 Fr(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)}},Xr=["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"],Dr=Object.fromEntries(Xr.map(e=>[e,`--land-shape-${e}`])),zr={"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"},Lr=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()}},Or=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)??[]}},$r=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 Fr(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)}},_r=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}},Nr=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)??[]}},Ur=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}},Hr=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}},Wr=new WeakMap,qr=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=n.validateProps({...n.getDefaultProps(),...e.props});return{id:t,typeName:"binding",scope:"document",type:e.type,fromId:e.fromId,toId:e.toId,props:i,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,oe(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,oe(s.id)):f(s)&&(i=Math.max(i,oe(s.id)));this.nextShapeNumber=e+1,this.nextPageNumber=t+1,this.nextBindingNumber=n+1,this.nextAssetNumber=i+1}},Gr=new Fr(24,24),Vr={propagation:"stop"},jr={propagation:"stop",clickSequence:"break"},Qr=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=rt(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=rt(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&&at(t,e)&&at(n,e))}matchesCurrentPointer(e){return!this.lastPointerDown||at(this.lastPointerDown,e)}reset(){this.lastPointerDown=null,this.lastPointerUp=null,this.currentClickCount=1}},Zr={propagation:"stop",clickSequence:"break"},Jr=class{editor;clickRecognizer=new Qr;activeRoutes=new WeakMap;constructor(e){this.editor=e}handle(e){const t=this.activeRoutes.get(e);return t?(t.effect=ot(t.effect,this.routeAfterInputs(e,t.context)),dt(t.effect)):dt(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=ot(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=ot(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(),ot(ot(n,i),Zr)}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:ot(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(),ot(ot(i,s),Zr)}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"}),ot(n,Zr)}},ea=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:ct(),screenVelocity:ct(),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:lt(n,e.pagePoint,o),screenVelocity:lt(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:ct(),screenVelocity:ct(),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:ct(),screenVelocity:ct(),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&&ht(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:lt(n,e.pagePoint,r),screenVelocity:lt(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:ct(),screenVelocity:ct(),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=>ht(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=>ht(t,e)?t:{...t,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey})}},ta=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=ot(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=ot(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}},na=class{editor;buffer;activeScopes=[];stateAtom;unsubscribeOperations;isDisposed=!1;state;constructor(e){this.editor=e,this.buffer=new xr,this.stateAtom=e.signals.atom("editor.history.state",{canUndo:!1,canRedo:!1},{isEqual:pt}),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})}},ia=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)}},sa=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 ia(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 ia(this,e):null}subscribe(e){return this.commitListeners.add(e),()=>{this.commitListeners.delete(e)}}commit(e){this.assertTopActive(e);const n=ut(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:ft(this.editor.snapshots.getDocument()),sessionSnapshot:mt(this.editor.snapshots.getSession())};return this.enqueueCommit(i),i}cancel(e){this.assertTopActive(e);const n=ut(e.diff);if(!t(n))try{S(this.editor).applyDiff(i(n),e.source),this.editor.snapshots.syncAfterDocumentRestore()}catch(s){if(!t(ut(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=ut(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:ft(this.editor.snapshots.getDocument()),sessionSnapshot:mt(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{}}},oa=["from","to","related"],ra=class{editor;state;bindingsFromShapeSignals=new Map;bindingsToShapeSignals=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(It),n={bindingById:new Map,bindingIdsByFromShape:new Map,bindingIdsByToShape:new Map,relatedBindingIdsByShape:new Map};for(const i of t)n.bindingById.set(i.id,i),St(n.bindingIdsByFromShape,i.fromId,i.id),St(n.bindingIdsByToShape,i.toId,i.id),St(n.relatedBindingIdsByShape,i.fromId,i.id),St(n.relatedBindingIdsByShape,i.toId,i.id);return n})(t.getAll()),this.unsubscribeFromStore=t.listen(e=>{this.handleStoreChange(e)})}dispose(){this.unsubscribeFromStore(),this.bindingsFromShapeSignals.clear(),this.bindingsToShapeSignals.clear(),this.bindingsForShapeSignals.clear(),this.draftBindingIndex=null}getBindingsFromShape(e){const t=this.getDraftBindingIndex();return t?[...this.getDraftBindingsForRelation("from",e,t)]:[...this.getBindingsFromShapeSignal(e).get()]}getBindingsFromShapeSignal(e){let t=this.bindingsFromShapeSignals.get(e);return t||(t=this.editor.signals.atom(`editor.query.bindingsFromShape.${e}`,this.getBindingsFromState(this.state,e),{isEqual:Q}),this.bindingsFromShapeSignals.set(e,t)),t}getBindingsToShape(e){const t=this.getDraftBindingIndex();return t?[...this.getDraftBindingsForRelation("to",e,t)]:[...this.getBindingsToShapeSignal(e).get()]}getBindingsToShapeSignal(e){let t=this.bindingsToShapeSignals.get(e);return t||(t=this.editor.signals.atom(`editor.query.bindingsToShape.${e}`,this.getBindingsToState(this.state,e),{isEqual:Q}),this.bindingsToShapeSignals.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:Q}),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(vt),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),bindingIdsByFromShape:new Map(e.bindingIdsByFromShape),bindingIdsByToShape:new Map(e.bindingIdsByToShape),relatedBindingIdsByShape:new Map(e.relatedBindingIdsByShape)};for(const r of s)o.bindingById.delete(r.id),wt(o,r);for(const{before:r,after:a}of i)r.fromId===a.fromId&&r.toId===a.toId||wt(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)xt(o,r);for(const{before:r,after:a}of i)r.fromId===a.fromId&&r.toId===a.toId||xt(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=>{g(e)&&(n.add(e.fromId),i.add(e.toId),s.add(e.fromId),s.add(e.toId))};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.bindingsFromShapeSignals.get(r)?.set(this.getBindingsFromState(t,r));for(const r of i)this.bindingsToShapeSignals.get(r)?.set(this.getBindingsToState(t,r));for(const r of s)this.bindingsForShapeSignals.get(r)?.set(this.getBindingsForState(t,r))}getBindingsFromState(e,t){return this.getBindingsForIds(e,e.bindingIdsByFromShape.get(t))}getBindingsToState(e,t){return this.getBindingsForIds(e,e.bindingIdsByToShape.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:{from:Ct(),to:Ct(),related:Ct()}};for(const i of t.removed)g(i)&&Mt(n,i,void 0);for(const i of t.updated)g(i.before)&&Mt(n,i.before,void 0),g(i.after)&&Mt(n,i.after,i.after);for(const i of t.added)g(i)&&Mt(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(It);return s.cacheByShape.set(i,d),d})({committed:"from"===e?this.getBindingsFromState(this.state,t):"to"===e?this.getBindingsToState(this.state,t):this.getBindingsForState(this.state,t),draftIndex:n,relation:e,shapeId:t})}},aa=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 Rt(this.getShapeLocalToPageTransformSignal(e).get())}getShapeParentToPageTransform(e){return e.startsWith("page:")?this.editor.pages.get(e)?$r.Identity():void 0:Rt(this.getOrCreateSignals(e).localToPageTransform.get())}getShapePositionedToPageTransform(e){return Rt(this.getOrCreateSignals(e).positionedToPageTransform.get())}getShapePageBounds(e){return Et(this.getShapePageBoundsSignal(e).get())??void 0}getShapePositionedBounds(e){return Et(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 At(this.getCachedShapeGeometry(e)?.corners)}getShapePageOutlineVertices(e){return At(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 Yt(this.editor,n,e=>this.editor.shapes.get(e))){const e=this.editor.shapes.getUtil(i).getChildClipLocalPolygons(i);if(!e||!B(e))continue;const n=this.getOrCreateSignals(i.id).localToPageTransform.get()?.tryInvert();if(!n||!E(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 Yt(this.editor,t,e=>this.editor.shapes.get(e))){const e=this.editor.shapes.getUtil(i).getChildClipLocalPolygons(i),t=e?B(e):null,s=this.getOrCreateSignals(i.id).localToPageTransform.get();if(!t||!s)continue;const o=Dt(n,Xt(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:ne}),s=this.editor.signals.computed(`editor.query.shapeLocalToPageTransform.${e}`,()=>{const t=n(e);return t?Kt(this.editor,t,n):void 0},{isEqual:Bt}),o=this.editor.signals.computed(`editor.query.shapeGeometry.${e}`,()=>{const t=n(e);if(!t)return;const i=Ft(this.editor,t.parentId,n);return i?Te(t,this.editor.shapes.getUtil(t),i):void 0},{isEqual:kt});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=Ft(this.editor,t.parentId,n);return i?be(t,this.editor.shapes.getUtil(t),i):void 0},{isEqual:Bt}),pageBounds:this.editor.signals.computed(`editor.query.shapePageBounds.${e}`,()=>o.get()?.bounds,{isEqual:ne}),clipAncestorIds:this.editor.signals.computed(`editor.query.shapeClipAncestorIds.${e}`,()=>{const t=n(e);return t?Yt(this.editor,t,n).map(e=>e.id):[]},{isEqual:Q})},this.signalsByShapeId.set(e,t)}return t}},da=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)zt(s,d.parentId,d.id);const a=(e,t)=>{for(const n of s.get(t)??[]){const t=r.get(n);t&&(zt(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:Q}),this.pagesSignal=this.pagesAtom,this.unsubscribeFromStore=s.listen(e=>{this.handleStoreChange(e)}),this.currentPageShapeIdsSignal=i("editor.query.currentPageShapeIds",()=>this.getShapeIdsForPageSnapshot(t.get()),{isEqual:Q}),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:_t})}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:Q}),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($t),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){Lt(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;Lt(r.childShapeIdsByParent,l.parentId,l.id),Ot(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)Ot(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])}},ca=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}},la=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 Yr(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=xe(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)=>Yr.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||!Ut(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=xe(c,e,l,h),u=xe(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=>A(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=Ht(Wt(this.editor,t),s),r=Yr.FromPoints([new Fr(i.minX,i.minY),new Fr(i.maxX,i.maxY),new Fr(o.minX,o.minY),new Fr(o.maxX,o.maxY)]);n.push({shapeId:e,shapeBounds:i,queryBounds:r,pointHitTestBounds:o})}return new ca(n)}),this.pageIndexSignals.set(e,t)),t}getPageIndex(e=this.editor.pages.getCurrentId()){return this.getPageIndexSignal(e).get()}},ha=class extends Error{constructor(e){super(e),this.name="SnapshotParseError"}},pa=.001,ua=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"],ga=["free","aspect_ratio_locked"],fa=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:Wn}),this.frameGeometrySignal=n("editor.selectionOverlayFrameGeometry",()=>{const t=this.selectedShapeItemsSignal.get();if(0===t.length)return null;if(ci(t))return null;const n=e.selection.getFrame();return n?{bounds:n.bounds,rotation:n.rotation,rotationCenter:n.rotationCenter}:null},{isEqual:qn}),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:Gn}),this.pathSignal=n("editor.selectionOverlayPath",()=>{const e=this.selectedShapeItemsSignal.get();return ci(e)?e[0]?.path??null:null}),this.pageClipPathSignal=n("editor.selectionOverlayPageClipPath",()=>{const e=this.selectedShapeItemsSignal.get();return ci(e)?e[0]?.pageClipPath??null:null}),this.bindingSegmentsSignal=n("editor.selectionOverlayBindingSegments",()=>{const e=this.selectedShapeItemsSignal.get();return ci(e)?[...e[0]?.bindingSegments??[]]:[]},{isEqual:Fn}),this.frameStyleSignal=n("editor.selectionOverlayFrameStyle",()=>{const e=t.cameraZoom.get();return{strokeWidth:2/e,cornerRadius:3/e}},{isEqual:Vn}),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:P,rotationCenter:b,hasCompatibleRotation:v}=n,w=t[0]?.rotation??P,x=8/i,C=14/i,M=I.w<2*x,T=I.h<2*x,B=e=>0===P?e:Fr.RotWith(e,b,P),k=new Fr(I.minX,I.minY),E=new Fr(I.center.x,I.minY),A=new Fr(I.maxX,I.minY),R=new Fr(I.maxX,I.center.y),K=new Fr(I.maxX,I.maxY),F=new Fr(I.center.x,I.maxY),Y=new Fr(I.minX,I.maxY),X=new Fr(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(F)}],...M||T?[]:[{kind:"resize",id:"bottom_left",point:B(Y)}],...T?[]:[{kind:"resize",id:"left",point:B(X)}]].filter(e=>g.has(e.id)),rotateHandleAnchors:!u||y||!v||M||T?[]:[{kind:"rotate",id:"bottom_left_rotate",point:B(di({bounds:I,rotateOffset:C,referenceRotation:w,frameRotation:P}))}],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=Nn(e,t,n);return ua.filter(n=>s.every(e=>e.includes(n))&&Un(e,t,n,o).length>0)})(e,e.selection.getResizeTargets(),i?.rotation??0))},{isEqual:ai}),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 Yr(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:ri})}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=Xn(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 Yr(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}},ma=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})}},Sa=class extends Error{},ya=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===Ri(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.getToShapeSignal(e).get().flatMap(e=>{const n=this.getShapeSignal(e.fromId).get();return n?this.editor.bindings.getUtil(e).getTargetShapeContentCutoutLocalPolygons?.(this.editor,e,{fromShape:n,toShape:t})??[]:[]}):[]},{isEqual:te}),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}`,()=>Ri(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)}},Ia=["corner","edge_midpoint","corner","edge_midpoint","center","edge_midpoint","corner","edge_midpoint","corner"],Pa={corner:0,edge_midpoint:1,center:2,custom:3},ba=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=Cs(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?Vi(s):(a??(c=i.getLocalBounds(e),[new Fr(c.minX,c.minY),new Fr(c.maxX,c.minY),new Fr(c.maxX,c.maxY),new Fr(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=Cs(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?Vi(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?Vi(i):this.editor.shapes.getPageOutlineVertices(e.id)).map(e=>0===t.rotation?e.clone():Xn(e,r));if(0===a.length)continue;const d=Yr.FromPoints(a);o.push({id:e.id,bounds:d});const l=n.getBoundsSnapGeometry(e).points,h=[];if(void 0===l)Oi(d).forEach((e,t)=>{h.push({point:e,kind:Ia[t]??"custom"})});else{const n=this.editor.shapes.computeLocalToPageTransform(e);for(const i of l){const s=Cs(i),o=n.applyToPoint(s.point);this.editor.shapes.isPagePointInClip(e.id,o)&&h.push({point:0===t.rotation?o:Xn(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:ss(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.fromId===e?"from":n.toId===e?"to":null;if(!o)continue;const r=this.editor.bindings.getUtil(n).getGeometryDependentShapeIds?.(this.editor,n,{shape:s,role:o})??[];for(const e of r)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))})}},va=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 ba(e)}setIndicators(e){const t=e.map(xs);us(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:es(n.nodes,"x"),y:es(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=qi(e.initialSelectionBounds,e.dragDelta),i=(s=Oi(e.initialSelectionBounds),o=e.dragDelta,s.map(e=>e.add(o)));var s,o;const r=this.gapCache.get(e.snapshot)??{x:es(e.snapshot.nodes,"x"),y:es(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:ps(ls("x",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===c?.type?new Set(c.candidatePointIds??[]):void 0,releaseThreshold:a,selectionPointKinds:Ia,switchDistance:d,stats:h}),is("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:ps(ls("y",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===l?.type?new Set(l.candidatePointIds??[]):void 0,releaseThreshold:a,selectionPointKinds:Ia,switchDistance:d,stats:h}),is("y",n,r.y,e.threshold,{previousSnapId:"gaps"===l?.type?l.id:null,releaseThreshold:a,switchDistance:d}),{previousSnap:l,switchDistance:d}),g=new Fr(p?.nudge??0,u?.nudge??0),f=[];return"points"===p?.type?f.push(...ms("x",p,g,e.snapshot.coordinateSpace)):"gaps"===p?.type&&f.push(ws(p,e.snapshot.coordinateSpace,g)),"points"===u?.type?f.push(...ms("y",u,g,e.snapshot.coordinateSpace)):"gaps"===u?.type&&f.push(ws(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=Di({handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY}),i=hs(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:ls("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:ls("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 Fr(h?.nudge??0,p?.nudge??0);if(e.isAspectRatioLocked&&Ki(f=n)!==Fi(f)&&Yi(f)!==Xi(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=Di({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?(Ki(n)?(i+=t.x,s-=t.x):Fi(n)&&(i-=t.x,s+=t.x),Yi(n)?(o+=t.y,r-=t.y):Xi(n)&&(o-=t.y,r+=t.y)):(Ki(n)?i+=t.x:Fi(n)&&(s+=t.x),Yi(n)?o+=t.y:Xi(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 Yr(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=zi({axis:"x",startBounds:e,bounds:t,handleId:n,scale:i,isResizingFromCenter:o}),a=zi({axis:"y",startBounds:e,bounds:t,handleId:n,scale:s,isResizingFromCenter:o});return{scaleX:Ki(n)||Fi(n)?r*(t.w/Math.max(1,e.w)):i??1,scaleY:Yi(n)||Xi(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 Li({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=hs("any",S),I=[];if(u.x){const t=ls("x",y,e.snapshot.pointIndex,1e-8,{stats:l});t&&I.push(...bs("x",t,Fr.Zero(),e.snapshot.coordinateSpace,S,e.snapshot.nodes))}if(u.y){const t=ls("y",y,e.snapshot.pointIndex,1e-8,{stats:l});t&&I.push(...bs("y",t,Fr.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=Ms(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=Zi(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:Ps("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=Ms(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 Fr(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(vs("x",s.add(d),n)),i&&o&&l.push(vs("y",o.add(d),i)),{snappedPagePoint:c,nudge:d,indicators:l}}},wa=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){ne(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&&J(t.rawPagePoint,n.rawPagePoint)&&J(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||!Yn(i,s))return!1}return!0})(this._terminalBindingGuidesSignal.get(),t)||this._terminalBindingGuidesSignal.set(t.map(Rn))}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)}},xa=class{editor;animationScheduler;_viewportScreenSizeSignal;viewportScreenSizeSignal;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}getCurrentCamera(){return this.editor.state.camera.get()}getCamera(e=this.editor.pages.getCurrentId()){return this.editor.state.session.get().pageCameraById[e]??kr}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)}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:ks(o.x,e.x,d),y:ks(o.y,e.y,d),z:ks(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),o={x:"number"==typeof e.x?e.x:s.x,y:"number"==typeof e.y?e.y:s.y,z:xn("number"==typeof e.z?e.z:s.z)};o.x===s.x&&o.y===s.y&&o.z===s.z||this.editor.session.update({pageCameraById:{...this.editor.state.session.get().pageCameraById,[i]:o}},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=xn(this.getCurrentCamera().z*Math.exp(.0015*-t));this.zoomCameraToScreenPoint(e,i,n)}zoomCameraToScreenPoint(e,t,n="system"){const i=xn(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 Fr(n.w/2,n.h/2);this.zoomCameraAtScreenPoint(i,e,t)}resetZoom(e="user"){const t=this.viewportScreenSizeSignal.get(),n=new Fr(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)}},Ca=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:Q}),this.retainedBaseShapeWindowSnapshotSignal=n("editor.retainedBaseShapeWindowSnapshot",e=>{const n=t.currentPageShapeIds.get(),i=null!==t.viewportPageBounds.get(),s=((e,t,n=0)=>As(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!==Ir&&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(As(i).length!==t.length)return null;const s=Ks(t);return Ks(i)>s+12?null:i})(As(e.ranges.map(e=>({...e}))),s);if(t)return Ys(n,t,{viewportReady:i})}return Ys(n,s,{viewportReady:i})},{isEqual:(e,t)=>Q(e.shapeIds,t.shapeIds)}),this.culledShapeIdSetSignal=n("editor.culledShapeIdSet",()=>new Set(this.culledShapeIdsSignal.get()),{isEqual:Z}),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:Q}),this.selectedShapeIdsOutsideCulledSetSignal=n("editor.selectedShapeIdsOutsideCulledSet",()=>new Set(this.selectedShapeIdsOutsideCulledSignal.get()),{isEqual:Z}),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:Q}),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:Es(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=As(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=Es(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=Rs(s?i.start-s.end:1/0,t),l=Rs(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?[]:As(r,2)})(n,s,this.selectedShapeIdsOutsideCulledSetSignal.get(),o);if(i&&e!==Ir&&e&&e.viewportReady&&e.ranges.length>0&&a.length>0){const t=As(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 Ys(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(As(i).length!==t.length)return null;const s=Ks(t);return Ks(i)>s+n?null:i})(t,a,o);if(s)return Ys(n,s,{viewportReady:i})}return Ys(n,a,{viewportReady:i})},{isEqual:(e,t)=>Q(e.shapeIds,t.shapeIds)}),this.retainedShapeIdsSignal=n("editor.retainedShapeIds",()=>this.retainedShapeWindowSnapshotSignal.get().shapeIds,{isEqual:Q}),this.renderVisibleShapeIdSetSignal=n("editor.renderVisibleShapeIdSet",()=>new Set(this.renderVisibleShapeIdsSignal.get()),{isEqual:Z}),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:Bs})}getPageIndexById(e){const t=new Map;for(const[n,i]of e.entries())t.set(i,n);return t}},Ma=class{signals=e();store;[Er];inputs;tools;cameraManager;editing;shapeUtils=new Ur;shapeSvgExporters=new Lr;shapeSvgDecorations=new Or;shapeHitTestDecorations=new Nr;bindingUtils=new Kr;interactions=new ta;runtime=new _r;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(Mr);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(Br);if(!u(e))throw new Error("Missing session record");return e},update:(e,t="system")=>{Xe(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)=>{Ye(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:()=>Be(this),pasteClipboardPayload:e=>(this.interaction.cancelForCommand(),ke(this,e)),duplicate:(e={})=>(this.interaction.cancelForCommand(),((e,t={})=>{const n=Be(e);return n?ke(e,{payload:n,offset:t.offset??Gr,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=ln(e,t);if(!n)return[];const i=hn(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=ln(e,t);return n?e.shapes.getUtil(t).getSelectionPagePoints(n)??[]:[]});if(0===n.length)return null;const i=Yr.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=ln(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:Yr.FromPoints(e.map(e=>Xn(e,t))))({points:r?[...r]:s.getPositionedOutlineVertices(t).map(n=>e.shapes.computePositionedToPageTransform(t).applyToPoint(n)),transform:n});return a?hn(e,t,o,s.flipSelectionBounds(o,{axis:i,selectionBounds:n.bounds,selectionLocalBounds:$n({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:()=>Bn(this,2),align:(e,t="user")=>(this.interaction.cancelForCommand(),((e,t,n="user")=>{const i=kn(e);if(i.length<2)return!1;const s=En(e,i[0].shape.parentId);if(!s)return!1;const o=Yr.FromPoints(i.flatMap(e=>[new Fr(e.bounds.minX,e.bounds.minY),new Fr(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=An(s,new Fr(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:()=>Bn(this,3),distribute:(e,t="user")=>(this.interaction.cancelForCommand(),((e,t,n="user")=>{const i=kn(e);if(i.length<3)return!1;const s=En(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=An(s,o?new Fr(d,0):new Fr(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=vn(e),n=1===t.length;return t.length>0&&t.every(t=>e.shapes.getUtil(t).canParticipateInSelectionResize(t,{editor:e,isOnlyAffectedShape:n}))})(this),canFlip:()=>bn(this),canRotate:()=>(e=>{const t=vn(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 In(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 wn(e,e.selection.getIds())){const t=e.shapes.get(s);t&&i(t)}return t})(this),getRotationTargets:()=>{return Pn(e=this,e.selection.getIds()).map(t=>e.shapes.get(t)).filter(e=>!!e);var e},getPageBounds:()=>this.selectionGeometry.pageBounds.get()?.clone()??null,getFrame:()=>yi(this),containsPoint:e=>((e,t)=>{const n=yi(e);if(!n)return!1;const i=Ii(e,t);return!!i&&n.bounds.containsPoint(i)})(this,e),toFramePoint:e=>Ii(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(!ie(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")=>nt(this,e,{flag:"isHidden",value:t,source:n}),setLocked:(e,t,n="user")=>nt(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=>fi(this,e),computeExportBoundsInShapeSpace:(e,t)=>function(e,t,n){if(t.id===n.id)return fi(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=mi(e,n).tryInvert();return i?Me(t,e.shapes.getUtil(t),i.compose(mi(e,t))):null}(this,e,t),computeLocalToPageTransform:e=>mi(this,e),computeRenderToPageTransform:e=>function(e,t){return((e,t,n)=>Pe(e,t,n))(t,e.shapes.getUtil(t),gi(e,t))}(this,e),computeExportToPageTransform:e=>((e,t)=>ve(t,e.shapes.getUtil(t),gi(e,t)))(this,e),computePageBounds:e=>function(e,t){return((e,t,n)=>Yr.FromPoints(Ce(e,t,n)))(t,e.shapes.getUtil(t),gi(e,t))}(this,e),computeExportPageBounds:e=>function(e,t){return((e,t,n)=>Me(e,t,ve(e,t,n)))(t,e.shapes.getUtil(t),gi(e,t))}(this,e),computeGeometry:e=>Si(this,e),computePositionedToPageTransform:e=>((e,t)=>be(t,e.shapes.getUtil(t),gi(e,t)))(this,e),computePageCenter:e=>Si(this,e).center,computePageCorners:e=>Si(this,e).corners,computePageOutlineVertices:e=>Si(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:()=>Ti(this),getSelectionGroupState:()=>Pi(this),canGroupSelection:()=>null!==Pi(this),canGroup:e=>((e,t)=>null!==bi(e,t))(this,e),group:(e,t="user")=>wi(this,e,t),groupSelection:(e="user")=>((e,t="user")=>{const n=wi(e,e.selection.getIds(),t);return n&&e.commands.setSelectedShapeIds([n.id],{source:t}),n})(this,e),getUngroupableSelectionIds:()=>xi(this),getUngroupableIds:e=>Ci(this,e),canUngroupSelection:()=>xi(this).length>0,canUngroup:e=>((e,t)=>Ci(e,t).length>0)(this,e),ungroup:(e,t="user")=>Mi(this,e,t),ungroupSelection:(e="user")=>((e,t="user")=>Mi(e,e.selection.getIds(),t))(this,e),getSelectionSiblingOrderState:()=>Bi(this),canMoveSelectionWithinParent:e=>((e,t)=>{const n=Bi(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this,e),canMoveSelection:e=>((e,t)=>{const n=Ti(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this,e),canMove:(e,t)=>((e,t,n)=>{const i=ki(e,t);return"backward"===n?i?.canMoveBackward??!1:i?.canMoveForward??!1})(this,e,t),move:(e,t,n="user")=>Ei(this,e,t,n),moveToEdge:(e,t,n="user")=>Ai(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=Bi(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:se(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=$e(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:se(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")=>Ei(e,e.selection.getIds(),t,n))(this,e,t),moveSelectionToEdge:(e,t="user")=>((e,t,n="user")=>Ai(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)=>Sn(e,e.layers.getDescendantIds(t)))(this,e),getSubtreePageBounds:e=>((e,t)=>Sn(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=>mn(this,e),getSelectionTransformIds:e=>In(this,e),getSelectionRotationIds:e=>Pn(this,e),getExportTraversalIds:e=>((e,t)=>{const n=mn(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 mn(e,[t]))i.has(s)||e.shapes.isHidden(s)||(i.add(s),n.push(s))}return n})(this,e),getContainment:(e,t)=>li(this,this.shapeGeometryQueries,e,t),getContainingParentId:e=>((e,t,n,i)=>hi({editor:e,shapeTree:t,geometry:n,shapeIds:i}))(this,this.shapeTreeIndex,this.shapeGeometryQueries,e),getContainingParentIdAtPoint:(e,t)=>((e,t,n,i,s)=>hi({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=Ft(e,n.parentId,t=>e.shapes.get(t));if(!s)return null;const o=Te(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(!ui(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)))&&pi(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&&!Le(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(Le(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},getFromShape:e=>this.bindingQueries.getBindingsFromShape(e),getFromShapeSignal:e=>this.bindingQueries.getBindingsFromShapeSignal(e),getToShape:e=>this.bindingQueries.getBindingsToShape(e),getToShapeSignal:e=>this.bindingQueries.getBindingsToShapeSignal(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),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())=>Cn(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)=>Mn(this,e,t),zoomToFit:e=>((e,t)=>{const n=Cn(e);return!!n&&Mn(e,n,t)})(this,e),zoomToSelection:e=>((e,t)=>{const n=Tn(e,e.selection.getIds());return!!n&&Mn(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:3,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=en(e,"document"),s=new Set,o=[];return i.records.forEach((e,i)=>{if(!qt(e))throw new ha("Invalid document record: expected object");if("string"!=typeof e.id)throw new ha("Invalid document record id");if(s.has(e.id))throw new ha(`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 ha(`Unsupported document record type: ${String(e.typeName)}`);o.push((e=>{if("string"!=typeof e.id||!e.id.startsWith("asset:"))throw new ha("Invalid asset record id");if("string"!=typeof e.type)throw new ha("Invalid asset record type");return{id:e.id,typeName:"asset",scope:"document",type:e.type,props:qt(e.props)?e.props:{},meta:Qt(e.meta)}})(e))}else o.push(((e,t)=>{if("string"!=typeof e.id||!e.id.startsWith("binding:"))throw new ha("Invalid binding record id");if("string"!=typeof e.type)throw new ha("Invalid binding record type");if("string"!=typeof e.fromId||!e.fromId.startsWith("shape:"))throw new ha(`Invalid from id for binding ${e.id}`);if("string"!=typeof e.toId||!e.toId.startsWith("shape:"))throw new ha(`Invalid to id for binding ${e.id}`);const n=e.type,i=t.get(n);return{id:e.id,typeName:"binding",scope:"document",type:n,fromId:e.fromId,toId:e.toId,props:i.validateProps(e.props),meta:Qt(e.meta)}})(e,n));else o.push(((e,t,n)=>{if("string"!=typeof e.id||!e.id.startsWith("shape:"))throw new ha("Invalid shape record id");if("string"!=typeof e.type)throw new ha("Invalid shape record type");if("string"!=typeof e.parentId||!e.parentId.startsWith("page:")&&!e.parentId.startsWith("shape:"))throw new ha(`Invalid parent id for shape ${e.id}`);return{id:e.id,typeName:"shape",scope:"document",parentId:e.parentId,index:Gt(e.index,String(n+1).padStart(6,"0")),x:Vt(e.x,0),y:Vt(e.y,0),rotation:Vt(e.rotation,0),scaleX:Vt(e.scaleX,1),scaleY:Vt(e.scaleY,1),opacity:Math.min(1,Math.max(0,Vt(e.opacity,1))),isHidden:jt(e.isHidden,!1),isLocked:jt(e.isLocked,!1),meta:Qt(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 ha("Invalid page record id");return{id:e.id,typeName:"page",scope:"document",name:Gt(e.name,`Page ${t+1}`),index:Gt(e.index,String(t+1).padStart(4,"0")),meta:Qt(e.meta)}})(e,i));else o.push((e=>{if("document:main"!==e.id)throw new ha("Invalid document metadata record id");return{id:Mr,typeName:"document",scope:"document",meta:Qt(e.meta)}})(e))}),{schemaVersion:3,records:tn(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();rn(e,[...s.records,o],i),on(e),e.history.clear(),e.bindings.repairLoaded(i)})(this,e,t),loadSession:(e,t)=>sn(this,e,t),syncAfterDocumentRestore:()=>on(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 v of o){const t=e.shapes.get(v);t?d.push(t):a.push({id:v,reason:"missing-shape"})}if(0===d.length)return null;const c=[];for(const v of d){if(!e.shapes.getUtil(v).contributesToExportBounds(v))continue;const t=O(e,v,r);t&&(x(t)?c.push(t):a.push({id:v.id,reason:"missing-bounds"}))}if(0===c.length)return null;const l=G(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 _(e,t,n)){const t=N(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 v of d){for(;m.length>0&&!L(e,m[m.length-1].id,v);)y(m.pop());const t=n.get(v.type);if(!t){a.push({id:v.id,reason:"missing-exporter"});continue}const i=t.toSvg(v,p);if(!i){a.push({id:v.id,reason:"empty-output"});continue}if(!x($(e,v))){a.push({id:v.id,reason:"missing-bounds"});continue}const s=[],o=[];for(const n of e.shapeSvgDecorations.get(v.subType)){const e=n.toSvgBackground?.(v,p);e&&s.push(e);const t=n.toSvg?.(v,p);t&&o.push(t)}const r=0===s.length&&0===o.length?i:{tag:"g",children:[...s,i,...o]};u.push(v.id),S(v,r),t.toSvgForeground&&m.push(v)}for(;m.length>0;)y(m.pop());if(0===u.length)return null;const I=Math.max(1,l.w),P=Math.max(1,l.h),b=[];return h.length>0&&b.push({tag:"defs",children:h}),i.background&&b.push({tag:"rect",attrs:{x:l.x,y:l.y,width:l.w,height:l.h,fill:i.background}}),b.push(...g),{svg:q({tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",width:I,height:P,viewBox:`${j(l.x)} ${j(l.y)} ${j(I)} ${j(P)}`},children:b}),bounds:l,width:I,height:P,requestedShapeIds:s,exportedShapeIds:u,skippedShapes:a}}(this,e,this.shapeSvgExporters,t),getIntegrityReport:(e=this.selection.getIds())=>v({editor:this,exporters:this.shapeSvgExporters,shapeIds:e}),repairIntegrity:(e=this.selection.getIds())=>(({editor:e,exporters:t,shapeIds:n})=>{const i=Array.from(n),s=v({editor:e,exporters:t,shapeIds:i});s.repairableIssueCount>0&&e.bindings.repairLoaded("system");const o=v({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 ea(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 Cr(((e={})=>[a(e),d(),c()])(e.documentMeta??{}),{signals:this.signals,writeGuard:e=>this.assertStoreChangeAllowed(e)});((e,t)=>{e[Er]=t})(this,n),this.store=n,this.tools=new Hr(this),this.cameraManager=new xa(this,e.cameraAnimationScheduler),this.editing=new ma(this),this.interactionManager=new wa(this);const i=t("editor.session",()=>{const e=n.getRecordSignal(Br).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()]??kr),g=t("editor.selectedShapeIds",()=>{const e=i.get();return e.pageSelectedShapeIdsById[e.currentPageId]??[]},{isEqual:Q}),f=t("editor.selectionCount",()=>g.get().length),m=t("editor.selectedShapeIdSet",()=>new Set(g.get()),{isEqual:Z}),S=t("editor.pageTransform",()=>{const e=p.get();return $r.Scale(e.z,e.z).compose($r.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 Yr(n.x,n.y,e/n.z,t/n.z)});(e=>{const t=new qr(e);Wr.set(e,t)})(this),this.shapeSignals=new ya(this),this.shapeGeometryQueries=new aa(this),this.shapeTreeIndex=new da(this,s),this.bindingQueries=new ra(this),this.bindingManager=new Rr(this),this.spatialIndex=new la(this,this.shapeTreeIndex,this.shapeGeometryQueries),this.snaps=new va(this,e.snapDiagnostics),this.selectionGeometry=((e,t,n)=>{const i=e.signals.computed("editor.query.selectionGeometry",()=>fn(e,t,n),{isEqual:pn}),s=e.signals.computed("editor.query.selectionPageOutlineVertices",()=>i.get().outlineVertices,{isEqual:ee}),o=e.signals.computed("editor.query.selectionPageBounds",()=>i.get().pageBounds,{isEqual:ne}),r=e.signals.computed("editor.query.selectionLocalBounds",()=>i.get().localBounds,{isEqual:ne}),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:J}),hasCompatibleRotation:e.signals.computed("editor.query.selectionHasCompatibleRotation",()=>i.get().hasCompatibleRotation),selectionAnchorPagePoint:e.signals.computed("editor.query.selectionAnchorPagePoint",()=>i.get().selectionAnchorPagePoint,{isEqual:J})}})(this,g,e=>this.shapeGeometryQueries.getCachedShapeGeometry(e));const P=t("editor.selectedShapes",()=>g.get().map(e=>this.shapes.getSignal(e).get()).filter(e=>!!e)),b=t("editor.selectionCanFlip",()=>bn(this,g.get())),v=t("editor.selectionState",()=>{const e=g.get(),t=1===e.length?this.shapes.getSignal(e[0]).get()??null:null,n=P.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:b.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()}}),w=t("editor.selectionMetadata",()=>{const e=v.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:Ts}),x=t("editor.renderViewportPageBounds",e=>{const t=I.get();return t?e!==Ir&&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:ne});this.renderWindowManager=new Ca(this,{currentPageId:s,currentPageShapeIds:this.shapeTreeIndex.currentPageShapeIdsSignal,selectedShapeIds:g,selectedShapeIdSet:m,viewportPageBounds:I,renderViewportPageBounds:x}),this.selectionOverlay=new fa(this,{tool:o,selectedShapeIds:g,selectedShapes:P,cameraZoom:y}),this.operations=new sa(this,e.onUnhandledError),this.history=new na(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:P,selectionCount:f,selection:v,selectionMetadata:w,selectionPageBounds:this.selectionGeometry.pageBounds,selectionLocalBounds:this.selectionGeometry.localBounds,selectionAnchorPagePoint:this.selectionGeometry.selectionAnchorPagePoint,camera:p,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=tt(this),this.eventRouter=new Jr(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.viewport.pan(t.delta)})(i,s),Vr;if("keyboard"===s.type&&(e=>"Space"===e.code)(s)){if("key_up"===s.name){const t=e;return e=!1,t?Vr:void 0}if(i.state.shapeEditingSession.get())return;return e=!0,Vr}if("tick"===s.type&&t){const e=i.inputs.state.get();return e.pointerId===t.pointerId&&e.currentScreenPoint&&st(i,t.camera,e.currentScreenPoint),Vr}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 0===s.button&&(e=!0),t={pointerId:s.pointerId,buttons:o,camera:it(i,s.screenPoint)},jr}if(t&&s.pointerId===t.pointerId)return"pointer_move"===s.name?(0===(s.buttons&t.buttons)&&n(),Vr):"pointer_up"===s.name?(st(i,t.camera,s.screenPoint),n(),Vr):"pointer_cancel"===s.name?(n(),Vr):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}},Ta=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)}},Ba=class extends Ta{constructor(e){super(e,"hand"),this.initial="idle",this.addChild(new ka(e,this)),this.addChild(new Ea(e,this))}},ka=class extends Ta{constructor(e,t){super(e,"idle",t)}onPointerDown(e){0===e.button&&this.transition("panning",it(this.editor,e.screenPoint))}},Ea=class extends Ta{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&&st(this.editor,this.info,t)}onPointerUp(e){this.info&&st(this.editor,this.info,e.screenPoint),this.transition("idle")}onCancel(){this.transition("idle")}onExit(){this.info=null}},Aa=Math.PI/180*15,Ra=Math.PI/2,Ka=Math.PI/180*5,Fa=class extends Ta{info=null;onEnter(e){this.info=e,this.onInfoEnter()}onExit(){this.onInfoExit(),this.info=null}onInfoEnter(){}onInfoExit(){}},Ya=class extends Fa{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)}},Xa=class extends Fa{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=_s(this.editor,e,"always_apply");t&&this.apply(t)}onKeyDown(){this.applyFromInputs()}onKeyUp(){this.applyFromInputs()}applyFromInputs(){Ns(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()}},Da=class extends Fa{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,qs(e))}onPointerMove(e){this.info&&this.updateBrush(e.pagePoint,Ws(e),qs(e))}onTick(e){if(!this.info)return;const t=_s(this.editor,e,"apply_after_scroll_or_without_screen_point");t&&this.updateBrush(t.pagePoint,Ws(t),qs(t))}onKeyDown(){this.updateBrushFromInputs()}onKeyUp(){this.updateBrushFromInputs()}onPointerUp(e){this.info&&this.updateBrush(e.pagePoint,Ws(e),qs(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 Yr(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(){Ns(this.editor,e=>this.updateBrush(e.pagePoint,Ws(e),qs(e)))}complete(){this.transition("idle")}cancel(){this.transition("idle")}},za=class extends Xa{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&&!Q(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"))}},La=class extends Ta{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=Ws(e),a=Us(this.editor,n,t),d=r?null:((e,t,n)=>{const i=new Set(n);for(const s of Hs(e,t))if(i.has(s.ancestorId))return s.ancestorId;return null})(this.editor,n,t),c=r?null:d?a:null,l=Us(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()&&!Ws(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:Ws(e)})}else this.transition("pointing_selection_handle_interaction",i)}},Oa=class extends Ya{constructor(e,t){super(e,"pointing_canvas",t)}onDragThresholdExceeded(e){this.info&&this.transition("brushing",{...this.info,additiveSelection:Ws(e)})}onPointerUp(e){Ws(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")}},$a=class extends Ya{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=ln(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?[]:Un(e,t,n,Nn(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:Xn(t[0],r),endLocalPagePoint:Xn(t[1],r),middleLocalPagePoint:(()=>{const t=s(e);return t?Xn(t,r):null})()}):a.push({shape:c,pageShape:e,localBounds:Yr.FromPoints(n(c).map(e=>Xn(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 Fr(e.minX,e.minY),new Fr(e.maxX,e.minY),new Fr(e.maxX,e.maxY),new Fr(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")}},_a=class extends Ya{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=ln(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:Fr.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")}},Na=class extends Ya{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")}},Ua=class extends Ya{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)):$r.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:Ws(e)});const o=s.map(e=>e.id),r=i?.hasCompatibleRotation?i.rotation:0,a=i?.rotationCenter.clone()??Fr.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 Ws(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")}},Ha=class extends Xa{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=Qs(this.info.rotationCenter,this.info.rotation),o=Xn(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=Ki(t)||Fi(t)?s*(Ki(t)?-2:2)/Math.max(1,e.w):1,c=Yi(t)||Xi(t)?o*(Yi(t)?-2:2)/Math.max(1,e.h):1;switch(t){case"top":case"bottom":return{bounds:new Yr(e.minX,i.y-a,e.w,2*a),scaleX:d,scaleY:c};case"left":case"right":return{bounds:new Yr(i.x-r,e.minY,2*r,e.h),scaleX:d,scaleY:c};default:return{bounds:new Yr(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=Ki(t)?i:s,d=Ki(t)?s:i,c=Yi(t)?o:r,l=Yi(t)?r:o;Ki(t)||Fi(t)?a=n.x:(a=s,d=i),Yi(t)||Xi(t)?c=n.y:(c=r,l=o);const h=a-d,p=c-l,u=Ki(t)?d-a:h,g=Yi(t)?l-c:p,f=Ki(t)||Fi(t)?u/Math.max(1,e.w):1,m=Yi(t)||Xi(t)?g/Math.max(1,e.h):1;return{bounds:new Yr(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?Li({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&&js(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&&Zs(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")}},Wa=class extends Xa{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=Gs(Fr.Angle(this.info.center,e)-this.info.startAngle);if(t)i=Vs(i,Aa);else if(!n&&this.editor.inputs.state.get().screenVelocity.len()<.5){const e=this.info.initialSelectionRotation+i,t=Vs(e,Ra),n=Gs(t-e);Math.abs(n)<=Ka&&(i=Gs(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&&eo(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&&to(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")}},qa=class extends Xa{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 Fr(o,r):new Fr(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):$r.Identity()).tryInvert();if(!a)continue;const d=Ie(a.compose($r.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)}so(this.editor,this.info.movingShapeIds,e),((e,t,n)=>{const i=io(e,t,n);if(i===no(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&&so(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")}},Ga=class extends Ta{constructor(e){super(e,"select"),this.initial="idle",this.addChild(new La(e,this)),this.addChild(new Oa(e,this)),this.addChild(new Da(e,this)),this.addChild(new Ua(e,this)),this.addChild(new qa(e,this)),this.addChild(new $a(e,this)),this.addChild(new Ha(e,this)),this.addChild(new _a(e,this)),this.addChild(new Wa(e,this)),this.addChild(new Na(e,this)),this.addChild(new za(e,this))}},Va=sr(null),ja=sr(co([])),Qa="var(--land-shape-hover, var(--land-selection, #2563eb))",Za=2,Ja=or(e=>{const{Component:t,editor:n,isSelected:i,shape:s,shapeEditingSession:o}=e;
|
|
23
|
+
return mr(t,{editor:n,isSelected:i,shape:s,shapeEditingSession:o})}),ed=or(({shapeId:e,stackingOrder:t})=>{const n=ro(),i=mo(n.shapes.getSignal(e)),s=mo(n.shapes.getLocalToPageTransformSignal(e)),o=mo(n.shapes.getRenderVisibleSignal(e)),r=mo(n.shapes.getSelectedSignal(e)),a=mo(n.shapes.getEditingSessionSignal(e)),d=mo(n.shapes.getEffectiveOpacitySignal(e)),c=mo(n.shapes.getClipAncestorIdsSignal(e)),l=go(),h=mo(hr(()=>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=wo(n,i,s),g=d*h;
|
|
24
|
+
return mr("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?mr(So,{clipAncestorIds:c,shapeElementToPage:u.elementToPage,children:mr(Ja,{Component:p,shape:i,editor:n,isSelected:r,shapeEditingSession:a})}):null})}),td=or(({shapeId:e,stackingOrder:t})=>{const n=ro(),i=mo(n.shapes.getSignal(e)),s=mo(n.shapes.getLocalToPageTransformSignal(e)),o=mo(n.shapes.getHoveredSignal(e)),r=mo(n.state.selectionCount),a=mo(n.render.interaction.brushBoxActive),d=mo(n.shapes.getRenderVisibleSignal(e)),c=mo(n.state.tool).activeToolId,l=mo(n.shapes.getSelectedSignal(e)),h="select"===c&&l,p=mo(n.shapes.getEditingSessionSignal(e)),u=mo(n.shapes.getRenderOrderSignal(e)),g=mo(n.shapes.getDropTargetSignal(e)),f=mo(n.shapes.getEffectiveOpacitySignal(e)),m=mo(n.shapes.getClipAncestorIdsSignal(e)),S=go(),y=mo(hr(()=>S.getShapeOpacityValue(n,e),[n,S,e]));if(!i||!s)return null;const I=S.getShapeRenderer(i.type);if(!I)return null;const P=I.component,b=I.hoverComponent,v=S.getShapeDecorations(i.subType),w=o&&!(1===r&&h)&&!a,x=wo(n,i,s),C=f*y;
|
|
25
|
+
return Sr("div",{"data-ui":"shape-instance","data-shape-id":i.id,"data-shape-type":i.type,"data-selected":h?"true":"false","data-hovered":w?"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?Sr(So,{clipAncestorIds:m,shapeElementToPage:x.elementToPage,children:[
|
|
26
|
+
mr(Ja,{Component:P,shape:i,editor:n,isSelected:h,shapeEditingSession:p}),v.map(e=>mr(Ja,{Component:e.component,shape:i,editor:n,isSelected:h,shapeEditingSession:p},e.id)),w&&b?mr(vo,{Component:b,editor:n,shape:i}):null]}):null,d&&g?mr(xo,{}):null]})}),nd=or(()=>{const e=ro();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&&!Co(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})(mo(e.render.viewport.retainedShapeIds),mo(e.state.currentPageShapeTree),go()).map((e,t)=>"shape"===e.layer?mr(td,{shapeId:e.shapeId,stackingOrder:t},e.shapeId):mr(ed,{shapeId:e.shapeId,stackingOrder:t},`${e.shapeId}:foreground`))}),id="rgba(100, 116, 139, 0.82)",sd="rgba(255, 255, 255, 0.84)",od=or(()=>mo(ro().render.interaction.bindingPreviewActive)?mr(rd,{}):null),rd=or(()=>{const e=ro(),t=mo(e.render.interaction.bindingPreview),n=mo(e.render.interaction.terminalBindingGuides);if(!t)return null;const i=n.some(e=>e.terminal===t.terminal&&e.targetShapeId===t.targetShapeId);
|
|
27
|
+
return Sr(fr,{children:[mr(ad,{targetShapeId:t.targetShapeId}),mr(dd,{bindingPreview:t,showGuide:!i})]})}),ad=or(({targetShapeId:e})=>{const t=ro(),n=mo(t.state.cameraZoom),i=mo(t.shapes.getSignal(e));return i?mr(Eo,{editor:t,shape:i,stroke:"rgba(14, 165, 233, 0.78)",fill:"rgba(14, 165, 233, 0.08)",strokeWidth:2/n}):null}),dd=or(({bindingPreview:e,showGuide:t})=>{const n=mo(ro().state.cameraZoom),i=2/n,s=6/n,o=4/n;
|
|
28
|
+
return Sr(fr,{children:[t?e.guidePath?mr(ko,{path:e.guidePath,strokeWidth:i,dashSize:s,gapSize:o,kind:"binding-preview",terminal:e.terminal}):mr(Bo,{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
|
+
mr("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
|
+
mr("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})]})}),cd=or(()=>mo(ro().render.interaction.brushBoxActive)?mr(ld,{}):null),ld=or(()=>{const e=mo(ro().render.interaction.brushBox);return e?mr("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}),hd=or(()=>{const e=ro(),t=mo(e.render.overlay.frameGeometry),n=mo(e.render.overlay.companionFrameGeometries);return t||0!==n.length?Sr(fr,{children:[t?mr(pd,{frameGeometry:t}):null,n.map((e,t)=>mr(pd,{frameGeometry:e},`companion-${t}`))]}):null}),pd=or(({frameGeometry:e})=>{const t=mo(ro().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 mr("g",{transform:0===i?void 0:`rotate(${d} ${s.x} ${s.y})`,children:mr("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})})}),ud=new Set(["top_left","top_right","bottom_right","bottom_left"]),gd=or(()=>{const e=ro(),t=mo(e.state.readonly),n=mo(e.render.overlay.handleAnchors);return t||!n?null:mr(fd,{anchors:n})}),fd=or(({})=>{const e=ro(),t=mo(e.render.overlay.handles),n=mo(e.render.overlay.frameGeometry),i=fo(),s=mo(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=>ud.has(e.id)),p=o.filter(e=>!ud.has(e.id)),u=n?.rotation??0,g=180*u/Math.PI;
|
|
32
|
+
return Sr(fr,{children:[n?mr("g",{transform:n&&0!==u?`rotate(${g} ${n.rotationCenter.x} ${n.rotationCenter.y})`:void 0,children:p.map(e=>mr(Ao,{frame:n,handleId:e.id,zoom:s},e.id))}):null,h.map(e=>mr("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:Ro(e.id,u),pointerEvents:"auto"}},e.id)),r.map(e=>Sr("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:[mr("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),mr("path",{d:"M21 3v5h-5"})]},e.id)),d.map(e=>mr("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=>mr("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 mr(t?t.component:Ko,{handle:e,strokeWidth:a},`${e.type}:${e.id}`)})]})}),md=["ew-resize","nwse-resize","ns-resize","nesw-resize"],Sd=1e-6,yd=or(()=>{const e=ro(),t=mo(e.render.overlay.path),n=mo(e.render.overlay.pageClipPath),i=mo(e.render.overlay.bindingSegments),s=mo(e.render.overlay.selectedShapeItems),o=mo(e.render.overlay.frameStyle),r=cr().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>Sd?Math.abs(e.localToPage.determinant())/n:0;return e.strokeWidth+2*t/(i>Sd?i:n>Sd?n:1)})(c,o.strokeWidth):null,h=c&&null!==l?c.localBounds.expand(l):null;return t?Sr(fr,{children:[
|
|
34
|
+
mr(Id,{bindingSegments:i,strokeWidth:o.strokeWidth}),n||c&&h?Sr("defs",{children:[n?mr("clipPath",{id:a,clipPathUnits:"userSpaceOnUse",children:mr("path",{d:n,clipRule:"evenodd",fillRule:"evenodd"})}):null,c&&null!==l&&h?Sr("mask",{id:d,maskUnits:"userSpaceOnUse",maskContentUnits:"userSpaceOnUse",x:h.x,y:h.y,width:h.w,height:h.h,children:[mr(Fo,{dataPrefix:"path-halo-mask-outer",pathStyle:c,stroke:"white",strokeWidth:l}),mr(Fo,{dataPrefix:"path-halo-mask-center",pathStyle:c,stroke:"black",strokeWidth:c.strokeWidth})]}):null]}):null,
|
|
35
|
+
mr("g",{"data-selection-overlay":"lines",clipPath:n?`url(#${a})`:void 0,children:c&&null!==l?mr("g",{"data-selection-overlay":"path-halo-transform",transform:c.localToPage.toSvgString(),children:mr("g",{mask:`url(#${d})`,children:mr(Fo,{dataPrefix:"path-halo",pathStyle:c,stroke:"rgba(37, 99, 235, 0.45)",strokeWidth:l})})}):Sr(fr,{children:[mr("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}),mr("path",{"data-selection-overlay":"path",d:t,fill:"none",stroke:"rgba(37, 99, 235, 0.88)",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:o.strokeWidth})]})})]}):null}),Id=or(({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 mr(fr,{children:e.map(e=>e.guidePath?mr(ko,{path:e.guidePath,strokeWidth:n,dashSize:i,gapSize:s,kind:t,terminal:e.terminal},e.terminal):mr(Bo,{start:e.anchorPagePoint,end:e.boundaryPagePoint,startInset:o,endInset:r,strokeWidth:n,dashSize:i,gapSize:s,kind:t,terminal:e.terminal},e.terminal))})}),Pd=or(()=>mo(ro().render.interaction.selectionTranslationActive)?null:Sr(fr,{children:[
|
|
37
|
+
mr(yd,{}),
|
|
38
|
+
mr(hd,{}),
|
|
39
|
+
mr(gd,{})]})),bd="rgba(37, 99, 235, 0.9)",vd=or(()=>{const e=ro(),t=mo(e.state.readonly),n=mo(e.render.interaction.snapIndicators);return t||0===n.length?null:mr(wd,{indicators:n})}),wd=or(({indicators:e})=>{const t=mo(ro().state.cameraZoom);
|
|
40
|
+
return mr(fr,{children:e.map(e=>mr("points"===e.type?xd:Cd,{indicator:e,zoom:t},e.id))})}),xd=or(({indicator:e,zoom:t})=>{const n=2.5/t,i=1/t,[s,o]=e.line,r=180*e.rotation/Math.PI;
|
|
41
|
+
return Sr("g",{"data-ui":"snap-indicator",transform:0===e.rotation?void 0:`rotate(${r} ${e.rotationCenter.x} ${e.rotationCenter.y})`,children:[mr("path",{"data-ui":"snap-indicator-line",d:`M ${s.x} ${s.y} L ${o.x} ${o.y}`,fill:"none",stroke:bd,strokeWidth:i,strokeLinecap:"round"}),e.points.map((t,s)=>mr("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:bd,strokeWidth:i,strokeLinecap:"round"},`${e.id}:${s}`))]})}),Cd=or(({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=Yo(i,[n?l.startEdge[0].y:l.startEdge[0].x,n?l.startEdge[1].y:l.startEdge[1].x]);e&&(i=e);const t=Yo(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 mr("path",{"data-ui":"snap-gap-indicator",d:a.join(" "),transform:c,fill:"none",stroke:bd,strokeWidth:1/t,strokeLinecap:"round",strokeLinejoin:"round"})}),Md=or(()=>{const e=ro(),t=mo(e.render.interaction.terminalBindingGuides),n=mo(e.render.overlay.frameStyle);return 0===t.length?null:mr(Id,{bindingSegments:t,kind:"terminal-binding-guide",strokeWidth:n.strokeWidth})}),Td=or(()=>Sr("svg",{width:"100%",height:"100%",style:{display:"block",width:"100%",height:"100%",overflow:"visible"},children:[
|
|
43
|
+
mr("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
|
+
mr(vd,{}),
|
|
45
|
+
mr(Md,{}),
|
|
46
|
+
mr(od,{}),
|
|
47
|
+
mr(cd,{}),
|
|
48
|
+
mr(Pd,{}),
|
|
49
|
+
mr(Bd,{})]})),Bd=or(()=>{const e=fo().getCanvasOverlays();return 0===e.length?null:mr(fr,{children:e.map(({id:e,component:t})=>mr(t,{},e))})}),kd=[{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}],Ed="canvas-surface",Ad=`[data-ui="${Ed}"]`,Rd=["Inter","ui-sans-serif","system-ui","-apple-system","BlinkMacSystemFont","'Segoe UI'","sans-serif"].join(", ");export{K as A,Va as C,Ba as D,Ga as E,z as F,D as I,Mr as L,X as M,Y as N,Ls as O,F as P,g as R,ao as S,oo as T,ja as _,Ad as a,go as b,_o as c,Lo as d,Oo as f,mo as g,Za as h,Ed as i,R as j,zs as k,Ho as l,Qa as m,nr as n,No as o,zo as p,tr as r,$o as s,ir as t,Uo as u,fo as v,ro as w,co as x,uo as y,p as z};
|