@yuzhouu/canvas-kit 0.1.14 → 0.1.15

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/index.mjs CHANGED
@@ -1,46 +1,6 @@
1
- function e(){return new Cd}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:Ed,typeName:"document",scope:"document",meta:{...e}}}function d(){return{id:kd,typeName:"page",scope:"document",name:"Page 1",index:"0001",meta:{}}}function c(e=kd){return{id:Bd,typeName:"session",scope:"session",currentPageId:e,activeToolId:"select",isToolLocked:!1,editingShapeId:null,shapeEditingSession:null,pageCameraById:{[e]:{...Ad}},pageSelectedShapeIdsById:{[e]:[]},meta:{}}}function l(e){return!!e&&"page"===e.typeName}function h(e){return!!e&&"document"===e.typeName}function u(e){return!!e&&"shape"===e.typeName}function p(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 y(e){return e[Rd]}function S(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 v({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 w(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 b({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?(P(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=y(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 P(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 Ld(e.x+i.x*r,e.y+i.y*r)})(t,n,e))}function T(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 M(e){return e.length>=3&&e.every(e=>Number.isFinite(e.x)&&Number.isFinite(e.y))}function E(e){const t=e.filter(M).flatMap(e=>e);return t.length>0?Yd.FromPoints(t):null}function k(e,t){if(!M(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 B(e,t){return t.some(t=>k(e,t))}function A(e,t,n,i=0){if(!M(n))return!1;if(k(e,n)||k(t,n))return!0;for(let s=0;s<n.length;s+=1)if(T(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 F(e){return{kind:"custom",value:e}}function K(e){return!!e&&"object"==typeof e&&"theme"===e.kind&&Xd.includes(e.slot)}function D(e){return!!e&&"object"==typeof e&&"custom"===e.kind&&"string"==typeof e.value}function L(e){return Od[e]}function Y(e){return"custom"===e.kind?e.value:`var(${L(e.slot)}, ${zd[e.slot]})`}function X(e,t){if("custom"===e.kind)return e.value;const n=L(e.slot),i=zd[e.slot];return t?.(n,i)??i}function O(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 z(e,t,n){let i=e.shapes.computeExportPageBounds(t);if(!x(i))return i;for(const s of((e,t,n)=>{const i=[];for(const s of N(e,t,n)){const t=_(e,s);t&&x(t)&&i.push(t)}return i})(e,t,n)){const e=U(i,s);if(!e)return null;i=e}return i}function N(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 $(e,t,n,i){if(n.has(t.id))return n.get(t.id)??null;const s=e.shapes.getUtil(t),o=s.getChildExportClipLocalPolygons(t);if(!o||!E(o))return n.set(t.id,null),null;const r=e.shapes.computeExportToPageTransform(t).toSvgString(),a=s.getChildExportClipLocalBounds(t),[d]=o,c=1===o.length&&d&&a&&((e,t)=>{const n=[new Ld(t.minX,t.minY),new Ld(t.maxX,t.minY),new Ld(t.maxX,t.maxY),new Ld(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 _(e,t){const n=e.shapes.getUtil(t).getChildExportClipLocalPolygons(t);if(!n||!E(n))return null;const i=e.shapes.computeExportToPageTransform(t);return E(n.map(e=>e.map(e=>i.applyToPoint(e))))}function H(e){return e.map((e,t)=>`${0===t?"M":"L"} ${e.x} ${e.y}`).concat("Z").join(" ")}function U(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 Yd(n,i,s-n,o-i)}function W(e){if("string"==typeof e)return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;");const t=(e=>{const t=[];for(const[n,i]of Object.entries(e))null!=i&&!1!==i&&t.push(`${n}="${q("number"==typeof i?V(i):String(i))}"`);return 0===t.length?"":` ${t.join(" ")}`})(e.attrs??{}),n=e.children?.map(W).join("")??"";return n?`<${e.tag}${t}>${n}</${e.tag}>`:`<${e.tag}${t}/>`}function q(e){return e.replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function V(e){return Number.isFinite(e)?Number(e.toFixed(4)).toString():"0"}function G(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 j(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 Q(e,t){return e===t||(e&&t?e.x===t.x&&e.y===t.y:e===t)}function Z(e,t){return G(e,t,Q)}function J(e,t){return G(e,t,Z)}function ee(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 te(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))&&G(e,t,te);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)&&te(n[e],i[e]))}function ne(e){const t=Wd.get(e);if(!t)throw new Error("Editor record factory is not initialized");return t}function ie(e){const t=Number(e.split(":")[1]??0);return Number.isFinite(t)?t:0}function se(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 oe(e){const t=e.props.assetId;return"string"==typeof t&&t.startsWith("asset:")?t:null}function re(e,t){const n=[],i=new Set;for(const s of t)for(const t of ae(s)){if(i.has(t))continue;const s=e.assets.get(t);s&&(i.add(t),n.push(ue(s)))}return n}function ae(e){const t=[],n=new Set,i=oe(e);return i&&(n.add(i),t.push(i)),de(e.props,n,t),t}function de(e,t,n){if(pe(e))t.has(e)||(t.add(e),n.push(e));else if(Array.isArray(e))for(const i of e)de(i,t,n);else if(e&&"object"==typeof e)for(const i of Object.values(e))de(i,t,n)}function ce(e,t){return le(e,t)}function le(e,t){if(pe(e))return t.get(e)??e;if(Array.isArray(e))return e.map(e=>le(e,t));if(!e||"object"!=typeof e)return e;const n={};for(const[i,s]of Object.entries(e))n[i]=le(s,t);return n}function he(e){return ue(e)}function ue(e){if(Array.isArray(e))return e.map(ue);if(!e||"object"!=typeof e)return e;const t={};for(const[n,i]of Object.entries(e))t[n]=ue(i);return t}function pe(e){return"string"==typeof e&&e.startsWith("asset:")}function ge(e){return void 0!==e&&e<0?-1:1}function fe(e,t){if(void 0===t)return e;const n=2*Math.PI;return e+Math.round((t-e)/n)*n}function me(e,t){const n=2*Math.PI,i=((e-t+Math.PI)%n+n)%n-Math.PI;return Math.abs(i)}function ye(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*ge(n.preferredScaleYSign);return a({rotation:fe(Math.atan2(-e.c/t,e.d/t),n.preferredRotation),scaleX:0,scaleY:t})}const t=s*ge(n.preferredScaleXSign);return a({rotation:fe(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),u=s,p=o*(r<0?-1:1),g=[{rotation:fe(h,n.preferredRotation),scaleX:u,scaleY:p},{rotation:fe(h+Math.PI,n.preferredRotation),scaleX:-u,scaleY:-p}],f=ge(n.preferredScaleXSign),m=ge(n.preferredScaleYSign),y=e=>{let t=0;return void 0!==n.preferredScaleXSign&&ge(e.scaleX)===f&&(t+=1),void 0!==n.preferredScaleYSign&&ge(e.scaleY)===m&&(t+=1),{signMatches:t,rotationDistance:void 0===n.preferredRotation?0:me(e.rotation,n.preferredRotation)}},S=y(g[0]),I=y(g[1]),v=I.signMatches>S.signMatches||I.signMatches===S.signMatches&&I.rotationDistance<S.rotationDistance?g[1]:g[0];return a({rotation:v.rotation,scaleX:v.scaleX,scaleY:v.scaleY})}function Se(e,t,n){return n.compose(t.getLocalTransform(e))}function Ie(e,t,n){return n.compose(t.getPositionedTransform(e))}function ve(e,t,n){return Se(e,t,n)}function we(e,t,n){return Se(e,t,n).applyToPoint(t.getLocalBounds(e).center)}function be(e,t,n,i){const s=Ie(e,n,i).tryInvert();if(s)return s.applyToPoint(t);const o=n.getLocalBounds(e).center,r=new Ld(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 Ld(0===e.scaleX?0:d.x/e.scaleX,0===e.scaleY?0:d.y/e.scaleY))}function Pe(e,t,n){const i=Ie(e,t,n);return((e,t)=>t.getPositionedOutlineVertices(e))(e,t).map(e=>i.applyToPoint(e))}function xe(e,t,n){const i=Pe(e,t,n),s=((e,t,n)=>{const i=t.getLocalBounds(e),s=Se(e,t,n);return[new Ld(i.minX,i.minY),new Ld(i.maxX,i.minY),new Ld(i.maxX,i.maxY),new Ld(i.minX,i.maxY)].map(e=>s.applyToPoint(e))})(e,t,n);return{bounds:Yd.FromPoints(i),center:we(e,t,n),corners:s,outlineVertices:i}}function Ce(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)||Me(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=Me(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:Ee(e,a,r),assets:re(e,a)},bounds:ke(e,o)}}function Te(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 Ld(t.x+t.w/2,t.y+t.h/2)):e.offset??Vd})(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));y(e).atomic(()=>{const t=n.records.assets.map(t=>{const n=ne(e).createAsset({type:t.type,props:he(t.props),meta:he(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=ce(t.props,r),i=l.has(t.id),d=ne(e).createShape({type:t.type,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:he(t.meta)});return a.set(t.id,d.id),{original:t,draft:d}}).map(({original:e,draft:t})=>({...t,parentId:Be(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:he(s.props),meta:he(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 Me(e,t,n){if(!e.shapes.getUtil(t).canCopyToClipboard(t,{editor:e,copiedShapeIds:n}))return null;const i=ue(t);if(t.parentId.startsWith("shape:")&&n.has(t.parentId))return i;const s=e.shapes.computeLocalBounds(t),o=ye(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 Ee(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(ue(t)));return i}function ke(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 Yd(t,n,i-t,s-n)})(t.map(t=>e.shapes.getPageBounds(t)).filter(e=>!!e))??new Yd(0,0,0,0);return{x:n.x,y:n.y,w:n.w,h:n.h}}function Be(e,t,n){return e.startsWith("shape:")?t.get(e)??n:n}function Ae(e,t,n){for(const i of t){const t=e.shapes.get(i);t?.parentId.startsWith("shape:")&&n.add(t.parentId)}}function Re(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)||G(a,o)||(e.interaction.setBindingPreview(null),e.interaction.setSnapIndicators(null),e.session.update({pageSelectedShapeIdsById:{...r.pageSelectedShapeIdsById,[i]:o}},s))}function Fe(e,t,n="system"){y(e).put([{...e.session.get(),...t}],n)}function Ke(e){return e.map((e,t)=>({...e,index:String(t+1).padStart(4,"0")}))}function De(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?De(s,1,n)&&De(o,1,n):s>n&&o>n&&De(s,o,n))?null:{shapeId:e.id,shapeType:e.type,policy:i,scaleX:e.scaleX,scaleY:e.scaleY}}function Ye(e){return`Container shape ${e.shapeId} (${e.shapeType}) violates ${e.policy} child transform policy with scale (${e.scaleX}, ${e.scaleY})`}function Xe(e,t,n){const i=n.startsWith("shape:")?e.shapes.get(n):null,s=(i?e.shapes.computeLocalToPageTransform(i):$d.Identity()).tryInvert();if(!s)return null;const o=e.shapes.computeLocalToPageTransform(t);return ye(s.compose(o),e.shapes.computeLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY})}function Oe(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),y(e).remove(i,n.source),n.afterRemove?.(i),e.selection.remove(i,n.source),e.editing.removeShapeIds(i,n.source),i)}function ze(e,t,n,i=new Set){const s=[...t].sort((t,n)=>Ne(e,n)-Ne(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=$e(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=Yd.FromPoints(a),c=s.getResizeToFitDescendantsProps(t,d);if(!c)continue;const l=s.validateProps(c),h={...t,props:l},u=ye(s.getLocalTransform(t).compose($d.Translate(d.x,d.y)),s.getLocalBounds(h),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});if(!u)continue;const p=[...r.map(e=>({before:e,after:{...e,x:e.x-d.x,y:e.y-d.y}})),{before:t,after:{...t,...u,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!==p.length&&(y(e).put(p.map(e=>e.after),n),e.bindings.handleShapeChanges(p,n))}}function Ne(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 $e(e,t){return y(e).getAll().filter(u).filter(e=>e.parentId===t).sort((e,t)=>e.index.localeCompare(t.index))}function _e(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 He(e,t){const n=new Set;for(const i of t){const t=e.shapes.get(i);t&&_e(e,t,n)}return n}function Ue(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=$e(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=$e(e,a.parentId).filter(e=>!n.has(e.id)).flatMap(e=>e.id===a.id?c.map(e=>e.id):[e.id]),u=new Map(h.map((t,n)=>[t,ne(e).createShapeIndex(n+1)])),p=[];let g=!0;for(const n of c){if(!e.layers.canReceiveChild(a.parentId,n.id)){g=!1;break}const t=Xe(e,n,a.parentId);if(!t){g=!1;break}p.push({before:n,after:{...n,...t,parentId:a.parentId,index:u.get(n.id)??a.index}})}if(!g)continue;const f=new Set;_e(e,a,f);for(const e of f)o.push(e);const m=new Set(p.map(e=>e.after.id)),S=h.flatMap(t=>{if(m.has(t))return[];const n=e.shapes.get(t),i=u.get(t);return n&&i&&n.index!==i?[{before:n,after:{...n,index:i}}]:[]}),I=[...p,...S];I.length>0&&(y(e).put(I.map(e=>e.after),i),e.bindings.handleShapeChanges(I,i));const v=e.selection.getIds();if(v.includes(a.id)){const t=Array.from(new Set(p.map(t=>{const n=e.bindings.getShapeCompanionRootId(t.after.id);return m.has(n)?n:t.after.id})));e.commands.setSelectedShapeIds(v.flatMap(e=>e===a.id?t:[e]),{source:i})}const w=Oe(e,[a.id],{source:i});for(const e of w)n.add(e),s.push(e)}return s}function We(e,t,n){const i=n?.source??"user";e.bindings.runWithSuppressedReactions(n?.suppressBindingIds??[],()=>((e,t,n)=>{y(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=s.rotation??t.rotation,d=s.scaleX??t.scaleX,c=s.scaleY??t.scaleY,l=void 0===s.opacity?t.opacity:je(s.opacity,t.opacity),h=s.isHidden??t.isHidden,u=s.isLocked??t.isLocked,p=s.parentId??t.parentId,g=s.index??t.index,f=void 0===s.meta?t.meta:{...s.meta};if(!s.props&&void 0===s.meta&&o===t.x&&r===t.y&&a===t.rotation&&d===t.scaleX&&c===t.scaleY&&l===t.opacity&&h===t.isHidden&&u===t.isLocked&&p===t.parentId&&g===t.index)continue;const m=e.shapeUtils.get(t.type),y={...t,x:o,y:r,rotation:a,scaleX:d,scaleY:c,opacity:l,isHidden:h,isLocked:u,parentId:p,index:g,props:s.props?m.validateProps({...t.props,...s.props}):t.props,meta:f};n.push(y),i.push({before:t,after:y})}return n.length>0&&qe(e,n),{records:n,changes:i}})(e,t);0!==i.records.length&&((e,t,n)=>{y(e).put(t.records,n),t.changes.some(({before:e,after:t})=>e.parentId!==t.parentId)&&Ve(e,n),e.bindings.handleShapeChanges(t.changes,n),((e,t,n)=>{const i=new Set,s=new Set;for(const r of t)_e(e,r.before,i),_e(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;Ue(e,s,o,n),ze(e,i,n,o)})(e,t.changes,n)})(e,i,n)},n)})(e,t,i))}function qe(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(y(e).getAll().filter(u).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(Ye(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 Ve(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=>Ge(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 Ge(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 Qe(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=$e(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=Xe(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:ne(e).createShapeIndex(i+r+1),...o.get(n.id),meta:a===n.meta?void 0:a}})})(e,t);return!!i&&(0===i.length||We(e,i,n),!0)}function Ze(e){const t=t=>(e.assertDocumentWriteAllowed(),t()),n=((e,t)=>({createBinding(n,i){const s=i?.source??"user",o=ne(e).createBinding(n);if(!e.bindings.canBind(o))throw new Error(`Invalid binding endpoints for ${o.type} binding`);const r=new Set;return Ae(e,[o.fromId,o.toId],r),y(e).atomic(()=>{const n=e.bindings.getConflicting(o).map(e=>e.id);n.length>0&&e.bindings.cleanup(n,s),y(e).put([o],s),e.bindings.syncCreated(o,s),Ae(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 Ae(e,[o.fromId,o.toId,a.fromId,a.toId],d),y(e).atomic(()=>{const n=e.bindings.getConflicting(a).map(e=>e.id);n.length>0&&e.bindings.cleanup(n,s),y(e).put([a],s),e.bindings.syncUpdated(o,a,s),Ae(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&&(y(e).atomic(()=>{e.bindings.cleanup([s.id],i),y(e).remove([s.id],i)},i),!0)}}))(e,(t,n,i)=>{Ue(e,t,n,i)});return{createPage:(n,i)=>t(()=>function(e,t,n){const i=n?.source??"user",s=ne(e).createPage(t);let o=s;return y(e).atomic(()=>{const t=Ke([...e.pages.getAll(),s]);o=t.find(e=>e.id===s.id)??s,y(e).put(t,i),((e,t,n="system")=>{const i=e.state.session.get(),s=i.pageCameraById[t]??{...Ad},o=i.pageSelectedShapeIdsById[t]??[];Fe(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=Ke(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 y(e).atomic(()=>{r.length>0&&e.commands.deleteShapes(r,n),y(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],Fe(e,{currentPageId:n,pageCameraById:o,pageSelectedShapeIdsById:r},i)})(e,t,c,i),y(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&&y(e).atomic(()=>{y(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 y(e).atomic(()=>{y(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 y(e).atomic(()=>{y(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),y(e).atomic(()=>{y(e).put(Ke(a),i)},i))})(e,n,i))},createShapes:(n,i)=>t(()=>function(e,t,n){const i=[],s=n?.source??"user";return y(e).atomic(()=>{const o=t.map(t=>ne(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(qe(e,a),y(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)Qe(e,{ids:o,parentId:t},n)}const d=He(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)}Ue(e,t,c,s)}ze(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 qe(e,t),y(e).atomic(()=>{y(e).put(t,i),Ve(e,i);const n=He(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;Ue(e,n,s,i),ze(e,n,i,s)},i),t.map(t=>e.shapes.get(t.id)).filter(e=>!!e)})(e,n,i)),updateShapes(n,i){t(()=>We(e,n,i))},reparentShapes:(n,i)=>t(()=>Qe(e,n,i)),deleteShapes(n,i){t(()=>function(e,t,n){const i=n?.source??"user",s=e.layers.includeDescendants(t),o=He(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 y(e).getAll().filter(u)){const e=oe(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),y(e).atomic(()=>{Oe(e,s,{source:i,afterRemove:()=>{a.length>0&&y(e).remove(a,i),Ue(e,o,r,i),ze(e,o,i,r)}})},i)}(e,n,i))},createAsset:(n,i)=>t(()=>((e,t,n)=>{const i=n?.source??"user",s=ne(e).createAsset(t);return y(e).atomic(()=>{y(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?[]:(y(e).atomic(()=>{y(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 y(e).atomic(()=>{y(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)&&(y(e).atomic(()=>{y(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();Fe(e,{currentPageId:t,pageCameraById:{...s.pageCameraById,[t]:s.pageCameraById[t]??{...Ad}},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)=>{Re(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),Fe(e,{activeToolId:t},i)})(e,t,n)},setToolLocked(t,n){((e,t,n)=>{const i=n?.source??"system";e.tools.syncLockedState(t),Fe(e,{isToolLocked:t},i)})(e,t,n)}}}function Je(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 et(e,t){return{originScreenPoint:t.clone(),originCamera:e.state.camera.get()}}function tt(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 nt(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 it(e){return{timestamp:e.timestamp,screenPoint:e.screenPoint.clone(),pointerId:e.pointerId,button:e.button,pointerType:e.pointerType}}function st(e,t){return e.pointerId===t.pointerId&&e.button===t.button&&e.pointerType===t.pointerType}function ot(e){return{claimed:"stop"===e?.propagation}}function rt(){return Ld.Zero()}function at(e,t,n){if(n<=0)return rt();const i=t.x-e.x,s=t.y-e.y;return 0===i&&0===s?rt():new Ld(i/n,s/n)}function dt(e,t){return e.shiftKey===t.shiftKey&&e.altKey===t.altKey&&e.ctrlKey===t.ctrlKey&&e.metaKey===t.metaKey&&e.accelKey===t.accelKey}function ct(e,t){return e.canUndo===t.canUndo&&e.canRedo===t.canRedo}function lt(e){return{added:[...e.added],updated:e.updated.filter(({before:e,after:t})=>!ht(e,t)),removed:[...e.removed]}}function ht(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)=>ht(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)&&ht(n[e],i[e]))}function ut(e){return JSON.parse(JSON.stringify(e))}function pt(e){return JSON.parse(JSON.stringify(e))}function gt(e,t,n){const i=e.get(t);i?i.push(n):e.set(t,[n])}function ft(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 mt(e,t){return e.fromId===t.fromId?e.id.localeCompare(t.id):e.fromId.localeCompare(t.fromId)}function yt(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):mt(t,n)}function St(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&&yt(n,t,o)<0)return s}return e.length})(o,n,i,s),0,n.id),e.set(t,r),!0}function It(e){return g(e.before)&&g(e.after)}function vt(e,t){ft(e.bindingIdsByFromShape,t.fromId,t.id),ft(e.bindingIdsByToShape,t.toId,t.id),ft(e.relatedBindingIdsByShape,t.fromId,t.id),ft(e.relatedBindingIdsByShape,t.toId,t.id)}function wt(e,t){const n=t=>e.bindingById.get(t);St(e.bindingIdsByFromShape,t.fromId,t,"from",n),St(e.bindingIdsByToShape,t.toId,t,"to",n),St(e.relatedBindingIdsByShape,t.fromId,t,"related",n),St(e.relatedBindingIdsByShape,t.toId,t,"related",n)}function bt(){return{changesByShape:new Map,cacheByShape:new Map}}function Pt(e,t,n){for(const i of oc)for(const s of xt(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 xt(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 Ct(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 Tt(e,t){return e===t||(e&&t?ee(e.bounds,t.bounds)&&Q(e.center,t.center)&&Z(e.corners,t.corners)&&Z(e.outlineVertices,t.outlineVertices):e===t)}function Mt(e){return e?e.clone():e}function Et(e){return e?.map(e=>e.clone())}function kt(e){return e?new $d(e.a,e.b,e.c,e.d,e.e,e.f):void 0}function Bt(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=$d.Identity();for(let a=i.length-1;a>=0;a-=1){const t=i[a];t&&(r=Se(t,e.shapes.getUtil(t),r))}return r}function At(e,t,n){if(t.startsWith("page:"))return e.pages.get(t)?$d.Identity():void 0;const i=n(t);return i?Bt(e,i,n):void 0}function Rt(e,t,n){const i=[],s=new Set;let o=t.parentId;for(;o.startsWith("shape:");){const t=o;if(s.has(t))break;s.add(t);const r=n(t);if(!r)break;const a=e.shapes.getUtil(r).getChildClipLocalPolygons(r);a&&E(a)&&i.push(r),o=r.parentId}return i.reverse()}function Ft(e,t){return Yd.FromPoints([new Ld(e.minX,e.minY),new Ld(e.maxX,e.minY),new Ld(e.maxX,e.maxY),new Ld(e.minX,e.maxY)].map(e=>t.applyToPoint(e)))}function Kt(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 Yd(n,i,s-n,o-i)}function Dt(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 Yt(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 Xt(e){return u(e.before)&&u(e.after)}function Ot(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})}function zt(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 Nt(e,t,n){if(n.containsPoint(e)||n.containsPoint(t))return!0;const i=[new Ld(n.minX,n.minY),new Ld(n.maxX,n.minY),new Ld(n.maxX,n.maxY),new Ld(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!==zt(e,t,n,o))return!0}return!1}function $t(e,t){return Yd.FromPoints([new Ld(e.minX,e.minY),new Ld(e.maxX,e.minY),new Ld(e.maxX,e.maxY),new Ld(e.minX,e.maxY)].map(e=>t.applyToPoint(e)))}function _t(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function Ht(e,t){return"string"==typeof e?e:t}function Ut(e,t){return"number"==typeof e&&Number.isFinite(e)?e:t}function Wt(e,t){return"boolean"==typeof e?e:t}function qt(e){return _t(e)?e:{}}function Vt(e){return _t(e)?{x:Ut(e.x,Ad.x),y:Ut(e.y,Ad.y),z:Math.min(8,Math.max(.1,Ut(e.z,Ad.z)))}:null}function Gt(e){return Array.from(new Set((e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[])(e).filter(e=>e.startsWith("shape:"))))}function jt(e,t){if(!_t(e))throw new hc(`Invalid ${t} snapshot: expected object`);const n=e.schemaVersion,i=Ut(n,NaN),s="document"===t?3:1;if(i!==s)throw new hc(`Unsupported ${t} snapshot schema version: expected ${s}, received ${String(n)}`);if(!Array.isArray(e.records))throw new hc(`Invalid ${t} snapshot: records must be an array`);return{schemaVersion:i,records:e.records}}function Qt(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")})),u=l[0]?.id??"page:default",p=new Set(l.map(e=>e.id)),m=[...o].sort((e,t)=>e.index.localeCompare(t.index)||e.id.localeCompare(t.id)),y=new Map(m.map(e=>[e.id,e])),I=new Map,v=new Set,w=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),v.delete(e.shape.id),i.pop();continue}const n=e.shape;if(I.has(n.id)){i.pop();continue}if(v.add(n.id),n.parentId.startsWith("page:")){I.set(n.id,p.has(n.parentId)?n.parentId:u),v.delete(n.id),i.pop();continue}const s=y.get(n.parentId);s&&!v.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,u),v.delete(n.id),i.pop())}return I.get(e.id)??u})(e);return{...e,parentId:i,index:e.index||String(n+1).padStart(6,"0")}});for(const a of w){const e=Le(a,t.get(a.type));if(e)throw new hc(Ye(e))}const b=((e,t,n,i)=>{const s=new Map(e.map(e=>[e.id,e])),o=t.filter(e=>{const t=s.get(e.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=S(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")])),u=t.getLocalTransform(e),p=[];for(const i of d){if(e.parentId.startsWith("shape:")&&!Zt(s,n,e.parentId,i)){p.length=0;break}const t=n.get(i.type),o=ye(u.compose(t.getLocalTransform(i)),t.getLocalBounds(i),{preferredRotation:i.rotation,preferredScaleXSign:i.scaleX,preferredScaleYSign:i.scaleY});if(!o){p.length=0;break}p.push({...i,...o,parentId:e.parentId,index:h.get(i.id)??e.index})}if(p.length===d.length){for(const e of p)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]:[]})})(w,r,t,n),P=new Set(b.map(e=>e.id)),x=r.filter(e=>P.has(e.fromId)&&P.has(e.toId));return[i,...l,...c,...b,...x]}function Zt(e,t,n,i){const s=e.get(n);return!!s&&t.get(s.type).canReceiveChild(s,i)}function Jt(e,t,n){const i=n?.source??"system",s=function(e){const t=jt(e,"session").records[0];if(!_t(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(!_t(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,Vt(t)]).filter(e=>null!==e[1]);return Object.fromEntries(t)})(t.pageCameraById),o=(e=>{if(!_t(e))return{};const t=Object.entries(e).filter(([e])=>e.startsWith("page:")).map(([e,t])=>[e,Gt(t)]);return Object.fromEntries(t)})(t.pageSelectedShapeIdsById);return{schemaVersion:1,records:[{...n,id:n.id,typeName:"session",scope:"session",currentPageId:i,activeToolId:Ht(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=y(e).getAll().filter(m);e.interaction.cancel("restore"),e.editing.end({runEditEnd:!1,source:i}),e.editing.cancelOperation(),tn(e,[...o,s],i),nn(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"),Fe(e,{activeToolId:"select"},t)),e.tools.syncLockedState(i)})(e,i)}function en(e){nn(e),ne(e).syncCounters()}function tn(e,t,i){const s=y(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 nn(e){const t=y(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(u),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,se(c,d,o)??s);const g=n.find(e=>e.id===Bd),f=p(g)?g:c(s),m={...f,currentPageId:o.has(f.currentPageId)?f.currentPageId:s,pageCameraById:sn(f.pageCameraById,o),pageSelectedShapeIdsById:on(f.pageSelectedShapeIdsById,o,a,h)};t.put([m],"system")}function sn(e,t){const n={};for(const i of t){const t=e[i]??Ad;n[i]={x:Number.isFinite(t.x)?t.x:Ad.x,y:Number.isFinite(t.y)?t.y:Ad.y,z:Math.min(8,Math.max(.1,Number.isFinite(t.z)?t.z:Ad.z))}}return n}function on(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 rn(e,t){const n=ye(e.shapes.computeLocalToPageTransform(t),e.shapes.computeLocalBounds(t),{preferredRotation:t.rotation,preferredScaleXSign:t.scaleX,preferredScaleYSign:t.scaleY});return n?{...t,...n}:null}function an(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):$d.Identity()).tryInvert();if(!a)return null;const d=ye(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 dn(e,t){return Z(e.outlineVertices,t.outlineVertices)&&ee(e.pageBounds,t.pageBounds)&&ee(e.frameBounds,t.frameBounds)&&e.rotation===t.rotation&&Q(e.rotationCenter,t.rotationCenter)&&Q(e.selectionAnchorPagePoint,t.selectionAnchorPagePoint)&&e.hasRotation===t.hasRotation&&e.hasCompatibleRotation===t.hasCompatibleRotation}function cn(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)<uc?0:t}function ln(e,t){const n=e.shapes.computeLocalToPageTransform(t);return Math.atan2(n.b,n.a)}function hn(e,t,n){const i=t.get();if(0===i.length)return{outlineVertices:[],pageBounds:null,frameBounds: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 S of i){const t=e.shapes.getSignal(S).get();if(!t)continue;const i=e.shapes.getUtil(t),h=rn(e,t),u=h?i.getSelectionPagePoints(h):null;if(u&&o.push(...u),!i.contributesToSelectionFrame(t,{editor:e}))continue;r.push(t);const p=n(S);if(!p)continue;const g=i.getSelectionFramePositionedOutlineVertices(t,{editor:e}),f=g?(()=>{const n=e.shapes.computePositionedToPageTransform(t);return g.map(e=>n.applyToPoint(e))})():p.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 Yd(a,d,c-a,l-d):null,u=!(r.length>0)||function(e,t){if(0===t.length)return!0;const n=t[0],i=cn(n?ln(e,n):0);return t.every(t=>((e,t)=>{const n=cn(e)-cn(t),i=Math.PI/2;return Math.abs(n-Math.round(n/i)*i)<uc})(ln(e,t),i))}(e,r),p=((e,t,n)=>{if(0===t.length||!n)return 0;const i=t[0];return cn(i?ln(e,i):0)})(e,r,u),g=((e,t)=>t.some(t=>Math.abs(cn(ln(e,t)))>uc))(e,r),f=h?.center??null,m=0===s.length?null:Math.abs(p)<uc||!f?Yd.FromPoints(s):Yd.FromPoints(s.map(e=>Ld.RotWith(e,f,-p))),y=o.length>0?Yd.FromPoints(o):null;return{outlineVertices:s,pageBounds:h,frameBounds:m,rotation:p,rotationCenter:f,selectionAnchorPagePoint:m&&f?Math.abs(p)<uc?new Ld(m.center.x,m.minY):Ld.RotWith(new Ld(m.center.x,m.minY),f,p):y?new Ld(y.center.x,y.minY):null,hasRotation:g,hasCompatibleRotation:u}}function un(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 pn(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 Yd(n,i,s-n,o-i):null}function gn(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 fn(e,t){return In(e,t)}function mn(e,t){return In(e,t)}function yn(e,t=e.selection.getIds()){const n=Sn(e,t),i=1===n.length;return n.length>0&&n.every(t=>e.shapes.getUtil(t).canParticipateInSelectionFlip(t,{editor:e,isOnlyAffectedShape:i}))}function Sn(e,t=e.selection.getIds()){return un(e,In(e,t)).map(t=>e.shapes.getSignal(t).get()).filter(e=>!!e)}function In(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)||gn(e,n.id,i))})}function vn(e){return Math.min(8,Math.max(.1,e))}function wn(e,t=e.pages.getCurrentId()){return Pn(e,e.shapes.getForPage(t).map(({id:e})=>e))}function bn(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=vn(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 Pn(e,t){const n=[];for(const s of t){const t=e.shapes.getPageBounds(s);t&&x(t)&&n.push(new Ld(t.minX,t.minY),new Ld(t.maxX,t.maxY))}if(0===n.length)return null;const i=Yd.FromPoints(n);return x(i)?i:null}function xn(e,t){const n=Cn(e);return n.length>=t&&null!==Tn(e,n[0].shape.parentId)}function Cn(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 Tn(e,t){const n=t.startsWith("shape:")?e.shapes.get(t):null;return n?e.shapes.computeLocalToPageTransform(n).tryInvert():$d.Identity()}function Mn(e,t){const n=e.applyToPoint(Ld.Zero());return e.applyToPoint(t).sub(n)}function En(e){return{...e,anchorPagePoint:e.anchorPagePoint.clone(),boundaryPagePoint:e.boundaryPagePoint.clone()}}function kn(e,t){return e.terminal===t.terminal&&Q(e.anchorPagePoint,t.anchorPagePoint)&&Q(e.boundaryPagePoint,t.boundaryPagePoint)&&(e.guidePath??null)===(t.guidePath??null)}function Bn(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 An(e,t){return kn(e,t)&&e.ownerShapeId===t.ownerShapeId&&(e.targetShapeId??null)===(t.targetShapeId??null)}function Rn(e,t){return 0===t.rotation?e.clone():Ld.RotWith(e,t.rotationCenter,-t.rotation)}function Fn(e,t){return 0===t.rotation?e.clone():Ld.RotWith(e,t.rotationCenter,t.rotation)}function Kn(e,t){return Fn(e,t)}function Dn(e,t,n,i,s){return 0===n?i:i+(e-t)/n*s}function Ln({point:e,fromBounds:t,toBounds:n}){return new Ld(Dn(e.x,t.minX,t.w,n.minX,n.w),Dn(e.y,t.minY,t.h,n.minY,n.h))}function Yn({axis:e,bounds:t,selectionBounds:n}){return"horizontal"===e?new Yd(n.minX+n.maxX-t.maxX,t.minY,t.w,t.h):new Yd(t.minX,n.minY+n.maxY-t.maxY,t.w,t.h)}function Xn(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 On(e,t,n){return t.every(t=>{const i=e.shapes.computeLocalToPageTransform(t);return null!==Xn(Math.atan2(i.b,i.a),n)})}function zn(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})),gc.filter(e=>r.every(t=>t.includes(e))));var r;return i?o:o.filter(e=>"free"!==e)}function Nn(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)&&ee(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 $n(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&&Q(i.startPagePoint,s.startPagePoint)&&Q(i.endPagePoint,s.endPagePoint)&&Q(i.middlePagePoint,s.middlePagePoint)&&Nn(i.pathStyle,s.pathStyle)&&Bn(i.bindingSegments,s.bindingSegments)&&i.path===s.path&&i.pageClipPath===s.pageClipPath))return!1}return!0}function _n(e,t){return e===t||(e&&t?ee(e.bounds,t.bounds)&&e.rotation===t.rotation&&Q(e.rotationCenter,t.rotationCenter):e===t)}function Hn(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!_n(e[n]??null,t[n]??null))return!1;return!0}function Un(e,t){return e.strokeWidth===t.strokeWidth&&e.cornerRadius===t.cornerRadius}function Wn(e,t){return e.id===t.id&&Q(e.point,t.point)&&ee(e.bounds,t.bounds)}function qn(e,t){return e.id===t.id&&Q(e.point,t.point)&&ee(e.bounds,t.bounds)}function Vn(e,t){return e.terminal===t.terminal&&Q(e.point,t.point)&&ee(e.bounds,t.bounds)}function Gn(e,t){return Q(e.point,t.point)&&ee(e.bounds,t.bounds)}function jn(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&Q(e.point,t.point)&&ee(e.bounds,t.bounds)}function Qn(e,t){return e.id===t.id&&Q(e.point,t.point)}function Zn(e,t){return e.id===t.id&&Q(e.point,t.point)}function Jn(e,t){return e.terminal===t.terminal&&Q(e.point,t.point)}function ei(e,t){return Q(e.point,t.point)}function ti(e,t){return e.type===t.type&&e.id===t.id&&e.cursor===t.cursor&&Q(e.point,t.point)}function ni(e,t){return e===t||(e&&t?e.strokeWidth===t.strokeWidth&&G(e.resizeHandles,t.resizeHandles,Wn)&&G(e.rotateHandles,t.rotateHandles,qn)&&G(e.terminalHandles,t.terminalHandles,Vn)&&G(e.middleHandles,t.middleHandles,Gn)&&G(e.customHandles,t.customHandles,jn):e===t)}function ii(e,t){return e===t||(e&&t?G(e.resizeHandleAnchors,t.resizeHandleAnchors,Qn)&&G(e.rotateHandleAnchors,t.rotateHandleAnchors,Zn)&&G(e.terminalHandleAnchors,t.terminalHandleAnchors,Jn)&&G(e.middleHandleAnchors,t.middleHandleAnchors,ei)&&G(e.customHandleAnchors,t.customHandleAnchors,ti):e===t)}function si({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 Ld(e.maxX+t,e.minY-t):new Ld(e.minX-t,e.maxY+t)}function oi(e){return 1===e.length&&!!e[0]?.usesSelectionPathOverlay}function ri(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 ai({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 p of r){d.add(p.id);for(const e of t.getDescendantShapeIds(p.id))d.add(e)}let c=null,l=1/0,h=-1;const u=t.getShapeIdsForPage(a);for(let p=0;p<u.length;p+=1){const t=u[p];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(!ci(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"===ri(e,n,i.id,t.id)))continue;const a=n.getShapePageBounds(i.id);a&&di(a,p,c,l,h)&&(c=i,l=a.w*a.h,h=p)}return c?.id??a}function di(e,t,n,i,s){const o=e.w*e.h;return!n||o<i||o===i&&t>s}function ci(e,t){return t.canAutomaticallyReceiveChildren(e)}function li(e,t,n=new Set([t.id])){if(!t.parentId.startsWith("shape:"))return $d.Identity();const i=e.shapes.get(t.parentId);if(!i||n.has(i.id))return $d.Identity();const s=new Set(n);return s.add(i.id),Se(i,e.shapes.getUtil(i),li(e,i,s))}function hi(e,t){return xe(t,e.shapes.getUtil(t),li(e,t))}function ui(e){const t=e.selection.getFrameBounds(),n=e.selection.getRotationCenter();return t&&n?{bounds:t,rotation:e.selection.getRotation(),rotationCenter:n,hasCompatibleRotation:e.selection.hasCompatibleRotation()}:null}function pi(e,t){const n=ui(e);return n?Rn(t,n):null}function gi(e){return fi(e,e.selection.getIds())}function fi(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=>!gn(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 u=c.flatMap(t=>e.shapes.getPageOutlineVertices(t).map(e=>h?h.applyToPoint(e):e)),p=u.length>0?Yd.FromPoints(u):null;if(!p||!x(p))return null;const g={parentId:r,shapeIds:c,parentLocalBounds:p};return mi(e,g)?g:null}function mi(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 yi(e,t,n="user"){const i=fi(e,t);return i?((e,t,n)=>{const i=mi(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{y(e).atomic(()=>{const[d]=e.commands.createShapes([i],{source:n,deferMinimumChildRepair:!0});if(!d)throw new yc;if(a=d.id,!e.commands.reparentShapes({ids:t.shapeIds,parentId:d.id},{source:n}))throw new yc;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:ne(e).createShapeIndex(n+1)})),...t.shapeIds.map((t,n)=>({id:t,index:ne(e).createShapeIndex(n+1)}))],{source:n})},n)}catch(d){if(d instanceof yc)return null;throw d}return a?e.shapes.get(a)??null:null})(e,i,n):null}function Si(e){return Ii(e,e.selection.getIds())}function Ii(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)&&!!Xe(e,n,t.parentId))).map(e=>e.id)}function vi(e,t,n="user"){const i=Array.from(new Set(t)),s=new Set(((e,t)=>{const n=Ii(e,t),i=new Set(n);return n.filter(t=>!gn(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=>!Xe(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 p of d){const t=[];for(const n of e.layers.getChildren(p)){const e=a.get(n.id);e?t.push(...e.children.map(e=>e.id)):t.push(n.id)}c.set(p,t)}e.interaction.cancelForCommand();const l=[],h=new Set;try{y(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 yc;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:ne(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&&Oe(e,i,{source:n})})(e,r.map(e=>e.group.id),n)},n)}catch(u){if(u instanceof yc)return[];throw u}return l.length>0&&e.commands.setSelectedShapeIds(l,{source:n}),l}function wi(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 Pi(e,t){const n=t.map(t=>e.shapes.get(t)).filter(e=>!!e);if(0===n.length)return null;if(n.some(t=>t.isLocked||e.shapes.isHidden(t.id)))return null;const i=n[0]?.parentId;if(!i)return null;if(n.some(e=>e.parentId!==i))return null;const s=e.layers.getChildren(i),o=new Set(n.map(e=>e.id)),r=s.map((e,t)=>o.has(e.id)?t:-1).filter(e=>e>=0);return r.length!==n.length?null:{parentId:i,selectedCount:n.length,count:s.length,canMoveBackward:r.some(e=>e>0&&!o.has(s[e-1].id)),canMoveForward:r.some(e=>e<s.length-1&&!o.has(s[e+1].id))}}function xi(e,t,n,i="user"){const s=Pi(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:ne(e).createShapeIndex(n+1)})),{source:i}),!0)}function Ci(e,t,n,i="user"){const s=Pi(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:ne(e).createShapeIndex(n+1)})),{source:i}),!0}function Ti(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 Mi(e){return"top_left"===e||"left"===e||"bottom_left"===e}function Ei(e){return"top_right"===e||"right"===e||"bottom_right"===e}function ki(e){return"top_left"===e||"top"===e||"top_right"===e}function Bi(e){return"bottom_left"===e||"bottom"===e||"bottom_right"===e}function Ai({handleId:e,scaleX:t,scaleY:n}){const i=Mi(e)?t<0?"right":"left":Ei(e)?t<0?"left":"right":null,s=ki(e)?n<0?"bottom":"top":Bi(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 Ri({axis:e,startBounds:t,bounds:n,handleId:i,scale:s,isResizingFromCenter:o}){const r=Math.sign(s??1)||1;return o?r:"x"===e?Mi(i)?n.minX>=t.maxX?-1:1:Ei(i)?n.maxX<=t.minX?-1:1:r:ki(i)?n.minY>=t.maxY?-1:1:Bi(i)?n.maxY<=t.minY?-1:1:r}function Fi({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 Yd(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 Yd(c<0?e.minX:e.maxX-a,l<0?e.minY:e.maxY-d,a,d);break;case"top_right":h=new Yd(c<0?e.maxX-a:e.minX,l<0?e.minY:e.maxY-d,a,d);break;case"bottom_right":h=new Yd(c<0?e.maxX-a:e.minX,l<0?e.maxY-d:e.minY,a,d);break;case"bottom_left":h=new Yd(c<0?e.minX:e.maxX-a,l<0?e.maxY-d:e.minY,a,d);break;case"top":h=new Yd(t.center.x-a/2,l<0?t.maxY:t.maxY-d,a,d);break;case"right":h=new Yd(c<0?t.minX-a:t.minX,t.center.y-d/2,a,d);break;case"bottom":h=new Yd(t.center.x-a/2,l<0?t.minY-d:t.minY,a,d);break;case"left":h=new Yd(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 Ki(e){return[new Ld(e.minX,e.minY),new Ld(e.center.x,e.minY),new Ld(e.maxX,e.minY),new Ld(e.minX,e.center.y),e.center,new Ld(e.maxX,e.center.y),new Ld(e.minX,e.maxY),new Ld(e.center.x,e.maxY),new Ld(e.maxX,e.maxY)]}function Di(e,t){return"x"===t?e.x:e.y}function Li(e,t){return"x"===t?e.minX:e.minY}function Yi(e,t){return"x"===t?e.maxX:e.maxY}function Xi(e,t){return"x"===t?[e.minY,e.maxY]:[e.minX,e.maxX]}function Oi(e,t){const n=Math.max(e[0],t[0]),i=Math.min(e[1],t[1]);return n<=i?[n,i]:null}function zi(e,t){return null!==Oi(e,t)}function Ni(e,t){return new Yd(e.x+t.x,e.y+t.y,e.w,e.h)}function $i(e,t,n){return Ni(e,((e,t)=>"x"===e?new Ld(t,0):new Ld(0,t))(t,n))}function _i(e){return[new Ld(e.minX,e.minY),new Ld(e.maxX,e.minY),new Ld(e.maxX,e.maxY),new Ld(e.minX,e.maxY)]}function Hi(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 Ld(t.x+i.x*o,t.y+i.y*o))}function Ui(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 Ld(t.x+i.x*o,t.y+i.y*o)}function Wi(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=Hi(e,s,r);a>=i||(i=a,n=Ui(e,s,r))}return n?{point:n,distanceSquared:i}:null}function qi(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 Vi(e,t){const n="x"===t?"horizontal":"vertical",i=[...e].sort((e,n)=>Li(e.bounds,t)-Li(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=Yi(e.bounds,t),c=Li(o.bounds,t);if(c>r+1e-8)break;if(d>=c)continue;const l=Oi(Xi(e.bounds,t),Xi(o.bounds,t));l&&(r=c,s.push({direction:n,startNode:e,endNode:o,length:c-d,breadthIntersection:l}))}}return s}function Gi(e,t,n,i){const s=Oi(Xi(t.bounds,i),Xi(n.bounds,i));return s?{direction:e,startNode:t,endNode:n,length:Li(n.bounds,i)-Yi(t.bounds,i),breadthIntersection:s}:null}function ji(e,t){return[e,t.direction,t.startNode.id,t.endNode.id,t.length.toFixed(8)].join(":")}function Qi(e,t,n,i,s={}){const o=Xi(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 u=(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}))},p=n=>({id:"selection",bounds:$i(t,e,n)});for(const g of n){if(r<=g.length&&zi(o,g.breadthIntersection)){const n=Yi(g.startNode.bounds,e)+(g.length-r)/2-Li(t,e),i=p(n);u(n,[Gi(g.direction,g.startNode,i,e),Gi(g.direction,i,g.endNode,e)].filter(e=>null!==e),`${ji(e,g)}:center`)}const n=Yi(g.endNode.bounds,e)+g.length-Li(t,e),i=p(n);if(zi(Xi(i.bounds,e),g.breadthIntersection)){const t=Gi(g.direction,g.endNode,i,e);u(n,t?[g,t]:[],`${ji(e,g)}:after`)}const s=Li(g.startNode.bounds,e)-g.length-Yi(t,e),a=p(s);if(zi(Xi(a.bounds,e),g.breadthIntersection)){const t=Gi(g.direction,a,g.startNode,e);u(s,t?[t,g]:[],`${ji(e,g)}:before`)}}return h&&(!l||l.distance+d>=h.distance)?h:l}function Zi(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(Ji),n.sort(Ji),{x:t,y:n}}function Ji(e,t){return e.value-t.value||e.point.id.localeCompare(t.point.id)}function es(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 ts(e){return e.weight??(e.kind?vc[e.kind]:0)}function ns(e,t){return`points:${e}:${[...t].sort().join("|")}`}function is(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 ss(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=Di(g,e),a=es(n,e,t-r,t+r);s.stats&&(s.stats.candidatePointCount+=a.length);for(const n of a){const r=Di(n.point,e)-t,a=Math.abs(r),l={offset:r,distance:a,weight:ts(n),fromPrevious:!1};if(a<=i&&is(l,d,i)&&(d=l),s.previousCandidatePointIds?.has(n.id)&&a<=o){const e={...l,fromPrevious:!0};is(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,u=[];for(const[g,f]of t.entries()){const t=Di(f,e),i=es(n,e,t-h,t+h);for(const n of i){const i=Di(n.point,e)-t;Math.abs(i)>h||Math.abs(i-l.offset)>1e-8||u.push({selectionPoint:f,selectionPointKind:s.selectionPointKinds?.[g],candidatePoint:n.point,candidatePointKind:n.kind,candidatePointId:n.id,candidateNodeId:n.nodeId})}}s.stats&&(s.stats.matchedPointCount+=u.length);const p=Array.from(new Set(u.map(e=>e.candidatePointId)));return u.length>0?{type:"points",id:ns(e,p),nudge:l.offset,distance:l.distance,weight:l.weight,candidatePointIds:p,pairs:u}:null}function os(e,t){const n=[];switch(e){case"top":case"left":case"top_left":case"any":n.push(new Ld(t.minX,t.minY))}switch(e){case"top":case"right":case"top_right":case"any":n.push(new Ld(t.maxX,t.minY))}switch(e){case"bottom":case"right":case"bottom_right":case"any":n.push(new Ld(t.maxX,t.maxY))}switch(e){case"bottom":case"left":case"bottom_left":case"any":n.push(new Ld(t.minX,t.maxY))}return n}function rs(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 as(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&&Q(e.rotationCenter,t.rotationCenter)&&Q(e.line[0],t.line[0])&&Q(e.line[1],t.line[1])&&e.points.length===t.points.length&&e.points.every((e,n)=>{const i=t.points[n];return!!i&&Q(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&&Q(e.rotationCenter,t.rotationCenter)&&e.gaps.length===t.gaps.length&&e.gaps.every((e,n)=>{const i=t.gaps[n];return!!i&&((e,t)=>Q(e.startEdge[0],t.startEdge[0])&&Q(e.startEdge[1],t.startEdge[1])&&Q(e.endEdge[0],t.endEdge[0])&&Q(e.endEdge[1],t.endEdge[1]))(e,i)})}(e,i))})}function ds(e){return"horizontal"===e.direction?{startEdge:[new Ld(e.startNode.bounds.maxX,e.startNode.bounds.minY),new Ld(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new Ld(e.endNode.bounds.minX,e.endNode.bounds.minY),new Ld(e.endNode.bounds.minX,e.endNode.bounds.maxY)]}:{startEdge:[new Ld(e.startNode.bounds.minX,e.startNode.bounds.maxY),new Ld(e.startNode.bounds.maxX,e.startNode.bounds.maxY)],endEdge:[new Ld(e.endNode.bounds.minX,e.endNode.bounds.minY),new Ld(e.endNode.bounds.maxX,e.endNode.bounds.minY)]}}function cs(e,t,n,i){const s=t.pairs.some(({candidatePointKind:e,selectionPointKind:t})=>"center"===e&&"center"===t),o=qi([...t.pairs.map(({selectionPoint:e})=>e.add(n)),...t.pairs.map(({candidatePoint:e})=>e.clone())]),r=qi([...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:qi([...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=ps(e,a);return{id:gs(e,c,d),type:"points",axis:e,line:c,points:d,rotation:i.rotation,rotationCenter:i.rotationCenter.clone()}}function ls(e,t,n,i){return hs(e,t,n).map(t=>cs(e,t,n,i))}function hs(e,t,n){const i=new Map;for(const s of t.pairs){const t=Di(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 us(e,t,n){return"x"===e?[new Ld(t,n.minY),new Ld(t,n.maxY)]:[new Ld(n.minX,t),new Ld(n.maxX,t)]}function ps(e,t){if(0===t.length)return[Ld.Zero(),Ld.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 Ld(n,s),new Ld(n,o)]:[new Ld(n,s),new Ld(i,s)]}function gs(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 fs(e,t,n,i,s,o){return hs(e,t,n).map(t=>((e,t,n,i,s,o)=>{const r=cs(e,t,n,i),a=t.pairs[0],d=Di(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(...us(e,d,t))}const u=qi([...r.points,...us(e,d,s),...l]),p=ps(e,qi([...us(e,d,s),...l]));return{...r,id:gs(e,p,u),line:p,points:u}})(e,t,n,i,s,o))}function ms(e,t,n){const i="x"===e?new Ld(n.x,t.y):new Ld(t.x,n.y),s=qi([n.clone(),i]),o=ps(e,s);return{id:gs(e,o,s),type:"points",axis:e,line:o,points:s,rotation:0,rotationCenter:Ld.Zero()}}function ys(e,t,n){const i="horizontal"===e.gaps[0]?.direction?new Ld(0,n.y):new Ld(n.x,0),s=e.gaps.map(e=>({...e,startNode:"selection"===e.startNode.id?{...e.startNode,bounds:Ni(e.startNode.bounds,i)}:e.startNode,endNode:"selection"===e.endNode.id?{...e.endNode,bounds:Ni(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(ds),rotation:t.rotation,rotationCenter:t.rotationCenter.clone()}}function Ss(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 Is(e){return{point:e.point,kind:e.kind??"custom",weight:e.weight}}function vs(e){const t=e.sourcePointOffsets;return t&&t.length>0?t.map(t=>e.pagePoint.add(t)):[e.pagePoint]}function ws(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 Ps(e,t,n){return e+(t-e)*n}function xs(e,t,n){return Math.min(n,Math.max(t,e))}function Cs(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 Ts(e,t){if(!Number.isFinite(e))return t;const n=Math.max(0,Math.floor((e-3)/2));return Math.min(t,n)}function Ms(e){return e.reduce((e,t)=>e+(t.end-t.start),0)}function Es(e,t){const n=[];for(const i of t)n.push(...e.slice(i.start,i.end));return n}function ks(e,t,n){return{viewportReady:n?.viewportReady??!0,ranges:t.map(e=>({...e})),shapeIds:Es(e,t)}}function Bs(e){return{shapeUtils:e.flatMap(e=>e.shapeUtils??[]),shapeSvgExporters:e.flatMap(e=>e.shapeSvgExporters??[]),bindingUtils:e.flatMap(e=>e.bindingUtils??[])}}function As(e){let t=null;for(const i of e.splice(0).reverse())try{i()}catch(n){t??=n}return t}function Rs(e){return e.toLowerCase()}function Fs(e){return Math.min(1,Math.max(0,(96-e)/96))}function Ks(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 Ld.Zero();const i=Math.min(n,32),s=Fs(e.x),o=Fs(t.w-e.x),r=Fs(e.y),a=1.25*(o-s)*i,d=1.25*(Fs(t.h-e.y)-r)*i;return 0===a&&0===d?Ld.Zero():new Ld(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 Ds(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 Ls(e,t,n){const i=new Set(n);if(i.has(t))return t;const s=Ys(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)=>Ys(e,t)[0]?.ancestorId??null)(e,t)===o)?t:s[s.length-1]?.ancestorId??t}function Ys(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 Xs({shiftKey:e,accelKey:t}){return e||t}function Os({ctrlKey:e}){return e}function zs(e){let t=e;for(;t<=-Math.PI;)t+=2*Math.PI;for(;t>Math.PI;)t-=2*Math.PI;return t}function Ns(e,t){return Math.round(e/t)*t}function $s(e,t,n,i,s,o,r,a,d,c,l,h){const u=_s(c,l),p=Us({point:t.localBounds.center,startBounds:n,scaleX:s,scaleY:o,handleId:r,isResizingFromCenter:d}),g=(({bounds:e,fromBounds:t,toBounds:n})=>{const i=Ln({point:new Ld(e.minX,e.minY),fromBounds:t,toBounds:n}),s=Ln({point:new Ld(e.maxX,e.maxY),fromBounds:t,toBounds:n});return new Yd(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 Yd(p.x-g.w/2,p.y-g.h/2,g.w,g.h),m=Fn(p,u),y=e.shapes.getUtil(t.pageShape),S=Xn(t.pageShape.rotation,l),I=null!==S,v="perpendicular"===S?new Yd(f.center.x-f.h/2,f.center.y-f.w/2,f.h,f.w):f,w=I?v:(()=>{const e=y.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 Yd(m.x-i/2,m.y-r/2,i,r)})(),b=y.resizeSelectionBounds(t.pageShape,{handleId:r,isOnlyResizeTarget:a,pageCenter:m,selectionLocalBounds:w,scaleX:s,scaleY:o,isResizingFromCenter:d,selectionRotation:I?l:t.pageShape.rotation,selectionRotationCenter:I?c:m}),P=an(e,t.shape,t.pageShape,b);P&&Object.assign(h,P)}function _s(e,t){return{rotation:t,rotationCenter:e}}function Hs(e,t,n,i,s,o,r,a,d,c,l){const h=_s(d,c),u=Fn(Us({point:t.startLocalPagePoint,startBounds:n,scaleX:s,scaleY:o,handleId:r,isResizingFromCenter:a}),h),p=Fn(Us({point:t.endLocalPagePoint,startBounds:n,scaleX:s,scaleY:o,handleId:r,isResizingFromCenter:a}),h),g=t.middleLocalPagePoint?Fn(Us({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:[u,p],pageMiddlePoint:g}),m=an(e,t.shape,t.pageShape,f);m&&Object.assign(l,m)}function Us({point:e,startBounds:t,scaleX:n,scaleY:i,handleId:s,isResizingFromCenter:o}){const r=(({startBounds:e,handleId:t,isResizingFromCenter:n})=>n?e.center.x:Mi(t)?e.maxX:Ei(t)?e.minX:e.center.x)({startBounds:t,handleId:s,isResizingFromCenter:o}),a=(({startBounds:e,handleId:t,isResizingFromCenter:n})=>n?e.center.y:ki(t)?e.maxY:Bi(t)?e.minY:e.center.y)({startBounds:t,handleId:s,isResizingFromCenter:o});return new Ld(r+(e.x-r)*n,a+(e.y-a)*i)}function Ws(e,t,n,i,s){const o=t.localBounds.center,r=Kn(new Ld(t.pageShape.x+o.x,t.pageShape.y+o.y),{rotation:i,rotationCenter:n}),a=an(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 qs(e,t,n,i,s){const o=e.shapes.getUtil(t.pageShape).updateSelectionPagePoints(t.pageShape,{pagePoints:[Kn(t.startPagePoint,{rotation:i,rotationCenter:n}),Kn(t.endPagePoint,{rotation:i,rotationCenter:n})],pageMiddlePoint:t.middlePagePoint?Kn(t.middlePagePoint,{rotation:i,rotationCenter:n}):void 0}),r=an(e,t.shape,t.pageShape,o);r&&Object.assign(s,r)}function Vs(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 Gs(e,t,n){const i=n?e.layers.getContainingParentIdAtPoint(t,n):e.layers.getContainingParentId(t);if(!i)return null;const s=Vs(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 js(e,t,n){const i=Gs(e,t,n);i&&t.some(t=>e.shapes.get(t)?.parentId!==i)&&e.commands.reparentShapes({ids:[...t],parentId:i})}function Qs(e,t,n,i={}){let s=!0;return t.graph.effect(e,()=>{t.get(),s&&!1===i.fireImmediately?s=!1:(s=!1,n())})}function Zs(e){return e}function Js(e){return Object.freeze({id:e,kind:"api"})}function eo(e,t){return e.require(t)}function to(){const e=ad(Gc);if(!e)throw new Error("useEditor must be used within EditorContext.Provider");return e}function no({children:e,className:t,dataUi:n}){const i=to(),s=ud(null);return ld(()=>Qs("PageSpace.transform",i.state.pageTransform,()=>{const e=s.current;e&&(e.style.transform=i.state.pageTransform.get().toCssString())}),[i]),md("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 io(e){const t=new Set,n=new Map,i=[],s=new Set,o=new Map,r=new Map,a=[],d=new Set,c=[],l=new Set;for(const f of e){oo(t,f.id,"canvas render plugin id");for(const e of f.shapeRenderers??[])so(n,e.type,e,"shape renderer type");for(const e of f.shapeOpacityModifiers??[])oo(s,e.id,"shape opacity modifier id"),i.push(e);for(const e of f.canvasOverlays??[])so(o,e.id,e,"canvas overlay id");for(const e of f.selectionCustomHandleRenderers??[])so(r,e.type,e,"selection handle renderer type");for(const e of f.domEventGuards??[])oo(d,e.id,"DOM event guard id"),a.push(e);for(const e of f.canvasComponents??[])oo(l,e.id,"canvas component id"),c.push(e)}const h=Object.freeze([...o.values()].sort(ro)),u=Object.freeze({getShapeRenderer:e=>n.get(e)??null,getShapeOpacityValue(e,t){const n=i.map(n=>n.getOpacityValue(e,t));return Object.freeze({graph:e.signals,get:()=>n.reduce((e,t)=>e*t.get(),1)})}}),p=Object.freeze({getCanvasOverlays:()=>h,getSelectionCustomHandleRenderer:e=>r.get(e)??null}),g=Object.freeze({handle(e){for(const t of a)if("handled"===t.handle(e))return"handled";return"continue"},getCursor(e){for(const t of a){const n=t.getCursor?.(e);if(void 0!==n)return n}}});return Object.freeze({canvasComponents:Object.freeze(c),renderers:u,overlays:p,domEventGuards:g})}function so(e,t,n,i){if(e.has(t))throw new Error(`Duplicate ${i}: ${t}.`);e.set(t,n)}function oo(e,t,n){if(e.has(t))throw new Error(`Duplicate ${n}: ${t}.`);e.add(t)}function ro(e,t){return(e.order??0)-(t.order??0)}function ao(){return ad(jc)}function co(){return ao().renderers}function lo(){return ao().overlays}function ho(e){const t=rd(t=>Qs("useValue",e,t,{fireImmediately:!1}),[e]),n=rd(()=>e.get(),[e]);return gd(t,n,n)}function uo({children:e,clipAncestorIds:t,shapeElementToPage:n}){return 0===t.length?md(fd,{children:e}):t.reduceRight((e,t)=>md(po,{ancestorId:t,shapeElementToPage:n,children:e},t),e)}function po({ancestorId:e,children:t,shapeElementToPage:n}){const i=to(),s=ho(i.shapes.getSignal(e));if(!s)return md(fd,{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(fo).join(", ")})`:`path("${r.map(go).join(" ")}")`})(i,s,n);return o?md("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}):md(fd,{children:t})}function go(e){return e.map((e,t)=>`${0===t?"M":"L"} ${mo(e.x)} ${mo(e.y)}`).concat("Z").join(" ")}function fo(e){return`${mo(e.x)}px ${mo(e.y)}px`}function mo(e){return Number.isFinite(e)?Number(e.toFixed(3)).toString():"0"}function yo({Component:e,editor:t,shape:n}){
2
- return md("div",{"aria-hidden":"true","data-ui":"shape-hover-decoration",style:{position:"absolute",inset:0,pointerEvents:"none"},children:md(e,{shape:n,editor:t,strokeWidth:2/ho(t.state.cameraZoom)})})}function So(e,t,n){const i=e.shapes.computeRenderBounds(t),s=n.compose($d.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 Io(){
3
- return md("div",{"data-ui":"transform-descendant-ancestor-boundary",style:{position:"absolute",inset:0,border:"1px dashed #64748b",pointerEvents:"none"}})}function vo(){
4
- return md("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 wo(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 bo(){
5
- return md("div",{"data-ui":"shape-layer",className:"land-canvas__shape-layer",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%"},children:md(no,{dataUi:"shape-page-space",className:"land-canvas__shape-page-space",children:md(el,{})})})}function Po(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 xo({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=Po(a,d);
6
- return yd("g",{style:{pointerEvents:"none"},children:[md("line",{...l.underlay,x1:c.start.x,y1:c.start.y,x2:c.end.x,y2:c.end.y,fill:"none",stroke:nl,strokeLinecap:"round",strokeWidth:2.2*s}),md("line",{...l.segment,x1:c.start.x,y1:c.start.y,x2:c.end.x,y2:c.end.y,fill:"none",stroke:tl,strokeDasharray:`${o} ${r}`,strokeLinecap:"round",strokeWidth:s})]})}function Co({path:e,strokeWidth:t,dashSize:n,gapSize:i,kind:s,terminal:o}){const r=Po(s,o);
7
- return yd("g",{style:{pointerEvents:"none"},children:[md("path",{...r.underlay,d:e,fill:"none",stroke:nl,strokeLinecap:"round",strokeWidth:2.2*t}),md("path",{...r.segment,d:e,fill:"none",stroke:tl,strokeDasharray:`${n} ${i}`,strokeLinecap:"round",strokeWidth:t})]})}function To({editor:e,shape:t,stroke:n,fill:i,strokeWidth:s}){const o=e.shapes.getPageOutlineVertices(t.id);return 0===o.length?null:md("polygon",{points:o.map(e=>`${e.x},${e.y}`).join(" "),fill:i,stroke:n,strokeWidth:s,strokeLinejoin:"round",strokeLinecap:"round"})}function Mo({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?md("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:Eo(t,e.rotation),pointerEvents:"stroke"}}):null}function Eo(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 gl[Math.round(n)%gl.length]??"default"}function ko({handle:e,strokeWidth:t}){
8
- return md("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 Bo({dataPrefix:e,pathStyle:t,stroke:n,strokeWidth:i}){
9
- return yd(fd,{children:[md("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)=>md("path",{"data-selection-overlay":`${e}-decoration`,d:t,fill:"none",stroke:n,strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round",pointerEvents:"none"},`${s}:${t}`))]})}function Ao(e,t){const n=Math.max(e[0],t[0]),i=Math.min(e[1],t[1]);return n<=i?[n,i]:null}function Ro(){
10
- return md("div",{"data-ui":"overlay-layer",className:"land-canvas__overlay-layer",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",pointerEvents:"none"},children:md(no,{dataUi:"overlay-page-space",className:"land-canvas__overlay-page-space",children:md(Cl,{})})})}function Fo(e,t){return(e%t+t)%t}function Ko(){const e=ho(to().state.camera);
11
- return yd("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:[md("defs",{children:Ml.map(({min:t,mid:n,step:i})=>{const s=15*i*e.z,o=((e,t)=>({x:Fo(.5-e.x*e.z,t),y:Fo(.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;
12
- return md("pattern",{id:`land-canvas-grid-${i}`,width:s,height:s,patternUnits:"userSpaceOnUse",children:md("circle",{cx:o.x,cy:o.y,r:1,fill:"var(--land-canvas-grid-minor, var(--canvas-dot))",opacity:r})},i)})}),Ml.map(({step:e})=>md("rect",{width:"100%",height:"100%",fill:`url(#land-canvas-grid-${e})`},e))]})}function Do(e){const t=(e=>e instanceof HTMLElement?e:null)(e);return!!t&&(!!t.isContentEditable||!!t.closest('[contenteditable="true"]')||t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)}function Lo(e){return(e??("undefined"==typeof document?null:document))?.querySelector(kl)??null}function Yo(e,t=Lo()){if(!t)return new Ld(e.clientX,e.clientY);const n=t.getBoundingClientRect();return new Ld(e.clientX-n.left,e.clientY-n.top)}function Xo(e,t){return{type:"keyboard",name:e,...zo(t),code:t.code}}function Oo(e,t,n){return e.state.shapeEditingSession.get(),n?null:e.handleEvent(Xo("key_up",t))}function zo(e){return{key:e.key,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.metaKey||e.ctrlKey}}function No(e){return"Space"===e.code}function $o(e,t){const n=t.ownerDocument;return e===n||e===n.body||e===n.documentElement||e instanceof Node&&t.contains(e)}function _o(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 Ho(e,t){return new Ld(e.clientX-t.left,e.clientY-t.top)}function Uo(e,t){return e instanceof Node&&t.contains(e)}function Wo(e,t,n,i){return n||"hand"===e&&t?"grabbing":i||"hand"===e?"grab":"select"===e?void 0:"crosshair"}function qo({onContextMenuRequest:e,renderBindings:t,showGrid:n=!1}){const i=to(),{canvasComponents:s,domEventGuards:o}=t,r=ho(i.state.tool).activeToolId,a=ho(i.state.shapeEditing).session,d=ho(i.inputs.isSpacePressed)&&null===a,{containerRef:c,handlers:l,isPointerActive:h,isCameraPanning:u,surfaceCursor:p}=function({activeDomEventGuards:e,activeToolId:t,editor:n,onContextMenuRequest:i,shapeEditingSession:s}){const o=ud(null),r=ud(null),a=ud(null),d=ud(null),c=ud(null),l=ud(null),h=ud(null),[u,p]=pd(!1),[g,f]=pd(!1),[m,y]=pd(void 0),S=null!==s;dd(()=>{("select"!==t||S)&&n.interaction.setHoveredShapeId(null)},[t,n,S]);const I=rd(()=>{null!==c.current&&(cancelAnimationFrame(c.current),c.current=null),l.current=null},[]),v=rd(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(v)},[n,I]),w=rd(()=>{null===c.current&&(l.current=null,c.current=requestAnimationFrame(v))},[v]);return dd(()=>{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(),u=()=>{null!==s&&(window.cancelAnimationFrame(s),s=null)},g=({clientPoint:e,target:s})=>{if(u(),!e||null!==a.current||"select"!==t||S)return void n.interaction.setHoveredShapeId(null);const o=i.getBoundingClientRect();if(!Uo(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 Ld(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})},v=()=>{null===s&&(s=window.requestAnimationFrame(()=>{s=null,m()}))},w=(t,s)=>"handled"===e.handle({name:t,event:s,editor:n,container:i}),b=()=>{if(!S)return void y(void 0);const t=h.current;y(t?e.getCursor({clientPoint:t,element:document.elementFromPoint(t.x,t.y),editor:n,container:i}):void 0)},P=(e,t)=>{if(!o.current)return;const i=Ho(t,l());n.handleEvent(_o(e,t,i,n.viewport.screenToPage(i)))},x=()=>{n.viewport.setScreenSize({w:i.clientWidth,h:i.clientHeight})};c(),x();const C=e=>{if(!w("key_down",e)){if(n.state.shapeEditingSession.get()){if(Do(e.target))return;return n.handleEvent(Xo("key_down",e)).claimed?(e.preventDefault(),void e.stopPropagation()):void("Enter"===e.key&&(e.metaKey||e.ctrlKey)&&n.editing.complete("user"))}Do(e.target)||No(e)&&!$o(e.target,i)||n.handleEvent(Xo("key_down",e)).claimed&&e.preventDefault()}},T=e=>{if(No(e)&&n.inputs.pressedKeyCodes.get().has(e.code)&&!n.state.shapeEditingSession.get())return e.preventDefault(),void Oo(n,e,!1);w("key_up",e)||No(e)&&!$o(e.target,i)||Oo(n,e,Do(e.target))?.claimed&&e.preventDefault()},M=()=>{a.current=null,d.current=null,p(!1),f(!1),n.interaction.setHoveredShapeId(null),I(),n.handleEvent({type:"cancel",reason:"blur"})},E=e=>{if(w("wheel",e))return;e.preventDefault();const t={x:e.clientX,y:e.clientY};h.current=t;const i=Ho(e,l()),s=n.viewport.screenToPage(i);n.handleEvent(((e,t,n)=>({type:"wheel",screenPoint:t,pagePoint:n,delta:new Ld(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}),b(),e.pointerId!==a.current){const t=Ho(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}),w("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)||!Uo(e.target,i)||Do(e.target))return;return void P("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,P("pointer_move",e))},B=(e,t)=>{t.pointerId===a.current&&(a.current=null,d.current=null,p(!1),f(!1),I(),i.hasPointerCapture(t.pointerId)&&i.releasePointerCapture(t.pointerId),P(e,t),"pointer_up"===e?m():n.interaction.setHoveredShapeId(null))},A=()=>{h.current=null,n.interaction.setHoveredShapeId(null),b()},R=e=>{h.current={x:e.clientX,y:e.clientY},window.setTimeout(b,0),e.pointerId===a.current?B("pointer_up",e):w("pointer_up",e)},F=e=>{h.current={x:e.clientX,y:e.clientY},b(),e.pointerId===a.current?B("pointer_cancel",e):w("pointer_cancel",e)},K=new ResizeObserver(()=>{c(),x(),v()}),D=()=>{c(),v()},L=n.listen(v);window.addEventListener("keydown",C),window.addEventListener("keyup",T),window.addEventListener("blur",M),window.addEventListener("scroll",D,{passive:!0,capture:!0}),window.addEventListener("pointermove",k,{passive:!0}),window.addEventListener("pointerup",R),window.addEventListener("pointercancel",F),i.addEventListener("pointerleave",A),i.addEventListener("wheel",E,{passive:!1}),K.observe(i);const Y=window.requestAnimationFrame(b);return v(),()=>{I(),u(),L(),p(!1),f(!1),n.interaction.setHoveredShapeId(null),window.cancelAnimationFrame(Y),window.removeEventListener("keydown",C),window.removeEventListener("keyup",T),window.removeEventListener("blur",M),window.removeEventListener("scroll",D,!0),window.removeEventListener("pointermove",k),window.removeEventListener("pointerup",R),window.removeEventListener("pointercancel",F),i.removeEventListener("pointerleave",A),i.removeEventListener("wheel",E),K.disconnect()}},[e,t,n,S,I]),{containerRef:o,handlers:{onPointerDown:rd(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(Do(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,p(!0),f(1===t.button||0===t.button&&n.inputs.isSpacePressed.get()&&!n.state.shapeEditingSession.get()),d.current=null,w();const c=Ho(t,r.current);n.interaction.setHoveredShapeId(null),n.handleEvent(_o("pointer_down",t,c,n.viewport.screenToPage(c)))},[e,n,w]),onAuxClick:rd(e=>{1!==e.button||Do(e.target)||(e.preventDefault(),e.stopPropagation())},[]),onContextMenu:rd(e=>{const t=o.current;if(!t||!i||Do(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,p(!1),f(!1),I();const s=Ho(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=Ho(e,r.current),l=n.viewport.screenToPage(c),h=n.shapes.hitTest(l);let u;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"}),u={anchor:{screenPoint:c,pagePoint:l},target:{type:"selection",selectedShapeIds:i?e:[t]}}}else u={anchor:{screenPoint:c,pagePoint:l},target:{type:"canvas"}};i(u)},[n,i,I])},isPointerActive:u,isCameraPanning:g,surfaceCursor:m}}({activeDomEventGuards:o,activeToolId:r,editor:i,onContextMenuRequest:e,shapeEditingSession:a});
13
- return yd("div",{ref:c,"data-ui":El,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:p??Wo(r,h,u,d)},...l,children:[n?md(Ko,{}):null,yd(jc.Provider,{value:t,children:[
14
- md(bo,{}),s.map(({id:e,component:t})=>md(t,{},e)),
15
- md(Ro,{})]})]})}function Vo(e){dd(()=>{const t=e.current;if(!t)return;const n=t.closest("[data-canvas-kit]"),i=e=>{!e.ctrlKey&&((e,t)=>{let n=e instanceof Element?e:e instanceof Node?e.parentElement:null;for(;n&&t.contains(n);){if(n instanceof HTMLElement&&Go(n))return!0;if(n===t)break;n=n.parentElement}return!1})(e.target,t)||function(e,t,n){const i=n?Lo(n):(e=>{const t=e?.getRootNode();return t instanceof Document||t instanceof ShadowRoot?Lo(t):Lo()})(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)}(e,t,n??void 0)&&(e.preventDefault(),e.stopPropagation())};return t.addEventListener("wheel",i,{passive:!1}),()=>{t.removeEventListener("wheel",i)}},[e])}function Go(e){const{overflowY:t}=window.getComputedStyle(e);return e.scrollHeight>e.clientHeight&&("auto"===t||"scroll"===t||"overlay"===t)}function jo({children:e}){const[t,n]=pd(null),i=rd(e=>{n(e)},[]),s=hd(()=>({registerTarget:i,target:t}),[i,t]);
16
- return md(Bl.Provider,{value:s,children:e})}function Qo(){const{registerTarget:e}=er(),t=ud(null);return Vo(t),md("div",{ref:rd(n=>{t.current=n,e(n)},[e]),className:"land-canvas__floating-portal-host","data-ui":"canvas-kit-floating-portal-host"})}function Zo(){return er().target}function Jo(){return ad(Bl)?.target??void 0}function er(){const e=ad(Bl);if(!e)throw new Error("CanvasKit floating content must be rendered inside CanvasKitRoot.");return e}function tr({canvas:e,children:t}){
17
- return md(Al.Provider,{value:e,children:t})}function nr(){const e=ad(Al);if(!e)throw new Error("useCanvasKit must be used inside CanvasKitProvider.");return e}function ir(e){return gd(e.subscribe,e.getSnapshot,e.getSnapshot)}function sr({contributions:e,getHostElement:t,isEditing:n,onError:i,screenToPage:s}){return dd(()=>{const o=s=>{if(!lr(t(),s)||n()||Do(s.target))return;const o=cr({source:"clipboard",dataTransfer:s.clipboardData});or(e,o)&&(s.preventDefault(),ar(e,o).catch(e=>{i(new Error("Canvas clipboard import failed.",{cause:e}))}))},r=i=>{!lr(t(),i)||n()||Do(i.target)||rr(e,dr(i.dataTransfer))&&(i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect="copy"))},a=o=>{const r=lr(t(),o);if(!r||n()||Do(o.target))return;const a=rr(e,dr(o.dataTransfer)),d=cr({source:"drop",dataTransfer:o.dataTransfer,pagePoint:s(Yo(o,r))});or(e,d)?(o.preventDefault(),ar(e,d).catch(e=>{i(new Error("Canvas drop import failed.",{cause:e}))})):a&&(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="none"))};return window.addEventListener("paste",o),window.addEventListener("dragover",r),window.addEventListener("drop",a),()=>{window.removeEventListener("paste",o),window.removeEventListener("dragover",r),window.removeEventListener("drop",a)}},[e,t,n,i,s]),null}function or(e,t){return e.some(e=>e.accepts(t))}function rr(e,t){return e.some(e=>e.acceptsPreview?.(t)??!1)}async function ar(e,t){for(const n of e)if(n.accepts(t)&&"handled"===await n.import(t))return"handled";return"ignored"}function dr(e){return e?{source:"drop",dataTypes:Array.from(e.types),fileTypes:Array.from(e.items).filter(e=>"file"===e.kind).map(e=>e.type).filter(Boolean)}:{source:"drop",dataTypes:[],fileTypes:[]}}function cr({dataTransfer:e,pagePoint:t,source:n}){const i=e?.getData("text/plain")||void 0,s=e?.getData("text/html")||void 0,o=[...(e?.getData("text/uri-list")||void 0)?.split(/\r?\n/).filter(e=>e&&!e.startsWith("#"))??[],...i&&ur(i.trim())?[i.trim()]:[]];return{source:n,files:hr(e),text:i,html:s,...o.length>0?{urls:o}:{},pagePoint:t}}function lr(e,t){if(!e)return null;const n=(t.target instanceof Element?t.target:document.activeElement)?.closest(kl);return n instanceof HTMLElement&&e.contains(n)?n:null}function hr(e){if(!e)return[];const t=Array.from(e.files);return t.length>0?t:Array.from(e.items).flatMap(e=>{if("file"!==e.kind)return[];const t=e.getAsFile();return t?[t]:[]})}function ur(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return e.startsWith("data:image/")}}function pr({bindings:e,getHostElement:t,onError:n}){const i=nr(),s=ir(i.viewport.grid.state),{editor:o,importContributions:r,renderBindings:a,setContextMenu:d}=e,c=rd(()=>i.tools.state.getSnapshot().isEditing,[i]),l=rd(e=>o.viewport.screenToPage(e),[o]);
18
- return yd(fd,{children:[md(Gc.Provider,{value:o,children:md(qo,{onContextMenuRequest:d,renderBindings:a,showGrid:s})}),md(sr,{contributions:r,getHostElement:t,isEditing:c,onError:n,screenToPage:l})]})}function gr(e){return void 0===e?[]:Array.isArray(e)?e:[e]}function fr(e,t){if(!t||0===Object.keys(t).length)return e;const n=new Set(Object.keys(t)),i=e.map(e=>{if(!Object.prototype.hasOwnProperty.call(t,e.id))return e;n.delete(e.id);const i=t[e.id];return{...e,shortcut:i??void 0}});if(n.size>0)throw new Error(`Unknown CanvasAction shortcut override ids: ${[...n].join(", ")}.`);return i}function mr({actions:e,canvas:t,isEditing:n,onError:i}){dd(()=>{(e=>{const t=new Set;for(const n of e){if(t.has(n.id))throw new Error(`Duplicate CanvasAction id "${n.id}".`);t.add(n.id)}})(e);const s=s=>{if(n()||Do(s.target))return;const o={key:s.key,shiftKey:s.shiftKey,altKey:s.altKey,ctrlKey:s.ctrlKey,metaKey:s.metaKey,accelKey:s.metaKey||s.ctrlKey},r=e.find(e=>void 0!==e.shortcut&&gr(e.shortcut).some(e=>function(e,t){return((e,t)=>!(Rs(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:Rs(t.key),altKey:t.altKey??!1,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey??!1,accelKey:t.accelKey}})(e),t)}(e,o)));if(!r)return;if(s.preventDefault(),s.stopPropagation(),!r.isEnabled(t))return;let a;try{a=r.run(t)}catch(d){return void i(new Error(`Canvas action "${r.id}" failed.`,{cause:d}))}a instanceof Promise&&a.catch(e=>{i(new Error(`Canvas action "${r.id}" failed.`,{cause:e}))})};return window.addEventListener("keydown",s,!0),()=>window.removeEventListener("keydown",s,!0)},[e,t,n,i])}function yr(e,t){if(e.api&&!t?.api)throw new Error(`Canvas plugin "${e.id}" declares API "${e.api.id}" but setup returned no API value.`);if(!e.api&&t?.api)throw new Error(`Canvas plugin "${e.id}" returned an API value without declaring an API token.`)}function Sr(e,t){return new Set((e.requires??[]).flatMap(e=>{const n=t.get(e.id);return n?.api?[n.api.id]:[]}))}function Ir(e,t){const n=new Set;for(const i of e){if(n.has(i))throw new Error(`Duplicate ${t} id: ${i}.`);n.add(i)}}function vr(e){return"provider"===e.kind}function wr(e){return"svg-inliner"===e.kind}function br(e,t){const n=new Set;for(const i of e){if(n.has(i))throw new Error(`Duplicate ${t}: ${i}.`);n.add(i)}}function Pr(){if("undefined"!=typeof window&&"function"==typeof window.requestAnimationFrame&&"function"==typeof window.cancelAnimationFrame)return{requestFrame:e=>window.requestAnimationFrame(e),cancelFrame:e=>window.cancelAnimationFrame(e),prefersReducedMotion:()=>"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}}function xr(e){return{id:e.id,name:e.name,index:e.index,meta:{...e.meta}}}function Cr(e){return{id:e?.id??"document:main",meta:{...e?.meta??{}}}}function Tr(e,t){return{id:e.id,type:e.type,parentId:e.parentId,pageId:t,index:e.index,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,props:{...e.props},meta:{...e.meta}}}function Mr(e){const{editor:t}=e,n=t.state.session.get(),i=n.activeToolId;e.assertToolId(i);const s=t.pages.getAll().map(e=>({pageId:e.id,selectedShapeIds:[...t.selection.getIds(e.id)],camera:{...t.viewport.getCamera(e.id)}}));return{currentPageId:n.currentPageId,activeToolId:i,isToolLocked:n.isToolLocked,meta:{...n.meta},pages:s}}function Er(e){return{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?{...e.props}:void 0,meta:void 0===e.meta?void 0:{...e.meta}}}function kr({childIds:e,companionIds:t,context:n,depth:i,editor:s,index:o,pageId:r,shape:a}){return{id:a.id,parentId:a.parentId,pageId:r,type:a.type,companionIds:t,childIds:e,siblingIndex:o,depth:i,canReceiveChildren:s.layers.canReceiveChildren(a.id),isHidden:a.isHidden,isLocked:a.isLocked,isEffectivelyHidden:Fr(s,n,a.id),isEffectivelyLocked:Kr(n,a.id)}}function Br({bindings:e,editor:t,shapes:n}){const i=new Map(n.map(e=>[e.id,e])),s=t.bindings.getShapeCompanionRootIds(n.map(({id:e})=>e),e),o=new Map,r=new Map,a=new Map;for(const d of n){const e=s.get(d.id)??d.id,t=i.has(e)?e:d.id;if(o.set(d.id,t),t===d.id){const e=a.get(d.parentId);e?e.push(d):a.set(d.parentId,[d])}else{const e=r.get(t);e?e.push(d.id):r.set(t,[d.id])}}return{childShapesByParentId:a,companionIdsByRootId:r,rootIdByShapeId:o,shapeById:i}}function Ar(e,t){return e.childShapesByParentId.get(t)??[]}function Rr(e,t){let n=0,i=e.shapeById.get(t);const s=new Set([t]);for(;i?.parentId.startsWith("shape:");){const t=i.parentId;if(s.has(t))break;s.add(t),i=e.shapeById.get(t),n+=1}return n}function Fr(e,t,n){const i=new Set;let s=t.shapeById.get(n);for(;s;){if(s.isHidden)return!0;if(!s.parentId.startsWith("shape:"))return!1;const n=s.parentId;if(i.has(n))return!1;i.add(n);const o=t.shapeById.get(n);if(!o)return!1;if(!e.shapes.getUtil(o).isChildVisible(o,s,{editor:e}))return!0;s=o}return!1}function Kr(e,t){const n=new Set;let i=e.shapeById.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.shapeById.get(t)}return!1}function Dr(e){let t=e;const n=new Set;return{readable:{getSnapshot:()=>t,subscribe:e=>(n.add(e),()=>n.delete(e))},set(e){if(!Object.is(t,e)){t=e;for(const e of[...n])e()}}}}function Lr({getDependencies:e,getSnapshot:t,name:n,signals:i}){let s,o=[],r=!1;const a=()=>{const n=e();return r&&((e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Object.is(e[n],t[n]))return!1;return!0})(o,n)||(o=n,s=t(n),r=!0),s};return{getSnapshot:a,subscribe(t){let s=a();return Qs(n,{get:e,graph:i},()=>{const e=a();Object.is(s,e)||(s=e,t())},{fireImmediately:!1})}}}function Yr({apis:e,editor:t,exports:n,productId:i,startup:s}){const o=e=>(e?e.map(e=>t.shapes.get(e)).filter(e=>!!e):t.pages.getAll().flatMap(e=>t.shapes.getForPage(e.id))).map(e=>Tr(e,t.layers.getPageId(e.id))),r=e=>{const[n,...i]=e;return(({bindings:e,editor:t,pageId:n,shapes:i})=>{const s=[],o=Br({bindings:e,editor:t,shapes:i}),r=(e,i)=>{Ar(o,e).forEach((e,a)=>{const d=Ar(o,e.id).map(e=>e.id);s.push(kr({childIds:d,companionIds:o.companionIdsByRootId.get(e.id)??[],context:o,depth:i,editor:t,index:a,pageId:n,shape:e})),r(e.id,i+1)})};return r(n,0),s})({bindings:i.filter(g),editor:t,pageId:n,shapes:i.filter(u)})},a=e=>{if(!t.tools.hasTool(e))throw new Error(`Unknown canvas kit tool "${e}".`)},d={assertToolId:a,editor:t,productId:i},{readable:c,set:l}=Dr(!1),{readable:h,set:p}=Dr(null),f=Lr({signals:t.signals,name:"CanvasKit.document",getDependencies:()=>[t.document.getMetadata()],getSnapshot:([e])=>Cr(e)}),m=Lr({signals:t.signals,name:"CanvasKit.document.readonlyState",getDependencies:()=>[t.state.readonly.get()],getSnapshot:([e])=>e}),y=Lr({signals:t.signals,name:"CanvasKit.session",getDependencies:()=>[t.state.session.get().meta],getSnapshot:([e])=>({meta:{...e}})}),S=Lr({signals:t.signals,name:"CanvasKit.selection",getDependencies:()=>[t.state.selectedShapeIds.get(),t.state.selectedShapes.get(),t.state.selectionMetadata.get(),t.state.selectionPageBounds.get(),t.state.selectionAnchorPagePoint.get(),t.render.interaction.selectionTranslationActive.get(),t.state.currentPageId.get()],getSnapshot:([e,t,n,i,s,o,r])=>({...n,ids:[...e],shapes:t.map(e=>Tr(e,r)),pageBounds:i?{x:i.minX,y:i.minY,width:i.w,height:i.h}:null,anchorPagePoint:s?{x:s.x,y:s.y}:null,isTranslating:o})}),I=Lr({signals:t.signals,name:"CanvasKit.pages",getDependencies:()=>[t.state.pages.get(),t.state.currentPageId.get(),t.state.currentPageShapeIds.get()],getSnapshot:([e,t,n])=>{const i=e.map(xr),s=i.find(e=>e.id===t)??null;return{pages:i,currentPage:s,currentPageId:t,currentPageShapeIds:[...n],canDeleteCurrentPage:i.length>1&&null!==s}}}),v=Lr({signals:t.signals,name:"CanvasKit.history",getDependencies:()=>[t.state.history.get()],getSnapshot:([e])=>({...e})}),w=Lr({signals:t.signals,name:"CanvasKit.viewport",getDependencies:()=>[t.state.camera.get(),t.state.pageTransform.get()],getSnapshot:([e,t])=>({camera:{...e},zoom:e.z,pageTransform:t.toCssString()})}),b=Lr({signals:t.signals,name:"CanvasKit.tools",getDependencies:()=>[t.state.tool.get(),t.state.shapeEditing.get()],getSnapshot:([e,t])=>(a(e.activeToolId),{currentToolId:e.activeToolId,isLocked:e.isToolLocked,isEditing:null!==t.session})}),P=Lr({signals:t.signals,name:"CanvasKit.layers",getDependencies:()=>Xr(t,t.pages.getCurrentId()),getSnapshot:r});return{canvas:{startup:s,api:t=>e.get(t)??void 0,document:{state:f,readonlyState:m,getSnapshot:()=>(e=>{const{editor:t}=e,n=t.state.tool.get().activeToolId;return e.assertToolId(n),{productId:e.productId,document:Cr(t.document.getMetadata()),pageId:t.pages.getCurrentId(),activeToolId:n,selectedShapeIds:[...t.selection.getIds()],shapeCount:t.state.currentPageShapeIds.get().length,session:Mr(e)}})(d),updateMeta:e=>(t.document.updateMetadata({...e},"user"),Cr(t.document.getMetadata()))},session:{state:y,updateMeta(e){const n=t.session.get();return t.session.update({meta:{...n.meta,...e}},"user"),{meta:{...t.state.session.get().meta}}}},selection:{state:S,select:e=>t.commands.setSelectedShapeIds([...e],{source:"user"}),selectAll:()=>t.selection.selectAll("user"),clear:()=>t.commands.setSelectedShapeIds([],{source:"user"}),delete:()=>t.selection.delete("user"),duplicate:()=>t.selection.duplicate({source:"user"}),resetRotation:()=>t.selection.resetRotation("user"),flip:e=>t.selection.flip(e,"user"),setOpacity:e=>((e,t)=>{if(!Number.isFinite(t))return;const n=Math.min(1,Math.max(0,t)),i=e.state.selectedShapes.get().filter(e=>e.opacity!==n).map(e=>({id:e.id,opacity:n}));i.length>0&&e.commands.updateShapes(i,{source:"user"})})(t,e),align:e=>t.selection.align(e,"user"),distribute:e=>t.selection.distribute(e,"user")},pages:{state:I,create:e=>xr(t.pages.createAndSelect(e?{name:e.name,meta:e.meta?{...e.meta}:void 0}:void 0,"user")),rename:(e,n)=>t.pages.rename(e,n,"user"),updateMeta:(e,n)=>t.pages.updateMetadata(e,{...n},"user")?.id??null,delete:e=>t.pages.delete(e,"user"),deleteCurrent:()=>t.pages.delete(t.pages.getCurrentId(),"user"),setCurrent:e=>t.pages.select(e,"user")},history:{state:v,clear:()=>t.history.clear(),undo:()=>t.history.undo(),redo:()=>t.history.redo()},viewport:{state:w,grid:{state:c,setVisible:l,toggle:()=>l(!c.getSnapshot())},setCamera:(e,n)=>t.commands.setCamera({pageId:n,camera:e},{source:"user"}),zoomIn:()=>t.viewport.zoomAtCenter(-120,"system"),zoomOut:()=>t.viewport.zoomAtCenter(120,"system"),resetZoom:()=>t.viewport.resetZoom("user"),reset:()=>t.commands.setCamera({camera:{x:0,y:0,z:1}},{source:"user"})},tools:{state:b,setCurrent:e=>{if(!t.tools.hasTool(e))throw new Error(`Unknown product tool "${e}".`);t.tools.select(e,"user")},setLocked:e=>t.tools.setLocked(e,"user"),toggleLocked:()=>t.tools.toggleLocked("user")},shapes:{get:e=>{const n=t.shapes.get(e);return n?Tr(n,t.layers.getPageId(n.id)):null},getMany:e=>o(e),getAll:()=>o(),update:e=>function(e,t){const n=t.filter(t=>{const n=e.shapes.get(t.id);return!!n&&((e,t)=>{return!(!t.props&&void 0===t.meta)||(t.x??e.x)!==e.x||(t.y??e.y)!==e.y||(t.rotation??e.rotation)!==e.rotation||(t.scaleX??e.scaleX)!==e.scaleX||(t.scaleY??e.scaleY)!==e.scaleY||(void 0===t.opacity?e.opacity:(i=e.opacity,"number"==typeof(n=t.opacity)&&Number.isFinite(n)?Math.min(1,Math.max(0,n)):i))!==e.opacity||(t.isHidden??e.isHidden)!==e.isHidden||(t.isLocked??e.isLocked)!==e.isLocked||(t.parentId??e.parentId)!==e.parentId||(t.index??e.index)!==e.index;var n,i})(n,t)}).map(Er);return 0===n.length?[]:(e.commands.updateShapes(n,{source:"user"}),n.map(e=>e.id))}(t,e),updateMeta:(e,n)=>{const i=t.shapes.get(e);return i?(t.commands.updateShapes([{id:e,meta:{...i.meta,...n}}],{source:"user"}),e):null},delete:e=>t.shapes.delete([...e],"user")},assets:{get:e=>{const n=t.assets.get(e);return n?(e=>({id:e.id,type:e.type,props:{...e.props},meta:{...e.meta}}))(n):null},resolveUrl:e=>t.assets.resolveUrl(e)},layers:{state:P,getTree:e=>r(Xr(t,e??t.pages.getCurrentId())),getNode:e=>(({editor:e,id:t})=>{const n=e.shapes.get(t),i=n?e.layers.getPageId(n.id):null;if(!n||!i)return null;const s=e.shapes.getForPage(i),o=Br({bindings:s.flatMap(t=>e.bindings.getForShape(t.id)),editor:e,shapes:s}),r=o.rootIdByShapeId.get(n.id)??n.id,a=o.shapeById.get(r);if(!a)return null;const d=Ar(o,a.parentId);return kr({childIds:Ar(o,a.id).map(e=>e.id),companionIds:o.companionIdsByRootId.get(a.id)??[],context:o,depth:Rr(o,a.id),editor:e,index:d.findIndex(e=>e.id===a.id),pageId:i,shape:a})})({editor:t,id:e}),getActionState:e=>({canGroup:t.layers.canGroup(e),canUngroup:t.layers.canUngroup(e),canMoveBackward:t.layers.canMove(e,"backward"),canMoveForward:t.layers.canMove(e,"forward")}),centerOn:(e,n)=>t.viewport.centerOnShape(e,{...n,source:"user"}),setHidden:(e,n)=>t.shapes.setHidden([...e],n,"user"),setLocked:(e,n)=>t.shapes.setLocked([...e],n,"user"),group:e=>t.layers.group([...e],"user")?.id??null,ungroup:e=>t.layers.ungroup([...e],"user"),move:(e,n)=>t.layers.move([...e],n,"user"),moveToEdge:(e,n)=>t.layers.moveToEdge([...e],n,"user"),moveToPlacement:(e,n)=>{const i=t.layers.moveToPlacement({ids:[...e],parentId:n.parentId,beforeId:n.beforeId??void 0},"user");return i.ok?{ok:!0,ids:i.movedIds}:{ok:!1,reason:"locked"===i.reason?"locked":"cycle"===i.reason?"cycle":"invalidBeforeId"===i.reason?"invalid-before":"unsupportedTransform"===i.reason?"mixed-parent":"notFound"===i.reason&&0===e.length?"empty-selection":"invalid-parent"}}},contextMenu:{state:h,dismiss:()=>p(null)},exports:{state:{getSnapshot:()=>n.getStatus(),subscribe:e=>n.subscribe(e)},getFormats:()=>n.getFormats(),getStatus:()=>n.getStatus(),export:(e,t)=>n.export(e,t)}},host:{setContextMenu:p}}}function Xr(e,t){const n=e.shapes.getForPage(t),i=new Map;for(const s of n)for(const t of e.bindings.getForShape(s.id))i.set(t.id,t);return[t,...n,...i.values()]}function Or(){const e=new Map;let t=!1;return{register({token:n,api:i,pluginId:s}){if(t)throw new Error("Canvas API registry is disposed.");if(e.has(n.id))throw new Error(`Duplicate canvas API token: ${n.id}.`);e.set(n.id,{token:n,api:i,pluginId:s})},view:t=>(({allowedTokenIds:t,ownerLabel:n})=>{const i=i=>{if(t&&!t.has(i.id))throw new Error(`${n} attempted to read undeclared canvas API "${i.id}".`);const s=e.get(i.id);return s?s.api:null};return{get:i,require(e){const t=i(e);if(null===t)throw new Error(`${n} requires unavailable canvas API "${e.id}".`);return t}}})(t),clear(){t||(t=!0,e.clear())}}}async function zr(e,t={}){(e=>{if(!e||!Array.isArray(e.plugins))throw new Error("CanvasKit requires an explicit plugins array.");if(!("persistence"in e))throw new Error("CanvasKit requires an explicit persistence option.")})(e),t.signal?.throwIfAborted();const{canvasPlugins:n,editorPlugins:i,renderPlugins:s}=function(e){const t=(e=>e.flat(1/0))(e);br(t.map(({id:e})=>e),"canvas plugin id");const n=(e=>{const t=new Map(e.map(e=>[e.id,e])),n=[],i=new Set,s=new Set,o=e=>{if(!s.has(e.id)){if(i.has(e.id))throw new Error(`Circular canvas plugin dependency detected at "${e.id}".`);i.add(e.id);for(const n of e.requires??[]){const i=t.get(n.id);if(!i)throw new Error(`Canvas plugin "${e.id}" requires missing plugin "${n.id}".`);o(i)}i.delete(e.id),s.add(e.id),n.push(e)}};for(const r of e)o(r);return n})(t),i=n.flatMap(e=>e.editor?[e.editor]:[]),s=n.flatMap(e=>e.render?[e.render]:[]);return br(i.map(({id:e})=>e),"editor plugin id"),br(n.flatMap(e=>e.api?[e.api.id]:[]),"canvas API token"),{canvasPlugins:n,editorPlugins:i,renderPlugins:s}}(e.plugins),o=io(s),r=new Fl,a=t.signal?AbortSignal.any([r.signal,t.signal]):r.signal;try{const s=e.id??"canvas-kit",d=e.persistence;d&&r.own(d,e=>e.dispose?.());let c=[];const l=r.own((e=>{const t=function(e={}){const{plugins:t=[],...n}=e,i=new Tc({...n,...Bs(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 As(n),i}return()=>{const e=As(n);if(null!==e)throw e}})(i,t)),i}catch(s){try{i.dispose()}catch{}throw s}}({cameraAnimationScheduler:Pr(),documentMeta:e.documentMeta,onUnhandledError:e.onUnhandledError,plugins:e.editorPlugins,resolveAssetUrl:e.resolveAssetUrl});return t.tools.register("select",e=>new Vc(e)),t.tools.register("hand",e=>new Ec(e)),t.tools.syncLockedState(t.state.tool.get().isToolLocked),t.commands.setActiveTool("select",{source:"system"}),t.history.clear(),t})({documentMeta:e.documentMeta?{...e.documentMeta}:void 0,onUnhandledError:e.onError,editorPlugins:i,resolveAssetUrl(e){for(const t of c){const n=t.resolve(e);if(n)return n}return null}}),e=>e.dispose()),h=d?r.own(new Dl(l,d,{flushEvents:t.persistenceFlushEvents,onError:e.onError}),{shutdown:e=>e.shutdown(),rollback:e=>e.rollback()}):null,{apis:u,contributions:{assetResolvers:p,exports:g,imports:f}}=function({apis:e,canvasPlugins:t,editor:n,owner:i,productId:s}){const o=new Map(t.map(e=>[e.id,e])),r=[];for(const d of t){i.signal.throwIfAborted();const t=d.setup?.({editor:n,productId:s,apis:e.view({allowedTokenIds:Sr(d,o),ownerLabel:`Canvas plugin "${d.id}" setup`}),tasks:i.tasks});t&&(i.own(t,e=>e.dispose?.()),r.push({plugin:d,instance:t})),yr(d,t),d.api&&t?.api&&e.register({token:d.api,api:t.api,pluginId:d.id})}const a=(e=>{const t=e.flatMap(({instance:e})=>e.imports??[]),n=e.flatMap(({instance:e})=>e.exports??[]),i=e.flatMap(({instance:e})=>e.assetResolvers??[]);return Ir(t.map(({id:e})=>e),"import contribution"),Ir(n.map(({id:e})=>e),"export contribution"),Ir(n.flatMap(e=>"provider"===e.kind?[e.format]:[]),"export format"),Ir(i.map(({id:e})=>e),"asset resolver contribution"),Object.freeze({imports:Object.freeze((s=t,s.map((e,t)=>({value:e,index:t})).sort((e,t)=>(e.value.order??0)-(t.value.order??0)||e.index-t.index).map(({value:e})=>e))),exports:Object.freeze([...n]),assetResolvers:Object.freeze([...i])});var s})(r);return{apis:e.view({ownerLabel:"CanvasKit"}),contributions:a}}({apis:r.own(Or(),e=>e.clear()),canvasPlugins:n,editor:l,owner:r,productId:s});c=p;const m=await(async({assetResolvers:e,editor:t,initialDocumentSnapshot:n,persistenceAdapter:i,persistenceCoordinator:s,signal:o})=>{const r=t.snapshots.getSession(),a=[],d=i?.load?await i.load({signal:o}):{documentSnapshot:null,sessionSnapshot:null};let c;o.throwIfAborted(),null!==d.documentSnapshot?(t.snapshots.loadDocument(d.documentSnapshot,{source:"system"}),c="restored"):void 0!==n?(t.snapshots.loadDocument(n,{source:"system"}),c="initial"):c="empty",o.throwIfAborted();let l=!1;if("restored"===c&&null!==d.sessionSnapshot)try{t.snapshots.loadSession(d.sessionSnapshot,{source:"system"}),l=!0}catch(h){o.throwIfAborted(),a.push(h),t.snapshots.loadSession(r,{source:"system"})}t.history.clear();for(const u of e){o.throwIfAborted();try{await(u.preload?.({editor:t,signal:o})),"restored"===c&&await(u.cleanupAfterRestore?.({editor:t,signal:o}))}catch(h){o.throwIfAborted(),a.push(h)}}return o.throwIfAborted(),s?.start(),{documentSource:c,sessionRestored:l,warnings:[...a]}})({assetResolvers:c,editor:l,initialDocumentSnapshot:e.initialDocumentSnapshot,persistenceAdapter:d,persistenceCoordinator:h,signal:a});!0===e.readonly&&l.document.setReadonly(!0),r.signal.throwIfAborted();const y=r.own(function({editor:e,contributions:t,tasks:n}){const i=t.filter(vr),s=t.filter(wr),o=new Map;for(const l of i){if(o.has(l.format))throw new Error(`Duplicate canvas export format: ${l.format}.`);o.set(l.format,l)}let r=Rl,a=!1;const d=new Set,c=e=>{if(!Object.is(r,e)){r=e;for(const e of[...d])e()}};return{getFormats:()=>i.map(({format:e,label:t,mimeType:n,fileExtension:i})=>({format:e,label:t,mimeType:n,fileExtension:i})),getStatus:()=>r,subscribe:e=>(d.add(e),()=>d.delete(e)),export:async(t,i)=>n.run(async n=>{if(a)throw new Error("Canvas export controller is disposed.");if("exporting"===r.state)throw new Error("An export is already in progress.");const d=o.get(t);if(!d)throw new Error(`Canvas export format is unavailable: ${t}.`);c({state:"exporting",format:t});try{const t=((e,t)=>{if("selection"===t.scope)return e.selection.getIds();if("page"===t.scope)return e.state.currentPageShapeIds.get();if(!t.shapeIds)throw new Error("Canvas export requires a scope or shapeIds.");return t.shapeIds})(e,i);for(const i of s)n.throwIfAborted(),await(i.prepare?.({editor:e,requestedShapeIds:t,signal:n}));n.throwIfAborted();const o=await d.export({editor:e,shapeIds:t,options:i.options},{signal:n,async inlineSvg(e){let t=e.svg;for(const i of s)n.throwIfAborted(),t=await i.inline({editor:e.editor,exportedShapes:e.exportedShapes,exportedShapeIds:e.exportedShapeIds,svg:t,signal:n});return n.throwIfAborted(),t}});return n.throwIfAborted(),{format:d.format,label:d.label,mimeType:d.mimeType,fileExtension:d.fileExtension,...o}}finally{c(Rl)}}),dispose(){a||(a=!0,c(Rl),d.clear())}}}({editor:l,contributions:g,tasks:r.tasks}),e=>e.dispose());r.signal.throwIfAborted();const{canvas:S,host:I}=Yr({apis:u,editor:l,exports:y,productId:s,startup:m});return{canvas:S,dispose:r.publish({beforeShutdown:()=>l.closeWrites()}),productId:s,render:{editor:l,importContributions:f,onError:e.onError,renderBindings:o,setContextMenu:I.setContextMenu}}}catch(d){return r.rollback(d)}}function Nr(e){try{const t=globalThis.reportError;if("function"==typeof t)return void t(e)}catch(t){console.error(t)}console.error(e)}function $r({actions:e=Yl,chromeRenderer:t,onCanvasChange:n,options:i}){const s=(e=>{const[t,n]=pd(null);return dd(()=>{let t=!0,i=null;const s=new AbortController,o=e.onError??Nr;return n({options:e,state:Ll}),zr(e,{persistenceFlushEvents:{subscribe(e){const t=()=>{"hidden"===document.visibilityState&&e()},n=()=>e();return document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",n),window.addEventListener("beforeunload",n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",n),window.removeEventListener("beforeunload",n)}}},signal:s.signal}).then(s=>{i=s,t?n({options:e,state:{status:"ready",runtime:s}}):s.dispose().catch(o)},i=>{t&&n({options:e,state:{status:"error",error:i}})}),()=>{t=!1,s.abort(new DOMException("CanvasKitRoot was cleaned up.","AbortError")),i?.dispose().catch(o)}},[e]),t?.options===e?t.state:Ll})(i);if("error"===s.status)throw s.error;return"ready"!==s.status?null:md(_r,{actions:e,chromeRenderer:t,onCanvasChange:n,runtime:s.runtime})}function _r({actions:e=Yl,chromeRenderer:t,onCanvasChange:n,runtime:i}){const s=ud(n),o=ud(null),r=rd(()=>o.current,[]),{canvas:a,productId:d,render:c}=i,l=c.onError??Nr,h=rd(()=>a.tools.state.getSnapshot().isEditing,[a]);return s.current=n,dd(()=>(s.current?.(a),()=>s.current?.(null)),[a]),mr({actions:e,canvas:a,isEditing:h,onError:l}),md(tr,{canvas:a,children:md(jo,{children:md("div",{ref:o,"data-ui":"app-shell","data-canvas-kit":d,className:"land-canvas-kit__shell",children:yd("main",{"data-ui":"workspace-viewport",className:"land-canvas-kit__viewport",children:[
19
- md(pr,{bindings:c,getHostElement:r,onError:l}),t?.(a)??null,
20
- md(Qo,{})]})})})})}function Hr(){return"undefined"==typeof indexedDB?Promise.resolve(null):(Ol||(Ol=new Promise((e,t)=>{const n=indexedDB.open("canvas-kit.persistence",2);n.addEventListener("upgradeneeded",()=>{var e;(e=n.result).objectStoreNames.contains("snapshots")||e.createObjectStore(Xl)}),n.addEventListener("success",()=>{const t=n.result;t.addEventListener("versionchange",()=>{t.close(),Ol=null}),e(t)}),n.addEventListener("error",()=>{Ol=null,t(n.error)})})),Ol)}function Ur(e={}){return{async load({signal:t}){t.throwIfAborted();const n=await qr(e);return t.throwIfAborted(),n},saveDocument:t=>Wr({documentSnapshot:JSON.stringify(t),sessionSnapshot:null},e),saveSession:t=>Wr({documentSnapshot:null,sessionSnapshot:JSON.stringify(t)},e)}}async function Wr(e,t){const n=[];null!==e.documentSnapshot&&n.push([jr(t),e.documentSnapshot]),null!==e.sessionSnapshot&&n.push([Qr(t),e.sessionSnapshot]),0!==n.length&&await(async(e,t)=>{if(0===t.length)return;const n=await Hr();n&&await new Promise((i,s)=>{const o=n.transaction(e,"readwrite"),r=o.objectStore(e);o.addEventListener("complete",()=>i()),o.addEventListener("abort",()=>s(o.error)),o.addEventListener("error",()=>s(o.error));for(const[e,n]of t)r.put(n,e)})})(Xl,n)}async function qr(e={}){const[t,n]=await Jr([jr(e),Qr(e)]);return{documentSnapshot:t,sessionSnapshot:n}}async function Vr(){return Zr(zl)}async function Gr(){return Zr(Nl)}function jr(e){return e.storageNamespace?`${e.storageNamespace}.document`:zl}function Qr(e){return e.storageNamespace?`${e.storageNamespace}.session`:Nl}async function Zr(e){const[t]=await Jr([e]);return t??null}async function Jr(e){return(await(async(e,t)=>{if(0===t.length)return[];const n=await Hr();return n?new Promise((i,s)=>{const o=n.transaction(e,"readonly"),r=o.objectStore(e),a=new Array(t.length).fill(null);o.addEventListener("complete",()=>i(a)),o.addEventListener("abort",()=>s(o.error)),o.addEventListener("error",()=>s(o.error)),t.forEach((e,t)=>{const n=r.get(e);n.addEventListener("success",()=>{a[t]=n.result??null}),n.addEventListener("error",()=>s(n.error))})}):null})("snapshots",e)??e.map(()=>null)).map(ea)}function ea(e){if(null==e)return null;if("string"!=typeof e)throw new Error("Persisted canvas snapshot is not a JSON string.");try{return JSON.parse(e)}catch(t){throw new Error("Persisted canvas snapshot contains invalid JSON.",{cause:t})}}function ta({children:e,className:t,dataUi:n="canvas-kit-floating-toolbar-layer"}){const i=Zo();return i?Sd(md("div",{"data-ui":n,className:na("land-canvas__floating-toolbar-layer",t),children:e}),i):null}function na(...e){return e.filter(Boolean).join(" ")}function ia(e,t,n){return _l(e,$l(t,n))}function sa(e,t){return"function"==typeof e?e(t):e}function oa(e){return e.split("-")[0]}function ra(e){return e.split("-")[1]}function aa(e){return"x"===e?"y":"x"}function da(e){return"y"===e?"height":"width"}function ca(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function la(e){return aa(ca(e))}function ha(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}function ua(e){const t=oa(e);return ql[t]+e.slice(t.length)}function pa(e){const{x:t,y:n,width:i,height:s}=e;return{width:i,height:s,top:n,left:t,right:t+i,bottom:n+s,x:t,y:n}}function ga(e,t,n){let{reference:i,floating:s}=e;const o=ca(t),r=la(t),a=da(r),d=oa(t),c="y"===o,l=i.x+i.width/2-s.width/2,h=i.y+i.height/2-s.height/2,u=i[a]/2-s[a]/2;let p;switch(d){case"top":p={x:l,y:i.y-s.height};break;case"bottom":p={x:l,y:i.y+i.height};break;case"right":p={x:i.x+i.width,y:h};break;case"left":p={x:i.x-s.width,y:h};break;default:p={x:i.x,y:i.y}}switch(ra(t)){case"start":p[r]-=u*(n&&c?-1:1);break;case"end":p[r]+=u*(n&&c?-1:1)}return p}async function fa(e,t){var n;void 0===t&&(t={});const{x:i,y:s,platform:o,rects:r,elements:a,strategy:d}=e,{boundary:c="clippingAncestors",rootBoundary:l="viewport",elementContext:h="floating",altBoundary:u=!1,padding:p=0}=sa(t,e),g=(e=>"number"!=typeof e?(e=>({top:0,right:0,bottom:0,left:0,...e}))(e):{top:e,right:e,bottom:e,left:e})(p),f=a[u?"floating"===h?"reference":"floating":h],m=pa(await o.getClippingRect({element:null==(n=await(null==o.isElement?void 0:o.isElement(f)))||n?f:f.contextElement||await(null==o.getDocumentElement?void 0:o.getDocumentElement(a.floating)),boundary:c,rootBoundary:l,strategy:d})),y="floating"===h?{x:i,y:s,width:r.floating.width,height:r.floating.height}:r.reference,S=await(null==o.getOffsetParent?void 0:o.getOffsetParent(a.floating)),I=await(null==o.isElement?void 0:o.isElement(S))&&await(null==o.getScale?void 0:o.getScale(S))||{x:1,y:1},v=pa(o.convertOffsetParentRelativeRectToViewportRelativeRect?await o.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:y,offsetParent:S,strategy:d}):y);return{top:(m.top-v.top+g.top)/I.y,bottom:(v.bottom-m.bottom+g.bottom)/I.y,left:(m.left-v.left+g.left)/I.x,right:(v.right-m.right+g.right)/I.x}}function ma(){return"undefined"!=typeof window}function ya(e){return va(e)?(e.nodeName||"").toLowerCase():"#document"}function Sa(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Ia(e){var t;return null==(t=(va(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function va(e){return!!ma()&&(e instanceof Node||e instanceof Sa(e).Node)}function wa(e){return!!ma()&&(e instanceof Element||e instanceof Sa(e).Element)}function ba(e){return!!ma()&&(e instanceof HTMLElement||e instanceof Sa(e).HTMLElement)}function Pa(e){return!(!ma()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Sa(e).ShadowRoot)}function xa(e){const{overflow:t,overflowX:n,overflowY:i,display:s}=Ba(e);return/auto|scroll|overlay|hidden|clip/.test(t+i+n)&&"inline"!==s&&"contents"!==s}function Ca(e){return/^(table|td|th)$/.test(ya(e))}function Ta(e){try{if(e.matches(":popover-open"))return!0}catch(t){}try{return e.matches(":modal")}catch(t){return!1}}function Ma(e){const t=wa(e)?Ba(e):e;return th(t.transform)||th(t.translate)||th(t.scale)||th(t.rotate)||th(t.perspective)||!Ea()&&(th(t.backdropFilter)||th(t.filter))||Jl.test(t.willChange||"")||eh.test(t.contain||"")}function Ea(){return null==Id&&(Id="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Id}function ka(e){return/^(html|body|#document)$/.test(ya(e))}function Ba(e){return Sa(e).getComputedStyle(e)}function Aa(e){return wa(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Ra(e){if("html"===ya(e))return e;const t=e.assignedSlot||e.parentNode||Pa(e)&&e.host||Ia(e);return Pa(t)?t.host:t}function Fa(e){const t=Ra(e);return ka(t)?e.ownerDocument?e.ownerDocument.body:e.body:ba(t)&&xa(t)?t:Fa(t)}function Ka(e,t,n){var i;void 0===t&&(t=[]),void 0===n&&(n=!0);const s=Fa(e),o=s===(null==(i=e.ownerDocument)?void 0:i.body),r=Sa(s);if(o){const e=Da(r);return t.concat(r,r.visualViewport||[],xa(s)?s:[],e&&n?Ka(e):[])}return t.concat(s,Ka(s,[],n))}function Da(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function La(e){const t=Ba(e);let n=parseFloat(t.width)||0,i=parseFloat(t.height)||0;const s=ba(e),o=s?e.offsetWidth:n,r=s?e.offsetHeight:i,a=Hl(n)!==o||Hl(i)!==r;return a&&(n=o,i=r),{width:n,height:i,$:a}}function Ya(e){return wa(e)?e:e.contextElement}function Xa(e){const t=Ya(e);if(!ba(t))return Wl(1);const n=t.getBoundingClientRect(),{width:i,height:s,$:o}=La(t);let r=(o?Hl(n.width):n.width)/i,a=(o?Hl(n.height):n.height)/s;return r&&Number.isFinite(r)||(r=1),a&&Number.isFinite(a)||(a=1),{x:r,y:a}}function Oa(e){const t=Sa(e);return Ea()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:nh}function za(e,t,n,i){void 0===t&&(t=!1),void 0===n&&(n=!1);const s=e.getBoundingClientRect(),o=Ya(e);let r=Wl(1);t&&(i?wa(i)&&(r=Xa(i)):r=Xa(e));const a=((e,t,n)=>(void 0===t&&(t=!1),!(!n||t&&n!==Sa(e))&&t))(o,n,i)?Oa(o):Wl(0);let d=(s.left+a.x)/r.x,c=(s.top+a.y)/r.y,l=s.width/r.x,h=s.height/r.y;if(o){const e=Sa(o),t=i&&wa(i)?Sa(i):i;let n=e,s=Da(n);for(;s&&i&&t!==n;){const e=Xa(s),t=s.getBoundingClientRect(),i=Ba(s),o=t.left+(s.clientLeft+parseFloat(i.paddingLeft))*e.x,r=t.top+(s.clientTop+parseFloat(i.paddingTop))*e.y;d*=e.x,c*=e.y,l*=e.x,h*=e.y,d+=o,c+=r,n=Sa(s),s=Da(n)}}return pa({width:l,height:h,x:d,y:c})}function Na(e,t){const n=Aa(e).scrollLeft;return t?t.left+n:za(Ia(e)).left+n}function $a(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-Na(e,n),y:n.top+t.scrollTop}}function _a(e,t,n){let i;if("viewport"===t)i=((e,t)=>{const n=Sa(e),i=Ia(e),s=n.visualViewport;let o=i.clientWidth,r=i.clientHeight,a=0,d=0;if(s){o=s.width,r=s.height;const e=Ea();(!e||e&&"fixed"===t)&&(a=s.offsetLeft,d=s.offsetTop)}const c=Na(i);if(c<=0){const e=i.ownerDocument,t=e.body,n=getComputedStyle(t),s="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,r=Math.abs(i.clientWidth-t.clientWidth-s);r<=25&&(o-=r)}else c<=25&&(o+=c);return{width:o,height:r,x:a,y:d}})(e,n);else if("document"===t)i=(e=>{const t=Ia(e),n=Aa(e),i=e.ownerDocument.body,s=_l(t.scrollWidth,t.clientWidth,i.scrollWidth,i.clientWidth),o=_l(t.scrollHeight,t.clientHeight,i.scrollHeight,i.clientHeight);let r=-n.scrollLeft+Na(e);const a=-n.scrollTop;return"rtl"===Ba(i).direction&&(r+=_l(t.clientWidth,i.clientWidth)-s),{width:s,height:o,x:r,y:a}})(Ia(e));else if(wa(t))i=((e,t)=>{const n=za(e,!0,"fixed"===t),i=n.top+e.clientTop,s=n.left+e.clientLeft,o=ba(e)?Xa(e):Wl(1);return{width:e.clientWidth*o.x,height:e.clientHeight*o.y,x:s*o.x,y:i*o.y}})(t,n);else{const n=Oa(e);i={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return pa(i)}function Ha(e,t){const n=Ra(e);return!(n===t||!wa(n)||ka(n))&&("fixed"===Ba(n).position||Ha(n,t))}function Ua(e,t){const n=t.get(e);if(n)return n;let i=Ka(e,[],!1).filter(e=>wa(e)&&"body"!==ya(e)),s=null;const o="fixed"===Ba(e).position;let r=o?Ra(e):e;for(;wa(r)&&!ka(r);){const t=Ba(r),n=Ma(r);n||"fixed"!==t.position||(s=null),(o?!n&&!s:!n&&"static"===t.position&&s&&("absolute"===s.position||"fixed"===s.position)||xa(r)&&!n&&Ha(e,r))?i=i.filter(e=>e!==r):s=t,r=Ra(r)}return t.set(e,i),i}function Wa(e,t,n){function i(){c.x=Na(o)}const s=ba(t),o=Ia(t),r="fixed"===n,a=za(e,!0,r,t);let d={scrollLeft:0,scrollTop:0};const c=Wl(0);if(s||!s&&!r)if(("body"!==ya(t)||xa(o))&&(d=Aa(t)),s){const e=za(t,!0,r,t);c.x=e.x+t.clientLeft,c.y=e.y+t.clientTop}else o&&i();r&&!s&&o&&i();const l=!o||s||r?Wl(0):$a(o,d);return{x:a.left+d.scrollLeft-c.x-l.x,y:a.top+d.scrollTop-c.y-l.y,width:a.width,height:a.height}}function qa(e){return"static"===Ba(e).position}function Va(e,t){if(!ba(e)||"fixed"===Ba(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Ia(e)===n&&(n=n.ownerDocument.body),n}function Ga(e,t){const n=Sa(e);if(Ta(e))return n;if(!ba(e)){let t=Ra(e);for(;t&&!ka(t);){if(wa(t)&&!qa(t))return t;t=Ra(t)}return n}let i=Va(e,t);for(;i&&Ca(i)&&qa(i);)i=Va(i,t);return i&&ka(i)&&qa(i)&&!Ma(i)?n:i||(e=>{let t=Ra(e);for(;ba(t)&&!ka(t);){if(Ma(t))return t;if(Ta(t))return null;t=Ra(t)}return null})(e)||n}function ja(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function Qa({viewport:e,fallbackPlacements:t,floatingRef:n,getReferenceElement:i,onPlacementChange:s,offset:o,placement:r,visible:a=!0}){dd(()=>{const d=i(),c=n.current;if(!d||!c)return;let l=!1,h=0;c.style.visibility="hidden";const u=()=>{const e=++h,n=Za("--toolbar-floating-shift-padding",8),i=o??Za("--toolbar-floating-offset",38),u={top:Za("--toolbar-floating-safe-top",64),right:n,bottom:n,left:n};((e,t,n)=>{const i={platform:ih,...n},s={...i.platform,_c:new Map};return(async(e,t,n)=>{const{placement:i="bottom",strategy:s="absolute",middleware:o=[],platform:r}=n,a=r.detectOverflow?r:{...r,detectOverflow:fa},d=await(null==r.isRTL?void 0:r.isRTL(t));let c=await r.getElementRects({reference:e,floating:t,strategy:s}),{x:l,y:h}=ga(c,i,d),u=i,p=0;const g={};for(let f=0;f<o.length;f++){const n=o[f];if(!n)continue;const{name:m,fn:y}=n,{x:S,y:I,data:v,reset:w}=await y({x:l,y:h,initialPlacement:i,placement:u,strategy:s,middlewareData:g,rects:c,platform:a,elements:{reference:e,floating:t}});l=null!=S?S:l,h=null!=I?I:h,g[m]={...g[m],...v},w&&p<50&&(p++,"object"==typeof w&&(w.placement&&(u=w.placement),w.rects&&(c=!0===w.rects?await r.getElementRects({reference:e,floating:t,strategy:s}):w.rects),({x:l,y:h}=ga(c,u,d))),f=-1)}return{x:l,y:h,placement:u,strategy:s,middlewareData:g}})(e,t,{...i,platform:s})})(d,c,{strategy:"fixed",placement:r,middleware:[sh(i),rh({fallbackPlacements:[...t],padding:u}),oh({padding:u})]}).then(({placement:t,x:n,y:i})=>{l||e!==h||(c.dataset.placement=t,s?.(t),c.style.transform=`translate3d(${Math.round(n)}px, ${Math.round(i)}px, 0)`,c.style.visibility=a?"visible":"hidden")})},p=function(e,t,n,i){void 0===i&&(i={});const{ancestorScroll:s=!0,ancestorResize:o=!0,elementResize:r="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:d=!1}=i,c=Ya(e),l=s||o?[...c?Ka(c):[],...t?Ka(t):[]]:[];l.forEach(e=>{s&&e.addEventListener("scroll",n,{passive:!0}),o&&e.addEventListener("resize",n)});const h=c&&a?((e,t)=>{function n(){var e;clearTimeout(i),null==(e=s)||e.disconnect(),s=null}let i,s=null;const o=Ia(e);return function r(a,d){function c(t){const n=t[0].intersectionRatio;if(n!==d){if(!m)return r();n?r(!1,n):i=setTimeout(()=>{r(!1,1e-7)},1e3)}1!==n||ja(l,e.getBoundingClientRect())||r(),m=!1}void 0===a&&(a=!1),void 0===d&&(d=1),n();const l=e.getBoundingClientRect(),{left:h,top:u,width:p,height:g}=l;if(a||t(),!p||!g)return;const f={rootMargin:-Ul(u)+"px "+-Ul(o.clientWidth-(h+p))+"px "+-Ul(o.clientHeight-(u+g))+"px "+-Ul(h)+"px",threshold:_l(0,$l(1,d))||1};let m=!0;try{s=new IntersectionObserver(c,{...f,root:o.ownerDocument})}catch(y){s=new IntersectionObserver(c,f)}s.observe(e)}(!0),n})(c,n):null;let u,p=-1,g=null;r&&(g=new ResizeObserver(e=>{let[i]=e;i&&i.target===c&&g&&t&&(g.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var e;null==(e=g)||e.observe(t)})),n()}),c&&!d&&g.observe(c),t&&g.observe(t));let f=d?za(e):null;return d&&function t(){const i=za(e);f&&!ja(f,i)&&n(),f=i,u=requestAnimationFrame(t)}(),n(),()=>{var e;l.forEach(e=>{s&&e.removeEventListener("scroll",n),o&&e.removeEventListener("resize",n)}),h?.(),null==(e=g)||e.disconnect(),g=null,d&&cancelAnimationFrame(u)}}(d,c,u,{ancestorResize:!0,ancestorScroll:!0,elementResize:!0,layoutShift:!0}),g=e.subscribe(u);return u(),()=>{l=!0,c.style.visibility="hidden",p(),g()}},[e,t,n,i,s,o,r,a])}function Za(e,t){if("undefined"==typeof document)return t;const n=getComputedStyle(document.documentElement).getPropertyValue(e).trim();if(!n)return t;const i=Number.parseFloat(n);return Number.isFinite(i)?n.endsWith("rem")?16*i:i:t}function Ja(e){const t=Zo();return t?Sd(md(ed,{...e}),t):null}function ed({fallbackPlacements:e=ah,offset:t=8,placement:n="top",referenceElement:i,...s}){const o=nr(),r=ud(null),a=rd(()=>i,[i]);return Vo(r),Qa({viewport:o.viewport.state,fallbackPlacements:e,floatingRef:r,getReferenceElement:a,offset:t,placement:n}),md("div",{...s,ref:r})}function td(){return ad(lh)}function nd({children:e,className:t,dataUi:n="floating-selection-toolbar-slot",horizontalAlign:i="start",offset:s,visible:o=!0}){const r=nr(),a=ir(r.selection.state),d=ir(r.viewport.state),c=ud(null),l=ud(null),[h,u]=pd("center"===i?"top":"top-start"),p=a.pageBounds??(a.anchorPagePoint?{x:a.anchorPagePoint.x,y:a.anchorPagePoint.y,width:0,height:0}:null),g=o&&null!==p,f=g&&!a.isTranslating,m=rd(()=>c.current,[p?.height,p?.width,p?.x,p?.y]),y=rd(()=>c.current?.getBoundingClientRect()??null,[]),S=hd(()=>({placement:h,getContentBounds:y}),[p?.height,p?.width,p?.x,p?.y,y,h,d.pageTransform]);return Vo(l),Qa({viewport:r.viewport.state,fallbackPlacements:"center"===i?ch:dh,floatingRef:l,getReferenceElement:m,onPlacementChange:u,offset:s,placement:"center"===i?"top":"top-start",visible:f}),g&&p?yd(fd,{children:[md("div",{"data-ui":`${n}-page-space`,className:"land-canvas__floating-selection-page-space",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",transform:d.pageTransform,transformOrigin:"0 0"},children:md("div",{ref:c,"aria-hidden":"true",style:{position:"absolute",left:p.x,top:p.y,width:p.width,height:p.height,pointerEvents:"none"}})}),md("div",{ref:l,"data-ui":n,className:id("land-canvas__floating-selection-anchor",t),style:{position:"fixed",left:0,top:0,visibility:"hidden",willChange:"transform"},children:md(lh.Provider,{value:S,children:e})})]}):null}function id(...e){return e.filter(Boolean).join(" ")}import{createContext as sd,memo as od,useCallback as rd,useContext as ad,useEffect as dd,useId as cd,useLayoutEffect as ld,useMemo as hd,useRef as ud,useState as pd,useSyncExternalStore as gd}from"react";import{Fragment as fd,jsx as md,jsxs as yd}from"react/jsx-runtime";import{createPortal as Sd}from"react-dom";var Id,vd=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))}},wd=Symbol("UNINITIALIZED"),bd=class{graph;name;derive;isEqual;isComputed=!0;lastChangedEpoch;lastCheckedEpoch=-1;consumers=new Set;state=wd;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!==wd&&!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!==wd&&(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}},Pd=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}},xd=null,Cd=class{epoch=0;currentTransaction=null;captureStack=null;atom=(e,t,n)=>((e,t,n,i)=>new vd(e,t,n,i?.isEqual))(this,e,t,n);computed=(e,t,n)=>((e,t,n,i)=>new bd(e,t,n,i?.isEqual))(this,e,t,n);effect=(e,t,n)=>((e,t,n,i)=>{const s=new Pd(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},xd={graph:this,previous:xd}}stopCapture(){if(!this.captureStack)throw new Error("Cannot stop dependency capture because no capture is active.");if(xd?.graph!==this)throw new Error("SignalGraph dependency capture stack is out of order.");const e=this.captureStack;return this.captureStack=e.previous,xd=xd.previous,e.dependencies}trackDependency(e){if(xd&&xd.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}},Td=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}},Md=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}},Ed="document:main",kd="page:default",Bd="session:main",Ad={x:0,y:0,z:1},Rd=Symbol("editorStore"),Fd=new Set,Kd=class{editor;suppressedReactionIds=Fd;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 w(t);this.suppressedReactionIds=s;try{return w(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){y(this.editor).atomic(()=>{const t=new Set,n=new Set;for(const i of this.getAllBindings()){const s=this.editor.shapes.get(i.fromId),o=this.editor.shapes.get(i.toId);if(!s||!o){this.applyEffect(this.editor.bindings.getUtil(i).onInvalidBindingLoad?.(this.editor,i),e,i.id),y(this.editor).remove([i.id],e);continue}if(!this.canBind(i)){this.applyEffect(this.editor.bindings.getUtil(i).onInvalidBindingLoad?.(this.editor,i),e,i.id),y(this.editor).remove([i.id],e);continue}const r=this.getExclusiveBindingKey(i);if(r){if(t.has(r)){y(this.editor).remove([i.id],e);continue}t.add(r)}const a=this.editor.bindings.getUtil(i).onBindingLoad?.(this.editor,i);this.applyEffect(a,e,i.id),n.add(i.fromId),n.add(i.toId)}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(v(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)){y(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&&y(this.editor).remove(Array.from(new Set(e.deleteBindingIds)),t),e.bindings&&e.bindings.length>0&&y(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=y(this.editor).getAll(),t=e.filter(u).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 y(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}},Dd=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}},Ld=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)}},Yd=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 Ld(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)}},Xd=["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"],Od=Object.fromEntries(Xd.map(e=>[e,`--land-shape-${e}`])),zd={"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"},Nd=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()}},$d=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 Ld(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)}},_d=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}},Hd=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}},Ud=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}},Wd=new WeakMap,qd=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,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 y(this.editor).getAll())if(u(s))e=Math.max(e,ie(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,ie(s.id)):f(s)&&(i=Math.max(i,ie(s.id)));this.nextShapeNumber=e+1,this.nextPageNumber=t+1,this.nextBindingNumber=n+1,this.nextAssetNumber=i+1}},Vd=new Ld(24,24),Gd={propagation:"stop"},jd={propagation:"stop",clickSequence:"break"},Qd=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=it(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=it(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&&st(t,e)&&st(n,e))}matchesCurrentPointer(e){return!this.lastPointerDown||st(this.lastPointerDown,e)}reset(){this.lastPointerDown=null,this.lastPointerUp=null,this.currentClickCount=1}},Zd={propagation:"stop",clickSequence:"break"},Jd=class{editor;clickRecognizer=new Qd;activeRoutes=new WeakMap;constructor(e){this.editor=e}handle(e){const t=this.activeRoutes.get(e);return t?(t.effect=nt(t.effect,this.routeAfterInputs(e,t.context)),ot(t.effect)):ot(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=nt(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=nt(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(),nt(nt(n,i),Zd)}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:nt(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(),nt(nt(i,s),Zd)}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"}),nt(n,Zd)}},ec=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:rt(),screenVelocity:rt(),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:at(n,e.pagePoint,o),screenVelocity:at(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:rt(),screenVelocity:rt(),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:rt(),screenVelocity:rt(),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&&dt(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:at(n,e.pagePoint,r),screenVelocity:at(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:rt(),screenVelocity:rt(),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=>dt(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=>dt(t,e)?t:{...t,shiftKey:e.shiftKey,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,accelKey:e.accelKey})}},tc=class{handlers=[];registeredIds=new Set;register(e){this.registeredIds.has(e.id)||(this.handlers.push(e),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=nt(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=nt(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}},nc=class{editor;buffer;activeScopes=[];stateAtom;unsubscribeOperations;isDisposed=!1;state;constructor(e){this.editor=e,this.buffer=new Td,this.stateAtom=e.signals.atom("editor.history.state",{canUndo:!1,canRedo:!1},{isEqual:ct}),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;y(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})}},ic=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)}},sc=class{editor;onUnhandledError;stack=[];commitListeners=new Set;commitQueue=[];nextOperationId=1;revision=0;isDrainingCommitQueue=!1;constructor(e,t=()=>{}){this.editor=e,this.onUnhandledError=t,y(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 ic(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 ic(this,e):null}subscribe(e){return this.commitListeners.add(e),()=>{this.commitListeners.delete(e)}}commit(e){this.assertTopActive(e);const n=lt(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:ut(this.editor.snapshots.getDocument()),sessionSnapshot:pt(this.editor.snapshots.getSession())};return this.enqueueCommit(i),i}cancel(e){this.assertTopActive(e);const n=lt(e.diff);if(!t(n))try{y(this.editor).applyDiff(i(n),e.source),this.editor.snapshots.syncAfterDocumentRestore()}catch(s){if(!t(lt(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=lt(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:ut(this.editor.snapshots.getDocument()),sessionSnapshot:pt(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{}}},oc=["from","to","related"],rc=class{editor;state;bindingsFromShapeSignals=new Map;bindingsToShapeSignals=new Map;bindingsForShapeSignals=new Map;draftBindingIndex=null;unsubscribeFromStore;constructor(e){this.editor=e;const t=y(e);this.state=(e=>{const t=e.filter(g).sort(mt),n={bindingById:new Map,bindingIdsByFromShape:new Map,bindingIdsByToShape:new Map,relatedBindingIdsByShape:new Map};for(const i of t)n.bindingById.set(i.id,i),gt(n.bindingIdsByFromShape,i.fromId,i.id),gt(n.bindingIdsByToShape,i.toId,i.id),gt(n.relatedBindingIdsByShape,i.fromId,i.id),gt(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:G}),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:G}),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:G}),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(It),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),vt(o,r);for(const{before:r,after:a}of i)r.fromId===a.fromId&&r.toId===a.toId||vt(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)wt(o,r);for(const{before:r,after:a}of i)r.fromId===a.fromId&&r.toId===a.toId||wt(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=y(this.editor),t=e.getActiveTransactionRevision();return null===t?null:(this.draftBindingIndex?.revision===t||(this.draftBindingIndex=((e,t)=>{const n={revision:e,relations:{from:bt(),to:bt(),related:bt()}};for(const i of t.removed)g(i)&&Pt(n,i,void 0);for(const i of t.updated)g(i.before)&&Pt(n,i.before,void 0),g(i.after)&&Pt(n,i.after,i.after);for(const i of t.added)g(i)&&Pt(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(mt);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})}},ac=class{editor;signalsByShapeId=new Map;unsubscribeFromStore;constructor(e){this.editor=e,this.unsubscribeFromStore=e.listen(({diff:e})=>{for(const t of e.removed)u(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 kt(this.getShapeLocalToPageTransformSignal(e).get())}getShapeParentToPageTransform(e){return e.startsWith("page:")?this.editor.pages.get(e)?$d.Identity():void 0:kt(this.getOrCreateSignals(e).localToPageTransform.get())}getShapePositionedToPageTransform(e){return kt(this.getOrCreateSignals(e).positionedToPageTransform.get())}getShapePageBounds(e){return Mt(this.getShapePageBoundsSignal(e).get())??void 0}getShapePositionedBounds(e){return Mt(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 Et(this.getCachedShapeGeometry(e)?.corners)}getShapePageOutlineVertices(e){return Et(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 Rt(this.editor,n,e=>this.editor.shapes.get(e))){const e=this.editor.shapes.getUtil(i).getChildClipLocalPolygons(i);if(!e||!E(e))continue;const n=this.getOrCreateSignals(i.id).localToPageTransform.get()?.tryInvert();if(!n||!B(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 Rt(this.editor,t,e=>this.editor.shapes.get(e))){const e=this.editor.shapes.getUtil(i).getChildClipLocalPolygons(i),t=e?E(e):null,s=this.getOrCreateSignals(i.id).localToPageTransform.get();if(!t||!s)continue;const o=Kt(n,Ft(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:ee}),s=this.editor.signals.computed(`editor.query.shapeLocalToPageTransform.${e}`,()=>{const t=n(e);return t?Bt(this.editor,t,n):void 0},{isEqual:Ct}),o=this.editor.signals.computed(`editor.query.shapeGeometry.${e}`,()=>{const t=n(e);if(!t)return;const i=At(this.editor,t.parentId,n);return i?xe(t,this.editor.shapes.getUtil(t),i):void 0},{isEqual:Tt});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=At(this.editor,t.parentId,n);return i?Ie(t,this.editor.shapes.getUtil(t),i):void 0},{isEqual:Ct}),pageBounds:this.editor.signals.computed(`editor.query.shapePageBounds.${e}`,()=>o.get()?.bounds,{isEqual:ee}),clipAncestorIds:this.editor.signals.computed(`editor.query.shapeClipAncestorIds.${e}`,()=>{const t=n(e);return t?Rt(this.editor,t,n).map(e=>e.id):[]},{isEqual:G})},this.signalsByShapeId.set(e,t)}return t}},dc=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=y(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(u).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)Dt(s,d.parentId,d.id);const a=(e,t)=>{for(const n of s.get(t)??[]){const t=r.get(n);t&&(Dt(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:G}),this.pagesSignal=this.pagesAtom,this.unsubscribeFromStore=s.listen(e=>{this.handleStoreChange(e)}),this.currentPageShapeIdsSignal=i("editor.query.currentPageShapeIds",()=>this.getShapeIdsForPageSnapshot(t.get()),{isEqual:G}),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})),{isEqual:Ot})}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:G}),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=y(this.editor),n=this.stateAtom.peek(),i=((e,t,n)=>{const i=t.diff.added.filter(u),s=t.diff.updated.filter(Xt),o=t.diff.removed.filter(u);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 u(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(!u(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),Yt(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)Yt(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])}},cc=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}},lc=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 Yd(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=be(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))&&i.push(r)}return i}getShapesHitByLineSegment(e,t,n){const i=n?.margin??0,s=((e,t,n)=>Yd.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||!Nt(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 u=be(c,e,l,h),p=be(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:u,positionedEnd:p,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;const i=this.editor.shapes.getUtil(t),s=this.geometry.getShapePageBoundsSignal(e).get();if(!s)continue;const o=this.geometry.getShapePositionedToPageTransform(e);if(!o)continue;const r=$t(i.getPointHitTestBounds(t,{editor:this.editor}),o),a=Yd.FromPoints([new Ld(s.minX,s.minY),new Ld(s.maxX,s.maxY),new Ld(r.minX,r.minY),new Ld(r.maxX,r.maxY)]);n.push({shapeId:e,shapeBounds:s,queryBounds:a,pointHitTestBounds:r})}return new cc(n)}),this.pageIndexSignals.set(e,t)),t}getPageIndex(e=this.editor.pages.getCurrentId()){return this.getPageIndexSignal(e).get()}},hc=class extends Error{constructor(e){super(e),this.name="SnapshotParseError"}},uc=.001,pc=["top_left","top","top_right","right","bottom_right","bottom","bottom_left","left"],gc=["free","aspect_ratio_locked"],fc=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:$n}),this.frameGeometrySignal=n("editor.selectionOverlayFrameGeometry",()=>{const t=this.selectedShapeItemsSignal.get();if(0===t.length)return null;if(oi(t))return null;const n=e.selection.getFrame();return n?{bounds:n.bounds,rotation:n.rotation,rotationCenter:n.rotationCenter}:null},{isEqual:_n}),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:Hn}),this.pathSignal=n("editor.selectionOverlayPath",()=>{const e=this.selectedShapeItemsSignal.get();return oi(e)?e[0]?.path??null:null}),this.pageClipPathSignal=n("editor.selectionOverlayPageClipPath",()=>{const e=this.selectedShapeItemsSignal.get();return oi(e)?e[0]?.pageClipPath??null:null}),this.bindingSegmentsSignal=n("editor.selectionOverlayBindingSegments",()=>{const e=this.selectedShapeItemsSignal.get();return oi(e)?[...e[0]?.bindingSegments??[]]:[]},{isEqual:Bn}),this.frameStyleSignal=n("editor.selectionOverlayFrameStyle",()=>{const e=t.cameraZoom.get();return{strokeWidth:2/e,cornerRadius:3/e}},{isEqual:Un}),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)),u=t.every(t=>(t=>r&&e.shapes.getUtil(t).canUseSelectionResizeHandles(t,{editor:e}))(t)),p=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),y=h.flatMap(e=>e.customHandleAnchors??[]),S=f.length>0||m.length>0||y.length>0;if(!n)return{resizeHandleAnchors:[],rotateHandleAnchors:[],terminalHandleAnchors:f,middleHandleAnchors:m,customHandleAnchors:y};const{bounds:I,rotation:v,rotationCenter:w,hasCompatibleRotation:b}=n,P=t[0]?.rotation??v,x=8/i,C=14/i,T=I.w<2*x,M=I.h<2*x,E=e=>0===v?e:Ld.RotWith(e,w,v),k=new Ld(I.minX,I.minY),B=new Ld(I.center.x,I.minY),A=new Ld(I.maxX,I.minY),R=new Ld(I.maxX,I.center.y),F=new Ld(I.maxX,I.maxY),K=new Ld(I.center.x,I.maxY),D=new Ld(I.minX,I.maxY),L=new Ld(I.minX,I.center.y);return{resizeHandleAnchors:!u||S?[]:[{kind:"resize",id:"top_left",point:E(k)},...T?[]:[{kind:"resize",id:"top",point:E(B)}],...T&&M?[]:[{kind:"resize",id:"top_right",point:E(A)}],...M?[]:[{kind:"resize",id:"right",point:E(R)}],...T||M?[]:[{kind:"resize",id:"bottom_right",point:E(F)}],...T?[]:[{kind:"resize",id:"bottom",point:E(K)}],...T||M?[]:[{kind:"resize",id:"bottom_left",point:E(D)}],...M?[]:[{kind:"resize",id:"left",point:E(L)}]].filter(e=>g.has(e.id)),rotateHandleAnchors:!p||S||!b||T||M?[]:[{kind:"rotate",id:"bottom_left_rotate",point:E(si({bounds:I,rotateOffset:C,referenceRotation:P,frameRotation:v}))}],terminalHandleAnchors:f,middleHandleAnchors:m,customHandleAnchors:y}})(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=On(e,t,n);return pc.filter(n=>s.every(e=>e.includes(n))&&zn(e,t,n,o).length>0)})(e,e.selection.getResizeTargets(),i?.rotation??0))},{isEqual:ii}),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 Yd(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:ni})}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=Rn(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 Yd(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}},mc=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})}},yc=class extends Error{},Sc=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;selectedDescendantTransformAncestorSignals=new Map;constructor(e){this.editor=e,this.unsubscribeFromStore=e.listen(({diff:e})=>{for(const t of e.removed)u(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(),this.selectedDescendantTransformAncestorSignals.clear()}isDocumentHidden(e){return!1===Ti(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 u(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:J}),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}`,()=>Ti(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}getSelectedDescendantTransformAncestorSignal(e){let t=this.selectedDescendantTransformAncestorSignals.get(e);return t||(t=this.editor.signals.computed(`editor.shapeSelectedDescendantTransformAncestor.${e}`,()=>{if(this.getSelectedSignal(e).get())return!1;const t=this.getShapeSignal(e).get();return!(!t||!this.editor.shapes.getUtil(t).isSelectionTransformContainer(t))&&this.editor.state.selectedShapeIds.get().some(t=>((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})(this.editor,t,e))}),this.selectedDescendantTransformAncestorSignals.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),this.selectedDescendantTransformAncestorSignals.delete(e)}},Ic=["corner","edge_midpoint","corner","edge_midpoint","center","edge_midpoint","corner","edge_midpoint","corner"],vc={corner:0,edge_midpoint:1,center:2,custom:3},wc=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=Is(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?_i(s):(a??(c=i.getLocalBounds(e),[new Ld(c.minX,c.minY),new Ld(c.maxX,c.minY),new Ld(c.maxX,c.maxY),new Ld(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 u of a.getSelfSnapPoints?.(c)??[]){const t=Is(u),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?_i(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?_i(i):this.editor.shapes.getPageOutlineVertices(e.id)).map(e=>0===t.rotation?e.clone():Rn(e,r));if(0===a.length)continue;const d=Yd.FromPoints(a);o.push({id:e.id,bounds:d});const l=n.getBoundsSnapGeometry(e).points,h=[];if(void 0===l)Ki(d).forEach((e,t)=>{h.push({point:e,kind:Ic[t]??"custom"})});else{const n=this.editor.shapes.computeLocalToPageTransform(e);for(const i of l){const s=Is(i),o=n.applyToPoint(s.point);this.editor.shapes.isPagePointInClip(e.id,o)&&h.push({point:0===t.rotation?o:Rn(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:Zi(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))})}},bc=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 wc(e)}setIndicators(e){const t=e.map(Ss);as(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:Vi(n.nodes,"x"),y:Vi(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=Ni(e.initialSelectionBounds,e.dragDelta),i=(s=Ki(e.initialSelectionBounds),o=e.dragDelta,s.map(e=>e.add(o)));var s,o;const r=this.gapCache.get(e.snapshot)??{x:Vi(e.snapshot.nodes,"x"),y:Vi(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},u="y"===e.lockedAxis?null:rs(ss("x",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===c?.type?new Set(c.candidatePointIds??[]):void 0,releaseThreshold:a,selectionPointKinds:Ic,switchDistance:d,stats:h}),Qi("x",n,r.x,e.threshold,{previousSnapId:"gaps"===c?.type?c.id:null,releaseThreshold:a,switchDistance:d}),{previousSnap:c,switchDistance:d}),p="x"===e.lockedAxis?null:rs(ss("y",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===l?.type?new Set(l.candidatePointIds??[]):void 0,releaseThreshold:a,selectionPointKinds:Ic,switchDistance:d,stats:h}),Qi("y",n,r.y,e.threshold,{previousSnapId:"gaps"===l?.type?l.id:null,releaseThreshold:a,switchDistance:d}),{previousSnap:l,switchDistance:d}),g=new Ld(u?.nudge??0,p?.nudge??0),f=[];return"points"===u?.type?f.push(...ls("x",u,g,e.snapshot.coordinateSpace)):"gaps"===u?.type&&f.push(ys(u,e.snapshot.coordinateSpace,g)),"points"===p?.type?f.push(...ls("y",p,g,e.snapshot.coordinateSpace)):"gaps"===p?.type&&f.push(ys(p,e.snapshot.coordinateSpace,g)),this.setIndicators(f),this.updateAxisSnapMemory("x",u),this.updateAxisSnapMemory("y",p),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:u?.id??null,ySnapId:p?.id??null,indicatorCount:f.length}),{nudge:g,indicators:f}}snapResize(e){const t=this.getNow(),n=Ai({handleId:e.handleId,scaleX:e.scaleX,scaleY:e.scaleY}),i=os(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:ss("x",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===d?.type?new Set(d.candidatePointIds??[]):void 0,releaseThreshold:r,switchDistance:a,stats:l}),u=o?null:ss("y",i,e.snapshot.pointIndex,e.threshold,{previousCandidatePointIds:"points"===c?.type?new Set(c.candidatePointIds??[]):void 0,releaseThreshold:r,switchDistance:a,stats:l}),p={x:null!==h,y:null!==u},g=new Ld(h?.nudge??0,u?.nudge??0);if(e.isAspectRatioLocked&&Mi(f=n)!==Ei(f)&&ki(f)!==Bi(f)&&(0!==g.x||0!==g.y)){const t=h&&u?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?(p.y=!1,g.y=g.x/i,"bottom_left"!==n&&"top_right"!==n||(g.y=-g.y)):(p.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=Ai({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?(Mi(n)?(i+=t.x,s-=t.x):Ei(n)&&(i-=t.x,s+=t.x),ki(n)?(o+=t.y,r-=t.y):Bi(n)&&(o-=t.y,r+=t.y)):(Mi(n)?i+=t.x:Ei(n)&&(s+=t.x),ki(n)?o+=t.y:Bi(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 Yd(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=Ri({axis:"x",startBounds:e,bounds:t,handleId:n,scale:i,isResizingFromCenter:o}),a=Ri({axis:"y",startBounds:e,bounds:t,handleId:n,scale:s,isResizingFromCenter:o});return{scaleX:Mi(n)||Ei(n)?r*(t.w/Math.max(1,e.w)):i??1,scaleY:ki(n)||Bi(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 Fi({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:y}=m,S=os("any",y),I=[];if(p.x){const t=ss("x",S,e.snapshot.pointIndex,1e-8,{stats:l});t&&I.push(...fs("x",t,Ld.Zero(),e.snapshot.coordinateSpace,y,e.snapshot.nodes))}if(p.y){const t=ss("y",S,e.snapshot.pointIndex,1e-8,{stats:l});t&&I.push(...fs("y",t,Ld.Zero(),e.snapshot.coordinateSpace,y,e.snapshot.nodes))}return this.setIndicators(I),this.updateAxisSnapMemory("x",p.x?h:null),this.updateAxisSnapMemory("y",p.y?u: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:p.x?h?.id??null:null,ySnapId:p.y?u?.id??null:null,indicatorCount:I.length}),{nudge:g,bounds:y,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=vs(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=Wi(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:gs("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=vs(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 Ld(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(ms("x",s.add(d),n)),i&&o&&l.push(ms("y",o.add(d),i)),{snappedPagePoint:c,nudge:d,indicators:l}}},Pc=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){ee(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&&Q(t.rawPagePoint,n.rawPagePoint)&&Q(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||!An(i,s))return!1}return!0})(this._terminalBindingGuidesSignal.get(),t)||this._terminalBindingGuidesSignal.set(t.map(En))}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)}},xc=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]??Ad}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:Ps(o.x,e.x,d),y:Ps(o.y,e.y,d),z:Ps(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:vn("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=vn(this.getCurrentCamera().z*Math.exp(.0015*-t));this.zoomCameraToScreenPoint(e,i,n)}zoomCameraToScreenPoint(e,t,n="system"){const i=vn(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 Ld(n.w/2,n.h/2);this.zoomCameraAtScreenPoint(i,e,t)}resetZoom(e="user"){const t=this.viewportScreenSizeSignal.get(),n=new Ld(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)}},Cc=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:G}),this.retainedBaseShapeWindowSnapshotSignal=n("editor.retainedBaseShapeWindowSnapshot",e=>{const n=t.currentPageShapeIds.get(),i=null!==t.viewportPageBounds.get(),s=((e,t,n=0)=>Cs(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!==wd&&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(Cs(i).length!==t.length)return null;const s=Ms(t);return Ms(i)>s+12?null:i})(Cs(e.ranges.map(e=>({...e}))),s);if(t)return ks(n,t,{viewportReady:i})}return ks(n,s,{viewportReady:i})},{isEqual:(e,t)=>G(e.shapeIds,t.shapeIds)}),this.culledShapeIdSetSignal=n("editor.culledShapeIdSet",()=>new Set(this.culledShapeIdsSignal.get()),{isEqual:j}),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:G}),this.selectedShapeIdsOutsideCulledSetSignal=n("editor.selectedShapeIdsOutsideCulledSet",()=>new Set(this.selectedShapeIdsOutsideCulledSignal.get()),{isEqual:j}),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:G}),this.retainedShapeWindowSnapshotSignal=n("editor.retainedShapeWindowSnapshot",e=>{const n=t.currentPageShapeIds.get(),i=null!==t.viewportPageBounds.get(),s=this.retainedBaseShapeWindowSnapshotSignal.get().shapeIds,o=(r=s.length)<=0?0:xs(Math.ceil(.5*r),12,96);var r;const a=((e,t,n,i)=>{if(0===e.length)return[];const s=new Map;for(const[a,d]of e.entries())s.set(d,a);const o=Cs(t.map(e=>s.get(e)).filter(e=>void 0!==e).sort((e,t)=>e-t).map(e=>({start:e,end:e+1})),2),r=[];if(o.length>0){const t=xs(Math.ceil(i/(2*o.length)),8,32);for(const[n,i]of o.entries()){const s=n>0?o[n-1]:null,a=n<o.length-1?o[n+1]:null,d=a?a.start-i.end:1/0,c=Ts(s?i.start-s.end:1/0,t),l=Ts(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?[]:Cs(r,2)})(n,s,this.selectedShapeIdsOutsideCulledSetSignal.get(),o);if(i&&e!==wd&&e&&e.viewportReady&&e.ranges.length>0&&a.length>0){const t=Cs(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 ks(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(Cs(i).length!==t.length)return null;const s=Ms(t);return Ms(i)>s+n?null:i})(t,a,o);if(s)return ks(n,s,{viewportReady:i})}return ks(n,a,{viewportReady:i})},{isEqual:(e,t)=>G(e.shapeIds,t.shapeIds)}),this.retainedShapeIdsSignal=n("editor.retainedShapeIds",()=>this.retainedShapeWindowSnapshotSignal.get().shapeIds,{isEqual:G}),this.renderVisibleShapeIdSetSignal=n("editor.renderVisibleShapeIdSet",()=>new Set(this.renderVisibleShapeIdsSignal.get()),{isEqual:j}),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}},Tc=class{signals=e();store;[Rd];inputs;tools;cameraManager;editing;shapeUtils=new Hd;shapeSvgExporters=new Nd;bindingUtils=new Dd;interactions=new tc;runtime=new _d;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(Ed);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(Bd);if(!p(e))throw new Error("Missing session record");return e},update:(e,t="system")=>{Fe(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)=>{Re(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:()=>Ce(this),pasteClipboardPayload:e=>(this.interaction.cancelForCommand(),Te(this,e)),duplicate:(e={})=>(this.interaction.cancelForCommand(),((e,t={})=>{const n=Ce(e);return n?Te(e,{payload:n,offset:t.offset??Vd,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=rn(e,t);if(!n)return[];const i=an(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=rn(e,t);return n?e.shapes.getUtil(t).getSelectionPagePoints(n)??[]:[]});if(0===n.length)return null;const i=Yd.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=rn(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:Yd.FromPoints(e.map(e=>Rn(e,t))))({points:r?[...r]:s.getPositionedOutlineVertices(t).map(n=>e.shapes.computePositionedToPageTransform(t).applyToPoint(n)),transform:n});return a?an(e,t,o,s.flipSelectionBounds(o,{axis:i,selectionBounds:n.bounds,selectionLocalBounds:Yn({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:()=>xn(this,2),align:(e,t="user")=>(this.interaction.cancelForCommand(),((e,t,n="user")=>{const i=Cn(e);if(i.length<2)return!1;const s=Tn(e,i[0].shape.parentId);if(!s)return!1;const o=Yd.FromPoints(i.flatMap(e=>[new Ld(e.bounds.minX,e.bounds.minY),new Ld(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=Mn(s,new Ld(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:()=>xn(this,3),distribute:(e,t="user")=>(this.interaction.cancelForCommand(),((e,t,n="user")=>{const i=Cn(e);if(i.length<3)return!1;const s=Tn(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,u=((o?h.maxX:h.maxY)-a(l)-c.reduce((e,t)=>e+r(t.bounds),0))/(c.length-1);let p=a(l);const g=c.map(({shape:e,bounds:t},n)=>{const i=0===n||n===c.length-1?a(t):p,d=i-a(t);p=i+r(t)+u;const l=Mn(s,o?new Ld(d,0):new Ld(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=Sn(e),n=1===t.length;return t.length>0&&t.every(t=>e.shapes.getUtil(t).canParticipateInSelectionResize(t,{editor:e,isOnlyAffectedShape:n}))})(this),canFlip:()=>yn(this),canRotate:()=>(e=>{const t=Sn(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 fn(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 In(e,e.selection.getIds())){const t=e.shapes.get(s);t&&i(t)}return t})(this),getRotationTargets:()=>{return mn(e=this,e.selection.getIds()).map(t=>e.shapes.get(t)).filter(e=>!!e);var e},getPageBounds:()=>this.selectionGeometry.pageBounds.get()?.clone()??null,getFrame:()=>ui(this),containsPoint:e=>((e,t)=>{const n=ui(e);if(!n)return!1;const i=pi(e,t);return!!i&&n.bounds.containsPoint(i)})(this,e),toFramePoint:e=>pi(this,e),getPageOutlineVertices:()=>this.selectionGeometry.pageOutlineVertices.get().map(e=>e.clone()),getAnchorPagePoint:()=>this.selectionGeometry.selectionAnchorPagePoint.get()?.clone()??null,getFrameBounds:()=>this.selectionGeometry.frameBounds.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 u(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),getSelectedDescendantTransformAncestorSignal:e=>this.shapeSignals.getSelectedDescendantTransformAncestorSignal(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(!te(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")=>Je(this,e,{flag:"isHidden",value:t,source:n}),setLocked:(e,t,n="user")=>Je(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=>((e,t)=>e.shapes.getUtil(t).getExportBounds(t))(this,e),computeLocalToPageTransform:e=>((e,t)=>Se(t,e.shapes.getUtil(t),li(e,t)))(this,e),computeRenderToPageTransform:e=>function(e,t){return((e,t,n)=>Se(e,t,n))(t,e.shapes.getUtil(t),li(e,t))}(this,e),computeExportToPageTransform:e=>((e,t)=>ve(t,e.shapes.getUtil(t),li(e,t)))(this,e),computePageBounds:e=>function(e,t){return((e,t,n)=>Yd.FromPoints(Pe(e,t,n)))(t,e.shapes.getUtil(t),li(e,t))}(this,e),computeExportPageBounds:e=>function(e,t){return((e,t,n)=>{const i=t.getExportBounds(e),s=ve(e,t,n);return Yd.FromPoints([new Ld(i.minX,i.minY),new Ld(i.maxX,i.minY),new Ld(i.maxX,i.maxY),new Ld(i.minX,i.maxY)].map(e=>s.applyToPoint(e)))})(t,e.shapes.getUtil(t),li(e,t))}(this,e),computeGeometry:e=>hi(this,e),computePositionedToPageTransform:e=>((e,t)=>Ie(t,e.shapes.getUtil(t),li(e,t)))(this,e),computePageCenter:e=>hi(this,e).center,computePageCorners:e=>hi(this,e).corners,computePageOutlineVertices:e=>hi(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:()=>wi(this),getSelectionGroupState:()=>gi(this),canGroupSelection:()=>null!==gi(this),canGroup:e=>((e,t)=>null!==fi(e,t))(this,e),group:(e,t="user")=>yi(this,e,t),groupSelection:(e="user")=>((e,t="user")=>{const n=yi(e,e.selection.getIds(),t);return n&&e.commands.setSelectedShapeIds([n.id],{source:t}),n})(this,e),getUngroupableSelectionIds:()=>Si(this),getUngroupableIds:e=>Ii(this,e),canUngroupSelection:()=>Si(this).length>0,canUngroup:e=>((e,t)=>Ii(e,t).length>0)(this,e),ungroup:(e,t="user")=>vi(this,e,t),ungroupSelection:(e="user")=>((e,t="user")=>vi(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=wi(e);return"backward"===t?n?.canMoveBackward??!1:n?.canMoveForward??!1})(this,e),canMove:(e,t)=>((e,t,n)=>{const i=Pi(e,t);return"backward"===n?i?.canMoveBackward??!1:i?.canMoveForward??!1})(this,e,t),move:(e,t,n="user")=>xi(this,e,t,n),moveToEdge:(e,t,n="user")=>Ci(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:ne(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=y(e).getAll().filter(e=>u(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=Xe(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:ne(e).createShapeIndex(i+1),...d.get(n.id),meta:s===n.meta?void 0:s}})}})(e,t,n,i);return o.ok?(e.interaction.cancelForCommand(),e.commands.updateShapes(o.updates,{source:s}),o):o})(e,t,i,s,n);return o.ok?{ok:!0,movedIds:i}:{ok:!1,reason:o.reason}}(this,e,t),moveSelection:(e,t="user")=>((e,t,n="user")=>xi(e,e.selection.getIds(),t,n))(this,e,t),moveSelectionToEdge:(e,t="user")=>((e,t,n="user")=>Ci(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)=>pn(e,e.layers.getDescendantIds(t)))(this,e),getSubtreePageBounds:e=>((e,t)=>pn(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=>un(this,e),getSelectionTransformIds:e=>fn(this,e),getSelectionRotationIds:e=>mn(this,e),getExportTraversalIds:e=>((e,t)=>{const n=un(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 un(e,[t]))i.has(s)||e.shapes.isHidden(s)||(i.add(s),n.push(s))}return n})(this,e),getContainment:(e,t)=>ri(this,this.shapeGeometryQueries,e,t),getContainingParentId:e=>((e,t,n,i)=>ai({editor:e,shapeTree:t,geometry:n,shapeIds:i}))(this,this.shapeTreeIndex,this.shapeGeometryQueries,e),getContainingParentIdAtPoint:(e,t)=>((e,t,n,i,s)=>ai({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=At(e,n.parentId,t=>e.shapes.get(t));if(!s)return null;const o=xe(n,e.shapes.getUtil(n),s),r=new Map;for(const g of y(e).getAll().filter(u)){const e=r.get(g.parentId)??[];e.push(g),r.set(g.parentId,e)}for(const u of r.values())u.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,p=-1;for(let u=0;u<a.length;u+=1){const t=a[u];if(!t||t.id===n.id||e.shapes.isHidden(t.id)||e.layers.isOrAncestorLocked(t.id))continue;const i=e.shapes.getUtil(t);if(!ci(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)))&&di(s,u,l,h,p)&&(l=t,h=s.w*s.h,p=u)}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())=>wn(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)=>bn(this,e,t),zoomToFit:e=>((e,t)=>{const n=wn(e);return!!n&&bn(e,n,t)})(this,e),zoomToSelection:e=>((e,t)=>{const n=Pn(e,e.selection.getIds());return!!n&&bn(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(u).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=jt(e,"document"),s=new Set,o=[];return i.records.forEach((e,i)=>{if(!_t(e))throw new hc("Invalid document record: expected object");if("string"!=typeof e.id)throw new hc("Invalid document record id");if(s.has(e.id))throw new hc(`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 hc(`Unsupported document record type: ${String(e.typeName)}`);o.push((e=>{if("string"!=typeof e.id||!e.id.startsWith("asset:"))throw new hc("Invalid asset record id");if("string"!=typeof e.type)throw new hc("Invalid asset record type");return{id:e.id,typeName:"asset",scope:"document",type:e.type,props:_t(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 hc("Invalid binding record id");if("string"!=typeof e.type)throw new hc("Invalid binding record type");if("string"!=typeof e.fromId||!e.fromId.startsWith("shape:"))throw new hc(`Invalid from id for binding ${e.id}`);if("string"!=typeof e.toId||!e.toId.startsWith("shape:"))throw new hc(`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 hc("Invalid shape record id");if("string"!=typeof e.type)throw new hc("Invalid shape record type");if("string"!=typeof e.parentId||!e.parentId.startsWith("page:")&&!e.parentId.startsWith("shape:"))throw new hc(`Invalid parent id for shape ${e.id}`);return{id:e.id,typeName:"shape",scope:"document",parentId:e.parentId,index:Ht(e.index,String(n+1).padStart(6,"0")),x:Ut(e.x,0),y:Ut(e.y,0),rotation:Ut(e.rotation,0),scaleX:Ut(e.scaleX,1),scaleY:Ut(e.scaleY,1),opacity:Math.min(1,Math.max(0,Ut(e.opacity,1))),isHidden:Wt(e.isHidden,!1),isLocked:Wt(e.isLocked,!1),meta:qt(e.meta),type:e.type,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 hc("Invalid page record id");return{id:e.id,typeName:"page",scope:"document",name:Ht(e.name,`Page ${t+1}`),index:Ht(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 hc("Invalid document metadata record id");return{id:Ed,typeName:"document",scope:"document",meta:qt(e.meta)}})(e))}),{schemaVersion:3,records:Qt(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();tn(e,[...s.records,o],i),en(e),e.history.clear(),e.bindings.repairLoaded(i)})(this,e,t),loadSession:(e,t)=>Jt(this,e,t),syncAfterDocumentRestore:()=>en(this)};exports={getSvgString:(e=this.selection.getIds(),t)=>function(e,t,n,i={}){const s=Array.from(t),o=e.layers.getExportTraversalIds(s),r=new Set(o),a=[],d=[];for(const b of o){const t=e.shapes.get(b);t?d.push(t):a.push({id:b,reason:"missing-shape"})}if(0===d.length)return null;const c=[];for(const b of d){if(!e.shapes.getUtil(b).contributesToExportBounds(b))continue;const t=z(e,b,r);t&&(x(t)?c.push(t):a.push({id:b.id,reason:"missing-bounds"}))}if(0===c.length)return null;const l=(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 Yd(t,n,i-t,s-n)})(c).expand(i.padding??16),h=[],u={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=>X(e,i.resolveThemeColor)},p=[],g=[],f=new Map,m=[],y=(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 N(e,t,n)){const t=$(e,r,i,s);t&&o.push(t)}return o})(e,t,r,f,u);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)},S=e=>{const t=n.get(e.type)?.toSvgForeground?.(e,u);t&&y(e,t)};for(const b of d){for(;m.length>0&&!O(e,m[m.length-1].id,b);)S(m.pop());const t=n.get(b.type);if(!t){a.push({id:b.id,reason:"missing-exporter"});continue}const i=t.toSvg(b,u);i?x(e.shapes.computeExportBounds(b))?(p.push(b.id),y(b,i),t.toSvgForeground&&m.push(b)):a.push({id:b.id,reason:"missing-bounds"}):a.push({id:b.id,reason:"empty-output"})}for(;m.length>0;)S(m.pop());if(0===p.length)return null;const I=Math.max(1,l.w),v=Math.max(1,l.h),w=[];return h.length>0&&w.push({tag:"defs",children:h}),i.background&&w.push({tag:"rect",attrs:{x:l.x,y:l.y,width:l.w,height:l.h,fill:i.background}}),w.push(...g),{svg:W({tag:"svg",attrs:{xmlns:"http://www.w3.org/2000/svg",width:I,height:v,viewBox:`${V(l.x)} ${V(l.y)} ${V(I)} ${V(v)}`},children:w}),bounds:l,width:I,height:v,requestedShapeIds:s,exportedShapeIds:p,skippedShapes:a}}(this,e,this.shapeSvgExporters,t),getIntegrityReport:(e=this.selection.getIds())=>b({editor:this,exporters:this.shapeSvgExporters,shapeIds:e}),repairIntegrity:(e=this.selection.getIds())=>(({editor:e,exporters:t,shapeIds:n})=>{const i=Array.from(n),s=b({editor:e,exporters:t,shapeIds:i});s.repairableIssueCount>0&&e.bindings.repairLoaded("system");const o=b({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 ec(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.bindingUtils??[])this.bindingUtils.register(a);const n=new Md(((e={})=>[a(e),d(),c()])(e.documentMeta??{}),{signals:this.signals,writeGuard:e=>this.assertStoreChangeAllowed(e)});((e,t)=>{e[Rd]=t})(this,n),this.store=n,this.tools=new Ud(this),this.cameraManager=new xc(this,e.cameraAnimationScheduler),this.editing=new mc(this),this.interactionManager=new Pc(this);const i=t("editor.session",()=>{const e=n.getRecordSignal(Bd).get();if(!p(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()})),u=t("editor.currentCamera",()=>i.get().pageCameraById[s.get()]??Ad),g=t("editor.selectedShapeIds",()=>{const e=i.get();return e.pageSelectedShapeIdsById[e.currentPageId]??[]},{isEqual:G}),f=t("editor.selectionCount",()=>g.get().length),m=t("editor.selectedShapeIdSet",()=>new Set(g.get()),{isEqual:j}),y=t("editor.pageTransform",()=>{const e=u.get();return $d.Scale(e.z,e.z).compose($d.Translate(-e.x,-e.y))}),S=t("editor.cameraZoom",()=>u.get().z),I=t("editor.viewportPageBounds",()=>{const{w:e,h:t}=this.cameraManager.viewportScreenSizeSignal.get();if(e<=0||t<=0)return null;const n=u.get();return new Yd(n.x,n.y,e/n.z,t/n.z)});(e=>{const t=new qd(e);Wd.set(e,t)})(this),this.shapeSignals=new Sc(this),this.shapeGeometryQueries=new ac(this),this.shapeTreeIndex=new dc(this,s),this.bindingQueries=new rc(this),this.bindingManager=new Kd(this),this.spatialIndex=new lc(this,this.shapeTreeIndex,this.shapeGeometryQueries),this.snaps=new bc(this,e.snapDiagnostics),this.selectionGeometry=((e,t,n)=>{const i=e.signals.computed("editor.query.selectionGeometry",()=>hn(e,t,n),{isEqual:dn}),s=e.signals.computed("editor.query.selectionPageOutlineVertices",()=>i.get().outlineVertices,{isEqual:Z}),o=e.signals.computed("editor.query.selectionPageBounds",()=>i.get().pageBounds,{isEqual:ee}),r=e.signals.computed("editor.query.selectionFrameBounds",()=>i.get().frameBounds,{isEqual:ee}),a=e.signals.computed("editor.query.selectionRotation",()=>i.get().rotation);return{geometry:i,pageOutlineVertices:s,pageBounds:o,frameBounds:r,hasRotation:e.signals.computed("editor.query.selectionHasRotation",()=>i.get().hasRotation),rotation:a,rotationCenter:e.signals.computed("editor.query.selectionRotationCenter",()=>i.get().rotationCenter,{isEqual:Q}),hasCompatibleRotation:e.signals.computed("editor.query.selectionHasCompatibleRotation",()=>i.get().hasCompatibleRotation),selectionAnchorPagePoint:e.signals.computed("editor.query.selectionAnchorPagePoint",()=>i.get().selectionAnchorPagePoint,{isEqual:Q})}})(this,g,e=>this.shapeGeometryQueries.getCachedShapeGeometry(e));const v=t("editor.selectedShapes",()=>g.get().map(e=>this.shapes.getSignal(e).get()).filter(e=>!!e)),w=t("editor.selectionCanFlip",()=>yn(this,g.get())),b=t("editor.selectionState",()=>{const e=g.get(),t=1===e.length?this.shapes.getSignal(e[0]).get()??null:null,n=v.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:w.get(),hasPointHandleSelection:o,hasFrameSelection:r,isMixedFrameAndPointHandleSelection:a,canDragPointHandles:c,hasSelectionRotation:l,hasMixedSelectionRotation:!this.selectionGeometry.hasCompatibleRotation.get(),canResetSelectionRotation:l&&r,frameBounds:this.selectionGeometry.frameBounds.get(),frameRotation:this.selectionGeometry.rotation.get(),frameRotationCenter:this.selectionGeometry.rotationCenter.get(),selectionAnchorPagePoint:this.selectionGeometry.selectionAnchorPagePoint.get()}}),P=t("editor.selectionMetadata",()=>{const e=b.get();return{count:e.count,singleShapeType:e.singleShapeType,commonShapeType:e.commonShapeType,canFlipSelection:e.canFlipSelection,hasPointHandleSelection:e.hasPointHandleSelection,hasFrameSelection:e.hasFrameSelection,isMixedFrameAndPointHandleSelection:e.isMixedFrameAndPointHandleSelection,canDragPointHandles:e.canDragPointHandles,hasSelectionRotation:e.hasSelectionRotation,hasMixedSelectionRotation:e.hasMixedSelectionRotation,canResetSelectionRotation:e.canResetSelectionRotation}},{isEqual:ws}),x=t("editor.renderViewportPageBounds",e=>{const t=I.get();return t?e!==wd&&e&&(i=t).minX>=(n=e).minX&&i.maxX<=n.maxX&&i.minY>=n.minY&&i.maxY<=n.maxY?e:t.expand(160/S.get()):null;var n,i},{isEqual:ee});this.renderWindowManager=new Cc(this,{currentPageId:s,currentPageShapeIds:this.shapeTreeIndex.currentPageShapeIdsSignal,selectedShapeIds:g,selectedShapeIdSet:m,viewportPageBounds:I,renderViewportPageBounds:x}),this.selectionOverlay=new fc(this,{tool:o,selectedShapeIds:g,selectedShapes:v,cameraZoom:S}),this.operations=new sc(this,e.onUnhandledError),this.history=new nc(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:v,selectionCount:f,selection:b,selectionMetadata:P,selectionPageBounds:this.selectionGeometry.pageBounds,selectionFrameBounds:this.selectionGeometry.frameBounds,selectionAnchorPagePoint:this.selectionGeometry.selectionAnchorPagePoint,camera:u,cameraZoom:S,pageTransform:y,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=Ze(this),this.eventRouter=new Jd(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),Gd;if("keyboard"===s.type&&(e=>"Space"===e.code)(s)){if("key_up"===s.name){const t=e;return e=!1,t?Gd:void 0}if(i.state.shapeEditingSession.get())return;return e=!0,Gd}if("tick"===s.type&&t){const e=i.inputs.state.get();return e.pointerId===t.pointerId&&e.currentScreenPoint&&tt(i,t.camera,e.currentScreenPoint),Gd}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:et(i,s.screenPoint)},jd}if(t&&s.pointerId===t.pointerId)return"pointer_move"===s.name?(0===(s.buttons&t.buttons)&&n(),Gd):"pointer_up"===s.name?(tt(i,t.camera,s.screenPoint),n(),Gd):"pointer_cancel"===s.name?(n(),Gd):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}},Mc=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)}},Ec=class extends Mc{constructor(e){super(e,"hand"),this.initial="idle",this.addChild(new kc(e,this)),this.addChild(new Bc(e,this))}},kc=class extends Mc{constructor(e,t){super(e,"idle",t)}onPointerDown(e){0===e.button&&this.transition("panning",et(this.editor,e.screenPoint))}},Bc=class extends Mc{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&&tt(this.editor,this.info,t)}onPointerUp(e){this.info&&tt(this.editor,this.info,e.screenPoint),this.transition("idle")}onCancel(){this.transition("idle")}onExit(){this.info=null}},Ac=Math.PI/180*15,Rc=Math.PI/2,Fc=Math.PI/180*5,Kc=class extends Mc{info=null;onEnter(e){this.info=e,this.onInfoEnter()}onExit(){this.onInfoExit(),this.info=null}onInfoEnter(){}onInfoExit(){}},Dc=class extends Kc{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)}},Lc=class extends Kc{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=Ks(this.editor,e,"always_apply");t&&this.apply(t)}onKeyDown(){this.applyFromInputs()}onKeyUp(){this.applyFromInputs()}applyFromInputs(){Ds(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()}},Yc=class extends Kc{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,Os(e))}onPointerMove(e){this.info&&this.updateBrush(e.pagePoint,Xs(e),Os(e))}onTick(e){if(!this.info)return;const t=Ks(this.editor,e,"apply_after_scroll_or_without_screen_point");t&&this.updateBrush(t.pagePoint,Xs(t),Os(t))}onKeyDown(){this.updateBrushFromInputs()}onKeyUp(){this.updateBrushFromInputs()}onPointerUp(e){this.info&&this.updateBrush(e.pagePoint,Xs(e),Os(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 Yd(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(){Ds(this.editor,e=>this.updateBrush(e.pagePoint,Xs(e),Os(e)))}complete(){this.transition("idle")}cancel(){this.transition("idle")}},Xc=class extends Lc{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&&!G(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"))}},Oc=class extends Mc{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=Xs(e),a=Ls(this.editor,n,t),d=r?null:((e,t,n)=>{const i=new Set(n);for(const s of Ys(e,t))if(i.has(s.ancestorId))return s.ancestorId;return null})(this.editor,n,t),c=r?null:d?a:null,l=Ls(this.editor,i,t),h=null===c?l:d??l,u=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:u}}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()&&!Xs(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:Xs(e)})}else this.transition("pointing_selection_handle_interaction",i)}},zc=class extends Dc{constructor(e,t){super(e,"pointing_canvas",t)}onDragThresholdExceeded(e){this.info&&this.transition("brushing",{...this.info,additiveSelection:Xs(e)})}onPointerUp(e){Xs(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")}},Nc=class extends Dc{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=rn(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?[]:zn(e,t,n,On(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:Rn(t[0],r),endLocalPagePoint:Rn(t[1],r),middleLocalPagePoint:(()=>{const t=s(e);return t?Rn(t,r):null})()}):a.push({shape:c,pageShape:e,localBounds:Yd.FromPoints(n(c).map(e=>Rn(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 Ld(e.minX,e.minY),new Ld(e.maxX,e.minY),new Ld(e.maxX,e.maxY),new Ld(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")}},$c=class extends Dc{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=rn(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:Ld.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")}},_c=class extends Dc{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")}},Hc=class extends Dc{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)):$d.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:Xs(e)});const o=s.map(e=>e.id),r=i?.hasCompatibleRotation?i.rotation:0,a=i?.rotationCenter.clone()??Ld.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 Xs(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")}},Uc=class extends Lc{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=_s(this.info.rotationCenter,this.info.rotation),o=Rn(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=Mi(t)||Ei(t)?s*(Mi(t)?-2:2)/Math.max(1,e.w):1,c=ki(t)||Bi(t)?o*(ki(t)?-2:2)/Math.max(1,e.h):1;switch(t){case"top":case"bottom":return{bounds:new Yd(e.minX,i.y-a,e.w,2*a),scaleX:d,scaleY:c};case"left":case"right":return{bounds:new Yd(i.x-r,e.minY,2*r,e.h),scaleX:d,scaleY:c};default:return{bounds:new Yd(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=Mi(t)?i:s,d=Mi(t)?s:i,c=ki(t)?o:r,l=ki(t)?r:o;Mi(t)||Ei(t)?a=n.x:(a=s,d=i),ki(t)||Bi(t)?c=n.y:(c=r,l=o);const h=a-d,u=c-l,p=Mi(t)?d-a:h,g=ki(t)?l-c:u,f=Mi(t)||Ei(t)?p/Math.max(1,e.w):1,m=ki(t)||Bi(t)?g/Math.max(1,e.h):1;return{bounds:new Yd(Math.min(a,d),Math.min(c,l),Math.max(1,Math.abs(h)),Math.max(1,Math.abs(u))),scaleX:f,scaleY:m}})({startBounds:e,handleId:t,pagePoint:n});return i?Fi({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 u=0;u<this.info.shapes.length;u+=1){const e=this.info.shapes[u],t=this.info.updates[u];e&&t&&$s(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 u=0;u<this.info.pointShapes.length;u+=1){const e=this.info.pointShapes[u],t=this.info.updates[this.info.shapes.length+u];e&&t&&Hs(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")}},Wc=class extends Lc{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=zs(Ld.Angle(this.info.center,e)-this.info.startAngle);if(t)i=Ns(i,Ac);else if(!n&&this.editor.inputs.state.get().screenVelocity.len()<.5){const e=this.info.initialSelectionRotation+i,t=Ns(e,Rc),n=zs(t-e);Math.abs(n)<=Fc&&(i=zs(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&&Ws(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&&qs(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")}},qc=class extends Lc{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 Ld(o,r):new Ld(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):$d.Identity()).tryInvert();if(!a)continue;const d=ye(a.compose($d.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)}js(this.editor,this.info.movingShapeIds,e),((e,t,n)=>{const i=Gs(e,t,n);if(i===Vs(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&&js(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")}},Vc=class extends Mc{constructor(e){super(e,"select"),this.initial="idle",this.addChild(new Oc(e,this)),this.addChild(new zc(e,this)),this.addChild(new Yc(e,this)),this.addChild(new Hc(e,this)),this.addChild(new qc(e,this)),this.addChild(new Nc(e,this)),this.addChild(new Uc(e,this)),this.addChild(new $c(e,this)),this.addChild(new Wc(e,this)),this.addChild(new _c(e,this)),this.addChild(new Xc(e,this))}},Gc=sd(null),jc=sd(io([])),Qc=od(e=>{const{Component:t,editor:n,isSelected:i,shape:s,shapeEditingSession:o}=e;
21
- return md(t,{editor:n,isSelected:i,shape:s,shapeEditingSession:o})}),Zc=od(({shapeId:e,stackingOrder:t})=>{const n=to(),i=ho(n.shapes.getSignal(e)),s=ho(n.shapes.getLocalToPageTransformSignal(e)),o=ho(n.shapes.getRenderVisibleSignal(e)),r=ho(n.shapes.getSelectedSignal(e)),a=ho(n.shapes.getEditingSessionSignal(e)),d=ho(n.shapes.getEffectiveOpacitySignal(e)),c=ho(n.shapes.getClipAncestorIdsSignal(e)),l=co(),h=ho(hd(()=>l.getShapeOpacityValue(n,e),[n,l,e]));if(!i||!s)return null;const u=l.getShapeRenderer(i.type)?.foregroundComponent;if(!u)return null;const p=So(n,i,s),g=d*h;
22
- return md("div",{"data-ui":"shape-foreground","data-owner-shape-id":i.id,"data-owner-shape-type":i.type,style:{position:"absolute",display:o?void 0:"none",left:p.left,top:p.top,width:p.width,height:p.height,opacity:1===g?void 0:g,transform:p.transform,transformOrigin:p.transformOrigin,pointerEvents:"none",zIndex:t+1},children:o?md(uo,{clipAncestorIds:c,shapeElementToPage:p.elementToPage,children:md(Qc,{Component:u,shape:i,editor:n,isSelected:r,shapeEditingSession:a})}):null})}),Jc=od(({shapeId:e,stackingOrder:t})=>{const n=to(),i=ho(n.shapes.getSignal(e)),s=ho(n.shapes.getLocalToPageTransformSignal(e)),o=ho(n.shapes.getHoveredSignal(e)),r=ho(n.state.selectionCount),a=ho(n.render.interaction.brushBoxActive),d=ho(n.shapes.getRenderVisibleSignal(e)),c=ho(n.state.tool).activeToolId,l=ho(n.shapes.getSelectedSignal(e)),h="select"===c&&l,u=ho(n.shapes.getEditingSessionSignal(e)),p=ho(n.shapes.getRenderOrderSignal(e)),g=ho(n.shapes.getDropTargetSignal(e)),f=ho(n.shapes.getEffectiveOpacitySignal(e)),m=ho(n.shapes.getSelectedDescendantTransformAncestorSignal(e)),y=ho(n.shapes.getClipAncestorIdsSignal(e)),S=co(),I=ho(hd(()=>S.getShapeOpacityValue(n,e),[n,S,e]));if(!i||!s)return null;const v=S.getShapeRenderer(i.type);if(!v)return null;const w=v.component,b=v.hoverComponent,P=o&&!(1===r&&h)&&!a,x=So(n,i,s),C=f*I;
23
- return yd("div",{"data-ui":"shape-instance","data-shape-id":i.id,"data-shape-type":i.type,"data-selected":h?"true":"false","data-hovered":P?"true":"false","data-drop-target":g?"true":"false","data-visible":d?"true":"false","data-render-order":p>=0?String(p):void 0,"data-clip-ancestor-count":y.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?yd(uo,{clipAncestorIds:y,shapeElementToPage:x.elementToPage,children:[md(Qc,{Component:w,shape:i,editor:n,isSelected:h,shapeEditingSession:u}),P&&b?md(yo,{Component:b,editor:n,shape:i}):null]}):null,d&&g?md(vo,{}):null,d&&m?md(Io,{}):null]})}),el=od(()=>{const e=to();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&&!wo(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})(ho(e.render.viewport.retainedShapeIds),ho(e.state.currentPageShapeTree),co()).map((e,t)=>"shape"===e.layer?md(Jc,{shapeId:e.shapeId,stackingOrder:t},e.shapeId):md(Zc,{shapeId:e.shapeId,stackingOrder:t},`${e.shapeId}:foreground`))}),tl="rgba(100, 116, 139, 0.82)",nl="rgba(255, 255, 255, 0.84)",il=od(()=>ho(to().render.interaction.bindingPreviewActive)?md(sl,{}):null),sl=od(()=>{const e=to(),t=ho(e.render.interaction.bindingPreview),n=ho(e.render.interaction.terminalBindingGuides);if(!t)return null;const i=n.some(e=>e.terminal===t.terminal&&e.targetShapeId===t.targetShapeId);
24
- return yd(fd,{children:[md(ol,{targetShapeId:t.targetShapeId}),md(rl,{bindingPreview:t,showGuide:!i})]})}),ol=od(({targetShapeId:e})=>{const t=to(),n=ho(t.state.cameraZoom),i=ho(t.shapes.getSignal(e));return i?md(To,{editor:t,shape:i,stroke:"rgba(14, 165, 233, 0.78)",fill:"rgba(14, 165, 233, 0.08)",strokeWidth:2/n}):null}),rl=od(({bindingPreview:e,showGuide:t})=>{const n=ho(to().state.cameraZoom),i=2/n,s=6/n,o=4/n;
25
- return yd(fd,{children:[t?e.guidePath?md(Co,{path:e.guidePath,strokeWidth:i,dashSize:s,gapSize:o,kind:"binding-preview",terminal:e.terminal}):md(xo,{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,
26
- md("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}),
27
- md("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})]})}),al=od(()=>ho(to().render.interaction.brushBoxActive)?md(dl,{}):null),dl=od(()=>{const e=ho(to().render.interaction.brushBox);return e?md("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}),cl=od(()=>{const e=to(),t=ho(e.render.overlay.frameGeometry),n=ho(e.render.overlay.companionFrameGeometries);return t||0!==n.length?yd(fd,{children:[t?md(ll,{frameGeometry:t}):null,n.map((e,t)=>md(ll,{frameGeometry:e},`companion-${t}`))]}):null}),ll=od(({frameGeometry:e})=>{const t=ho(to().render.overlay.frameStyle),{bounds:n,rotation:i,rotationCenter:s}=e,{cornerRadius:o,strokeWidth:r}=t,a=r/2,d=180*i/Math.PI;
28
- return md("g",{transform:0===i?void 0:`rotate(${d} ${s.x} ${s.y})`,children:md("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})})}),hl=new Set(["top_left","top_right","bottom_right","bottom_left"]),ul=od(()=>{const e=to(),t=ho(e.state.readonly),n=ho(e.render.overlay.handleAnchors);return t||!n?null:md(pl,{anchors:n})}),pl=od(({})=>{const e=to(),t=ho(e.render.overlay.handles),n=ho(e.render.overlay.frameGeometry),i=lo(),s=ho(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=>hl.has(e.id)),u=o.filter(e=>!hl.has(e.id)),p=n?.rotation??0,g=180*p/Math.PI;
29
- return yd(fd,{children:[n?md("g",{transform:n&&0!==p?`rotate(${g} ${n.rotationCenter.x} ${n.rotationCenter.y})`:void 0,children:u.map(e=>md(Mo,{frame:n,handleId:e.id,zoom:s},e.id))}):null,h.map(e=>md("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:Eo(e.id,p),pointerEvents:"auto"}},e.id)),r.map(e=>yd("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:[md("path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}),md("path",{d:"M21 3v5h-5"})]},e.id)),d.map(e=>md("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=>md("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);
30
- return md(t?t.component:ko,{handle:e,strokeWidth:a},`${e.type}:${e.id}`)})]})}),gl=["ew-resize","nwse-resize","ns-resize","nesw-resize"],fl=1e-6,ml=od(()=>{const e=to(),t=ho(e.render.overlay.path),n=ho(e.render.overlay.pageClipPath),i=ho(e.render.overlay.bindingSegments),s=ho(e.render.overlay.selectedShapeItems),o=ho(e.render.overlay.frameStyle),r=cd().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>fl?Math.abs(e.localToPage.determinant())/n:0;return e.strokeWidth+2*t/(i>fl?i:n>fl?n:1)})(c,o.strokeWidth):null,h=c&&null!==l?c.localBounds.expand(l):null;return t?yd(fd,{children:[
31
- md(yl,{bindingSegments:i,strokeWidth:o.strokeWidth}),n||c&&h?yd("defs",{children:[n?md("clipPath",{id:a,clipPathUnits:"userSpaceOnUse",children:md("path",{d:n,clipRule:"evenodd",fillRule:"evenodd"})}):null,c&&null!==l&&h?yd("mask",{id:d,maskUnits:"userSpaceOnUse",maskContentUnits:"userSpaceOnUse",x:h.x,y:h.y,width:h.w,height:h.h,children:[md(Bo,{dataPrefix:"path-halo-mask-outer",pathStyle:c,stroke:"white",strokeWidth:l}),md(Bo,{dataPrefix:"path-halo-mask-center",pathStyle:c,stroke:"black",strokeWidth:c.strokeWidth})]}):null]}):null,
32
- md("g",{"data-selection-overlay":"lines",clipPath:n?`url(#${a})`:void 0,children:c&&null!==l?md("g",{"data-selection-overlay":"path-halo-transform",transform:c.localToPage.toSvgString(),children:md("g",{mask:`url(#${d})`,children:md(Bo,{dataPrefix:"path-halo",pathStyle:c,stroke:"rgba(37, 99, 235, 0.45)",strokeWidth:l})})}):yd(fd,{children:[md("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}),md("path",{"data-selection-overlay":"path",d:t,fill:"none",stroke:"rgba(37, 99, 235, 0.88)",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:o.strokeWidth})]})})]}):null}),yl=od(({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;
33
- return md(fd,{children:e.map(e=>e.guidePath?md(Co,{path:e.guidePath,strokeWidth:n,dashSize:i,gapSize:s,kind:t,terminal:e.terminal},e.terminal):md(xo,{start:e.anchorPagePoint,end:e.boundaryPagePoint,startInset:o,endInset:r,strokeWidth:n,dashSize:i,gapSize:s,kind:t,terminal:e.terminal},e.terminal))})}),Sl=od(()=>ho(to().render.interaction.selectionTranslationActive)?null:yd(fd,{children:[
34
- md(ml,{}),
35
- md(cl,{}),
36
- md(ul,{})]})),Il="rgba(37, 99, 235, 0.9)",vl=od(()=>{const e=to(),t=ho(e.state.readonly),n=ho(e.render.interaction.snapIndicators);return t||0===n.length?null:md(wl,{indicators:n})}),wl=od(({indicators:e})=>{const t=ho(to().state.cameraZoom);
37
- return md(fd,{children:e.map(e=>md("points"===e.type?bl:Pl,{indicator:e,zoom:t},e.id))})}),bl=od(({indicator:e,zoom:t})=>{const n=2.5/t,i=1/t,[s,o]=e.line,r=180*e.rotation/Math.PI;
38
- return yd("g",{"data-ui":"snap-indicator",transform:0===e.rotation?void 0:`rotate(${r} ${e.rotationCenter.x} ${e.rotationCenter.y})`,children:[md("path",{"data-ui":"snap-indicator-line",d:`M ${s.x} ${s.y} L ${o.x} ${o.y}`,fill:"none",stroke:Il,strokeWidth:i,strokeLinecap:"round"}),e.points.map((t,s)=>md("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:Il,strokeWidth:i,strokeLinecap:"round"},`${e.id}:${s}`))]})}),Pl=od(({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=Ao(i,[n?l.startEdge[0].y:l.startEdge[0].x,n?l.startEdge[1].y:l.startEdge[1].x]);e&&(i=e);const t=Ao(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})`;
39
- return md("path",{"data-ui":"snap-gap-indicator",d:a.join(" "),transform:c,fill:"none",stroke:Il,strokeWidth:1/t,strokeLinecap:"round",strokeLinejoin:"round"})}),xl=od(()=>{const e=to(),t=ho(e.render.interaction.terminalBindingGuides),n=ho(e.render.overlay.frameStyle);return 0===t.length?null:md(yl,{bindingSegments:t,kind:"terminal-binding-guide",strokeWidth:n.strokeWidth})}),Cl=od(()=>yd("svg",{width:"100%",height:"100%",style:{display:"block",width:"100%",height:"100%",overflow:"visible"},children:[
40
- md("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 '}),
41
- md(vl,{}),
42
- md(xl,{}),
43
- md(il,{}),
44
- md(al,{}),
45
- md(Sl,{}),
46
- md(Tl,{})]})),Tl=od(()=>{const e=lo().getCanvasOverlays();return 0===e.length?null:md(fd,{children:e.map(({id:e,component:t})=>md(t,{},e))})}),Ml=[{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}],El="canvas-surface",kl=`[data-ui="${El}"]`,Bl=sd(null),Al=sd(null),Rl={state:"idle"},Fl=class{abortController=new AbortController;activeTasks=new Set;disposers=[];phase="starting";close=null;signal=this.abortController.signal;tasks={run:e=>this.runTask(e)};own(e,t){if("starting"!==this.phase)throw new Error("Cannot register a resource after the Canvas Runtime is published or disposal starts.");return this.disposers.push(n=>"function"==typeof t?t(e):"rollback"===n&&t.rollback?t.rollback(e):t.shutdown(e)),e}publish({beforeShutdown:e}={}){if("starting"!==this.phase)throw new Error(`Only a starting Canvas Runtime can be published; received runtime in "${this.phase}" phase.`);return this.phase="ready",()=>null!==this.close?"shutdown"===this.close.mode?this.close.result:Promise.reject(new Error("Cannot shut down a Canvas Runtime during rollback.")):this.beginClose({mode:"shutdown",beforeShutdown:e})}rollback(e){return null!==this.close?"rollback"===this.close.mode?this.close.result:Promise.reject(new Error("Cannot roll back a Canvas Runtime during shutdown.")):"starting"!==this.phase?Promise.reject(new Error(`Only a starting Canvas Runtime can roll back; received runtime in "${this.phase}" phase.`)):this.beginClose({mode:"rollback",cause:e})}beginClose(e){const t=[],n=Promise.resolve().then(async()=>{const n=[...t,...await this.disposeResources(e.mode)];if(this.phase="disposed","rollback"===e.mode){if(n.length>0)throw new AggregateError([e.cause,...n],"CanvasKit Runtime initialization failed and cleanup reported errors.",{cause:e.cause});throw e.cause}if(n.length>0)throw new AggregateError(n,"Failed to dispose one or more CanvasKit Runtime resources.")});if(this.close={mode:e.mode,result:n},"shutdown"===e.mode)try{e.beforeShutdown?.()}catch(i){t.push(i)}return this.phase="disposing",this.abortController.abort("rollback"===e.mode?e.cause:new DOMException("Canvas runtime is disposing.","AbortError")),n}runTask(e){if("ready"!==this.phase)throw new Error(`Canvas tasks require a ready runtime; received runtime in "${this.phase}" phase.`);this.signal.throwIfAborted();const t=Promise.resolve().then(()=>e(this.signal));return this.activeTasks.add(t),t.finally(()=>this.activeTasks.delete(t)).catch(()=>{}),t}async disposeResources(e){await Promise.allSettled([...this.activeTasks]);const t=[];for(;this.disposers.length>0;){const i=this.disposers.pop();try{await i(e)}catch(n){t.push(n)}}return t}},Kl=[500,1e3,2e3,5e3],Dl=class{editor;adapter;options;unsubscribeDocument=null;unsubscribeSession=null;unsubscribeFlushEvents=null;documentTimer=null;sessionTimer=null;pendingDocument=null;pendingSession=null;documentVersion=0;sessionVersion=0;documentRetryCount=0;sessionRetryCount=0;writeChain=Promise.resolve();flushChain=Promise.resolve();isRunning=!1;disposeMode=null;disposePromise=null;constructor(e,t,n={}){this.editor=e,this.adapter=t,this.options=n}start(){if(null!==this.disposeMode)throw new Error("Cannot start disposed canvas persistence.");this.isRunning||(this.isRunning=!0,this.adapter.saveDocument&&(this.unsubscribeDocument=this.editor.operations.subscribe(e=>{var t;this.documentVersion+=1,this.documentRetryCount=0,this.pendingDocument={snapshot:(t=e.snapshot,JSON.parse(JSON.stringify(t))),version:this.documentVersion},this.scheduleDocumentSave(200)})),this.adapter.saveSession&&(this.unsubscribeSession=this.editor.listen(e=>{var t,n;((t=e.diff).added.some(e=>"session"===e.scope)||t.updated.some(e=>"session"===e.before.scope||"session"===e.after.scope)||t.removed.some(e=>"session"===e.scope))&&(this.sessionVersion+=1,this.sessionRetryCount=0,this.pendingSession={snapshot:(n=this.editor.snapshots.getSession(),JSON.parse(JSON.stringify(n))),version:this.sessionVersion},this.scheduleSessionSave(200))})),this.unsubscribeFlushEvents=this.options.flushEvents?.subscribe(this.flushForHostLifecycle)??null)}flush(){if(null!==this.disposeMode)return Promise.reject(new Error("Cannot flush disposed canvas persistence."));const e=this.flushChain.then(()=>this.flushNow());return this.flushChain=e.catch(()=>{}),e}shutdown(){return this.dispose("shutdown")}rollback(){return this.dispose("rollback")}dispose(e){return null!==this.disposeMode?this.disposeMode!==e?Promise.reject(new Error(`Canvas persistence disposal already started in "${this.disposeMode}" mode.`)):this.disposePromise:(this.disposeMode=e,this.disposePromise=Promise.resolve().then(()=>"shutdown"===e?this.finishShutdown():this.finishRollback()),this.disposePromise)}async finishShutdown(){this.stopIntake(),await this.flushChain,await this.flushNow()}async finishRollback(){this.stopIntake(),this.discardPendingSnapshots(),await this.flushChain,await this.writeChain,this.discardPendingSnapshots()}stopIntake(){this.isRunning=!1,this.cancelDocumentTimer(),this.cancelSessionTimer(),this.unsubscribeDocument?.(),this.unsubscribeSession?.(),this.unsubscribeFlushEvents?.(),this.unsubscribeDocument=null,this.unsubscribeSession=null,this.unsubscribeFlushEvents=null}async flushNow(){const e=await this.flushPendingSnapshots();try{await(this.adapter.flush?.())}catch(t){e.push(t)}if(e.length>0)throw new AggregateError(e,"Failed to flush canvas persistence.")}async flushPendingSnapshots(){this.cancelDocumentTimer(),this.cancelSessionTimer();const e=this.savePendingDocument(),t=this.savePendingSession();return(await Promise.allSettled([e,t])).flatMap(e=>"rejected"===e.status?[e.reason]:[])}discardPendingSnapshots(){this.cancelDocumentTimer(),this.cancelSessionTimer(),this.pendingDocument=null,this.pendingSession=null}savePendingDocument(){const e=this.pendingDocument;if(!e||!this.adapter.saveDocument)return this.writeChain;this.pendingDocument=null;const t=this.queueWrite(()=>Promise.resolve(this.adapter.saveDocument(e.snapshot))).then(()=>{this.documentVersion===e.version&&(this.documentRetryCount=0)}).catch(t=>{throw this.documentVersion===e.version&&null===this.pendingDocument&&(this.pendingDocument=e,this.scheduleDocumentRetry()),t});return this.writeChain=t.catch(()=>{}),t}savePendingSession(){const e=this.pendingSession;if(!e||!this.adapter.saveSession)return this.writeChain;this.pendingSession=null;const t=this.queueWrite(()=>Promise.resolve(this.adapter.saveSession(e.snapshot))).then(()=>{this.sessionVersion===e.version&&(this.sessionRetryCount=0)}).catch(t=>{throw this.sessionVersion===e.version&&null===this.pendingSession&&(this.pendingSession=e,this.scheduleSessionRetry()),t});return this.writeChain=t.catch(()=>{}),t}queueWrite(e){return this.writeChain.then(e)}scheduleDocumentSave(e){this.cancelDocumentTimer(),this.documentTimer=setTimeout(()=>{this.documentTimer=null,this.savePendingDocument().catch(e=>{this.reportError("Could not persist canvas document.",e)})},e)}scheduleSessionSave(e){this.cancelSessionTimer(),this.sessionTimer=setTimeout(()=>{this.sessionTimer=null,this.savePendingSession().catch(e=>{this.reportError("Could not persist canvas session.",e)})},e)}scheduleDocumentRetry(){if(!this.isRunning||null!==this.documentTimer)return;const e=Kl[this.documentRetryCount];void 0!==e&&(this.documentRetryCount+=1,this.scheduleDocumentSave(e))}scheduleSessionRetry(){if(!this.isRunning||null!==this.sessionTimer)return;const e=Kl[this.sessionRetryCount];void 0!==e&&(this.sessionRetryCount+=1,this.scheduleSessionSave(e))}cancelDocumentTimer(){null!==this.documentTimer&&(clearTimeout(this.documentTimer),this.documentTimer=null)}cancelSessionTimer(){null!==this.sessionTimer&&(clearTimeout(this.sessionTimer),this.sessionTimer=null)}flushForHostLifecycle=()=>{this.flush().catch(e=>{this.reportError("Could not persist canvas snapshot.",e)})};reportError(e,t){try{this.options.onError?.(new Error(e,{cause:t}))}catch{}}},Ll={status:"starting"},Yl=[],Xl="snapshots",Ol=null,zl="canvas-kit.document",Nl="canvas-kit.session",$l=Math.min,_l=Math.max,Hl=Math.round,Ul=Math.floor,Wl=e=>({x:e,y:e}),ql={left:"right",right:"left",bottom:"top",top:"bottom"},Vl=["left","right"],Gl=["right","left"],jl=["top","bottom"],Ql=["bottom","top"],Zl=new Set(["left","top"]),Jl=/transform|translate|scale|rotate|perspective|filter/,eh=/paint|layout|strict|content/,th=e=>!!e&&"none"!==e,nh=Wl(0),ih={convertOffsetParentRelativeRectToViewportRelativeRect:e=>{let{elements:t,rect:n,offsetParent:i,strategy:s}=e;const o="fixed"===s,r=Ia(i),a=!!t&&Ta(t.floating);if(i===r||a&&o)return n;let d={scrollLeft:0,scrollTop:0},c=Wl(1);const l=Wl(0),h=ba(i);if((h||!h&&!o)&&(("body"!==ya(i)||xa(r))&&(d=Aa(i)),h)){const e=za(i);c=Xa(i),l.x=e.x+i.clientLeft,l.y=e.y+i.clientTop}const u=!r||h||o?Wl(0):$a(r,d);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-d.scrollLeft*c.x+l.x+u.x,y:n.y*c.y-d.scrollTop*c.y+l.y+u.y}},getDocumentElement:Ia,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:i,strategy:s}=e;const o=[..."clippingAncestors"===n?Ta(t)?[]:Ua(t,this._c):[].concat(n),i],r=_a(t,o[0],s);let a=r.top,d=r.right,c=r.bottom,l=r.left;for(let h=1;h<o.length;h++){const e=_a(t,o[h],s);a=_l(e.top,a),d=$l(e.right,d),c=$l(e.bottom,c),l=_l(e.left,l)}return{width:d-l,height:c-a,x:l,y:a}},getOffsetParent:Ga,getElementRects:async function(e){const t=this.getOffsetParent||Ga,n=this.getDimensions,i=await n(e.floating);return{reference:Wa(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:i.width,height:i.height}}},getClientRects:e=>Array.from(e.getClientRects()),getDimensions:e=>{const{width:t,height:n}=La(e);return{width:t,height:n}},getScale:Xa,isElement:wa,isRTL:e=>"rtl"===Ba(e).direction},sh=e=>(void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var n,i;const{x:s,y:o,placement:r,middlewareData:a}=t,d=await(async(e,t)=>{const{placement:n,platform:i,elements:s}=e,o=await(null==i.isRTL?void 0:i.isRTL(s.floating)),r=oa(n),a=ra(n),d="y"===ca(n),c=Zl.has(r)?-1:1,l=o&&d?-1:1,h=sa(t,e);let{mainAxis:u,crossAxis:p,alignmentAxis:g}="number"==typeof h?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:h.mainAxis||0,crossAxis:h.crossAxis||0,alignmentAxis:h.alignmentAxis};return a&&"number"==typeof g&&(p="end"===a?-1*g:g),d?{x:p*l,y:u*c}:{x:u*c,y:p*l}})(t,e);return r===(null==(n=a.offset)?void 0:n.placement)&&null!=(i=a.arrow)&&i.alignmentOffset?{}:{x:s+d.x,y:o+d.y,data:{...d,placement:r}}}}),oh=e=>(void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:i,placement:s,platform:o}=t,{mainAxis:r=!0,crossAxis:a=!1,limiter:d={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...c}=sa(e,t),l={x:n,y:i},h=await o.detectOverflow(t,c),u=ca(oa(s)),p=aa(u);let g=l[p],f=l[u];r&&(g=ia(g+h["y"===p?"top":"left"],g,g-h["y"===p?"bottom":"right"])),a&&(f=ia(f+h["y"===u?"top":"left"],f,f-h["y"===u?"bottom":"right"]));const m=d.fn({...t,[p]:g,[u]:f});return{...m,data:{x:m.x-n,y:m.y-i,enabled:{[p]:r,[u]:a}}}}}),rh=e=>(void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,i;const{placement:s,middlewareData:o,rects:r,initialPlacement:a,platform:d,elements:c}=t,{mainAxis:l=!0,crossAxis:h=!0,fallbackPlacements:u,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:g="none",flipAlignment:f=!0,...m}=sa(e,t);if(null!=(n=o.arrow)&&n.alignmentOffset)return{};const y=oa(s),S=ca(a),I=oa(a)===a,v=await(null==d.isRTL?void 0:d.isRTL(c.floating)),w=u||(I||!f?[ua(a)]:(e=>{const t=ua(e);return[ha(e),t,ha(t)]})(a)),b="none"!==g;!u&&b&&w.push(...function(e,t,n,i){const s=ra(e);let o=((e,t,n)=>{switch(e){case"top":case"bottom":return n?t?Gl:Vl:t?Vl:Gl;case"left":case"right":return t?jl:Ql;default:return[]}})(oa(e),"start"===n,i);return s&&(o=o.map(e=>e+"-"+s),t&&(o=o.concat(o.map(ha)))),o}(a,f,g,v));const P=[a,...w],x=await d.detectOverflow(t,m),C=[];let T=(null==(i=o.flip)?void 0:i.overflows)||[];if(l&&C.push(x[y]),h){const e=((e,t,n)=>{void 0===n&&(n=!1);const i=ra(e),s=la(e),o=da(s);let r="x"===s?i===(n?"end":"start")?"right":"left":"start"===i?"bottom":"top";return t.reference[o]>t.floating[o]&&(r=ua(r)),[r,ua(r)]})(s,r,v);C.push(x[e[0]],x[e[1]])}if(T=[...T,{placement:s,overflows:C}],!C.every(e=>e<=0)){var M,E;const e=((null==(M=o.flip)?void 0:M.index)||0)+1,t=P[e];if(t&&("alignment"!==h||S===ca(t)||T.every(e=>ca(e.placement)!==S||e.overflows[0]>0)))return{data:{index:e,overflows:T},reset:{placement:t}};let n=null==(E=T.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:E.placement;if(!n)switch(p){case"bestFit":{var k;const e=null==(k=T.filter(e=>{if(b){const t=ca(e.placement);return t===S||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:k[0];e&&(n=e);break}case"initialPlacement":n=a}if(s!==n)return{reset:{placement:n}}}return{}}}),ah=["bottom"],dh=["bottom-start"],ch=["bottom"],lh=sd(null);export{Ja as CanvasKitFloatingContent,ta as CanvasKitFloatingToolbarLayer,tr as CanvasKitProvider,$r as CanvasKitRoot,nd as FloatingSelectionToolbarPageSpace,fr as applyCanvasActionShortcutOverrides,Js as createCanvasApiToken,F as createCustomShapeColor,Ur as createLocalSnapshotPersistence,R as createThemeShapeColor,Zs as defineCanvasPlugin,gr as getCanvasActionShortcuts,L as getThemeColorTokenName,D as isCustomShapeColorRef,K as isThemeShapeColorRef,Vr as readPersistedDocumentSnapshot,qr as readPersistedEditorSnapshots,Gr as readPersistedSessionSnapshot,eo as requireApi,X as resolveShapeColor,Y as shapeColorToCssColor,nr as useCanvasKit,Jo as useCanvasKitFloatingPortalContainer,Vo as useCanvasKitWheelCapture,ir as useCanvasValue,td as useFloatingSelectionToolbarPosition};
1
+ function e(e){return e}function t(e){return Object.freeze({id:e,kind:"api"})}function n(e,t){return e.require(t)}function s(e){Nt(()=>{const t=e.current;if(!t)return;const n=t.closest("[data-canvas-kit]"),s=e=>{!e.ctrlKey&&((e,t)=>{let n=e instanceof Element?e:e instanceof Node?e.parentElement:null;for(;n&&t.contains(n);){if(n instanceof HTMLElement&&o(n))return!0;if(n===t)break;n=n.parentElement}return!1})(e.target,t)||bt(e,t,n??void 0)&&(e.preventDefault(),e.stopPropagation())};return t.addEventListener("wheel",s,{passive:!1}),()=>{t.removeEventListener("wheel",s)}},[e])}function o(e){const{overflowY:t}=window.getComputedStyle(e);return e.scrollHeight>e.clientHeight&&("auto"===t||"scroll"===t||"overlay"===t)}function r({children:e}){const[t,n]=Kt(null),s=Ft(e=>{n(e)},[]),o=$t(()=>({registerTarget:s,target:t}),[s,t]);
2
+ return Vt(_t.Provider,{value:o,children:e})}function i(){const{registerTarget:e}=l(),t=Ht(null);return s(t),Vt("div",{ref:Ft(n=>{t.current=n,e(n)},[e]),className:"land-canvas__floating-portal-host","data-ui":"canvas-kit-floating-portal-host"})}function a(){return l().target}function c(){return Bt(_t)?.target??void 0}function l(){const e=Bt(_t);if(!e)throw new Error("CanvasKit floating content must be rendered inside CanvasKitRoot.");return e}function d({canvas:e,children:t}){
3
+ return Vt(Yt.Provider,{value:e,children:t})}function u(){const e=Bt(Yt);if(!e)throw new Error("useCanvasKit must be used inside CanvasKitProvider.");return e}function p(e){return jt(e.subscribe,e.getSnapshot,e.getSnapshot)}function h({contributions:e,getHostElement:t,isEditing:n,onError:s,screenToPage:o}){return Nt(()=>{const r=o=>{if(!y(t(),o)||n()||Rt(o.target))return;const r=w({source:"clipboard",dataTransfer:o.clipboardData});f(e,r)&&(o.preventDefault(),m(e,r).catch(e=>{s(new Error("Canvas clipboard import failed.",{cause:e}))}))},i=s=>{!y(t(),s)||n()||Rt(s.target)||g(e,v(s.dataTransfer))&&(s.preventDefault(),s.dataTransfer&&(s.dataTransfer.dropEffect="copy"))},a=r=>{const i=y(t(),r);if(!i||n()||Rt(r.target))return;const a=g(e,v(r.dataTransfer)),c=w({source:"drop",dataTransfer:r.dataTransfer,pagePoint:o(Tt(r,i))});f(e,c)?(r.preventDefault(),m(e,c).catch(e=>{s(new Error("Canvas drop import failed.",{cause:e}))})):a&&(r.preventDefault(),r.dataTransfer&&(r.dataTransfer.dropEffect="none"))};return window.addEventListener("paste",r),window.addEventListener("dragover",i),window.addEventListener("drop",a),()=>{window.removeEventListener("paste",r),window.removeEventListener("dragover",i),window.removeEventListener("drop",a)}},[e,t,n,s,o]),null}function f(e,t){return e.some(e=>e.accepts(t))}function g(e,t){return e.some(e=>e.acceptsPreview?.(t)??!1)}async function m(e,t){for(const n of e)if(n.accepts(t)&&"handled"===await n.import(t))return"handled";return"ignored"}function v(e){return e?{source:"drop",dataTypes:Array.from(e.types),fileTypes:Array.from(e.items).filter(e=>"file"===e.kind).map(e=>e.type).filter(Boolean)}:{source:"drop",dataTypes:[],fileTypes:[]}}function w({dataTransfer:e,pagePoint:t,source:n}){const s=e?.getData("text/plain")||void 0,o=e?.getData("text/html")||void 0,r=[...(e?.getData("text/uri-list")||void 0)?.split(/\r?\n/).filter(e=>e&&!e.startsWith("#"))??[],...s&&x(s.trim())?[s.trim()]:[]];return{source:n,files:b(e),text:s,html:o,...r.length>0?{urls:r}:{},pagePoint:t}}function y(e,t){if(!e)return null;const n=(t.target instanceof Element?t.target:document.activeElement)?.closest(It);return n instanceof HTMLElement&&e.contains(n)?n:null}function b(e){if(!e)return[];const t=Array.from(e.files);return t.length>0?t:Array.from(e.items).flatMap(e=>{if("file"!==e.kind)return[];const t=e.getAsFile();return t?[t]:[]})}function x(e){try{const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch{return e.startsWith("data:image/")}}function S({bindings:e,getHostElement:t,onError:n}){const s=u(),o=p(s.viewport.grid.state),{editor:r,importContributions:i,renderBindings:a,setContextMenu:c}=e,l=Ft(()=>s.tools.state.getSnapshot().isEditing,[s]),d=Ft(e=>r.viewport.screenToPage(e),[r]);
4
+ return Wt(zt,{children:[Vt(St.Provider,{value:r,children:Vt(kt,{onContextMenuRequest:c,renderBindings:a,showGrid:o})}),Vt(h,{contributions:i,getHostElement:t,isEditing:l,onError:n,screenToPage:d})]})}function E(e){return void 0===e?[]:Array.isArray(e)?e:[e]}function I(e,t){if(!t||0===Object.keys(t).length)return e;const n=new Set(Object.keys(t)),s=e.map(e=>{if(!Object.prototype.hasOwnProperty.call(t,e.id))return e;n.delete(e.id);const s=t[e.id];return{...e,shortcut:s??void 0}});if(n.size>0)throw new Error(`Unknown CanvasAction shortcut override ids: ${[...n].join(", ")}.`);return s}function C(e,t){if(e.api&&!t?.api)throw new Error(`Canvas plugin "${e.id}" declares API "${e.api.id}" but setup returned no API value.`);if(!e.api&&t?.api)throw new Error(`Canvas plugin "${e.id}" returned an API value without declaring an API token.`)}function P(e,t){return new Set((e.requires??[]).flatMap(e=>{const n=t.get(e.id);return n?.api?[n.api.id]:[]}))}function T(e,t){const n=new Set;for(const s of e){if(n.has(s))throw new Error(`Duplicate ${t} id: ${s}.`);n.add(s)}}function k(e){return"provider"===e.kind}function R(e){return"svg-inliner"===e.kind}function A(e,t){const n=new Set;for(const s of e){if(n.has(s))throw new Error(`Duplicate ${t}: ${s}.`);n.add(s)}}function L(){if("undefined"!=typeof window&&"function"==typeof window.requestAnimationFrame&&"function"==typeof window.cancelAnimationFrame)return{requestFrame:e=>window.requestAnimationFrame(e),cancelFrame:e=>window.cancelAnimationFrame(e),prefersReducedMotion:()=>"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}}function D(e){return{id:e.id,name:e.name,index:e.index,meta:{...e.meta}}}function M(e){return{id:e?.id??"document:main",meta:{...e?.meta??{}}}}function O(e,t){return{id:e.id,type:e.type,parentId:e.parentId,pageId:t,index:e.index,x:e.x,y:e.y,rotation:e.rotation,scaleX:e.scaleX,scaleY:e.scaleY,opacity:e.opacity,isHidden:e.isHidden,isLocked:e.isLocked,props:{...e.props},meta:{...e.meta}}}function F(e){const{editor:t}=e,n=t.state.session.get(),s=n.activeToolId;e.assertToolId(s);const o=t.pages.getAll().map(e=>({pageId:e.id,selectedShapeIds:[...t.selection.getIds(e.id)],camera:{...t.viewport.getCamera(e.id)}}));return{currentPageId:n.currentPageId,activeToolId:s,isToolLocked:n.isToolLocked,meta:{...n.meta},pages:o}}function B(e){return{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?{...e.props}:void 0,meta:void 0===e.meta?void 0:{...e.meta}}}function N({childIds:e,companionIds:t,context:n,depth:s,editor:o,index:r,pageId:i,shape:a}){return{id:a.id,parentId:a.parentId,pageId:i,type:a.type,companionIds:t,childIds:e,siblingIndex:r,depth:s,canReceiveChildren:o.layers.canReceiveChildren(a.id),isHidden:a.isHidden,isLocked:a.isLocked,isEffectivelyHidden:j(o,n,a.id),isEffectivelyLocked:z(n,a.id)}}function $({bindings:e,editor:t,shapes:n}){const s=new Map(n.map(e=>[e.id,e])),o=t.bindings.getShapeCompanionRootIds(n.map(({id:e})=>e),e),r=new Map,i=new Map,a=new Map;for(const c of n){const e=o.get(c.id)??c.id,t=s.has(e)?e:c.id;if(r.set(c.id,t),t===c.id){const e=a.get(c.parentId);e?e.push(c):a.set(c.parentId,[c])}else{const e=i.get(t);e?e.push(c.id):i.set(t,[c.id])}}return{childShapesByParentId:a,companionIdsByRootId:i,rootIdByShapeId:r,shapeById:s}}function H(e,t){return e.childShapesByParentId.get(t)??[]}function K(e,t){let n=0,s=e.shapeById.get(t);const o=new Set([t]);for(;s?.parentId.startsWith("shape:");){const t=s.parentId;if(o.has(t))break;o.add(t),s=e.shapeById.get(t),n+=1}return n}function j(e,t,n){const s=new Set;let o=t.shapeById.get(n);for(;o;){if(o.isHidden)return!0;if(!o.parentId.startsWith("shape:"))return!1;const n=o.parentId;if(s.has(n))return!1;s.add(n);const r=t.shapeById.get(n);if(!r)return!1;if(!e.shapes.getUtil(r).isChildVisible(r,o,{editor:e}))return!0;o=r}return!1}function z(e,t){const n=new Set;let s=e.shapeById.get(t);for(;s;){if(s.isLocked)return!0;if(!s.parentId.startsWith("shape:"))return!1;const t=s.parentId;if(n.has(t))return!1;n.add(t),s=e.shapeById.get(t)}return!1}function V(e){let t=e;const n=new Set;return{readable:{getSnapshot:()=>t,subscribe:e=>(n.add(e),()=>n.delete(e))},set(e){if(!Object.is(t,e)){t=e;for(const e of[...n])e()}}}}function W({getDependencies:e,getSnapshot:t,name:n,signals:s}){let o,r=[],i=!1;const a=()=>{const n=e();return i&&((e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Object.is(e[n],t[n]))return!1;return!0})(r,n)||(r=n,o=t(n),i=!0),o};return{getSnapshot:a,subscribe(t){let o=a();return At(n,{get:e,graph:s},()=>{const e=a();Object.is(o,e)||(o=e,t())},{fireImmediately:!1})}}}function q({apis:e,editor:t,exports:n,productId:s,startup:o}){const r=e=>(e?e.map(e=>t.shapes.get(e)).filter(e=>!!e):t.pages.getAll().flatMap(e=>t.shapes.getForPage(e.id))).map(e=>O(e,t.layers.getPageId(e.id))),i=e=>{const[n,...s]=e;return(({bindings:e,editor:t,pageId:n,shapes:s})=>{const o=[],r=$({bindings:e,editor:t,shapes:s}),i=(e,s)=>{H(r,e).forEach((e,a)=>{const c=H(r,e.id).map(e=>e.id);o.push(N({childIds:c,companionIds:r.companionIdsByRootId.get(e.id)??[],context:r,depth:s,editor:t,index:a,pageId:n,shape:e})),i(e.id,s+1)})};return i(n,0),o})({bindings:s.filter(Ct),editor:t,pageId:n,shapes:s.filter(mt)})},a=e=>{if(!t.tools.hasTool(e))throw new Error(`Unknown canvas kit tool "${e}".`)},c={assertToolId:a,editor:t,productId:s},{readable:l,set:d}=V(!1),{readable:u,set:p}=V(null),h=W({signals:t.signals,name:"CanvasKit.document",getDependencies:()=>[t.document.getMetadata()],getSnapshot:([e])=>M(e)}),f=W({signals:t.signals,name:"CanvasKit.document.readonlyState",getDependencies:()=>[t.state.readonly.get()],getSnapshot:([e])=>e}),g=W({signals:t.signals,name:"CanvasKit.session",getDependencies:()=>[t.state.session.get().meta],getSnapshot:([e])=>({meta:{...e}})}),m=W({signals:t.signals,name:"CanvasKit.selection",getDependencies:()=>[t.state.selectedShapeIds.get(),t.state.selectedShapes.get(),t.state.selectionMetadata.get(),t.state.selectionPageBounds.get(),t.state.selectionAnchorPagePoint.get(),t.render.interaction.selectionTranslationActive.get(),t.state.currentPageId.get()],getSnapshot:([e,t,n,s,o,r,i])=>({...n,ids:[...e],shapes:t.map(e=>O(e,i)),pageBounds:s?{x:s.minX,y:s.minY,width:s.w,height:s.h}:null,anchorPagePoint:o?{x:o.x,y:o.y}:null,isTranslating:r})}),v=W({signals:t.signals,name:"CanvasKit.pages",getDependencies:()=>[t.state.pages.get(),t.state.currentPageId.get(),t.state.currentPageShapeIds.get()],getSnapshot:([e,t,n])=>{const s=e.map(D),o=s.find(e=>e.id===t)??null;return{pages:s,currentPage:o,currentPageId:t,currentPageShapeIds:[...n],canDeleteCurrentPage:s.length>1&&null!==o}}}),w=W({signals:t.signals,name:"CanvasKit.history",getDependencies:()=>[t.state.history.get()],getSnapshot:([e])=>({...e})}),y=W({signals:t.signals,name:"CanvasKit.viewport",getDependencies:()=>[t.state.camera.get(),t.state.pageTransform.get()],getSnapshot:([e,t])=>({camera:{...e},zoom:e.z,pageTransform:t.toCssString()})}),b=W({signals:t.signals,name:"CanvasKit.tools",getDependencies:()=>[t.state.tool.get(),t.state.shapeEditing.get()],getSnapshot:([e,t])=>(a(e.activeToolId),{currentToolId:e.activeToolId,isLocked:e.isToolLocked,isEditing:null!==t.session})}),x=W({signals:t.signals,name:"CanvasKit.layers",getDependencies:()=>U(t,t.pages.getCurrentId()),getSnapshot:i});return{canvas:{startup:o,api:t=>e.get(t)??void 0,document:{state:h,readonlyState:f,getSnapshot:()=>(e=>{const{editor:t}=e,n=t.state.tool.get().activeToolId;return e.assertToolId(n),{productId:e.productId,document:M(t.document.getMetadata()),pageId:t.pages.getCurrentId(),activeToolId:n,selectedShapeIds:[...t.selection.getIds()],shapeCount:t.state.currentPageShapeIds.get().length,session:F(e)}})(c),updateMeta:e=>(t.document.updateMetadata({...e},"user"),M(t.document.getMetadata()))},session:{state:g,updateMeta(e){const n=t.session.get();return t.session.update({meta:{...n.meta,...e}},"user"),{meta:{...t.state.session.get().meta}}}},selection:{state:m,select:e=>t.commands.setSelectedShapeIds([...e],{source:"user"}),selectAll:()=>t.selection.selectAll("user"),clear:()=>t.commands.setSelectedShapeIds([],{source:"user"}),delete:()=>t.selection.delete("user"),duplicate:()=>t.selection.duplicate({source:"user"}),resetRotation:()=>t.selection.resetRotation("user"),flip:e=>t.selection.flip(e,"user"),setOpacity:e=>((e,t)=>{if(!Number.isFinite(t))return;const n=Math.min(1,Math.max(0,t)),s=e.state.selectedShapes.get().filter(e=>e.opacity!==n).map(e=>({id:e.id,opacity:n}));s.length>0&&e.commands.updateShapes(s,{source:"user"})})(t,e),align:e=>t.selection.align(e,"user"),distribute:e=>t.selection.distribute(e,"user")},pages:{state:v,create:e=>D(t.pages.createAndSelect(e?{name:e.name,meta:e.meta?{...e.meta}:void 0}:void 0,"user")),rename:(e,n)=>t.pages.rename(e,n,"user"),updateMeta:(e,n)=>t.pages.updateMetadata(e,{...n},"user")?.id??null,delete:e=>t.pages.delete(e,"user"),deleteCurrent:()=>t.pages.delete(t.pages.getCurrentId(),"user"),setCurrent:e=>t.pages.select(e,"user")},history:{state:w,clear:()=>t.history.clear(),undo:()=>t.history.undo(),redo:()=>t.history.redo()},viewport:{state:y,grid:{state:l,setVisible:d,toggle:()=>d(!l.getSnapshot())},setCamera:(e,n)=>t.commands.setCamera({pageId:n,camera:e},{source:"user"}),zoomIn:()=>t.viewport.zoomAtCenter(-120,"system"),zoomOut:()=>t.viewport.zoomAtCenter(120,"system"),resetZoom:()=>t.viewport.resetZoom("user"),reset:()=>t.commands.setCamera({camera:{x:0,y:0,z:1}},{source:"user"})},tools:{state:b,setCurrent:e=>{if(!t.tools.hasTool(e))throw new Error(`Unknown product tool "${e}".`);t.tools.select(e,"user")},setLocked:e=>t.tools.setLocked(e,"user"),toggleLocked:()=>t.tools.toggleLocked("user")},shapes:{get:e=>{const n=t.shapes.get(e);return n?O(n,t.layers.getPageId(n.id)):null},getMany:e=>r(e),getAll:()=>r(),getExportBounds:(e,n)=>{const s=t.shapes.get(e);if(!s)return null;let o;switch(n.space.type){case"shape-local":{const e=t.shapes.get(n.space.shapeId);if(!e)return null;if(o=t.shapes.computeExportBoundsInShapeSpace(s,e),!o)return null;break}case"page":o=t.shapes.computeExportPageBounds(s);break;default:throw new Error(`Unsupported canvas shape export bounds space "${String(n.space)}".`)}return![o.x,o.y,o.w,o.h].every(Number.isFinite)||o.w<0||o.h<0?null:{x:o.x,y:o.y,width:o.w,height:o.h}},update:e=>function(e,t){const n=t.filter(t=>{const n=e.shapes.get(t.id);return!!n&&((e,t)=>{return!(!t.props&&void 0===t.meta)||(t.x??e.x)!==e.x||(t.y??e.y)!==e.y||(t.rotation??e.rotation)!==e.rotation||(t.scaleX??e.scaleX)!==e.scaleX||(t.scaleY??e.scaleY)!==e.scaleY||(void 0===t.opacity?e.opacity:(s=e.opacity,"number"==typeof(n=t.opacity)&&Number.isFinite(n)?Math.min(1,Math.max(0,n)):s))!==e.opacity||(t.isHidden??e.isHidden)!==e.isHidden||(t.isLocked??e.isLocked)!==e.isLocked||(t.parentId??e.parentId)!==e.parentId||(t.index??e.index)!==e.index;var n,s})(n,t)}).map(B);return 0===n.length?[]:(e.commands.updateShapes(n,{source:"user"}),n.map(e=>e.id))}(t,e),updateMeta:(e,n)=>{const s=t.shapes.get(e);return s?(t.commands.updateShapes([{id:e,meta:{...s.meta,...n}}],{source:"user"}),e):null},delete:e=>t.shapes.delete([...e],"user")},assets:{get:e=>{const n=t.assets.get(e);return n?(e=>({id:e.id,type:e.type,props:{...e.props},meta:{...e.meta}}))(n):null},resolveUrl:e=>t.assets.resolveUrl(e)},layers:{state:x,getTree:e=>i(U(t,e??t.pages.getCurrentId())),getNode:e=>(({editor:e,id:t})=>{const n=e.shapes.get(t),s=n?e.layers.getPageId(n.id):null;if(!n||!s)return null;const o=e.shapes.getForPage(s),r=$({bindings:o.flatMap(t=>e.bindings.getForShape(t.id)),editor:e,shapes:o}),i=r.rootIdByShapeId.get(n.id)??n.id,a=r.shapeById.get(i);if(!a)return null;const c=H(r,a.parentId);return N({childIds:H(r,a.id).map(e=>e.id),companionIds:r.companionIdsByRootId.get(a.id)??[],context:r,depth:K(r,a.id),editor:e,index:c.findIndex(e=>e.id===a.id),pageId:s,shape:a})})({editor:t,id:e}),getActionState:e=>({canGroup:t.layers.canGroup(e),canUngroup:t.layers.canUngroup(e),canMoveBackward:t.layers.canMove(e,"backward"),canMoveForward:t.layers.canMove(e,"forward")}),centerOn:(e,n)=>t.viewport.centerOnShape(e,{...n,source:"user"}),setHidden:(e,n)=>t.shapes.setHidden([...e],n,"user"),setLocked:(e,n)=>t.shapes.setLocked([...e],n,"user"),group:e=>t.layers.group([...e],"user")?.id??null,ungroup:e=>t.layers.ungroup([...e],"user"),move:(e,n)=>t.layers.move([...e],n,"user"),moveToEdge:(e,n)=>t.layers.moveToEdge([...e],n,"user"),moveToPlacement:(e,n)=>{const s=t.layers.moveToPlacement({ids:[...e],parentId:n.parentId,beforeId:n.beforeId??void 0},"user");return s.ok?{ok:!0,ids:s.movedIds}:{ok:!1,reason:"locked"===s.reason?"locked":"cycle"===s.reason?"cycle":"invalidBeforeId"===s.reason?"invalid-before":"unsupportedTransform"===s.reason?"mixed-parent":"notFound"===s.reason&&0===e.length?"empty-selection":"invalid-parent"}}},contextMenu:{state:u,dismiss:()=>p(null)},exports:{state:{getSnapshot:()=>n.getStatus(),subscribe:e=>n.subscribe(e)},getFormats:()=>n.getFormats(),getStatus:()=>n.getStatus(),export:(e,t)=>n.export(e,t)}},host:{setContextMenu:p}}}function U(e,t){const n=e.shapes.getForPage(t),s=new Map;for(const o of n)for(const t of e.bindings.getForShape(o.id))s.set(t.id,t);return[t,...n,...s.values()]}function _(){const e=new Map;let t=!1;return{register({token:n,api:s,pluginId:o}){if(t)throw new Error("Canvas API registry is disposed.");if(e.has(n.id))throw new Error(`Duplicate canvas API token: ${n.id}.`);e.set(n.id,{token:n,api:s,pluginId:o})},view:t=>(({allowedTokenIds:t,ownerLabel:n})=>{const s=s=>{if(t&&!t.has(s.id))throw new Error(`${n} attempted to read undeclared canvas API "${s.id}".`);const o=e.get(s.id);return o?o.api:null};return{get:s,require(e){const t=s(e);if(null===t)throw new Error(`${n} requires unavailable canvas API "${e.id}".`);return t}}})(t),clear(){t||(t=!0,e.clear())}}}async function Y(e,t={}){(e=>{if(!e||!Array.isArray(e.plugins))throw new Error("CanvasKit requires an explicit plugins array.");if(!("persistence"in e))throw new Error("CanvasKit requires an explicit persistence option.")})(e),t.signal?.throwIfAborted();const{canvasPlugins:n,editorPlugins:s,renderPlugins:o}=function(e){const t=(e=>e.flat(1/0))(e);A(t.map(({id:e})=>e),"canvas plugin id");const n=(e=>{const t=new Map(e.map(e=>[e.id,e])),n=[],s=new Set,o=new Set,r=e=>{if(!o.has(e.id)){if(s.has(e.id))throw new Error(`Circular canvas plugin dependency detected at "${e.id}".`);s.add(e.id);for(const n of e.requires??[]){const s=t.get(n.id);if(!s)throw new Error(`Canvas plugin "${e.id}" requires missing plugin "${n.id}".`);r(s)}s.delete(e.id),o.add(e.id),n.push(e)}};for(const i of e)r(i);return n})(t),s=n.flatMap(e=>e.editor?[e.editor]:[]),o=n.flatMap(e=>e.render?[e.render]:[]);return A(s.map(({id:e})=>e),"editor plugin id"),A(n.flatMap(e=>e.api?[e.api.id]:[]),"canvas API token"),{canvasPlugins:n,editorPlugins:s,renderPlugins:o}}(e.plugins),r=Et(o),i=new Jt,a=t.signal?AbortSignal.any([i.signal,t.signal]):i.signal;try{const o=e.id??"canvas-kit",c=e.persistence;c&&i.own(c,e=>e.dispose?.());let l=[];const d=i.own((e=>{const t=wt({cameraAnimationScheduler:L(),documentMeta:e.documentMeta,onUnhandledError:e.onUnhandledError,plugins:e.editorPlugins,resolveAssetUrl:e.resolveAssetUrl});return t.tools.register("select",e=>new Mt(e)),t.tools.register("hand",e=>new xt(e)),t.tools.syncLockedState(t.state.tool.get().isToolLocked),t.commands.setActiveTool("select",{source:"system"}),t.history.clear(),t})({documentMeta:e.documentMeta?{...e.documentMeta}:void 0,onUnhandledError:e.onError,editorPlugins:s,resolveAssetUrl(e){for(const t of l){const n=t.resolve(e);if(n)return n}return null}}),e=>e.dispose()),u=c?i.own(new Zt(d,c,{flushEvents:t.persistenceFlushEvents,onError:e.onError}),{shutdown:e=>e.shutdown(),rollback:e=>e.rollback()}):null,{apis:p,contributions:{assetResolvers:h,exports:f,imports:g}}=function({apis:e,canvasPlugins:t,editor:n,owner:s,productId:o}){const r=new Map(t.map(e=>[e.id,e])),i=[];for(const c of t){s.signal.throwIfAborted();const t=c.setup?.({editor:n,productId:o,apis:e.view({allowedTokenIds:P(c,r),ownerLabel:`Canvas plugin "${c.id}" setup`}),tasks:s.tasks});t&&(s.own(t,e=>e.dispose?.()),i.push({plugin:c,instance:t})),C(c,t),c.api&&t?.api&&e.register({token:c.api,api:t.api,pluginId:c.id})}const a=(e=>{const t=e.flatMap(({instance:e})=>e.imports??[]),n=e.flatMap(({instance:e})=>e.exports??[]),s=e.flatMap(({instance:e})=>e.assetResolvers??[]);return T(t.map(({id:e})=>e),"import contribution"),T(n.map(({id:e})=>e),"export contribution"),T(n.flatMap(e=>"provider"===e.kind?[e.format]:[]),"export format"),T(s.map(({id:e})=>e),"asset resolver contribution"),Object.freeze({imports:Object.freeze((o=t,o.map((e,t)=>({value:e,index:t})).sort((e,t)=>(e.value.order??0)-(t.value.order??0)||e.index-t.index).map(({value:e})=>e))),exports:Object.freeze([...n]),assetResolvers:Object.freeze([...s])});var o})(i);return{apis:e.view({ownerLabel:"CanvasKit"}),contributions:a}}({apis:i.own(_(),e=>e.clear()),canvasPlugins:n,editor:d,owner:i,productId:o});l=h;const m=await(async({assetResolvers:e,editor:t,initialDocumentSnapshot:n,persistenceAdapter:s,persistenceCoordinator:o,signal:r})=>{const i=t.snapshots.getSession(),a=[],c=s?.load?await s.load({signal:r}):{documentSnapshot:null,sessionSnapshot:null};let l;r.throwIfAborted(),null!==c.documentSnapshot?(t.snapshots.loadDocument(c.documentSnapshot,{source:"system"}),l="restored"):void 0!==n?(t.snapshots.loadDocument(n,{source:"system"}),l="initial"):l="empty",r.throwIfAborted();let d=!1;if("restored"===l&&null!==c.sessionSnapshot)try{t.snapshots.loadSession(c.sessionSnapshot,{source:"system"}),d=!0}catch(u){r.throwIfAborted(),a.push(u),t.snapshots.loadSession(i,{source:"system"})}t.history.clear();for(const p of e){r.throwIfAborted();try{await(p.preload?.({editor:t,signal:r})),"restored"===l&&await(p.cleanupAfterRestore?.({editor:t,signal:r}))}catch(u){r.throwIfAborted(),a.push(u)}}return r.throwIfAborted(),o?.start(),{documentSource:l,sessionRestored:d,warnings:[...a]}})({assetResolvers:l,editor:d,initialDocumentSnapshot:e.initialDocumentSnapshot,persistenceAdapter:c,persistenceCoordinator:u,signal:a});!0===e.readonly&&d.document.setReadonly(!0),i.signal.throwIfAborted();const v=i.own(function({editor:e,contributions:t,tasks:n}){const s=t.filter(k),o=t.filter(R),r=new Map;for(const d of s){if(r.has(d.format))throw new Error(`Duplicate canvas export format: ${d.format}.`);r.set(d.format,d)}let i=Xt,a=!1;const c=new Set,l=e=>{if(!Object.is(i,e)){i=e;for(const e of[...c])e()}};return{getFormats:()=>s.map(({format:e,label:t,mimeType:n,fileExtension:s})=>({format:e,label:t,mimeType:n,fileExtension:s})),getStatus:()=>i,subscribe:e=>(c.add(e),()=>c.delete(e)),export:async(t,s)=>n.run(async n=>{if(a)throw new Error("Canvas export controller is disposed.");if("exporting"===i.state)throw new Error("An export is already in progress.");const c=r.get(t);if(!c)throw new Error(`Canvas export format is unavailable: ${t}.`);l({state:"exporting",format:t});try{const t=((e,t)=>{if("selection"===t.scope)return e.selection.getIds();if("page"===t.scope)return e.state.currentPageShapeIds.get();if(!t.shapeIds)throw new Error("Canvas export requires a scope or shapeIds.");return t.shapeIds})(e,s);for(const s of o)n.throwIfAborted(),await(s.prepare?.({editor:e,requestedShapeIds:t,signal:n}));n.throwIfAborted();const r=await c.export({editor:e,shapeIds:t,options:s.options},{signal:n,async inlineSvg(e){let t=e.svg;for(const s of o)n.throwIfAborted(),t=await s.inline({editor:e.editor,exportedShapes:e.exportedShapes,exportedShapeIds:e.exportedShapeIds,svg:t,signal:n});return n.throwIfAborted(),t}});return n.throwIfAborted(),{format:c.format,label:c.label,mimeType:c.mimeType,fileExtension:c.fileExtension,...r}}finally{l(Xt)}}),dispose(){a||(a=!0,l(Xt),c.clear())}}}({editor:d,contributions:f,tasks:i.tasks}),e=>e.dispose());i.signal.throwIfAborted();const{canvas:w,host:y}=q({apis:p,editor:d,exports:v,productId:o,startup:m});return{canvas:w,dispose:i.publish({beforeShutdown:()=>d.closeWrites()}),productId:o,render:{editor:d,importContributions:g,onError:e.onError,renderBindings:r,setContextMenu:y.setContextMenu}}}catch(c){return i.rollback(c)}}function X(e){try{const t=globalThis.reportError;if("function"==typeof t)return void t(e)}catch(t){console.error(t)}console.error(e)}function J({actions:e=en,chromeRenderer:t,onCanvasChange:n,options:s}){const o=(e=>{const[t,n]=Kt(null);return Nt(()=>{let t=!0,s=null;const o=new AbortController,r=e.onError??X;return n({options:e,state:Qt}),Y(e,{persistenceFlushEvents:{subscribe(e){const t=()=>{"hidden"===document.visibilityState&&e()},n=()=>e();return document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",n),window.addEventListener("beforeunload",n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",n),window.removeEventListener("beforeunload",n)}}},signal:o.signal}).then(o=>{s=o,t?n({options:e,state:{status:"ready",runtime:o}}):o.dispose().catch(r)},s=>{t&&n({options:e,state:{status:"error",error:s}})}),()=>{t=!1,o.abort(new DOMException("CanvasKitRoot was cleaned up.","AbortError")),s?.dispose().catch(r)}},[e]),t?.options===e?t.state:Qt})(s);if("error"===o.status)throw o.error;return"ready"!==o.status?null:Vt(G,{actions:e,chromeRenderer:t,onCanvasChange:n,runtime:o.runtime})}function G({actions:e=en,chromeRenderer:t,onCanvasChange:n,runtime:s}){const o=Ht(n),a=Ht(null),c=Ft(()=>a.current,[]),{canvas:l,productId:u,render:p}=s,h=p.onError??X,f=Ft(()=>l.tools.state.getSnapshot().isEditing,[l]);return o.current=n,Nt(()=>(o.current?.(l),()=>o.current?.(null)),[l]),function({actions:e,canvas:t,isEditing:n,onError:s}){Nt(()=>{(e=>{const t=new Set;for(const n of e){if(t.has(n.id))throw new Error(`Duplicate CanvasAction id "${n.id}".`);t.add(n.id)}})(e);const o=o=>{if(n()||Rt(o.target))return;const r={key:o.key,shiftKey:o.shiftKey,altKey:o.altKey,ctrlKey:o.ctrlKey,metaKey:o.metaKey,accelKey:o.metaKey||o.ctrlKey},i=e.find(e=>void 0!==e.shortcut&&E(e.shortcut).some(e=>Dt(e,r)));if(!i)return;if(o.preventDefault(),o.stopPropagation(),!i.isEnabled(t))return;let a;try{a=i.run(t)}catch(c){return void s(new Error(`Canvas action "${i.id}" failed.`,{cause:c}))}a instanceof Promise&&a.catch(e=>{s(new Error(`Canvas action "${i.id}" failed.`,{cause:e}))})};return window.addEventListener("keydown",o,!0),()=>window.removeEventListener("keydown",o,!0)},[e,t,n,s])}({actions:e,canvas:l,isEditing:f,onError:h}),Vt(d,{canvas:l,children:Vt(r,{children:Vt("div",{ref:a,"data-ui":"app-shell","data-canvas-kit":u,className:"land-canvas-kit__shell",children:Wt("main",{"data-ui":"workspace-viewport",className:"land-canvas-kit__viewport",children:[
5
+ Vt(S,{bindings:p,getHostElement:c,onError:h}),t?.(l)??null,
6
+ Vt(i,{})]})})})})}function Z(){return"undefined"==typeof indexedDB?Promise.resolve(null):(nn||(nn=new Promise((e,t)=>{const n=indexedDB.open("canvas-kit.persistence",2);n.addEventListener("upgradeneeded",()=>{var e;(e=n.result).objectStoreNames.contains("snapshots")||e.createObjectStore(tn)}),n.addEventListener("success",()=>{const t=n.result;t.addEventListener("versionchange",()=>{t.close(),nn=null}),e(t)}),n.addEventListener("error",()=>{nn=null,t(n.error)})})),nn)}function Q(e={}){return{async load({signal:t}){t.throwIfAborted();const n=await te(e);return t.throwIfAborted(),n},saveDocument:t=>ee({documentSnapshot:JSON.stringify(t),sessionSnapshot:null},e),saveSession:t=>ee({documentSnapshot:null,sessionSnapshot:JSON.stringify(t)},e)}}async function ee(e,t){const n=[];null!==e.documentSnapshot&&n.push([oe(t),e.documentSnapshot]),null!==e.sessionSnapshot&&n.push([re(t),e.sessionSnapshot]),0!==n.length&&await(async(e,t)=>{if(0===t.length)return;const n=await Z();n&&await new Promise((s,o)=>{const r=n.transaction(e,"readwrite"),i=r.objectStore(e);r.addEventListener("complete",()=>s()),r.addEventListener("abort",()=>o(r.error)),r.addEventListener("error",()=>o(r.error));for(const[e,n]of t)i.put(n,e)})})(tn,n)}async function te(e={}){const[t,n]=await ae([oe(e),re(e)]);return{documentSnapshot:t,sessionSnapshot:n}}async function ne(){return ie(sn)}async function se(){return ie(on)}function oe(e){return e.storageNamespace?`${e.storageNamespace}.document`:sn}function re(e){return e.storageNamespace?`${e.storageNamespace}.session`:on}async function ie(e){const[t]=await ae([e]);return t??null}async function ae(e){return(await(async(e,t)=>{if(0===t.length)return[];const n=await Z();return n?new Promise((s,o)=>{const r=n.transaction(e,"readonly"),i=r.objectStore(e),a=new Array(t.length).fill(null);r.addEventListener("complete",()=>s(a)),r.addEventListener("abort",()=>o(r.error)),r.addEventListener("error",()=>o(r.error)),t.forEach((e,t)=>{const n=i.get(e);n.addEventListener("success",()=>{a[t]=n.result??null}),n.addEventListener("error",()=>o(n.error))})}):null})("snapshots",e)??e.map(()=>null)).map(ce)}function ce(e){if(null==e)return null;if("string"!=typeof e)throw new Error("Persisted canvas snapshot is not a JSON string.");try{return JSON.parse(e)}catch(t){throw new Error("Persisted canvas snapshot contains invalid JSON.",{cause:t})}}function le({children:e,className:t,dataUi:n="canvas-kit-floating-toolbar-layer"}){const s=a();return s?qt(Vt("div",{"data-ui":n,className:de("land-canvas__floating-toolbar-layer",t),children:e}),s):null}function de(...e){return e.filter(Boolean).join(" ")}function ue(e,t,n){return an(e,rn(t,n))}function pe(e,t){return"function"==typeof e?e(t):e}function he(e){return e.split("-")[0]}function fe(e){return e.split("-")[1]}function ge(e){return"x"===e?"y":"x"}function me(e){return"y"===e?"height":"width"}function ve(e){const t=e[0];return"t"===t||"b"===t?"y":"x"}function we(e){return ge(ve(e))}function ye(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}function be(e){const t=he(e);return un[t]+e.slice(t.length)}function xe(e){const{x:t,y:n,width:s,height:o}=e;return{width:s,height:o,top:n,left:t,right:t+s,bottom:n+o,x:t,y:n}}function Se(e,t,n){let{reference:s,floating:o}=e;const r=ve(t),i=we(t),a=me(i),c=he(t),l="y"===r,d=s.x+s.width/2-o.width/2,u=s.y+s.height/2-o.height/2,p=s[a]/2-o[a]/2;let h;switch(c){case"top":h={x:d,y:s.y-o.height};break;case"bottom":h={x:d,y:s.y+s.height};break;case"right":h={x:s.x+s.width,y:u};break;case"left":h={x:s.x-o.width,y:u};break;default:h={x:s.x,y:s.y}}switch(fe(t)){case"start":h[i]-=p*(n&&l?-1:1);break;case"end":h[i]+=p*(n&&l?-1:1)}return h}async function Ee(e,t){var n;void 0===t&&(t={});const{x:s,y:o,platform:r,rects:i,elements:a,strategy:c}=e,{boundary:l="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:p=!1,padding:h=0}=pe(t,e),f=(e=>"number"!=typeof e?(e=>({top:0,right:0,bottom:0,left:0,...e}))(e):{top:e,right:e,bottom:e,left:e})(h),g=a[p?"floating"===u?"reference":"floating":u],m=xe(await r.getClippingRect({element:null==(n=await(null==r.isElement?void 0:r.isElement(g)))||n?g:g.contextElement||await(null==r.getDocumentElement?void 0:r.getDocumentElement(a.floating)),boundary:l,rootBoundary:d,strategy:c})),v="floating"===u?{x:s,y:o,width:i.floating.width,height:i.floating.height}:i.reference,w=await(null==r.getOffsetParent?void 0:r.getOffsetParent(a.floating)),y=await(null==r.isElement?void 0:r.isElement(w))&&await(null==r.getScale?void 0:r.getScale(w))||{x:1,y:1},b=xe(r.convertOffsetParentRelativeRectToViewportRelativeRect?await r.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:v,offsetParent:w,strategy:c}):v);return{top:(m.top-b.top+f.top)/y.y,bottom:(b.bottom-m.bottom+f.bottom)/y.y,left:(m.left-b.left+f.left)/y.x,right:(b.right-m.right+f.right)/y.x}}function Ie(){return"undefined"!=typeof window}function Ce(e){return ke(e)?(e.nodeName||"").toLowerCase():"#document"}function Pe(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function Te(e){var t;return null==(t=(ke(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function ke(e){return!!Ie()&&(e instanceof Node||e instanceof Pe(e).Node)}function Re(e){return!!Ie()&&(e instanceof Element||e instanceof Pe(e).Element)}function Ae(e){return!!Ie()&&(e instanceof HTMLElement||e instanceof Pe(e).HTMLElement)}function Le(e){return!(!Ie()||"undefined"==typeof ShadowRoot)&&(e instanceof ShadowRoot||e instanceof Pe(e).ShadowRoot)}function De(e){const{overflow:t,overflowX:n,overflowY:s,display:o}=$e(e);return/auto|scroll|overlay|hidden|clip/.test(t+s+n)&&"inline"!==o&&"contents"!==o}function Me(e){return/^(table|td|th)$/.test(Ce(e))}function Oe(e){try{if(e.matches(":popover-open"))return!0}catch(t){}try{return e.matches(":modal")}catch(t){return!1}}function Fe(e){const t=Re(e)?$e(e):e;return yn(t.transform)||yn(t.translate)||yn(t.scale)||yn(t.rotate)||yn(t.perspective)||!Be()&&(yn(t.backdropFilter)||yn(t.filter))||vn.test(t.willChange||"")||wn.test(t.contain||"")}function Be(){return null==Ut&&(Ut="undefined"!=typeof CSS&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Ut}function Ne(e){return/^(html|body|#document)$/.test(Ce(e))}function $e(e){return Pe(e).getComputedStyle(e)}function He(e){return Re(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Ke(e){if("html"===Ce(e))return e;const t=e.assignedSlot||e.parentNode||Le(e)&&e.host||Te(e);return Le(t)?t.host:t}function je(e){const t=Ke(e);return Ne(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ae(t)&&De(t)?t:je(t)}function ze(e,t,n){var s;void 0===t&&(t=[]),void 0===n&&(n=!0);const o=je(e),r=o===(null==(s=e.ownerDocument)?void 0:s.body),i=Pe(o);if(r){const e=Ve(i);return t.concat(i,i.visualViewport||[],De(o)?o:[],e&&n?ze(e):[])}return t.concat(o,ze(o,[],n))}function Ve(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function We(e){const t=$e(e);let n=parseFloat(t.width)||0,s=parseFloat(t.height)||0;const o=Ae(e),r=o?e.offsetWidth:n,i=o?e.offsetHeight:s,a=cn(n)!==r||cn(s)!==i;return a&&(n=r,s=i),{width:n,height:s,$:a}}function qe(e){return Re(e)?e:e.contextElement}function Ue(e){const t=qe(e);if(!Ae(t))return dn(1);const n=t.getBoundingClientRect(),{width:s,height:o,$:r}=We(t);let i=(r?cn(n.width):n.width)/s,a=(r?cn(n.height):n.height)/o;return i&&Number.isFinite(i)||(i=1),a&&Number.isFinite(a)||(a=1),{x:i,y:a}}function _e(e){const t=Pe(e);return Be()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:bn}function Ye(e,t,n,s){void 0===t&&(t=!1),void 0===n&&(n=!1);const o=e.getBoundingClientRect(),r=qe(e);let i=dn(1);t&&(s?Re(s)&&(i=Ue(s)):i=Ue(e));const a=((e,t,n)=>(void 0===t&&(t=!1),!(!n||t&&n!==Pe(e))&&t))(r,n,s)?_e(r):dn(0);let c=(o.left+a.x)/i.x,l=(o.top+a.y)/i.y,d=o.width/i.x,u=o.height/i.y;if(r){const e=Pe(r),t=s&&Re(s)?Pe(s):s;let n=e,o=Ve(n);for(;o&&s&&t!==n;){const e=Ue(o),t=o.getBoundingClientRect(),s=$e(o),r=t.left+(o.clientLeft+parseFloat(s.paddingLeft))*e.x,i=t.top+(o.clientTop+parseFloat(s.paddingTop))*e.y;c*=e.x,l*=e.y,d*=e.x,u*=e.y,c+=r,l+=i,n=Pe(o),o=Ve(n)}}return xe({width:d,height:u,x:c,y:l})}function Xe(e,t){const n=He(e).scrollLeft;return t?t.left+n:Ye(Te(e)).left+n}function Je(e,t){const n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-Xe(e,n),y:n.top+t.scrollTop}}function Ge(e,t,n){let s;if("viewport"===t)s=((e,t)=>{const n=Pe(e),s=Te(e),o=n.visualViewport;let r=s.clientWidth,i=s.clientHeight,a=0,c=0;if(o){r=o.width,i=o.height;const e=Be();(!e||e&&"fixed"===t)&&(a=o.offsetLeft,c=o.offsetTop)}const l=Xe(s);if(l<=0){const e=s.ownerDocument,t=e.body,n=getComputedStyle(t),o="CSS1Compat"===e.compatMode&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(s.clientWidth-t.clientWidth-o);i<=25&&(r-=i)}else l<=25&&(r+=l);return{width:r,height:i,x:a,y:c}})(e,n);else if("document"===t)s=(e=>{const t=Te(e),n=He(e),s=e.ownerDocument.body,o=an(t.scrollWidth,t.clientWidth,s.scrollWidth,s.clientWidth),r=an(t.scrollHeight,t.clientHeight,s.scrollHeight,s.clientHeight);let i=-n.scrollLeft+Xe(e);const a=-n.scrollTop;return"rtl"===$e(s).direction&&(i+=an(t.clientWidth,s.clientWidth)-o),{width:o,height:r,x:i,y:a}})(Te(e));else if(Re(t))s=((e,t)=>{const n=Ye(e,!0,"fixed"===t),s=n.top+e.clientTop,o=n.left+e.clientLeft,r=Ae(e)?Ue(e):dn(1);return{width:e.clientWidth*r.x,height:e.clientHeight*r.y,x:o*r.x,y:s*r.y}})(t,n);else{const n=_e(e);s={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return xe(s)}function Ze(e,t){const n=Ke(e);return!(n===t||!Re(n)||Ne(n))&&("fixed"===$e(n).position||Ze(n,t))}function Qe(e,t){const n=t.get(e);if(n)return n;let s=ze(e,[],!1).filter(e=>Re(e)&&"body"!==Ce(e)),o=null;const r="fixed"===$e(e).position;let i=r?Ke(e):e;for(;Re(i)&&!Ne(i);){const t=$e(i),n=Fe(i);n||"fixed"!==t.position||(o=null),(r?!n&&!o:!n&&"static"===t.position&&o&&("absolute"===o.position||"fixed"===o.position)||De(i)&&!n&&Ze(e,i))?s=s.filter(e=>e!==i):o=t,i=Ke(i)}return t.set(e,s),s}function et(e,t,n){function s(){l.x=Xe(r)}const o=Ae(t),r=Te(t),i="fixed"===n,a=Ye(e,!0,i,t);let c={scrollLeft:0,scrollTop:0};const l=dn(0);if(o||!o&&!i)if(("body"!==Ce(t)||De(r))&&(c=He(t)),o){const e=Ye(t,!0,i,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}else r&&s();i&&!o&&r&&s();const d=!r||o||i?dn(0):Je(r,c);return{x:a.left+c.scrollLeft-l.x-d.x,y:a.top+c.scrollTop-l.y-d.y,width:a.width,height:a.height}}function tt(e){return"static"===$e(e).position}function nt(e,t){if(!Ae(e)||"fixed"===$e(e).position)return null;if(t)return t(e);let n=e.offsetParent;return Te(e)===n&&(n=n.ownerDocument.body),n}function st(e,t){const n=Pe(e);if(Oe(e))return n;if(!Ae(e)){let t=Ke(e);for(;t&&!Ne(t);){if(Re(t)&&!tt(t))return t;t=Ke(t)}return n}let s=nt(e,t);for(;s&&Me(s)&&tt(s);)s=nt(s,t);return s&&Ne(s)&&tt(s)&&!Fe(s)?n:s||(e=>{let t=Ke(e);for(;Ae(t)&&!Ne(t);){if(Fe(t))return t;if(Oe(t))return null;t=Ke(t)}return null})(e)||n}function ot(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function rt({viewport:e,fallbackPlacements:t,floatingRef:n,getReferenceElement:s,onPlacementChange:o,offset:r,placement:i,visible:a=!0}){Nt(()=>{const c=s(),l=n.current;if(!c||!l)return;let d=!1,u=0;l.style.visibility="hidden";const p=()=>{const e=++u,n=it("--toolbar-floating-shift-padding",8),s=r??it("--toolbar-floating-offset",38),p={top:it("--toolbar-floating-safe-top",64),right:n,bottom:n,left:n};((e,t,n)=>{const s={platform:xn,...n},o={...s.platform,_c:new Map};return(async(e,t,n)=>{const{placement:s="bottom",strategy:o="absolute",middleware:r=[],platform:i}=n,a=i.detectOverflow?i:{...i,detectOverflow:Ee},c=await(null==i.isRTL?void 0:i.isRTL(t));let l=await i.getElementRects({reference:e,floating:t,strategy:o}),{x:d,y:u}=Se(l,s,c),p=s,h=0;const f={};for(let g=0;g<r.length;g++){const n=r[g];if(!n)continue;const{name:m,fn:v}=n,{x:w,y:y,data:b,reset:x}=await v({x:d,y:u,initialPlacement:s,placement:p,strategy:o,middlewareData:f,rects:l,platform:a,elements:{reference:e,floating:t}});d=null!=w?w:d,u=null!=y?y:u,f[m]={...f[m],...b},x&&h<50&&(h++,"object"==typeof x&&(x.placement&&(p=x.placement),x.rects&&(l=!0===x.rects?await i.getElementRects({reference:e,floating:t,strategy:o}):x.rects),({x:d,y:u}=Se(l,p,c))),g=-1)}return{x:d,y:u,placement:p,strategy:o,middlewareData:f}})(e,t,{...s,platform:o})})(c,l,{strategy:"fixed",placement:i,middleware:[Sn(s),In({fallbackPlacements:[...t],padding:p}),En({padding:p})]}).then(({placement:t,x:n,y:s})=>{d||e!==u||(l.dataset.placement=t,o?.(t),l.style.transform=`translate3d(${Math.round(n)}px, ${Math.round(s)}px, 0)`,l.style.visibility=a?"visible":"hidden")})},h=function(e,t,n,s){void 0===s&&(s={});const{ancestorScroll:o=!0,ancestorResize:r=!0,elementResize:i="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:c=!1}=s,l=qe(e),d=o||r?[...l?ze(l):[],...t?ze(t):[]]:[];d.forEach(e=>{o&&e.addEventListener("scroll",n,{passive:!0}),r&&e.addEventListener("resize",n)});const u=l&&a?((e,t)=>{function n(){var e;clearTimeout(s),null==(e=o)||e.disconnect(),o=null}let s,o=null;const r=Te(e);return function i(a,c){function l(t){const n=t[0].intersectionRatio;if(n!==c){if(!m)return i();n?i(!1,n):s=setTimeout(()=>{i(!1,1e-7)},1e3)}1!==n||ot(d,e.getBoundingClientRect())||i(),m=!1}void 0===a&&(a=!1),void 0===c&&(c=1),n();const d=e.getBoundingClientRect(),{left:u,top:p,width:h,height:f}=d;if(a||t(),!h||!f)return;const g={rootMargin:-ln(p)+"px "+-ln(r.clientWidth-(u+h))+"px "+-ln(r.clientHeight-(p+f))+"px "+-ln(u)+"px",threshold:an(0,rn(1,c))||1};let m=!0;try{o=new IntersectionObserver(l,{...g,root:r.ownerDocument})}catch(v){o=new IntersectionObserver(l,g)}o.observe(e)}(!0),n})(l,n):null;let p,h=-1,f=null;i&&(f=new ResizeObserver(e=>{let[s]=e;s&&s.target===l&&f&&t&&(f.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var e;null==(e=f)||e.observe(t)})),n()}),l&&!c&&f.observe(l),t&&f.observe(t));let g=c?Ye(e):null;return c&&function t(){const s=Ye(e);g&&!ot(g,s)&&n(),g=s,p=requestAnimationFrame(t)}(),n(),()=>{var e;d.forEach(e=>{o&&e.removeEventListener("scroll",n),r&&e.removeEventListener("resize",n)}),u?.(),null==(e=f)||e.disconnect(),f=null,c&&cancelAnimationFrame(p)}}(c,l,p,{ancestorResize:!0,ancestorScroll:!0,elementResize:!0,layoutShift:!0}),f=e.subscribe(p);return p(),()=>{d=!0,l.style.visibility="hidden",h(),f()}},[e,t,n,s,o,r,i,a])}function it(e,t){if("undefined"==typeof document)return t;const n=getComputedStyle(document.documentElement).getPropertyValue(e).trim();if(!n)return t;const s=Number.parseFloat(n);return Number.isFinite(s)?n.endsWith("rem")?16*s:s:t}function at(e){const t=a();return t?qt(Vt(ct,{...e}),t):null}function ct({fallbackPlacements:e=Cn,offset:t=8,placement:n="top",referenceElement:o,...r}){const i=u(),a=Ht(null),c=Ft(()=>o,[o]);return s(a),rt({viewport:i.viewport.state,fallbackPlacements:e,floatingRef:a,getReferenceElement:c,offset:t,placement:n}),Vt("div",{...r,ref:a})}function lt(){return Bt(kn)}function dt({children:e,className:t,dataUi:n="floating-selection-toolbar-slot",horizontalAlign:o="start",offset:r,visible:i=!0}){const a=u(),c=p(a.selection.state),l=p(a.viewport.state),d=Ht(null),h=Ht(null),[f,g]=Kt("center"===o?"top":"top-start"),m=c.pageBounds??(c.anchorPagePoint?{x:c.anchorPagePoint.x,y:c.anchorPagePoint.y,width:0,height:0}:null),v=i&&null!==m,w=v&&!c.isTranslating,y=Ft(()=>d.current,[m?.height,m?.width,m?.x,m?.y]),b=Ft(()=>d.current?.getBoundingClientRect()??null,[]),x=$t(()=>({placement:f,getContentBounds:b}),[m?.height,m?.width,m?.x,m?.y,b,f,l.pageTransform]);return s(h),rt({viewport:a.viewport.state,fallbackPlacements:"center"===o?Tn:Pn,floatingRef:h,getReferenceElement:y,onPlacementChange:g,offset:r,placement:"center"===o?"top":"top-start",visible:w}),v&&m?Wt(zt,{children:[Vt("div",{"data-ui":`${n}-page-space`,className:"land-canvas__floating-selection-page-space",style:{position:"absolute",left:0,top:0,width:"100%",height:"100%",transform:l.pageTransform,transformOrigin:"0 0"},children:Vt("div",{ref:d,"aria-hidden":"true",style:{position:"absolute",left:m.x,top:m.y,width:m.width,height:m.height,pointerEvents:"none"}})}),Vt("div",{ref:h,"data-ui":n,className:ut("land-canvas__floating-selection-anchor",t),style:{position:"fixed",left:0,top:0,visibility:"hidden",willChange:"transform"},children:Vt(kn.Provider,{value:x,children:e})})]}):null}function ut(...e){return e.filter(Boolean).join(" ")}import{A as pt,C as ht,D as ft,E as gt,M as mt,O as vt,S as wt,T as yt,a as bt,b as xt,g as St,h as Et,i as It,j as Ct,k as Pt,o as Tt,r as kt,s as Rt,v as At,w as Lt,x as Dt,y as Mt}from"./host-VhUj_Gf6.mjs";import{createContext as Ot,useCallback as Ft,useContext as Bt,useEffect as Nt,useMemo as $t,useRef as Ht,useState as Kt,useSyncExternalStore as jt}from"react";import{Fragment as zt,jsx as Vt,jsxs as Wt}from"react/jsx-runtime";import{createPortal as qt}from"react-dom";var Ut,_t=Ot(null),Yt=Ot(null),Xt={state:"idle"},Jt=class{abortController=new AbortController;activeTasks=new Set;disposers=[];phase="starting";close=null;signal=this.abortController.signal;tasks={run:e=>this.runTask(e)};own(e,t){if("starting"!==this.phase)throw new Error("Cannot register a resource after the Canvas Runtime is published or disposal starts.");return this.disposers.push(n=>"function"==typeof t?t(e):"rollback"===n&&t.rollback?t.rollback(e):t.shutdown(e)),e}publish({beforeShutdown:e}={}){if("starting"!==this.phase)throw new Error(`Only a starting Canvas Runtime can be published; received runtime in "${this.phase}" phase.`);return this.phase="ready",()=>null!==this.close?"shutdown"===this.close.mode?this.close.result:Promise.reject(new Error("Cannot shut down a Canvas Runtime during rollback.")):this.beginClose({mode:"shutdown",beforeShutdown:e})}rollback(e){return null!==this.close?"rollback"===this.close.mode?this.close.result:Promise.reject(new Error("Cannot roll back a Canvas Runtime during shutdown.")):"starting"!==this.phase?Promise.reject(new Error(`Only a starting Canvas Runtime can roll back; received runtime in "${this.phase}" phase.`)):this.beginClose({mode:"rollback",cause:e})}beginClose(e){const t=[],n=Promise.resolve().then(async()=>{const n=[...t,...await this.disposeResources(e.mode)];if(this.phase="disposed","rollback"===e.mode){if(n.length>0)throw new AggregateError([e.cause,...n],"CanvasKit Runtime initialization failed and cleanup reported errors.",{cause:e.cause});throw e.cause}if(n.length>0)throw new AggregateError(n,"Failed to dispose one or more CanvasKit Runtime resources.")});if(this.close={mode:e.mode,result:n},"shutdown"===e.mode)try{e.beforeShutdown?.()}catch(s){t.push(s)}return this.phase="disposing",this.abortController.abort("rollback"===e.mode?e.cause:new DOMException("Canvas runtime is disposing.","AbortError")),n}runTask(e){if("ready"!==this.phase)throw new Error(`Canvas tasks require a ready runtime; received runtime in "${this.phase}" phase.`);this.signal.throwIfAborted();const t=Promise.resolve().then(()=>e(this.signal));return this.activeTasks.add(t),t.finally(()=>this.activeTasks.delete(t)).catch(()=>{}),t}async disposeResources(e){await Promise.allSettled([...this.activeTasks]);const t=[];for(;this.disposers.length>0;){const s=this.disposers.pop();try{await s(e)}catch(n){t.push(n)}}return t}},Gt=[500,1e3,2e3,5e3],Zt=class{editor;adapter;options;unsubscribeDocument=null;unsubscribeSession=null;unsubscribeFlushEvents=null;documentTimer=null;sessionTimer=null;pendingDocument=null;pendingSession=null;documentVersion=0;sessionVersion=0;documentRetryCount=0;sessionRetryCount=0;writeChain=Promise.resolve();flushChain=Promise.resolve();isRunning=!1;disposeMode=null;disposePromise=null;constructor(e,t,n={}){this.editor=e,this.adapter=t,this.options=n}start(){if(null!==this.disposeMode)throw new Error("Cannot start disposed canvas persistence.");this.isRunning||(this.isRunning=!0,this.adapter.saveDocument&&(this.unsubscribeDocument=this.editor.operations.subscribe(e=>{var t;this.documentVersion+=1,this.documentRetryCount=0,this.pendingDocument={snapshot:(t=e.snapshot,JSON.parse(JSON.stringify(t))),version:this.documentVersion},this.scheduleDocumentSave(200)})),this.adapter.saveSession&&(this.unsubscribeSession=this.editor.listen(e=>{var t,n;((t=e.diff).added.some(e=>"session"===e.scope)||t.updated.some(e=>"session"===e.before.scope||"session"===e.after.scope)||t.removed.some(e=>"session"===e.scope))&&(this.sessionVersion+=1,this.sessionRetryCount=0,this.pendingSession={snapshot:(n=this.editor.snapshots.getSession(),JSON.parse(JSON.stringify(n))),version:this.sessionVersion},this.scheduleSessionSave(200))})),this.unsubscribeFlushEvents=this.options.flushEvents?.subscribe(this.flushForHostLifecycle)??null)}flush(){if(null!==this.disposeMode)return Promise.reject(new Error("Cannot flush disposed canvas persistence."));const e=this.flushChain.then(()=>this.flushNow());return this.flushChain=e.catch(()=>{}),e}shutdown(){return this.dispose("shutdown")}rollback(){return this.dispose("rollback")}dispose(e){return null!==this.disposeMode?this.disposeMode!==e?Promise.reject(new Error(`Canvas persistence disposal already started in "${this.disposeMode}" mode.`)):this.disposePromise:(this.disposeMode=e,this.disposePromise=Promise.resolve().then(()=>"shutdown"===e?this.finishShutdown():this.finishRollback()),this.disposePromise)}async finishShutdown(){this.stopIntake(),await this.flushChain,await this.flushNow()}async finishRollback(){this.stopIntake(),this.discardPendingSnapshots(),await this.flushChain,await this.writeChain,this.discardPendingSnapshots()}stopIntake(){this.isRunning=!1,this.cancelDocumentTimer(),this.cancelSessionTimer(),this.unsubscribeDocument?.(),this.unsubscribeSession?.(),this.unsubscribeFlushEvents?.(),this.unsubscribeDocument=null,this.unsubscribeSession=null,this.unsubscribeFlushEvents=null}async flushNow(){const e=await this.flushPendingSnapshots();try{await(this.adapter.flush?.())}catch(t){e.push(t)}if(e.length>0)throw new AggregateError(e,"Failed to flush canvas persistence.")}async flushPendingSnapshots(){this.cancelDocumentTimer(),this.cancelSessionTimer();const e=this.savePendingDocument(),t=this.savePendingSession();return(await Promise.allSettled([e,t])).flatMap(e=>"rejected"===e.status?[e.reason]:[])}discardPendingSnapshots(){this.cancelDocumentTimer(),this.cancelSessionTimer(),this.pendingDocument=null,this.pendingSession=null}savePendingDocument(){const e=this.pendingDocument;if(!e||!this.adapter.saveDocument)return this.writeChain;this.pendingDocument=null;const t=this.queueWrite(()=>Promise.resolve(this.adapter.saveDocument(e.snapshot))).then(()=>{this.documentVersion===e.version&&(this.documentRetryCount=0)}).catch(t=>{throw this.documentVersion===e.version&&null===this.pendingDocument&&(this.pendingDocument=e,this.scheduleDocumentRetry()),t});return this.writeChain=t.catch(()=>{}),t}savePendingSession(){const e=this.pendingSession;if(!e||!this.adapter.saveSession)return this.writeChain;this.pendingSession=null;const t=this.queueWrite(()=>Promise.resolve(this.adapter.saveSession(e.snapshot))).then(()=>{this.sessionVersion===e.version&&(this.sessionRetryCount=0)}).catch(t=>{throw this.sessionVersion===e.version&&null===this.pendingSession&&(this.pendingSession=e,this.scheduleSessionRetry()),t});return this.writeChain=t.catch(()=>{}),t}queueWrite(e){return this.writeChain.then(e)}scheduleDocumentSave(e){this.cancelDocumentTimer(),this.documentTimer=setTimeout(()=>{this.documentTimer=null,this.savePendingDocument().catch(e=>{this.reportError("Could not persist canvas document.",e)})},e)}scheduleSessionSave(e){this.cancelSessionTimer(),this.sessionTimer=setTimeout(()=>{this.sessionTimer=null,this.savePendingSession().catch(e=>{this.reportError("Could not persist canvas session.",e)})},e)}scheduleDocumentRetry(){if(!this.isRunning||null!==this.documentTimer)return;const e=Gt[this.documentRetryCount];void 0!==e&&(this.documentRetryCount+=1,this.scheduleDocumentSave(e))}scheduleSessionRetry(){if(!this.isRunning||null!==this.sessionTimer)return;const e=Gt[this.sessionRetryCount];void 0!==e&&(this.sessionRetryCount+=1,this.scheduleSessionSave(e))}cancelDocumentTimer(){null!==this.documentTimer&&(clearTimeout(this.documentTimer),this.documentTimer=null)}cancelSessionTimer(){null!==this.sessionTimer&&(clearTimeout(this.sessionTimer),this.sessionTimer=null)}flushForHostLifecycle=()=>{this.flush().catch(e=>{this.reportError("Could not persist canvas snapshot.",e)})};reportError(e,t){try{this.options.onError?.(new Error(e,{cause:t}))}catch{}}},Qt={status:"starting"},en=[],tn="snapshots",nn=null,sn="canvas-kit.document",on="canvas-kit.session",rn=Math.min,an=Math.max,cn=Math.round,ln=Math.floor,dn=e=>({x:e,y:e}),un={left:"right",right:"left",bottom:"top",top:"bottom"},pn=["left","right"],hn=["right","left"],fn=["top","bottom"],gn=["bottom","top"],mn=new Set(["left","top"]),vn=/transform|translate|scale|rotate|perspective|filter/,wn=/paint|layout|strict|content/,yn=e=>!!e&&"none"!==e,bn=dn(0),xn={convertOffsetParentRelativeRectToViewportRelativeRect:e=>{let{elements:t,rect:n,offsetParent:s,strategy:o}=e;const r="fixed"===o,i=Te(s),a=!!t&&Oe(t.floating);if(s===i||a&&r)return n;let c={scrollLeft:0,scrollTop:0},l=dn(1);const d=dn(0),u=Ae(s);if((u||!u&&!r)&&(("body"!==Ce(s)||De(i))&&(c=He(s)),u)){const e=Ye(s);l=Ue(s),d.x=e.x+s.clientLeft,d.y=e.y+s.clientTop}const p=!i||u||r?dn(0):Je(i,c);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+d.x+p.x,y:n.y*l.y-c.scrollTop*l.y+d.y+p.y}},getDocumentElement:Te,getClippingRect:function(e){let{element:t,boundary:n,rootBoundary:s,strategy:o}=e;const r=[..."clippingAncestors"===n?Oe(t)?[]:Qe(t,this._c):[].concat(n),s],i=Ge(t,r[0],o);let a=i.top,c=i.right,l=i.bottom,d=i.left;for(let u=1;u<r.length;u++){const e=Ge(t,r[u],o);a=an(e.top,a),c=rn(e.right,c),l=rn(e.bottom,l),d=an(e.left,d)}return{width:c-d,height:l-a,x:d,y:a}},getOffsetParent:st,getElementRects:async function(e){const t=this.getOffsetParent||st,n=this.getDimensions,s=await n(e.floating);return{reference:et(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:s.width,height:s.height}}},getClientRects:e=>Array.from(e.getClientRects()),getDimensions:e=>{const{width:t,height:n}=We(e);return{width:t,height:n}},getScale:Ue,isElement:Re,isRTL:e=>"rtl"===$e(e).direction},Sn=e=>(void 0===e&&(e=0),{name:"offset",options:e,async fn(t){var n,s;const{x:o,y:r,placement:i,middlewareData:a}=t,c=await(async(e,t)=>{const{placement:n,platform:s,elements:o}=e,r=await(null==s.isRTL?void 0:s.isRTL(o.floating)),i=he(n),a=fe(n),c="y"===ve(n),l=mn.has(i)?-1:1,d=r&&c?-1:1,u=pe(t,e);let{mainAxis:p,crossAxis:h,alignmentAxis:f}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&"number"==typeof f&&(h="end"===a?-1*f:f),c?{x:h*d,y:p*l}:{x:p*l,y:h*d}})(t,e);return i===(null==(n=a.offset)?void 0:n.placement)&&null!=(s=a.arrow)&&s.alignmentOffset?{}:{x:o+c.x,y:r+c.y,data:{...c,placement:i}}}}),En=e=>(void 0===e&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:s,placement:o,platform:r}=t,{mainAxis:i=!0,crossAxis:a=!1,limiter:c={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=pe(e,t),d={x:n,y:s},u=await r.detectOverflow(t,l),p=ve(he(o)),h=ge(p);let f=d[h],g=d[p];i&&(f=ue(f+u["y"===h?"top":"left"],f,f-u["y"===h?"bottom":"right"])),a&&(g=ue(g+u["y"===p?"top":"left"],g,g-u["y"===p?"bottom":"right"]));const m=c.fn({...t,[h]:f,[p]:g});return{...m,data:{x:m.x-n,y:m.y-s,enabled:{[h]:i,[p]:a}}}}}),In=e=>(void 0===e&&(e={}),{name:"flip",options:e,async fn(t){var n,s;const{placement:o,middlewareData:r,rects:i,initialPlacement:a,platform:c,elements:l}=t,{mainAxis:d=!0,crossAxis:u=!0,fallbackPlacements:p,fallbackStrategy:h="bestFit",fallbackAxisSideDirection:f="none",flipAlignment:g=!0,...m}=pe(e,t);if(null!=(n=r.arrow)&&n.alignmentOffset)return{};const v=he(o),w=ve(a),y=he(a)===a,b=await(null==c.isRTL?void 0:c.isRTL(l.floating)),x=p||(y||!g?[be(a)]:(e=>{const t=be(e);return[ye(e),t,ye(t)]})(a)),S="none"!==f;!p&&S&&x.push(...function(e,t,n,s){const o=fe(e);let r=((e,t,n)=>{switch(e){case"top":case"bottom":return n?t?hn:pn:t?pn:hn;case"left":case"right":return t?fn:gn;default:return[]}})(he(e),"start"===n,s);return o&&(r=r.map(e=>e+"-"+o),t&&(r=r.concat(r.map(ye)))),r}(a,g,f,b));const E=[a,...x],I=await c.detectOverflow(t,m),C=[];let P=(null==(s=r.flip)?void 0:s.overflows)||[];if(d&&C.push(I[v]),u){const e=((e,t,n)=>{void 0===n&&(n=!1);const s=fe(e),o=we(e),r=me(o);let i="x"===o?s===(n?"end":"start")?"right":"left":"start"===s?"bottom":"top";return t.reference[r]>t.floating[r]&&(i=be(i)),[i,be(i)]})(o,i,b);C.push(I[e[0]],I[e[1]])}if(P=[...P,{placement:o,overflows:C}],!C.every(e=>e<=0)){var T,k;const e=((null==(T=r.flip)?void 0:T.index)||0)+1,t=E[e];if(t&&("alignment"!==u||w===ve(t)||P.every(e=>ve(e.placement)!==w||e.overflows[0]>0)))return{data:{index:e,overflows:P},reset:{placement:t}};let n=null==(k=P.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:k.placement;if(!n)switch(h){case"bestFit":{var R;const e=null==(R=P.filter(e=>{if(S){const t=ve(e.placement);return t===w||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:R[0];e&&(n=e);break}case"initialPlacement":n=a}if(o!==n)return{reset:{placement:n}}}return{}}}),Cn=["bottom"],Pn=["bottom-start"],Tn=["bottom"],kn=Ot(null);export{at as CanvasKitFloatingContent,le as CanvasKitFloatingToolbarLayer,d as CanvasKitProvider,J as CanvasKitRoot,dt as FloatingSelectionToolbarPageSpace,I as applyCanvasActionShortcutOverrides,t as createCanvasApiToken,ht as createCustomShapeColor,Q as createLocalSnapshotPersistence,Lt as createThemeShapeColor,e as defineCanvasPlugin,E as getCanvasActionShortcuts,yt as getThemeColorTokenName,gt as isCustomShapeColorRef,ft as isThemeShapeColorRef,ne as readPersistedDocumentSnapshot,te as readPersistedEditorSnapshots,se as readPersistedSessionSnapshot,n as requireApi,vt as resolveShapeColor,Pt as shapeColorToCssColor,u as useCanvasKit,c as useCanvasKitFloatingPortalContainer,s as useCanvasKitWheelCapture,p as useCanvasValue,lt as useFloatingSelectionToolbarPosition};